Compare commits

..
18 Commits
Author SHA1 Message Date
kory 5c64796892 fix: preserve agent environment in installer unit 2026-10-02 17:20:22 +08:00
kory 88bd8a9265 fix: verify agent installer startup and hub connection 2026-10-02 17:20:22 +08:00
kory ea7b47c955 fix: expand agent environment in systemd service 2026-10-02 17:20:22 +08:00
kory f084ac5bae feat: isolate release source for installers and provisioning
Release / Build & Release (push) Canceled after 0s
2026-10-02 15:25:19 +08:00
kory ea7aebd276 fix: remove remaining GitHub links from Gitea scripts 2026-10-02 15:21:03 +08:00
kory 539c1e986b fix: isolate Gitea installer from GitHub 2026-10-02 15:20:28 +08:00
kory 0b5b0323f2 fix: read installer prompts from tty
Release / Build & Release (push) Canceled after 0s
2026-10-02 15:05:31 +08:00
kory a83436c78b release: unify upgrade and release pipeline
Release / Build & Release (push) Canceled after 0s
2026-10-02 15:00:11 +08:00
kory aa257e9b8b fix: harden one-click installer downloads
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:57:26 +08:00
kory 78d3ee6527 fix: repair one-click installer
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:52:05 +08:00
kory 5551f69b17 test: stabilize local session lifecycle timing 2026-10-02 14:35:32 +08:00
kory 650dc7186e docs: document constrained diagnostic mode
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:34:30 +08:00
kory 5e6281ae99 feat: add constrained read-only diagnostics 2026-10-02 14:32:40 +08:00
kory 2a072f9cc9 fix: detach local sessions from request context
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:18:24 +08:00
kory 4e016fd3ba docs: record streamable http compatibility gap
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:14:26 +08:00
kory 343708eebe fix: repair session API and local session fallback
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:10:56 +08:00
kory 583b27fb5c fix: expose write_file and document one-click operations
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:07:11 +08:00
kory cc99022215 docs: restore established documentation format
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:01:14 +08:00
26 changed files with 2065 additions and 549 deletions
+16 -37
View File
@@ -2,8 +2,6 @@ name: Release
on: on:
push: push:
branches:
- main
tags: tags:
- 'v*' - 'v*'
@@ -20,49 +18,27 @@ jobs:
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Determine Version Tag & Generate Notes - name: Prepare Release Notes
id: versioning id: versioning
run: | run: |
PREV_TAG=$(git tag -l "v*" --sort=-v:refname | head -n1)
echo "Previous tag: $PREV_TAG"
if [[ "${{ github.ref }}" == refs/tags/v* ]]; then
TAG="${GITHUB_REF#refs/tags/}" TAG="${GITHUB_REF#refs/tags/}"
else git fetch --tags --force
if [ -z "$PREV_TAG" ]; then PREV_TAG=$(git tag -l "v*" --sort=-v:refname | grep -Fxv "$TAG" | head -n1 || true)
TAG="v1.0.0" echo "tag=$TAG" >> "$GITHUB_OUTPUT"
else {
VER_NUM="${PREV_TAG#v}" echo "### 🚀 What's Changed in ${TAG}"
IFS='.' read -r MAJOR MINOR PATCH <<< "$VER_NUM" echo
PATCH=$((PATCH + 1))
TAG="v${MAJOR}.${MINOR}.${PATCH}"
fi
echo "Auto incremented patch version to $TAG"
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag "$TAG"
git push origin "$TAG"
fi
echo "tag=$TAG" >> $GITHUB_OUTPUT
# 生成详细的 Release Changelog 正文
cat << NOTES > release_notes.md
### 🚀 What's Changed in ${TAG}
NOTES
if [ -n "$PREV_TAG" ]; then if [ -n "$PREV_TAG" ]; then
git log "${PREV_TAG}..HEAD" --pretty=format:"- %s (%h by @kyaring)" >> release_notes.md git log "${PREV_TAG}..${TAG}" --pretty=format:"- %s (%h by @kyaring)"
else else
git log -n 10 --pretty=format:"- %s (%h by @kyaring)" >> release_notes.md git log -n 10 --pretty=format:"- %s (%h by @kyaring)"
fi fi
echo
echo "" >> release_notes.md echo
echo "" >> release_notes.md
if [ -n "$PREV_TAG" ]; then if [ -n "$PREV_TAG" ]; then
echo "**Full Changelog**: https://github.com/${{ github.repository }}/compare/${PREV_TAG}...${TAG}" >> release_notes.md echo "**Full Changelog**: https://github.com/${{ github.repository }}/compare/${PREV_TAG}...${TAG}"
fi fi
} > release_notes.md
cat release_notes.md cat release_notes.md
- name: Set up Go - name: Set up Go
@@ -81,6 +57,9 @@ jobs:
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -ldflags "-s -w" -o dist/vps-commander-hub-linux-arm64 ./cmd/hub CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -ldflags "-s -w" -o dist/vps-commander-hub-linux-arm64 ./cmd/hub
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -ldflags "-s -w" -o dist/vps-commander-agent-linux-arm64 ./cmd/agent CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -ldflags "-s -w" -o dist/vps-commander-agent-linux-arm64 ./cmd/agent
# MCP stdio(与 Gitea 本地发布保持一致)
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w" -o dist/vps-commander-mcp-stdio-linux-amd64 ./cmd/mcp-stdio
# Checksums # Checksums
cd dist cd dist
sha256sum * > checksums.txt sha256sum * > checksums.txt
+202 -35
View File
@@ -1,50 +1,217 @@
<div align="center">
# VPS-Commander # VPS-Commander
> 当前文档基线:2026-10-02 **面向 AI Agent、MCP 与个人运维的高性能、轻量、多节点私有基础设施调度中枢**
自托管、多节点、AI Agent 友好的 Linux 运维控制中枢。 [![Go Version](https://img.shields.io/badge/Go-1.22+-00ADD8?style=flat&logo=go)](https://golang.org)
[![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Architecture](https://img.shields.io/badge/Arch-Linux%20AMD64%20%7C%20ARM64-orange)](#)
## 研发最初目标 </div>
- 不依赖第三方运维 Relay,建立用户自己的私有控制面;
- 从单机运维扩展到多 VPS 统一调度;
- 在主机级能力之上建立认证、授权、审计、资源限制和可回滚发布体系。
当前系统已经从早期的 OpenAPI + Cluster Secret + 4 个 MCP 工具,演进为: ---
Hub/Agent 双通道 + per-device credential + Policy Snapshot + Tool Registry + MCP/HTTP 统一安全门禁 + SQLite audit + Web Panel。
## 当前架构 ## 🌟 核心特性
AI / MCP / Web Panel → HTTPS/WSS → Reverse Proxy → Hub 127.0.0.1:9521
Hub → Local Executor,或 Hub → Agent WSS → Remote VPS。
Hub 不直接公网监听;Agent 只主动回连 Hub。
## 当前 MCP:11 个工具 - ⚡ **轻量单体部署**:纯 Go 原生编译,Hub、Agent、MCP stdio 均可独立部署。
list_devices、exec_command、read_file、read_multiple_files、create_directory、move_file、list_processes、edit_block、write_file、list_agent_mcp、call_agent_mcp。 - 🤖 **原生 AI / MCP 接入**:提供 HTTP API、MCP SSE、stdio 以及 Agent WebSocket,多种客户端可以共用同一套安全模型。
- 🌐 **Hub & Agent 双通道架构**:Hub 负责控制与授权,Agent 通过 WSS 主动回连,不要求远端开放入站管理端口。
- 🛡️ **认证与授权分离**:HTTP/MCP 使用 Bearer API Key;Agent 使用每设备独立 Credential;Tool Registry + Security Snapshot 实现 Low / Medium / High 风险门禁。
- 📋 **完整审计链**:SQLite 持久化设备、凭据哈希、策略版本、操作审计与 Webhook 配置。
- 🧩 **多节点能力聚合**:文件、Shell、进程、Session、Agent MCP 等能力由 Hub 统一调度。
- 🖥️ **内嵌 Web 管理面板**:Go embed 打包,无需 Node.js 运行时。
风险:Low=读取/观察;Medium=文件修改/目录移动/Agent MCP;High=Shell/进程控制。 ---
远程 HTTP MCP 当前为 legacy HTTP+SSE;本地客户端为 stdio。Streamable HTTP 属于后续演进方向。
## 当前 HTTP ## 🏁 研发最初目标
/api/v1/devices、/api/v1/exec、/api/v1/file/read、/api/v1/file/list、/api/v1/file/info、/api/v1/file/search、/api/v1/process/session、/api/v1/file/write、/api/v1/devices/file/edit_block、/api/v1/mcp/*、/api/v1/security/*、/api/v1/notifications/webhook*、/agent/ws、/healthz、/openapi.json、/panel/*。
## 安全 VPS-Commander 最初并不是一个简单的远程 Shell 工具,而是为 AI Agent 建立一个**用户自己控制的私有化 Linux 运维控制面**。
HTTP/MCP 使用 Bearer API Key;Agent 使用每设备独立 credential,Hub 只保存 hash。
生产 Shared Secret fallback 已关闭;URL token 不作为认证方式。
MCP、HTTP、direct Agent MCP 共用 Hub security model;未知设备必须 fail-closed。
Panel Admin Token 由服务端内部 bridge,不下发浏览器。
## 部署 ### 1.1 私有化
Hub:/opt/vps-commander/vps-commander-hub,监听 127.0.0.1:9521,数据库 /opt/vps-commander/data/commander.db。 - 运维请求通过用户自己的 Hub 和 VPS 节点完成。
Agent:/opt/vps-commander/vps-commander-agent,配置 /etc/vps-commander/agent.env,通过 WSS 回连 Hub。 - 不依赖第三方运维 Relay。
- 凭据、策略和审计数据由用户自己的基础设施控制。
发布必须:clean tree → go test ./... → go test -race ./... → clean build → vcs.modified=false → 单节点灰度 → Hub recovery → rolling Agent → MCP/security/audit 验收。 ### 1.2 Host-centric 运维
- 全局 Shell。
- 全局文件读写。
- 进程与长任务 Session。
- 远程 Agent MCP。
## 文档 ### 1.3 多节点统一调度
docs/DOCUMENTATION_BASELINE_20261002.md、docs/ARCHITECTURE.md、docs/DEV_SPEC.md、docs/MCP_INTEGRATION.md、deploy/README.md、docs/ACCEPTANCE_CRITERIA.md、docs/PROGRESS_TRACKING.md、docs/VPS_COMMANDER_V2_1_SECURITY_HARDENING_SPEC.md。 - 一个 Hub 管理多个 VPS。
- 使用节点名称选择目标。
- 节点离线后保留设备身份与持久化状态。
## 当前生产注意 ### 1.4 AI 原生接口
2026-10-02 Bug Hunt 发现生产二进制曾以 vcs.modified=true 构建,因此生产现场不能直接视为 HEAD 的可复现产物。 - HTTP API。
下一次发布必须 clean rebuild,并把 revision/modified 作为发布证据。 - MCP。
- OpenAPI 契约。
- Web 管理面板。
## v2.1 ---
P0:EffectiveRisk 完全 fail-closed;Agent credential 不进入 argv/cmdline。
P1:Principal/Operator 身份、Session owner 强隔离、principal→credential→session→device→operation 审计链。 ## 🏗️ 当前总体架构
```text
+--------------------------------------+
| AI / MCP Client / Web Panel |
+------------------+-------------------+
| HTTPS / MCP / WSS
v
+--------------------------------------+
| Reverse Proxy / TLS |
+------------------+-------------------+
| 127.0.0.1:9521
v
+-----------------------------------------------------------+
| VPS-Commander Hub |
|-----------------------------------------------------------|
| Auth / API / MCP / Web Panel |
| Security Snapshot / Tool Registry / Audit |
| Cluster Router / Session / Rate Limiter |
+----------------------+-------------------+---------------+
| |
Local Executor Agent WSS
| |
v v
Hub 本机 Remote VPS
|
Host Executor
File / Shell / Process
```
---
## 🔐 当前安全模型
### 1. Client Authentication
`Authorization: Bearer <API_KEY>` 是 HTTP / MCP 的主要客户端认证方式。
### 2. Agent Authentication
每个 Agent 使用独立的 `VPS_COMMANDER_AGENT_TOKEN`。
Hub SQLite 只保存 Credential Hash,不保存明文 Token。
### 3. Authorization
Tool Registry 首先确定操作风险:
| 风险 | 典型能力 |
| :--- | :--- |
| Low | 读取、搜索、设备/进程观察 |
| Medium | 文件修改、目录创建/移动、Agent MCP |
| High | Shell、进程启动、交互、终止 |
未知设备、未知身份或策略无法解析时不得获得 High 权限。
### 4. Shared Secret
生产环境已经关闭 Cluster Secret / Shared Secret fallback。
---
## 🤖 当前 MCP 能力
目前共 **12 个 MCP Tools**:
| Tool | Risk | 功能 |
| :--- | :--- | :--- |
| `list_devices` | Low | 节点列表与状态 |
| `exec_command` | High | Shell 执行 |
| `read_file` | Low | 分页读取文件 |
| `read_multiple_files` | Low | 批量读取文件 |
| `create_directory` | Medium | 创建目录 |
| `move_file` | Medium | 移动/重命名 |
| `list_processes` | Low | 进程观察 |
| `edit_block` | Medium | 原子文本修改 |
| `write_file` | Medium | 创建/覆写文件 |
| `list_agent_mcp` | Low | 查看 Agent MCP |
| `call_agent_mcp` | Medium | 调用 Agent MCP |
远程 MCP 当前使用 **legacy HTTP + SSE**;本地客户端使用 stdio。
Streamable HTTP 作为下一阶段 transport 演进方向。
---
## 📊 HTTP / Web 能力
| 接口 | 方法 | 功能 |
| :--- | :--- | :--- |
| `/api/v1/devices` | GET | 设备状态与资源画像 |
| `/api/v1/exec` | POST | 远程 Shell |
| `/api/v1/file/read` | POST | 文件读取 |
| `/api/v1/file/list` | POST | 目录列表 |
| `/api/v1/file/info` | POST | 文件信息 |
| `/api/v1/file/search` | POST | 文件搜索 |
| `/api/v1/file/write` | POST | 文件写入 |
| `/api/v1/devices/file/edit_block` | POST | 安全块编辑 |
| `/api/v1/process/session` | POST | Session 操作 |
| `/api/v1/mcp/*` | GET/POST/DELETE | MCP 服务管理与调用 |
| `/api/v1/security/*` | GET/POST | 安全策略 |
| `/api/v1/notifications/webhook*` | GET/POST/DELETE | Webhook |
| `/agent/ws` | WebSocket | Agent 长连接 |
| `/panel/*` | GET/POST | Web 管理面板 |
---
## 🚀 生产部署
Hub:
```text
/opt/vps-commander/vps-commander-hub
/etc/vps-commander/hub.env
/opt/vps-commander/data/commander.db
127.0.0.1:9521
```
Agent:
```text
/opt/vps-commander/vps-commander-agent
/etc/vps-commander/agent.env
wss://vpstool.kory.kdns.fr/agent/ws
```
Agent 只主动连接 Hub,不需要公网入站端口。
生产发布顺序:
`backup → clean build → 单节点灰度 → Hub restart recovery → rolling Agent → MCP/security/audit 验收`。
---
## 🚀 一键安装与升级
### 一键安装
```bash
curl -fsSL https://gitea.king.nyc.mn/openclaw/vps-commander/raw/branch/main/deploy/install.sh | sudo bash
```
安装脚本自动识别 `amd64/arm64` 并进入 Hub / Agent 安装流程。
### 一键升级 Agent
```bash
curl -fsSL https://gitea.king.nyc.mn/openclaw/vps-commander/raw/branch/main/deploy/upgrade-agent.sh | sudo bash
```
升级脚本下载目标 Release、校验文件大小、备份旧版本并在启动失败时自动回滚。
生产环境的 Agent 凭据以独立设备凭据为准;不要将 Cluster Secret 作为长期生产凭据重新启用。
---
## 📄 文档索引
- [文档基线与全局索引](docs/DOCUMENTATION_BASELINE_20261002.md)
- [系统架构与开发设计规范](docs/ARCHITECTURE.md)
- [研发与协议规范](docs/DEV_SPEC.md)
- [MCP 接入指南](docs/MCP_INTEGRATION.md)
- [生产部署与运维指南](deploy/README.md)
- [发布验收标准](docs/ACCEPTANCE_CRITERIA.md)
- [项目进度与路线图](docs/PROGRESS_TRACKING.md)
- [v2.1 安全加固规范](docs/VPS_COMMANDER_V2_1_SECURITY_HARDENING_SPEC.md)
---
## 📜 开源协议
本项目基于 [MIT](LICENSE) 协议开源。
+11
View File
@@ -152,6 +152,17 @@ func run(hub, name, token string, insecure bool) error {
func handle(writeJSON func(cluster.Message) error, exec executor.Local, mcpRuntime *cluster.MCPRuntime, sessions *executor.SessionManager, msg cluster.Message) error { func handle(writeJSON func(cluster.Message) error, exec executor.Local, mcpRuntime *cluster.MCPRuntime, sessions *executor.SessionManager, msg cluster.Message) error {
switch msg.Action { switch msg.Action {
case "diagnostic_command":
var p executor.DiagnosticRequest
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
v, err := executor.Diagnostic(context.Background(), p)
if err != nil {
return sendError(writeJSON, msg.ID, err)
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: v})
case "mcp_list": case "mcp_list":
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: mcpRuntime.List()}) return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: mcpRuntime.List()})
case "mcp_test": case "mcp_test":
+10
View File
@@ -38,6 +38,7 @@ func main() {
clusterSecret := os.Getenv("VPS_COMMANDER_CLUSTER_SECRET") clusterSecret := os.Getenv("VPS_COMMANDER_CLUSTER_SECRET")
webPassword := os.Getenv("VPS_COMMANDER_WEB_PASSWORD") webPassword := os.Getenv("VPS_COMMANDER_WEB_PASSWORD")
adminToken := os.Getenv("VPS_COMMANDER_ADMIN_TOKEN") adminToken := os.Getenv("VPS_COMMANDER_ADMIN_TOKEN")
installCommand := os.Getenv("VPS_COMMANDER_INSTALL_COMMAND")
if adminToken == "" { if adminToken == "" {
adminToken = webPassword adminToken = webPassword
} }
@@ -68,8 +69,10 @@ func main() {
LocalName: local, LocalName: local,
Notify: notificationManager, Notify: notificationManager,
AdminToken: adminToken, AdminToken: adminToken,
InstallCommand: installCommand,
ExecLimiter: make(chan struct{}, 32), ExecLimiter: make(chan struct{}, 32),
SearchLimiter: make(chan struct{}, 8), SearchLimiter: make(chan struct{}, 8),
LocalSessions: executor.NewSessionManager(0),
} }
if err := s.LoadSecurityPolicySnapshot(); err != nil { if err := s.LoadSecurityPolicySnapshot(); err != nil {
log.Fatalf("load security policy snapshot: %v", err) log.Fatalf("load security policy snapshot: %v", err)
@@ -121,6 +124,13 @@ func main() {
IdleTimeout: 90 * time.Second, IdleTimeout: 90 * time.Second,
} }
log.Printf("vps-commander-hub listening on %s as %s", *addr, local) log.Printf("vps-commander-hub listening on %s as %s", *addr, local)
go func() {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for range ticker.C {
s.LocalSessions.Cleanup()
}
}()
go func() { go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal(err) log.Fatal(err)
+226 -38
View File
@@ -1,52 +1,240 @@
# VPS-Commander 生产部署与运维 # VPS-Commander 部署与运维指南
> 基线:2026-10-02 本文档介绍 VPS-Commander 当前生产环境部署架构、凭据规范、Agent 接入、升级与回滚流程。
## 1. 拓扑 ---
Internet → TLS Reverse Proxy → vpstool.kory.kdns.fr → 127.0.0.1:9521 → Hub。
Hub → Local Executor 或 Agent WSS。
Hub 不直接公网监听;Agent 不需要公网入站管理端口。
## 2. Hub ## 一、系统架构与端口规划
binary:/opt/vps-commander/vps-commander-hub
env:/etc/vps-commander/hub.env
db:/opt/vps-commander/data/commander.db
systemd:vps-commander-hub.service
listen:127.0.0.1:9521
## 3. Agent - **Hub 服务端**:监听 `127.0.0.1:9521`,不直接暴露公网。
binary:/opt/vps-commander/vps-commander-agent - **反向代理**:公网 HTTPS/WSS 入口为 `https://vpstool.kory.kdns.fr`。
env:/etc/vps-commander/agent.env - **Agent 客户端**:通过 `wss://vpstool.kory.kdns.fr/agent/ws` 主动回连 Hub。
必须包含 VPS_COMMANDER_HUB_WS_URL、VPS_COMMANDER_AGENT_NAME、VPS_COMMANDER_AGENT_TOKEN。
env 文件必须 0600。
## 4. Credential 反代必须支持:
每个 Agent 使用独立 token;Hub SQLite 只保存 token hash。 - WebSocket Upgrade;
生产不依赖 Cluster Secret fallback。 - `/agent/ws`;
v2.0 代码仍兼容旧 -token 参数;v2.1 要求 secret 不进入 argv/cmdline。 - `/mcp/*`;
- `/api/v1/*`;
- `/panel/*`;
- `/.well-known/*`;
- `/oauth/*`。
## 5. Reverse Proxy ---
必须支持 HTTPS、WebSocket Upgrade、/agent/ws、/mcp/*、/api/v1/*、/panel/*、/.well-known/*、/oauth/*。
## 6. Clean Release ## 二、凭据安全规范(强制要求)
禁止 dirty tree build。
git status --short;go test ./...;go test -race ./...;git diff --check;make clean;make linux-amd64;make linux-arm64。
发布证据必须包含 vcs.modified=false 和 vcs.revision=<release commit>。
## 7. Rolling ### 2.1 Hub 凭据
backup → Hub install/restart → Agent recovery → single-node gray → rolling Agent → MCP smoke → audit → acceptance。 Hub 使用:
任何断联或授权异常都停止。 - `VPS_COMMANDER_API_KEY`;
- `VPS_COMMANDER_WEB_PASSWORD`。
## 8. 日常检查 生产环境不再依赖 `VPS_COMMANDER_CLUSTER_SECRET` 作为 Agent 身份 fallback。
### 2.2 Agent 凭据
每台 Agent 使用独立:
`VPS_COMMANDER_AGENT_TOKEN`。
Hub SQLite 仅保存 Credential Hash。
### 2.3 文件权限
```bash
chmod 0600 /etc/vps-commander/hub.env
chmod 0600 /etc/vps-commander/agent.env
```
### 2.4 v2.1 安全要求
当前 v2.0 代码仍兼容旧的 `-token` 参数;下一版本要求 Secret 不出现在 argv / `/proc/*/cmdline`,优先使用 systemd EnvironmentFile / LoadCredential。
---
## 三、一键安装与升级
### 3.1 一键安装
```bash
curl -fsSL https://gitea.king.nyc.mn/openclaw/vps-commander/raw/branch/main/deploy/install.sh | sudo bash
```
脚本自动识别 `amd64/arm64`,并进入 Hub / Agent 安装流程。
- Hub:自动生成 API Key 与 Web 面板密码。
- Agent:输入 Hub WSS 地址、节点名称和独立 Agent Token。
- 生产环境不再要求 Cluster Secret 作为长期凭据。
### 3.2 一键升级 Agent
```bash
curl -fsSL https://gitea.king.nyc.mn/openclaw/vps-commander/raw/branch/main/deploy/upgrade-agent.sh | sudo bash
```
升级流程:
```text
下载 Release
↓
临时文件完整性检查
↓
备份当前 Agent
↓
原子替换
↓
systemd restart
↓
健康检查
├─ 成功 → 删除备份
└─ 失败 → 自动恢复旧版本
```
### 3.3 手工安装
如果需要固定版本、离线部署或灰度验证,再使用下面的手工安装流程。
---
## 四、Hub 服务端部署步骤
### 4.1 编译
```bash
cd /root/.openclaw/workspace/vps-commander
go test ./...
go test -race ./...
git diff --check
make clean
make linux-amd64
```
发布前必须确认:
```text
vcs.modified=false
vcs.revision=<release commit>
```
### 4.2 安装
```bash
install -d -m 0750 /opt/vps-commander/data /etc/vps-commander
install -m 0755 bin/vps-commander-hub-linux-amd64 /opt/vps-commander/vps-commander-hub
```
### 4.3 配置
```bash
cat << 'ENV' > /etc/vps-commander/hub.env
VPS_COMMANDER_API_KEY=your_secure_api_key
VPS_COMMANDER_WEB_PASSWORD=your_web_password
ENV
chmod 0600 /etc/vps-commander/hub.env
```
### 4.4 Systemd
```ini
[Service]
EnvironmentFile=-/etc/vps-commander/hub.env
ExecStart=/opt/vps-commander/vps-commander-hub -addr 127.0.0.1:9521 -db /opt/vps-commander/data/commander.db
Restart=always
RestartSec=3s
```
### 4.5 启动
```bash
systemctl daemon-reload
systemctl enable --now vps-commander-hub
systemctl status vps-commander-hub
```
---
## 五、远程 Agent 节点部署步骤
### 5.1 安装二进制
```bash
install -d -m 0750 /etc/vps-commander /opt/vps-commander
install -m 0755 vps-commander-agent-linux-amd64 /opt/vps-commander/vps-commander-agent
```
### 5.2 配置
```bash
cat << 'ENV' > /etc/vps-commander/agent.env
VPS_COMMANDER_HUB_WS_URL=wss://vpstool.kory.kdns.fr/agent/ws
VPS_COMMANDER_AGENT_NAME=vps-node-01
VPS_COMMANDER_AGENT_TOKEN=<per-device-token>
ENV
chmod 0600 /etc/vps-commander/agent.env
```
### 5.3 Systemd
```ini
[Service]
EnvironmentFile=-/etc/vps-commander/agent.env
ExecStart=/opt/vps-commander/vps-commander-agent -hub ${VPS_COMMANDER_HUB_WS_URL} -name ${VPS_COMMANDER_AGENT_NAME}
Restart=always
RestartSec=3s
```
当前 v2.0 生产迁移阶段可兼容显式 token;v2.1 发布后必须改为不出现在 ExecStart 的方式。
### 5.4 启动
```bash
systemctl daemon-reload
systemctl enable --now vps-commander-agent
systemctl status vps-commander-agent
```
Agent 启动后主动连接 Hub,并在设备列表中显示为 `online`。
---
## 六、控制面板与 MCP 使用
### 6.1 管理面板
`https://vpstool.kory.kdns.fr/panel/login`
面板包含设备状态、安全策略、操作控制、审计和相关管理功能。
### 6.2 MCP
远程入口:
`https://vpstool.kory.kdns.fr/mcp/sse`
本地 stdio 使用 `vps-commander-mcp-stdio`。
当前共 12 个 MCP tools,详见 `docs/MCP_INTEGRATION.md`。
---
## 七、生产升级流程
```text
Backup
↓
Clean Build
↓
Single-node Gray Release
↓
Hub Restart Recovery
↓
Rolling Agent
↓
MCP / Security / Audit Smoke Test
↓
Full Acceptance
```
任一节点断联、权限绕过、Credential 泄露或协议不兼容,立即停止发布并回滚。
---
## 八、日常运维检查
```bash
systemctl status vps-commander-hub systemctl status vps-commander-hub
journalctl -u vps-commander-hub -n 100 journalctl -u vps-commander-hub -n 100
curl -fsS http://127.0.0.1:9521/healthz curl -fsS http://127.0.0.1:9521/healthz
/api/v1/devices、Web Panel、MCP list_devices。 ```
## 9. 当前生产审计 集群可通过 Web Panel、`/api/v1/devices` 或 MCP `list_devices` 检查。
2026-10-02 Bug Hunt 发现生产 Hub/Agent 曾 vcs.modified=true。
这说明现场二进制不能直接视为 HEAD 的可复现产物;下一次发布必须 clean rebuild 并重新部署。
## 10. 回滚 ---
保留 Hub/Agent binary、systemd env、commander.db backup、release commit。
协议不兼容时先恢复 Hub,再滚动恢复 Agent。 ## 九、当前生产审计提示
2026-10-02 审计发现生产 Hub / Agent 曾由 `vcs.modified=true` 的工作树构建。
因此生产现场二进制不能直接视为当前 HEAD 的可复现产物。
下一次正式发布必须 clean rebuild,并重新部署与验证。
+116 -41
View File
@@ -2,12 +2,15 @@
set -e set -e
# VPS-Commander 一键安装与配置脚本 (Hub / Agent) # VPS-Commander 一键安装与配置脚本 (Hub / Agent)
# Repo: https://github.com/kyaring/vps-commander # Repo: https://gitea.king.nyc.mn/openclaw/vps-commander
REPO="kyaring/vps-commander" REPO="openclaw/vps-commander"
INSTALL_DIR="/opt/vps-commander" INSTALL_DIR="/opt/vps-commander"
CONF_DIR="/etc/vps-commander" CONF_DIR="/etc/vps-commander"
GITHUB_URL="https://github.com" RELEASE_BASE_URL="https://gitea.king.nyc.mn"
API_URL="https://gitea.king.nyc.mn/api/v1"
RAW_INSTALL_URL="https://gitea.king.nyc.mn/openclaw/vps-commander/raw/branch/main/deploy/install.sh"
INSTALL_COMMAND="curl -fsSL ${RAW_INSTALL_URL} | bash"
# 颜色输出 # 颜色输出
RED='\033[0;31m' RED='\033[0;31m'
@@ -37,50 +40,90 @@ command -v curl >/dev/null 2>&1 || (apt-get update && apt-get install -y curl ||
# 获取最新版本 tag # 获取最新版本 tag
info "正在获取 VPS-Commander 最新版本信息..." info "正在获取 VPS-Commander 最新版本信息..."
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/') LATEST_TAG=$(curl -fsSL --proto '=https' --proto-redir '=https' --retry 3 --connect-timeout 15 --max-time 30 "${API_URL}/repos/${REPO}/releases/latest" | sed -n 's/^[[:space:]]*"tag_name": "\([^"]*\)".*/\1/p' | head -n1)
if [ -z "$LATEST_TAG" ]; then if [ -z "$LATEST_TAG" ]; then
warn "无法通过 GitHub API 自动获取 Tag,回退至 v1.1.5" error "无法从 Gitea 获取最新正式 Release,已停止安装;不会回退到旧版本"
LATEST_TAG="v1.1.5"
fi fi
info "检测到最新版本: ${LATEST_TAG} (${TARGET_ARCH})" info "检测到最新版本: ${LATEST_TAG} (${TARGET_ARCH})"
download_verified() {
local url="$1" dest="$2" asset_name="$3"
local tmp checksum expected actual
tmp=$(mktemp "${dest}.tmp.XXXXXX") || error "无法创建临时下载文件: ${dest}"
rm -f "$tmp"
trap 'rm -f "${tmp}"' RETURN
info "正在下载: ${url}"
if ! curl -fL --proto '=https' --proto-redir '=https' --retry 3 --connect-timeout 15 --max-time 600 -o "$tmp" "$url"; then
rm -f "$tmp"
error "下载失败: ${url}"
fi
if [ ! -s "$tmp" ]; then
rm -f "$tmp"
error "下载结果为空: ${asset_name}"
fi
if command -v sha256sum >/dev/null 2>&1; then
checksum=$(curl -fsSL --proto '=https' --proto-redir '=https' --retry 3 --connect-timeout 15 --max-time 60 "${RELEASE_BASE_URL}/${REPO}/releases/download/${LATEST_TAG}/checksums.txt") || error "无法获取 Release 校验文件"
expected=$(printf '%s\n' "$checksum" | awk -v f="$asset_name" '$2 == f {print $1; exit}')
[ -n "$expected" ] || error "Release 校验文件中缺少 ${asset_name}"
actual=$(sha256sum "$tmp" | awk '{print $1}')
[ "$actual" = "$expected" ] || error "SHA256 校验失败: ${asset_name}"
else
error "系统缺少 sha256sum,无法安全校验 Release"
fi
mv -f "$tmp" "$dest" || error "无法安装下载文件到: ${dest}"
trap - RETURN
}
mkdir -p "$INSTALL_DIR" "$INSTALL_DIR/data" "$CONF_DIR" mkdir -p "$INSTALL_DIR" "$INSTALL_DIR/data" "$CONF_DIR"
chmod 750 "$INSTALL_DIR" "$CONF_DIR" chmod 750 "$INSTALL_DIR" "$CONF_DIR"
read_tty() {
local prompt="$1"
local __var="$2"
if [ -r /dev/tty ]; then
local value
if ! IFS= read -r -p "$prompt" value < /dev/tty; then
error "无法读取交互输入,请在带 TTY 的终端中运行安装脚本;也可以通过环境变量提供配置。"
fi
printf -v "$__var" '%s' "$value"
else
error "检测不到可用 TTY。当前命令可能通过管道运行;请使用带终端的 shell 执行,例如: curl -fsSL ${RAW_INSTALL_URL} | bash"
fi
}
select_mode() { select_mode() {
echo -e "\n请选择安装模式:" echo -e "\n请选择安装模式:"
echo "1) 安装受控端 Agent (推荐:在受控 VPS 上一键连入集群)" echo "1) 安装受控端 Agent (推荐:在受控 VPS 上一键连入集群)"
echo "2) 安装中心端 Hub (管理中心)" echo "2) 安装中心端 Hub (管理中心)"
read -rp "请输入选项 [1-2] (默认 1): " MODE read_tty "请输入选项 [1-2] (默认 1): " MODE
MODE=${MODE:-1} MODE=${MODE:-1}
} }
install_agent() { install_agent() {
info "开始安装 VPS-Commander Agent (${TARGET_ARCH})..." info "开始安装 VPS-Commander Agent (${TARGET_ARCH})..."
BIN_NAME="vps-commander-agent-linux-${TARGET_ARCH}" BIN_NAME="vps-commander-agent-linux-${TARGET_ARCH}"
DOWNLOAD_URL="${GITHUB_URL}/${REPO}/releases/download/${LATEST_TAG}/${BIN_NAME}" DOWNLOAD_URL="${RELEASE_BASE_URL}/${REPO}/releases/download/${LATEST_TAG}/${BIN_NAME}"
info "正在下载 Agent: ${DOWNLOAD_URL}" download_verified "${DOWNLOAD_URL}" "${INSTALL_DIR}/vps-commander-agent" "${BIN_NAME}"
curl -fsSL -k -o "${INSTALL_DIR}/vps-commander-agent" "${DOWNLOAD_URL}" || error "下载失败,请检查网络或 Release 是否存在"
chmod +x "${INSTALL_DIR}/vps-commander-agent" chmod +x "${INSTALL_DIR}/vps-commander-agent"
echo -e "\n--- 配置 Agent 参数 ---" echo -e "\n--- 配置 Agent 参数 ---"
read -rp "请输入 Hub WSS 连接地址 (默认: wss://vpstool.kory.kdns.fr/agent/ws): " HUB_WS read_tty "请输入 Hub WSS 连接地址 (默认: wss://vpstool.kory.kdns.fr/agent/ws): " HUB_WS
HUB_WS=${HUB_WS:-"wss://vpstool.kory.kdns.fr/agent/ws"} HUB_WS=${HUB_WS:-"wss://vpstool.kory.kdns.fr/agent/ws"}
DEFAULT_NAME=$(hostname) DEFAULT_NAME=$(hostname)
read -rp "请输入本节点名称 (默认: ${DEFAULT_NAME}): " AGENT_NAME read_tty "请输入本节点名称 (默认: ${DEFAULT_NAME}): " AGENT_NAME
AGENT_NAME=${AGENT_NAME:-${DEFAULT_NAME}} AGENT_NAME=${AGENT_NAME:-${DEFAULT_NAME}}
read -rp "请输入 Cluster Secret (集群通信密钥): " CLUSTER_SECRET read_tty "请输入 Agent 独立凭据 Token: " AGENT_TOKEN
while [ -z "$CLUSTER_SECRET" ]; do while [ -z "$AGENT_TOKEN" ]; do
read -rp "Cluster Secret 不能为空,请重新输入: " CLUSTER_SECRET read_tty "Agent Token 不能为空,请重新输入: " AGENT_TOKEN
done done
cat << ENV > "${CONF_DIR}/agent.env" cat << ENV > "${CONF_DIR}/agent.env"
VPS_COMMANDER_HUB_WS_URL=${HUB_WS} VPS_COMMANDER_HUB_WS_URL=${HUB_WS}
VPS_COMMANDER_AGENT_NAME=${AGENT_NAME} VPS_COMMANDER_AGENT_NAME=${AGENT_NAME}
VPS_COMMANDER_CLUSTER_SECRET=*** VPS_COMMANDER_AGENT_TOKEN=${AGENT_TOKEN}
ENV ENV
chmod 0600 "${CONF_DIR}/agent.env" chmod 0600 "${CONF_DIR}/agent.env"
@@ -95,7 +138,7 @@ Type=simple
User=root User=root
WorkingDirectory=${INSTALL_DIR} WorkingDirectory=${INSTALL_DIR}
EnvironmentFile=-${CONF_DIR}/agent.env EnvironmentFile=-${CONF_DIR}/agent.env
ExecStart=${INSTALL_DIR}/vps-commander-agent -hub \${VPS_COMMANDER_HUB_WS_URL} -name \${VPS_COMMANDER_AGENT_NAME} ExecStart=/bin/sh -c 'exec ${INSTALL_DIR}/vps-commander-agent -hub "\$VPS_COMMANDER_HUB_WS_URL" -name "\$VPS_COMMANDER_AGENT_NAME"'
Restart=always Restart=always
RestartSec=3s RestartSec=3s
KillSignal=SIGTERM KillSignal=SIGTERM
@@ -108,48 +151,81 @@ WantedBy=multi-user.target
SVC SVC
systemctl daemon-reload systemctl daemon-reload
systemctl enable --now vps-commander-agent
sleep 1
if systemctl is-active --quiet vps-commander-agent; then # Validate the generated unit before starting it. systemd does not expand
success "VPS-Commander Agent 安装并启动成功!" # ${VPS_COMMANDER_*} in ExecStart directly; the shell wrapper above must
# remain intact. This prevents a false-success install with a broken URL.
if ! grep -Fq 'ExecStart=/bin/sh -c' /etc/systemd/system/vps-commander-agent.service ||
! grep -Fq '$VPS_COMMANDER_HUB_WS_URL' /etc/systemd/system/vps-commander-agent.service ||
! grep -Fq '$VPS_COMMANDER_AGENT_NAME' /etc/systemd/system/vps-commander-agent.service; then
error "生成的 Agent systemd 服务异常,ExecStart 未通过校验。安装已中止。"
fi
if ! [[ "$HUB_WS" =~ ^wss://[^[:space:]]+/agent/ws$ ]]; then
error "Hub WSS 地址格式无效: ${HUB_WS}"
fi
if [[ "$AGENT_NAME" =~ [[:space:]/\?\&\=\#\%] ]]; then
error "节点名称包含非法字符: ${AGENT_NAME}"
fi
INSTALL_CHECK_SINCE=$(date --iso-8601=seconds)
systemctl enable --now vps-commander-agent
sleep 2
if ! systemctl is-active --quiet vps-commander-agent; then
error "Agent 服务启动失败,请执行: journalctl -u vps-commander-agent -n 50 --no-pager"
fi
# Verify that the running process received the actual URL/name, not literal
# placeholders or installer source text.
AGENT_CMD=$(ps -eo args= | grep -F "${INSTALL_DIR}/vps-commander-agent" | grep -v grep | head -n1 || true)
if [[ "$AGENT_CMD" != *"-hub ${HUB_WS} -name ${AGENT_NAME}"* ]]; then
error "Agent 进程参数校验失败: ${AGENT_CMD}"
fi
# A fresh connection produces this message after the Hub handshake/MCP sync.
# Do not report success merely because systemd says the process is running.
CONNECTED=0
for _ in {1..13}; do
if journalctl -u vps-commander-agent --since "$INSTALL_CHECK_SINCE" --no-pager -o cat 2>/dev/null | grep -q "MCP services synced:"; then
CONNECTED=1
break
fi
sleep 1
done
if [ "$CONNECTED" -ne 1 ]; then
error "Agent 已启动,但 15 秒内未确认成功连接 Hub,请检查: journalctl -u vps-commander-agent -n 50 --no-pager"
fi
success "VPS-Commander Agent 安装、启动并完成 Hub 连接校验!"
info "节点名称: ${AGENT_NAME}" info "节点名称: ${AGENT_NAME}"
info "可通过 'systemctl status vps-commander-agent' 查看运行状态。" info "可通过 'systemctl status vps-commander-agent' 查看运行状态。"
else
warn "服务已启动但状态可能异常,请检查 'journalctl -u vps-commander-agent -n 20'。"
fi
} }
install_hub() { install_hub() {
info "开始安装 VPS-Commander Hub (${TARGET_ARCH})..." info "开始安装 VPS-Commander Hub (${TARGET_ARCH})..."
BIN_NAME="vps-commander-hub-linux-${TARGET_ARCH}" BIN_NAME="vps-commander-hub-linux-${TARGET_ARCH}"
DOWNLOAD_URL="${GITHUB_URL}/${REPO}/releases/download/${LATEST_TAG}/${BIN_NAME}" DOWNLOAD_URL="${RELEASE_BASE_URL}/${REPO}/releases/download/${LATEST_TAG}/${BIN_NAME}"
info "正在下载 Hub: ${DOWNLOAD_URL}" download_verified "${DOWNLOAD_URL}" "${INSTALL_DIR}/vps-commander-hub" "${BIN_NAME}"
curl -fsSL -k -o "${INSTALL_DIR}/vps-commander-hub" "${DOWNLOAD_URL}" || error "下载失败,请检查网络或 Release 是否存在"
chmod +x "${INSTALL_DIR}/vps-commander-hub" chmod +x "${INSTALL_DIR}/vps-commander-hub"
echo -e "\n--- 配置 Hub 参数 ---" echo -e "\n--- 配置 Hub 参数 ---"
read -rp "请输入监听端口 (默认 9521): " HUB_PORT read_tty "请输入监听端口 (默认 9521): " HUB_PORT
HUB_PORT=${HUB_PORT:-9521} HUB_PORT=${HUB_PORT:-9521}
GEN_API_KEY=*** -c 24 /dev/urandom | xxd -p) GEN_API_KEY=$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n')
GEN_SECRET=*** -c 24 /dev/urandom | xxd -p) GEN_PASS=$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')
GEN_PASS=$(head -c 16 /dev/urandom | xxd -p)
read -rp "请输入 API Key (默认随机生成): " API_KEY read_tty "请输入 API Key (默认随机生成): " API_KEY
API_KEY=*** API_KEY=${API_KEY:-$GEN_API_KEY}
read -rp "请输入 Cluster Secret (默认随机生成): " CLUSTER_SECRET read_tty "请输入 Web 管理面板密码 (默认随机生成): " WEB_PASS
CLUSTER_SECRET=${CLUS…RET}
read -rp "请输入 Web 管理面板密码 (默认随机生成): " WEB_PASS
WEB_PASS=${WEB_PASS:-$GEN_PASS} WEB_PASS=${WEB_PASS:-$GEN_PASS}
cat << ENV > "${CONF_DIR}/hub.env" cat << ENV > "${CONF_DIR}/hub.env"
VPS_COMMANDER_API_KEY=*** VPS_COMMANDER_API_KEY=${API_KEY}
VPS_COMMANDER_CLUSTER_SECRET=*** VPS_COMMANDER_WEB_PASSWORD=${WEB_PASS}
VPS_COMMANDER_WEB_PASSWORD=*** VPS_COMMANDER_INSTALL_COMMAND="${INSTALL_COMMAND}"
ENV ENV
chmod 0600 "${CONF_DIR}/hub.env" chmod 0600 "${CONF_DIR}/hub.env"
@@ -185,7 +261,6 @@ SVC
echo -e "\n================== Hub 配置凭据 ==================" echo -e "\n================== Hub 配置凭据 =================="
echo -e "监听地址: 127.0.0.1:${HUB_PORT}" echo -e "监听地址: 127.0.0.1:${HUB_PORT}"
echo -e "API Key: ${API_KEY}" echo -e "API Key: ${API_KEY}"
echo -e "Cluster Secret: ${CLUSTER_SECRET}"
echo -e "Web 面板密码: ${WEB_PASS}" echo -e "Web 面板密码: ${WEB_PASS}"
echo -e "==================================================\n" echo -e "==================================================\n"
warn "请妥善保管上述凭据,反代请将域名反代至 127.0.0.1:${HUB_PORT}" warn "请妥善保管上述凭据,反代请将域名反代至 127.0.0.1:${HUB_PORT}"
+35 -41
View File
@@ -1,34 +1,25 @@
#!/bin/bash #!/bin/bash
set -e set -euo pipefail
# VPS-Commander Agent 一键安全升级脚本 # VPS-Commander Agent 一键安全升级脚本
# Repo: https://github.com/kyaring/vps-commander # Repo: https://gitea.king.nyc.mn/openclaw/vps-commander
REPO="kyaring/vps-commander" REPO="openclaw/vps-commander"
INSTALL_DIR="/opt/vps-commander" INSTALL_DIR="/opt/vps-commander"
GITHUB_URL="https://github.com" RELEASE_BASE_URL="https://gitea.king.nyc.mn"
API_URL="https://gitea.king.nyc.mn/api/v1"
# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; NC='\033[0m'
info() { echo -e "${BLUE}[INFO]${NC} $*"; } info() { echo -e "${BLUE}[INFO]${NC} $*"; }
success() { echo -e "${GREEN}[SUCCESS]${NC} $*"; } success() { echo -e "${GREEN}[SUCCESS]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; } warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*"; exit 1; } error() { echo -e "${RED}[ERROR]${NC} $*"; exit 1; }
# 检查 root 权限
[[ $EUID -ne 0 ]] && error "必须使用 root 权限运行此脚本" [[ $EUID -ne 0 ]] && error "必须使用 root 权限运行此脚本"
[ -f "${INSTALL_DIR}/vps-commander-agent" ] || error "未检测到已安装的 Agent (${INSTALL_DIR}/vps-commander-agent),请先使用 install.sh 完整安装。"
command -v curl >/dev/null 2>&1 || error "系统缺少 curl"
command -v sha256sum >/dev/null 2>&1 || error "系统缺少 sha256sum,无法安全校验 Release"
# 检查是否安装过 agent
if [ ! -f "${INSTALL_DIR}/vps-commander-agent" ]; then
error "未检测到已安装的 Agent (${INSTALL_DIR}/vps-commander-agent),请先使用 install.sh 完整安装。"
fi
# 架构检测
ARCH=$(uname -m) ARCH=$(uname -m)
case "$ARCH" in case "$ARCH" in
x86_64|amd64) TARGET_ARCH="amd64" ;; x86_64|amd64) TARGET_ARCH="amd64" ;;
@@ -36,45 +27,48 @@ case "$ARCH" in
*) error "暂不支持的系统架构: $ARCH" ;; *) error "暂不支持的系统架构: $ARCH" ;;
esac esac
info "正在获取最新 Release 版本信息..." info "正在获取最新正式 Release 版本信息..."
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/') LATEST_TAG=$(curl -fsSL --proto '=https' --proto-redir '=https' --retry 3 --connect-timeout 15 --max-time 30 \
if [ -z "$LATEST_TAG" ]; then "${API_URL}/repos/${REPO}/releases/latest" |
warn "无法通过 GitHub API 自动获取 Tag,回退至 v1.1.5" sed -n 's/^[[:space:]]*"tag_name": "\\([^"]*\\)".*/\\1/p' | head -n1)
LATEST_TAG="v1.1.5" [ -n "$LATEST_TAG" ] || error "无法从 Gitea 获取最新正式 Release,已停止升级;不会回退到旧版本"
fi
info "目标升级版本: ${LATEST_TAG} (${TARGET_ARCH})" info "目标升级版本: ${LATEST_TAG} (${TARGET_ARCH})"
BIN_NAME="vps-commander-agent-linux-${TARGET_ARCH}" BIN_NAME="vps-commander-agent-linux-${TARGET_ARCH}"
DOWNLOAD_URL="${GITHUB_URL}/${REPO}/releases/download/${LATEST_TAG}/${BIN_NAME}" DOWNLOAD_URL="${RELEASE_BASE_URL}/${REPO}/releases/download/${LATEST_TAG}/${BIN_NAME}"
TMP_BIN="${INSTALL_DIR}/vps-commander-agent.tmp" CHECKSUM_URL="${RELEASE_BASE_URL}/${REPO}/releases/download/${LATEST_TAG}/checksums.txt"
TMP_BIN=$(mktemp "${INSTALL_DIR}/vps-commander-agent.tmp.XXXXXX") || error "无法创建临时文件"
TMP_SUM=$(mktemp "${INSTALL_DIR}/vps-commander-checksums.tmp.XXXXXX") || { rm -f "$TMP_BIN"; error "无法创建校验文件"; }
BAK_BIN="${INSTALL_DIR}/vps-commander-agent.bak" BAK_BIN="${INSTALL_DIR}/vps-commander-agent.bak"
cleanup() { rm -f "$TMP_BIN" "$TMP_SUM"; }
trap cleanup EXIT
info "正在下载新版本二进制文件..." info "正在下载新版本二进制文件..."
curl -fsSL -k -o "${TMP_BIN}" "${DOWNLOAD_URL}" || error "下载失败,请检查网络或 Release 是否存在" curl -fL --proto '=https' --proto-redir '=https' --retry 3 --connect-timeout 15 --max-time 600 -o "$TMP_BIN" "$DOWNLOAD_URL" || error "下载失败: ${DOWNLOAD_URL}"
[ -s "$TMP_BIN" ] || error "下载结果为空"
# 完整性校验:文件大小不能小于 1MB info "正在校验 SHA256..."
FILE_SIZE=$(stat -c%s "${TMP_BIN}" 2>/dev/null || stat -f%z "${TMP_BIN}" 2>/dev/null || echo 0) curl -fsSL --proto '=https' --proto-redir '=https' --retry 3 --connect-timeout 15 --max-time 60 -o "$TMP_SUM" "$CHECKSUM_URL" || error "无法获取 Release 校验文件"
if [ "$FILE_SIZE" -lt 1000000 ]; then EXPECTED=$(awk -v f="$BIN_NAME" '$2 == f {print $1; exit}' "$TMP_SUM")
rm -f "${TMP_BIN}" [ -n "$EXPECTED" ] || error "Release 校验文件中缺少 ${BIN_NAME}"
error "下载的文件不完整或损坏 (大小: ${FILE_SIZE} 字节),已终止升级" ACTUAL=$(sha256sum "$TMP_BIN" | awk '{print $1}')
fi [ "$ACTUAL" = "$EXPECTED" ] || error "SHA256 校验失败: ${BIN_NAME}"
info "SHA256 校验通过: ${ACTUAL}"
chmod +x "${TMP_BIN}"
chmod +x "$TMP_BIN"
info "备份旧版本并原子替换..." info "备份旧版本并原子替换..."
cp -f "${INSTALL_DIR}/vps-commander-agent" "${BAK_BIN}" 2>/dev/null || true cp -f "${INSTALL_DIR}/vps-commander-agent" "$BAK_BIN" 2>/dev/null || true
mv -f "${TMP_BIN}" "${INSTALL_DIR}/vps-commander-agent" mv -f "$TMP_BIN" "${INSTALL_DIR}/vps-commander-agent"
info "重启 vps-commander-agent 服务..." info "重启 vps-commander-agent 服务..."
systemctl restart vps-commander-agent systemctl restart vps-commander-agent
sleep 2 sleep 2
if systemctl is-active --quiet vps-commander-agent; then if systemctl is-active --quiet vps-commander-agent; then
success "Agent 成功平滑升级至 ${LATEST_TAG} 并已恢复运行!" success "Agent 成功升级至 ${LATEST_TAG},SHA256 已验证并恢复运行。"
rm -f "${BAK_BIN}" rm -f "$BAK_BIN"
else else
warn "服务启动异常,正在自动回滚原版本..." warn "服务启动异常,正在自动回滚原版本..."
mv -f "${BAK_BIN}" "${INSTALL_DIR}/vps-commander-agent" mv -f "$BAK_BIN" "${INSTALL_DIR}/vps-commander-agent"
systemctl restart vps-commander-agent systemctl restart vps-commander-agent
error "升级失败,已安全回滚至上一版本,请查看日志: journalctl -u vps-commander-agent -n 20" error "升级失败,已安全回滚至上一版本,请查看日志: journalctl -u vps-commander-agent -n 20"
fi fi
+120 -47
View File
@@ -1,58 +1,131 @@
# VPS-Commander 当前发布门禁 # VPS-Commander 阶段验收标准与发布门禁用例矩阵
## 1. Build 本文档定义当前 v2.0 生产架构的发布门禁,并为 v2.1 安全加固预留验收项。
- clean Git tree
- vcs.modified=false
- vcs.revision == release commit
- AMD64/ARM64 build 成功
## 2. Cluster ---
- Hub 127.0.0.1:9521
- 5 个远程 Agent online
- Hub restart 后自动恢复
- unknown device fail-closed
## 3. Auth ## 一、构建与版本一致性
- Bearer auth
- URL token rejected
- per-device credential
- Shared Secret fallback disabled
- Panel Admin Token 不进浏览器
## 4. Authorization ### 1.1 基础测试
- Tool Registry 固定 ```bash
- Low/Medium/High 一致 go test ./...
- MCP 与 HTTP 共用 gate go test -race ./...
- call_agent_mcp 无旁路 git diff --check
- policy version 不回退 ```
## 5. File ### 1.2 生产构建
- edit_block 唯一匹配 - Git 工作树必须 clean。
- atomic write - `vcs.modified=false`。
- generation check - `vcs.revision` 必须等于 release commit。
- failure 不损坏原文件 - AMD64 / ARM64 编译成功。
## 6. Session ---
- hard TTL
- idle TTL
- ring buffer cap
- manager concurrency safe
- kill 只操作 Session 内部 process handle
## 7. MCP ## 二、Hub / Agent 集群验收
11 tools 与源码一致:list_devices、exec_command、read_file、read_multiple_files、create_directory、move_file、list_processes、edit_block、write_file、list_agent_mcp、call_agent_mcp。
必须验证:Medium 可拦截写工具;Medium 可拦截 High 工具;Agent MCP 有 gate;stdio 正常;SSE 正常。
## 8. API regression | 项目 | 验收标准 |
devices、exec、file read/list/info/search/write、edit_block、process/session、MCP、security、webhook、panel、agent WS。 | :--- | :--- |
| Hub | 监听 `127.0.0.1:9521` |
| Agent | 5 个远程节点可正常回连 |
| Restart | Hub 重启后 Agent 自动恢复 |
| Identity | Credential 与设备身份一致 |
| Unknown | 未知设备必须 fail-closed |
## 9. Test ---
go test ./...;go test -race ./...;git diff --check。
并在 clean build 后重新执行核心 smoke。
## 10. Stop conditions ## 三、认证与授权验收
Agent 断联、认证绕过、unknown device 获得 High、MCP 旁路、token 进入 argv、审计丢失、dirty binary、policy version 回退、Session 无限制增长,任一发生即停止发布。
## 11. v2.1 - Bearer API Key 正常。
P0:EffectiveRisk fail-closed;Agent credential 不进 argv。 - URL token (`?token` / `?key` / `?api_key`) 必须拒绝。
P1:Principal、Session owner 强隔离、身份链审计。 - 每设备 Credential 独立。
- Shared Secret fallback 关闭。
- Panel Admin Token 不进入浏览器。
- Tool Registry 风险等级一致。
- Policy version 不允许回退。
---
## 四、MCP 验收矩阵
| Tool | Risk | 基础用例 |
| :--- | :--- | :--- |
| `list_devices` | Low | 返回设备列表 |
| `exec_command` | High | `echo/true` |
| `read_file` | Low | 读取 `/etc/hostname` |
| `read_multiple_files` | Low | 批量读取临时文件 |
| `create_directory` | Medium | 创建临时目录 |
| `move_file` | Medium | 移动临时文件 |
| `list_processes` | Low | 返回进程 |
| `edit_block` | Medium | 唯一匹配修改 |
| `write_file` | Medium | 写入临时文件 |
| `list_agent_mcp` | Low | 查询 Agent MCP |
| `call_agent_mcp` | Medium | 调用无害 Agent MCP |
必须同时验证:
- Medium 策略可以阻断 Medium 工具。
- Medium 策略可以阻断 High 工具。
- MCP 与 HTTP 使用同一授权逻辑。
- `call_agent_mcp` 无旁路。
---
## 五、文件与 Session 验收
### 5.1 edit_block
- old_text 唯一匹配。
- generation check。
- atomic write。
- fsync。
- 失败不破坏原文件。
### 5.2 Session
- Hard TTL。
- Idle TTL。
- Ring Buffer 上限。
- 总 buffer 上限。
- 并发访问安全。
- kill 只能作用于 Session 内部 process handle。
---
## 六、API Regression
必须覆盖:
- `/api/v1/devices`
- `/api/v1/exec`
- file read/list/info/search/write
- edit_block
- process/session
- MCP services/list/call/test
- security settings
- webhook
- Panel
- Agent WebSocket
---
## 七、发布停止条件
出现以下任一情况立即停止发布:
- Agent 断联。
- 未授权请求成功。
- unknown device 获得 High。
- MCP 存在旁路。
- Token 出现在 argv。
- 审计丢失。
- dirty binary。
- Policy version 回退。
- Session 资源无限增长。
---
## 八、v2.1 验收预留
### P0
- EffectiveRisk 完全 fail-closed。
- Agent Credential 不进入 argv / cmdline。
### P1
- Principal / Operator。
- Session Owner 强隔离。
- principal → credential → session → device → operation 审计链。
+192 -39
View File
@@ -1,48 +1,201 @@
# VPS-Commander 当前系统架构规范 # VPS-Commander(自托管私有化多节点运维管家)架构与开发设计规范
## 1. 研发起点 ## 一、项目立项背景与目标
项目最初不是远程终端 UI,而是私有化 AI 运维控制面:用户自己的 Hub 作为控制中枢,多 VPS 通过 Agent 汇聚,AI 通过标准 API/MCP 发起操作,高权限能力可认证、可授权、可审计、可回滚。
## 2. 双通道 ### 1.1 背景与痛点
控制通道:AI/MCP/HTTP → Hub → Local Executor 或 Agent RPC。 - 早期方案过度依赖第三方 Relay,控制面与节点执行面边界不清。
节点通道:Agent → WSS → Hub。 - 单机开发网关通常存在项目目录沙箱,无法覆盖完整 Host-centric 运维。
Hub 同时承担身份、策略、路由、审计和资源门禁;任何 MCP 或 Agent MCP 调用都不能绕过 Hub。 - AI Agent 需要的不只是 Shell,而是节点发现、文件、进程、Session、MCP 和审计的一体化控制面。
## 3. Hub ### 1.2 核心目标
生产 binary:/opt/vps-commander/vps-commander-hub。 - **100% 私有化控制面**:Hub、Agent、SQLite 与反向代理均由用户控制。
监听:127.0.0.1:9521。 - **Host-centric 运维**:Shell、文件、进程、Session、远程 MCP。
数据库:/opt/vps-commander/data/commander.db。 - **多节点统一调度**:一个 Hub 管理多个 VPS,节点状态持久化。
systemd:vps-commander-hub.service。 - **AI 原生接入**:HTTP、MCP、stdio、Web 管理面板。
职责:HTTP API、MCP、Panel、设备状态、Agent RPC、Policy Snapshot、credential、audit、Webhook、本地执行。 - **安全闭环**:认证、风险授权、资源限制、审计、可回滚发布。
## 4. Agent ---
Agent 是目标主机上的最小执行面,主动连接 /agent/ws,不要求远端开放管理端口。
握手包含 protocol version、AgentVersion、capabilities、per-device credential。
设备身份必须来自已认证 credential,不能信任客户端自报 device/name。
## 5. 安全模型 ## 二、总体架构设计
Client:Bearer API Key;Panel:Panel Session;Agent:per-device credential。
Tool Registry 定义静态风险;Policy Snapshot 定义设备运行时权限。
Low / Medium / High 是权限上限;unknown device → deny。
生产 Shared Secret fallback 已关闭。
## 6. Tool Registry ```text
Low:read_file、read_multiple_files、list_directory、get_file_info、start_search、get_more_search_results、list_processes、list_sessions、read_process_output。 [ AI / MCP Client / Web Panel ]
Medium:edit_block、write_file、create_directory、move_file、mcp_call。 │
High:exec_command、start_process、interact_with_process、kill_process、force_terminate。 ▼ HTTPS / MCP
[ Reverse Proxy / TLS ]
│
▼ 127.0.0.1:9521
┌──────────────────────────────────────────────┐
│ VPS-Commander Hub │
│----------------------------------------------│
│ Auth / API / MCP / Web Panel │
│ Policy Snapshot / Tool Registry │
│ Cluster Router / Session / Rate Limit │
│ SQLite / Audit / Webhook │
└──────────────┬───────────────────┬───────────┘
│ │
Local Executor Agent WSS
│ │
▼ ▼
Hub 本机 Remote VPS
│
Host Executor
Shell / File / Process
```
## 7. Policy Snapshot ### 2.1 控制通道
SQLite 保存策略版本,Hub 使用内存 Snapshot 处理读路径。 AI / MCP / HTTP 请求进入 Hub,由 Hub 完成认证、设备解析、风险判断和路由。
version 单调递增;发布失败不替换旧 Snapshot;unknown device 不继承 GlobalRisk High。
v2.1 将彻底消除 EffectiveRisk 的 GlobalRisk fail-open fallback。
## 8. Session 与文件安全 ### 2.2 节点通道
Session:默认 RingBuffer 2MB,总 buffer 8MB,hard TTL 30m,idle TTL 10m,LastAccess + cleanup。 Agent 主动通过 WSS 回连 Hub,负责设备注册、状态、能力协商及 RPC 请求/响应。
kill/terminate 使用 Session 内部 process handle,不接受客户端 PID;Principal 强隔离属于 v2.1。
edit_block:唯一匹配、generation fingerprint、临时文件、fsync、atomic rename、保留权限。
## 9. 部署与回滚 两条通道共享同一设备身份、策略和审计上下文,不允许出现 MCP 或 Agent MCP 绕过 Hub 授权的旁路。
Internet → TLS Reverse Proxy → 127.0.0.1:9521;Agent 仅出站 WSS。
生产节点:wjyhk、N3450、hwhk、hwsg、m4-live-agent、qnvn。 ---
backup → clean build → single-node gray → Hub recovery → rolling Agent → audit → acceptance。
发现断联、授权绕过、credential 泄露或协议不兼容,立即停止 rollout 并回滚。 ## 三、Hub 与 Agent 通信规范
### 3.1 Agent 注册与鉴权
- Agent 连接:`wss://<hub>/agent/ws`。
- 使用每设备独立 Credential。
- Hub 从已认证 Credential 建立 Canonical Device Identity。
- 客户端自报 `device/name` 不能成为授权身份来源。
- 生产不再使用 Cluster Secret fallback。
### 3.2 协议握手
握手包含:
- Protocol Version;
- AgentVersion;
- Capabilities;
- Per-device Credential。
### 3.3 RPC
Hub 将经过授权的操作转换为 Agent RPC。
Agent 返回结果后,Hub 完成审计并将结果返回 HTTP/MCP 调用方。
---
## 四、安全与权限模型
### 4.1 认证
- HTTP / MCP:Bearer API Key。
- Web Panel:Panel Session,服务端内部 bridge Admin Token。
- Agent:per-device credential。
### 4.2 Tool Risk Registry
| 风险 | 典型操作 |
| :--- | :--- |
| Low | read_file、read_multiple_files、list_directory、file_info、search、list_processes |
| Medium | edit_block、write_file、create_directory、move_file、mcp_call |
| Low | diagnostic_command:严格白名单只读诊断(Docker、systemd、journal、网络监听、磁盘、内存、uptime) |
| High | exec_command、start_process、interact_with_process、kill_process、force_terminate |
### 4.3 Policy Snapshot
- 安全策略持久化到 SQLite。
- 每次更新生成单调递增 version。
- Hub 请求路径读取内存 Snapshot。
- 未知、未注册、凭据错误或身份无法解析的设备必须 deny。
- GlobalRisk 不得让未知设备获得 High。
v2.1 将彻底清理 `EffectiveRisk` 中仍存在的 GlobalRisk fallback。
---
## 五、Session 与执行安全
### 5.1 Session 资源限制
- Ring Buffer 默认 2MB。
- 总 Session buffer 上限 8MB。
- Hard TTL 30 分钟。
- Idle TTL 10 分钟。
- LastAccess 自动刷新。
- 过期与空闲 Session 自动清理。
### 5.2 进程生命周期
kill / terminate 使用 Session 内部进程句柄,不接受客户端任意 PID 作为授权对象。
### 5.3 文件修改
`edit_block` 使用唯一匹配、generation check、临时文件、fsync、atomic rename 和权限保留,失败时不破坏原文件。
---
## 六、MCP 架构
当前 MCP 共 12 个工具:
1. `list_devices`
2. `exec_command`
3. `read_file`
4. `read_multiple_files`
5. `create_directory`
6. `move_file`
7. `list_processes`
8. `diagnostic_command`:严格白名单的只读系统诊断;
8. `edit_block`
9. `write_file`
10. `list_agent_mcp`
11. `call_agent_mcp`
`call_agent_mcp` 必须经过 MCP risk gate,不允许成为远程 Agent 的权限旁路。
当前远程 transport 为 legacy HTTP + SSE,本地客户端为 stdio;Streamable HTTP 属于后续演进。
---
## 七、项目工程结构与技术选型
- **语言**:Go。
- **存储**:SQLite。
- **HTTP**:标准库。
- **Web**:Go embed。
- **节点通信**:WebSocket。
```text
cmd/
├── hub/
├── agent/
└── mcp-stdio/
internal/
├── api/
├── auth/
├── cluster/
├── executor/
├── mcp/
├── model/
├── notify/
├── security/
├── storage/
└── web/
```
---
## 八、生产部署边界
- Hub:`127.0.0.1:9521`。
- 公网由 Reverse Proxy 终止 TLS。
- Agent 仅出站连接 Hub。
- 数据库:`/opt/vps-commander/data/commander.db`。
- systemd:`vps-commander-hub.service` / `vps-commander-agent.service`。
升级必须执行:
1. backup;
2. clean build;
3. 单节点灰度;
4. Hub restart recovery;
5. rolling Agent;
6. MCP/security/audit 验收。
---
## 九、v2.1 演进方向
### 9.1 P0
- EffectiveRisk 完全 fail-closed。
- Agent Credential 不进入 argv / cmdline。
### 9.2 P1
- Principal / Operator Identity。
- Session Owner 强隔离。
- principal → credential → session → device → operation 完整审计链。
+158 -33
View File
@@ -1,42 +1,167 @@
# VPS-Commander 开发与协议规范 # VPS-Commander 研发设计规范与协议说明
## 1. 技术基线 ## 一、技术选型与工程原则
Go + SQLite + net/http + WebSocket。
组件:cmd/hub、cmd/agent、cmd/mcp-stdio;internal/api、auth、cluster、executor、mcp、security、storage、web、notify、model。
## 2. Agent Protocol - **开发语言**:Go。
Agent 主动连接 /agent/ws。 - **存储**:SQLite。
握手包含 protocol version、AgentVersion、capabilities、per-device credential。 - **HTTP**:标准库 `net/http`。
Hub 依据 credential 建立 canonical device identity;device/name 只能作为路由参数。 - **节点通信**:WebSocket。
- **Web 前端**:Go `embed`。
## 3. HTTP 工程原则:
/api/v1/devices、/api/v1/exec、/api/v1/file/read、/api/v1/file/list、/api/v1/file/info、/api/v1/file/search、/api/v1/process/session、/api/v1/file/write、/api/v1/devices/file/edit_block、/api/v1/mcp/*、/api/v1/security/*、/api/v1/notifications/webhook*、/healthz、/openapi.json。 1. 认证与授权分离。
Panel 使用 /panel/*。 2. Tool Risk 静态注册。
3. Device Policy 运行时解析。
4. 默认 fail-closed。
5. Session 必须有 TTL 与资源上限。
6. 生产二进制必须可追溯。
7. 发布必须可回滚。
## 4. MCP ---
serverInfo version:1.2.0;protocolVersion:2024-11-05。
11 tools:list_devices、exec_command、read_file、read_multiple_files、create_directory、move_file、list_processes、edit_block、write_file、list_agent_mcp、call_agent_mcp。
远程 HTTP 当前为 legacy SSE:GET /mcp/sse + POST /mcp/message?sessionId=...;本地为 stdio。
## 5. MCP 授权 ## 二、项目工程结构
exec → High;read → Low;write/edit/create/move → Medium;call_agent_mcp → mcp;list_agent_mcp → read。
MCP adapter 与 direct Agent MCP 使用同一 Hub security model。
## 6. 认证 ```text
HTTP/MCP:Authorization: Bearer API_KEY。 vps-commander/
禁止 ?token、?key、?api_key。 ├── cmd/
Agent:per-device credential;SQLite 只保存 hash;生产不依赖 Cluster Secret fallback。 │ ├── hub/
Panel:浏览器只持有 Panel Session;Admin Token 在服务端 bridge。 │ ├── agent/
│ └── mcp-stdio/
├── internal/
│ ├── api/
│ ├── auth/
│ ├── cluster/
│ ├── executor/
│ ├── mcp/
│ ├── model/
│ ├── notify/
│ ├── security/
│ ├── storage/
│ └── web/
├── docs/
├── deploy/
└── openapi.json
```
## 7. 资源 ---
ExecLimiter 32;SearchLimiter 8;Node.WriteMu;Node.OpMu。
Session:ring 2MB;total 8MB;hard TTL 30m;idle TTL 10m;cleanup。
## 8. 测试 ## 三、Agent WebSocket 协议
go test ./...;go test -race ./...;git diff --check。
生产额外要求 clean tree、vcs.modified=false、revision 与 release commit 一致、单 Agent 灰度、Hub recovery、MCP smoke、security matrix。
## 9. v2.1 Agent 主动连接:`/agent/ws`。
P0:EffectiveRisk fail-closed;Agent token 不进入 argv/cmdline。
P1:Principal/Operator、Session owner 强隔离、完整身份审计链。 握手包含:
v2.1 不改变 Low/Medium/High 语义,不恢复 Shared Secret。 - Protocol Version。
- AgentVersion。
- Capabilities。
- Per-device Credential。
Hub 根据 Credential 建立 Canonical Device Identity。
客户端请求中的 `device/name` 只能用于路由,不能作为授权身份来源。
---
## 四、HTTP API 规范
| 路径 | 方法 | 功能 |
| :--- | :--- | :--- |
| `/api/v1/devices` | GET | 设备列表 |
| `/api/v1/exec` | POST | Shell |
| `/api/v1/file/read` | POST | 文件读取 |
| `/api/v1/file/list` | POST | 目录列表 |
| `/api/v1/file/info` | POST | 文件信息 |
| `/api/v1/file/search` | POST | 文件搜索 |
| `/api/v1/process/session` | POST | Session |
| `/api/v1/file/write` | POST | 文件写入 |
| `/api/v1/devices/file/edit_block` | POST | 原子编辑 |
| `/api/v1/mcp/*` | GET/POST/DELETE | MCP |
| `/api/v1/security/*` | GET/POST | 安全策略 |
| `/api/v1/notifications/webhook*` | GET/POST/DELETE | Webhook |
| `/healthz` | GET | 健康检查 |
| `/openapi.json` | GET | OpenAPI |
---
## 五、MCP 协议规范
Server version:`1.2.0`。
Protocol Version:`2024-11-05`。
当前工具共 12 个:
`list_devices`、`exec_command`、`read_file`、`read_multiple_files`、`create_directory`、`move_file`、`list_processes`、`edit_block`、`write_file`、`list_agent_mcp`、`call_agent_mcp`。
远程 transport:legacy HTTP + SSE。
本地 transport:stdio。
未来 transport:Streamable HTTP。
---
## 六、认证与安全规范
### 6.1 HTTP / MCP
```http
Authorization: Bearer <API_KEY>
```
禁止:
- `?token=`
- `?key=`
- `?api_key=`
### 6.2 Agent
- 每设备独立 Credential。
- SQLite 只保存 Hash。
- 生产关闭 Shared Secret fallback。
### 6.3 Panel
Panel Session 在服务端认证。
Admin Token 只在 Panel → 内部 API bridge 中使用,不发送给浏览器。
---
## 七、并发与资源限制
| 项目 | 限制 |
| :--- | :--- |
| Exec | 32 并发 |
| Search | 8 并发 |
| Session Ring | 2MB |
| Session 总 Buffer | 8MB |
| Session Hard TTL | 30m |
| Session Idle TTL | 10m |
| WS Write | Node.WriteMu |
| Medium/High | Node.OpMu |
---
## 八、测试与发布规范
### 8.1 提交前
```bash
go test ./...
go test -race ./...
git diff --check
```
### 8.2 发布前
- clean Git tree。
- `vcs.modified=false`。
- revision 与 release commit 一致。
- 单 Agent 灰度。
- Hub restart recovery。
- MCP smoke test。
- security deny/allow matrix。
---
## 九、v2.1 研发计划
### 9.1 P0
- EffectiveRisk 完全 fail-closed。
- Credential 不进入 argv / cmdline。
### 9.2 P1
- Principal / Operator Identity。
- Session Owner 强隔离。
- 完整身份审计链。
v2.1 不改变 Low / Medium / High 语义,不恢复 Shared Secret。
+103 -98
View File
@@ -1,123 +1,128 @@
# VPS-Commander 文档基线与现状索引 # VPS-Commander 全仓库文档基线与索引
> 基线日期:2026-10-02 本文档作为 2026-10-02 之后的文档总入口,用于区分当前设计、历史记录与下一版本研发计划。
> 本文件是仓库文档的导航入口。历史审核记录保留原貌,不作为当前实现契约。
## 当前定位 ---
VPS-Commander 是自托管的多节点 Linux 运维控制中枢。 ## 一、当前项目定位
链路:AI/客户端 → Hub → Local Executor 或 Agent WebSocket → 目标主机。
当前目标: VPS-Commander 是自托管、多节点、AI Agent 友好的 Linux 运维控制中枢。
- 多节点统一身份、路由与状态管理;
- 文件、进程、Shell、MCP 运维能力;
- 认证、三级风险授权与审计;
- 可回滚、可持续升级的生产部署;
- 面向 AI Agent 的 MCP 与 HTTP 接口。
## 当前架构 核心链路:
`AI / MCP / Web Panel → Hub → Local Executor 或 Agent WSS → Target Host`。
```text ---
AI / MCP / Web
|
HTTPS/WSS
|
Reverse Proxy
|
Hub 127.0.0.1:9521
| |
Local Agent WSS
Executor |
+-- N3450
+-- hwhk
+-- hwsg
+-- m4-live-agent
+-- qnvn
|
SQLite: state / policy / audit
```
Hub 不直接公网监听;Agent 只主动回连 Hub。 ## 二、当前架构基线
## 当前安全模型 ### 2.1 Hub
- HTTP API。
- MCP。
- Web Panel。
- Agent Router。
- Security Snapshot。
- Tool Registry。
- Session。
- SQLite。
- Audit / Webhook。
- HTTP/MCP:Bearer API Key; ### 2.2 Agent
- Agent:per-device credential; - 主动 WSS 回连。
- Policy Snapshot:设备级有效策略; - per-device Credential。
- Tool Registry:Low / Medium / High; - Protocol / AgentVersion / Capabilities。
- MCP、HTTP、direct Agent MCP 统一授权; - Host-level File / Shell / Process 执行。
- SQLite 审计;
- 生产 Shared Secret fallback 已关闭。
## 当前 MCP ### 2.3 双通道
- 控制通道:HTTP / MCP → Hub → Executor。
- 节点通道:Agent → WSS → Hub。
11 个工具: ---
list_devices、exec_command、read_file、read_multiple_files、
create_directory、move_file、list_processes、edit_block、
write_file、list_agent_mcp、call_agent_mcp。
当前 HTTP MCP 是 legacy HTTP+SSE;本地是 stdio。 ## 三、当前 MCP 基线
Streamable HTTP 是后续演进方向。
## 当前 HTTP 12 个工具:
`list_devices`、`exec_command`、`read_file`、`read_multiple_files`、`create_directory`、`move_file`、`list_processes`、`edit_block`、`write_file`、`list_agent_mcp`、`call_agent_mcp`。
主要接口: 远程:legacy SSE。
/api/v1/devices 本地:stdio。
/api/v1/exec 下一阶段:Streamable HTTP。
/api/v1/file/read
/api/v1/file/list
/api/v1/file/info
/api/v1/file/search
/api/v1/process/session
/api/v1/file/write
/api/v1/devices/file/edit_block
/api/v1/mcp/*
/api/v1/security/*
/api/v1/notifications/webhook*
/agent/ws
/healthz
/openapi.json
/panel/*
## 文档分层 ---
当前规范: ## 四、当前安全基线
- README.md
- docs/ARCHITECTURE.md
- docs/DEV_SPEC.md
- docs/MCP_INTEGRATION.md
- deploy/README.md
- docs/ACCEPTANCE_CRITERIA.md
- docs/PROGRESS_TRACKING.md
- docs/VPS_COMMANDER_V2_1_SECURITY_HARDENING_SPEC.md
审计/整改输入: - HTTP/MCP:Bearer API Key。
- docs/BUGHUNT_20261002.md - Agent:per-device Credential。
- docs/DC_REFACTORING_AND_SECURITY_SPEC.md - SQLite:Credential Hash。
- docs/DC_REFACTORING_SECURITY_REVIEW_HANDOFF_20261002.md - Low / Medium / High Tool Risk。
- docs/REVIEW_B_TO_A_HANDOFF_20261002.md - Policy Snapshot。
- Shared Secret fallback:生产关闭。
- MCP 与 HTTP:统一授权门禁。
- Panel Admin Token:服务端 bridge。
历史记录: ---
- REVIEW_A_CODE_AUDIT_20261002.md
- REVIEW_B_CODE_AUDIT_20261002.md
- INCIDENT_TIMEOUT-20260930.md
- M4_FINAL_ACCEPTANCE_REPORT.md
- DC_PHASE1_IMPLEMENTATION.md
历史报告解释演进原因,不覆盖当前规范。 ## 五、文档分层
## 生产状态 ### 5.1 当前规范
- `README.md`:项目入口与能力总览。
- `docs/ARCHITECTURE.md`:架构与设计。
- `docs/DEV_SPEC.md`:研发与协议。
- `docs/MCP_INTEGRATION.md`:MCP 接入。
- `deploy/README.md`:生产部署。
- `docs/ACCEPTANCE_CRITERIA.md`:验收门禁。
- `docs/PROGRESS_TRACKING.md`:当前进度。
- `docs/VPS_COMMANDER_V2_1_SECURITY_HARDENING_SPEC.md`:v2.1 安全加固。
2026-10-02 审计确认 6 个设备在线: ### 5.2 审计 / 整改材料
wjyhk、N3450、hwhk、hwsg、m4-live-agent、qnvn。 - `docs/BUGHUNT_20261002.md`。
- `docs/DC_REFACTORING_AND_SECURITY_SPEC.md`。
- `docs/DC_REFACTORING_SECURITY_REVIEW_HANDOFF_20261002.md`。
- `docs/REVIEW_B_TO_A_HANDOFF_20261002.md`。
同时发现生产二进制存在 vcs.modified=true 的构建漂移。 ### 5.3 历史记录
因此必须区分“源码当前状态”和“生产现场状态”。 - `REVIEW_A_CODE_AUDIT_20261002.md`。
下一次发布必须 clean build、校验 revision/modified,再滚动部署。 - `REVIEW_B_CODE_AUDIT_20261002.md`。
- `INCIDENT_TIMEOUT-20260930.md`。
- `M4_FINAL_ACCEPTANCE_REPORT.md`。
- `DC_PHASE1_IMPLEMENTATION.md`。
## v2.1 历史文件用于记录演进过程,不覆盖当前规范。
P0:EffectiveRisk fail-closed;Agent Token 脱离 argv/cmdline。 ---
P1:Principal/Operator 身份、Session 强隔离、完整身份审计链。
这些属于下一版本,不伪装成 v2.0 已完成能劘,不伪装成 v2.0 已完成能力。
## 六、当前生产基线
当前生产集群包括:
- `wjyhk`
- `N3450`
- `hwhk`
- `hwsg`
- `m4-live-agent`
- `qnvn`
Hub:`/opt/vps-commander/vps-commander-hub`。
Database:`/opt/vps-commander/data/commander.db`。
Listen:`127.0.0.1:9521`。
2026-10-02 审计发现生产二进制曾 `vcs.modified=true`,因此下一次发布必须 clean rebuild 后重新对齐生产现场。
---
## 七、v2.1 基线
### P0
- EffectiveRisk 完全 fail-closed。
- Agent Credential 脱离 argv / cmdline。
### P1
- Principal / Operator Identity。
- Session Owner 强隔离。
- principal → credential → session → device → operation 审计链。
---
## 八、文档维护规则
新增能力必须同时检查 README、架构、开发规范、MCP、部署、验收、进度以及 OpenAPI Contract。
历史报告只追加新的后续报告,不覆盖原始证据。
@@ -0,0 +1,49 @@
# 已知问题:MCP Streamable HTTP 传输不受支持(待排期)
- **发现日期**:2026-10-02
- **发现人**:审核专家 B(生产问题分析)
- **状态**:待排期,未修复
---
## 现象
Android 客户端使用 MCP Kotlin SDK 的 `StreamableHttpClientTransport` 连接 vps-commander,
发送第一条消息(`initialize`)时失败:
```
io.modelcontextprotocol.kotlin.sdk.types.McpException: Error while sending message: Streamable HTTP error:
Caused by: io.modelcontextprotocol.kotlin.sdk.client.StreamableHttpError: Streamable HTTP error:
at ...StreamableHttpClientTransport.performSend(...)
```
## 根因
传输协议代际不匹配:
| | 服务端 (vps-commander) | 客户端 (Kotlin SDK) |
|---|---|---|
| 协议 | SSE 传输(MCP 2024-11-05) | Streamable HTTP(MCP 2025-03-26) |
| 端点 | `GET /mcp/sse` + `POST /mcp/message` | `POST /mcp`(单端点) |
| 行为 | `HandleSSE` 非 GET 直接 405(`internal/mcp/mcp.go:120`) | POST 收到非 2xx 即抛 `StreamableHttpError` |
服务端没有 `POST /mcp` 路由。客户端 POST 打到 `/mcp/sse` 得 405,打到 `/mcp` 得 404,
两种情况都会触发该异常。SDK 的错误信息为空(未携带 HTTP 状态码),需抓包/curl 确认。
## 验证
```bash
curl -i -X POST https://vpstool.kory.kdns.fr/mcp/sse \
-H "Content-Type: application/json" -d '{}'
# 预期:405 method not allowed(坐实协议不匹配)
```
## 修复选项(待决策)
1. **客户端改(快)**:Android 端改用 `SseClientTransport`,URL 指向 `/mcp/sse`,与服务端现状匹配。
2. **服务端加(彻底)**:实现 Streamable HTTP(`POST /mcp`,MCP 2025-03-26),属新功能开发。
## 备注
- 与 2026-10-02 bug hunt 的 4 个 bug 无关,是独立的协议兼容性问题。
- 决策前不要动生产端点。
+214 -44
View File
@@ -1,52 +1,222 @@
# VPS-Commander MCP 接入与能力 # VPS-Commander MCP(Model Context Protocol)接入指南
## 1. 当前状态 本文介绍 VPS-Commander 当前 MCP 能力、客户端接入方式、工具权限以及后续 transport 演进方向。
MCP JSON-RPC 2.0;serverInfo 1.2.0;initialize protocolVersion 2024-11-05。
远程 HTTP 当前是 legacy HTTP+SSE;本地是 stdio。Streamable HTTP 是后续演进方向。
## 2. 11 个工具 ---
| Tool | Risk | 作用 |
|---|---|---|
| list_devices | Low | 设备列表 |
| exec_command | High | Shell |
| read_file | Low | 文件读取 |
| read_multiple_files | Low | 批量读取 |
| create_directory | Medium | 创建目录 |
| move_file | Medium | 移动/重命名 |
| list_processes | Low | 进程观察 |
| edit_block | Medium | 原子文本修改 |
| write_file | Medium | 文件写入 |
| list_agent_mcp | Low | Agent MCP 列表 |
| call_agent_mcp | Medium | 调度 Agent MCP |
## 3. 远程接入 ## 一、MCP 总体能力
GET /mcp/sse → sessionId → POST /mcp/message?sessionId=<id>。
请求头:Authorization: Bearer <API_KEY>。
HTTP+SSE 仅作为兼容层,不作为未来新能力的主要 transport。
## 4. stdio VPS-Commander 当前提供两种 MCP 接入模式:
启动 vps-commander-mcp-stdio,参数 -hub <Hub URL> -key <API_KEY>。
API Key 不提交到仓库。
## 5. 参数 - **远程 HTTP SSE 模式**:适用于远程 MCP Client。
exec_command:device、command、workdir、timeout。 - **本地 stdio 模式**:适用于 Claude Desktop、Cursor、VS Code 等本地客户端。
read_file:device、path、offset、limit;默认 256 KiB,最大 1 MiB。
read_multiple_files:device、paths、limit;paths 最多 32 个。
create_directory:device、path。
move_file:device、source、destination。
list_processes:device。
edit_block:device、path、old_text、new_text;old_text 必须唯一匹配。
write_file:device、path、content。
list_agent_mcp:device。
call_agent_mcp:device、server、tool、arguments。
## 6. 安全链路 当前 MCP Server:
MCP Client → Bearer auth → JSON-RPC → tool mapping → authenticated device → Policy Snapshot → Tool Registry → allow/deny → Local/Agent → audit。 - JSON-RPC 2.0。
未知设备不得因为 GlobalRisk 而获得 High。 - server version:`1.2.0`。
- initialize protocolVersion:`2024-11-05`。
## 7. Agent MCP 当前远程 SSE 属于兼容 transport;后续新能力优先考虑 Streamable HTTP。
Hub 发现远程 Agent MCP service;客户端不直连 Agent。
Hub 负责 device authentication、risk gate、routing、audit。
## 8. 下一步 ---
Streamable HTTP、SSE fallback、capability-based advertisement、Principal audit context、显式 operation/session handle。
## 二、当前支持的 12 大 MCP Tools
| Tool 名称 | 风险等级 | 参数/功能说明 |
| :--- | :--- | :--- |
| `list_devices` | Low | 列出设备、状态及资源画像 |
| `exec_command` | High | 指定节点执行 Shell |
| `read_file` | Low | 分页读取文件 |
| `read_multiple_files` | Low | 批量读取多个文件 |
| `create_directory` | Medium | 创建目录 |
| `move_file` | Medium | 移动/重命名文件 |
| `list_processes` | Low | 查看进程 |
| `diagnostic_command` | Low | 严格白名单只读诊断,不接受任意 Shell |
| `edit_block` | Medium | 唯一匹配 + 原子写回 |
| `write_file` | Medium | 创建或覆写文件 |
| `list_agent_mcp` | Low | 查询 Agent MCP 服务 |
| `call_agent_mcp` | Medium | 调用 Agent MCP 工具 |
风险等级不是客户端提示,而是 Hub 强制执行的授权门禁。
---
## 三、统一安全链路
```text
MCP Client
│
▼
Bearer Authentication
│
▼
MCP JSON-RPC
│
▼
Tool / Action Mapping
│
▼
Authenticated Device Identity
│
▼
Security Snapshot + Tool Risk
│
├── DENY
│
▼
Local Executor / Agent WSS
│
▼
Audit
```
`call_agent_mcp` 同样必须进入 MCP risk gate,不能因为目标是 Agent MCP 就绕过 Hub 授权。
---
## 四、远程 SSE 模式
### 4.1 SSE 建立
```text
GET https://your-domain.example/mcp/sse
Authorization: Bearer <YOUR_API_KEY>
```
服务器建立 MCP Session 后提供消息端点:
```text
POST /mcp/message?sessionId=<sessionId>
Authorization: Bearer <YOUR_API_KEY>
```
### 4.2 注意事项
- URL 中禁止放 Token。
- `?token=`、`?key=`、`?api_key=` 不作为认证方式。
- SSE 当前作为 legacy compatibility transport。
---
## 五、本地 stdio 模式
适用于 Claude Desktop、Cursor、VS Code 等本地客户端。
```json
{
"mcpServers": {
"vps-commander": {
"command": "/opt/vps-commander/vps-commander-mcp-stdio",
"args": [
"-hub", "https://your-domain.example",
"-key", "YOUR_API_KEY"
]
}
}
}
```
API Key 不应提交到 Git 仓库。
---
## 六、主要工具参数
### 6.1 exec_command
- `device`:目标节点,可选。
- `command`:必填。
- `workdir`:可选。
- `timeout`:默认 30 秒,最大 300 秒。
### 6.2 read_file
- `device`、`path` 必填。
- `offset` 可选。
- `limit` 默认 256 KiB,最大 1 MiB。
### 6.3 read_multiple_files
- `device` 可选。
- `paths` 必填数组。
- 当前 Hub 最多接受 32 个路径。
### 6.4 create_directory
- `device`、`path`。
### 6.5 move_file
- `device`、`source`、`destination`。
### 6.6 list_processes
- `device` 可选。
### 6.7 diagnostic_command
- `device`、`action` 必填。
- `action` 仅允许:`docker_ps`、`docker_logs`、`docker_inspect`、`systemctl_status`、`journalctl`、`ss_listen`、`df`、`free`、`uptime`。
- 这是 Low 风险只读诊断通道,不接受任意 Shell;Medium 模式可使用,但 `exec_command` 仍保持 High。
### 6.7 edit_block
- `device`、`path`、`old_text`、`new_text`。
- `old_text` 必须唯一匹配。
- 使用 generation check + atomic write。
### 6.8 write_file
- `device`、`path`、`content`。
### 6.9 list_agent_mcp
- `device` 必填。
### 6.10 call_agent_mcp
- `device`、`server`、`tool` 必填。
- `arguments` 可选 JSON 对象。
---
## 七、一键安装与升级
### 7.1 一键安装
仓库已经提供统一安装脚本,支持 Linux `amd64` 与 `arm64`,安装时自动识别架构并从 GitHub Release 获取对应二进制。
```bash
curl -fsSL https://gitea.king.nyc.mn/openclaw/vps-commander/raw/branch/main/deploy/install.sh | sudo bash
```
脚本会进入交互式安装流程,可选择 Hub 或 Agent。生产环境使用时,Agent 应使用独立设备凭据,不应重新启用全局 Shared Secret。
### 7.2 一键升级 Agent
```bash
curl -fsSL https://gitea.king.nyc.mn/openclaw/vps-commander/raw/branch/main/deploy/upgrade-agent.sh | sudo bash
```
升级采用临时文件下载 → 基础完整性检查 → 旧二进制备份 → 原子替换 → systemd 重启 → 健康检查;启动失败时自动回滚旧版本。
> Hub 的生产升级建议继续采用滚动发布:先完成 Release 与构建校验,再替换 Hub,确认节点重新上线后再继续后续节点。避免把 Hub 升级做成无保护的“一键重启”。
---
## 八、Agent MCP
Hub 可以发现远程 Agent 暴露的 MCP Service。
```text
MCP Client
↓
Hub Authentication
↓
Security Gate
↓
Authenticated Agent
↓
Agent MCP Service
```
客户端不直接连接 Agent MCP。
---
## 八、后续演进
1. Streamable HTTP。
2. 保留 SSE fallback。
3. Capability-based Tool Advertisement。
4. Principal Identity 纳入 MCP Audit Context。
5. 长任务引入显式 Operation / Session Handle。
+124 -38
View File
@@ -1,47 +1,133 @@
# VPS-Commander 当前进度与路线图 # VPS-Commander 项目进度与路线图
> 更新时间:2026-10-02 本文档记录当前版本真实进度。历史审计文件继续保留原始证据,不直接作为当前状态判断依据。
## 1. 已完成 ---
- Hub/Agent 双通道
- 多节点状态持久化
- per-device credential
- Security Snapshot
- Low/Medium/High gate
- MCP 安全门禁
- edit_block 原子安全
- Session 资源限制
- Web Panel
- Webhook
- MCP 11 tools
## 2. 当前 MCP ## 一、当前总体状态
11 个:list_devices、exec_command、read_file、read_multiple_files、create_directory、move_file、list_processes、edit_block、write_file、list_agent_mcp、call_agent_mcp。
早期文档中的“4 个 MCP 工具”已废止。
## 3. v2.0 当前定位 | 模块 | 状态 |
Hub、Agent WSS、per-device credential、Policy Snapshot、Tool Registry、MCP/HTTP unified gate、SQLite audit、Panel、Session limits 已形成完整架构。 | :--- | :--- |
| Hub / Agent 双通道 | ✅ 已完成 |
| 多节点持久化 | ✅ 已完成 |
| Per-device Credential | ✅ 已完成 |
| Security Snapshot | ✅ 已完成 |
| Low / Medium / High Gate | ✅ 已完成 |
| MCP 安全门禁 | ✅ 已完成 |
| edit_block 原子安全 | ✅ 已完成 |
| Session 资源限制 | ✅ 已完成 |
| Web Panel | ✅ 已完成 |
| Webhook | ✅ 已完成 |
| MCP 11 Tools | ✅ 已完成源码实现 |
| Clean Production Rebuild | 🟡 下一次发布收口 |
| EffectiveRisk 完全 Fail-closed | 🔵 v2.1 |
| Agent Token 脱离 argv | 🔵 v2.1 |
| Principal 强隔离 | 🔵 v2.1 |
## 4. 当前发布问题 ---
2026-10-02 Bug Hunt:
1. 生产 binary 曾由 dirty tree 构建;
2. 造成生产 Agent 与 HEAD 能力漂移;
3. process/session snake_case 请求字段存在兼容问题;
4. Hub 本地 process/session 缺少 local fallback。
在源码、测试、生产现场同时确认前,不把这些项目标记为已修复。
## 5. v2.1 P0 ## 二、MCP 当前能力
EffectiveRisk:canonical device identity;unknown/offline/bad credential → risk 0;GlobalRisk 仅用于已认证设备;unknown 不得继承 High。
Agent credential:EnvironmentFile/LoadCredential;ExecStart 不出现 secret;ps/cmdline 不可读 token;支持 rotation + rollback。
## 6. v2.1 P1 当前共 12 个 Tools:
Principal:principal_id、principal_type、credential_id、device_id。 1. `list_devices`
Session owner 绑定 Principal;takeover 必须显式授权并审计。 2. `exec_command`
形成 principal → credential → session → device → operation 链。 3. `read_file`
4. `read_multiple_files`
5. `create_directory`
6. `move_file`
7. `list_processes`
8. `edit_block`
9. `write_file`
10. `list_agent_mcp`
11. `call_agent_mcp`
## 7. 发布顺序 早期“4 个 MCP Tools”的文档已经废止。
backup → clean build → single-node gray → Hub recovery → rolling Agent → MCP smoke → security matrix → audit → acceptance。
## 8. 文档同步规则 ---
功能变化同时检查 README、ARCHITECTURE、DEV_SPEC、MCP_INTEGRATION、deploy/README、ACCEPTANCE_CRITERIA、PROGRESS_TRACKING、openapi.json。
历史审核报告保留原貌,不回写当前结论。 ## 三、v2.0 当前收口
当前架构已经形成:
- Hub 中央控制。
- Agent WSS 回连。
- Per-device Credential。
- Policy Snapshot。
- Tool Registry。
- MCP / HTTP Unified Gate。
- SQLite Audit。
- Session Resource Limits。
- Web Management Panel。
---
## 四、2026-10-02 审计发现
### 4.1 生产构建漂移
生产 Hub / Agent 曾以 `vcs.modified=true` 构建。
这会破坏源码 → revision → binary 的可追溯链。
### 4.2 代码兼容问题
- process/session API 存在 snake_case 请求字段兼容问题。
- Hub 本地 process/session 路径缺少 local fallback。
在源码、测试和生产现场全部验证之前,上述项目不标记为“已修复”。
---
## 五、v2.1 路线
### 5.1 P0-1:EffectiveRisk
- Canonical Device Identity。
- unknown / offline / bad credential → risk 0。
- GlobalRisk 只作为已认证设备的业务默认。
- Unknown 不得继承 High。
### 5.2 P0-2:Agent Credential
- EnvironmentFile / LoadCredential。
- ExecStart 不出现 secret。
- `/proc/*/cmdline` 不可读取 token。
- 支持 rotation + rollback。
### 5.3 P1:Principal
- `principal_id`。
- `principal_type`。
- `credential_id`。
- `device_id`。
- Session Owner 绑定 Principal。
- takeover 必须显式授权并审计。
---
## 六、标准发布顺序
```text
Backup
↓
Clean Build
↓
Single-node Gray Release
↓
Hub Restart Recovery
↓
Rolling Agent
↓
MCP / Security / Audit
↓
Full Acceptance
```
---
## 七、文档同步规则
任何新功能或安全变更必须同步检查:
- README
- ARCHITECTURE
- DEV_SPEC
- MCP_INTEGRATION
- deploy/README
- ACCEPTANCE_CRITERIA
- PROGRESS_TRACKING
- openapi.json(如影响 HTTP Contract)
历史审核报告保持原貌,不回写成当前状态。
+96 -13
View File
@@ -47,8 +47,10 @@ type Server struct {
Notify *notify.Manager Notify *notify.Manager
Policy *security.Snapshot Policy *security.Snapshot
AdminToken string AdminToken string
InstallCommand string
ExecLimiter chan struct{} ExecLimiter chan struct{}
SearchLimiter chan struct{} SearchLimiter chan struct{}
LocalSessions *executor.SessionManager
} }
const ( const (
@@ -253,8 +255,17 @@ func (s *Server) ProvisionDeviceCredentialJSON(w http.ResponseWriter, r *http.Re
http.Error(w, "local control node does not use agent credential", 400) http.Error(w, "local control node does not use agent credential", 400)
return return
} }
if s.Cluster == nil || !s.Cluster.Online(q.Device) { if strings.ContainsAny(q.Device, "/\\?&=#%") {
http.Error(w, "device offline", 409) http.Error(w, "invalid device name", 400)
return
}
configured, err := s.Store.HasDeviceCredential(q.Device)
if err != nil {
http.Error(w, "credential lookup failed", 500)
return
}
if configured {
http.Error(w, "device credential already exists; revoke/rotate it before provisioning again", 409)
return return
} }
b := make([]byte, 32) b := make([]byte, 32)
@@ -268,7 +279,7 @@ func (s *Server) ProvisionDeviceCredentialJSON(w http.ResponseWriter, r *http.Re
return return
} }
_ = s.Store.Audit(clientIP(r), q.Device, "device_credential_provision", "device="+q.Device, 0, 0, "credential provisioned") _ = s.Store.Audit(clientIP(r), q.Device, "device_credential_provision", "device="+q.Device, 0, 0, "credential provisioned")
jsonOut(w, map[string]any{"ok": true, "device": q.Device, "token": token}) jsonOut(w, map[string]any{"ok": true, "device": q.Device, "token": token, "install_command": s.InstallCommand})
} }
func (s *Server) UpdateSecuritySettingsJSON(w http.ResponseWriter, r *http.Request) { func (s *Server) UpdateSecuritySettingsJSON(w http.ResponseWriter, r *http.Request) {
@@ -782,8 +793,12 @@ func (s *Server) processSession(w http.ResponseWriter, r *http.Request) {
return return
} }
var req struct { var req struct {
Device, SessionID, Command, Workdir, Data string Device string `json:"device"`
Force bool SessionID string `json:"session_id"`
Command string `json:"command"`
Workdir string `json:"workdir"`
Data string `json:"data"`
Force bool `json:"force"`
RingCapacity int `json:"ring_capacity"` RingCapacity int `json:"ring_capacity"`
} }
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256*1024)).Decode(&req); err != nil { if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256*1024)).Decode(&req); err != nil {
@@ -796,15 +811,17 @@ func (s *Server) processSession(w http.ResponseWriter, r *http.Request) {
if !s.requireSecurity(w, r, req.Device, "exec", req.SessionID) { if !s.requireSecurity(w, r, req.Device, "exec", req.SessionID) {
return return
} }
if s.Cluster == nil {
http.Error(w, "cluster unavailable", 503)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel() defer cancel()
action := r.URL.Query().Get("action") action := r.URL.Query().Get("action")
owner := sessionOwner(r)
var result any var result any
var err error var err error
if s.isRemote(req.Device) {
if s.Cluster == nil || !s.Cluster.Online(req.Device) {
http.Error(w, "device offline", 409)
return
}
switch action { switch action {
case "start": case "start":
if req.SessionID == "" { if req.SessionID == "" {
@@ -814,14 +831,14 @@ func (s *Server) processSession(w http.ResponseWriter, r *http.Request) {
return return
} }
} }
result, err = s.Cluster.StartProcess(ctx, req.Device, cluster.StartProcessPayload{Command: req.Command, Workdir: req.Workdir, SessionID: req.SessionID, Owner: sessionOwner(r), RingCapacity: req.RingCapacity}) result, err = s.Cluster.StartProcess(ctx, req.Device, cluster.StartProcessPayload{Command: req.Command, Workdir: req.Workdir, SessionID: req.SessionID, Owner: owner, RingCapacity: req.RingCapacity})
case "read": case "read":
result, err = s.Cluster.ReadProcessOutput(ctx, req.Device, req.SessionID, sessionOwner(r)) result, err = s.Cluster.ReadProcessOutput(ctx, req.Device, req.SessionID, owner)
case "input": case "input":
err = s.Cluster.InteractProcess(ctx, req.Device, req.SessionID, req.Data, sessionOwner(r)) err = s.Cluster.InteractProcess(ctx, req.Device, req.SessionID, req.Data, owner)
result = map[string]any{"ok": true} result = map[string]any{"ok": true}
case "stop": case "stop":
err = s.Cluster.ForceTerminate(ctx, req.Device, req.SessionID, sessionOwner(r)) err = s.Cluster.ForceTerminate(ctx, req.Device, req.SessionID, owner)
result = map[string]any{"ok": true} result = map[string]any{"ok": true}
case "list": case "list":
result, err = s.Cluster.ListSessions(ctx, req.Device) result, err = s.Cluster.ListSessions(ctx, req.Device)
@@ -829,6 +846,72 @@ func (s *Server) processSession(w http.ResponseWriter, r *http.Request) {
http.Error(w, "unknown action", 400) http.Error(w, "unknown action", 400)
return return
} }
} else {
if s.LocalSessions == nil {
http.Error(w, "local session manager unavailable", 503)
return
}
switch action {
case "start":
if req.SessionID == "" {
req.SessionID, err = newSessionID()
if err != nil {
http.Error(w, "session id generation failed", 500)
return
}
}
var sess *executor.Session
sess, err = s.LocalSessions.Start(context.Background(), req.SessionID, req.Command, req.Workdir, owner, req.RingCapacity)
if err == nil {
result = map[string]any{"session_id": sess.ID, "started_at": sess.StartedAt.Unix()}
}
case "read":
var sess *executor.Session
sess, ok := s.LocalSessions.Get(req.SessionID)
if !ok {
err = fmt.Errorf("session not found")
break
}
if !sess.Authorized(owner) {
err = fmt.Errorf("session ownership denied")
break
}
code, done, _ := sess.Status()
stdout, stderr := sess.Output()
result = cluster.ProcessOutputPayload{SessionID: req.SessionID, Stdout: stdout, Stderr: stderr, ExitCode: code, Running: !done}
case "input":
var sess *executor.Session
sess, ok := s.LocalSessions.Get(req.SessionID)
if !ok {
err = fmt.Errorf("session not found")
break
}
if !sess.Authorized(owner) {
err = fmt.Errorf("session ownership denied")
break
}
err = sess.Stdin([]byte(req.Data))
result = map[string]any{"ok": true}
case "stop":
var sess *executor.Session
sess, ok := s.LocalSessions.Get(req.SessionID)
if !ok {
err = fmt.Errorf("session not found")
break
}
if !sess.Authorized(owner) {
err = fmt.Errorf("session ownership denied")
break
}
err = s.LocalSessions.Stop(req.SessionID, true)
result = map[string]any{"ok": true}
case "list":
result = s.LocalSessions.List()
default:
http.Error(w, "unknown action", 400)
return
}
}
if err != nil { if err != nil {
http.Error(w, err.Error(), 409) http.Error(w, err.Error(), 409)
return return
+74
View File
@@ -9,6 +9,7 @@ import (
"strings" "strings"
"sync" "sync"
"testing" "testing"
"time"
"github.com/wjyhk/vps-commander/internal/executor" "github.com/wjyhk/vps-commander/internal/executor"
"github.com/wjyhk/vps-commander/internal/storage" "github.com/wjyhk/vps-commander/internal/storage"
@@ -92,6 +93,38 @@ func TestSecurityEffectiveModeAndExecGate(t *testing.T) {
} }
} }
func TestProcessSessionLocalSnakeCaseAndLifecycle(t *testing.T) {
dir := t.TempDir()
store, err := storage.Open(filepath.Join(dir, "db.sqlite"))
if err != nil {
t.Fatal(err)
}
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", LocalSessions: executor.NewSessionManager(0)}
if err := s.LoadSecurityPolicySnapshot(); err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/api/v1/process/session?action=start", strings.NewReader(`{"device":"local","session_id":"session-test-001","command":"sleep 0.2; printf local-ok"}`))
w := httptest.NewRecorder()
s.processSession(w, req)
if w.Code != http.StatusOK {
t.Fatalf("start status=%d body=%s", w.Code, w.Body.String())
}
time.Sleep(1 * time.Second)
req = httptest.NewRequest(http.MethodPost, "/api/v1/process/session?action=read", strings.NewReader(`{"device":"local","session_id":"session-test-001"}`))
w = httptest.NewRecorder()
s.processSession(w, req)
if w.Code != http.StatusOK {
t.Fatalf("read status=%d body=%s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), "local-ok") {
t.Fatalf("missing session output: %s", w.Body.String())
}
}
func TestEditBlockSecurityAndReplacement(t *testing.T) { func TestEditBlockSecurityAndReplacement(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
store, err := storage.Open(filepath.Join(dir, "db.sqlite")) store, err := storage.Open(filepath.Join(dir, "db.sqlite"))
@@ -134,3 +167,44 @@ func TestEditBlockSecurityAndReplacement(t *testing.T) {
t.Fatalf("low mode status=%d body=%s", w.Code, w.Body.String()) t.Fatalf("low mode status=%d body=%s", w.Code, w.Body.String())
} }
} }
func TestProvisionDeviceCredentialForNewOfflineDevice(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{
Store: store,
LocalName: "wjyhk",
AdminToken: "admin-test-token",
}
req := httptest.NewRequest(http.MethodPost, "/api/v1/security/device-credentials/provision", strings.NewReader("{\"device\":\"new-node-01\"}"))
req.Header.Set("X-Admin-Token", "admin-test-token")
w := httptest.NewRecorder()
s.ProvisionDeviceCredentialJSON(w, req)
if w.Code != http.StatusOK {
t.Fatalf("provision status=%d body=%s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), "\"token\"") {
t.Fatalf("missing token: %s", w.Body.String())
}
ok, err := store.HasDeviceCredential("new-node-01")
if err != nil {
t.Fatal(err)
}
if !ok {
t.Fatal("credential was not persisted")
}
req = httptest.NewRequest(http.MethodPost, "/api/v1/security/device-credentials/provision", strings.NewReader("{\"device\":\"new-node-01\"}"))
req.Header.Set("X-Admin-Token", "admin-test-token")
w = httptest.NewRecorder()
s.ProvisionDeviceCredentialJSON(w, req)
if w.Code != http.StatusConflict {
t.Fatalf("duplicate provision status=%d body=%s", w.Code, w.Body.String())
}
}
+27
View File
@@ -98,6 +98,33 @@ func (b *MCPBackend) ExecCommand(ctx context.Context, clientIP, device, command,
}, nil }, nil
} }
func (b *MCPBackend) DiagnosticCommand(ctx context.Context, clientIP, device string, req executor.DiagnosticRequest) (any, error) {
if device == "" {
device = b.server.LocalName
}
if err := b.authorize(device, "diagnostic", clientIP); err != nil {
return nil, err
}
if req.Action == "" {
return nil, errors.New("diagnostic action required")
}
if b.server.isRemote(device) {
if b.server.Cluster == nil || !b.server.Cluster.Online(device) {
return nil, fmt.Errorf("device %s is offline", device)
}
res, err := b.server.Cluster.Diagnostic(ctx, device, req)
if err != nil {
return nil, err
}
return res, nil
}
res, err := executor.Diagnostic(ctx, req)
if err != nil {
return nil, err
}
return res, nil
}
func (b *MCPBackend) ReadFile(ctx context.Context, clientIP, device, path string, offset, limit int64) (any, error) { func (b *MCPBackend) ReadFile(ctx context.Context, clientIP, device, path string, offset, limit int64) (any, error) {
if device == "" { if device == "" {
device = b.server.LocalName device = b.server.LocalName
+14
View File
@@ -13,6 +13,7 @@ import (
"time" "time"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"github.com/wjyhk/vps-commander/internal/executor"
"github.com/wjyhk/vps-commander/internal/security" "github.com/wjyhk/vps-commander/internal/security"
"github.com/wjyhk/vps-commander/internal/storage" "github.com/wjyhk/vps-commander/internal/storage"
"github.com/wjyhk/vps-commander/internal/sysinfo" "github.com/wjyhk/vps-commander/internal/sysinfo"
@@ -464,6 +465,19 @@ func (m *Manager) Exec(ctx context.Context, name string, p ExecPayload) (Result,
return Result{msg.ExitCode, msg.Stdout, msg.Stderr, msg.DurationMS}, nil return Result{msg.ExitCode, msg.Stdout, msg.Stderr, msg.DurationMS}, nil
} }
func (m *Manager) Diagnostic(ctx context.Context, name string, req executor.DiagnosticRequest) (executor.DiagnosticResult, error) {
msg, err := m.call(ctx, name, "diagnostic_command", req)
if err != nil {
return executor.DiagnosticResult{}, err
}
b, _ := json.Marshal(msg.Payload)
var out executor.DiagnosticResult
if err := json.Unmarshal(b, &out); err != nil {
return out, err
}
return out, nil
}
func (m *Manager) ReadFile(ctx context.Context, name string, p FileReadPayload) (FileResult, error) { func (m *Manager) ReadFile(ctx context.Context, name string, p FileReadPayload) (FileResult, error) {
msg, err := m.call(ctx, name, "file_read", p) msg, err := m.call(ctx, name, "file_read", p)
if err != nil { if err != nil {
+117
View File
@@ -0,0 +1,117 @@
package executor
import (
"context"
"errors"
"fmt"
"os/exec"
"strconv"
"strings"
"time"
)
// DiagnosticRequest is a structured, read-only diagnostic operation. It is deliberately
// not a shell command: every action maps to a fixed executable/argument set.
type DiagnosticRequest struct {
Action string `json:"action"`
Target string `json:"target,omitempty"`
Lines int `json:"lines,omitempty"`
}
type DiagnosticResult struct {
Action string `json:"action"`
Target string `json:"target,omitempty"`
ExitCode int `json:"exit_code"`
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
DurationMS int64 `json:"duration_ms"`
}
func Diagnostic(ctx context.Context, req DiagnosticRequest) (DiagnosticResult, error) {
args, err := diagnosticArgs(req)
if err != nil {
return DiagnosticResult{}, err
}
if req.Lines <= 0 {
req.Lines = 100
}
if req.Lines > 500 {
req.Lines = 500
}
// docker logs is the only operation where a caller-controlled numeric limit is useful.
if req.Action == "docker_logs" {
args = []string{"logs", "--tail", strconv.Itoa(req.Lines), req.Target}
}
start := time.Now()
c, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
cmd := exec.CommandContext(c, args[0], args[1:]...)
out, runErr := cmd.CombinedOutput()
const maxOutput = 256 * 1024
if len(out) > maxOutput {
out = append(out[:maxOutput], []byte("\n[output truncated at 256 KiB]\n")...)
}
code := 0
if cmd.ProcessState != nil {
code = cmd.ProcessState.ExitCode()
}
result := DiagnosticResult{Action: req.Action, Target: req.Target, ExitCode: code, Stdout: string(out), DurationMS: time.Since(start).Milliseconds()}
if runErr != nil && code == -1 {
return result, fmt.Errorf("diagnostic failed: %w", runErr)
}
return result, nil
}
func diagnosticArgs(req DiagnosticRequest) ([]string, error) {
target := strings.TrimSpace(req.Target)
switch req.Action {
case "docker_ps":
if target != "" {
return nil, errors.New("docker_ps does not accept target")
}
return []string{"docker", "ps", "--no-trunc"}, nil
case "docker_logs":
if target == "" || strings.ContainsAny(target, " \t\r\n;|&<>$`") {
return nil, errors.New("invalid docker container target")
}
return []string{"docker", "logs", "--tail", "100", target}, nil
case "docker_inspect":
if target == "" || strings.ContainsAny(target, " \t\r\n;|&<>$`") {
return nil, errors.New("invalid docker target")
}
return []string{"docker", "inspect", target}, nil
case "systemctl_status":
if target == "" || strings.ContainsAny(target, " \t\r\n;|&<>$`") {
return nil, errors.New("invalid systemd unit")
}
return []string{"systemctl", "status", "--no-pager", "--full", target}, nil
case "journalctl":
if target == "" || strings.ContainsAny(target, " \t\r\n;|&<>$`") {
return nil, errors.New("invalid journal unit")
}
return []string{"journalctl", "--no-pager", "-u", target, "-n", "100"}, nil
case "ss_listen":
if target != "" {
return nil, errors.New("ss_listen does not accept target")
}
return []string{"ss", "-lntp"}, nil
case "df":
if target != "" {
return nil, errors.New("df does not accept target")
}
return []string{"df", "-h"}, nil
case "free":
if target != "" {
return nil, errors.New("free does not accept target")
}
return []string{"free", "-h"}, nil
case "uptime":
if target != "" {
return nil, errors.New("uptime does not accept target")
}
return []string{"uptime"}, nil
default:
return nil, fmt.Errorf("unsupported diagnostic action: %s", req.Action)
}
}
+24
View File
@@ -0,0 +1,24 @@
package executor
import (
"context"
"strings"
"testing"
)
func TestDiagnosticRejectsShellInjection(t *testing.T) {
_, err := Diagnostic(context.Background(), DiagnosticRequest{Action: "docker_logs", Target: "edgeever;rm -rf /"})
if err == nil || !strings.Contains(err.Error(), "invalid docker") {
t.Fatalf("expected target rejection, got %v", err)
}
}
func TestDiagnosticAllowsReadOnlyUptime(t *testing.T) {
got, err := Diagnostic(context.Background(), DiagnosticRequest{Action: "uptime"})
if err != nil {
t.Fatal(err)
}
if got.ExitCode != 0 || strings.TrimSpace(got.Stdout) == "" {
t.Fatalf("unexpected uptime result: %#v", got)
}
}
+25
View File
@@ -12,6 +12,7 @@ import (
"time" "time"
"github.com/wjyhk/vps-commander/internal/auth" "github.com/wjyhk/vps-commander/internal/auth"
"github.com/wjyhk/vps-commander/internal/executor"
) )
// MCP Protocol / JSON-RPC 2.0 Types // MCP Protocol / JSON-RPC 2.0 Types
@@ -77,6 +78,10 @@ type ActionBackend interface {
EditBlock(ctx context.Context, clientIP, device, path, oldText, newText string) (any, error) EditBlock(ctx context.Context, clientIP, device, path, oldText, newText string) (any, error)
} }
type DiagnosticBackend interface {
DiagnosticCommand(ctx context.Context, clientIP, device string, req executor.DiagnosticRequest) (any, error)
}
type ExtendedBackend interface { type ExtendedBackend interface {
ReadMultipleFiles(ctx context.Context, clientIP, device string, paths []string, limit int64) (any, error) ReadMultipleFiles(ctx context.Context, clientIP, device string, paths []string, limit int64) (any, error)
CreateDirectory(ctx context.Context, clientIP, device, path string) (any, error) CreateDirectory(ctx context.Context, clientIP, device, path string) (any, error)
@@ -280,12 +285,14 @@ func (s *Server) handleRequest(ctx context.Context, r *http.Request, req JSONRPC
{Name: "create_directory", Description: "创建目录", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}, "path": {Type: "string", Description: "目录路径"}}, Required: []string{"path"}}}, {Name: "create_directory", Description: "创建目录", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}, "path": {Type: "string", Description: "目录路径"}}, Required: []string{"path"}}},
{Name: "move_file", Description: "移动或重命名文件", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}, "source": {Type: "string", Description: "源路径"}, "destination": {Type: "string", Description: "目标路径"}}, Required: []string{"source", "destination"}}}, {Name: "move_file", Description: "移动或重命名文件", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}, "source": {Type: "string", Description: "源路径"}, "destination": {Type: "string", Description: "目标路径"}}, Required: []string{"source", "destination"}}},
{Name: "list_processes", Description: "列出受控节点当前进程", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}}}}, {Name: "list_processes", Description: "列出受控节点当前进程", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}}}},
{Name: "diagnostic_command", Description: "执行严格白名单的只读系统诊断,不接受任意 Shell", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}, "action": {Type: "string", Description: "docker_ps|docker_logs|docker_inspect|systemctl_status|journalctl|ss_listen|df|free|uptime"}, "target": {Type: "string", Description: "容器名或 systemd unit(按 action 使用)"}, "lines": {Type: "integer", Description: "docker_logs 最大行数,1-500"}}, Required: []string{"action"}}},
{ {
Name: "edit_block", Name: "edit_block",
Description: "对指定文件执行唯一文本块的原子替换;old_text 必须恰好匹配一次", Description: "对指定文件执行唯一文本块的原子替换;old_text 必须恰好匹配一次",
InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标节点名称"}, "path": {Type: "string", Description: "目标文件路径"}, "old_text": {Type: "string", Description: "必须唯一匹配的原文本块"}, "new_text": {Type: "string", Description: "替换后的文本块"}}, Required: []string{"path", "old_text", "new_text"}}, InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标节点名称"}, "path": {Type: "string", Description: "目标文件路径"}, "old_text": {Type: "string", Description: "必须唯一匹配的原文本块"}, "new_text": {Type: "string", Description: "替换后的文本块"}}, Required: []string{"path", "old_text", "new_text"}},
}, },
{ {
Name: "write_file",
Description: "向指定受控节点创建或覆写文件", Description: "向指定受控节点创建或覆写文件",
InputSchema: InputSchema{ InputSchema: InputSchema{
Type: "object", Type: "object",
@@ -429,6 +436,24 @@ func (s *Server) callTool(ctx context.Context, clientIP string, params CallToolP
return map[string]string{"error": err.Error()}, true return map[string]string{"error": err.Error()}, true
} }
return res, false return res, false
case "diagnostic_command":
var a struct {
Device string `json:"device"`
Action string `json:"action"`
Target string `json:"target"`
Lines int `json:"lines"`
}
_ = json.Unmarshal(params.Arguments, &a)
b, ok := s.Backend.(DiagnosticBackend)
if !ok {
return map[string]string{"error": "diagnostic tools unavailable"}, true
}
res, err := b.DiagnosticCommand(ctx, clientIP, a.Device, executor.DiagnosticRequest{Action: a.Action, Target: a.Target, Lines: a.Lines})
if err != nil {
return map[string]string{"error": err.Error()}, true
}
return res, false
case "list_processes": case "list_processes":
var a struct { var a struct {
Device string `json:"device"` Device string `json:"device"`
+18 -1
View File
@@ -79,9 +79,26 @@ func TestMCPInitializeAndListTools(t *testing.T) {
t.Fatalf("expected map result") t.Fatalf("expected map result")
} }
tools, ok := resMap["tools"].([]any) tools, ok := resMap["tools"].([]any)
if !ok || len(tools) != 11 { if !ok || len(tools) != 12 {
t.Fatalf("expected 11 tools, got %d", len(tools)) t.Fatalf("expected 11 tools, got %d", len(tools))
} }
foundWriteFile := false
for _, raw := range tools {
tool, ok := raw.(map[string]any)
if !ok {
t.Fatalf("tool entry is not an object: %#v", raw)
}
name, _ := tool["name"].(string)
if name == "" {
t.Fatalf("tool entry has empty name: %#v", tool)
}
if name == "write_file" {
foundWriteFile = true
}
}
if !foundWriteFile {
t.Fatalf("write_file missing from tools/list")
}
} }
func TestMCPCallTool(t *testing.T) { func TestMCPCallTool(t *testing.T) {
+2 -1
View File
@@ -15,6 +15,7 @@ var registry = map[string]ToolSpec{
"start_search": {Name: "start_search", RequiredRisk: RiskLow, Category: "search", ReadOnly: true}, "start_search": {Name: "start_search", RequiredRisk: RiskLow, Category: "search", ReadOnly: true},
"get_more_search_results": {Name: "get_more_search_results", RequiredRisk: RiskLow, Category: "search", ReadOnly: true}, "get_more_search_results": {Name: "get_more_search_results", RequiredRisk: RiskLow, Category: "search", ReadOnly: true},
"list_processes": {Name: "list_processes", RequiredRisk: RiskLow, Category: "process", ReadOnly: true}, "list_processes": {Name: "list_processes", RequiredRisk: RiskLow, Category: "process", ReadOnly: true},
"diagnostic_command": {Name: "diagnostic_command", RequiredRisk: RiskLow, Category: "diagnostic", ReadOnly: true},
"list_sessions": {Name: "list_sessions", RequiredRisk: RiskLow, Category: "process", ReadOnly: true}, "list_sessions": {Name: "list_sessions", RequiredRisk: RiskLow, Category: "process", ReadOnly: true},
"read_process_output": {Name: "read_process_output", RequiredRisk: RiskLow, Category: "process", ReadOnly: true}, "read_process_output": {Name: "read_process_output", RequiredRisk: RiskLow, Category: "process", ReadOnly: true},
"edit_block": {Name: "edit_block", RequiredRisk: RiskMedium, Category: "file", ReadOnly: false}, "edit_block": {Name: "edit_block", RequiredRisk: RiskMedium, Category: "file", ReadOnly: false},
@@ -31,7 +32,7 @@ var registry = map[string]ToolSpec{
var actionTools = map[string]string{ var actionTools = map[string]string{
"read": "read_file", "probe": "read_file", "write": "write_file", "read": "read_file", "probe": "read_file", "write": "write_file",
"mcp": "mcp_call", "exec": "exec_command", "mcp": "mcp_call", "exec": "exec_command", "diagnostic": "diagnostic_command",
} }
func Lookup(name string) (ToolSpec, bool) { func Lookup(name string) (ToolSpec, bool) {
+13
View File
@@ -54,6 +54,7 @@ func (p *Panel) Handler() http.Handler {
mux.HandleFunc("/panel/api/mcp/test", p.protected(p.testMCP)) 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", p.protected(p.securitySettings))
mux.HandleFunc("/panel/api/security/settings/update", p.protected(p.updateSecuritySettings)) mux.HandleFunc("/panel/api/security/settings/update", p.protected(p.updateSecuritySettings))
mux.HandleFunc("/panel/api/security/device-credentials/provision", p.protected(p.provisionDeviceCredential))
mux.HandleFunc("/panel/api/notifications/webhooks", p.protected(p.webhookTargets)) 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/update", p.protected(p.updateWebhookTarget))
mux.HandleFunc("/panel/api/notifications/webhook/delete", p.protected(p.deleteWebhookTarget)) mux.HandleFunc("/panel/api/notifications/webhook/delete", p.protected(p.deleteWebhookTarget))
@@ -65,6 +66,7 @@ func (p *Panel) Handler() http.Handler {
type securityPanelRunner interface { type securityPanelRunner interface {
SecuritySettingsJSON(http.ResponseWriter, *http.Request) SecuritySettingsJSON(http.ResponseWriter, *http.Request)
UpdateSecuritySettingsJSON(http.ResponseWriter, *http.Request) UpdateSecuritySettingsJSON(http.ResponseWriter, *http.Request)
ProvisionDeviceCredentialJSON(http.ResponseWriter, *http.Request)
} }
type mcpPanelRunner interface { type mcpPanelRunner interface {
@@ -121,6 +123,17 @@ func (p *Panel) updateSecuritySettings(w http.ResponseWriter, r *http.Request) {
http.Error(w, "security API unavailable", 501) http.Error(w, "security API unavailable", 501)
} }
func (p *Panel) provisionDeviceCredential(w http.ResponseWriter, r *http.Request) {
if p.AdminToken != "" {
r.Header.Set("X-Admin-Token", p.AdminToken)
}
if v, ok := p.Runner.(securityPanelRunner); ok {
v.ProvisionDeviceCredentialJSON(w, r)
return
}
http.Error(w, "security API unavailable", 501)
}
func (p *Panel) testMCP(w http.ResponseWriter, r *http.Request) { func (p *Panel) testMCP(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(mcpPanelRunner); ok { if v, ok := p.Runner.(mcpPanelRunner); ok {
v.TestMCPJSON(w, r) v.TestMCPJSON(w, r)
+19
View File
@@ -213,6 +213,25 @@ $("#mcpTest").onclick=async()=>{
$("#mcpTransport").onchange=()=>{const stdio=$("#mcpTransport").value==="stdio";$("#mcpCommand").parentElement.style.display=stdio?"":"none";$("#mcpArgs").parentElement.style.display=stdio?"":"none";$("#mcpUrl").parentElement.style.display=stdio?"none":""}; $("#mcpTransport").onchange=()=>{const stdio=$("#mcpTransport").value==="stdio";$("#mcpCommand").parentElement.style.display=stdio?"":"none";$("#mcpArgs").parentElement.style.display=stdio?"":"none";$("#mcpUrl").parentElement.style.display=stdio?"none":""};
loadMCPServices().catch(console.error); loadMCPServices().catch(console.error);
async function provisionDeviceCredential(){
const result=$("#deviceProvisionResult");
const status=$("#deviceProvisionStatus");
const name=($("#provisionDeviceName").value||"").trim();
if(!name){status.textContent="请输入节点名称。";return}
try{
const x=await api("/security/device-credentials/provision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device:name})});
$("#deviceProvisionToken").value=x.token||"";
$("#deviceProvisionCommand").value=x.install_command||"";
result.hidden=false;
status.textContent=name+" 接入凭证已生成。安装时把 Token 填入 Agent Token。";
}catch(e){status.textContent="生成失败: "+e.message}
}
$("#deviceProvisionNew").onclick=()=>{$("#deviceProvisionEditor").hidden=false;$("#deviceProvisionResult").hidden=true;$("#deviceProvisionStatus").textContent="";$("#provisionDeviceName").focus()};
$("#deviceProvisionCancel").onclick=()=>{$("#deviceProvisionEditor").hidden=true};
$("#deviceProvisionCreate").onclick=()=>provisionDeviceCredential();
$("#deviceProvisionToken").onclick=e=>e.target.select();
$("#deviceProvisionCommand").onclick=e=>e.target.select();
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 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}} 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); $("#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);
+18 -1
View File
@@ -1,5 +1,22 @@
<!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> <!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"> <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="deviceProvisionNew" type="button">添加设备</button></div>
<div id="deviceProvisionEditor" hidden>
<div class="mcp-form">
<label>节点名称<input id="provisionDeviceName" placeholder="例如 hk-vps-01"></label>
</div>
<div class="mcp-actions">
<button id="deviceProvisionCreate" type="button">生成接入凭证</button>
<button id="deviceProvisionCancel" type="button">取消</button>
</div>
<div id="deviceProvisionStatus" class="mcp-status"></div>
<div id="deviceProvisionResult" hidden>
<label>Agent Token<input id="deviceProvisionToken" readonly></label>
<label>一键安装命令<textarea id="deviceProvisionCommand" readonly></textarea></label>
<p>Token 只在这里明文显示;Hub 仅保存 Token 哈希。</p>
</div>
</div>
</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"> <div class="mcp-toolbar">
<h2>通知</h2> <h2>通知</h2>
<div style="display:flex;gap:8px"> <div style="display:flex;gap:8px">