Compare commits

..
12 Commits
Author SHA1 Message Date
kory a5620cb9c4 fix(panel): resolve duplicate polling timer declaration causing JS execution failure
Release / Build & Release (push) Canceled after 0s
2026-10-02 00:45:10 +08:00
kory 601a0b6e25 feat(ui): upgrade probe and console Web UI to Apple Design System 2026-10-02 00:45:10 +08:00
kory 57c99ac72b feat: fix dashboard real-time data sync, stabilize node order and eliminate UI jitter 2026-09-30 13:16:27 +08:00
kory 512e7c91c8 feat: add v2 phase2 security policy 2026-09-30 13:16:27 +08:00
kory 2a9d01d7f7 fix: sync agent MCP payloads and query runtime state 2026-09-30 13:16:27 +08:00
kory 7f000b8833 feat: centrally mount and dispatch agent MCP services 2026-09-30 13:16:27 +08:00
kory 6aabc53a68 fix(web): fix literal newline escaping in app.js 2026-09-30 13:16:27 +08:00
kory 79179c585a feat: persist device offline lifecycle 2026-09-30 13:16:27 +08:00
kyaring 97bbe3ced6 refactor(deploy): keep purely GitHub paths and releases in main branch for GitHub
Release / Build & Release (push) Canceled after 0s
2026-09-28 11:23:15 +08:00
kyaring 46af20e96c feat(deploy): support smart dual-source (GitHub + Gitea) binary download with automatic fallback and insecure cert tolerance
Release / Build & Release (push) Canceled after 0s
2026-09-28 11:13:00 +08:00
kyaring c3114492bb ci(release): attribute changelog commits directly to @kyaring
Release / Build & Release (push) Canceled after 0s
2026-09-28 10:37:42 +08:00
kory ff04cb0c1a docs: update ChatGPT integration guide to new Apps and MCP specification
Release / Build & Release (push) Canceled after 0s
2026-09-28 10:32:11 +08:00
34 changed files with 5202 additions and 229 deletions
+2 -2
View File
@@ -53,9 +53,9 @@ jobs:
NOTES
if [ -n "$PREV_TAG" ]; then
git log "${PREV_TAG}..HEAD" --pretty=format:"- %s (%h by @%an)" >> release_notes.md
git log "${PREV_TAG}..HEAD" --pretty=format:"- %s (%h by @kyaring)" >> release_notes.md
else
git log -n 10 --pretty=format:"- %s (%h by @%an)" >> release_notes.md
git log -n 10 --pretty=format:"- %s (%h by @kyaring)" >> release_notes.md
fi
echo "" >> release_notes.md
+45 -14
View File
@@ -79,7 +79,7 @@
无论是在受控端 VPS 还是中心端,只需一行命令即可交互式安装与启动:
```bash
bash <(curl -sSL https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/install.sh)
bash <(curl -fsSLk https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/install.sh)
```
- **安装 Agent (受控 VPS)**:输入 Hub 的 WSS 地址与通信密钥,全自动配置开机自启并秒级连入集群。
- **安装 Hub (中心服务端)**:自动生成安全 API Key / Web 面板密码并以 Systemd 托管常驻。
@@ -88,7 +88,7 @@ bash <(curl -sSL https://raw.githubusercontent.com/kyaring/vps-commander/main/de
当新版本发布后,无需重新配置通信密钥或重新安装,在任意受控机上直接运行升级脚本:
```bash
curl -fsSL https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/upgrade-agent.sh | bash
curl -fsSLk https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/upgrade-agent.sh | bash
```
- 自动检测并拉取 GitHub 最新版本架构包(AMD64 / ARM64);
- 自动备份旧版本二进制(`.bak`);
@@ -150,20 +150,51 @@ Agent 启动后会通过 WSS 自动连入 Hub,在 Hub 管理面板与 `/api/v1
---
## 🤖 接入 ChatGPT / AI 客户端
## 🤖 接入 ChatGPT (新版插件 Apps & MCP 模式)
### 方式 1:ChatGPT Actions (推荐)
1. 在 ChatGPT 创建自定义 GPT(GPT Builder)-> **Actions** -> **Create new action**。
2. **Schema 导入**:在 `Import from URL` 填入 `https://your-domain.com/openapi.json`。
3. **Authentication (身份验证)**:
- Authentication Type 选择 **API Key**。
- Auth Type 选择 **Bearer**。
- 填入你配置的 `VPS_COMMANDER_API_KEY`。
当前 ChatGPT 已升级为以 **插件 / 应用 (Apps & MCP)** 规范连接外部服务。VPS-Commander 原生内置完整的 **MCP SSE + OAuth2** 协议支持,无需部署额外适配层。
### 方式 2:MCP (Model Context Protocol)
- **SSE 端点**:`https://your-domain.com/mcp/sse`
- **消息交互**:`https://your-domain.com/mcp/message`
- **认证**:支持 URL 参数 `?token=...` 或标准 Header `Authorization: Bearer <TOKEN>`。
### 接入配置步骤:
1. **进入 ChatGPT 插件/应用配置页**:
- 打开 ChatGPT -> **Settings (设置)** -> **Apps & Integrations (应用与集成) / Plugins** -> **Create / Add App (添加应用)**。
2. **连接方式选择 MCP**:
- 连接协议选择 **MCP (Model Context Protocol)** 或 **Server-Sent Events (SSE)**。
- **MCP Server URL**:填入 Hub 的 SSE 统一入口:
```text
https://your-domain.com/mcp/sse
```
3. **身份认证 (Authentication)**:
- **方式 A (OAuth 2.0 自动授权,推荐)**:
- Hub 内置了标准 RFC 8414 OAuth Metadata (`/.well-known/oauth-authorization-server`);
- 授权端点与 Token 端点由 ChatGPT 自动识别,一键点击「Authorize」即可完成免密安全绑定。
- **方式 B (Bearer API Key)**:
- 若选择 API Key,填入 Hub 环境变量 `VPS_COMMANDER_API_KEY` 即可。
4. **自动发现 4 大运维工具**:
- 握手成功后,ChatGPT 会自动加载并列出 4 个原生运维工具:
- `list_devices`:列出受控节点、CPU/内存/磁盘剩余绝对值及 Docker 状态;
- `exec_command`:在目标机器(如 `m4-live-agent`)执行 Shell 指令;
- `read_file`:分页读取目标文件;
- `write_file`:远程编辑或创建文件。
---
### 传统客户端支持 (Claude Desktop / Cursor / VS Code)
支持通过本地 stdio 二进制连接 Hub:
```json
{
"mcpServers": {
"vps-commander": {
"command": "/path/to/vps-commander-mcp-stdio-linux-amd64",
"args": [
"-hub", "https://your-domain.com",
"-key", "YOUR_API_KEY"
]
}
}
}
```
---
+55 -5
View File
@@ -10,6 +10,7 @@ import (
"log"
"net/http"
"os"
"runtime"
"sync"
"time"
@@ -69,10 +70,11 @@ func run(hub, name, token string, insecure bool) error {
return err
}
exec := executor.Local{MaxOutput: 1024 * 1024}
mcpRuntime := cluster.NewMCPRuntime()
// 初始握手附带画像
initProf := sysinfo.Collect("APPLICATION")
if err := writeJSON(cluster.Message{Event: "hello", Device: name, Profile: &initProf, TS: time.Now().Unix()}); err != nil {
if err := writeJSON(cluster.Message{Event: "hello", Device: name, Arch: runtime.GOARCH, OS: runtime.GOOS, Profile: &initProf, TS: time.Now().Unix()}); err != nil {
return err
}
@@ -85,7 +87,7 @@ func run(hub, name, token string, insecure bool) error {
select {
case <-t.C:
prof := sysinfo.Collect("APPLICATION")
_ = writeJSON(cluster.Message{Event: "ping", Device: name, Profile: &prof, TS: time.Now().Unix()})
_ = writeJSON(cluster.Message{Event: "ping", Device: name, Arch: runtime.GOARCH, OS: runtime.GOOS, Profile: &prof, TS: time.Now().Unix()})
case <-stopPing:
return
}
@@ -101,13 +103,23 @@ func run(hub, name, token string, insecure bool) error {
if msg.Event == "registered" {
continue
}
if msg.Event == "mcp_sync" {
var services []cluster.MCPService
if err := decodePayload(msg.Payload, &services); err != nil {
log.Printf("mcp sync failed: %v", err)
} else {
mcpRuntime.Sync(services)
log.Printf("MCP services synced: %d", len(services))
}
continue
}
if msg.Event == "revoked" {
log.Printf("device revoked by admin: %s", msg.Error)
return errors.New("revoked by admin")
}
if msg.Event == "ping" {
prof := sysinfo.Collect("APPLICATION")
if err := writeJSON(cluster.Message{Event: "pong", Device: name, Profile: &prof, TS: msg.TS}); err != nil {
if err := writeJSON(cluster.Message{Event: "pong", Device: name, Arch: runtime.GOARCH, OS: runtime.GOOS, Profile: &prof, TS: msg.TS}); err != nil {
return err
}
continue
@@ -116,7 +128,7 @@ func run(hub, name, token string, insecure bool) error {
continue
}
go func(msg cluster.Message) {
if err := handle(writeJSON, exec, msg); err != nil {
if err := handle(writeJSON, exec, mcpRuntime, msg); err != nil {
log.Printf("request %s failed: %v", msg.ID, err)
_ = c.Close()
}
@@ -124,8 +136,46 @@ func run(hub, name, token string, insecure bool) error {
}
}
func handle(writeJSON func(cluster.Message) error, exec executor.Local, msg cluster.Message) error {
func handle(writeJSON func(cluster.Message) error, exec executor.Local, mcpRuntime *cluster.MCPRuntime, msg cluster.Message) error {
switch msg.Action {
case "mcp_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":
var p struct {
Server string `json:"server"`
Tool string `json:"tool"`
Args any `json:"args"`
}
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
if p.Server == "" || p.Tool == "" {
return sendError(writeJSON, msg.ID, errors.New("server and tool required"))
}
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second)
defer cancel()
start := time.Now()
result, err := mcpRuntime.Call(ctx, p.Server, p.Tool, p.Args)
duration := time.Since(start).Milliseconds()
if err != nil {
_ = writeJSON(cluster.Message{ID: msg.ID, Status: "error", Error: err.Error(), Payload: map[string]any{"server": p.Server, "tool": p.Tool, "duration_ms": duration}})
return nil
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: map[string]any{"server": p.Server, "tool": p.Tool, "result": result, "duration_ms": duration}})
case "exec":
var p cluster.ExecPayload
if err := decodePayload(msg.Payload, &p); err != nil {
+6 -1
View File
@@ -18,6 +18,7 @@ import (
"github.com/wjyhk/vps-commander/internal/cluster"
"github.com/wjyhk/vps-commander/internal/executor"
"github.com/wjyhk/vps-commander/internal/mcp"
"github.com/wjyhk/vps-commander/internal/notify"
"github.com/wjyhk/vps-commander/internal/storage"
)
@@ -52,12 +53,16 @@ func main() {
if err := store.UpsertLocal(local, runtime.GOARCH, runtime.GOOS); err != nil {
log.Fatal(err)
}
notificationManager := notify.New(store)
notificationManager.Start()
defer notificationManager.Stop()
s := &api.Server{
Auth: authManager,
Exec: executor.Local{MaxOutput: 1024 * 1024},
Cluster: func() *cluster.Manager { m := cluster.NewManager(clusterSecret); m.SetStore(store); return m }(),
Cluster: cluster.NewManager(clusterSecret, store),
Store: store,
LocalName: local,
Notify: notificationManager,
}
// MCP Server instance
+29
View File
@@ -9,6 +9,7 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
@@ -147,3 +148,31 @@ func main() {
os.Stdout.WriteString("\n")
}
}
func (h *HubRemoteBackend) ListAgentMCP(ctx context.Context, device string) (any, error) {
var res any
err := h.get(ctx, "/api/v1/mcp/list?device="+url.QueryEscape(device), &res)
return res, err
}
func (h *HubRemoteBackend) CallAgentMCP(ctx context.Context, clientIP, device, server, tool string, args any) (any, error) {
payload := map[string]any{"device": device, "server": server, "tool": tool, "arguments": args}
var res any
return res, h.post("/api/v1/mcp/call", payload, &res)
}
func (h *HubRemoteBackend) get(ctx context.Context, path string, out any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(h.BaseURL, "/")+path, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+h.APIKey)
resp, err := h.HTTPClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
b, _ := io.ReadAll(resp.Body)
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(b))
}
return json.NewDecoder(resp.Body).Decode(out)
}
+12 -15
View File
@@ -37,12 +37,12 @@ command -v curl >/dev/null 2>&1 || (apt-get update && apt-get install -y curl ||
# 获取最新版本 tag
info "正在获取 VPS-Commander 最新版本信息..."
LATEST_TAG=$(curl -fsSL -k "https://api.github.com/repos/${REPO}/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
LATEST_TAG=$(curl -fsSL -k "https://api.github.com/repos/${REPO}/releases/latest" 2>/dev/null | grep '"tag_name":' | head -n1 | sed -E 's/.*"([^"]+)".*/\1/')
if [ -z "$LATEST_TAG" ]; then
warn "无法通过 GitHub API 自动获取 Tag,将尝试使用默认版本 v1.0.0"
LATEST_TAG="v1.0.0"
warn "无法通过 GitHub API 自动获取 Tag,回退至 v1.1.5"
LATEST_TAG="v1.1.5"
fi
info "检测到最新版本: ${LATEST_TAG}"
info "检测到最新版本: ${LATEST_TAG} (${TARGET_ARCH})"
mkdir -p "$INSTALL_DIR" "$INSTALL_DIR/data" "$CONF_DIR"
chmod 750 "$INSTALL_DIR" "$CONF_DIR"
@@ -77,15 +77,13 @@ install_agent() {
read -rp "Cluster Secret 不能为空,请重新输入: " CLUSTER_SECRET
done
# 写入凭据文件
cat << ENV > "${CONF_DIR}/agent.env"
VPS_COMMANDER_HUB_WS_URL=${HUB_WS}
VPS_COMMANDER_AGENT_NAME=${AGENT_NAME}
VPS_COMMANDER_CLUSTER_SECRET=${CLUSTER_SECRET}
VPS_COMMANDER_CLUSTER_SECRET=***
ENV
chmod 0600 "${CONF_DIR}/agent.env"
# 配置 systemd
cat << SVC > /etc/systemd/system/vps-commander-agent.service
[Unit]
Description=VPS-Commander Agent
@@ -135,24 +133,23 @@ install_hub() {
read -rp "请输入监听端口 (默认 9521): " HUB_PORT
HUB_PORT=${HUB_PORT:-9521}
# 自动生成随机凭据
GEN_API_KEY=$(head -c 24 /dev/urandom | xxd -p)
GEN_SECRET=$(head -c 24 /dev/urandom | xxd -p)
GEN_API_KEY=*** -c 24 /dev/urandom | xxd -p)
GEN_SECRET=*** -c 24 /dev/urandom | xxd -p)
GEN_PASS=$(head -c 16 /dev/urandom | xxd -p)
read -rp "请输入 API Key (默认随机生成): " API_KEY
API_KEY=${API_KEY:-$GEN_API_KEY}
API_KEY=***
read -rp "请输入 Cluster Secret (默认随机生成): " CLUSTER_SECRET
CLUSTER_SECRET=${CLUSTER_SECRET:-$GEN_SECRET}
CLUSTER_SECRET=${CLUS…RET}
read -rp "请输入 Web 管理面板密码 (默认随机生成): " WEB_PASS
WEB_PASS=${WEB_PASS:-$GEN_PASS}
cat << ENV > "${CONF_DIR}/hub.env"
VPS_COMMANDER_API_KEY=${API_KEY}
VPS_COMMANDER_CLUSTER_SECRET=${CLUSTER_SECRET}
VPS_COMMANDER_WEB_PASSWORD=${WEB_PASS}
VPS_COMMANDER_API_KEY=***
VPS_COMMANDER_CLUSTER_SECRET=***
VPS_COMMANDER_WEB_PASSWORD=***
ENV
chmod 0600 "${CONF_DIR}/hub.env"
+3 -3
View File
@@ -37,10 +37,10 @@ case "$ARCH" in
esac
info "正在获取最新 Release 版本信息..."
LATEST_TAG=$(curl -fsSL -k "https://api.github.com/repos/${REPO}/releases/latest" | grep '"tag_name":' | head -n1 | sed -E 's/.*"([^"]+)".*/\1/')
LATEST_TAG=$(curl -fsSL -k "https://api.github.com/repos/${REPO}/releases/latest" 2>/dev/null | grep '"tag_name":' | head -n1 | sed -E 's/.*"([^"]+)".*/\1/')
if [ -z "$LATEST_TAG" ]; then
warn "无法通过 GitHub API 自动获取 Tag,回退至 v1.1.0"
LATEST_TAG="v1.1.0"
warn "无法通过 GitHub API 自动获取 Tag,回退至 v1.1.5"
LATEST_TAG="v1.1.5"
fi
info "目标升级版本: ${LATEST_TAG} (${TARGET_ARCH})"
+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,便于后续优化执行器与任务编排策略。
+443 -3
View File
@@ -1,9 +1,11 @@
package api
import (
"sort"
"context"
"embed"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
@@ -17,6 +19,7 @@ import (
"github.com/wjyhk/vps-commander/internal/cluster"
"github.com/wjyhk/vps-commander/internal/executor"
"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/sysinfo"
panelweb "github.com/wjyhk/vps-commander/internal/web"
@@ -36,6 +39,187 @@ type Server struct {
Cluster *cluster.Manager
Store *storage.Store
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 {
@@ -76,6 +260,222 @@ func (s *Server) AuditsJSON(w http.ResponseWriter, r *http.Request) {
jsonOut(w, logs)
}
type MCPServiceRequest struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Transport string `json:"transport"`
Command string `json:"command"`
Args []string `json:"args"`
Env map[string]string `json:"env"`
URL string `json:"url"`
Headers map[string]string `json:"headers"`
Scope string `json:"scope"`
TargetNodes []string `json:"target_nodes"`
Enabled bool `json:"enabled"`
}
type MCPCallRequest struct {
Device string `json:"device"`
Server string `json:"server"`
Tool string `json:"tool"`
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) {
if s.Store == nil {
http.Error(w, "storage unavailable", 500)
return
}
switch r.Method {
case http.MethodGet:
v, err := s.Store.ListMCPServices()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
jsonOut(w, v)
case http.MethodPost:
var q MCPServiceRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256*1024)).Decode(&q); err != nil {
http.Error(w, "bad json", 400)
return
}
if q.ID == "" || q.Name == "" || q.Transport == "stdio" && q.Command == "" || (q.Transport != "stdio" && q.URL == "") {
http.Error(w, "invalid MCP service", 400)
return
}
args, _ := json.Marshal(q.Args)
env, _ := json.Marshal(q.Env)
headers, _ := json.Marshal(q.Headers)
nodes, _ := json.Marshal(q.TargetNodes)
if q.Scope == "" {
q.Scope = "all"
}
if q.Scope != "all" && q.Scope != "custom" {
http.Error(w, "invalid scope", 400)
return
}
v := storage.MCPService{ID: q.ID, Name: q.Name, Description: q.Description, Transport: q.Transport, Command: q.Command, ArgsJSON: string(args), EnvJSON: string(env), URL: q.URL, HeadersJSON: string(headers), Scope: q.Scope, TargetNodesJSON: string(nodes), Enabled: q.Enabled}
if err := s.Store.SaveMCPService(v); err != nil {
http.Error(w, err.Error(), 500)
return
}
if s.Cluster != nil {
s.Cluster.SyncMCPServices()
}
_ = s.Store.Audit(clientIP(r), s.LocalName, "mcp_service_save", q.ID, 0, 0, "")
jsonOut(w, v)
default:
http.Error(w, "method not allowed", 405)
}
}
func (s *Server) DeleteMCPService(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.DeleteMCPService(id); err != nil {
http.Error(w, err.Error(), 500)
return
}
if s.Cluster != nil {
s.Cluster.SyncMCPServices()
}
_ = s.Store.Audit(clientIP(r), s.LocalName, "mcp_service_delete", id, 0, 0, "")
jsonOut(w, map[string]any{"ok": true})
}
func (s *Server) ListAgentMCPJSON(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", 405)
return
}
device := r.URL.Query().Get("device")
if device == "" {
http.Error(w, "device required", 400)
return
}
if s.isRemote(device) && (s.Cluster == nil || !s.Cluster.Online(device)) {
http.Error(w, "device offline", 409)
return
}
if s.isRemote(device) {
v, err := s.Cluster.ListMCP(device)
if err != nil {
http.Error(w, err.Error(), 404)
return
}
jsonOut(w, map[string]any{"device": device, "services": v})
return
}
jsonOut(w, map[string]any{"device": s.LocalName, "services": []any{}})
}
func (s *Server) CallAgentMCPJSON(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
return
}
var q MCPCallRequest
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.Server == "" || q.Tool == "" {
http.Error(w, "device, server and tool required", 400)
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.Store != nil {
_ = s.Store.Audit(clientIP(r), q.Device, "mcp_call", q.Server+"/"+q.Tool, 1, 0, "device offline")
}
http.Error(w, "device offline", 409)
return
}
if !s.isRemote(q.Device) {
http.Error(w, "agent MCP requires a remote device", 400)
return
}
start := time.Now()
v, err := s.Cluster.CallMCP(r.Context(), q.Device, q.Server, q.Tool, q.Arguments)
ms := time.Since(start).Milliseconds()
if err != nil {
_ = s.Store.Audit(clientIP(r), q.Device, "mcp_call", q.Server+"/"+q.Tool, 1, ms, err.Error())
http.Error(w, err.Error(), 502)
return
}
_ = s.Store.Audit(clientIP(r), q.Device, "mcp_call", q.Server+"/"+q.Tool, 0, ms, "")
jsonOut(w, v)
}
func (s *Server) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/healthz", s.health)
@@ -83,6 +483,17 @@ func (s *Server) Routes() http.Handler {
mux.HandleFunc("/api/v1/exec", s.exec)
mux.HandleFunc("/api/v1/file/read", s.fileRead)
mux.HandleFunc("/api/v1/file/write", s.fileWrite)
mux.HandleFunc("/api/v1/mcp/services", s.MCPServicesJSON)
mux.HandleFunc("/api/v1/mcp/service", s.DeleteMCPService)
mux.HandleFunc("/api/v1/mcp/list", s.ListAgentMCPJSON)
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("/openapi.json", s.openapi)
return mux
@@ -106,15 +517,35 @@ func (s *Server) devices(w http.ResponseWriter, r *http.Request) {
return
}
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 {
for _, d := range s.Cluster.Devices() {
b, _ := json.Marshal(d)
var v model.Device
_ = 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)
}
@@ -168,6 +599,9 @@ func (s *Server) exec(w http.ResponseWriter, r *http.Request) {
if req.Device == "" {
req.Device = s.LocalName
}
if !s.requireSecurity(w, r, req.Device, "exec", req.Command) {
return
}
if req.Timeout <= 0 {
req.Timeout = 30
}
@@ -179,7 +613,7 @@ func (s *Server) exec(w http.ResponseWriter, r *http.Request) {
var res executor.Result
if s.isRemote(req.Device) {
if s.Cluster == nil || !s.Cluster.Online(req.Device) {
http.Error(w, "device offline", 404)
http.Error(w, "device offline", 409)
return
}
rr, err := s.Cluster.Exec(ctx, req.Device, cluster.ExecPayload{Command: req.Command, Workdir: req.Workdir, Timeout: req.Timeout})
@@ -210,6 +644,9 @@ func (s *Server) fileRead(w http.ResponseWriter, r *http.Request) {
if req.Device == "" {
req.Device = s.LocalName
}
if !s.requireSecurity(w, r, req.Device, "read", req.Path) {
return
}
if req.Path == "" || !validPath(req.Path) || req.Offset < 0 {
http.Error(w, "invalid path or offset", 400)
return
@@ -282,6 +719,9 @@ func (s *Server) fileWrite(w http.ResponseWriter, r *http.Request) {
if req.Device == "" {
req.Device = s.LocalName
}
if !s.requireSecurity(w, r, req.Device, "write", req.Path) {
return
}
if req.Path == "" || !validPath(req.Path) {
http.Error(w, "path required", 400)
return
+40
View File
@@ -18,6 +18,9 @@ func TestExecConcurrent100AuditsPersisted(t *testing.T) {
}
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"}
const n = 100
@@ -48,3 +51,40 @@ func TestExecConcurrent100AuditsPersisted(t *testing.T) {
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)
}
}
+35
View File
@@ -188,3 +188,38 @@ func (b *MCPBackend) WriteFile(ctx context.Context, clientIP, device, path, cont
Bytes: n,
}, nil
}
func (b *MCPBackend) ListAgentMCP(ctx context.Context, device string) (any, error) {
if device == "" {
return nil, errors.New("device required")
}
if b.server.isRemote(device) && (b.server.Cluster == nil || !b.server.Cluster.Online(device)) {
return nil, fmt.Errorf("device %s is offline", device)
}
if !b.server.isRemote(device) {
return map[string]any{"device": b.server.LocalName, "services": []any{}}, nil
}
return b.server.Cluster.ListMCP(device)
}
func (b *MCPBackend) CallAgentMCP(ctx context.Context, clientIP, device, server, tool string, args any) (any, error) {
if device == "" || server == "" || tool == "" {
return nil, errors.New("device, server and tool required")
}
if b.server.isRemote(device) && (b.server.Cluster == nil || !b.server.Cluster.Online(device)) {
return nil, fmt.Errorf("device %s is offline", device)
}
if !b.server.isRemote(device) {
return nil, errors.New("agent MCP requires a remote device")
}
start := time.Now()
v, err := b.server.Cluster.CallMCP(ctx, device, server, tool, args)
ms := time.Since(start).Milliseconds()
if b.server.Store != nil {
if err != nil {
_ = b.server.Store.Audit(clientIP, device, "mcp_call", server+"/"+tool, 1, ms, err.Error())
} else {
_ = b.server.Store.Audit(clientIP, device, "mcp_call", server+"/"+tool, 0, ms, "")
}
}
return v, err
}
+335
View File
@@ -157,6 +157,69 @@
"type": "integer"
}
}
},
"MCPService": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"description": {
"type": "string"
},
"transport": {
"type": "string"
},
"command": {
"type": "string"
},
"args_json": {
"type": "string"
},
"env_json": {
"type": "string"
},
"url": {
"type": "string"
},
"headers_json": {
"type": "string"
},
"scope": {
"type": "string"
},
"target_nodes_json": {
"type": "string"
},
"enabled": {
"type": "boolean"
}
}
},
"MCPCallRequest": {
"type": "object",
"required": [
"device",
"server",
"tool"
],
"properties": {
"device": {
"type": "string"
},
"server": {
"type": "string"
},
"tool": {
"type": "string"
},
"arguments": {
"type": "object"
}
}
}
}
},
@@ -281,6 +344,278 @@
}
}
}
},
"/api/v1/mcp/services": {
"get": {
"operationId": "list_mcp_services",
"security": [
{
"bearerAuth": []
}
],
"responses": {
"200": {
"description": "MCP services",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/MCPService"
}
}
}
}
}
}
},
"post": {
"operationId": "save_mcp_service",
"security": [
{
"bearerAuth": []
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/MCPService"
}
}
}
},
"responses": {
"200": {
"description": "Saved MCP service"
}
}
}
},
"/api/v1/mcp/service": {
"delete": {
"operationId": "delete_mcp_service",
"security": [
{
"bearerAuth": []
}
],
"parameters": [
{
"name": "id",
"in": "query",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Deleted"
}
}
}
},
"/api/v1/mcp/list": {
"get": {
"operationId": "list_agent_mcp",
"security": [
{
"bearerAuth": []
}
],
"parameters": [
{
"name": "device",
"in": "query",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Mounted MCP services"
},
"409": {
"description": "Device offline"
}
}
}
},
"/api/v1/mcp/call": {
"post": {
"operationId": "call_agent_mcp",
"security": [
{
"bearerAuth": []
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/MCPCallRequest"
}
}
}
},
"responses": {
"200": {
"description": "MCP result"
},
"409": {
"description": "Device offline"
}
}
}
},
"/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")
}
})
}
+224 -39
View File
@@ -2,6 +2,7 @@ package cluster
import (
"context"
"sort"
"crypto/subtle"
"encoding/json"
"errors"
@@ -16,6 +17,8 @@ import (
"github.com/wjyhk/vps-commander/internal/sysinfo"
)
const deviceOfflineAfter = 70 * time.Second
type Manager struct {
Secret string
Store *storage.Store
@@ -24,12 +27,22 @@ type Manager struct {
}
type Node struct {
Name string
Conn *websocket.Conn
WriteMu sync.Mutex
Pending sync.Map
LastSeen atomic.Int64
LastProfile *sysinfo.Profile
Name string
Conn *websocket.Conn
ConnectionID string
WriteMu sync.Mutex
Pending sync.Map
LastSeen atomic.Int64
LastHeartbeat atomic.Int64
Connected atomic.Bool
LastProfile *sysinfo.Profile
Arch string
OS string
IsLocal bool
RemoteIP string
CountryCode string
Country string
MCP *MCPRuntime
}
type Result struct {
@@ -47,8 +60,30 @@ type FileResult struct {
EOF bool `json:"eof"`
}
func NewManager(secret string) *Manager {
return &Manager{Secret: secret, nodes: make(map[string]*Node)}
func NewManager(secret string, store *storage.Store) *Manager {
m := &Manager{Secret: secret, Store: store, nodes: make(map[string]*Node)}
if store != nil {
if records, err := store.ListDevices(); err == nil {
for _, d := range records {
if d.IsLocal {
continue
}
n := &Node{Name: d.Name, Arch: d.Arch, OS: d.OS, MCP: NewMCPRuntime()}
n.LastSeen.Store(d.LastSeen * int64(time.Second))
n.LastHeartbeat.Store(d.LastHeartbeat * int64(time.Second))
if d.ProfileJSON != "" {
var p sysinfo.Profile
if json.Unmarshal([]byte(d.ProfileJSON), &p) == nil {
n.LastProfile = &p
}
}
n.Connected.Store(false)
m.nodes[d.Name] = n
_ = store.UpdateDeviceStatus(d.Name, "offline", d.LastHeartbeat)
}
}
}
return m
}
func (m *Manager) SetStore(s *storage.Store) {
@@ -83,15 +118,29 @@ func (m *Manager) ServeWS(w http.ResponseWriter, r *http.Request) {
if err != nil {
return
}
n := &Node{Name: name, Conn: c}
n.LastSeen.Store(time.Now().UnixNano())
m.mu.Lock()
if old := m.nodes[name]; old != nil {
_ = old.Conn.Close()
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.LastHeartbeat.Store(time.Now().UnixNano())
n.Connected.Store(true)
m.mu.Lock()
old := m.nodes[name]
m.nodes[name] = n
m.mu.Unlock()
if old != nil && old.Conn != nil {
_ = old.Conn.Close()
}
_ = n.write(Message{Event: "registered", Device: name, TS: time.Now().Unix()})
m.syncMCP(n)
go m.heartbeat(n)
go m.readLoop(n)
}
@@ -107,33 +156,59 @@ func (n *Node) write(msg Message) error {
func (m *Manager) readLoop(n *Node) {
defer func() {
m.mu.Lock()
if m.nodes[n.Name] == n {
delete(m.nodes, n.Name)
n.Connected.Store(false)
conn := n.Conn
m.mu.RLock()
current := m.nodes[n.Name] == n
m.mu.RUnlock()
if conn != nil {
_ = conn.Close()
}
m.mu.Unlock()
_ = n.Conn.Close()
n.Pending.Range(func(key, v any) bool {
if ch, ok := v.(chan Message); ok {
select {
case ch <- Message{Status: "error", Error: "device disconnected"}:
default:
}
n.Pending.Delete(key)
}
n.Pending.Delete(key)
return true
})
if current && m.Store != nil {
_ = m.Store.UpdateDeviceStatus(n.Name, "offline", n.LastHeartbeat.Load()/int64(time.Second))
}
}()
_ = n.Conn.SetReadDeadline(time.Now().Add(75 * time.Second))
conn := n.Conn
if conn == nil {
return
}
_ = conn.SetReadDeadline(time.Now().Add(75 * time.Second))
for {
var msg Message
if err := n.Conn.ReadJSON(&msg); err != nil {
if err := conn.ReadJSON(&msg); err != nil {
return
}
n.LastSeen.Store(time.Now().UnixNano())
_ = n.Conn.SetReadDeadline(time.Now().Add(75 * time.Second))
now := time.Now().UnixNano()
n.LastSeen.Store(now)
_ = conn.SetReadDeadline(time.Now().Add(75 * time.Second))
if msg.Arch != "" {
n.Arch = msg.Arch
}
if msg.OS != "" {
n.OS = msg.OS
}
if msg.Profile != nil {
n.LastProfile = msg.Profile
n.LastHeartbeat.Store(now)
if m.Store != nil {
b, _ := json.Marshal(msg.Profile)
_ = m.Store.UpsertRemote(n.Name, "online", n.Arch, n.OS, now/int64(time.Second), string(b))
}
} else {
n.LastHeartbeat.Store(now)
if m.Store != nil {
_ = m.Store.UpdateDeviceStatus(n.Name, "online", now/int64(time.Second))
}
}
if msg.Event == "pong" || msg.Event == "ping" || msg.Event == "hello" || msg.Event == "profile" {
continue
@@ -153,21 +228,26 @@ func (m *Manager) readLoop(n *Node) {
func (m *Manager) Online(name string) bool {
m.mu.RLock()
defer m.mu.RUnlock()
n := m.nodes[name]
return n != nil && time.Since(time.Unix(0, n.LastSeen.Load())) < 70*time.Second
m.mu.RUnlock()
if n == nil || !n.Connected.Load() {
return false
}
return time.Since(time.Unix(0, n.LastSeen.Load())) < deviceOfflineAfter
}
func (m *Manager) RevokeDevice(name, reason string) error {
m.mu.Lock()
n, exists := m.nodes[name]
if exists {
delete(m.nodes, name)
_ = n.write(Message{Event: "revoked", Error: "revoked by admin"})
_ = n.Conn.Close()
}
n := m.nodes[name]
delete(m.nodes, name)
m.mu.Unlock()
if n != nil {
n.Connected.Store(false)
if n.Conn != nil {
_ = n.write(Message{Event: "revoked", Error: "revoked by admin"})
_ = n.Conn.Close()
}
}
if m.Store != nil {
return m.Store.RevokeDevice(name, reason)
}
@@ -179,22 +259,29 @@ func (m *Manager) Devices() []map[string]any {
defer m.mu.RUnlock()
out := make([]map[string]any, 0, len(m.nodes))
for name, n := range m.nodes {
status := "online"
status := "offline"
lastSeen := time.Unix(0, n.LastSeen.Load())
if time.Since(lastSeen) >= 70*time.Second {
status = "offline"
if n.Connected.Load() && time.Since(lastSeen) < deviceOfflineAfter {
status = "online"
}
item := map[string]any{
"name": name,
"status": status,
"is_local": false,
"last_heartbeat": lastSeen.Unix(),
"name": name, "status": status, "is_local": n.IsLocal,
"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),
}
if n.LastProfile != nil {
item["profile"] = n.LastProfile
}
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
}
@@ -263,6 +350,104 @@ func (m *Manager) WriteFile(ctx context.Context, name string, p FileWritePayload
return v.Bytes, nil
}
func (m *Manager) syncMCP(n *Node) {
if n == nil || n.MCP == nil || m.Store == nil {
return
}
stored, err := m.Store.ListMCPServicesForNode(n.Name)
if err != nil {
return
}
services := make([]MCPService, 0, len(stored))
for _, v := range stored {
services = append(services, decodeStoredMCPService(v))
}
_ = n.write(Message{Event: "mcp_sync", Payload: services, TS: time.Now().Unix()})
}
func decodeStoredMCPService(v storage.MCPService) MCPService {
out := MCPService{ID: v.ID, Name: v.Name, Description: v.Description, Transport: v.Transport, Command: v.Command, URL: v.URL}
_ = json.Unmarshal([]byte(v.ArgsJSON), &out.Args)
_ = json.Unmarshal([]byte(v.EnvJSON), &out.Env)
_ = json.Unmarshal([]byte(v.HeadersJSON), &out.Headers)
return out
}
func (m *Manager) SyncMCPServices() {
m.mu.RLock()
nodes := make([]*Node, 0, len(m.nodes))
for _, n := range m.nodes {
nodes = append(nodes, n)
}
m.mu.RUnlock()
for _, n := range nodes {
if n.Connected.Load() {
m.syncMCP(n)
}
}
}
func (m *Manager) ListMCP(name string) ([]MCPService, 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(context.Background(), name, "mcp_list", nil)
if err != nil {
return nil, err
}
var out []MCPService
b, _ := json.Marshal(msg.Payload)
if err := json.Unmarshal(b, &out); err != nil {
return nil, err
}
if n.MCP == nil {
n.MCP = NewMCPRuntime()
}
n.MCP.Sync(out)
return out, nil
}
func (m *Manager) CallMCP(ctx context.Context, name, server, tool string, args any) (MCPCallResult, error) {
m.mu.RLock()
n := m.nodes[name]
m.mu.RUnlock()
if n == nil || !m.Online(name) {
return MCPCallResult{}, fmt.Errorf("device %s is offline", name)
}
msg, err := m.call(ctx, name, "mcp_call", map[string]any{"server": server, "tool": tool, "args": args})
if err != nil {
return MCPCallResult{}, err
}
var out MCPCallResult
b, _ := json.Marshal(msg.Payload)
if err := json.Unmarshal(b, &out); err != nil {
return MCPCallResult{}, err
}
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) {
t := time.NewTicker(30 * time.Second)
defer t.Stop()
+483
View File
@@ -0,0 +1,483 @@
package cluster
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"strings"
"sync"
)
type MCPService struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Transport string `json:"transport"`
Command string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
Env map[string]string `json:"env,omitempty"`
URL string `json:"url,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
}
type MCPCallResult struct {
Server string `json:"server"`
Tool string `json:"tool"`
Result any `json:"result,omitempty"`
Error string `json:"error,omitempty"`
DurationMS int64 `json:"duration_ms"`
}
type mcpRPC struct {
JSONRPC string `json:"jsonrpc"`
ID any `json:"id,omitempty"`
Method string `json:"method"`
Params any `json:"params,omitempty"`
}
type mcpRPCResponse struct {
JSONRPC string `json:"jsonrpc"`
ID any `json:"id,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
} `json:"error,omitempty"`
}
type MCPRuntime struct {
mu sync.RWMutex
services map[string]MCPService
}
func NewMCPRuntime() *MCPRuntime { return &MCPRuntime{services: make(map[string]MCPService)} }
func (r *MCPRuntime) Sync(services []MCPService) {
next := make(map[string]MCPService, len(services))
for _, s := range services {
if s.ID == "" || s.Transport == "" {
continue
}
next[s.ID] = s
}
r.mu.Lock()
r.services = next
r.mu.Unlock()
}
func (r *MCPRuntime) List() []MCPService {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]MCPService, 0, len(r.services))
for _, s := range r.services {
out = append(out, s)
}
return out
}
func (r *MCPRuntime) Get(id string) (MCPService, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
s, ok := r.services[id]
return s, ok
}
func (r *MCPRuntime) Call(ctx context.Context, server, tool string, args any) (any, error) {
s, ok := r.Get(server)
if !ok {
return nil, fmt.Errorf("MCP service %q is not mounted", server)
}
switch strings.ToLower(s.Transport) {
case "stdio":
return callStdio(ctx, s, tool, args)
case "http", "sse":
return callHTTP(ctx, s, tool, args)
default:
return nil, fmt.Errorf("unsupported MCP transport %q", s.Transport)
}
}
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) {
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)
id := int64(1)
if err := enc.Encode(mcpRPC{JSONRPC: "2.0", ID: id, Method: "initialize", Params: map[string]any{
"protocolVersion": "2024-11-05", "capabilities": map[string]any{},
"clientInfo": map[string]string{"name": "vps-commander-agent", "version": "1.0"},
}}); err != nil {
return nil, err
}
if _, err := readRPC(ctx, dec, id); 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
}
id++
if err := enc.Encode(mcpRPC{JSONRPC: "2.0", ID: id, Method: "tools/call", Params: map[string]any{"name": tool, "arguments": args}}); err != nil {
return nil, err
}
return readRPC(ctx, dec, id)
}
func readRPC(ctx context.Context, r *bufio.Reader, wantID int64) (any, error) {
for {
lineCh := make(chan []byte, 1)
errCh := make(chan error, 1)
go func() {
b, err := r.ReadBytes('\n')
if err != nil && len(b) == 0 {
errCh <- err
return
}
lineCh <- bytes.TrimSpace(b)
}()
var line []byte
select {
case <-ctx.Done():
return nil, ctx.Err()
case err := <-errCh:
return nil, err
case line = <-lineCh:
}
if len(line) == 0 {
continue
}
var resp mcpRPCResponse
if json.Unmarshal(line, &resp) != nil {
continue
}
if resp.ID == nil {
continue
}
if n, ok := resp.ID.(float64); !ok || int64(n) != wantID {
continue
}
if resp.Error != nil {
return nil, fmt.Errorf("MCP error %d: %s", resp.Error.Code, resp.Error.Message)
}
var out any
if len(resp.Result) > 0 {
if err := json.Unmarshal(resp.Result, &out); err != nil {
return nil, err
}
}
return out, nil
}
}
func callHTTP(ctx context.Context, s MCPService, tool string, args any) (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, http.Header, error) {
b, _ := json.Marshal(req)
h := make(http.Header)
h.Set("Content-Type", "application/json")
h.Set("Accept", "application/json, text/event-stream")
for k, v := range s.Headers {
h.Set(k, v)
}
if session != "" {
h.Set("Mcp-Session-Id", session)
}
hr, err := http.NewRequestWithContext(ctx, http.MethodPost, s.URL, bytes.NewReader(b))
if err != nil {
return nil, nil, err
}
hr.Header = h
resp, err := client.Do(hr)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, resp.Header, 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, nil, err
}
if len(bytes.TrimSpace(data)) == 0 {
return nil, resp.Header, 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, resp.Header, err
}
if rr.Error != nil {
return nil, resp.Header, 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, resp.Header, err
}
}
return out, resp.Header, nil
}
if strings.EqualFold(s.Transport, "sse") {
endpoint, err := discoverSSEEndpoint(ctx, s)
if err != nil {
return nil, err
}
old := s.URL
s.URL = endpoint
defer func() { s.URL = old }()
}
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-agent", "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
}
return func() (any, error) {
v, _, err := post(mcpRPC{JSONRPC: "2.0", ID: int64(2), Method: "tools/call", Params: map[string]any{"name": tool, "arguments": args}})
return v, err
}()
}
func discoverSSEEndpoint(ctx context.Context, s MCPService) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.URL, nil)
if err != nil {
return "", err
}
for k, v := range s.Headers {
req.Header.Set(k, v)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return "", fmt.Errorf("MCP SSE status %s", resp.Status)
}
sc := bufio.NewScanner(io.LimitReader(resp.Body, 256*1024))
isEndpoint := false
for sc.Scan() {
line := sc.Text()
if strings.HasPrefix(line, "event:") {
isEndpoint = strings.TrimSpace(strings.TrimPrefix(line, "event:")) == "endpoint"
continue
}
if isEndpoint && strings.HasPrefix(line, "data:") {
u := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
if strings.HasPrefix(u, "/") {
base := *resp.Request.URL
base.Path = u
base.RawQuery = ""
return base.String(), nil
}
return u, nil
}
}
return "", errors.New("MCP SSE endpoint event not received")
}
func parseSSEData(b []byte) []byte {
for _, line := range strings.Split(string(b), "\n") {
if strings.HasPrefix(line, "data:") {
return []byte(strings.TrimSpace(strings.TrimPrefix(line, "data:")))
}
}
return b
}
func envList(m map[string]string) []string {
out := make([]string, 0, len(m))
for k, v := range m {
out = append(out, k+"="+v)
}
return out
}
+80
View File
@@ -0,0 +1,80 @@
package cluster
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"testing"
"time"
)
func TestMCPRuntimeStdioOnDemand(t *testing.T) {
if _, err := exec.LookPath("python3"); err != nil {
t.Skip("python3 unavailable")
}
dir := t.TempDir()
script := dir + "/mcp.py"
code := `import json,sys
for line in sys.stdin:
r=json.loads(line)
if r.get("method")=="initialize":
print(json.dumps({"jsonrpc":"2.0","id":r["id"],"result":{"protocolVersion":"2024-11-05"}}),flush=True)
elif r.get("method")=="tools/call":
a=r.get("params",{}).get("arguments",{})
print(json.dumps({"jsonrpc":"2.0","id":r["id"],"result":{"content":[{"type":"text","text":"hello "+a.get("name","")}]}}),flush=True)
`
if err := os.WriteFile(script, []byte(code), 0755); err != nil {
t.Fatal(err)
}
r := NewMCPRuntime()
r.Sync([]MCPService{{ID: "test", Transport: "stdio", Command: "python3", Args: []string{script}}})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
v, err := r.Call(ctx, "test", "hello", map[string]any{"name": "vpc"})
if err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(v)
if string(b) == "" {
t.Fatal("empty result")
}
if !contains(string(b), "hello vpc") {
t.Fatalf("unexpected %s", b)
}
}
func TestMCPRuntimeHTTP(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
var q mcpRPC
_ = json.Unmarshal(b, &q)
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%s,"result":{"ok":true}}`, jsonID(q.ID))
}))
defer ts.Close()
r := NewMCPRuntime()
r.Sync([]MCPService{{ID: "http", Transport: "http", URL: ts.URL}})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
v, err := r.Call(ctx, "http", "ping", map[string]any{})
if err != nil {
t.Fatal(err)
}
if !contains(fmt.Sprint(v), "true") {
t.Fatalf("unexpected %v", v)
}
}
func jsonID(v any) string { b, _ := json.Marshal(v); return string(b) }
func contains(s, x string) bool {
for i := 0; i+len(x) <= len(s); i++ {
if s[i:i+len(x)] == x {
return true
}
}
return false
}
+2
View File
@@ -7,6 +7,8 @@ type Message struct {
Event string `json:"event,omitempty"`
Action string `json:"action,omitempty"`
Device string `json:"device,omitempty"`
Arch string `json:"arch,omitempty"`
OS string `json:"os,omitempty"`
Status string `json:"status,omitempty"`
Payload any `json:"payload,omitempty"`
Profile *sysinfo.Profile `json:"profile,omitempty"`
+50
View File
@@ -76,6 +76,11 @@ type ActionBackend interface {
WriteFile(ctx context.Context, clientIP, device, path, content string) (any, error)
}
type AgentMCPBackend interface {
ListAgentMCP(ctx context.Context, device string) (any, error)
CallAgentMCP(ctx context.Context, clientIP, device, server, tool string, args any) (any, error)
}
type Server struct {
Backend ActionBackend
Auth *auth.Manager
@@ -272,6 +277,14 @@ func (s *Server) handleRequest(ctx context.Context, r *http.Request, req JSONRPC
Required: []string{"path", "content"},
},
},
{
Name: "list_agent_mcp", Description: "列出指定 Agent 当前通过 Hub 动态挂载的 MCP 服务及状态",
InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标 Agent 节点名称"}}, Required: []string{"device"}},
},
{
Name: "call_agent_mcp", Description: "通过 Hub 调度指定 Agent 上已挂载的 MCP 工具",
InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标 Agent 节点名称"}, "server": {Type: "string", Description: "MCP 服务 ID"}, "tool": {Type: "string", Description: "MCP 工具名称"}, "arguments": {Type: "object", Description: "MCP 工具参数 JSON 对象"}}, Required: []string{"device", "server", "tool"}},
},
}
return JSONRPCResponse{
JSONRPC: "2.0",
@@ -372,6 +385,43 @@ func (s *Server) callTool(ctx context.Context, clientIP string, params CallToolP
}
return res, false
case "list_agent_mcp":
var args struct {
Device string `json:"device"`
}
_ = json.Unmarshal(params.Arguments, &args)
b, ok := s.Backend.(AgentMCPBackend)
if !ok {
return map[string]string{"error": "agent MCP unavailable"}, true
}
res, err := b.ListAgentMCP(ctx, args.Device)
if err != nil {
return map[string]string{"error": err.Error()}, true
}
return res, false
case "call_agent_mcp":
var args struct {
Device string `json:"device"`
Server string `json:"server"`
Tool string `json:"tool"`
Arguments json.RawMessage `json:"arguments"`
}
_ = json.Unmarshal(params.Arguments, &args)
b, ok := s.Backend.(AgentMCPBackend)
if !ok {
return map[string]string{"error": "agent MCP unavailable"}, true
}
var av any
if len(args.Arguments) > 0 {
_ = json.Unmarshal(args.Arguments, &av)
}
res, err := b.CallAgentMCP(ctx, clientIP, args.Device, args.Server, args.Tool, av)
if err != nil {
return map[string]string{"error": err.Error()}, true
}
return res, false
default:
return map[string]string{"error": "unknown tool: " + params.Name}, true
}
+2 -2
View File
@@ -75,8 +75,8 @@ func TestMCPInitializeAndListTools(t *testing.T) {
t.Fatalf("expected map result")
}
tools, ok := resMap["tools"].([]any)
if !ok || len(tools) != 4 {
t.Fatalf("expected 4 tools, got %d", len(tools))
if !ok || len(tools) != 6 {
t.Fatalf("expected 6 tools, got %d", len(tools))
}
}
+9 -6
View File
@@ -18,12 +18,15 @@ type ExecResponse struct {
}
type Device struct {
Name string `json:"name"`
Status string `json:"status"`
Local bool `json:"is_local"`
Arch string `json:"arch,omitempty"`
OS string `json:"os,omitempty"`
Profile *sysinfo.Profile `json:"profile,omitempty"`
Name string `json:"name"`
Status string `json:"status"`
Local bool `json:"is_local"`
Arch string `json:"arch,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"`
}
type FileReadRequest struct {
+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)
}
}
+51
View File
@@ -0,0 +1,51 @@
package storage
import (
"path/filepath"
"testing"
)
func TestDeviceLifecyclePersistence(t *testing.T) {
s, err := Open(filepath.Join(t.TempDir(), "commander.db"))
if err != nil {
t.Fatal(err)
}
defer s.DB.Close()
if err := s.UpsertRemote("node1", "online", "amd64", "linux", 100, "{\"role\":\"APPLICATION\"}"); err != nil {
t.Fatal(err)
}
rows, err := s.ListDevices()
if err != nil || len(rows) != 1 {
t.Fatalf("rows=%d err=%v", len(rows), err)
}
if rows[0].Status != "online" || rows[0].Arch != "amd64" || rows[0].OS != "linux" {
t.Fatalf("unexpected row: %+v", rows[0])
}
if err := s.UpdateDeviceStatus("node1", "offline", 120); err != nil {
t.Fatal(err)
}
rows, err = s.ListDevices()
if err != nil || len(rows) != 1 {
t.Fatalf("rows=%d err=%v", len(rows), err)
}
if rows[0].Status != "offline" || rows[0].OfflineAt == nil {
t.Fatalf("offline state not persisted: %+v", rows[0])
}
if err := s.RevokeDevice("node1", "test"); err != nil {
t.Fatal(err)
}
rows, err = s.ListDevices()
if err != nil {
t.Fatal(err)
}
if len(rows) != 0 {
t.Fatalf("revoked device still present: %+v", rows)
}
revoked, err := s.IsRevoked("node1")
if err != nil || !revoked {
t.Fatalf("revoked=%v err=%v", revoked, err)
}
}
+365 -35
View File
@@ -2,9 +2,12 @@ package storage
import (
"database/sql"
"encoding/json"
"errors"
_ "modernc.org/sqlite"
"os"
"path/filepath"
"strings"
"time"
)
@@ -18,8 +21,6 @@ func Open(path string) (*Store, error) {
if err != nil {
return nil, err
}
// SQLite has a single-writer model. Keep one application connection so
// concurrent callers queue instead of opening competing writer connections.
db.SetMaxOpenConns(1)
db.SetMaxIdleConns(1)
s := &Store{db}
@@ -31,28 +32,235 @@ func Open(path string) (*Store, error) {
}
func (s *Store) init() error {
if _, err := s.DB.Exec(`PRAGMA journal_mode = WAL`); err != nil {
if _, err := s.DB.Exec("PRAGMA journal_mode = WAL"); err != nil {
return err
}
if _, err := s.DB.Exec(`PRAGMA busy_timeout = 5000`); err != nil {
if _, err := s.DB.Exec("PRAGMA busy_timeout = 5000"); err != nil {
return err
}
_, err := s.DB.Exec(`CREATE TABLE IF NOT EXISTS devices (
name TEXT PRIMARY KEY, status TEXT NOT NULL, is_local INTEGER NOT NULL,
arch TEXT, os TEXT, updated_at INTEGER NOT NULL
); 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,
exit_code INTEGER, duration_ms INTEGER, error_msg TEXT
);`)
_, 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, " +
"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); " +
"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, " +
"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 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 {
return err
}
return s.migrateDevices()
}
type MCPService struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Transport string `json:"transport"`
Command string `json:"command,omitempty"`
ArgsJSON string `json:"args_json,omitempty"`
EnvJSON string `json:"env_json,omitempty"`
URL string `json:"url,omitempty"`
HeadersJSON string `json:"headers_json,omitempty"`
Scope string `json:"scope"`
TargetNodesJSON string `json:"target_nodes_json,omitempty"`
Enabled bool `json:"enabled"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
func (s *Store) SaveMCPService(v MCPService) error {
now := time.Now().Unix()
if v.CreatedAt <= 0 {
v.CreatedAt = now
}
v.UpdatedAt = now
if v.Scope == "" {
v.Scope = "all"
}
if v.Transport == "" {
return errors.New("transport required")
}
_, err := s.DB.Exec(`INSERT INTO mcp_services(id,name,description,transport,command,args_json,env_json,url,headers_json,scope,target_nodes_json,enabled,created_at,updated_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,description=excluded.description,transport=excluded.transport,command=excluded.command,args_json=excluded.args_json,env_json=excluded.env_json,url=excluded.url,headers_json=excluded.headers_json,scope=excluded.scope,target_nodes_json=excluded.target_nodes_json,enabled=excluded.enabled,updated_at=excluded.updated_at`,
v.ID, v.Name, v.Description, v.Transport, v.Command, v.ArgsJSON, v.EnvJSON, v.URL, v.HeadersJSON, v.Scope, v.TargetNodesJSON, boolInt(v.Enabled), v.CreatedAt, v.UpdatedAt)
return err
}
func boolInt(v bool) int {
if v {
return 1
}
return 0
}
func (s *Store) DeleteMCPService(id string) error {
_, err := s.DB.Exec(`DELETE FROM mcp_services WHERE id=?`, id)
return err
}
func (s *Store) ListMCPServices() ([]MCPService, error) {
return s.listMCP(`SELECT id,name,description,transport,COALESCE(command,''),COALESCE(args_json,''),COALESCE(env_json,''),COALESCE(url,''),COALESCE(headers_json,''),scope,COALESCE(target_nodes_json,''),enabled,created_at,updated_at FROM mcp_services ORDER BY id`)
}
func (s *Store) ListMCPServicesForNode(node string) ([]MCPService, error) {
all, err := s.listMCP(`SELECT id,name,description,transport,COALESCE(command,''),COALESCE(args_json,''),COALESCE(env_json,''),COALESCE(url,''),COALESCE(headers_json,''),scope,COALESCE(target_nodes_json,''),enabled,created_at,updated_at FROM mcp_services WHERE enabled=1 ORDER BY id`)
if err != nil {
return nil, err
}
out := make([]MCPService, 0, len(all))
for _, v := range all {
if v.Scope != "custom" || containsNode(v.TargetNodesJSON, node) {
out = append(out, v)
}
}
return out, nil
}
func containsNode(raw, node string) bool {
var a []string
if json.Unmarshal([]byte(raw), &a) != nil {
return false
}
for _, v := range a {
if v == node {
return true
}
}
return false
}
func (s *Store) listMCP(q string) ([]MCPService, error) {
rows, err := s.DB.Query(q)
if err != nil {
return nil, err
}
defer rows.Close()
out := []MCPService{}
for rows.Next() {
var v MCPService
var en int
if err := rows.Scan(&v.ID, &v.Name, &v.Description, &v.Transport, &v.Command, &v.ArgsJSON, &v.EnvJSON, &v.URL, &v.HeadersJSON, &v.Scope, &v.TargetNodesJSON, &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) migrateDevices() error {
cols := map[string]bool{}
rows, err := s.DB.Query("PRAGMA table_info(devices)")
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var cid, notnull, pk int
var name, typ string
var dflt sql.NullString
if err := rows.Scan(&cid, &name, &typ, &notnull, &dflt, &pk); err != nil {
return err
}
cols[name] = true
}
if err := rows.Err(); err != nil {
return err
}
migrations := []struct{ name, sql string }{
{"last_seen", "ALTER TABLE devices ADD COLUMN last_seen INTEGER NOT NULL DEFAULT 0"},
{"last_heartbeat", "ALTER TABLE devices ADD COLUMN last_heartbeat INTEGER NOT NULL DEFAULT 0"},
{"offline_at", "ALTER TABLE devices ADD COLUMN offline_at INTEGER"},
{"profile_json", "ALTER TABLE devices ADD COLUMN profile_json TEXT"},
{"created_at", "ALTER TABLE devices ADD COLUMN created_at INTEGER NOT NULL DEFAULT 0"},
}
for _, m := range migrations {
if !cols[m.name] {
if _, err := s.DB.Exec(m.sql); err != nil {
return err
}
}
}
_, err = s.DB.Exec("UPDATE devices SET created_at=CASE WHEN created_at=0 THEN updated_at ELSE created_at END, " +
"last_seen=CASE WHEN last_seen=0 THEN updated_at ELSE last_seen END, " +
"last_heartbeat=CASE WHEN last_heartbeat=0 THEN updated_at ELSE last_heartbeat END " +
"WHERE created_at=0 OR last_seen=0 OR last_heartbeat=0")
return err
}
func (s *Store) UpsertLocal(name, arch, osName string) error {
_, err := s.DB.Exec(`INSERT INTO devices(name,status,is_local,arch,os,updated_at)
VALUES(?,?,?,?,?,?) ON CONFLICT(name) DO UPDATE SET status=excluded.status,
arch=excluded.arch, os=excluded.os, updated_at=excluded.updated_at`,
name, "online", 1, arch, osName, time.Now().Unix())
now := time.Now().Unix()
_, err := s.DB.Exec("INSERT INTO devices(name,status,is_local,arch,os,last_seen,last_heartbeat,offline_at,profile_json,created_at,updated_at) "+
"VALUES(?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(name) DO UPDATE SET status='online', is_local=1, arch=excluded.arch, os=excluded.os, offline_at=NULL, updated_at=excluded.updated_at",
name, "online", 1, arch, osName, now, now, nil, nil, now, now)
return err
}
func (s *Store) UpsertRemote(name, status, arch, osName string, lastHeartbeat int64, profileJSON string) error {
now := time.Now().Unix()
if lastHeartbeat <= 0 {
lastHeartbeat = now
}
_, err := s.DB.Exec("INSERT INTO devices(name,status,is_local,arch,os,last_seen,last_heartbeat,offline_at,profile_json,created_at,updated_at) "+
"VALUES(?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(name) DO UPDATE SET status=excluded.status, is_local=0, arch=excluded.arch, os=excluded.os, "+
"last_seen=excluded.last_seen, last_heartbeat=excluded.last_heartbeat, offline_at=NULL, profile_json=excluded.profile_json, updated_at=excluded.updated_at",
name, status, 0, arch, osName, lastHeartbeat, lastHeartbeat, nil, profileJSON, now, now)
return err
}
func (s *Store) UpdateRemoteProfile(name string, lastHeartbeat int64, arch, osName, profileJSON string) error {
now := time.Now().Unix()
if lastHeartbeat <= 0 {
lastHeartbeat = now
}
_, err := s.DB.Exec("UPDATE devices SET status='online', arch=?, os=?, last_seen=?, last_heartbeat=?, offline_at=NULL, profile_json=?, updated_at=? WHERE name=? AND is_local=0",
arch, osName, lastHeartbeat, lastHeartbeat, profileJSON, now, name)
return err
}
func (s *Store) UpdateDeviceStatus(name, status string, lastHeartbeat int64) error {
now := time.Now().Unix()
if lastHeartbeat <= 0 {
lastHeartbeat = now
}
var offlineAt any
if status == "offline" {
offlineAt = now
}
_, err := s.DB.Exec("UPDATE devices SET status=?, last_seen=?, last_heartbeat=?, offline_at=?, updated_at=? WHERE name=? AND is_local=0",
status, lastHeartbeat, lastHeartbeat, offlineAt, now, name)
return err
}
type DeviceRecord struct {
Name, Status, Arch, OS, ProfileJSON string
IsLocal bool
LastSeen, LastHeartbeat int64
OfflineAt *int64
UpdatedAt int64
}
func (s *Store) ListDevices() ([]DeviceRecord, error) {
rows, err := s.DB.Query("SELECT name,status,is_local,COALESCE(arch,''),COALESCE(os,''),last_seen,last_heartbeat,offline_at,COALESCE(profile_json,''),updated_at FROM devices ORDER BY name")
if err != nil {
return nil, err
}
defer rows.Close()
var out []DeviceRecord
for rows.Next() {
var d DeviceRecord
var local int
var offline sql.NullInt64
if err := rows.Scan(&d.Name, &d.Status, &local, &d.Arch, &d.OS, &d.LastSeen, &d.LastHeartbeat, &offline, &d.ProfileJSON, &d.UpdatedAt); err != nil {
return nil, err
}
d.IsLocal = local != 0
if offline.Valid {
v := offline.Int64
d.OfflineAt = &v
}
out = append(out, d)
}
return out, rows.Err()
}
func (s *Store) DeleteDevice(name string) error {
_, err := s.DB.Exec("DELETE FROM devices WHERE name=? AND is_local=0", name)
return err
}
@@ -69,11 +277,57 @@ type AuditLog struct {
}
func (s *Store) Audit(ip, device, action, command string, code int, ms int64, msg string) error {
_, err := s.DB.Exec(`INSERT INTO audit_logs(timestamp,caller_ip,device,action,command,exit_code,duration_ms,error_msg)
VALUES(?,?,?,?,?,?,?,?)`, time.Now().Unix(), ip, device, action, command, code, ms, msg)
_, err := s.DB.Exec("INSERT INTO audit_logs(timestamp,caller_ip,device,action,command,exit_code,duration_ms,error_msg) VALUES(?,?,?,?,?,?,?,?)",
time.Now().Unix(), ip, device, action, command, code, ms, msg)
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) {
if limit <= 0 {
limit = 100
@@ -81,8 +335,7 @@ func (s *Store) RecentAudits(limit int) ([]AuditLog, error) {
if limit > 500 {
limit = 500
}
rows, err := s.DB.Query(`SELECT id,timestamp,caller_ip,device,action,command,exit_code,duration_ms,error_msg
FROM audit_logs ORDER BY id DESC LIMIT ?`, limit)
rows, err := s.DB.Query("SELECT id,timestamp,caller_ip,device,action,command,exit_code,duration_ms,error_msg FROM audit_logs ORDER BY id DESC LIMIT ?", limit)
if err != nil {
return nil, err
}
@@ -98,29 +351,106 @@ func (s *Store) RecentAudits(limit int) ([]AuditLog, error) {
return out, rows.Err()
}
func (s *Store) InitRevocationTable() error {
_, err := s.DB.Exec(`CREATE TABLE IF NOT EXISTS revoked_devices (
name TEXT PRIMARY KEY,
revoked_at INTEGER NOT NULL,
reason TEXT
);`)
return err
}
func (s *Store) RevokeDevice(name, reason string) error {
_, err := s.DB.Exec(`INSERT INTO revoked_devices(name, revoked_at, reason)
VALUES(?, ?, ?) ON CONFLICT(name) DO UPDATE SET revoked_at=excluded.revoked_at, reason=excluded.reason`,
name, time.Now().Unix(), reason)
return err
tx, err := s.DB.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.Exec("INSERT INTO revoked_devices(name,revoked_at,reason) VALUES(?,?,?) ON CONFLICT(name) DO UPDATE SET revoked_at=excluded.revoked_at,reason=excluded.reason",
name, time.Now().Unix(), reason); err != nil {
return err
}
if _, err := tx.Exec("DELETE FROM devices WHERE name=? AND is_local=0", name); err != nil {
return err
}
return tx.Commit()
}
func (s *Store) UnrevokeDevice(name string) error {
_, err := s.DB.Exec(`DELETE FROM revoked_devices WHERE name = ?`, name)
_, err := s.DB.Exec("DELETE FROM revoked_devices WHERE name = ?", name)
return err
}
func (s *Store) IsRevoked(name string) (bool, error) {
var count int
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
}
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()
}
+140 -27
View File
@@ -7,15 +7,37 @@ import (
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"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 {
Role string `json:"role,omitempty"`
CPUCores int `json:"cpu_cores"`
CPUUsagePercent int `json:"cpu_usage_percent"`
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"`
MemAvailable string `json:"mem_available"`
DiskPercent int `json:"disk_percent"`
@@ -36,7 +58,9 @@ func Collect(defaultRole string) Profile {
cores := runtime.NumCPU()
cpuPercent := getCPUUsage()
load1m := getLoad1M()
load1m, load5m, load15m := getLoads()
netRX, netTX, netRXT, netTXT := getNetwork()
uptime, boot := getUptime()
memPct, memAvl := getMemInfo()
diskPct, diskFree := getDiskInfo()
psi := getIOPSI()
@@ -47,6 +71,14 @@ func Collect(defaultRole string) Profile {
CPUCores: cores,
CPUUsagePercent: cpuPercent,
Load1M: load1m,
Load5M: load5m,
Load15M: load15m,
NetRXRate: netRX,
NetTXRate: netTX,
NetRXTotal: netRXT,
NetTXTotal: netTXT,
UptimeSeconds: uptime,
BootTime: boot,
MemPercent: memPct,
MemAvailable: memAvl,
DiskPercent: diskPct,
@@ -57,16 +89,70 @@ func Collect(defaultRole string) Profile {
}
}
func getLoad1M() float64 {
if data, err := os.ReadFile("/proc/loadavg"); err == nil {
fields := strings.Fields(string(data))
if len(fields) > 0 {
if val, err := strconv.ParseFloat(fields[0], 64); err == nil {
return val
}
func getLoads() (float64, float64, float64) {
data, err := os.ReadFile("/proc/loadavg")
if err != nil {
return 0, 0, 0
}
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
}
}
return 0.0
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
}
}
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 {
@@ -116,28 +202,55 @@ func sampleCPUStat() int {
return 0, 0, false
}
idle1, total1, ok1 := readStat()
if !ok1 {
idleCurr, totalCurr, ok := readStat()
if !ok {
return -1
}
time.Sleep(50 * time.Millisecond)
idle2, total2, ok2 := readStat()
if !ok2 || total2 <= total1 {
return -1
now := time.Now()
cpuMu.Lock()
defer cpuMu.Unlock()
if lastCPU.total > 0 && totalCurr > lastCPU.total && now.Sub(lastCPU.at) >= 500*time.Millisecond {
deltaTotal := totalCurr - lastCPU.total
deltaIdle := idleCurr - lastCPU.idle
if deltaTotal > 0 && deltaTotal >= deltaIdle {
busy := float64(deltaTotal-deltaIdle) / float64(deltaTotal) * 100
if busy < 0 {
busy = 0
}
if busy > 100 {
busy = 100
}
lastCPU.usage = int(busy)
lastCPU.idle = idleCurr
lastCPU.total = totalCurr
lastCPU.at = now
return lastCPU.usage
}
}
deltaTotal := total2 - total1
deltaIdle := idle2 - idle1
if deltaTotal == 0 {
return 0
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()
}
}
}
busy := float64(deltaTotal-deltaIdle) / float64(deltaTotal) * 100
if busy < 0 {
busy = 0
}
if busy > 100 {
busy = 100
}
return int(busy)
return lastCPU.usage
}
func getMemInfo() (memPct int, memAvl string) {
+133 -1
View File
@@ -38,15 +38,129 @@ func (p *Panel) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/panel/login", p.login)
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("/panel/api/devices", p.protected(p.handleDevices))
mux.HandleFunc("/panel/api/audits", p.protected(p.Runner.AuditsJSON))
mux.HandleFunc("/panel/api/exec", p.protected(p.Runner.PanelExec))
mux.HandleFunc("/panel/api/key/rotate", p.protected(p.Runner.RotateAPIKey))
mux.HandleFunc("/", p.index)
mux.HandleFunc("/panel/api/mcp/services", p.protected(p.mcpServices))
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/call", p.protected(p.callAgentMCP))
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
}
type securityPanelRunner interface {
SecuritySettingsJSON(http.ResponseWriter, *http.Request)
UpdateSecuritySettingsJSON(http.ResponseWriter, *http.Request)
}
type mcpPanelRunner interface {
MCPServicesJSON(http.ResponseWriter, *http.Request)
DeleteMCPService(http.ResponseWriter, *http.Request)
ListAgentMCPJSON(http.ResponseWriter, *http.Request)
CallAgentMCPJSON(http.ResponseWriter, *http.Request)
TestMCPJSON(http.ResponseWriter, *http.Request)
}
func (p *Panel) mcpServices(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(mcpPanelRunner); ok {
v.MCPServicesJSON(w, r)
return
}
http.Error(w, "MCP API unavailable", 501)
}
func (p *Panel) deleteMCPService(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(mcpPanelRunner); ok {
v.DeleteMCPService(w, r)
return
}
http.Error(w, "MCP API unavailable", 501)
}
func (p *Panel) listAgentMCP(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(mcpPanelRunner); ok {
v.ListAgentMCPJSON(w, r)
return
}
http.Error(w, "MCP API unavailable", 501)
}
func (p *Panel) callAgentMCP(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(mcpPanelRunner); ok {
v.CallAgentMCPJSON(w, r)
return
}
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) {
if r.Method == http.MethodDelete {
p.Runner.DeleteDevice(w, r)
@@ -55,6 +169,24 @@ func (p *Panel) handleDevices(w http.ResponseWriter, r *http.Request) {
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) {
if !p.valid(r) {
http.Redirect(w, r, "/panel/login", http.StatusFound)
+726 -35
View File
@@ -1,40 +1,731 @@
*{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[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)}
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-logo{width:36px;height:36px;border-radius:8px;object-fit:cover;flex:none;box-shadow:0 2px 8px rgba(0,0,0,.15)}
header strong{font-size:18px}header span{margin-left:12px;color:var(--text-muted);font-size:12px}.header-actions{display:flex;align-items:center;gap:8px;flex-shrink:0}main{max-width:1400px;margin:auto;padding:22px}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.wide{grid-column:1/-1}.card{min-width:0;background:var(--bg-card);border:1px solid var(--border);border-radius:14px;padding:18px;box-shadow:var(--shadow)}.cardhead{display:flex;align-items:center;justify-content:space-between;gap:12px;min-width:0}.cardhead>h2{min-width:0}h2{margin:0 0 14px;font-size:16px}button,select,input,textarea{border:1px solid var(--border-strong);border-radius:9px;background:var(--bg-sub);color:var(--text-main);padding:9px 12px;font:inherit;max-width:100%}button{cursor:pointer}button:hover{filter:brightness(1.05)}button:focus-visible,select:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--border-strong);outline-offset:2px}textarea{width:100%;height:110px;resize:vertical;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;margin:8px 0}pre{white-space:pre-wrap;overflow:auto;background:var(--bg-sub);border:1px solid var(--border);border-radius:9px;padding:12px;color:var(--pre-text)}.devices{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px}.device{min-width:0;padding:14px;border:1px solid var(--border);border-radius:10px;background:var(--bg-sub)}.device b{display:block;min-width:0;overflow-wrap:anywhere;word-break:break-all}.dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--dot-online);vertical-align:middle;flex:none;margin-right:7px}.offline .dot{background:var(--dot-offline)}.muted{color:var(--text-muted)}.status{margin-top:3px;font-size:12px;color:var(--text-status);overflow-wrap:anywhere;word-break:break-word}.actions{display:flex;flex-wrap:wrap;gap:8px}.actions button{flex:1 1 150px}#device{min-width:180px}.tablewrap{width:100%;max-width:100%;overflow-x:auto;overscroll-behavior-x:contain}table{width:100%;min-width:760px;border-collapse:collapse}th,td{text-align:left;padding:9px;border-bottom:1px solid var(--border);font-size:12px;white-space:nowrap}th{color:var(--thead)}.login{display:grid;place-items:center;min-height:100vh;padding:20px}.login form{width:min(380px,90vw);background:var(--bg-card);border:1px solid var(--border);border-radius:16px;padding:28px;box-shadow:var(--shadow)}.login input,.login button{width:100%;margin-top:10px}.login h1{margin:0}.login p,#error{color:var(--text-muted)}
@media(max-width:800px){.grid{grid-template-columns:1fr}.wide{grid-column:auto}main{padding:12px}header{padding:0 14px}.header-actions{gap:6px}.card{padding:15px}.cardhead{flex-wrap:wrap}.cardhead>#device{width:100%;min-width:0}.actions button{flex:1 1 140px}}
@media(max-width:680px){header{align-items:flex-start;padding-top:12px;padding-bottom:12px}header span{display:none}.brand-wrap{padding-top:2px}.brand-logo{width:32px;height:32px}.header-actions{flex-direction:column;align-items:stretch;width:112px}.header-actions button{width:100%;padding:8px 9px}.devices{grid-template-columns:1fr}.cardhead{flex-direction:column;align-items:stretch;gap:8px}.cardhead h2{margin-bottom:0}.cardhead button,#device{width:100%;min-width:0}.actions button{flex:1 1 calc(50% - 4px)}}
@media(max-width:450px){main{padding:9px}.card{padding:13px;border-radius:12px}.actions{display:grid;grid-template-columns:1fr 1fr}.actions button{width:100%;min-width:0}.login form{padding:22px}.header-actions{width:104px}}
@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important}}
/**
* Apple Design System - VPS Commander Console (app.css)
* Grounded in Apple HIG (macOS / iPadOS) & Liquid Glass Design Specs
*/
/* 主题切换极简矢量图标按钮 */
.btn-icon{display:inline-flex;align-items:center;justify-content:center;width:38px;height:38px;padding:0;border-radius:9px;background:var(--bg-sub);border:1px solid var(--border-strong);color:var(--text-main);cursor:pointer;transition:background .2s,border-color .2s}
.btn-icon:hover{filter:brightness(1.1)}
.theme-svg{display:none;width:18px;height:18px}
:root[data-theme="dark"] .svg-sun{display:block;color:#facc15}
:root[data-theme="light"] .svg-moon{display:block;color:#475569}
:root {
color-scheme: dark;
/* macOS Dark Semantic Colors */
--bg-body: #000000;
--bg-card: #16181d;
--bg-sub: #1f232b;
--bg-input: #121418;
--border: rgba(255, 255, 255, 0.08);
--border-strong: rgba(255, 255, 255, 0.14);
--border-subtle: rgba(255, 255, 255, 0.04);
--text-main: #f5f5f7;
--text-muted: #86868b;
--text-status: #a1a1a6;
--pre-text: #e5e5ea;
--thead: #86868b;
/* 设备卡片与画像升级 (方案 1: 经典主副标题分行) */
.devices{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:12px}
.device-card{min-width:0;padding:16px;border:1px solid var(--border);border-radius:12px;background:var(--bg-sub);display:flex;flex-direction:column;gap:12px}
--accent: #0a84ff;
--accent-subtle: rgba(10, 132, 255, 0.15);
--accent-hover: #0071e3;
.v1-head{display:flex;flex-direction:column;gap:4px;min-width:0}
.v1-row1{display:flex;align-items:center;justify-content:space-between;gap:8px;min-width:0}
.v1-title{display:flex;align-items:center;gap:8px;min-width:0;flex:1}
.v1-name{font-size:16px;font-weight:700;color:var(--text-main);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block}
.v1-row2{font-size:12px;color:var(--text-muted);padding-left:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
--dot-online: #30d158;
--dot-offline: #ff453a;
--dot-warn: #ffd60a;
.btn-revoke{padding:2px 8px;font-size:11px;border-radius:5px;background:transparent;border:1px solid var(--border-strong);color:var(--dot-offline);cursor:pointer;flex-shrink:0}
.btn-revoke:hover{background:rgba(239,68,68,.15);border-color:var(--dot-offline)}
--shadow: 0 4px 20px rgba(0, 0, 0, 0.35);
--shadow-hover: 0 8px 30px rgba(0, 0, 0, 0.5);
/* 资源画像 2列紧凑栅格 */
.profile-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:6px 12px;padding:10px 12px;background:var(--bg-card);border:1px solid var(--border);border-radius:8px;font-size:12px}
.p-item{display:flex;justify-content:space-between;align-items:center;gap:6px;min-height:20px}
.p-label{color:var(--text-muted);font-weight:500;font-size:11px}
.p-val{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;font-weight:600;font-size:12px;color:var(--text-main);white-space:nowrap}
.badge-docker-text{padding:1px 6px;border-radius:4px;font-size:11px;font-weight:700}
.badge-docker-text.yes{background:rgba(34,197,94,.15);color:var(--dot-online);border:1px solid rgba(34,197,94,.3)}
.badge-docker-text.no{background:rgba(148,163,184,.15);color:var(--text-muted);border:1px solid var(--border)}
--font-system: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Helvetica Neue", Helvetica, Arial, sans-serif;
--font-mono: "SF Mono", ui-monospace, Menlo, Monaco, Consolas, monospace;
--card: var(--bg-card);
--line: var(--border);
--radius-lg: 16px;
--radius-md: 10px;
--radius-sm: 6px;
--ease-apple: cubic-bezier(0.16, 1, 0.3, 1);
}
:root[data-theme="light"] {
color-scheme: light;
/* macOS Light Semantic Colors */
--bg-body: #f5f5f7;
--bg-card: #ffffff;
--bg-sub: #f0f0f4;
--bg-input: #ffffff;
--border: rgba(0, 0, 0, 0.08);
--border-strong: rgba(0, 0, 0, 0.14);
--border-subtle: rgba(0, 0, 0, 0.04);
--text-main: #1d1d1f;
--text-muted: #86868b;
--text-status: #6e6e73;
--pre-text: #1d1d1f;
--thead: #86868b;
--accent: #0071e3;
--accent-subtle: rgba(0, 113, 227, 0.12);
--accent-hover: #0077ed;
--dot-online: #34c759;
--dot-offline: #ff3b30;
--dot-warn: #ff9500;
--shadow: 0 2px 14px rgba(0, 0, 0, 0.06);
--shadow-hover: 0 6px 20px rgba(0, 0, 0, 0.12);
--card: var(--bg-card);
--line: var(--border);
}
* {
box-sizing: border-box;
}
html, body {
min-height: 100%;
}
body {
margin: 0;
background: var(--bg-body);
color: var(--text-main);
font: 13px/1.5 var(--font-system);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* ==========================================================================
macOS Style Header (Liquid Glass Floating Topbar)
========================================================================== */
header {
min-height: 56px;
padding: 0 24px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
border-bottom: 1px solid var(--border);
background: rgba(22, 24, 29, 0.75);
backdrop-filter: blur(24px) saturate(190%);
-webkit-backdrop-filter: blur(24px) saturate(190%);
position: sticky;
top: 0;
z-index: 100;
transition: all 0.2s var(--ease-apple);
}
:root[data-theme="light"] header {
background: rgba(255, 255, 255, 0.8);
}
.brand-wrap {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-logo {
width: 32px;
height: 32px;
border-radius: 8px;
object-fit: cover;
flex: none;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
header strong {
font-size: 16px;
font-weight: 600;
letter-spacing: -0.015em;
color: var(--text-main);
}
header span {
margin-left: 10px;
color: var(--text-muted);
font-size: 12px;
font-weight: 400;
}
.header-actions {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
/* ==========================================================================
Main Grid Layout & Content Cards
========================================================================== */
main {
max-width: 1400px;
margin: auto;
padding: 24px;
}
.grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 20px;
}
.wide {
grid-column: 1 / -1;
}
.card {
min-width: 0;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 20px 22px;
box-shadow: var(--shadow);
transition: border-color 0.2s var(--ease-apple), box-shadow 0.2s var(--ease-apple);
}
.cardhead {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
min-width: 0;
margin-bottom: 16px;
}
.cardhead > h2 {
min-width: 0;
margin: 0;
}
h2 {
margin: 0 0 16px;
font-size: 15px;
font-weight: 600;
letter-spacing: -0.01em;
color: var(--text-main);
}
/* ==========================================================================
Controls: Buttons, Inputs, Selects
========================================================================== */
button, select, input, textarea {
border: 1px solid var(--border-strong);
border-radius: 8px;
background: var(--bg-sub);
color: var(--text-main);
padding: 7px 12px;
font-family: var(--font-system);
font-size: 13px;
max-width: 100%;
transition: all 0.15s ease-out;
}
button {
display: inline-flex;
align-items: center;
justify-content: center;
cursor: pointer;
font-weight: 500;
user-select: none;
}
button:hover {
background: var(--bg-card);
border-color: var(--accent);
}
button:active {
transform: scale(0.98);
}
button:focus-visible, select:focus-visible, input:focus-visible, textarea:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 1px;
}
/* Primary Action Buttons */
#run, #mcpSave, #webhookSave, #saveGlobalSecurity {
background: var(--accent);
color: #ffffff;
border-color: transparent;
font-weight: 600;
}
#run:hover, #mcpSave:hover, #webhookSave:hover, #saveGlobalSecurity:hover {
background: var(--accent-hover);
border-color: transparent;
}
/* Secondary & Action Buttons */
#logout {
background: transparent;
border-color: var(--border);
color: var(--text-muted);
}
#logout:hover {
color: var(--dot-offline);
border-color: rgba(255, 69, 58, 0.4);
background: rgba(255, 69, 58, 0.1);
}
/* Icon Button (Theme Toggle) */
.btn-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
padding: 0;
border-radius: 8px;
background: var(--bg-sub);
border: 1px solid var(--border);
color: var(--text-main);
cursor: pointer;
}
.btn-icon:hover {
border-color: var(--border-strong);
background: var(--bg-card);
}
.theme-svg {
display: none;
width: 16px;
height: 16px;
}
:root[data-theme="dark"] .svg-sun {
display: block;
color: #ffd60a;
}
:root[data-theme="light"] .svg-moon {
display: block;
color: #1d1d1f;
}
/* Console & Code Blocks */
textarea {
width: 100%;
height: 110px;
resize: vertical;
font-family: var(--font-mono);
font-size: 12px;
margin: 10px 0;
background: var(--bg-input);
border-radius: 8px;
}
pre {
white-space: pre-wrap;
overflow: auto;
background: var(--bg-input);
border: 1px solid var(--border);
border-radius: 8px;
padding: 14px;
color: var(--pre-text);
font-family: var(--font-mono);
font-size: 12px;
line-height: 1.5;
font-variant-numeric: tabular-nums;
}
/* ==========================================================================
Devices Grid & Cards (Content Layer)
========================================================================== */
.devices {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 14px;
}
.device-card {
min-width: 0;
padding: 16px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--bg-sub);
display: flex;
flex-direction: column;
gap: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
transition: transform 0.2s var(--ease-apple), border-color 0.2s var(--ease-apple);
}
.device-card:hover {
transform: translateY(-1.5px);
border-color: var(--border-strong);
}
.v1-head {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
.v1-row1 {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
min-width: 0;
}
.v1-title {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
flex: 1;
}
.v1-name {
font-size: 15px;
font-weight: 600;
letter-spacing: -0.01em;
color: var(--text-main);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: block;
}
.v1-row2 {
font-size: 11px;
color: var(--text-muted);
padding-left: 15px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-variant-numeric: tabular-nums;
}
.dot {
display: inline-block;
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--dot-online);
vertical-align: middle;
flex: none;
}
.offline .dot {
background: var(--dot-offline);
}
.btn-revoke {
padding: 2px 8px;
font-size: 11px;
border-radius: 5px;
background: transparent;
border: 1px solid var(--border);
color: var(--dot-offline);
cursor: pointer;
flex-shrink: 0;
}
.btn-revoke:hover {
background: rgba(255, 69, 58, 0.14);
border-color: var(--dot-offline);
}
/* Node Profile Grid (Compact 2-Column Metrics) */
.profile-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 6px 12px;
padding: 10px 12px;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 8px;
font-size: 12px;
}
.p-item {
display: flex;
justify-content: space-between;
align-items: center;
gap: 6px;
min-height: 20px;
}
.p-label {
color: var(--text-muted);
font-weight: 500;
font-size: 11px;
}
.p-val {
font-family: var(--font-mono);
font-weight: 600;
font-size: 12px;
color: var(--text-main);
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.badge-docker-text {
padding: 1px 6px;
border-radius: 4px;
font-size: 10px;
font-weight: 600;
}
.badge-docker-text.yes {
background: rgba(48, 209, 88, 0.15);
color: var(--dot-online);
border: 1px solid rgba(48, 209, 88, 0.3);
}
.badge-docker-text.no {
background: rgba(142, 142, 147, 0.15);
color: var(--text-muted);
border: 1px solid var(--border);
}
.device-card.offline {
opacity: 0.65;
filter: saturate(0.5);
}
/* ==========================================================================
MCP Toolbar, Grid & Forms
========================================================================== */
.mcp-toolbar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
.mcp-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 14px;
}
.mcp-item {
border: 1px solid var(--border);
border-radius: 10px;
padding: 16px;
background: var(--bg-sub);
}
.mcp-item h3 {
margin: 0 0 6px;
font-size: 14px;
font-weight: 600;
color: var(--text-main);
}
.mcp-meta {
font-size: 12px;
color: var(--text-muted);
line-height: 1.6;
}
.mcp-actions {
display: flex;
gap: 8px;
margin-top: 14px;
}
.mcp-form {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.mcp-form .full {
grid-column: 1 / -1;
}
.mcp-form label {
display: flex;
flex-direction: column;
gap: 6px;
font-size: 12px;
font-weight: 500;
color: var(--text-muted);
}
.mcp-form input, .mcp-form select, .mcp-form textarea {
width: 100%;
}
.mcp-form textarea {
min-height: 72px;
font-family: var(--font-mono);
}
.mcp-nodes {
display: flex;
flex-wrap: wrap;
gap: 8px;
padding-top: 4px;
}
.mcp-nodes label {
flex-direction: row;
align-items: center;
gap: 6px;
cursor: pointer;
}
.mcp-status {
font-size: 12px;
margin-top: 8px;
min-height: 18px;
}
.mcp-test-result {
margin-top: 12px;
padding: 12px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--bg-input);
font-size: 12px;
}
.mcp-test-result.ok {
border-color: rgba(48, 209, 88, 0.4);
}
.mcp-test-result.fail {
border-color: rgba(255, 69, 58, 0.4);
}
/* ==========================================================================
Data Tables (macOS Table Standard)
========================================================================== */
.tablewrap {
width: 100%;
max-width: 100%;
overflow-x: auto;
border-radius: 8px;
border: 1px solid var(--border);
}
table {
width: 100%;
min-width: 760px;
border-collapse: collapse;
}
th, td {
text-align: left;
padding: 10px 14px;
border-bottom: 1px solid var(--border);
font-size: 12px;
white-space: nowrap;
}
th {
background: var(--bg-sub);
color: var(--thead);
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.03em;
font-size: 11px;
}
td {
color: var(--text-main);
}
tr:last-child td {
border-bottom: none;
}
tr:hover td {
background: rgba(255, 255, 255, 0.02);
}
/* Security Policies */
.security-grid {
display: flex;
gap: 14px;
align-items: flex-end;
flex-wrap: wrap;
margin-bottom: 16px;
}
.security-grid label {
display: flex;
flex-direction: column;
gap: 6px;
font-size: 12px;
font-weight: 500;
color: var(--text-muted);
}
.security-grid button {
height: 32px;
}
/* Login Page (Apple Centered Card) */
.login {
display: grid;
place-items: center;
min-height: 100vh;
padding: 20px;
}
.login form {
width: min(360px, 90vw);
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 32px 28px;
box-shadow: var(--shadow-hover);
}
.login input, .login button {
width: 100%;
margin-top: 14px;
height: 38px;
}
.login h1 {
margin: 0 0 8px;
font-size: 20px;
font-weight: 700;
letter-spacing: -0.015em;
text-align: center;
}
.login p, #error {
color: var(--text-muted);
text-align: center;
font-size: 13px;
margin-bottom: 12px;
}
#error {
color: var(--dot-offline);
font-weight: 500;
}
/* Responsive */
@media (max-width: 800px) {
.grid {
grid-template-columns: 1fr;
}
.wide {
grid-column: auto;
}
main {
padding: 16px 12px;
}
header {
padding: 0 16px;
}
}
+315 -39
View File
@@ -11,7 +11,8 @@ const $=s=>document.querySelector(s);
})();
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.ok)throw Error(await r.text());
return r.json()
@@ -31,48 +32,76 @@ async function removeDevice(name){
}
}
async function loadDevices(){
let all=await api("/devices");
let ds=all.filter(d=>!d.is_local);
$("#devices").innerHTML=ds.map(d=>{
const p = d.profile || {};
const role = p.role || "APPLICATION";
const isOnline = d.status === "online";
const statusText = isOnline ? "在线" : "离线";
const archOs = (d.arch || d.os) ? `${esc(d.arch||"")}/${esc(d.os||"")} · ` : "";
const cpuStr = p.cpu_cores ? `${p.cpu_cores}C · ${p.cpu_usage_percent ?? 0}%` : '-';
const loadStr = p.load_1m !== undefined ? p.load_1m.toFixed(2) : '-';
const memStr = p.mem_available ? `${p.mem_available} (${p.mem_percent}%)` : (p.mem_percent !== undefined ? `${p.mem_percent}%` : '-');
const diskStr = p.disk_free ? `${p.disk_free} (${p.disk_percent}%)` : (p.disk_percent !== undefined ? `${p.disk_percent}%` : '-');
const psiStr = p.io_psi !== undefined ? p.io_psi.toFixed(2) : '-';
const dockerVal = p.docker ? 'YES' : 'NO';
const dockerClass = p.docker ? 'yes' : 'no';
function renderSingleCard(d) {
const p = d.profile || {};
const isOnline = d.status === "online";
const statusText = isOnline ? "在线" : "离线";
const lastText = d.last_heartbeat ? new Date(d.last_heartbeat*1000).toLocaleString() : "";
const archOs = (d.arch || d.os) ? `${esc(d.arch||"")}/${esc(d.os||"")} · ` : "";
const cpuStr = p.cpu_cores ? `${p.cpu_cores}C · ${p.cpu_usage_percent ?? 0}%` : '-';
const loadStr = p.load_1m !== undefined ? p.load_1m.toFixed(2) : '-';
const memStr = p.mem_available ? `${p.mem_available} (${p.mem_percent}%)` : (p.mem_percent !== undefined ? `${p.mem_percent}%` : '-');
const diskStr = p.disk_free ? `${p.disk_free} (${p.disk_percent}%)` : (p.disk_percent !== undefined ? `${p.disk_percent}%` : '-');
const psiStr = p.io_psi !== undefined ? p.io_psi.toFixed(2) : '-';
const dockerVal = p.docker ? 'YES' : 'NO';
const dockerClass = p.docker ? 'yes' : 'no';
return `
<div class="device-card ${isOnline ? "online" : "offline"}">
<div class="v1-head">
<div class="v1-row1">
<div class="v1-title">
<span class="dot"></span>
<strong class="v1-name" title="${esc(d.name)}">${esc(d.name)}</strong>
</div>
<button class="btn-revoke" onclick="removeDevice('${esc(d.name)}')">注销</button>
</div>
<div class="v1-row2">${archOs}${statusText}</div>
</div>
<div class="profile-grid">
<div class="p-item"><span class="p-label">CPU</span><span class="p-val">${cpuStr}</span></div>
<div class="p-item"><span class="p-label">LOAD</span><span class="p-val">${loadStr}</span></div>
<div class="p-item"><span class="p-label">MEM</span><span class="p-val">${memStr}</span></div>
<div class="p-item"><span class="p-label">DISK</span><span class="p-val">${diskStr}</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>
return `
<div class="v1-head">
<div class="v1-row1">
<div class="v1-title">
<span class="dot"></span>
<strong class="v1-name" title="${esc(d.name)}">${esc(d.name)}</strong>
</div>
<button class="btn-revoke" onclick="removeDevice('${esc(d.name)}')">注销</button>
</div>
`;
}).join("");
<div class="v1-row2">${archOs}${statusText}${isOnline ? "" : (lastText ? " · 最后活跃: "+lastText : "")}</div>
</div>
<div class="profile-grid">
<div class="p-item"><span class="p-label">CPU</span><span class="p-val">${cpuStr}</span></div>
<div class="p-item"><span class="p-label">LOAD</span><span class="p-val">${loadStr}</span></div>
<div class="p-item"><span class="p-label">MEM</span><span class="p-val">${memStr}</span></div>
<div class="p-item"><span class="p-label">DISK</span><span class="p-val">${diskStr}</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>
`;
}
$("#device").innerHTML=ds.map(d=>'<option>'+esc(d.name)+'</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(){
@@ -108,3 +137,250 @@ $("#logout").onclick=async()=>{
location.href="/panel/login"
};
loadDevices().then(loadAudits).catch(console.error);
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(){
const services=await api("/mcp/services");
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("");
$("#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(){
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){
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)}}
$("#mcpNew").onclick=resetMCPForm; $("#mcpCancel").onclick=()=>$("#mcpEditor").hidden=true;
$("#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":""};
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);
+38 -1
View File
@@ -1 +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="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>
<!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="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>
+615
View File
@@ -0,0 +1,615 @@
/**
* Apple Design System - VPS Probe
* Grounded in Apple HIG (macOS / iOS) & Liquid Glass Design Specs
*/
:root {
/* Dynamic System Colors - Dark (Default) */
--system-bg: #000000;
--secondary-system-bg: #16181d;
--tertiary-system-bg: #21252d;
/* Materials & Overlays */
--liquid-glass-bg: rgba(22, 24, 29, 0.72);
--liquid-glass-border: rgba(255, 255, 255, 0.09);
--hairline-border: rgba(255, 255, 255, 0.08);
--hairline-border-hover: rgba(255, 255, 255, 0.16);
--hairline-highlight: rgba(255, 255, 255, 0.04);
/* Apple Semantic Labels */
--label-primary: #f5f5f7;
--label-secondary: #98989d;
--label-tertiary: #636366;
--label-quaternary: #48484a;
/* Apple System Accents & Status */
--accent: #0a84ff;
--accent-subtle: rgba(10, 132, 255, 0.15);
--system-green: #30d158;
--system-green-subtle: rgba(48, 209, 88, 0.14);
--system-yellow: #ffd60a;
--system-yellow-subtle: rgba(255, 214, 10, 0.14);
--system-red: #ff453a;
--system-red-subtle: rgba(255, 69, 58, 0.14);
--system-purple: #bf5af2;
/* Typography Stacks */
--font-system: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Helvetica Neue", Helvetica, Arial, sans-serif;
--font-mono: "SF Mono", ui-monospace, Menlo, Monaco, Consolas, monospace;
/* Radii & Shadows */
--radius-lg: 16px;
--radius-md: 10px;
--radius-sm: 6px;
--shadow-subtle: 0 4px 20px rgba(0, 0, 0, 0.35);
--shadow-hover: 0 8px 30px rgba(0, 0, 0, 0.5);
/* Animation */
--ease-apple: cubic-bezier(0.16, 1, 0.3, 1);
}
/* Light Appearance */
@media (prefers-color-scheme: light) {
:root {
--system-bg: #f5f5f7;
--secondary-system-bg: #ffffff;
--tertiary-system-bg: #e5e5ea;
--liquid-glass-bg: rgba(255, 255, 255, 0.78);
--liquid-glass-border: rgba(0, 0, 0, 0.08);
--hairline-border: rgba(0, 0, 0, 0.07);
--hairline-border-hover: rgba(0, 0, 0, 0.14);
--hairline-highlight: rgba(0, 0, 0, 0.02);
--label-primary: #1d1d1f;
--label-secondary: #86868b;
--label-tertiary: #a1a1a6;
--label-quaternary: #d1d1d6;
--accent: #0071e3;
--accent-subtle: rgba(0, 113, 227, 0.1);
--system-green: #34c759;
--system-green-subtle: rgba(52, 199, 89, 0.12);
--system-yellow: #ff9500;
--system-yellow-subtle: rgba(255, 149, 0, 0.12);
--system-red: #ff3b30;
--system-red-subtle: rgba(255, 59, 48, 0.12);
--shadow-subtle: 0 2px 14px rgba(0, 0, 0, 0.06);
--shadow-hover: 0 6px 20px rgba(0, 0, 0, 0.12);
}
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background-color: var(--system-bg);
color: var(--label-primary);
font-family: var(--font-system);
font-size: 13px;
line-height: 1.45;
min-height: 100vh;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.layout {
max-width: 1400px;
margin: 0 auto;
padding: 0 24px 48px;
display: flex;
flex-direction: column;
min-height: 100vh;
}
/* ==========================================================================
Header & Liquid Glass Navbar
========================================================================== */
.navbar {
position: sticky;
top: 0;
z-index: 100;
margin: 0 -24px 28px;
padding: 14px 24px;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 16px;
background: var(--liquid-glass-bg);
backdrop-filter: blur(24px) saturate(190%);
-webkit-backdrop-filter: blur(24px) saturate(190%);
border-bottom: 1px solid var(--liquid-glass-border);
transition: all 0.2s var(--ease-apple);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
}
.logo-dot {
width: 12px;
height: 12px;
background: var(--accent);
border-radius: 3px;
box-shadow: 0 0 10px var(--accent-subtle);
}
.brand-text {
display: flex;
align-items: baseline;
gap: 8px;
}
.brand-text h1 {
font-size: 17px;
font-weight: 600;
letter-spacing: -0.015em;
color: var(--label-primary);
}
.brand-text .sub {
font-size: 12px;
color: var(--label-secondary);
font-weight: 400;
}
.controls {
display: flex;
align-items: center;
gap: 12px;
}
/* Cluster Summary Pill */
.summary-badge {
display: flex;
align-items: center;
gap: 8px;
background: var(--hairline-highlight);
border: 1px solid var(--hairline-border);
padding: 5px 12px;
border-radius: 980px;
font-size: 12px;
font-weight: 500;
color: var(--label-secondary);
}
.dot-online {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--system-green);
box-shadow: 0 0 6px var(--system-green);
}
/* macOS-Style Segmented Control */
.view-switch {
display: flex;
background: var(--tertiary-system-bg);
border: 1px solid var(--hairline-border);
border-radius: 8px;
padding: 2px;
gap: 2px;
}
.view-switch .btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
height: 26px;
padding: 0 12px;
border: none;
background: transparent;
color: var(--label-secondary);
font-family: var(--font-system);
font-size: 12px;
font-weight: 500;
border-radius: 6px;
cursor: pointer;
transition: all 0.15s ease-out;
user-select: none;
}
.view-switch .btn:hover {
color: var(--label-primary);
}
.view-switch .btn.active {
background: var(--secondary-system-bg);
color: var(--label-primary);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 0.5px 1px rgba(0, 0, 0, 0.08);
}
/* ==========================================================================
Content Grid & Node Card (Content Layer)
========================================================================== */
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
gap: 18px;
}
.node-card {
background: var(--secondary-system-bg);
border: 1px solid var(--hairline-border);
border-radius: var(--radius-lg);
padding: 18px 20px;
display: flex;
flex-direction: column;
gap: 16px;
box-shadow: var(--shadow-subtle);
transition: transform 0.25s var(--ease-apple), border-color 0.25s var(--ease-apple), box-shadow 0.25s var(--ease-apple);
}
.node-card:hover {
transform: translateY(-1.5px);
border-color: var(--hairline-border-hover);
box-shadow: var(--shadow-hover);
}
.card-top {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 8px;
}
.node-title {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
.node-name-wrap {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.flag-icon {
font-size: 15px;
line-height: 1;
}
.node-name {
font-size: 15px;
font-weight: 600;
letter-spacing: -0.01em;
color: var(--label-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.local-badge {
font-size: 10px;
font-weight: 600;
padding: 2px 6px;
border-radius: 5px;
background: var(--accent-subtle);
color: var(--accent);
border: 1px solid rgba(10, 132, 255, 0.25);
flex-shrink: 0;
}
.node-meta {
font-size: 11px;
color: var(--label-secondary);
display: flex;
align-items: center;
gap: 6px;
font-variant-numeric: tabular-nums;
}
.meta-pill {
background: var(--hairline-highlight);
border: 1px solid var(--hairline-border);
padding: 1px 6px;
border-radius: 4px;
color: var(--label-secondary);
font-weight: 500;
}
/* Status Pill */
.status-badge {
font-size: 11px;
font-weight: 600;
padding: 2px 8px;
border-radius: 980px;
display: inline-flex;
align-items: center;
gap: 5px;
flex-shrink: 0;
}
.status-badge.online {
background: var(--system-green-subtle);
color: var(--system-green);
border: 1px solid rgba(48, 209, 88, 0.22);
}
.status-badge.offline {
background: var(--system-red-subtle);
color: var(--system-red);
border: 1px solid rgba(255, 69, 58, 0.22);
}
.status-badge .dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
}
/* ==========================================================================
Metrics & Progress Bars (San Francisco Metrics)
========================================================================== */
.metrics-bars {
display: flex;
flex-direction: column;
gap: 12px;
}
.metric-item {
display: flex;
flex-direction: column;
gap: 5px;
}
.metric-header {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 12px;
}
.metric-label {
color: var(--label-secondary);
font-weight: 500;
}
.metric-value {
color: var(--label-primary);
font-family: var(--font-mono);
font-size: 12px;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.progress-track {
height: 5px;
background: var(--tertiary-system-bg);
border-radius: 980px;
overflow: hidden;
position: relative;
}
.progress-fill {
height: 100%;
border-radius: 980px;
transition: width 0.4s var(--ease-apple), background 0.3s ease;
}
.progress-fill.normal {
background: var(--system-green);
}
.progress-fill.warn {
background: var(--system-yellow);
}
.progress-fill.danger {
background: var(--system-red);
}
/* Secondary Stat Widget (Inset Grouped) */
.card-stats-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
background: var(--hairline-highlight);
border-radius: var(--radius-md);
padding: 10px 12px;
border: 1px solid var(--hairline-border);
}
.stat-box {
display: flex;
flex-direction: column;
gap: 2px;
}
.stat-title {
font-size: 11px;
font-weight: 500;
color: var(--label-secondary);
}
.stat-desc {
font-size: 12px;
color: var(--label-secondary);
font-family: var(--font-mono);
font-variant-numeric: tabular-nums;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.stat-desc b {
color: var(--label-primary);
font-weight: 600;
}
.traffic-in { color: var(--accent) !important; font-weight: 600; }
.traffic-out { color: var(--system-purple) !important; font-weight: 600; }
/* ==========================================================================
Compact Table View (macOS Table Standard)
========================================================================== */
.table-wrapper {
background: var(--secondary-system-bg);
border: 1px solid var(--hairline-border);
border-radius: var(--radius-lg);
overflow-x: auto;
box-shadow: var(--shadow-subtle);
}
.probe-table {
width: 100%;
min-width: 960px;
border-collapse: collapse;
text-align: left;
}
.probe-table th {
background: var(--tertiary-system-bg);
padding: 10px 16px;
font-size: 11px;
font-weight: 600;
color: var(--label-secondary);
border-bottom: 1px solid var(--hairline-border);
text-transform: uppercase;
letter-spacing: 0.03em;
white-space: nowrap;
}
.probe-table td {
padding: 12px 16px;
border-bottom: 1px solid var(--hairline-border);
font-size: 12px;
vertical-align: middle;
color: var(--label-primary);
}
.probe-table tr:last-child td {
border-bottom: none;
}
.probe-table tr:hover td {
background: var(--hairline-highlight);
}
.col-mono {
font-family: var(--font-mono);
font-variant-numeric: tabular-nums;
}
.mini-bar-wrap {
display: flex;
align-items: center;
gap: 8px;
min-width: 110px;
}
.mini-bar {
flex: 1;
height: 5px;
background: var(--tertiary-system-bg);
border-radius: 980px;
overflow: hidden;
}
.mini-bar-fill {
height: 100%;
border-radius: 980px;
}
.table-node {
display: flex;
flex-direction: column;
}
.table-node .name {
font-size: 13px;
font-weight: 600;
color: var(--label-primary);
}
.table-node .sub {
font-size: 11px;
color: var(--label-secondary);
}
/* ==========================================================================
Footer
========================================================================== */
.footer {
margin-top: auto;
padding-top: 32px;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 12px;
color: var(--label-secondary);
border-top: 1px solid var(--hairline-border);
}
.update-time {
font-family: var(--font-mono);
font-variant-numeric: tabular-nums;
}
/* Error State */
.error-msg {
text-align: center;
padding: 40px;
color: var(--system-red);
background: var(--system-red-subtle);
border: 1px dashed rgba(255, 69, 58, 0.3);
border-radius: var(--radius-lg);
}
/* ==========================================================================
Responsive Adaptations
========================================================================== */
@media (max-width: 768px) {
.layout {
padding: 0 16px 36px;
}
.navbar {
margin: 0 -16px 20px;
padding: 12px 16px;
}
.brand-text h1 {
font-size: 16px;
}
.controls {
width: 100%;
justify-content: space-between;
}
.card-grid {
grid-template-columns: 1fr;
gap: 14px;
}
.node-card {
padding: 16px;
}
.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=20261001">
</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=20261001"></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);
})();