Compare commits

..
11 Commits
Author SHA1 Message Date
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
22 changed files with 667 additions and 161 deletions
+20 -41
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) TAG="${GITHUB_REF#refs/tags/}"
echo "Previous tag: $PREV_TAG" git fetch --tags --force
PREV_TAG=$(git tag -l "v*" --sort=-v:refname | grep -Fxv "$TAG" | head -n1 || true)
if [[ "${{ github.ref }}" == refs/tags/v* ]]; then echo "tag=$TAG" >> "$GITHUB_OUTPUT"
TAG="${GITHUB_REF#refs/tags/}" {
else echo "### 🚀 What's Changed in ${TAG}"
if [ -z "$PREV_TAG" ]; then echo
TAG="v1.0.0" if [ -n "$PREV_TAG" ]; then
git log "${PREV_TAG}..${TAG}" --pretty=format:"- %s (%h by @kyaring)"
else else
VER_NUM="${PREV_TAG#v}" git log -n 10 --pretty=format:"- %s (%h by @kyaring)"
IFS='.' read -r MAJOR MINOR PATCH <<< "$VER_NUM"
PATCH=$((PATCH + 1))
TAG="v${MAJOR}.${MINOR}.${PATCH}"
fi fi
echo "Auto incremented patch version to $TAG" echo
echo
git config user.name "github-actions[bot]" if [ -n "$PREV_TAG" ]; then
git config user.email "github-actions[bot]@users.noreply.github.com" echo "**Full Changelog**: https://github.com/${{ github.repository }}/compare/${PREV_TAG}...${TAG}"
git tag "$TAG" fi
git push origin "$TAG" } > release_notes.md
fi
echo "tag=$TAG" >> $GITHUB_OUTPUT
# 生成详细的 Release Changelog 正文
cat << NOTES > release_notes.md
### 🚀 What's Changed in ${TAG}
NOTES
if [ -n "$PREV_TAG" ]; then
git log "${PREV_TAG}..HEAD" --pretty=format:"- %s (%h by @kyaring)" >> release_notes.md
else
git log -n 10 --pretty=format:"- %s (%h by @kyaring)" >> release_notes.md
fi
echo "" >> release_notes.md
echo "" >> release_notes.md
if [ -n "$PREV_TAG" ]; then
echo "**Full Changelog**: https://github.com/${{ github.repository }}/compare/${PREV_TAG}...${TAG}" >> release_notes.md
fi
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
+23 -1
View File
@@ -111,7 +111,7 @@ Tool Registry 首先确定操作风险:
## 🤖 当前 MCP 能力 ## 🤖 当前 MCP 能力
目前共 **11 个 MCP Tools**: 目前共 **12 个 MCP Tools**:
| Tool | Risk | 功能 | | Tool | Risk | 功能 |
| :--- | :--- | :--- | | :--- | :--- | :--- |
@@ -177,6 +177,28 @@ Agent 只主动连接 Hub,不需要公网入站端口。
--- ---
## 🚀 一键安装与升级
### 一键安装
```bash
curl -fsSL https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/install.sh | sudo bash
```
安装脚本自动识别 `amd64/arm64` 并进入 Hub / Agent 安装流程。
### 一键升级 Agent
```bash
curl -fsSL https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/upgrade-agent.sh | sudo bash
```
升级脚本下载目标 Release、校验文件大小、备份旧版本并在启动失败时自动回滚。
生产环境的 Agent 凭据以独立设备凭据为准;不要将 Cluster Secret 作为长期生产凭据重新启用。
---
## 📄 文档索引 ## 📄 文档索引
- [文档基线与全局索引](docs/DOCUMENTATION_BASELINE_20261002.md) - [文档基线与全局索引](docs/DOCUMENTATION_BASELINE_20261002.md)
+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":
+8
View File
@@ -70,6 +70,7 @@ func main() {
AdminToken: adminToken, AdminToken: adminToken,
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 +122,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)
+62 -18
View File
@@ -47,9 +47,53 @@ chmod 0600 /etc/vps-commander/agent.env
--- ---
## 三、Hub 服务端部署步骤 ## 三、一键安装与升级
### 3.1 编译 ### 3.1 一键安装
```bash
curl -fsSL https://raw.githubusercontent.com/kyaring/vps-commander/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://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/upgrade-agent.sh | sudo bash
```
升级流程:
```text
下载 Release
↓
临时文件完整性检查
↓
备份当前 Agent
↓
原子替换
↓
systemd restart
↓
健康检查
├─ 成功 → 删除备份
└─ 失败 → 自动恢复旧版本
```
### 3.3 手工安装
如果需要固定版本、离线部署或灰度验证,再使用下面的手工安装流程。
---
## 四、Hub 服务端部署步骤
### 4.1 编译
```bash ```bash
cd /root/.openclaw/workspace/vps-commander cd /root/.openclaw/workspace/vps-commander
go test ./... go test ./...
@@ -65,13 +109,13 @@ vcs.modified=false
vcs.revision=<release commit> vcs.revision=<release commit>
``` ```
### 3.2 安装 ### 4.2 安装
```bash ```bash
install -d -m 0750 /opt/vps-commander/data /etc/vps-commander 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 install -m 0755 bin/vps-commander-hub-linux-amd64 /opt/vps-commander/vps-commander-hub
``` ```
### 3.3 配置 ### 4.3 配置
```bash ```bash
cat << 'ENV' > /etc/vps-commander/hub.env cat << 'ENV' > /etc/vps-commander/hub.env
VPS_COMMANDER_API_KEY=your_secure_api_key VPS_COMMANDER_API_KEY=your_secure_api_key
@@ -80,7 +124,7 @@ ENV
chmod 0600 /etc/vps-commander/hub.env chmod 0600 /etc/vps-commander/hub.env
``` ```
### 3.4 Systemd ### 4.4 Systemd
```ini ```ini
[Service] [Service]
EnvironmentFile=-/etc/vps-commander/hub.env EnvironmentFile=-/etc/vps-commander/hub.env
@@ -89,7 +133,7 @@ Restart=always
RestartSec=3s RestartSec=3s
``` ```
### 3.5 启动 ### 4.5 启动
```bash ```bash
systemctl daemon-reload systemctl daemon-reload
systemctl enable --now vps-commander-hub systemctl enable --now vps-commander-hub
@@ -98,15 +142,15 @@ systemctl status vps-commander-hub
--- ---
## 四、远程 Agent 节点部署步骤 ## 五、远程 Agent 节点部署步骤
### 4.1 安装二进制 ### 5.1 安装二进制
```bash ```bash
install -d -m 0750 /etc/vps-commander /opt/vps-commander install -d -m 0750 /etc/vps-commander /opt/vps-commander
install -m 0755 vps-commander-agent-linux-amd64 /opt/vps-commander/vps-commander-agent install -m 0755 vps-commander-agent-linux-amd64 /opt/vps-commander/vps-commander-agent
``` ```
### 4.2 配置 ### 5.2 配置
```bash ```bash
cat << 'ENV' > /etc/vps-commander/agent.env cat << 'ENV' > /etc/vps-commander/agent.env
VPS_COMMANDER_HUB_WS_URL=wss://vpstool.kory.kdns.fr/agent/ws VPS_COMMANDER_HUB_WS_URL=wss://vpstool.kory.kdns.fr/agent/ws
@@ -116,7 +160,7 @@ ENV
chmod 0600 /etc/vps-commander/agent.env chmod 0600 /etc/vps-commander/agent.env
``` ```
### 4.3 Systemd ### 5.3 Systemd
```ini ```ini
[Service] [Service]
EnvironmentFile=-/etc/vps-commander/agent.env EnvironmentFile=-/etc/vps-commander/agent.env
@@ -127,7 +171,7 @@ RestartSec=3s
当前 v2.0 生产迁移阶段可兼容显式 token;v2.1 发布后必须改为不出现在 ExecStart 的方式。 当前 v2.0 生产迁移阶段可兼容显式 token;v2.1 发布后必须改为不出现在 ExecStart 的方式。
### 4.4 启动 ### 5.4 启动
```bash ```bash
systemctl daemon-reload systemctl daemon-reload
systemctl enable --now vps-commander-agent systemctl enable --now vps-commander-agent
@@ -138,24 +182,24 @@ Agent 启动后主动连接 Hub,并在设备列表中显示为 `online`。
--- ---
## 五、控制面板与 MCP 使用 ## 六、控制面板与 MCP 使用
### 5.1 管理面板 ### 6.1 管理面板
`https://vpstool.kory.kdns.fr/panel/login` `https://vpstool.kory.kdns.fr/panel/login`
面板包含设备状态、安全策略、操作控制、审计和相关管理功能。 面板包含设备状态、安全策略、操作控制、审计和相关管理功能。
### 5.2 MCP ### 6.2 MCP
远程入口: 远程入口:
`https://vpstool.kory.kdns.fr/mcp/sse` `https://vpstool.kory.kdns.fr/mcp/sse`
本地 stdio 使用 `vps-commander-mcp-stdio`。 本地 stdio 使用 `vps-commander-mcp-stdio`。
当前共 11 个 MCP tools,详见 `docs/MCP_INTEGRATION.md`。 当前共 12 个 MCP tools,详见 `docs/MCP_INTEGRATION.md`。
--- ---
## 六、生产升级流程 ## 七、生产升级流程
```text ```text
Backup Backup
@@ -177,7 +221,7 @@ Full Acceptance
--- ---
## 七、日常运维检查 ## 八、日常运维检查
```bash ```bash
systemctl status vps-commander-hub systemctl status vps-commander-hub
@@ -189,7 +233,7 @@ curl -fsS http://127.0.0.1:9521/healthz
--- ---
## 八、当前生产审计提示 ## 九、当前生产审计提示
2026-10-02 审计发现生产 Hub / Agent 曾由 `vcs.modified=true` 的工作树构建。 2026-10-02 审计发现生产 Hub / Agent 曾由 `vcs.modified=true` 的工作树构建。
因此生产现场二进制不能直接视为当前 HEAD 的可复现产物。 因此生产现场二进制不能直接视为当前 HEAD 的可复现产物。
+62 -28
View File
@@ -8,6 +8,7 @@ REPO="kyaring/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" GITHUB_URL="https://github.com"
API_URL="https://api.github.com"
# 颜色输出 # 颜色输出
RED='\033[0;31m' RED='\033[0;31m'
@@ -37,21 +38,62 @@ 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 "无法从 GitHub 获取最新正式 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 "${GITHUB_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 https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/install.sh | 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}
} }
@@ -60,27 +102,26 @@ install_agent() {
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="${GITHUB_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"
@@ -125,31 +166,25 @@ install_hub() {
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="${GITHUB_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=***
ENV ENV
chmod 0600 "${CONF_DIR}/hub.env" chmod 0600 "${CONF_DIR}/hub.env"
@@ -185,7 +220,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}"
+31 -37
View File
@@ -1,5 +1,5 @@
#!/bin/bash #!/bin/bash
set -e set -euo pipefail
# VPS-Commander Agent 一键安全升级脚本 # VPS-Commander Agent 一键安全升级脚本
# Repo: https://github.com/kyaring/vps-commander # Repo: https://github.com/kyaring/vps-commander
@@ -7,28 +7,19 @@ set -e
REPO="kyaring/vps-commander" REPO="kyaring/vps-commander"
INSTALL_DIR="/opt/vps-commander" INSTALL_DIR="/opt/vps-commander"
GITHUB_URL="https://github.com" GITHUB_URL="https://github.com"
API_URL="https://api.github.com"
# 颜色输出 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 "无法从 GitHub 获取最新正式 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="${GITHUB_URL}/${REPO}/releases/download/${LATEST_TAG}/${BIN_NAME}"
TMP_BIN="${INSTALL_DIR}/vps-commander-agent.tmp" CHECKSUM_URL="${GITHUB_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
+4 -1
View File
@@ -88,6 +88,7 @@ Agent 返回结果后,Hub 完成审计并将结果返回 HTTP/MCP 调用方。
| :--- | :--- | | :--- | :--- |
| Low | read_file、read_multiple_files、list_directory、file_info、search、list_processes | | Low | read_file、read_multiple_files、list_directory、file_info、search、list_processes |
| Medium | edit_block、write_file、create_directory、move_file、mcp_call | | 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 | | High | exec_command、start_process、interact_with_process、kill_process、force_terminate |
### 4.3 Policy Snapshot ### 4.3 Policy Snapshot
@@ -121,7 +122,7 @@ kill / terminate 使用 Session 内部进程句柄,不接受客户端任意 PI
## 六、MCP 架构 ## 六、MCP 架构
当前 MCP 共 11 个工具: 当前 MCP 共 12 个工具:
1. `list_devices` 1. `list_devices`
2. `exec_command` 2. `exec_command`
3. `read_file` 3. `read_file`
@@ -129,6 +130,8 @@ kill / terminate 使用 Session 内部进程句柄,不接受客户端任意 PI
5. `create_directory` 5. `create_directory`
6. `move_file` 6. `move_file`
7. `list_processes` 7. `list_processes`
8. `diagnostic_command`:严格白名单的只读系统诊断;
8. `edit_block` 8. `edit_block`
9. `write_file` 9. `write_file`
10. `list_agent_mcp` 10. `list_agent_mcp`
+1 -1
View File
@@ -86,7 +86,7 @@ Hub 根据 Credential 建立 Canonical Device Identity。
Server version:`1.2.0`。 Server version:`1.2.0`。
Protocol Version:`2024-11-05`。 Protocol Version:`2024-11-05`。
当前工具共 11 个: 当前工具共 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`。 `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:legacy HTTP + SSE。
+1 -1
View File
@@ -40,7 +40,7 @@ VPS-Commander 是自托管、多节点、AI Agent 友好的 Linux 运维控制
## 三、当前 MCP 基线 ## 三、当前 MCP 基线
11 个工具: 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`。 `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。 远程:legacy SSE。
@@ -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 无关,是独立的协议兼容性问题。
- 决策前不要动生产端点。
+33 -2
View File
@@ -20,7 +20,7 @@ VPS-Commander 当前提供两种 MCP 接入模式:
--- ---
## 二、当前支持的 11 大 MCP Tools ## 二、当前支持的 12 大 MCP Tools
| Tool 名称 | 风险等级 | 参数/功能说明 | | Tool 名称 | 风险等级 | 参数/功能说明 |
| :--- | :--- | :--- | | :--- | :--- | :--- |
@@ -31,6 +31,7 @@ VPS-Commander 当前提供两种 MCP 接入模式:
| `create_directory` | Medium | 创建目录 | | `create_directory` | Medium | 创建目录 |
| `move_file` | Medium | 移动/重命名文件 | | `move_file` | Medium | 移动/重命名文件 |
| `list_processes` | Low | 查看进程 | | `list_processes` | Low | 查看进程 |
| `diagnostic_command` | Low | 严格白名单只读诊断,不接受任意 Shell |
| `edit_block` | Medium | 唯一匹配 + 原子写回 | | `edit_block` | Medium | 唯一匹配 + 原子写回 |
| `write_file` | Medium | 创建或覆写文件 | | `write_file` | Medium | 创建或覆写文件 |
| `list_agent_mcp` | Low | 查询 Agent MCP 服务 | | `list_agent_mcp` | Low | 查询 Agent MCP 服务 |
@@ -145,6 +146,12 @@ API Key 不应提交到 Git 仓库。
### 6.6 list_processes ### 6.6 list_processes
- `device` 可选。 - `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 ### 6.7 edit_block
- `device`、`path`、`old_text`、`new_text`。 - `device`、`path`、`old_text`、`new_text`。
- `old_text` 必须唯一匹配。 - `old_text` 必须唯一匹配。
@@ -162,7 +169,31 @@ API Key 不应提交到 Git 仓库。
--- ---
## 七、Agent MCP ## 七、一键安装与升级
### 7.1 一键安装
仓库已经提供统一安装脚本,支持 Linux `amd64` 与 `arm64`,安装时自动识别架构并从 GitHub Release 获取对应二进制。
```bash
curl -fsSL https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/install.sh | sudo bash
```
脚本会进入交互式安装流程,可选择 Hub 或 Agent。生产环境使用时,Agent 应使用独立设备凭据,不应重新启用全局 Shared Secret。
### 7.2 一键升级 Agent
```bash
curl -fsSL https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/upgrade-agent.sh | sudo bash
```
升级采用临时文件下载 → 基础完整性检查 → 旧二进制备份 → 原子替换 → systemd 重启 → 健康检查;启动失败时自动回滚旧版本。
> Hub 的生产升级建议继续采用滚动发布:先完成 Release 与构建校验,再替换 Hub,确认节点重新上线后再继续后续节点。避免把 Hub 升级做成无保护的“一键重启”。
---
## 八、Agent MCP
Hub 可以发现远程 Agent 暴露的 MCP Service。 Hub 可以发现远程 Agent 暴露的 MCP Service。
+1 -1
View File
@@ -28,7 +28,7 @@
## 二、MCP 当前能力 ## 二、MCP 当前能力
当前共 11 个 Tools: 当前共 12 个 Tools:
1. `list_devices` 1. `list_devices`
2. `exec_command` 2. `exec_command`
3. `read_file` 3. `read_file`
+101 -28
View File
@@ -49,6 +49,7 @@ type Server struct {
AdminToken string AdminToken string
ExecLimiter chan struct{} ExecLimiter chan struct{}
SearchLimiter chan struct{} SearchLimiter chan struct{}
LocalSessions *executor.SessionManager
} }
const ( const (
@@ -782,9 +783,13 @@ 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"`
RingCapacity int `json:"ring_capacity"` Command string `json:"command"`
Workdir string `json:"workdir"`
Data string `json:"data"`
Force bool `json:"force"`
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 {
http.Error(w, "bad json", 400) http.Error(w, "bad json", 400)
@@ -796,38 +801,106 @@ 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
switch action { if s.isRemote(req.Device) {
case "start": if s.Cluster == nil || !s.Cluster.Online(req.Device) {
if req.SessionID == "" { http.Error(w, "device offline", 409)
req.SessionID, err = newSessionID() return
if err != nil { }
http.Error(w, "session id generation failed", 500) switch action {
return case "start":
if req.SessionID == "" {
req.SessionID, err = newSessionID()
if err != nil {
http.Error(w, "session id generation failed", 500)
return
}
} }
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":
result, err = s.Cluster.ReadProcessOutput(ctx, req.Device, req.SessionID, owner)
case "input":
err = s.Cluster.InteractProcess(ctx, req.Device, req.SessionID, req.Data, owner)
result = map[string]any{"ok": true}
case "stop":
err = s.Cluster.ForceTerminate(ctx, req.Device, req.SessionID, owner)
result = map[string]any{"ok": true}
case "list":
result, err = s.Cluster.ListSessions(ctx, req.Device)
default:
http.Error(w, "unknown action", 400)
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
} }
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})
case "read":
result, err = s.Cluster.ReadProcessOutput(ctx, req.Device, req.SessionID, sessionOwner(r))
case "input":
err = s.Cluster.InteractProcess(ctx, req.Device, req.SessionID, req.Data, sessionOwner(r))
result = map[string]any{"ok": true}
case "stop":
err = s.Cluster.ForceTerminate(ctx, req.Device, req.SessionID, sessionOwner(r))
result = map[string]any{"ok": true}
case "list":
result, err = s.Cluster.ListSessions(ctx, req.Device)
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)
+33
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"))
+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) {