Compare commits
23
Commits
v1.1.7
...
78d3ee6527
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78d3ee6527 | ||
|
|
5551f69b17 | ||
|
|
650dc7186e | ||
|
|
5e6281ae99 | ||
|
|
2a072f9cc9 | ||
|
|
4e016fd3ba | ||
|
|
343708eebe | ||
|
|
583b27fb5c | ||
|
|
cc99022215 | ||
|
|
71a596a556 | ||
|
|
b9f7197ec7 | ||
|
|
9fbb2bd80a | ||
|
|
556870b594 | ||
|
|
38382d2486 | ||
|
|
192969d7f6 | ||
|
|
a5620cb9c4 | ||
|
|
601a0b6e25 | ||
|
|
57c99ac72b | ||
|
|
512e7c91c8 | ||
|
|
2a9d01d7f7 | ||
|
|
7f000b8833 | ||
|
|
6aabc53a68 | ||
|
|
79179c585a |
@@ -2,12 +2,11 @@
|
||||
|
||||
# VPS-Commander
|
||||
|
||||
**面向 AI Agent (ChatGPT / Claude / MCP) 与个人运维的高性能、极轻量、多节点私有基础设施调度中枢**
|
||||
**面向 AI Agent、MCP 与个人运维的高性能、轻量、多节点私有基础设施调度中枢**
|
||||
|
||||
[](https://golang.org)
|
||||
[](LICENSE)
|
||||
[](#)
|
||||
[](#)
|
||||
|
||||
</div>
|
||||
|
||||
@@ -15,210 +14,201 @@
|
||||
|
||||
## 🌟 核心特性
|
||||
|
||||
- ⚡ **极致轻量,极低常驻**:纯 Go 原生编写,静态无依赖编译。Hub 核心管理进程物理常驻内存(RSS)稳定在 **15MB** 左右;受控端 Agent 内存占用仅 **7~11MB**,小内存 VPS 零负担。
|
||||
- 🤖 **原生 AI 友好 (ChatGPT Actions & MCP 双协议)**:
|
||||
- **OpenAPI 3.1.0 标准**:开箱即用支持 ChatGPT Custom GPTs / Claude Actions。
|
||||
- **MCP (Model Context Protocol)**:内置兼容 SSE 与 JSON-RPC 标准,支持 Cursor、Windsurf、Claude Desktop 等客户端。
|
||||
- **OAuth 2.0 / Bearer 认证**:支持公开客户端授权与 Bearer API Key 访问控制。
|
||||
- 🌐 **多节点集群架构 (Hub & Agent)**:
|
||||
- 单中心 Hub 统一管理多台受控 VPS。
|
||||
- 远程 Agent 节点通过标准 WebSocket (WSS) 主动建立安全长连接回连,天然穿透 NAT 与内网,无需受控端暴露端口。
|
||||
- 🛡️ **严格安全防护与权限闭环**:
|
||||
- **零参数泄露**:全面封禁 CLI 敏感传参,凭据由 `0600` 环境变量接管,避免 `/proc/*/cmdline` 泄密。
|
||||
- **完整审计追溯**:内置本地 SQLite 存储,全量记录调用者 IP、下发节点、指令内容、退出码及精确执行耗时。
|
||||
- **执行隔离与超时回收**:内置上下文超时控制,强制清理孤儿进程,彻底杜绝僵尸进程。
|
||||
- 📊 **实时节点资源画像 (Node Profiling & Role)**:
|
||||
- **原生零依赖深度采集**:直接读取 Linux 内核指标,实时监控物理 CPU 核心数与瞬时负载、真实可用内存(`MemAvailable`)与 Swap、根分区磁盘占用、IO 压力指数(内核原生 PSI / Loadavg)及 Docker 守护进程运行状态。
|
||||
- **动态角色标签**:支持节点角色分工(如 `CONTROL` 控制中枢、`APPLICATION` 应用节点、`DATABASE` 等),为 AI Agent 自动化调度部署决策提供全维度实时依据。
|
||||
- 🛡️ **设备生命周期管理与防重连黑名单**:
|
||||
- 支持管理员在 Web 控制台一键注销并强制断开指定受控节点。
|
||||
- 持久化吊销拦截(Revocation List),彻底杜绝被下线 Agent 因 Systemd 自动重启而死灰复燃。
|
||||
- 本地主控节点(Local)强制安全锁,防误操作防护。
|
||||
- 🖥️ **内嵌极简 Web 管理面板**:
|
||||
- 静态单页面(SPA)采用 Go `embed` 完整打包进二进制文件,单文件独立运行,无需安装 Node.js、Nginx 或外部静态资源 CDN。
|
||||
- **工程级双态主题**:纯手绘 SVG 极简几何微图标(太阳/弦月),支持深曜蓝黑与柔和浅灰白一键切换,完美适配系统偏好且零 FOUC 白屏闪烁。
|
||||
- **全端响应式**:彻底适配手机移动端(≤680px),宽表独立触控滑动,长节点名自动断行不穿透。
|
||||
- ⚡ **轻量单体部署**:纯 Go 原生编译,Hub、Agent、MCP stdio 均可独立部署。
|
||||
- 🤖 **原生 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 运行时。
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 架构概览
|
||||
## 🏁 研发最初目标
|
||||
|
||||
VPS-Commander 最初并不是一个简单的远程 Shell 工具,而是为 AI Agent 建立一个**用户自己控制的私有化 Linux 运维控制面**。
|
||||
|
||||
### 1.1 私有化
|
||||
- 运维请求通过用户自己的 Hub 和 VPS 节点完成。
|
||||
- 不依赖第三方运维 Relay。
|
||||
- 凭据、策略和审计数据由用户自己的基础设施控制。
|
||||
|
||||
### 1.2 Host-centric 运维
|
||||
- 全局 Shell。
|
||||
- 全局文件读写。
|
||||
- 进程与长任务 Session。
|
||||
- 远程 Agent MCP。
|
||||
|
||||
### 1.3 多节点统一调度
|
||||
- 一个 Hub 管理多个 VPS。
|
||||
- 使用节点名称选择目标。
|
||||
- 节点离线后保留设备身份与持久化状态。
|
||||
|
||||
### 1.4 AI 原生接口
|
||||
- HTTP API。
|
||||
- MCP。
|
||||
- OpenAPI 契约。
|
||||
- Web 管理面板。
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 当前总体架构
|
||||
|
||||
```text
|
||||
+-----------------------------------+
|
||||
| OpenAI ChatGPT / AI Agents |
|
||||
+-----------------+-----------------+
|
||||
| HTTPS / MCP SSE / WSS
|
||||
+--------------------------------------+
|
||||
| AI / MCP Client / Web Panel |
|
||||
+------------------+-------------------+
|
||||
| HTTPS / MCP / WSS
|
||||
v
|
||||
+-----------------------------------+
|
||||
| 反向代理 / SSL 终止 (Lucky/Nginx)|
|
||||
+-----------------+-----------------+
|
||||
+--------------------------------------+
|
||||
| Reverse Proxy / TLS |
|
||||
+------------------+-------------------+
|
||||
| 127.0.0.1:9521
|
||||
v
|
||||
+-------------------------------------------------------------+
|
||||
+-----------------------------------------------------------+
|
||||
| VPS-Commander Hub |
|
||||
| - OpenAPI 3.1 & MCP 路由引擎 |
|
||||
| - OAuth / Bearer 鉴权与 Session 会话 |
|
||||
| - 本地 SQLite 审计数据库 (commander.db) |
|
||||
| - 内嵌 Web 管理面板 (SPA) |
|
||||
+--------------+-------------------------------+--------------+
|
||||
|-----------------------------------------------------------|
|
||||
| Auth / API / MCP / Web Panel |
|
||||
| Security Snapshot / Tool Registry / Audit |
|
||||
| Cluster Router / Session / Rate Limiter |
|
||||
+----------------------+-------------------+---------------+
|
||||
| |
|
||||
(本地执行通道) (WebSocket RPC 长连接通道)
|
||||
Local Executor Agent WSS
|
||||
| |
|
||||
v v
|
||||
+--------------------+ +--------------------+
|
||||
| 宿主机 (Local) | | 受控 VPS (Agent) |
|
||||
| uname / sh / 文件 | | vps-commander-a |
|
||||
+--------------------+ +--------------------+
|
||||
Hub 本机 Remote VPS
|
||||
|
|
||||
Host Executor
|
||||
File / Shell / Process
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 极速一键部署与平滑升级
|
||||
## 🔐 当前安全模型
|
||||
|
||||
### 1. 一键全自动安装 (推荐)
|
||||
无论是在受控端 VPS 还是中心端,只需一行命令即可交互式安装与启动:
|
||||
### 1. Client Authentication
|
||||
`Authorization: Bearer <API_KEY>` 是 HTTP / MCP 的主要客户端认证方式。
|
||||
|
||||
```bash
|
||||
bash <(curl -fsSLk https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/install.sh)
|
||||
```
|
||||
- **安装 Agent (受控 VPS)**:输入 Hub 的 WSS 地址与通信密钥,全自动配置开机自启并秒级连入集群。
|
||||
- **安装 Hub (中心服务端)**:自动生成安全 API Key / Web 面板密码并以 Systemd 托管常驻。
|
||||
### 2. Agent Authentication
|
||||
每个 Agent 使用独立的 `VPS_COMMANDER_AGENT_TOKEN`。
|
||||
Hub SQLite 只保存 Credential Hash,不保存明文 Token。
|
||||
|
||||
### 2. 受控端 Agent 一键平滑升级 (免重输配置)
|
||||
当新版本发布后,无需重新配置通信密钥或重新安装,在任意受控机上直接运行升级脚本:
|
||||
### 3. Authorization
|
||||
Tool Registry 首先确定操作风险:
|
||||
|
||||
```bash
|
||||
curl -fsSLk https://raw.githubusercontent.com/kyaring/vps-commander/main/deploy/upgrade-agent.sh | bash
|
||||
```
|
||||
- 自动检测并拉取 GitHub 最新版本架构包(AMD64 / ARM64);
|
||||
- 自动备份旧版本二进制(`.bak`);
|
||||
- 升级异常(校验失败或无法启动)时**自动秒级回滚**,保证节点永不失联。
|
||||
| 风险 | 典型能力 |
|
||||
| :--- | :--- |
|
||||
| Low | 读取、搜索、设备/进程观察 |
|
||||
| Medium | 文件修改、目录创建/移动、Agent MCP |
|
||||
| High | Shell、进程启动、交互、终止 |
|
||||
|
||||
未知设备、未知身份或策略无法解析时不得获得 High 权限。
|
||||
|
||||
### 4. Shared Secret
|
||||
生产环境已经关闭 Cluster Secret / Shared Secret fallback。
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ 手动编译部署
|
||||
## 🤖 当前 MCP 能力
|
||||
|
||||
### 1. Hub 服务端部署
|
||||
目前共 **12 个 MCP Tools**:
|
||||
|
||||
在中心管理机上部署 Hub:
|
||||
|
||||
```bash
|
||||
# 1. 编译二进制
|
||||
make linux-amd64
|
||||
|
||||
# 2. 安装二进制文件
|
||||
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
|
||||
|
||||
# 3. 创建环境变量配置 (注意保护权限)
|
||||
cat << 'ENV' > /etc/vps-commander/hub.env
|
||||
VPS_COMMANDER_API_KEY=your_secure_api_key_here
|
||||
VPS_COMMANDER_CLUSTER_SECRET=your_cluster_sync_secret_here
|
||||
VPS_COMMANDER_WEB_PASSWORD=your_web_panel_password_here
|
||||
ENV
|
||||
chmod 0600 /etc/vps-commander/hub.env
|
||||
|
||||
# 4. 配置并启动 Systemd 服务
|
||||
cp deploy/vps-commander-hub.service /etc/systemd/system/
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now vps-commander-hub
|
||||
```
|
||||
|
||||
### 2. 远程 VPS Agent 受控端部署
|
||||
|
||||
在需要受控的远程 VPS 机器上执行:
|
||||
|
||||
```bash
|
||||
# 1. 下载或拷贝 agent 二进制至远程机器
|
||||
install -d -m 0750 /etc/vps-commander /opt/vps-commander
|
||||
install -m 0755 vps-commander-agent-linux-amd64 /opt/vps-commander/vps-commander-agent
|
||||
|
||||
# 2. 配置 Agent 环境变量
|
||||
cat << 'ENV' > /etc/vps-commander/agent.env
|
||||
VPS_COMMANDER_HUB_WS_URL=wss://your-domain.com/agent/ws
|
||||
VPS_COMMANDER_AGENT_NAME=vps-us-node01
|
||||
VPS_COMMANDER_CLUSTER_SECRET=your_cluster_sync_secret_here
|
||||
ENV
|
||||
chmod 0600 /etc/vps-commander/agent.env
|
||||
|
||||
# 3. 配置并启动 Systemd 服务
|
||||
cp deploy/vps-commander-agent.service /etc/systemd/system/
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now vps-commander-agent
|
||||
```
|
||||
Agent 启动后会通过 WSS 自动连入 Hub,在 Hub 管理面板与 `/api/v1/devices` 接口中实时显示为 `online`。
|
||||
|
||||
---
|
||||
|
||||
## 🤖 接入 ChatGPT (新版插件 Apps & MCP 模式)
|
||||
|
||||
当前 ChatGPT 已升级为以 **插件 / 应用 (Apps & MCP)** 规范连接外部服务。VPS-Commander 原生内置完整的 **MCP SSE + OAuth2** 协议支持,无需部署额外适配层。
|
||||
|
||||
### 接入配置步骤:
|
||||
|
||||
1. **进入 ChatGPT 插件/应用配置页**:
|
||||
- 打开 ChatGPT -> **Settings (设置)** -> **Apps & Integrations (应用与集成) / Plugins** -> **Create / Add App (添加应用)**。
|
||||
2. **连接方式选择 MCP**:
|
||||
- 连接协议选择 **MCP (Model Context Protocol)** 或 **Server-Sent Events (SSE)**。
|
||||
- **MCP Server URL**:填入 Hub 的 SSE 统一入口:
|
||||
```text
|
||||
https://your-domain.com/mcp/sse
|
||||
```
|
||||
3. **身份认证 (Authentication)**:
|
||||
- **方式 A (OAuth 2.0 自动授权,推荐)**:
|
||||
- Hub 内置了标准 RFC 8414 OAuth Metadata (`/.well-known/oauth-authorization-server`);
|
||||
- 授权端点与 Token 端点由 ChatGPT 自动识别,一键点击「Authorize」即可完成免密安全绑定。
|
||||
- **方式 B (Bearer API Key)**:
|
||||
- 若选择 API Key,填入 Hub 环境变量 `VPS_COMMANDER_API_KEY` 即可。
|
||||
4. **自动发现 4 大运维工具**:
|
||||
- 握手成功后,ChatGPT 会自动加载并列出 4 个原生运维工具:
|
||||
- `list_devices`:列出受控节点、CPU/内存/磁盘剩余绝对值及 Docker 状态;
|
||||
- `exec_command`:在目标机器(如 `m4-live-agent`)执行 Shell 指令;
|
||||
- `read_file`:分页读取目标文件;
|
||||
- `write_file`:远程编辑或创建文件。
|
||||
|
||||
---
|
||||
|
||||
### 传统客户端支持 (Claude Desktop / Cursor / VS Code)
|
||||
|
||||
支持通过本地 stdio 二进制连接 Hub:
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"vps-commander": {
|
||||
"command": "/path/to/vps-commander-mcp-stdio-linux-amd64",
|
||||
"args": [
|
||||
"-hub", "https://your-domain.com",
|
||||
"-key", "YOUR_API_KEY"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 接口与能力一览
|
||||
|
||||
| 接口路径 | 方法 | 功能描述 |
|
||||
| Tool | Risk | 功能 |
|
||||
| :--- | :--- | :--- |
|
||||
| `/api/v1/devices` | `GET` | 列出集群中所有受控设备状态与**实时资源画像 (CPU/Mem/Disk/IO PSI/Docker/Role)** |
|
||||
| `/panel/api/devices` | `DELETE` | 【管理员】注销并踢出指定受控节点,持久化写入防重连黑名单 |
|
||||
| `/api/v1/exec` | `POST` | 在指定受控节点执行任意 Shell 指令(支持超时截断) |
|
||||
| `/api/v1/file/read` | `POST` | 安全分页读取目标机器上的文件内容(防内存溢出) |
|
||||
| `/api/v1/file/write` | `POST` | 向目标机器指定路径覆写或创建文件 |
|
||||
| `/mcp/sse` | `GET` | MCP 协议长连接事件流通道 |
|
||||
| `/panel/login` | `GET/POST`| 内嵌 Web 运维管理控制台 |
|
||||
| `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://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 作为长期生产凭据重新启用。
|
||||
|
||||
---
|
||||
|
||||
## 📄 文档索引
|
||||
|
||||
- [生产部署指南与运维手册](deploy/README.md)
|
||||
- [系统架构与安全设计说明](docs/ARCHITECTURE.md)
|
||||
- [研发设计规范与内存基线](docs/DEV_SPEC.md)
|
||||
- [阶段验收标准与门禁用例矩阵](docs/ACCEPTANCE_CRITERIA.md)
|
||||
- [MCP 客户端接入协议文档](docs/MCP_INTEGRATION.md)
|
||||
- [文档基线与全局索引](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)
|
||||
|
||||
---
|
||||
|
||||
|
||||
+229
-7
@@ -10,6 +10,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -22,7 +23,7 @@ import (
|
||||
func main() {
|
||||
hub := flag.String("hub", "", "Hub WebSocket URL")
|
||||
name := flag.String("name", "", "device name")
|
||||
token := flag.String("token", os.Getenv("VPS_COMMANDER_CLUSTER_SECRET"), "cluster secret")
|
||||
token := flag.String("token", firstNonEmpty(os.Getenv("VPS_COMMANDER_AGENT_TOKEN"), os.Getenv("VPS_COMMANDER_CLUSTER_SECRET")), "agent credential")
|
||||
insecure := flag.Bool("insecure", false, "skip TLS verification")
|
||||
flag.Parse()
|
||||
if *hub == "" || *name == "" || *token == "" {
|
||||
@@ -69,10 +70,11 @@ func run(hub, name, token string, insecure bool) error {
|
||||
return err
|
||||
}
|
||||
exec := executor.Local{MaxOutput: 1024 * 1024}
|
||||
mcpRuntime := cluster.NewMCPRuntime()
|
||||
|
||||
// 初始握手附带画像
|
||||
initProf := sysinfo.Collect("APPLICATION")
|
||||
if err := writeJSON(cluster.Message{Event: "hello", Device: name, Profile: &initProf, TS: time.Now().Unix()}); err != nil {
|
||||
if err := writeJSON(cluster.Message{Event: "hello", Device: name, Arch: runtime.GOARCH, OS: runtime.GOOS, Profile: &initProf, TS: time.Now().Unix(), ProtocolVersion: "2", AgentVersion: "2.0", Capabilities: []string{"read_file", "read_multiple_files", "list_directory", "get_file_info", "start_search", "get_more_search_results", "list_processes", "list_sessions", "read_process_output", "edit_block", "write_file", "create_directory", "move_file", "exec_command", "start_process", "interact_with_process", "kill_process", "force_terminate", "mcp_call", "mcp_list", "mcp_test"}}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -85,7 +87,21 @@ func run(hub, name, token string, insecure bool) error {
|
||||
select {
|
||||
case <-t.C:
|
||||
prof := sysinfo.Collect("APPLICATION")
|
||||
_ = writeJSON(cluster.Message{Event: "ping", Device: name, Profile: &prof, TS: time.Now().Unix()})
|
||||
_ = writeJSON(cluster.Message{Event: "ping", Device: name, Arch: runtime.GOARCH, OS: runtime.GOOS, Profile: &prof, TS: time.Now().Unix()})
|
||||
case <-stopPing:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
sessions := executor.NewSessionManager(16)
|
||||
go func() {
|
||||
t := time.NewTicker(1 * time.Minute)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-t.C:
|
||||
sessions.Cleanup()
|
||||
case <-stopPing:
|
||||
return
|
||||
}
|
||||
@@ -101,13 +117,23 @@ func run(hub, name, token string, insecure bool) error {
|
||||
if msg.Event == "registered" {
|
||||
continue
|
||||
}
|
||||
if msg.Event == "mcp_sync" {
|
||||
var services []cluster.MCPService
|
||||
if err := decodePayload(msg.Payload, &services); err != nil {
|
||||
log.Printf("mcp sync failed: %v", err)
|
||||
} else {
|
||||
mcpRuntime.Sync(services)
|
||||
log.Printf("MCP services synced: %d", len(services))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if msg.Event == "revoked" {
|
||||
log.Printf("device revoked by admin: %s", msg.Error)
|
||||
return errors.New("revoked by admin")
|
||||
}
|
||||
if msg.Event == "ping" {
|
||||
prof := sysinfo.Collect("APPLICATION")
|
||||
if err := writeJSON(cluster.Message{Event: "pong", Device: name, Profile: &prof, TS: msg.TS}); err != nil {
|
||||
if err := writeJSON(cluster.Message{Event: "pong", Device: name, Arch: runtime.GOARCH, OS: runtime.GOOS, Profile: &prof, TS: msg.TS}); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
@@ -116,16 +142,193 @@ func run(hub, name, token string, insecure bool) error {
|
||||
continue
|
||||
}
|
||||
go func(msg cluster.Message) {
|
||||
if err := handle(writeJSON, exec, msg); err != nil {
|
||||
if err := handle(writeJSON, exec, mcpRuntime, sessions, msg); err != nil {
|
||||
log.Printf("request %s failed: %v", msg.ID, err)
|
||||
_ = c.Close()
|
||||
_ = sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
}(msg)
|
||||
}
|
||||
}
|
||||
|
||||
func handle(writeJSON func(cluster.Message) error, exec executor.Local, msg cluster.Message) error {
|
||||
func handle(writeJSON func(cluster.Message) error, exec executor.Local, mcpRuntime *cluster.MCPRuntime, sessions *executor.SessionManager, msg cluster.Message) error {
|
||||
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":
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: mcpRuntime.List()})
|
||||
case "mcp_test":
|
||||
var p cluster.MCPService
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
tools, err := cluster.ProbeMCP(ctx, p)
|
||||
duration := time.Since(start).Milliseconds()
|
||||
if err != nil {
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "error", Error: err.Error(), Payload: map[string]any{"duration_ms": duration}})
|
||||
}
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: tools})
|
||||
case "mcp_call":
|
||||
var p struct {
|
||||
Server string `json:"server"`
|
||||
Tool string `json:"tool"`
|
||||
Args any `json:"args"`
|
||||
}
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
if p.Server == "" || p.Tool == "" {
|
||||
return sendError(writeJSON, msg.ID, errors.New("server and tool required"))
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
result, err := mcpRuntime.Call(ctx, p.Server, p.Tool, p.Args)
|
||||
duration := time.Since(start).Milliseconds()
|
||||
if err != nil {
|
||||
_ = writeJSON(cluster.Message{ID: msg.ID, Status: "error", Error: err.Error(), Payload: map[string]any{"server": p.Server, "tool": p.Tool, "duration_ms": duration}})
|
||||
return nil
|
||||
}
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: map[string]any{"server": p.Server, "tool": p.Tool, "result": result, "duration_ms": duration}})
|
||||
case "start_process":
|
||||
var p cluster.StartProcessPayload
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
if p.SessionID == "" || p.Command == "" {
|
||||
return sendError(writeJSON, msg.ID, errors.New("session_id and command required"))
|
||||
}
|
||||
s, err := sessions.Start(context.Background(), p.SessionID, p.Command, p.Workdir, p.Owner, p.RingCapacity)
|
||||
if err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: map[string]any{"session_id": s.ID, "started_at": s.StartedAt.Unix()}})
|
||||
case "read_process_output":
|
||||
var p struct {
|
||||
SessionID string `json:"session_id"`
|
||||
Owner string `json:"owner"`
|
||||
}
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
s, ok := sessions.Get(p.SessionID)
|
||||
if !ok {
|
||||
return sendError(writeJSON, msg.ID, errors.New("session not found"))
|
||||
}
|
||||
if !s.Authorized(p.Owner) {
|
||||
return sendError(writeJSON, msg.ID, errors.New("session ownership denied"))
|
||||
}
|
||||
code, done, _ := s.Status()
|
||||
out, errout := s.Output()
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: cluster.ProcessOutputPayload{SessionID: p.SessionID, Stdout: out, Stderr: errout, ExitCode: code, Running: !done}})
|
||||
case "interact_with_process":
|
||||
var p cluster.ProcessInputPayload
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
s, ok := sessions.Get(p.SessionID)
|
||||
if !ok {
|
||||
return sendError(writeJSON, msg.ID, errors.New("session not found"))
|
||||
}
|
||||
if !s.Authorized(p.Owner) {
|
||||
return sendError(writeJSON, msg.ID, errors.New("session ownership denied"))
|
||||
}
|
||||
if err := s.Stdin([]byte(p.Data)); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success"})
|
||||
case "force_terminate":
|
||||
var p struct {
|
||||
SessionID string `json:"session_id"`
|
||||
Owner string `json:"owner"`
|
||||
}
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
ss, ok := sessions.Get(p.SessionID)
|
||||
if !ok {
|
||||
return sendError(writeJSON, msg.ID, errors.New("session not found"))
|
||||
}
|
||||
if !ss.Authorized(p.Owner) {
|
||||
return sendError(writeJSON, msg.ID, errors.New("session ownership denied"))
|
||||
}
|
||||
if err := sessions.Stop(p.SessionID, true); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success"})
|
||||
case "list_sessions":
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: sessions.List()})
|
||||
case "read_multiple_files":
|
||||
var p cluster.ReadMultipleFilesPayload
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: executor.ReadMultipleFiles(p.Paths, p.Limit)})
|
||||
case "create_directory":
|
||||
var p cluster.CreateDirectoryPayload
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
if err := executor.CreateDirectory(p.Path); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success"})
|
||||
case "move_file":
|
||||
var p cluster.MoveFilePayload
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
if err := executor.MoveFile(p.Source, p.Destination); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success"})
|
||||
case "list_processes":
|
||||
v, err := executor.ListProcesses()
|
||||
if err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: v})
|
||||
case "list_directory":
|
||||
var p cluster.ListDirectoryPayload
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
v, err := executor.ListDirectory(p.Path, p.Recursive, p.MaxEntries)
|
||||
if err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: v})
|
||||
case "get_file_info":
|
||||
var p cluster.FileInfoPayload
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
v, err := executor.GetFileInfo(p.Path)
|
||||
if err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: v})
|
||||
case "start_search":
|
||||
var p cluster.SearchPayload
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
v, err := executor.Search(context.Background(), p.Root, p.Query, p.MaxResults)
|
||||
if err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: v})
|
||||
case "exec":
|
||||
var p cluster.ExecPayload
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
@@ -173,6 +376,16 @@ func handle(writeJSON func(cluster.Message) error, exec executor.Local, msg clus
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: map[string]any{"content": string(buf[:n]), "bytes": n, "total_size": info.Size(), "has_more": p.Offset+int64(n) < info.Size(), "eof": eof}})
|
||||
case "edit_block":
|
||||
var p cluster.EditBlockPayload
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
res, err := executor.EditBlock(p.Path, p.OldText, p.NewText)
|
||||
if err != nil {
|
||||
return sendError(writeJSON, msg.ID, err)
|
||||
}
|
||||
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: res})
|
||||
case "file_write":
|
||||
var p cluster.FileWritePayload
|
||||
if err := decodePayload(msg.Payload, &p); err != nil {
|
||||
@@ -201,3 +414,12 @@ func decodePayload(v any, out any) error {
|
||||
func sendError(writeJSON func(cluster.Message) error, id string, err error) error {
|
||||
return writeJSON(cluster.Message{ID: id, Status: "error", Error: err.Error()})
|
||||
}
|
||||
|
||||
func firstNonEmpty(vs ...string) string {
|
||||
for _, v := range vs {
|
||||
if v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
+26
-3
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/wjyhk/vps-commander/internal/cluster"
|
||||
"github.com/wjyhk/vps-commander/internal/executor"
|
||||
"github.com/wjyhk/vps-commander/internal/mcp"
|
||||
"github.com/wjyhk/vps-commander/internal/notify"
|
||||
"github.com/wjyhk/vps-commander/internal/storage"
|
||||
)
|
||||
|
||||
@@ -36,8 +37,12 @@ func main() {
|
||||
apiKey := os.Getenv("VPS_COMMANDER_API_KEY")
|
||||
clusterSecret := os.Getenv("VPS_COMMANDER_CLUSTER_SECRET")
|
||||
webPassword := os.Getenv("VPS_COMMANDER_WEB_PASSWORD")
|
||||
if apiKey == "" || clusterSecret == "" || webPassword == "" {
|
||||
log.Fatal("VPS_COMMANDER_API_KEY, VPS_COMMANDER_CLUSTER_SECRET and VPS_COMMANDER_WEB_PASSWORD are required via environment")
|
||||
adminToken := os.Getenv("VPS_COMMANDER_ADMIN_TOKEN")
|
||||
if adminToken == "" {
|
||||
adminToken = webPassword
|
||||
}
|
||||
if apiKey == "" || webPassword == "" {
|
||||
log.Fatal("VPS_COMMANDER_API_KEY and VPS_COMMANDER_WEB_PASSWORD are required via environment")
|
||||
}
|
||||
authManager := auth.NewManager(apiKey)
|
||||
store, err := storage.Open(*dbPath)
|
||||
@@ -52,12 +57,23 @@ func main() {
|
||||
if err := store.UpsertLocal(local, runtime.GOARCH, runtime.GOOS); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
notificationManager := notify.New(store)
|
||||
notificationManager.Start()
|
||||
defer notificationManager.Stop()
|
||||
s := &api.Server{
|
||||
Auth: authManager,
|
||||
Exec: executor.Local{MaxOutput: 1024 * 1024},
|
||||
Cluster: func() *cluster.Manager { m := cluster.NewManager(clusterSecret); m.SetStore(store); return m }(),
|
||||
Cluster: cluster.NewManager(clusterSecret, store),
|
||||
Store: store,
|
||||
LocalName: local,
|
||||
Notify: notificationManager,
|
||||
AdminToken: adminToken,
|
||||
ExecLimiter: make(chan struct{}, 32),
|
||||
SearchLimiter: make(chan struct{}, 8),
|
||||
LocalSessions: executor.NewSessionManager(0),
|
||||
}
|
||||
if err := s.LoadSecurityPolicySnapshot(); err != nil {
|
||||
log.Fatalf("load security policy snapshot: %v", err)
|
||||
}
|
||||
|
||||
// MCP Server instance
|
||||
@@ -106,6 +122,13 @@ func main() {
|
||||
IdleTimeout: 90 * time.Second,
|
||||
}
|
||||
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() {
|
||||
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatal(err)
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -99,6 +100,13 @@ func (h *HubRemoteBackend) ReadFile(ctx context.Context, clientIP, device, path
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (h *HubRemoteBackend) EditBlock(ctx context.Context, clientIP, device, path, oldText, newText string) (any, error) {
|
||||
payload := map[string]any{"device": device, "path": path, "old_text": oldText, "new_text": newText}
|
||||
var res any
|
||||
err := h.post("/api/v1/devices/file/edit_block", payload, &res)
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (h *HubRemoteBackend) WriteFile(ctx context.Context, clientIP, device, path, content string) (any, error) {
|
||||
payload := map[string]any{
|
||||
"device": device,
|
||||
@@ -147,3 +155,31 @@ func main() {
|
||||
os.Stdout.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
func (h *HubRemoteBackend) ListAgentMCP(ctx context.Context, device string) (any, error) {
|
||||
var res any
|
||||
err := h.get(ctx, "/api/v1/mcp/list?device="+url.QueryEscape(device), &res)
|
||||
return res, err
|
||||
}
|
||||
func (h *HubRemoteBackend) CallAgentMCP(ctx context.Context, clientIP, device, server, tool string, args any) (any, error) {
|
||||
payload := map[string]any{"device": device, "server": server, "tool": tool, "arguments": args}
|
||||
var res any
|
||||
return res, h.post("/api/v1/mcp/call", payload, &res)
|
||||
}
|
||||
func (h *HubRemoteBackend) get(ctx context.Context, path string, out any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(h.BaseURL, "/")+path, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+h.APIKey)
|
||||
resp, err := h.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 400 {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(b))
|
||||
}
|
||||
return json.NewDecoder(resp.Body).Decode(out)
|
||||
}
|
||||
|
||||
+169
-72
@@ -1,79 +1,139 @@
|
||||
# VPS-Commander 部署与运维指南
|
||||
|
||||
本文档介绍 VPS-Commander 的生产环境部署架构、配置规范与运维操作。
|
||||
本文档介绍 VPS-Commander 当前生产环境部署架构、凭据规范、Agent 接入、升级与回滚流程。
|
||||
|
||||
---
|
||||
|
||||
## 一、系统架构与端口规划
|
||||
|
||||
- **Hub 服务端**:统一监听本地 `127.0.0.1:9521`,不对公网直接暴露端口。
|
||||
- **反向代理 (Lucky)**:
|
||||
- 域名:`https://vpstool.kory.kdns.fr`
|
||||
- 转发目标:`http://127.0.0.1:9521`
|
||||
- 核心要求:开启 **WebSocket Upgrade** 支持,转发透传所有子路径(`/.well-known/*`、`/oauth/*`、`/mcp/*`、`/api/v1/*`、`/agent/ws`、`/panel/*`)。
|
||||
- SSL 终止于反代层,反代自动携带 `X-Forwarded-Proto: https` 头以保障 Cookie 的 `Secure` 属性。
|
||||
- **Agent 客户端**:
|
||||
- 运行于受控的远程 VPS 机器上。
|
||||
- 通过公网 WSS 长连接主动回连 Hub:`wss://vpstool.kory.kdns.fr/agent/ws`。
|
||||
- **Hub 服务端**:监听 `127.0.0.1:9521`,不直接暴露公网。
|
||||
- **反向代理**:公网 HTTPS/WSS 入口为 `https://vpstool.kory.kdns.fr`。
|
||||
- **Agent 客户端**:通过 `wss://vpstool.kory.kdns.fr/agent/ws` 主动回连 Hub。
|
||||
|
||||
反代必须支持:
|
||||
- WebSocket Upgrade;
|
||||
- `/agent/ws`;
|
||||
- `/mcp/*`;
|
||||
- `/api/v1/*`;
|
||||
- `/panel/*`;
|
||||
- `/.well-known/*`;
|
||||
- `/oauth/*`。
|
||||
|
||||
---
|
||||
|
||||
## 二、凭据安全规范(强制要求)
|
||||
|
||||
1. **绝对禁止命令行参数传密**:
|
||||
- 二进制不再支持 `--api-key`、`--cluster-secret`、`--web-password` 命令行参数。
|
||||
- 彻底杜绝在 `/proc/*/cmdline` 和 `ps aux` 中泄露明文密码。
|
||||
2. **凭据存储位置与权限**:
|
||||
- 凭据文件保存在 `/etc/vps-commander/hub.env` 与 `/etc/vps-commander/agent.env`。
|
||||
- 权限必须严格设置为 `0600`(仅 root 可读写)。
|
||||
### 2.1 Hub 凭据
|
||||
Hub 使用:
|
||||
- `VPS_COMMANDER_API_KEY`;
|
||||
- `VPS_COMMANDER_WEB_PASSWORD`。
|
||||
|
||||
生产环境不再依赖 `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。
|
||||
|
||||
---
|
||||
|
||||
## 三、 Hub 服务端部署步骤
|
||||
## 三、一键安装与升级
|
||||
|
||||
### 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
|
||||
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
|
||||
```
|
||||
|
||||
### 2. 配置环境变量文件 (`/etc/vps-commander/hub.env`)
|
||||
### 4.3 配置
|
||||
```bash
|
||||
cat << 'ENV' > /etc/vps-commander/hub.env
|
||||
VPS_COMMANDER_API_KEY=your_generated_api_key_here
|
||||
VPS_COMMANDER_CLUSTER_SECRET=your_generated_cluster_secret_here
|
||||
VPS_COMMANDER_WEB_PASSWORD=your_generated_web_password_here
|
||||
VPS_COMMANDER_API_KEY=your_secure_api_key
|
||||
VPS_COMMANDER_WEB_PASSWORD=your_web_password
|
||||
ENV
|
||||
chmod 0600 /etc/vps-commander/hub.env
|
||||
```
|
||||
|
||||
### 3. 配置 Systemd 托管 (`/etc/systemd/system/vps-commander-hub.service`)
|
||||
### 4.4 Systemd
|
||||
```ini
|
||||
[Unit]
|
||||
Description=VPS-Commander Hub
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
WorkingDirectory=/opt/vps-commander
|
||||
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
|
||||
KillSignal=SIGTERM
|
||||
TimeoutStopSec=10s
|
||||
LimitNOFILE=65536
|
||||
Environment=GOGC=50
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
### 4. 启动服务
|
||||
### 4.5 启动
|
||||
```bash
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now vps-commander-hub
|
||||
@@ -82,62 +142,99 @@ systemctl status vps-commander-hub
|
||||
|
||||
---
|
||||
|
||||
## 四、 远程 Agent 节点部署步骤
|
||||
## 五、远程 Agent 节点部署步骤
|
||||
|
||||
若要将其他 VPS 纳入受控列表,在该远程 VPS 上执行:
|
||||
### 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
|
||||
```
|
||||
|
||||
### 1. 安装 Agent 二进制
|
||||
将编译生成的 `bin/vps-commander-agent-linux-amd64`(或 ARM64 版本)上传至目标 VPS 的 `/opt/vps-commander/vps-commander-agent` 并赋予执行权限 `chmod +x`。
|
||||
|
||||
### 2. 配置 Agent 环境变量 (`/etc/vps-commander/agent.env`)
|
||||
### 5.2 配置
|
||||
```bash
|
||||
install -d -m 0750 /etc/vps-commander
|
||||
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_CLUSTER_SECRET=与Hub相同的CLUSTER_SECRET
|
||||
VPS_COMMANDER_AGENT_TOKEN=<per-device-token>
|
||||
ENV
|
||||
chmod 0600 /etc/vps-commander/agent.env
|
||||
```
|
||||
|
||||
### 3. 配置 Systemd 托管 (`/etc/systemd/system/vps-commander-agent.service`)
|
||||
### 5.3 Systemd
|
||||
```ini
|
||||
[Unit]
|
||||
Description=VPS-Commander Agent
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
WorkingDirectory=/opt/vps-commander
|
||||
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
|
||||
KillSignal=SIGTERM
|
||||
TimeoutStopSec=10s
|
||||
LimitNOFILE=65536
|
||||
Environment=GOGC=50
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
### 4. 启动并连入集群
|
||||
当前 v2.0 生产迁移阶段可兼容显式 token;v2.1 发布后必须改为不出现在 ExecStart 的方式。
|
||||
|
||||
### 5.4 启动
|
||||
```bash
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now vps-commander-agent
|
||||
systemctl status vps-commander-agent
|
||||
```
|
||||
启动后,Hub 控制面板与 `/api/v1/devices` 接口将立即展示该节点并标记为 `online`。
|
||||
|
||||
Agent 启动后主动连接 Hub,并在设备列表中显示为 `online`。
|
||||
|
||||
---
|
||||
|
||||
## 五、 控制面板与 Actions 使用
|
||||
## 六、控制面板与 MCP 使用
|
||||
|
||||
1. **管理后台地址**:`https://vpstool.kory.kdns.fr/panel/login`
|
||||
2. **后台功能**:
|
||||
- **设备看板**:查看所有在线/离线节点、系统架构与延迟。
|
||||
- **快速控制台**:直接在网页端向指定节点执行 Shell 指令。
|
||||
- **审计日志**:实时监控 GPT 与用户的全部执行调用、命令详情与耗时。
|
||||
- **Actions 向导**:一键复制 Schema 地址、System Prompt 与 API 密钥。
|
||||
### 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
|
||||
journalctl -u vps-commander-hub -n 100
|
||||
curl -fsS http://127.0.0.1:9521/healthz
|
||||
```
|
||||
|
||||
集群可通过 Web Panel、`/api/v1/devices` 或 MCP `list_devices` 检查。
|
||||
|
||||
---
|
||||
|
||||
## 九、当前生产审计提示
|
||||
|
||||
2026-10-02 审计发现生产 Hub / Agent 曾由 `vcs.modified=true` 的工作树构建。
|
||||
因此生产现场二进制不能直接视为当前 HEAD 的可复现产物。
|
||||
下一次正式发布必须 clean rebuild,并重新部署与验证。
|
||||
|
||||
+9
-15
@@ -72,15 +72,15 @@ install_agent() {
|
||||
read -rp "请输入本节点名称 (默认: ${DEFAULT_NAME}): " AGENT_NAME
|
||||
AGENT_NAME=${AGENT_NAME:-${DEFAULT_NAME}}
|
||||
|
||||
read -rp "请输入 Cluster Secret (集群通信密钥): " CLUSTER_SECRET
|
||||
while [ -z "$CLUSTER_SECRET" ]; do
|
||||
read -rp "Cluster Secret 不能为空,请重新输入: " CLUSTER_SECRET
|
||||
read -rp "请输入 Agent 独立凭据 Token: " AGENT_TOKEN
|
||||
while [ -z "$AGENT_TOKEN" ]; do
|
||||
read -rp "Agent Token 不能为空,请重新输入: " AGENT_TOKEN
|
||||
done
|
||||
|
||||
cat << ENV > "${CONF_DIR}/agent.env"
|
||||
VPS_COMMANDER_HUB_WS_URL=${HUB_WS}
|
||||
VPS_COMMANDER_AGENT_NAME=${AGENT_NAME}
|
||||
VPS_COMMANDER_CLUSTER_SECRET=***
|
||||
VPS_COMMANDER_AGENT_TOKEN=${AGENT_TOKEN}
|
||||
ENV
|
||||
chmod 0600 "${CONF_DIR}/agent.env"
|
||||
|
||||
@@ -133,23 +133,18 @@ install_hub() {
|
||||
read -rp "请输入监听端口 (默认 9521): " HUB_PORT
|
||||
HUB_PORT=${HUB_PORT:-9521}
|
||||
|
||||
GEN_API_KEY=*** -c 24 /dev/urandom | xxd -p)
|
||||
GEN_SECRET=*** -c 24 /dev/urandom | xxd -p)
|
||||
GEN_PASS=$(head -c 16 /dev/urandom | xxd -p)
|
||||
GEN_API_KEY=$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n')
|
||||
GEN_PASS=$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')
|
||||
|
||||
read -rp "请输入 API Key (默认随机生成): " API_KEY
|
||||
API_KEY=***
|
||||
|
||||
read -rp "请输入 Cluster Secret (默认随机生成): " CLUSTER_SECRET
|
||||
CLUSTER_SECRET=${CLUS…RET}
|
||||
API_KEY=${API_KEY:-$GEN_API_KEY}
|
||||
|
||||
read -rp "请输入 Web 管理面板密码 (默认随机生成): " WEB_PASS
|
||||
WEB_PASS=${WEB_PASS:-$GEN_PASS}
|
||||
|
||||
cat << ENV > "${CONF_DIR}/hub.env"
|
||||
VPS_COMMANDER_API_KEY=***
|
||||
VPS_COMMANDER_CLUSTER_SECRET=***
|
||||
VPS_COMMANDER_WEB_PASSWORD=***
|
||||
VPS_COMMANDER_API_KEY=${API_KEY}
|
||||
VPS_COMMANDER_WEB_PASSWORD=${WEB_PASS}
|
||||
ENV
|
||||
chmod 0600 "${CONF_DIR}/hub.env"
|
||||
|
||||
@@ -185,7 +180,6 @@ SVC
|
||||
echo -e "\n================== Hub 配置凭据 =================="
|
||||
echo -e "监听地址: 127.0.0.1:${HUB_PORT}"
|
||||
echo -e "API Key: ${API_KEY}"
|
||||
echo -e "Cluster Secret: ${CLUSTER_SECRET}"
|
||||
echo -e "Web 面板密码: ${WEB_PASS}"
|
||||
echo -e "==================================================\n"
|
||||
warn "请妥善保管上述凭据,反代请将域名反代至 127.0.0.1:${HUB_PORT}"
|
||||
|
||||
+118
-37
@@ -1,50 +1,131 @@
|
||||
# VPS-Commander 验收审核标准与收尾门禁规范 (Quality Gate & Acceptance Criteria)
|
||||
# VPS-Commander 阶段验收标准与发布门禁用例矩阵
|
||||
|
||||
> 本规范由架构与质量负责人(OpenClaw)制定并执行最终裁决。
|
||||
> 任何交付代码必须满足以下全量准入与准出指标方可判定为验收通过(Release Ready)。
|
||||
本文档定义当前 v2.0 生产架构的发布门禁,并为 v2.1 安全加固预留验收项。
|
||||
|
||||
---
|
||||
|
||||
## 一、 核心门禁四不原则(强制一票否决项)
|
||||
## 一、构建与版本一致性
|
||||
|
||||
1. **绝对无外部公网中转**:任何网络交互(除与 OpenAI 官方通信外)严禁经过第三方 Relay 服务器,必须 100% 走私有域名直连。
|
||||
2. **绝对零残留孤儿进程**:执行任何命令、超时中断或连接断开后,后台不得产生僵尸进程或孤儿子进程。
|
||||
3. **绝对无未授权越权**:所有非公共接口必须强制 Bearer Token / Cluster Secret 校验,缺失或错误凭证必须严厉返回 HTTP 401,严禁静默放行。
|
||||
4. **内存超标即挂**:Hub 静态常驻物理内存不得突破 **25 MB**,Agent 客户端常驻物理内存不得突破 **12 MB**;10MB 为优化目标。
|
||||
### 1.1 基础测试
|
||||
```bash
|
||||
go test ./...
|
||||
go test -race ./...
|
||||
git diff --check
|
||||
```
|
||||
|
||||
### 1.2 生产构建
|
||||
- Git 工作树必须 clean。
|
||||
- `vcs.modified=false`。
|
||||
- `vcs.revision` 必须等于 release commit。
|
||||
- AMD64 / ARM64 编译成功。
|
||||
|
||||
---
|
||||
|
||||
## 二、 详细验收测试用例矩阵 (12 项全绿门禁)
|
||||
## 二、Hub / Agent 集群验收
|
||||
|
||||
| 用例 ID | 验证模块 | 测试动作与输入 | 预期结果与合格标准 | 验证方式 |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| **TC-01** | **OpenAPI 规范合法性** | `GET /openapi.json` | 格式符合 OpenAPI 3.1.0 标准,包含 servers URL、4 个标准 path、安全定义为 `bearerAuth`(HTTP Bearer),可通过 Swagger / OpenAI Actions 校验无报错。 | 机器静态校验 |
|
||||
| **TC-02** | **未授权拦截** | 无 Token 请求 `/api/v1/exec` | 立即返回 HTTP 401 Unauthorized,响应体包含 `{"error": "Unauthorized"}`,不触发任何底层 bash。 | `curl -i` 验证 |
|
||||
| **TC-03** | **本地基础命令执行** | `POST /api/v1/exec` (`{"device":"local","command":"uname -a"}`) | 返回 exit_code: 0,stdout 正确包含 Linux 内核信息,duration_ms > 0 且合理。 | 实测响应校验 |
|
||||
| **TC-04** | **命令超时与进程回收** | 执行 `sleep 10`,设置 `timeout: 2` | 命令在 2 秒后强制终止,返回超时错误,且检查系统进程树确认 `sleep` 进程彻底消失,无僵尸残留。 | `ps -ef` 核查 |
|
||||
| **TC-05** | **文件分页读取防爆** | 读取 10MB 文本文件,设置 `limit: 1024` | 仅返回前 1024 字节内容,返回 `total_size` 与 `has_more: true`,严禁一次性将全文件读入内存。 | 接口响应验证 |
|
||||
| **TC-06** | **文件安全覆写** | `POST /api/v1/file/write` 写入 `/tmp/vps_cmd_test.txt` | 文件内容精确写入,权限正常,支持覆盖写入。 | 本地文件比对 |
|
||||
| **TC-07** | **Agent 握手与注册** | 启动 Agent 连入 Hub WSS | Hub 面板与 `GET /api/v1/devices` 瞬间显示该设备为 `online`,展示正确 IP 与内核信息。 | 状态机校验 |
|
||||
| **TC-08** | **心跳保活与离线感知** | 模拟杀死 Agent 进程 | 经过 2 个心跳周期(~60s)后,Hub 自动将该节点状态变更为 `offline`,不发生 panic。 | 节点状态监听 |
|
||||
| **TC-09** | **跨节点路由下发** | `POST /api/v1/exec` (`{"device":"hwsg","command":"uptime"}`) | Hub 正确通过 WebSocket 寻址到远程 Agent,Agent 执行并原路返回,耗时增加在 RTT 合理范围内。 | 跨机实测 |
|
||||
| **TC-10** | **Web 管理面板嵌入** | 浏览器直接访问 `GET /` | 页面秒开,设备列表、ChatGPT 向导、审计日志正常渲染,无任何外部 CDN 404,无 node 构建产物遗留。 | 浏览器/Headless 验证 |
|
||||
| **TC-11** | **审计日志完备性** | 执行一次正常命令与一次失败命令 | 查询 SQLite `audit_logs` 表,两条记录均完整存在(含 IP、设备、指令、退出码、耗时),字段无空缺。 | SQLite 查询比对 |
|
||||
| **TC-12** | **内存基线压测** | 连续并发执行 100 次 `ps aux` | 压测结束后,Hub RSS 必须 ≤ 25MB;20MB 为优化目标。压测结束后应回落并稳定,无持续增长趋势。 | `ps -eo rss` 采样 |
|
||||
| 项目 | 验收标准 |
|
||||
| :--- | :--- |
|
||||
| Hub | 监听 `127.0.0.1:9521` |
|
||||
| Agent | 5 个远程节点可正常回连 |
|
||||
| Restart | Hub 重启后 Agent 自动恢复 |
|
||||
| Identity | Credential 与设备身份一致 |
|
||||
| Unknown | 未知设备必须 fail-closed |
|
||||
|
||||
---
|
||||
|
||||
## 三、 严格收尾与交付规范 (Sign-off Checklist)
|
||||
## 三、认证与授权验收
|
||||
|
||||
GPT 完成开发提交代码后,由我执行以下严苛收尾工作:
|
||||
1. **代码审计 (Code Review)**:
|
||||
- 检查并发安全性(互斥锁 `sync.RWMutex` 是否合理、Channel 是否有阻塞泄漏风险)。
|
||||
- 检查外部输入 Shell 命令的执行上下文,是否存在注入或不可控行为。
|
||||
2. **构建与打包 (Clean Build)**:
|
||||
- 生成标准的 `Makefile`,支持编译 Linux AMD64/ARM64 静态无依赖产物。
|
||||
- 清理所有中间编译缓存与临时测试文件。
|
||||
3. **部署托管与 Systemd 固化**:
|
||||
- 为 Hub 编写规范的 `vps-commander-hub.service`。
|
||||
- Lucky 反代添加规则及 SSL 校验。
|
||||
4. **终验报告与归档**:
|
||||
- 输出完整的《VPS-Commander 最终验收合格报告》。
|
||||
- 将完整配置参数与使用说明同步至长期记忆 `MEMORY.md`。
|
||||
- Bearer API Key 正常。
|
||||
- URL token (`?token` / `?key` / `?api_key`) 必须拒绝。
|
||||
- 每设备 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 审计链。
|
||||
|
||||
+175
-122
@@ -1,148 +1,201 @@
|
||||
# VPS-Commander(自托管私有化多节点运维管家)架构与开发设计规范
|
||||
|
||||
## 1. 项目立项背景与目标
|
||||
## 一、项目立项背景与目标
|
||||
|
||||
### 1.1 背景与痛点
|
||||
- 当前市面方案(如 Desktop Commander)严重依赖公共第三方中继(SaaS Relay),存在严重的命令与数据泄漏风险、Token 明文暴露风险以及第三方额度/速率限制。
|
||||
- 现有纯开发网关(如 CodePier)采用项目目录沙箱隔离,无法进行系统级运维(如查看全局进程、管理 Lucky/Docker、修改全盘系统配置等),且不支持 ChatGPT 原生 Actions 插件生态。
|
||||
- 早期方案过度依赖第三方 Relay,控制面与节点执行面边界不清。
|
||||
- 单机开发网关通常存在项目目录沙箱,无法覆盖完整 Host-centric 运维。
|
||||
- AI Agent 需要的不只是 Shell,而是节点发现、文件、进程、Session、MCP 和审计的一体化控制面。
|
||||
|
||||
### 1.2 核心目标
|
||||
- **100% 私有化部署**:数据仅在 OpenAI 官方服务器和用户私有 VPS 之间传输,零第三方中转。
|
||||
- **全权宿主运维 (Host-centric)**:提供全局 Shell、进程管理、文件读写能力。
|
||||
- **多节点别名调度**:通过单一 Hub 统一管理多台 VPS/客户端节点,支持在 ChatGPT 中通过自然语言昵称(如 "hwsg"、"wjyhk")随时切换目标节点。
|
||||
- **原生 ChatGPT 插件集成**:提供标准 OpenAPI 3.1 规范与 Actions 端点,在 ChatGPT 手机端/网页端呈现为原生交互卡片。
|
||||
- **超轻量 Go 架构**:Hub 常驻 RSS 目标 ≤ 20MB、硬上限 25MB;Agent 常驻 RSS 目标 ≤ 10MB、硬上限 12MB。
|
||||
- **100% 私有化控制面**:Hub、Agent、SQLite 与反向代理均由用户控制。
|
||||
- **Host-centric 运维**:Shell、文件、进程、Session、远程 MCP。
|
||||
- **多节点统一调度**:一个 Hub 管理多个 VPS,节点状态持久化。
|
||||
- **AI 原生接入**:HTTP、MCP、stdio、Web 管理面板。
|
||||
- **安全闭环**:认证、风险授权、资源限制、审计、可回滚发布。
|
||||
|
||||
---
|
||||
|
||||
## 2. 总体架构设计
|
||||
## 二、总体架构设计
|
||||
|
||||
```text
|
||||
[ 用户在 ChatGPT APP / Web 端发指令 ]
|
||||
[ AI / MCP Client / Web Panel ]
|
||||
│
|
||||
▼ (HTTPS POST + Bearer API Key)
|
||||
[ 用户私有域名反代 (Lucky SSL) ]
|
||||
▼ HTTPS / MCP
|
||||
[ Reverse Proxy / TLS ]
|
||||
│
|
||||
▼ (反向代理至 127.0.0.1:28800)
|
||||
┌────────────────────────────────────────────────────────┐
|
||||
│ VPS-Commander Hub (中央管理网关) │
|
||||
▼ 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 │
|
||||
└──────────────┬───────────────────┬───────────┘
|
||||
│ │
|
||||
│ ├─ OpenAPI / Actions Engine (/openapi.json, /api/v1) │
|
||||
│ ├─ 鉴权与安全过滤中间件 (Auth Middleware) │
|
||||
│ ├─ 设备拓扑注册表 (Device Registry & State Machine) │
|
||||
│ ├─ 审计日志存储 (SQLite: audit.db) │
|
||||
│ └─ 路由分发器 (Router Dispatcher) │
|
||||
└───────────┬────────────────────────────────┬───────────┘
|
||||
│ │
|
||||
(本地进程直连: target="local") (安全 WebSocket 长连接 / mTLS)
|
||||
Local Executor Agent WSS
|
||||
│ │
|
||||
▼ ▼
|
||||
[ 本机 Local Executor ] [ 远程 Agent (Node: hwsg) ]
|
||||
- bash -c ... - Client Agent Daemon
|
||||
- 文件/进程直接操作 - 接收 JSON-RPC 指令并执行
|
||||
Hub 本机 Remote VPS
|
||||
│
|
||||
Host Executor
|
||||
Shell / File / Process
|
||||
```
|
||||
|
||||
### 2.1 控制通道
|
||||
AI / MCP / HTTP 请求进入 Hub,由 Hub 完成认证、设备解析、风险判断和路由。
|
||||
|
||||
### 2.2 节点通道
|
||||
Agent 主动通过 WSS 回连 Hub,负责设备注册、状态、能力协商及 RPC 请求/响应。
|
||||
|
||||
两条通道共享同一设备身份、策略和审计上下文,不允许出现 MCP 或 Agent MCP 绕过 Hub 授权的旁路。
|
||||
|
||||
---
|
||||
|
||||
## 三、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/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 核心接口与协议规范 (OpenAPI 3.1)
|
||||
## 八、生产部署边界
|
||||
|
||||
ChatGPT Actions 识别的标准接口集合:
|
||||
- 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`。
|
||||
|
||||
### 3.1 `/api/v1/devices` (GET)
|
||||
- **说明**:获取当前所有在线/受管设备列表及健康状态。
|
||||
- **返回**:`[{"name": "wjyhk", "is_local": true, "status": "online"}, {"name": "hwsg", "status": "online"}]`
|
||||
|
||||
### 3.2 `/api/v1/exec` (POST)
|
||||
- **说明**:在指定节点执行 Shell 命令。
|
||||
- **请求体**:
|
||||
```json
|
||||
{
|
||||
"device": "hwsg", // 节点昵称,缺省默认 local / wjyhk
|
||||
"command": "free -h", // 要执行的命令
|
||||
"workdir": "/root", // 可选工作目录
|
||||
"timeout": 30 // 超时时间(秒)
|
||||
}
|
||||
```
|
||||
- **响应体**:
|
||||
```json
|
||||
{
|
||||
"device": "hwsg",
|
||||
"exit_code": 0,
|
||||
"stdout": "...",
|
||||
"stderr": "",
|
||||
"duration_ms": 120
|
||||
}
|
||||
```
|
||||
|
||||
### 3.3 `/api/v1/fs/read` (POST)
|
||||
- **说明**:受控读取指定设备的文件内容。
|
||||
- **参数**:`device`, `path`, `offset_bytes`, `limit_bytes`(防止大文件撑爆模型上下文)。
|
||||
|
||||
### 3.4 `/api/v1/fs/write` (POST)
|
||||
- **说明**:在指定设备创建或覆写文件。
|
||||
- **参数**:`device`, `path`, `content`。
|
||||
升级必须执行:
|
||||
1. backup;
|
||||
2. clean build;
|
||||
3. 单节点灰度;
|
||||
4. Hub restart recovery;
|
||||
5. rolling Agent;
|
||||
6. MCP/security/audit 验收。
|
||||
|
||||
---
|
||||
|
||||
## 4. Hub 与 Agent 节点通信规范
|
||||
## 九、v2.1 演进方向
|
||||
|
||||
1. **Agent 注册与鉴权**:
|
||||
- Agent 启动时通过 `wss://hub.domain.com/agent/ws` 发起长连接。
|
||||
- 握手使用 `Authorization: Bearer <cluster-secret>` Header;Cluster Secret 不进入 URL。
|
||||
- 握手成功后,Hub 内存注册表更新该设备为 `online`,并启动双向 Heartbeat ping/pong(30s 周期)。
|
||||
### 9.1 P0
|
||||
- EffectiveRisk 完全 fail-closed。
|
||||
- Agent Credential 不进入 argv / cmdline。
|
||||
|
||||
2. **指令下发 (JSON-RPC)**:
|
||||
- Hub 收到 ChatGPT 请求 ➡️ 生成 `task_id` ➡️ 通过 WS 发送 `{"action": "exec", "task_id": "...", "command": "..."}`。
|
||||
- Agent 执行完毕后返回 `{"task_id": "...", "result": {...}}`。
|
||||
- Hub 审计日志落库后返回给 ChatGPT。
|
||||
|
||||
---
|
||||
|
||||
## 5. 项目工程结构与技术选型
|
||||
|
||||
- **开发语言**:Go 1.22+(高性能、低内存、单二进制交叉编译友好)
|
||||
- **Web 框架**:Gin 或纯标准库 `net/http` + `gorilla/websocket`
|
||||
- **存储**:SQLite (纯粹用于审计日志与持久化配置)
|
||||
|
||||
```
|
||||
vps-commander/
|
||||
├── cmd/
|
||||
│ ├── hub/ # 中央控制网关主入口
|
||||
│ └── agent/ # 节点客户端主入口
|
||||
├── internal/
|
||||
│ ├── api/ # ChatGPT Actions HTTP 接口
|
||||
│ ├── auth/ # Bearer Token 与 Secret 鉴权
|
||||
│ ├── cluster/ # 节点连接池、心跳与 WebSocket 管理
|
||||
│ ├── executor/ # 本地/远程执行器抽象
|
||||
│ └── storage/ # 审计日志与设备配置持久化
|
||||
├── web/ # 极简设备状态面板(纯 HTML/CSS 嵌入二进制)
|
||||
├── openapi/ # 供 ChatGPT 导入的 openapi.json
|
||||
├── Makefile # 多架构编译 (linux/amd64, linux/arm64)
|
||||
└── README.md # 部署与 ChatGPT 配置指南
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Hub Web 控制面板设计规范
|
||||
|
||||
### 6.1 定位与设计原则
|
||||
- **极简独立**:前端采用纯 HTML5 + TailwindCSS/原生CSS + Vanilla JS,不引入复杂 node 构建工具链,通过 Go 1.16+ `embed.FS` 直接打包进单一二进制产物。
|
||||
- **开箱即用**:零外部静态资源依赖,访问 `https://hub.yourdomain.com/` 即可直接加载。
|
||||
- **低资源消耗**:Web 面板由 Hub 服务原生托管,静态文件常驻开销基本为零。
|
||||
|
||||
### 6.2 核心功能模块
|
||||
1. **设备看板 (Device Overview)**
|
||||
- 受管设备列表:别名(Alias)、当前状态(Online/Offline)、系统架构与内核、IP 地址、最后心跳(Heartbeat)。
|
||||
- 快速连接指引:点击“添加节点”,自动生成带 Token 的单行一键安装/运行命令(如 `curl -sL https://... | bash -s -- --hub=... --token=...`)。
|
||||
- 设备启停与踢出操作:支持在面板主动注销失效/弃用节点。
|
||||
|
||||
2. **ChatGPT Actions 配置与向导中心**
|
||||
- 托管与展示 `/openapi.json` 规范预览。
|
||||
- 提供专属 API Key 生成、轮换与撤销功能。
|
||||
- 提供直接导入 ChatGPT Custom GPT 的一键复制 Schema 按钮与预设 System Prompt 建议。
|
||||
|
||||
3. **实时操作审计与日志 (Audit Log)**
|
||||
- 记录来源(ChatGPT / Web 手动)、目标设备、动作(exec / file_read / file_write)、执行内容、执行耗时、退出码与结果摘要。
|
||||
- 支持按设备、关键字实时搜索过滤。
|
||||
|
||||
4. **Web 快速调试终端 (Quick Terminal / Console)**
|
||||
- 提供快速测试输入框,选择目标设备后可直接输入命令测试执行并查看即时输出,无需打开 ChatGPT 即可验证节点联通性。
|
||||
### 9.2 P1
|
||||
- Principal / Operator Identity。
|
||||
- Session Owner 强隔离。
|
||||
- principal → credential → session → device → operation 完整审计链。
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
# vps-commander 生产 Bug Hunt 报告(2026-10-02)
|
||||
|
||||
- **测试人**:安全测试员(独立 bug hunt)
|
||||
- **测试时间**:2026-10-02 13:36–13:50(+08)
|
||||
- **测试对象**:生产 Hub(wjyhk,13:36:06 重启)+ 6 节点 Agent
|
||||
- **测试方式**:只读探测 + 无害命令(echo/true),未写生产文件、未改配置、未重启服务、未碰 commander.db
|
||||
- **结论**:发现 **4 个 bug**,最高严重度 **高**。另有若干“未发现问题”的项如实记录。
|
||||
|
||||
---
|
||||
|
||||
## 【标题】生产 Agent 二进制构建自脏工作树,缺失已提交代码
|
||||
|
||||
**【严重度:高】**
|
||||
|
||||
**【复现步骤】**
|
||||
1. 在 wjyhk 执行 `go version -m /opt/vps-commander/vps-commander-agent`,观察 `vcs.revision=a5620cb` 且 `vcs.modified=true`。
|
||||
2. 对比源码:`git show a5620cb:cmd/agent/main.go` 的 action switch 只有 6 个 case(mcp_list/mcp_test/mcp_call/exec/file_read/file_write),无 session 相关、无 `read_multiple_files`。
|
||||
3. 但生产 Agent 实际能处理 `start_process`(session 功能可用),说明二进制内容无法从任何 commit 还原——是脏树构建。
|
||||
4. Hub 同样 `vcs.modified=true`(13:36 重部署的二进制,revision=556870b)。
|
||||
|
||||
**【证据】**
|
||||
```
|
||||
build vcs.revision=a5620cb9c4d3570cf5ce2abe8772ef4e3b91bd76
|
||||
build vcs.time=2026-10-01T16:45:10Z
|
||||
build vcs.modified=true
|
||||
```
|
||||
各节点 Agent md5 一致(35e965a9),均为同一脏构建,于 13:22 统一重启部署。
|
||||
|
||||
**【影响分析】**
|
||||
- 生产二进制不可复现:出问题时无法用 `git checkout <rev> && go build` 还原现场,排障与回滚失去基准。
|
||||
- 脏构建内容未知:`read_multiple_files` 在源码 192969d 中已加入 Agent,但生产 Agent 不支持(见 Bug #3),说明构建时的脏树处于部分完成状态,**可能还缺失其他已提交的安全修复**,需逐项核对。
|
||||
- **建议**:从干净 HEAD 重新构建 Hub+Agent,全量重新部署,部署后校验 `vcs.modified` 为空且 revision==HEAD。
|
||||
|
||||
---
|
||||
|
||||
## 【标题】`read_multiple_files` 在所有远端节点上失败(Hub-Agent 协议不一致)
|
||||
|
||||
**【严重度:中】**
|
||||
|
||||
**【复现步骤】**
|
||||
1. `vps-mcp.py call read_multiple_files '{"device":"hwsg","paths":["/etc/hostname"],"limit":100}'` → 返回 `{"error": "unsupported action"}`。
|
||||
2. 同样调用 `device=wjyhk`(本地)→ 正常返回文件内容。
|
||||
3. 查源码:`internal/api/mcp_adapter.go:287` 的 `ReadMultipleFiles` 对远端走 `Cluster.ReadMultipleFiles`;Agent 侧 `cmd/agent/main.go:261` 在当前源码中有该 case,但生产 Agent 二进制(脏构建)不支持,落入 `default: unsupported action`(main.go:391)。
|
||||
|
||||
**【证据】**
|
||||
```json
|
||||
{"error": "unsupported action"}
|
||||
```
|
||||
(hwsg/N3450 等远端节点复现,wjyhk 本地正常)
|
||||
|
||||
**【影响分析】**
|
||||
- MCP 工具列表向 AI 客户端 quảng cáo `read_multiple_files` 可用于所有设备,实际 5/6 节点不可用,功能性 bug。
|
||||
- 根因是 Bug #1(脏构建)的直接后果;修复 Bug #1(干净重建+重部署)后本项自动解决。
|
||||
- 在修复前,建议 Hub 对不支持该 action 的 Agent 返回明确错误而非透传 `unsupported action`,或在 capability 协商中隐藏该工具。
|
||||
|
||||
---
|
||||
|
||||
## 【标题】`/api/v1/process/session` 请求结构体无 JSON tag,snake_case 字段被静默丢弃
|
||||
|
||||
**【严重度:中】**
|
||||
|
||||
**【复现步骤】**
|
||||
1. `POST /api/v1/process/session?action=start`,body `{"device":"hwsg","command":"echo hi","session_id":"my-id"}`(snake_case,如响应格式所示)。
|
||||
2. 响应返回 `{"session_id":"04d39d85b150..."}`——**客户端传的 ID 被丢弃**,服务端生成了随机 ID。
|
||||
3. 随后用 `my-id` 做 read/stop → `session not found`。
|
||||
4. 改用精确大小写 `{"SessionID":"my-id"}` → 全流程正常。
|
||||
|
||||
**【证据】**
|
||||
```go
|
||||
// internal/api/api.go:784
|
||||
var req struct {
|
||||
Device, SessionID, Command, Workdir, Data string // 无 json tag!
|
||||
Force bool
|
||||
RingCapacity int `json:"ring_capacity"`
|
||||
}
|
||||
```
|
||||
Go encoding/json 对无 tag 字段仅做大小写不敏感匹配,`session_id`(snake_case)无法匹配 `SessionID`,被静默忽略。
|
||||
|
||||
**【影响分析】**
|
||||
- API 契约破裂:响应用 `session_id`(snake_case),请求却要求 `SessionID`(CamelCase);任何按常规 REST 惯例(或照着响应字段)写的客户端都会踩坑,且失败是静默的(拿到一个“成功”但对不上的 session)。
|
||||
- 非安全漏洞,但属于生产功能 bug。修复:在结构体上加 `json:"device"` 等 snake_case tag(注意与 openapi.json 文档对齐)。
|
||||
|
||||
---
|
||||
|
||||
## 【标题】`/api/v1/process/session` 不支持 Hub 本节点(无本地回退)
|
||||
|
||||
**【严重度:中低】**
|
||||
|
||||
**【复现步骤】**
|
||||
1. `POST /api/v1/process/session?action=start`,body `{"Device":"wjyhk","Command":"echo hi"}`。
|
||||
2. 返回 `device offline`(HTTP 409)。
|
||||
3. 对比:`POST /api/v1/exec` 同样 `device=wjyhk` 可正常执行(`exec` 有 `isRemote` 本地回退,api.go:744)。
|
||||
|
||||
**【证据】**
|
||||
```go
|
||||
// processSession 直接走 Cluster,无 isRemote 判断:
|
||||
if s.Cluster == nil { http.Error(w, "cluster unavailable", 503); return }
|
||||
...
|
||||
result, err = s.Cluster.StartProcess(ctx, req.Device, ...) // wjyhk 无 agent WS 连接 → device offline
|
||||
```
|
||||
|
||||
**【影响分析】**
|
||||
- 功能不一致:exec/read/write 等在 Hub 本节点可用,唯独 session 管理不可用。用户在 Hub 本机无法使用长会话功能。
|
||||
- 修复:给 processSession 加与 exec 相同的 `isRemote` 本地回退(Hub 侧需持有一个本地 SessionManager,或复用 executor 包)。
|
||||
|
||||
---
|
||||
|
||||
## 未发现问题的项(逐项如实记录)
|
||||
|
||||
1. **认证绕过**:无 token/错 token/空 Bearer 访问 `/api/v1/*` 与 `/panel/api/*` 均返回 401;`/healthz` 200 为预期设计。未发现绕过。
|
||||
2. **畸形输入**:malformed JSON、空 body、300KB 超大 body(超 256KB MaxBytesReader 限制)均返回 400,无 panic。Hub 日志自 13:24 以来 0 panic、0 error。
|
||||
3. **路径穿越**:`../../../etc/hostname` 可读、`\0` 被 `validPath` 拦截(400)。但本工具是已认证管理员工具,无沙箱设计约束,`..` 解析属操作系统正常行为,不视为漏洞。
|
||||
4. **设备名注入**:空字符串回退本机(设计如此)、不存在设备/超长字符串/含 `\0` 的设备名均 `security mode unknown denies exec`,fail-closed,无 panic。
|
||||
5. **Session 生命周期**:Agent 侧每分钟 `sessions.Cleanup()`,idle TTL 10min + hard TTL 存在;`SessionManager` 有互斥锁,5 并发创建 session 无竞态崩溃(2 成功、3 因达到上限 4 被正确拒绝,上限由 `MaxSessionBufferTotal/DefaultRingCapacity=4` 决定,符合设计)。
|
||||
6. **并发压力**:10 并行原生 HTTP 请求全部 200、响应快;Hub 内存稳定(~20MB)。30 并行 MCP 调用大量超时系客户端 SSE 建连开销,非 Hub 问题。
|
||||
7. **配额**:`ExecLimiter` 32 并发信号量存在;无单客户端速率限制(设计选择,非 bug)。
|
||||
8. **Agent-MCP 畸形参数**:不存在的 tool/含 `\0` 的参数返回干净的 `MCP HTTP status 400`,无 panic、无信息泄漏。
|
||||
9. **kill 进程**:API 只接受 SessionID,Agent 用内部 `cmd.Process` 句柄 kill,不接受客户端 PID,无 PID 重用误杀风险。
|
||||
|
||||
---
|
||||
|
||||
## 附:测试期间观察到的部署活动
|
||||
|
||||
- 13:36:06 Hub 被重部署(此前为 13:24),二进制 revision 由 38382d2 变为 556870b。测试期间生产处于活跃变更中,部分结论(如 Hub revision)以测试时刻为准。
|
||||
- Agent 在各节点为同一脏构建(md5 35e965a9,13:22 部署),`vcs.modified=true`。
|
||||
|
||||
---
|
||||
|
||||
*安全测试员,2026-10-02*
|
||||
@@ -0,0 +1,81 @@
|
||||
# DC Refactoring Phase 1 Implementation Record
|
||||
|
||||
> 文档属性:历史实施记录。后续阶段和当前状态以当前架构规范与 v2.1 规范为准。
|
||||
|
||||
Date: 2026-10-02
|
||||
|
||||
## Completed
|
||||
|
||||
- Added immutable Hub `PolicySnapshot` protected by `RWMutex`.
|
||||
- Added monotonic security policy version persisted in SQLite.
|
||||
- Hub startup now rebuilds the snapshot from SQLite; snapshot load failure aborts startup rather than defaulting to High.
|
||||
- Security setting writes use SQLite transactions and only publish the new snapshot after the durable write succeeds.
|
||||
- Added a compile-time Tool Registry with fixed `RequiredRisk` for Low/Medium/High capabilities.
|
||||
- Existing API security checks now resolve required risk through the registry instead of duplicating risk numbers in handlers.
|
||||
- Security-setting audit records include old/new effective mode and snapshot version.
|
||||
|
||||
## Compatibility / Safety
|
||||
|
||||
- Existing API routes and Agent WebSocket protocol were not changed in this phase.
|
||||
- No production Hub/Agent restart was performed.
|
||||
- When `Server.Policy` is initialized, security checks use the in-memory snapshot and do not query SQLite on the request hot path.
|
||||
- Existing tests that construct `Server` without a snapshot retain the legacy storage fallback for test/backward compatibility; production startup always initializes the snapshot.
|
||||
|
||||
## Verification
|
||||
|
||||
- `go test ./...` passed.
|
||||
- `go test -race ./...` passed.
|
||||
- Hub and Agent clean builds passed.
|
||||
- No production service restart was performed; live rollout remains a separate controlled step to preserve the no-interruption requirement.
|
||||
|
||||
## Phase 2 Completed
|
||||
|
||||
- Added `edit_block` to the Agent execution engine.
|
||||
- `old_text` must match exactly once; zero/multiple matches are rejected without mutation.
|
||||
- Replacement uses a same-directory temporary file, preserves file permission bits, fsyncs the file, renames atomically, and syncs the directory.
|
||||
- Added Agent RPC action `edit_block`, Hub `/api/v1/devices/file/edit_block`, MCP `edit_block`, and stdio proxy support.
|
||||
- `edit_block` is registered as Medium risk and therefore follows the existing Hub policy snapshot gate.
|
||||
- Added optional `sub_action` protocol field without changing existing message semantics.
|
||||
- Added tests for unique replacement, duplicate/missing rejection, permissions, Low-mode denial, and MCP registration.
|
||||
|
||||
Phase 2 rollout remains deliberately separate from production process replacement. Existing production Agent connections have not been restarted.
|
||||
|
||||
## Phase 3 Completed
|
||||
|
||||
- Added a per-Agent `SessionManager` with a bounded session count (default 16).
|
||||
- Added fixed-size 2 MiB stdout/stderr RingBuffers; old output is discarded when capacity is exceeded.
|
||||
- Added long-running process actions: `start_process`, `read_process_output`, `interact_with_process`, `force_terminate`, `list_sessions`.
|
||||
- Processes run in their own process group so termination/force termination covers the command tree.
|
||||
- Added periodic completed-session cleanup.
|
||||
- Added Hub RPC and HTTP `/api/v1/process/session` dispatch with action-based lifecycle operations.
|
||||
- Added session tests for ring retention, output capture, termination, duplicate IDs, and session limits.
|
||||
- Existing WebSocket request/response protocol remains compatible; new process actions are additive.
|
||||
|
||||
Production Hub/Agents were not restarted during Phase 3 implementation.
|
||||
|
||||
## Phase 3 Security Hardening / Concurrency Gate
|
||||
|
||||
- Added per-node operation arbitration in `cluster.Node.OpMu`.
|
||||
- Low-risk read actions use `RLock` and may run concurrently.
|
||||
- Medium/High mutations use exclusive `Lock`, preventing overlapping writes/control operations against the same node.
|
||||
- Unknown actions fail closed as High risk for the concurrency gate.
|
||||
- Session IDs are generated with 128-bit `crypto/rand` entropy when omitted by the API caller; PID is never used as identity.
|
||||
- Session ownership is bound to a non-reversible SHA-256 fingerprint of the authenticated API credential and checked by Agent for read/input/terminate operations.
|
||||
- Session TTL is enforced; stdin is capped at 64 KiB per call.
|
||||
- Agent restart still leaves all sessions in process memory only, so old session state is not restored.
|
||||
|
||||
All validation passed with `go test ./...`, `go test -race ./...`, Hub/Agent builds, and `git diff --check`. No production process was restarted.
|
||||
|
||||
## Phase 4 Completed
|
||||
|
||||
- Added optional protocol/agent capability metadata: `ProtocolVersion`, `AgentVersion`, `Capabilities`.
|
||||
- Hub records the capability set per connected Agent; when a modern Agent explicitly advertises capabilities, unsupported actions fail with `capability missing` rather than silently degrading.
|
||||
- Old Agents remain compatible because capability metadata is optional and capability enforcement is only applied when a capability set is advertised.
|
||||
- Added structured read-only filesystem operations: `list_directory`, `get_file_info`, `start_search`.
|
||||
- Directory listing supports bounded recursive traversal and a maximum entry count.
|
||||
- File metadata exposes type, size, mode and modification time.
|
||||
- Search is context-cancellable and bounded by a result cap; symlinks are skipped to avoid traversal surprises.
|
||||
- Added Hub endpoints `/api/v1/file/list`, `/api/v1/file/info`, `/api/v1/file/search`.
|
||||
- Added executor tests for directory listing, file metadata and bounded search.
|
||||
|
||||
Phase 4 validation: full tests, race tests, Hub/Agent builds and `git diff --check` passed. Production Hub/Agents were not restarted.
|
||||
@@ -0,0 +1,934 @@
|
||||
# 《VPS-Commander 平滑升级改造与三级安全拦截实施方案》
|
||||
|
||||
## 1. 改造目标与背景
|
||||
本项目计划全量复刻 **Desktop Commander(DC)** 在终端与文件系统上的核心工程能力(包括局部块级精准替换、后台长进程生命周期管理、交互式 stdin 注入、结构化目录遍历与只读检索),并将其无缝接入 **Low(低风险)/ Medium(中风险)/ High(高风险)** 三级安全门禁体系。
|
||||
|
||||
**核心红线与验收标准:**
|
||||
1. **服务不中断**:升级过程不影响正在运行的 Agent 探针与 Hub 中心。
|
||||
2. **协议向后兼容**:旧版 Agent 与新版 Hub 混合共存,老接口绝不废弃。
|
||||
3. **性能零损耗**:杜绝动态运行时映射,安全校验在编译期即已绑定。
|
||||
4. **轻量化保真**:继续保持纯 Go 静态编译的高效特性,严控内存占用(常驻内存锁定在 20MB 以内)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 工具池全量复刻与三级风险定级表(静态强绑定)
|
||||
|
||||
所有功能根据系统破坏力与副作用大小,在**编译期**严格归属于三级风险体系:
|
||||
|
||||
| 风险等级 (Level) | 行为边界定义 | 包含的复刻工具 (DC 标杆) | 允许放行的安全模式 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| 🟢 **Low(只读/感知)** | **纯只读、无状态改变、无系统副作用** | • `read_file` (支持切片与 Tail)<br>• `read_multiple_files`<br>• `list_directory` (结构化目录树)<br>• `get_file_info` (元数据)<br>• `start_search` / `get_more_search_results`<br>• `list_processes` / `list_sessions`<br>• `read_process_output` (拉取输出) | **Low**<br>**Medium**<br>**High** |
|
||||
| 🟡 **Medium(文件写)** | **文件与目录变更,但严禁拉起任意二进制或执行命令** | • `edit_block` (局部文本块精准替换,核心)<br>• `write_file` (文件新建/全量写入)<br>• `create_directory` (新建目录)<br>• `move_file` (移动/重命名) | **Medium**<br>**High**<br>*(Low 拦截)* |
|
||||
| 🔴 **High(完全控制)** | **具备操作系统执行权、进程生命周期调度与管道干预** | • `exec_command` (同步短命令)<br>• `start_process` (后台异步启动长进程)<br>• `interact_with_process` (stdin 交互写入)<br>• `kill_process` / `force_terminate` (终止进程) | **High**<br>*(Low / Medium 拦截)* |
|
||||
|
||||
---
|
||||
|
||||
## 3. 架构改造与平滑过渡设计
|
||||
|
||||
### 3.1 协议层平滑升级(零破坏向后兼容)
|
||||
在 `internal/cluster/protocol.go` 中,保留原有字段,新增可选的扩展动作:
|
||||
```go
|
||||
type Message struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Action string `json:"action,omitempty"` // 保持原有字段: "read" / "write" / "exec" / "probe"
|
||||
SubAction string `json:"sub_action,omitempty"` // ✨ 增量动作: "edit_block", "start_process" 等
|
||||
Device string `json:"device,omitempty"`
|
||||
Payload any `json:"payload,omitempty"`
|
||||
...
|
||||
}
|
||||
```
|
||||
* **兼容保障**:老版本 Agent 接收到带 `SubAction` 的 JSON 消息时会自动忽略多余字段,继续按老逻辑工作;升级后的 Agent 优先路由给 `SubAction` 处理。
|
||||
|
||||
### 3.2 Hub 门禁与高并发性能优化(读写分离)
|
||||
现有系统每次请求均去 SQLite 查询策略,高并发下存在文件锁瓶颈。改造后引入 **RWMutex 内存策略快照**:
|
||||
1. **读路径(Fast Path,纳秒级)**:
|
||||
```go
|
||||
// 常量数值定义,直接内联比较
|
||||
const ( RiskLow = 1; RiskMedium = 2; RiskHigh = 3 )
|
||||
|
||||
func (s *Server) requireSecurity(w http.ResponseWriter, r *http.Request, device string, requiredRisk int, detail string) bool {
|
||||
allowed := s.getEffectiveRiskLevel(device) // 查内存 RLock,耗时 < 10ns
|
||||
if allowed >= requiredRisk {
|
||||
return true
|
||||
}
|
||||
// 记录 audit_logs ("security_denied", 403) 并返回拦截响应
|
||||
return false
|
||||
}
|
||||
```
|
||||
2. **写路径(Slow Path,低频)**:
|
||||
* 仅在管理员通过 Web 界面更改安全策略时,写一次 SQLite 并原子更新内存缓存。
|
||||
3. **老 API 零改动**:
|
||||
* 原有 `/api/v1/devices/exec`、`/read`、`/write` 继续保留,老脚本老客户端零感知。
|
||||
|
||||
### 3.3 Agent 端核心引擎实现(防资源膨胀设计)
|
||||
* **`edit_block` 引擎**:
|
||||
* 读取原文件后校验 `old_text` 全局唯一性,唯一时单次替换并使用临时文件进行原子覆写(`os.Rename`)。
|
||||
* 相比原有全量上传,网络传输和内存开销下降 95%。
|
||||
* **长进程与 PTY 会话引擎(`start_process` 等)**:
|
||||
* Agent 内部建立轻量 `SessionManager`,挂接内核标准输入输出管道。
|
||||
* **硬编码内存锁(Circular RingBuffer)**:每个进程会话分配最大 2MB 环形日志缓冲区,达到上限自动覆盖最早输出,**从物理上杜绝日志死循环导致的内存溢出(OOM)**。
|
||||
|
||||
---
|
||||
|
||||
## 4. 资源开销评估与性能上限控制
|
||||
|
||||
得益于纯 Go 原生静态编译,系统坚决不引入任何 Node.js/Python 运行时,资源开销保持极致克制:
|
||||
|
||||
| 评估指标 | 改造前基准(实测) | 改造后预期 | 性能/资源防护机制 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Agent 静默内存** | ~13 MB | **~15 MB - 18 MB** | 零后台轮询,事件驱动 |
|
||||
| **Agent 峰值内存** | 随命令大小波动 | **基准 + (2MB × 活跃会话数)** | 环形缓冲区硬顶锁定,防内存泄露 |
|
||||
| **Hub 服务端内存** | ~16 MB | **~18 MB - 22 MB** | 内存门禁仅占不到 10KB |
|
||||
| **二进制体积** | ~9.4 MB | **~11 MB - 13 MB** | 静态单文件编译,极易分发部署 |
|
||||
| **安全判定延迟** | 毫秒级(查 SQLite) | **纳秒级(内存读锁)** | 单机可轻松支撑 10W+ QPS 门禁并发 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 四阶段实施与回滚路线图(稳健落地)
|
||||
|
||||
* **Phase 1:服务端门禁升级与内存读缓存**
|
||||
* 在 Hub 端落地 `RWMutex` 安全策略缓存;
|
||||
* API 入口统一接入 `requireSecurity(..., RiskLevel)`;
|
||||
* *验证标准*:旧版 4 项基础功能与 Web 面板完好,并发查询 QPS 大幅提升。
|
||||
* **Phase 2:落地中风险神器 `edit_block`**
|
||||
* Agent 端实现块级精准替换算法;
|
||||
* Hub 暴露 `/api/v1/devices/file/edit_block` 并注册至 MCP Adapter;
|
||||
* *验证标准*:在 Medium 模式下可正常修配置文件,在 Low 模式下被精确阻断并记入审计。
|
||||
* **Phase 3:落地高风险长进程引擎**
|
||||
* Agent 端引入带 RingBuffer 的 `SessionManager`;
|
||||
* 实现 `start_process`、`read_process_output`、`interact_with_process`、`kill_process`;
|
||||
* *验证标准*:跑耗时任务不会超时断连,支持实时 Tail 查看输出与注入 stdin。
|
||||
* **Phase 4:落地只读结构化文件与系统感知(Low)**
|
||||
* 实现 `list_directory`、`get_file_info` 及后台异步只读搜索。
|
||||
|
||||
---
|
||||
|
||||
## 6. 评估与审计重点建议
|
||||
1. **安全维度**:Low/Medium/High 对能力的切分是否彻底杜绝了提权与逃逸风险?
|
||||
2. **性能维度**:使用内存 RWMutex + 编译期静态安全级别判定,是否彻底解决了单文件 SQLite 高频读瓶颈?
|
||||
3. **稳定性维度**:为每个长进程会话限定 RingBuffer 内存上限,是否有效防止了边缘 VPS 探针被日志撑爆?
|
||||
|
||||
---
|
||||
|
||||
# 7. 架构收敛修订(2026-10-02)
|
||||
|
||||
> 本章节在进入代码实施前增加,用于两位外部 Agent 审核。原方案的工具分级、四阶段路线和向后兼容原则继续保留;本章节对安全权威、策略一致性、工具注册以及高风险 Session 生命周期作进一步约束。
|
||||
|
||||
## 7.1 安全等级的正确边界:静态工具风险 + 运行时设备策略
|
||||
|
||||
原方案中“静态强绑定”应准确解释为:**工具所需风险等级在编译期固定,是否允许执行在运行时由 Hub 的权威策略决定。**
|
||||
|
||||
不得将设备当前 Low/Medium/High 策略编译进 Agent,也不得允许 Agent 自行提升自身安全等级。
|
||||
|
||||
### 7.1.1 工具风险等级
|
||||
|
||||
每个工具在代码注册表中拥有不可运行时修改的 `RequiredRisk`:
|
||||
|
||||
```go
|
||||
const (
|
||||
RiskLow = 1
|
||||
RiskMedium = 2
|
||||
RiskHigh = 3
|
||||
)
|
||||
|
||||
type ToolSpec struct {
|
||||
Name string
|
||||
RequiredRisk int
|
||||
ReadOnly bool
|
||||
}
|
||||
```
|
||||
|
||||
示例:
|
||||
|
||||
```text
|
||||
read_file / list_directory / search -> Low
|
||||
edit_block / write_file / move_file -> Medium
|
||||
exec_command / start_process / stdin -> High
|
||||
```
|
||||
|
||||
禁止通过 Web 面板、Agent 配置文件或远端请求动态修改工具自身的 `RequiredRisk`。
|
||||
|
||||
### 7.1.2 设备有效策略
|
||||
|
||||
设备的 `EffectiveRisk` 是 Hub 运行时策略,不属于 Agent 自主能力。
|
||||
|
||||
请求授权模型:
|
||||
|
||||
```text
|
||||
Request
|
||||
-> identify device
|
||||
-> identify ToolSpec.RequiredRisk
|
||||
-> read Hub PolicySnapshot
|
||||
-> compare EffectiveRisk >= RequiredRisk
|
||||
-> allow / deny
|
||||
```
|
||||
|
||||
因此完整安全边界为:
|
||||
|
||||
**编译期固定“工具需要什么权限” + 运行时决定“该设备当前获得什么权限”。**
|
||||
|
||||
---
|
||||
|
||||
## 7.2 Policy Store 与 Policy Snapshot 一致性模型
|
||||
|
||||
SQLite 继续作为持久化权威源(durable source of truth),但请求热路径禁止每次查询 SQLite。
|
||||
|
||||
### 7.2.1 数据流
|
||||
|
||||
```text
|
||||
Admin Web
|
||||
|
|
||||
v
|
||||
SQLite transaction
|
||||
|
|
||||
v
|
||||
Build new immutable PolicySnapshot
|
||||
|
|
||||
v
|
||||
Atomic publish / swap
|
||||
|
|
||||
v
|
||||
Request fast path
|
||||
```
|
||||
|
||||
请求只读取当前不可变 snapshot;不在请求过程中修改策略对象。
|
||||
|
||||
### 7.2.2 更新原则
|
||||
|
||||
策略修改必须满足:
|
||||
|
||||
1. SQLite 写入成功后才允许发布新 snapshot。
|
||||
2. SQLite 写失败时,内存策略保持旧版本。
|
||||
3. snapshot 发布必须是原子操作,不允许出现半更新状态。
|
||||
4. Hub 启动时必须从 SQLite 完整重建 snapshot。
|
||||
5. snapshot 应携带单调递增 `Version`,便于审计和诊断。
|
||||
6. 审计记录应包含 `device`, `oldRisk`, `newRisk`, `version`, `actor`, `timestamp`。
|
||||
|
||||
推荐结构:
|
||||
|
||||
```go
|
||||
type PolicySnapshot struct {
|
||||
Version uint64
|
||||
Devices map[string]DevicePolicy
|
||||
CreatedAt time.Time
|
||||
}
|
||||
```
|
||||
|
||||
热路径原则:
|
||||
|
||||
```text
|
||||
load current snapshot
|
||||
-> lookup device
|
||||
-> compare integer risk
|
||||
-> allow/deny
|
||||
```
|
||||
|
||||
不得在高频 API 请求中重新读取 SQLite 策略表。
|
||||
|
||||
### 7.2.3 故障安全
|
||||
|
||||
如果 Hub 无法加载有效策略 snapshot:
|
||||
|
||||
- 不得默认放行 High。
|
||||
- 不得从请求参数接受临时风险等级。
|
||||
- 对需要 Medium/High 的操作默认拒绝。
|
||||
- Low 只读能力是否可继续开放,必须由启动时的明确安全默认策略决定,并记录审计事件。
|
||||
|
||||
---
|
||||
|
||||
## 7.3 Tool Registry:统一能力与风险注册表
|
||||
|
||||
避免各 API handler 自己实现不同的安全判断。所有能力必须进入统一 Tool Registry。
|
||||
|
||||
建议:
|
||||
|
||||
```go
|
||||
type ToolSpec struct {
|
||||
Name string
|
||||
RequiredRisk int
|
||||
Category string
|
||||
ReadOnly bool
|
||||
Description string
|
||||
}
|
||||
```
|
||||
|
||||
例如:
|
||||
|
||||
```text
|
||||
read_file Low
|
||||
read_multiple_files Low
|
||||
list_directory Low
|
||||
get_file_info Low
|
||||
start_search Low
|
||||
get_more_search_results Low
|
||||
list_processes Low
|
||||
list_sessions Low
|
||||
read_process_output Low
|
||||
|
||||
edit_block Medium
|
||||
write_file Medium
|
||||
create_directory Medium
|
||||
move_file Medium
|
||||
|
||||
exec_command High
|
||||
start_process High
|
||||
interact_with_process High
|
||||
kill_process High
|
||||
force_terminate High
|
||||
```
|
||||
|
||||
API、MCP Adapter 和内部调用均通过 Registry 获取 `RequiredRisk`,不得在多个入口复制风险数字。
|
||||
|
||||
---
|
||||
|
||||
## 7.4 Agent 信任边界
|
||||
|
||||
Agent 是执行者,不是安全策略的最终裁决者。
|
||||
|
||||
Hub 是设备授权策略的权威来源。
|
||||
|
||||
但 Agent 仍必须执行本地最低限度安全校验,包括:
|
||||
|
||||
- 请求格式与参数校验;
|
||||
- session 所有权校验;
|
||||
- session 是否仍然有效;
|
||||
- 单次输入/输出大小限制;
|
||||
- 超时和资源限制;
|
||||
- 不接受客户端自行声明的 `RiskLevel` 作为授权依据。
|
||||
|
||||
Agent 不得因为请求中携带:
|
||||
|
||||
```json
|
||||
{"risk":"high"}
|
||||
```
|
||||
|
||||
或类似字段而自行获得 High 权限。
|
||||
|
||||
如果协议未来需要携带授权信息,应使用 Hub 生成的受保护授权上下文,并绑定:
|
||||
|
||||
```text
|
||||
device + request/session + policy version + expiry
|
||||
```
|
||||
|
||||
具体签名/令牌方案在实现阶段单独评审。
|
||||
|
||||
---
|
||||
|
||||
## 7.5 High Risk SessionManager 安全模型
|
||||
|
||||
`start_process`、`interact_with_process`、`kill_process` 不应被视为普通 HTTP 命令,而应视为一个受生命周期管理的高风险 Session。
|
||||
|
||||
### 7.5.1 Session 属性
|
||||
|
||||
每个 Session 至少包含:
|
||||
|
||||
```go
|
||||
type ProcessSession struct {
|
||||
ID string
|
||||
Owner string
|
||||
Device string
|
||||
PID int
|
||||
CreatedAt time.Time
|
||||
LastAccess time.Time
|
||||
ExpiresAt time.Time
|
||||
State string
|
||||
OutputBytes uint64
|
||||
}
|
||||
```
|
||||
|
||||
Session ID 必须不可预测,并且不能复用操作系统 PID 作为唯一身份。
|
||||
|
||||
### 7.5.2 所有权
|
||||
|
||||
只有创建 Session 的授权调用方才能:
|
||||
|
||||
- 读取该 Session 输出;
|
||||
- 向 stdin 写入数据;
|
||||
- 终止该 Session。
|
||||
|
||||
管理员级操作如果未来需要跨 Owner 接管 Session,应定义明确的审计事件和单独权限,不得通过普通 session API 隐式获得。
|
||||
|
||||
### 7.5.3 生命周期
|
||||
|
||||
```text
|
||||
start_process
|
||||
|
|
||||
v
|
||||
RUNNING
|
||||
/ \
|
||||
/ \
|
||||
EXITED EXPIRED
|
||||
| |
|
||||
+----+---+
|
||||
v
|
||||
CLEANUP
|
||||
```
|
||||
|
||||
Agent 重启后所有旧 Session 必须失效,不得从持久化文件自动恢复可写 stdin 的旧 Session。
|
||||
|
||||
### 7.5.4 时间限制
|
||||
|
||||
Session 必须具备:
|
||||
|
||||
- 最大生命周期;
|
||||
- 空闲超时;
|
||||
- stdin 单次大小限制;
|
||||
- stdin 速率限制;
|
||||
- 输出缓冲区上限。
|
||||
|
||||
具体默认数值在实现前通过压测确定,不在设计阶段硬编码未经验证的数值。
|
||||
|
||||
---
|
||||
|
||||
## 7.6 RingBuffer 与全局资源上限
|
||||
|
||||
原方案中的“2MB × 活跃 Session”只能作为单 Session 上限,不应视为 Agent 的总内存预算。
|
||||
|
||||
必须同时存在:
|
||||
|
||||
```text
|
||||
per-session output cap
|
||||
+
|
||||
max active sessions
|
||||
+
|
||||
agent-wide session buffer cap
|
||||
+
|
||||
process creation rate limit
|
||||
```
|
||||
|
||||
例如:
|
||||
|
||||
```text
|
||||
单 Session:最大 2MB output buffer
|
||||
全局:最大 N 个活跃 Session
|
||||
全局:最大 M MB Session buffer
|
||||
```
|
||||
|
||||
当达到任意全局上限时,新 Session 必须被拒绝并记录审计,而不是继续消耗内存。
|
||||
|
||||
RingBuffer 的覆盖行为只能覆盖旧输出,不得覆盖 session 元数据、错误状态或安全审计记录。
|
||||
|
||||
---
|
||||
|
||||
## 7.7 审计要求
|
||||
|
||||
至少记录以下安全事件:
|
||||
|
||||
```text
|
||||
security_denied
|
||||
policy_changed
|
||||
session_created
|
||||
session_expired
|
||||
session_killed
|
||||
session_owner_denied
|
||||
resource_limit_denied
|
||||
```
|
||||
|
||||
High Risk 操作的审计信息必须包含:
|
||||
|
||||
```text
|
||||
device
|
||||
actor / owner
|
||||
request id
|
||||
session id(如适用)
|
||||
tool
|
||||
result
|
||||
policy version
|
||||
timestamp
|
||||
```
|
||||
|
||||
审计日志不能因为 Session RingBuffer 达到上限而被覆盖。
|
||||
|
||||
---
|
||||
|
||||
## 7.8 协议兼容补充约束
|
||||
|
||||
旧 Agent 与新 Hub 混合运行期间:
|
||||
|
||||
1. 原有 `action=read/write/exec/probe` 字段继续有效。
|
||||
2. 新 `SubAction` 为可选字段。
|
||||
3. 新字段不能改变旧 Agent 对旧消息的既有语义。
|
||||
4. Hub 必须根据 Agent capability/version 判断是否可以下发新 SubAction。
|
||||
5. 对不支持新能力的 Agent,返回明确的 capability error,而不是让旧 Agent 猜测。
|
||||
6. 安全门禁必须在能力路由之前执行,避免通过旧 API 绕过新 Tool Registry。
|
||||
|
||||
---
|
||||
|
||||
## 7.9 实施前必须完成的设计验收
|
||||
|
||||
在进入 Phase 1 代码改造前,两位审核 Agent 应重点审查:
|
||||
|
||||
### A. 权威性
|
||||
|
||||
- Hub 是否始终是 EffectiveRisk 的唯一权威来源?
|
||||
- Agent 是否存在任何自升权路径?
|
||||
- 旧 API 是否可能绕过 Tool Registry?
|
||||
|
||||
### B. 一致性
|
||||
|
||||
- SQLite commit 与 snapshot publish 顺序是否正确?
|
||||
- Hub 重启能否确定性恢复策略?
|
||||
- snapshot version 是否足以定位策略变更?
|
||||
|
||||
### C. Session 安全
|
||||
|
||||
- session ownership 是否不可伪造?
|
||||
- Agent 重启后旧 session 是否必然失效?
|
||||
- stdin、stdout、session 数量是否存在全局资源上限?
|
||||
|
||||
### D. 向后兼容
|
||||
|
||||
- 老 Agent + 新 Hub 是否继续工作?
|
||||
- 新 Hub 是否能识别 Agent capability?
|
||||
- 新能力是否可能通过旧接口绕过门禁?
|
||||
|
||||
### E. 性能
|
||||
|
||||
- 热路径是否完全脱离 SQLite?
|
||||
- snapshot 是否真正 immutable / atomic?
|
||||
- session ring buffer 是否存在隐藏的额外复制?
|
||||
|
||||
**只有上述问题通过审核后,才进入 Phase 1 实现。**
|
||||
|
||||
---
|
||||
|
||||
# 8. 审核意见收敛修订(2026-10-02)
|
||||
|
||||
本章节根据第一轮 Agent 审核结果补充。**Phase 1 在本章节阻断项完成前不得进入代码实施。**
|
||||
|
||||
## 8.1 阻断项一:设备身份认证
|
||||
|
||||
`identify device` 不得等同于读取请求中的 `device` 字段。设备名称只能作为路由提示,不能作为授权依据。
|
||||
|
||||
### 8.1.1 权威身份模型
|
||||
|
||||
每个 Agent 必须拥有唯一设备身份以及与之绑定的设备凭证。Hub 必须先完成设备认证,再建立:
|
||||
|
||||
```text
|
||||
authenticated agent identity
|
||||
↓
|
||||
device ID
|
||||
↓
|
||||
PolicySnapshot lookup
|
||||
↓
|
||||
EffectiveRisk
|
||||
```
|
||||
|
||||
推荐优先采用 **per-agent credential**;部署条件允许时使用 mTLS。若采用 Agent Token,Token 必须:
|
||||
|
||||
- 与单一 Agent 身份绑定;
|
||||
- 可撤销;
|
||||
- 不得由客户端自行指定 device 后复用;
|
||||
- 传输必须经过受保护通道;
|
||||
- 认证失败不得进入安全策略查询阶段。
|
||||
|
||||
`device` 请求字段不得覆盖认证得到的 canonical device identity。
|
||||
|
||||
### 8.1.2 身份与策略绑定
|
||||
|
||||
策略查询必须使用认证层产生的 canonical device ID:
|
||||
|
||||
```go
|
||||
identity := authenticateAgent(r)
|
||||
if !identity.OK {
|
||||
deny()
|
||||
}
|
||||
policy := snapshot.Device(identity.DeviceID)
|
||||
```
|
||||
|
||||
禁止:
|
||||
|
||||
```go
|
||||
policy := snapshot.Device(r.Device)
|
||||
```
|
||||
|
||||
设备注册、凭证轮换、凭证撤销必须产生审计事件。具体凭证格式与密钥轮换流程在 Phase 1 实施设计中单独冻结。
|
||||
|
||||
---
|
||||
|
||||
## 8.2 阻断项二:kill_process 作用域
|
||||
|
||||
`kill_process` / `force_terminate` **绝不能接受任意 PID 作为授权对象**。
|
||||
|
||||
High Risk Session 必须建立进程归属关系:
|
||||
|
||||
```text
|
||||
Session
|
||||
└── Process Group / Process Tree
|
||||
├── root process
|
||||
├── child
|
||||
└── child...
|
||||
```
|
||||
|
||||
默认允许终止的对象仅为该 Session 创建的进程树。
|
||||
|
||||
必须拒绝:
|
||||
|
||||
- 不属于当前 Session 的 PID;
|
||||
- Hub / Agent 自身关键进程;
|
||||
- 未经单独授权的其他用户进程;
|
||||
- 通过伪造 PID、session ID 或 owner 字段进行的跨 Session 操作。
|
||||
|
||||
实现时应记录 root PID / process group ID,并通过 OS 级关系验证目标进程仍属于该 Session,而不是只相信客户端提供的 PID。
|
||||
|
||||
未来若需要管理员跨 Session 终止能力,必须作为独立能力和独立审计事件设计,不复用普通 `kill_process`。
|
||||
|
||||
---
|
||||
|
||||
## 8.3 阻断项三:Agent capability/version 握手
|
||||
|
||||
协议必须正式增加 capability/version 元数据,使 7.8 的混合版本策略可以实际落地。
|
||||
|
||||
建议扩展:
|
||||
|
||||
```go
|
||||
type Message struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Action string `json:"action,omitempty"`
|
||||
SubAction string `json:"sub_action,omitempty"`
|
||||
Device string `json:"device,omitempty"`
|
||||
Payload any `json:"payload,omitempty"`
|
||||
|
||||
ProtocolVersion string `json:"protocol_version,omitempty"`
|
||||
AgentVersion string `json:"agent_version,omitempty"`
|
||||
Capabilities []string `json:"capabilities,omitempty"`
|
||||
}
|
||||
```
|
||||
|
||||
为避免旧 Agent 解析失败,新增字段必须保持 optional;旧 Agent 忽略未知字段即可继续处理旧消息。
|
||||
|
||||
更严格的 capability 协商流程:
|
||||
|
||||
```text
|
||||
Agent connect
|
||||
↓
|
||||
identity authentication
|
||||
↓
|
||||
protocol/version handshake
|
||||
↓
|
||||
capability registry
|
||||
↓
|
||||
Hub records effective capabilities
|
||||
↓
|
||||
request routing
|
||||
```
|
||||
|
||||
Hub 不得仅根据版本字符串猜测能力。实际可用能力以 capability set 为准。
|
||||
|
||||
如果 Agent 不支持某个 `SubAction`:
|
||||
|
||||
```text
|
||||
capability_missing
|
||||
```
|
||||
|
||||
必须成为明确错误,不得静默降级到语义不同的危险操作。
|
||||
|
||||
---
|
||||
|
||||
## 8.4 威胁模型
|
||||
|
||||
三级安全体系主要解决的是 **调用方对受控设备的越权操作风险**,而不是保证已经被完全攻陷的 Agent 本身可信。
|
||||
|
||||
### T1:恶意调用方
|
||||
|
||||
目标:冒充设备、伪造风险等级、跨设备操作、跨 Session 操作。
|
||||
|
||||
防护:
|
||||
|
||||
- Agent 身份认证;
|
||||
- canonical device ID;
|
||||
- Hub authoritative PolicySnapshot;
|
||||
- Session ownership;
|
||||
- Tool Registry;
|
||||
- 审计。
|
||||
|
||||
### T2:有 Bug 的调用方
|
||||
|
||||
目标:错误调用 High API、重复创建 Session、资源耗尽。
|
||||
|
||||
防护:
|
||||
|
||||
- 参数验证;
|
||||
- per-device 并发限制;
|
||||
- rate limit;
|
||||
- Session/global resource cap;
|
||||
- fail-closed。
|
||||
|
||||
### T3:被攻陷的 Agent
|
||||
|
||||
如果攻击者已经取得 Agent 进程的等价本地执行权,则 Agent 内部校验不能被视为可信边界。
|
||||
|
||||
因此:
|
||||
|
||||
> Hub 门禁保护的是“未经授权的远程调用不能获得设备能力”,而不是“Agent 被完全攻陷后仍能阻止本地攻击者”。
|
||||
|
||||
Agent 被攻陷属于独立威胁域,应依赖最小权限、系统账户隔离、凭证撤销、节点隔离和重新注册等机制处理。
|
||||
|
||||
文档不得把 Agent 侧校验描述为能够抵御完全控制 Agent 的攻击者。
|
||||
|
||||
---
|
||||
|
||||
## 8.5 审计敏感数据脱敏
|
||||
|
||||
现有 `audit_logs.command` 等字段不得无条件记录完整命令或参数。
|
||||
|
||||
审计系统必须采用结构化事件优先:
|
||||
|
||||
```text
|
||||
command template / tool
|
||||
arguments metadata
|
||||
result
|
||||
risk
|
||||
actor
|
||||
request id
|
||||
```
|
||||
|
||||
对于可能包含 Secret 的字段,必须在进入持久化审计前脱敏,包括但不限于:
|
||||
|
||||
```text
|
||||
password
|
||||
passwd
|
||||
token
|
||||
access_token
|
||||
refresh_token
|
||||
api_key
|
||||
secret
|
||||
authorization
|
||||
cookie
|
||||
private_key
|
||||
```
|
||||
|
||||
Shell 命令中的敏感值不能仅依赖字段名识别;实现阶段应定义命令审计策略,至少做到:
|
||||
|
||||
1. 不默认记录完整 stdin;
|
||||
2. 对已识别敏感参数替换为 `[REDACTED]`;
|
||||
3. Secret 不得通过错误消息重新写入 audit;
|
||||
4. 原始命令仅在明确安全策略允许时保留。
|
||||
|
||||
---
|
||||
|
||||
## 8.6 回滚与混合版本路线
|
||||
|
||||
原第 5 节标题为“回滚路线图”,现补充实际策略。
|
||||
|
||||
### 8.6.1 Hub 升级失败
|
||||
|
||||
- 新版本不得在旧 schema 尚未兼容时直接删除旧字段;
|
||||
- DB migration 必须可检测版本;
|
||||
- migration 失败则 Hub 不进入正常服务状态;
|
||||
- 策略 snapshot 可以从旧兼容 schema 重建;
|
||||
- 升级前保留 DB 备份/快照。
|
||||
|
||||
### 8.6.2 新 Hub + 旧 Agent
|
||||
|
||||
旧 Agent 继续使用旧 API/旧 Action。
|
||||
|
||||
Hub 必须:
|
||||
|
||||
```text
|
||||
认证旧 Agent
|
||||
↓
|
||||
读取其 capability
|
||||
↓
|
||||
只下发它声明支持的能力
|
||||
```
|
||||
|
||||
不能因为 Hub 已升级就要求旧 Agent 自动支持新 SubAction。
|
||||
|
||||
### 8.6.3 新 Agent + 旧 Hub
|
||||
|
||||
新 Agent 必须保持旧协议兼容能力;若 Hub 不支持 capability handshake,新 Agent 使用 legacy compatibility mode,不得因此自行启用 High 新能力。
|
||||
|
||||
### 8.6.4 数据降级原则
|
||||
|
||||
数据库 schema 新增字段应尽量可选;新功能数据不能成为旧版本启动的硬依赖。
|
||||
|
||||
任何不可逆 migration 必须在正式 Phase 前单独评审。
|
||||
|
||||
---
|
||||
|
||||
## 8.7 Session ID 与进程安全参数
|
||||
|
||||
Session ID 必须使用 `crypto/rand` 生成,最低 **128-bit entropy**,并以不暴露内部 PID 的方式编码。
|
||||
|
||||
PID 仅作为内部 process identity 的组成部分,不作为 session credential。
|
||||
|
||||
Session authorization 必须同时验证:
|
||||
|
||||
```text
|
||||
authenticated device
|
||||
+ session ID
|
||||
+ owner
|
||||
+ session state
|
||||
+ expiry
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8.8 edit_block 的 TOCTOU 防护
|
||||
|
||||
`edit_block` 不能只做:
|
||||
|
||||
```text
|
||||
read -> verify -> rename
|
||||
```
|
||||
|
||||
因为读取后到替换前存在 TOCTOU 窗口。
|
||||
|
||||
实现至少需要以下一种一致性保护:
|
||||
|
||||
- 文件锁;或
|
||||
- generation / mtime / size / hash 校验后再提交;或
|
||||
- OS 支持的原子条件更新机制。
|
||||
|
||||
推荐:读取时计算 generation fingerprint,写回前重新验证;若文件已经发生变化则拒绝修改并返回 conflict,而不是覆盖第三方更新。
|
||||
|
||||
---
|
||||
|
||||
## 8.9 内存预算重新约束
|
||||
|
||||
原方案“Agent 常驻 20MB 以内”与 `2MB × N sessions` 必须统一解释。
|
||||
|
||||
新的约束是:
|
||||
|
||||
> **20MB 是 Agent 基础常驻预算;Session buffer 必须从剩余预算反推最大并发数,而不是无限叠加。**
|
||||
|
||||
因此实现前必须定义:
|
||||
|
||||
```text
|
||||
BaseMemoryBudget
|
||||
SessionBufferBudget
|
||||
MaxActiveSessions
|
||||
PerSessionBuffer
|
||||
```
|
||||
|
||||
满足:
|
||||
|
||||
```text
|
||||
BaseMemory + MaxSessionBufferBudget + safety margin
|
||||
<= approved Agent memory ceiling
|
||||
```
|
||||
|
||||
如果单 Session 仍采用 2MB,则 `MaxActiveSessions` 必须由压测和实际内存预算计算得出。
|
||||
|
||||
---
|
||||
|
||||
## 8.10 性能指标修正
|
||||
|
||||
删除或修正“整机 10W+ QPS”可能造成的误导。
|
||||
|
||||
准确表述应为:
|
||||
|
||||
> **安全门禁自身的策略读取路径不以 SQLite 为热路径,单次判定成本应保持在内存级别;端到端 API 吞吐仍受网络、Agent、磁盘、进程创建和实际 IO 限制。**
|
||||
|
||||
性能验收应分别测量:
|
||||
|
||||
1. PolicySnapshot lookup latency;
|
||||
2. authorization decision latency;
|
||||
3. API end-to-end latency;
|
||||
4. Agent execution throughput;
|
||||
5. process/session creation rate。
|
||||
|
||||
---
|
||||
|
||||
## 8.11 进程交互传输模型
|
||||
|
||||
`interact_with_process` 的实时 stdin/stdout 通道必须在实现前冻结。
|
||||
|
||||
设计目标:
|
||||
|
||||
```text
|
||||
Hub / MCP
|
||||
↓ stdin
|
||||
Agent Session
|
||||
↑ stdout/stderr stream
|
||||
```
|
||||
|
||||
传输协议必须明确:
|
||||
|
||||
- session binding;
|
||||
- reconnect 行为;
|
||||
- backpressure;
|
||||
- output cursor / offset;
|
||||
- heartbeat / timeout;
|
||||
- disconnect 后 Session 是否继续运行;
|
||||
- reconnect 后 owner 如何重新认证。
|
||||
|
||||
如果采用 HTTP/SSE、WebSocket 或轮询,必须在 Phase 3 实施设计中明确其安全和资源模型,不能由 handler 临时决定。
|
||||
|
||||
---
|
||||
|
||||
## 8.12 非 Session 类资源限制
|
||||
|
||||
全局资源控制不仅适用于 `start_process`。
|
||||
|
||||
### exec_command
|
||||
|
||||
必须增加:
|
||||
|
||||
- per-device concurrent exec limit;
|
||||
- 单命令执行时间上限;
|
||||
- 输出大小上限;
|
||||
- 创建速率限制。
|
||||
|
||||
防止通过大量同步 `exec_command` 造成 fork/process exhaustion。
|
||||
|
||||
### list_processes
|
||||
|
||||
进程命令行可能包含密码、Token、Cookie 等敏感信息。返回结果必须执行敏感信息处理,并限制返回规模。
|
||||
|
||||
### start_search / get_more_search_results
|
||||
|
||||
后台搜索属于全盘 IO 风险,应具备:
|
||||
|
||||
- per-device search concurrency;
|
||||
- 最大搜索范围/深度;
|
||||
- 最大结果数;
|
||||
- 超时;
|
||||
- 可取消任务;
|
||||
- 全局 IO 预算。
|
||||
|
||||
---
|
||||
|
||||
## 8.13 Phase 1 红队验收
|
||||
|
||||
除原 A–E 正向验收外,Phase 1 必须增加以下对抗用例:
|
||||
|
||||
1. 伪造 `{"risk":"high"}` 是否被拒绝;
|
||||
2. 使用合法 Agent A 凭证请求 device B 是否被拒绝;
|
||||
3. 旧 API 是否能绕过 Tool Registry;
|
||||
4. Session A 的 ID 是否能访问 Session B;
|
||||
5. Session A 是否能 kill 非自身进程;
|
||||
6. Agent 重启后旧 Session 是否失效;
|
||||
7. Policy snapshot 更新过程中是否出现半更新状态;
|
||||
8. SQLite 更新失败时是否错误发布新策略;
|
||||
9. 旧 Agent + 新 Hub 是否保持旧功能;
|
||||
10. 新能力是否在 capability 缺失时被错误下发;
|
||||
11. audit 是否泄露 password/token/cookie/private key;
|
||||
12. 并发 exec 是否能够超过 per-device 上限;
|
||||
13. search 是否能够无限占用 IO;
|
||||
14. RingBuffer / session 上限是否能防止内存线性增长。
|
||||
|
||||
---
|
||||
|
||||
## 8.14 Phase 1 开工闸门
|
||||
|
||||
Phase 1 只有在以下条件全部满足后才能开始:
|
||||
|
||||
```text
|
||||
[ ] Agent identity authentication model frozen
|
||||
[ ] Canonical device identity frozen
|
||||
[ ] kill_process process-tree scope frozen
|
||||
[ ] protocol capability/version handshake frozen
|
||||
[ ] Threat model accepted
|
||||
[ ] Audit redaction policy accepted
|
||||
[ ] DB migration / rollback strategy accepted
|
||||
[ ] Session ID generation frozen
|
||||
[ ] edit_block consistency strategy frozen
|
||||
[ ] Agent memory budget reconciled
|
||||
[ ] Streaming transport model frozen or explicitly deferred to Phase 3
|
||||
[ ] exec/search resource limits defined
|
||||
[ ] Red-team test plan accepted
|
||||
```
|
||||
|
||||
**本章节是 Phase 1 的设计闸门,不是可选建议。任何阻断项未关闭时,不得以“先实现再补安全”为理由进入代码改造。**
|
||||
@@ -0,0 +1,109 @@
|
||||
# 《VPS-Commander 平滑升级改造与三级安全拦截实施方案》
|
||||
|
||||
## 1. 改造目标与背景
|
||||
本项目计划全量复刻 **Desktop Commander(DC)** 在终端与文件系统上的核心工程能力(包括局部块级精准替换、后台长进程生命周期管理、交互式 stdin 注入、结构化目录遍历与只读检索),并将其无缝接入 **Low(低风险)/ Medium(中风险)/ High(高风险)** 三级安全门禁体系。
|
||||
|
||||
**核心红线与验收标准:**
|
||||
1. **服务不中断**:升级过程不影响正在运行的 Agent 探针与 Hub 中心。
|
||||
2. **协议向后兼容**:旧版 Agent 与新版 Hub 混合共存,老接口绝不废弃。
|
||||
3. **性能零损耗**:杜绝动态运行时映射,安全校验在编译期即已绑定。
|
||||
4. **轻量化保真**:继续保持纯 Go 静态编译的高效特性,严控内存占用(常驻内存锁定在 20MB 以内)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 工具池全量复刻与三级风险定级表(静态强绑定)
|
||||
|
||||
所有功能根据系统破坏力与副作用大小,在**编译期**严格归属于三级风险体系:
|
||||
|
||||
| 风险等级 (Level) | 行为边界定义 | 包含的复刻工具 (DC 标杆) | 允许放行的安全模式 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| 🟢 **Low(只读/感知)** | **纯只读、无状态改变、无系统副作用** | • `read_file` (支持切片与 Tail)<br>• `read_multiple_files`<br>• `list_directory` (结构化目录树)<br>• `get_file_info` (元数据)<br>• `start_search` / `get_more_search_results`<br>• `list_processes` / `list_sessions`<br>• `read_process_output` (拉取输出) | **Low**<br>**Medium**<br>**High** |
|
||||
| 🟡 **Medium(文件写)** | **文件与目录变更,但严禁拉起任意二进制或执行命令** | • `edit_block` (局部文本块精准替换,核心)<br>• `write_file` (文件新建/全量写入)<br>• `create_directory` (新建目录)<br>• `move_file` (移动/重命名) | **Medium**<br>**High**<br>*(Low 拦截)* |
|
||||
| 🔴 **High(完全控制)** | **具备操作系统执行权、进程生命周期调度与管道干预** | • `exec_command` (同步短命令)<br>• `start_process` (后台异步启动长进程)<br>• `interact_with_process` (stdin 交互写入)<br>• `kill_process` / `force_terminate` (终止进程) | **High**<br>*(Low / Medium 拦截)* |
|
||||
|
||||
---
|
||||
|
||||
## 3. 架构改造与平滑过渡设计
|
||||
|
||||
### 3.1 协议层平滑升级(零破坏向后兼容)
|
||||
在 `internal/cluster/protocol.go` 中,保留原有字段,新增可选的扩展动作:
|
||||
```go
|
||||
type Message struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Action string `json:"action,omitempty"` // 保持原有字段: "read" / "write" / "exec" / "probe"
|
||||
SubAction string `json:"sub_action,omitempty"` // ✨ 增量动作: "edit_block", "start_process" 等
|
||||
Device string `json:"device,omitempty"`
|
||||
Payload any `json:"payload,omitempty"`
|
||||
...
|
||||
}
|
||||
```
|
||||
* **兼容保障**:老版本 Agent 接收到带 `SubAction` 的 JSON 消息时会自动忽略多余字段,继续按老逻辑工作;升级后的 Agent 优先路由给 `SubAction` 处理。
|
||||
|
||||
### 3.2 Hub 门禁与高并发性能优化(读写分离)
|
||||
现有系统每次请求均去 SQLite 查询策略,高并发下存在文件锁瓶颈。改造后引入 **RWMutex 内存策略快照**:
|
||||
1. **读路径(Fast Path,纳秒级)**:
|
||||
```go
|
||||
// 常量数值定义,直接内联比较
|
||||
const ( RiskLow = 1; RiskMedium = 2; RiskHigh = 3 )
|
||||
|
||||
func (s *Server) requireSecurity(w http.ResponseWriter, r *http.Request, device string, requiredRisk int, detail string) bool {
|
||||
allowed := s.getEffectiveRiskLevel(device) // 查内存 RLock,耗时 < 10ns
|
||||
if allowed >= requiredRisk {
|
||||
return true
|
||||
}
|
||||
// 记录 audit_logs ("security_denied", 403) 并返回拦截响应
|
||||
return false
|
||||
}
|
||||
```
|
||||
2. **写路径(Slow Path,低频)**:
|
||||
* 仅在管理员通过 Web 界面更改安全策略时,写一次 SQLite 并原子更新内存缓存。
|
||||
3. **老 API 零改动**:
|
||||
* 原有 `/api/v1/devices/exec`、`/read`、`/write` 继续保留,老脚本老客户端零感知。
|
||||
|
||||
### 3.3 Agent 端核心引擎实现(防资源膨胀设计)
|
||||
* **`edit_block` 引擎**:
|
||||
* 读取原文件后校验 `old_text` 全局唯一性,唯一时单次替换并使用临时文件进行原子覆写(`os.Rename`)。
|
||||
* 相比原有全量上传,网络传输和内存开销下降 95%。
|
||||
* **长进程与 PTY 会话引擎(`start_process` 等)**:
|
||||
* Agent 内部建立轻量 `SessionManager`,挂接内核标准输入输出管道。
|
||||
* **硬编码内存锁(Circular RingBuffer)**:每个进程会话分配最大 2MB 环形日志缓冲区,达到上限自动覆盖最早输出,**从物理上杜绝日志死循环导致的内存溢出(OOM)**。
|
||||
|
||||
---
|
||||
|
||||
## 4. 资源开销评估与性能上限控制
|
||||
|
||||
得益于纯 Go 原生静态编译,系统坚决不引入任何 Node.js/Python 运行时,资源开销保持极致克制:
|
||||
|
||||
| 评估指标 | 改造前基准(实测) | 改造后预期 | 性能/资源防护机制 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Agent 静默内存** | ~13 MB | **~15 MB - 18 MB** | 零后台轮询,事件驱动 |
|
||||
| **Agent 峰值内存** | 随命令大小波动 | **基准 + (2MB × 活跃会话数)** | 环形缓冲区硬顶锁定,防内存泄露 |
|
||||
| **Hub 服务端内存** | ~16 MB | **~18 MB - 22 MB** | 内存门禁仅占不到 10KB |
|
||||
| **二进制体积** | ~9.4 MB | **~11 MB - 13 MB** | 静态单文件编译,极易分发部署 |
|
||||
| **安全判定延迟** | 毫秒级(查 SQLite) | **纳秒级(内存读锁)** | 单机可轻松支撑 10W+ QPS 门禁并发 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 四阶段实施与回滚路线图(稳健落地)
|
||||
|
||||
* **Phase 1:服务端门禁升级与内存读缓存**
|
||||
* 在 Hub 端落地 `RWMutex` 安全策略缓存;
|
||||
* API 入口统一接入 `requireSecurity(..., RiskLevel)`;
|
||||
* *验证标准*:旧版 4 项基础功能与 Web 面板完好,并发查询 QPS 大幅提升。
|
||||
* **Phase 2:落地中风险神器 `edit_block`**
|
||||
* Agent 端实现块级精准替换算法;
|
||||
* Hub 暴露 `/api/v1/devices/file/edit_block` 并注册至 MCP Adapter;
|
||||
* *验证标准*:在 Medium 模式下可正常修配置文件,在 Low 模式下被精确阻断并记入审计。
|
||||
* **Phase 3:落地高风险长进程引擎**
|
||||
* Agent 端引入带 RingBuffer 的 `SessionManager`;
|
||||
* 实现 `start_process`、`read_process_output`、`interact_with_process`、`kill_process`;
|
||||
* *验证标准*:跑耗时任务不会超时断连,支持实时 Tail 查看输出与注入 stdin。
|
||||
* **Phase 4:落地只读结构化文件与系统感知(Low)**
|
||||
* 实现 `list_directory`、`get_file_info` 及后台异步只读搜索。
|
||||
|
||||
---
|
||||
|
||||
## 6. 评估与审计重点建议
|
||||
1. **安全维度**:Low/Medium/High 对能力的切分是否彻底杜绝了提权与逃逸风险?
|
||||
2. **性能维度**:使用内存 RWMutex + 编译期静态安全级别判定,是否彻底解决了单文件 SQLite 高频读瓶颈?
|
||||
3. **稳定性维度**:为每个长进程会话限定 RingBuffer 内存上限,是否有效防止了边缘 VPS 探针被日志撑爆?
|
||||
@@ -0,0 +1,491 @@
|
||||
# 《VPS-Commander 平滑升级改造与三级安全拦截实施方案》
|
||||
|
||||
## 1. 改造目标与背景
|
||||
本项目计划全量复刻 **Desktop Commander(DC)** 在终端与文件系统上的核心工程能力(包括局部块级精准替换、后台长进程生命周期管理、交互式 stdin 注入、结构化目录遍历与只读检索),并将其无缝接入 **Low(低风险)/ Medium(中风险)/ High(高风险)** 三级安全门禁体系。
|
||||
|
||||
**核心红线与验收标准:**
|
||||
1. **服务不中断**:升级过程不影响正在运行的 Agent 探针与 Hub 中心。
|
||||
2. **协议向后兼容**:旧版 Agent 与新版 Hub 混合共存,老接口绝不废弃。
|
||||
3. **性能零损耗**:杜绝动态运行时映射,安全校验在编译期即已绑定。
|
||||
4. **轻量化保真**:继续保持纯 Go 静态编译的高效特性,严控内存占用(常驻内存锁定在 20MB 以内)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 工具池全量复刻与三级风险定级表(静态强绑定)
|
||||
|
||||
所有功能根据系统破坏力与副作用大小,在**编译期**严格归属于三级风险体系:
|
||||
|
||||
| 风险等级 (Level) | 行为边界定义 | 包含的复刻工具 (DC 标杆) | 允许放行的安全模式 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| 🟢 **Low(只读/感知)** | **纯只读、无状态改变、无系统副作用** | • `read_file` (支持切片与 Tail)<br>• `read_multiple_files`<br>• `list_directory` (结构化目录树)<br>• `get_file_info` (元数据)<br>• `start_search` / `get_more_search_results`<br>• `list_processes` / `list_sessions`<br>• `read_process_output` (拉取输出) | **Low**<br>**Medium**<br>**High** |
|
||||
| 🟡 **Medium(文件写)** | **文件与目录变更,但严禁拉起任意二进制或执行命令** | • `edit_block` (局部文本块精准替换,核心)<br>• `write_file` (文件新建/全量写入)<br>• `create_directory` (新建目录)<br>• `move_file` (移动/重命名) | **Medium**<br>**High**<br>*(Low 拦截)* |
|
||||
| 🔴 **High(完全控制)** | **具备操作系统执行权、进程生命周期调度与管道干预** | • `exec_command` (同步短命令)<br>• `start_process` (后台异步启动长进程)<br>• `interact_with_process` (stdin 交互写入)<br>• `kill_process` / `force_terminate` (终止进程) | **High**<br>*(Low / Medium 拦截)* |
|
||||
|
||||
---
|
||||
|
||||
## 3. 架构改造与平滑过渡设计
|
||||
|
||||
### 3.1 协议层平滑升级(零破坏向后兼容)
|
||||
在 `internal/cluster/protocol.go` 中,保留原有字段,新增可选的扩展动作:
|
||||
```go
|
||||
type Message struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Action string `json:"action,omitempty"` // 保持原有字段: "read" / "write" / "exec" / "probe"
|
||||
SubAction string `json:"sub_action,omitempty"` // ✨ 增量动作: "edit_block", "start_process" 等
|
||||
Device string `json:"device,omitempty"`
|
||||
Payload any `json:"payload,omitempty"`
|
||||
...
|
||||
}
|
||||
```
|
||||
* **兼容保障**:老版本 Agent 接收到带 `SubAction` 的 JSON 消息时会自动忽略多余字段,继续按老逻辑工作;升级后的 Agent 优先路由给 `SubAction` 处理。
|
||||
|
||||
### 3.2 Hub 门禁与高并发性能优化(读写分离)
|
||||
现有系统每次请求均去 SQLite 查询策略,高并发下存在文件锁瓶颈。改造后引入 **RWMutex 内存策略快照**:
|
||||
1. **读路径(Fast Path,纳秒级)**:
|
||||
```go
|
||||
// 常量数值定义,直接内联比较
|
||||
const ( RiskLow = 1; RiskMedium = 2; RiskHigh = 3 )
|
||||
|
||||
func (s *Server) requireSecurity(w http.ResponseWriter, r *http.Request, device string, requiredRisk int, detail string) bool {
|
||||
allowed := s.getEffectiveRiskLevel(device) // 查内存 RLock,耗时 < 10ns
|
||||
if allowed >= requiredRisk {
|
||||
return true
|
||||
}
|
||||
// 记录 audit_logs ("security_denied", 403) 并返回拦截响应
|
||||
return false
|
||||
}
|
||||
```
|
||||
2. **写路径(Slow Path,低频)**:
|
||||
* 仅在管理员通过 Web 界面更改安全策略时,写一次 SQLite 并原子更新内存缓存。
|
||||
3. **老 API 零改动**:
|
||||
* 原有 `/api/v1/devices/exec`、`/read`、`/write` 继续保留,老脚本老客户端零感知。
|
||||
|
||||
### 3.3 Agent 端核心引擎实现(防资源膨胀设计)
|
||||
* **`edit_block` 引擎**:
|
||||
* 读取原文件后校验 `old_text` 全局唯一性,唯一时单次替换并使用临时文件进行原子覆写(`os.Rename`)。
|
||||
* 相比原有全量上传,网络传输和内存开销下降 95%。
|
||||
* **长进程与 PTY 会话引擎(`start_process` 等)**:
|
||||
* Agent 内部建立轻量 `SessionManager`,挂接内核标准输入输出管道。
|
||||
* **硬编码内存锁(Circular RingBuffer)**:每个进程会话分配最大 2MB 环形日志缓冲区,达到上限自动覆盖最早输出,**从物理上杜绝日志死循环导致的内存溢出(OOM)**。
|
||||
|
||||
---
|
||||
|
||||
## 4. 资源开销评估与性能上限控制
|
||||
|
||||
得益于纯 Go 原生静态编译,系统坚决不引入任何 Node.js/Python 运行时,资源开销保持极致克制:
|
||||
|
||||
| 评估指标 | 改造前基准(实测) | 改造后预期 | 性能/资源防护机制 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Agent 静默内存** | ~13 MB | **~15 MB - 18 MB** | 零后台轮询,事件驱动 |
|
||||
| **Agent 峰值内存** | 随命令大小波动 | **基准 + (2MB × 活跃会话数)** | 环形缓冲区硬顶锁定,防内存泄露 |
|
||||
| **Hub 服务端内存** | ~16 MB | **~18 MB - 22 MB** | 内存门禁仅占不到 10KB |
|
||||
| **二进制体积** | ~9.4 MB | **~11 MB - 13 MB** | 静态单文件编译,极易分发部署 |
|
||||
| **安全判定延迟** | 毫秒级(查 SQLite) | **纳秒级(内存读锁)** | 单机可轻松支撑 10W+ QPS 门禁并发 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 四阶段实施与回滚路线图(稳健落地)
|
||||
|
||||
* **Phase 1:服务端门禁升级与内存读缓存**
|
||||
* 在 Hub 端落地 `RWMutex` 安全策略缓存;
|
||||
* API 入口统一接入 `requireSecurity(..., RiskLevel)`;
|
||||
* *验证标准*:旧版 4 项基础功能与 Web 面板完好,并发查询 QPS 大幅提升。
|
||||
* **Phase 2:落地中风险神器 `edit_block`**
|
||||
* Agent 端实现块级精准替换算法;
|
||||
* Hub 暴露 `/api/v1/devices/file/edit_block` 并注册至 MCP Adapter;
|
||||
* *验证标准*:在 Medium 模式下可正常修配置文件,在 Low 模式下被精确阻断并记入审计。
|
||||
* **Phase 3:落地高风险长进程引擎**
|
||||
* Agent 端引入带 RingBuffer 的 `SessionManager`;
|
||||
* 实现 `start_process`、`read_process_output`、`interact_with_process`、`kill_process`;
|
||||
* *验证标准*:跑耗时任务不会超时断连,支持实时 Tail 查看输出与注入 stdin。
|
||||
* **Phase 4:落地只读结构化文件与系统感知(Low)**
|
||||
* 实现 `list_directory`、`get_file_info` 及后台异步只读搜索。
|
||||
|
||||
---
|
||||
|
||||
## 6. 评估与审计重点建议
|
||||
1. **安全维度**:Low/Medium/High 对能力的切分是否彻底杜绝了提权与逃逸风险?
|
||||
2. **性能维度**:使用内存 RWMutex + 编译期静态安全级别判定,是否彻底解决了单文件 SQLite 高频读瓶颈?
|
||||
3. **稳定性维度**:为每个长进程会话限定 RingBuffer 内存上限,是否有效防止了边缘 VPS 探针被日志撑爆?
|
||||
|
||||
---
|
||||
|
||||
# 7. 架构收敛修订(2026-10-02)
|
||||
|
||||
> 本章节在进入代码实施前增加,用于两位外部 Agent 审核。原方案的工具分级、四阶段路线和向后兼容原则继续保留;本章节对安全权威、策略一致性、工具注册以及高风险 Session 生命周期作进一步约束。
|
||||
|
||||
## 7.1 安全等级的正确边界:静态工具风险 + 运行时设备策略
|
||||
|
||||
原方案中“静态强绑定”应准确解释为:**工具所需风险等级在编译期固定,是否允许执行在运行时由 Hub 的权威策略决定。**
|
||||
|
||||
不得将设备当前 Low/Medium/High 策略编译进 Agent,也不得允许 Agent 自行提升自身安全等级。
|
||||
|
||||
### 7.1.1 工具风险等级
|
||||
|
||||
每个工具在代码注册表中拥有不可运行时修改的 `RequiredRisk`:
|
||||
|
||||
```go
|
||||
const (
|
||||
RiskLow = 1
|
||||
RiskMedium = 2
|
||||
RiskHigh = 3
|
||||
)
|
||||
|
||||
type ToolSpec struct {
|
||||
Name string
|
||||
RequiredRisk int
|
||||
ReadOnly bool
|
||||
}
|
||||
```
|
||||
|
||||
示例:
|
||||
|
||||
```text
|
||||
read_file / list_directory / search -> Low
|
||||
edit_block / write_file / move_file -> Medium
|
||||
exec_command / start_process / stdin -> High
|
||||
```
|
||||
|
||||
禁止通过 Web 面板、Agent 配置文件或远端请求动态修改工具自身的 `RequiredRisk`。
|
||||
|
||||
### 7.1.2 设备有效策略
|
||||
|
||||
设备的 `EffectiveRisk` 是 Hub 运行时策略,不属于 Agent 自主能力。
|
||||
|
||||
请求授权模型:
|
||||
|
||||
```text
|
||||
Request
|
||||
-> identify device
|
||||
-> identify ToolSpec.RequiredRisk
|
||||
-> read Hub PolicySnapshot
|
||||
-> compare EffectiveRisk >= RequiredRisk
|
||||
-> allow / deny
|
||||
```
|
||||
|
||||
因此完整安全边界为:
|
||||
|
||||
**编译期固定“工具需要什么权限” + 运行时决定“该设备当前获得什么权限”。**
|
||||
|
||||
---
|
||||
|
||||
## 7.2 Policy Store 与 Policy Snapshot 一致性模型
|
||||
|
||||
SQLite 继续作为持久化权威源(durable source of truth),但请求热路径禁止每次查询 SQLite。
|
||||
|
||||
### 7.2.1 数据流
|
||||
|
||||
```text
|
||||
Admin Web
|
||||
|
|
||||
v
|
||||
SQLite transaction
|
||||
|
|
||||
v
|
||||
Build new immutable PolicySnapshot
|
||||
|
|
||||
v
|
||||
Atomic publish / swap
|
||||
|
|
||||
v
|
||||
Request fast path
|
||||
```
|
||||
|
||||
请求只读取当前不可变 snapshot;不在请求过程中修改策略对象。
|
||||
|
||||
### 7.2.2 更新原则
|
||||
|
||||
策略修改必须满足:
|
||||
|
||||
1. SQLite 写入成功后才允许发布新 snapshot。
|
||||
2. SQLite 写失败时,内存策略保持旧版本。
|
||||
3. snapshot 发布必须是原子操作,不允许出现半更新状态。
|
||||
4. Hub 启动时必须从 SQLite 完整重建 snapshot。
|
||||
5. snapshot 应携带单调递增 `Version`,便于审计和诊断。
|
||||
6. 审计记录应包含 `device`, `oldRisk`, `newRisk`, `version`, `actor`, `timestamp`。
|
||||
|
||||
推荐结构:
|
||||
|
||||
```go
|
||||
type PolicySnapshot struct {
|
||||
Version uint64
|
||||
Devices map[string]DevicePolicy
|
||||
CreatedAt time.Time
|
||||
}
|
||||
```
|
||||
|
||||
热路径原则:
|
||||
|
||||
```text
|
||||
load current snapshot
|
||||
-> lookup device
|
||||
-> compare integer risk
|
||||
-> allow/deny
|
||||
```
|
||||
|
||||
不得在高频 API 请求中重新读取 SQLite 策略表。
|
||||
|
||||
### 7.2.3 故障安全
|
||||
|
||||
如果 Hub 无法加载有效策略 snapshot:
|
||||
|
||||
- 不得默认放行 High。
|
||||
- 不得从请求参数接受临时风险等级。
|
||||
- 对需要 Medium/High 的操作默认拒绝。
|
||||
- Low 只读能力是否可继续开放,必须由启动时的明确安全默认策略决定,并记录审计事件。
|
||||
|
||||
---
|
||||
|
||||
## 7.3 Tool Registry:统一能力与风险注册表
|
||||
|
||||
避免各 API handler 自己实现不同的安全判断。所有能力必须进入统一 Tool Registry。
|
||||
|
||||
建议:
|
||||
|
||||
```go
|
||||
type ToolSpec struct {
|
||||
Name string
|
||||
RequiredRisk int
|
||||
Category string
|
||||
ReadOnly bool
|
||||
Description string
|
||||
}
|
||||
```
|
||||
|
||||
例如:
|
||||
|
||||
```text
|
||||
read_file Low
|
||||
read_multiple_files Low
|
||||
list_directory Low
|
||||
get_file_info Low
|
||||
start_search Low
|
||||
get_more_search_results Low
|
||||
list_processes Low
|
||||
list_sessions Low
|
||||
read_process_output Low
|
||||
|
||||
edit_block Medium
|
||||
write_file Medium
|
||||
create_directory Medium
|
||||
move_file Medium
|
||||
|
||||
exec_command High
|
||||
start_process High
|
||||
interact_with_process High
|
||||
kill_process High
|
||||
force_terminate High
|
||||
```
|
||||
|
||||
API、MCP Adapter 和内部调用均通过 Registry 获取 `RequiredRisk`,不得在多个入口复制风险数字。
|
||||
|
||||
---
|
||||
|
||||
## 7.4 Agent 信任边界
|
||||
|
||||
Agent 是执行者,不是安全策略的最终裁决者。
|
||||
|
||||
Hub 是设备授权策略的权威来源。
|
||||
|
||||
但 Agent 仍必须执行本地最低限度安全校验,包括:
|
||||
|
||||
- 请求格式与参数校验;
|
||||
- session 所有权校验;
|
||||
- session 是否仍然有效;
|
||||
- 单次输入/输出大小限制;
|
||||
- 超时和资源限制;
|
||||
- 不接受客户端自行声明的 `RiskLevel` 作为授权依据。
|
||||
|
||||
Agent 不得因为请求中携带:
|
||||
|
||||
```json
|
||||
{"risk":"high"}
|
||||
```
|
||||
|
||||
或类似字段而自行获得 High 权限。
|
||||
|
||||
如果协议未来需要携带授权信息,应使用 Hub 生成的受保护授权上下文,并绑定:
|
||||
|
||||
```text
|
||||
device + request/session + policy version + expiry
|
||||
```
|
||||
|
||||
具体签名/令牌方案在实现阶段单独评审。
|
||||
|
||||
---
|
||||
|
||||
## 7.5 High Risk SessionManager 安全模型
|
||||
|
||||
`start_process`、`interact_with_process`、`kill_process` 不应被视为普通 HTTP 命令,而应视为一个受生命周期管理的高风险 Session。
|
||||
|
||||
### 7.5.1 Session 属性
|
||||
|
||||
每个 Session 至少包含:
|
||||
|
||||
```go
|
||||
type ProcessSession struct {
|
||||
ID string
|
||||
Owner string
|
||||
Device string
|
||||
PID int
|
||||
CreatedAt time.Time
|
||||
LastAccess time.Time
|
||||
ExpiresAt time.Time
|
||||
State string
|
||||
OutputBytes uint64
|
||||
}
|
||||
```
|
||||
|
||||
Session ID 必须不可预测,并且不能复用操作系统 PID 作为唯一身份。
|
||||
|
||||
### 7.5.2 所有权
|
||||
|
||||
只有创建 Session 的授权调用方才能:
|
||||
|
||||
- 读取该 Session 输出;
|
||||
- 向 stdin 写入数据;
|
||||
- 终止该 Session。
|
||||
|
||||
管理员级操作如果未来需要跨 Owner 接管 Session,应定义明确的审计事件和单独权限,不得通过普通 session API 隐式获得。
|
||||
|
||||
### 7.5.3 生命周期
|
||||
|
||||
```text
|
||||
start_process
|
||||
|
|
||||
v
|
||||
RUNNING
|
||||
/ \
|
||||
/ \
|
||||
EXITED EXPIRED
|
||||
| |
|
||||
+----+---+
|
||||
v
|
||||
CLEANUP
|
||||
```
|
||||
|
||||
Agent 重启后所有旧 Session 必须失效,不得从持久化文件自动恢复可写 stdin 的旧 Session。
|
||||
|
||||
### 7.5.4 时间限制
|
||||
|
||||
Session 必须具备:
|
||||
|
||||
- 最大生命周期;
|
||||
- 空闲超时;
|
||||
- stdin 单次大小限制;
|
||||
- stdin 速率限制;
|
||||
- 输出缓冲区上限。
|
||||
|
||||
具体默认数值在实现前通过压测确定,不在设计阶段硬编码未经验证的数值。
|
||||
|
||||
---
|
||||
|
||||
## 7.6 RingBuffer 与全局资源上限
|
||||
|
||||
原方案中的“2MB × 活跃 Session”只能作为单 Session 上限,不应视为 Agent 的总内存预算。
|
||||
|
||||
必须同时存在:
|
||||
|
||||
```text
|
||||
per-session output cap
|
||||
+
|
||||
max active sessions
|
||||
+
|
||||
agent-wide session buffer cap
|
||||
+
|
||||
process creation rate limit
|
||||
```
|
||||
|
||||
例如:
|
||||
|
||||
```text
|
||||
单 Session:最大 2MB output buffer
|
||||
全局:最大 N 个活跃 Session
|
||||
全局:最大 M MB Session buffer
|
||||
```
|
||||
|
||||
当达到任意全局上限时,新 Session 必须被拒绝并记录审计,而不是继续消耗内存。
|
||||
|
||||
RingBuffer 的覆盖行为只能覆盖旧输出,不得覆盖 session 元数据、错误状态或安全审计记录。
|
||||
|
||||
---
|
||||
|
||||
## 7.7 审计要求
|
||||
|
||||
至少记录以下安全事件:
|
||||
|
||||
```text
|
||||
security_denied
|
||||
policy_changed
|
||||
session_created
|
||||
session_expired
|
||||
session_killed
|
||||
session_owner_denied
|
||||
resource_limit_denied
|
||||
```
|
||||
|
||||
High Risk 操作的审计信息必须包含:
|
||||
|
||||
```text
|
||||
device
|
||||
actor / owner
|
||||
request id
|
||||
session id(如适用)
|
||||
tool
|
||||
result
|
||||
policy version
|
||||
timestamp
|
||||
```
|
||||
|
||||
审计日志不能因为 Session RingBuffer 达到上限而被覆盖。
|
||||
|
||||
---
|
||||
|
||||
## 7.8 协议兼容补充约束
|
||||
|
||||
旧 Agent 与新 Hub 混合运行期间:
|
||||
|
||||
1. 原有 `action=read/write/exec/probe` 字段继续有效。
|
||||
2. 新 `SubAction` 为可选字段。
|
||||
3. 新字段不能改变旧 Agent 对旧消息的既有语义。
|
||||
4. Hub 必须根据 Agent capability/version 判断是否可以下发新 SubAction。
|
||||
5. 对不支持新能力的 Agent,返回明确的 capability error,而不是让旧 Agent 猜测。
|
||||
6. 安全门禁必须在能力路由之前执行,避免通过旧 API 绕过新 Tool Registry。
|
||||
|
||||
---
|
||||
|
||||
## 7.9 实施前必须完成的设计验收
|
||||
|
||||
在进入 Phase 1 代码改造前,两位审核 Agent 应重点审查:
|
||||
|
||||
### A. 权威性
|
||||
|
||||
- Hub 是否始终是 EffectiveRisk 的唯一权威来源?
|
||||
- Agent 是否存在任何自升权路径?
|
||||
- 旧 API 是否可能绕过 Tool Registry?
|
||||
|
||||
### B. 一致性
|
||||
|
||||
- SQLite commit 与 snapshot publish 顺序是否正确?
|
||||
- Hub 重启能否确定性恢复策略?
|
||||
- snapshot version 是否足以定位策略变更?
|
||||
|
||||
### C. Session 安全
|
||||
|
||||
- session ownership 是否不可伪造?
|
||||
- Agent 重启后旧 session 是否必然失效?
|
||||
- stdin、stdout、session 数量是否存在全局资源上限?
|
||||
|
||||
### D. 向后兼容
|
||||
|
||||
- 老 Agent + 新 Hub 是否继续工作?
|
||||
- 新 Hub 是否能识别 Agent capability?
|
||||
- 新能力是否可能通过旧接口绕过门禁?
|
||||
|
||||
### E. 性能
|
||||
|
||||
- 热路径是否完全脱离 SQLite?
|
||||
- snapshot 是否真正 immutable / atomic?
|
||||
- session ring buffer 是否存在隐藏的额外复制?
|
||||
|
||||
**只有上述问题通过审核后,才进入 Phase 1 实现。**
|
||||
@@ -0,0 +1,433 @@
|
||||
# VPS-Commander 双通道架构与安全整改——送审交接文档
|
||||
|
||||
**文档版本:** 2026-10-02 / Review Handoff v1
|
||||
**项目:** VPS-Commander v2.0
|
||||
**用途:** 提交外部审核,审核通过后作为生产上线前置依据
|
||||
|
||||
---
|
||||
|
||||
## 1. 本次交接目标
|
||||
|
||||
本次开发针对双通道架构重构及此前审核专家 A/B 提出的安全、并发、权限、会话和文件操作问题进行集中整改。
|
||||
|
||||
本文件只描述**当前代码实际完成状态**,不把尚未部署到生产的代码描述为“已上线”。
|
||||
|
||||
当前原则:
|
||||
|
||||
- 生产 Hub / Agent 在本轮整改过程中**没有重启**。
|
||||
- 所有新增能力先在代码与测试环境完成验证。
|
||||
- 生产切换采用分阶段、可回滚方式。
|
||||
- 审核通过后,才进入生产上线阶段。
|
||||
|
||||
---
|
||||
|
||||
## 2. 当前生产保护状态
|
||||
|
||||
本轮整改期间确认生产进程仍保持运行,未执行 Hub/Agent 重启:
|
||||
|
||||
- Hub:`/opt/vps-commander/vps-commander-hub`
|
||||
- Agent:`/opt/vps-commander/vps-commander-agent`
|
||||
|
||||
因此,本次代码整改本身没有主动造成生产节点失联。
|
||||
|
||||
**注意:** 当前生产进程运行的是现有部署版本,不等同于本工作树代码已经上线。
|
||||
|
||||
---
|
||||
|
||||
## 3. 审核问题整改总表
|
||||
|
||||
| 审核问题 | 当前状态 | 说明 |
|
||||
|---|---|---|
|
||||
| Security Snapshot 统一门禁 | PASS | API/MCP 等执行路径使用统一安全模式判断 |
|
||||
| MCP 绕过安全门禁 | PASS | `exec/read/write/edit/mcp` 路径已接入门禁;Agent-MCP 直通已补齐 |
|
||||
| 未知设备继承 GlobalRisk | PASS | 未注册/未知设备 fail-closed 为 `unknown` |
|
||||
| Security Policy Version 回退 | PASS | Snapshot Publish 拒绝版本回退 |
|
||||
| Admin 安全策略权限 | PASS | 安全策略修改要求独立 Admin Token |
|
||||
| edit_block 原子写入 | PASS | 临时文件、fsync、原子 rename、权限保留 |
|
||||
| edit_block 并发/生成冲突 | PASS* | 已增加提交前重新读取校验及进程内串行保护;可选 expected hash |
|
||||
| Session Owner | PARTIAL / HARDENING | 当前 owner 绑定认证主体指纹;若所有调用者共享同一全局 token,无法天然区分操作者 |
|
||||
| Session TTL | PASS | 30 分钟硬 TTL + 10 分钟 idle TTL,访问会刷新 LastAccess |
|
||||
| Session 资源上限 | PASS | 单 Manager 会话/缓冲总量有限制 |
|
||||
| WebSocket 并发写 | PASS | Node 写操作通过 WriteMu 串行化 |
|
||||
| Agent 业务错误导致断链 | PASS | 业务错误返回错误消息,不主动关闭 WebSocket |
|
||||
| Agent 能力声明 | PASS | Modern Agent 按 capability 校验;旧 Agent 保持兼容 |
|
||||
| 设备级凭证 | IMPLEMENTED / NOT DEPLOYED | SQLite 已支持 per-device credential hash;未切换生产认证 |
|
||||
| URL Query Token | PASS | Auth 不再接受 `?token/?key/?api_key` |
|
||||
| 审计记录 | PASS | 关键安全拒绝、MCP 调用等路径具备审计 |
|
||||
| 审计敏感信息治理 | HARDENING | 仍建议上线前进一步检查 command/error 的敏感字段脱敏 |
|
||||
| 全局 exec/search 资源配额 | HARDENING | 已有 session/ring buffer 限制,但仍可进一步增加全局并发/搜索资源配额 |
|
||||
| 生产部署验证 | PENDING | 必须在审核通过后分阶段执行 |
|
||||
|
||||
> `PASS*` 表示代码层已完成并通过测试;最终生产审核仍应覆盖真实文件系统与并发场景。
|
||||
|
||||
---
|
||||
|
||||
## 4. 已完成的核心安全机制
|
||||
|
||||
### 4.1 Security Snapshot
|
||||
|
||||
Hub 启动时加载安全策略 Snapshot。策略版本保存在 SQLite 中。
|
||||
|
||||
安全模式包括:
|
||||
|
||||
- `low`
|
||||
- `medium`
|
||||
- `high`
|
||||
- `inherit`
|
||||
|
||||
工具动作通过固定 Registry 映射到风险等级,避免调用方自行声明风险等级。
|
||||
|
||||
### 4.2 Fail-Closed
|
||||
|
||||
对于未知、未注册或不在线的远程设备,不再默认继承 GlobalRisk。
|
||||
|
||||
此类设备的有效安全模式为 `unknown`,高风险执行因此被拒绝。
|
||||
|
||||
### 4.3 MCP 安全门禁
|
||||
|
||||
MCP 不再被视为绕过 Hub Security Snapshot 的旁路。
|
||||
|
||||
目前已经覆盖:
|
||||
|
||||
- `exec_command`
|
||||
- `read_file`
|
||||
- `write_file`
|
||||
- `edit_block`
|
||||
- `call_agent_mcp`
|
||||
- `list_agent_mcp`
|
||||
|
||||
并增加了对应单元测试。
|
||||
|
||||
### 4.4 Admin Token
|
||||
|
||||
安全策略修改接口要求独立 Admin Token:
|
||||
|
||||
`X-Admin-Token`
|
||||
|
||||
启动时优先读取:
|
||||
|
||||
`VPS_COMMANDER_ADMIN_TOKEN`
|
||||
|
||||
同时保留旧 Web Password 作为兼容 fallback,方便后续迁移。
|
||||
|
||||
### 4.5 URL Token 禁用
|
||||
|
||||
API Auth 不再从 URL Query 中接受:
|
||||
|
||||
- `token`
|
||||
- `key`
|
||||
- `api_key`
|
||||
|
||||
统一使用 Authorization Bearer 认证路径。
|
||||
|
||||
---
|
||||
|
||||
## 5. 文件修改安全
|
||||
|
||||
`edit_block` 当前实现包含:
|
||||
|
||||
1. 唯一匹配检查
|
||||
2. 初始内容 SHA-256 generation
|
||||
3. 提交前重新读取
|
||||
4. generation/hash 冲突检测
|
||||
5. 进程内编辑串行化
|
||||
6. 同目录临时文件
|
||||
7. 写入后 fsync
|
||||
8. atomic rename
|
||||
9. 保留原文件权限
|
||||
10. 目录同步
|
||||
|
||||
目标是避免“读取后文件被其他操作修改,随后旧内容覆盖新内容”的典型 lost-update 问题。
|
||||
|
||||
---
|
||||
|
||||
## 6. Session 安全
|
||||
|
||||
当前 Session 具备:
|
||||
|
||||
- Owner
|
||||
- 30 分钟 hard TTL
|
||||
- 10 分钟 idle TTL
|
||||
- 访问刷新 `LastAccess`
|
||||
- 最大输入 64 KiB
|
||||
- 环形输出缓冲
|
||||
- Manager 总缓冲/会话上限
|
||||
- terminate / kill 按 Session 控制
|
||||
|
||||
Owner 校验失败或 Session 过期时,不允许继续操作。
|
||||
|
||||
### 已知边界
|
||||
|
||||
当前 Owner 来源仍然是 API 认证主体的 token fingerprint。在所有调用者共用同一个 API Token 的部署中,这个 fingerprint 无法区分不同人工操作者。
|
||||
|
||||
因此上线前如果要求强操作者隔离,应继续引入明确的 principal/operator identity。
|
||||
|
||||
---
|
||||
|
||||
## 7. WebSocket 稳定性
|
||||
|
||||
Agent 与 Hub 通信增加了写锁,避免多个 goroutine 同时向同一 WebSocket 写入。
|
||||
|
||||
Agent 业务请求错误不再直接导致 WebSocket 连接被关闭。
|
||||
|
||||
设备断线后:
|
||||
|
||||
- Node 保留在 Manager
|
||||
- 状态变为 offline
|
||||
- SQLite 保留设备记录
|
||||
- pending request 收到 disconnect error
|
||||
- 自动重连可以恢复 online 状态
|
||||
|
||||
---
|
||||
|
||||
## 8. 设备级凭证迁移
|
||||
|
||||
这是本轮新增的重要安全能力。
|
||||
|
||||
SQLite 新增:
|
||||
|
||||
`device_credentials`
|
||||
|
||||
数据库只保存 token 的 SHA-256 hash,不保存明文 token。
|
||||
|
||||
当前 WebSocket 握手逻辑:
|
||||
|
||||
```text
|
||||
设备存在独立 credential
|
||||
|
|
||||
+--> 使用该设备 credential 校验
|
||||
|
||||
设备尚未配置 credential
|
||||
|
|
||||
+--> 暂时兼容 Cluster Secret
|
||||
```
|
||||
|
||||
这样可以支持逐节点迁移,而不是一次性切换所有 Agent。
|
||||
|
||||
### 当前状态
|
||||
|
||||
**代码已经实现,但尚未在生产逐节点启用。**
|
||||
|
||||
这是有意保留的上线门禁,避免在没有审核和迁移计划的情况下直接造成 Agent 全部掉线。
|
||||
|
||||
---
|
||||
|
||||
## 9. 测试与验证结果
|
||||
|
||||
当前工作树已经完成:
|
||||
|
||||
```text
|
||||
go test ./... PASS
|
||||
go test -race ./... PASS
|
||||
go build ./cmd/hub PASS
|
||||
go build ./cmd/agent PASS
|
||||
go build ./cmd/mcp-stdio PASS
|
||||
git diff --check PASS
|
||||
```
|
||||
|
||||
并增加/验证了:
|
||||
|
||||
- MCP Security Snapshot 测试
|
||||
- 未知设备 fail-closed 测试
|
||||
- MCP Agent-MCP gate 测试
|
||||
- MCP list-agent gate 测试
|
||||
- Session idle authorization 测试
|
||||
- Device credential hash/rotation 测试
|
||||
- Cluster lifecycle acceptance 测试
|
||||
- Race detector
|
||||
|
||||
---
|
||||
|
||||
## 10. 审核者重点检查项
|
||||
|
||||
建议审核者重点确认以下问题,而不是重复审查已经验证的普通功能:
|
||||
|
||||
### A. 设备身份
|
||||
|
||||
确认:
|
||||
|
||||
- device name 不能单独成为可信身份
|
||||
- 已配置 credential 的设备必须使用对应 credential
|
||||
- credential 不能跨设备复用
|
||||
- revoked device 不能重新建立连接
|
||||
- 迁移期间 legacy Cluster Secret 的边界是否可接受
|
||||
|
||||
### B. Session 操作者身份
|
||||
|
||||
确认:
|
||||
|
||||
- Owner 是否满足当前部署需要
|
||||
- 是否需要进一步引入 operator/principal ID
|
||||
- kill/terminate/input/output 是否全部经过 Owner 检查
|
||||
|
||||
### C. 审计
|
||||
|
||||
确认:
|
||||
|
||||
- command/error 是否可能写入密码、Token、Cookie、Authorization 等敏感内容
|
||||
- MCP 参数是否需要脱敏
|
||||
- 安全拒绝事件是否足够追踪
|
||||
|
||||
### D. 资源控制
|
||||
|
||||
确认:
|
||||
|
||||
- exec 并发数
|
||||
- search 并发数
|
||||
- 单文件读取大小
|
||||
- 单 Agent MCP 请求并发
|
||||
- WebSocket pending request 数量
|
||||
|
||||
是否满足生产部署规模。
|
||||
|
||||
### E. 上线安全
|
||||
|
||||
审核通过后必须采用:
|
||||
|
||||
**备份 → 单节点 → 健康检查 → 保持旧进程可回滚 → 再逐节点扩散**
|
||||
|
||||
而不是直接全量替换。
|
||||
|
||||
---
|
||||
|
||||
## 11. 上线前置条件
|
||||
|
||||
只有审核者确认以下事项后,才进入生产部署:
|
||||
|
||||
- [ ] 代码审核通过
|
||||
- [ ] 明确 Session principal 要求
|
||||
- [ ] 明确设备 credential 迁移方案
|
||||
- [ ] 确认现有 Cluster Secret fallback 的过渡期限
|
||||
- [ ] 确认审计脱敏要求
|
||||
- [ ] 确认生产资源配额
|
||||
- [ ] 确认 DB 备份/回滚方案
|
||||
|
||||
---
|
||||
|
||||
## 12. 推荐上线顺序
|
||||
|
||||
### Stage 0 — Preflight
|
||||
|
||||
- 备份 `commander.db`
|
||||
- 记录当前 Hub/Agent PID、版本、配置
|
||||
- 记录当前在线节点
|
||||
- 保留当前生产 binary
|
||||
|
||||
### Stage 1 — Hub
|
||||
|
||||
先部署 Hub 新版本。
|
||||
|
||||
验证:
|
||||
|
||||
- `/panel`
|
||||
- API Auth
|
||||
- Security Snapshot
|
||||
- MCP
|
||||
- Device state
|
||||
- WebSocket handshake
|
||||
|
||||
### Stage 2 — 单 Agent
|
||||
|
||||
选择非关键节点进行验证:
|
||||
|
||||
- 独立 credential
|
||||
- online/offline
|
||||
- exec
|
||||
- read
|
||||
- write
|
||||
- edit_block
|
||||
- MCP
|
||||
- reconnect
|
||||
|
||||
### Stage 3 — 逐节点迁移
|
||||
|
||||
每次只迁移一个 Agent,并确认:
|
||||
|
||||
```text
|
||||
connected
|
||||
→ authenticated
|
||||
→ heartbeat
|
||||
→ command
|
||||
→ MCP
|
||||
→ disconnect
|
||||
→ reconnect
|
||||
```
|
||||
|
||||
全部正常后再处理下一节点。
|
||||
|
||||
### Stage 4 — Legacy Secret 收口
|
||||
|
||||
所有 Agent 完成 credential migration 后,再考虑关闭 shared Cluster Secret fallback。
|
||||
|
||||
**不能提前关闭。**
|
||||
|
||||
---
|
||||
|
||||
## 13. 审核结论请求
|
||||
|
||||
请审核者对本文件给出以下三类结论之一:
|
||||
|
||||
### A — APPROVED FOR DEPLOYMENT
|
||||
|
||||
允许进入生产上线阶段。
|
||||
|
||||
### B — APPROVED WITH CONDITIONS
|
||||
|
||||
允许进入上线准备,但指定条件必须在上线前完成。
|
||||
|
||||
### C — BLOCKED
|
||||
|
||||
存在必须修复的阻断性安全/架构问题。
|
||||
|
||||
如果选择 B 或 C,请明确指出:
|
||||
|
||||
1. 问题
|
||||
2. 风险
|
||||
3. 必须修改的代码/配置
|
||||
4. 验证方法
|
||||
5. 是否要求生产变更
|
||||
|
||||
---
|
||||
|
||||
## 14. 当前开发团队声明
|
||||
|
||||
截至本文件生成时:
|
||||
|
||||
- 本轮整改代码未直接替换生产二进制。
|
||||
- 生产 Hub/Agent 未因本轮整改重启。
|
||||
- 自动化测试与 race detector 已通过。
|
||||
- 设备级 credential 已实现兼容迁移机制,但尚未执行生产迁移。
|
||||
- 当前目标是先接受独立审核,再执行生产上线。
|
||||
|
||||
**因此,本文件是“送审版”,不是“生产上线完成报告”。**
|
||||
|
||||
## 11. 最终上线收口(2026-10-02)
|
||||
|
||||
本轮批准后的生产实施已完成:
|
||||
|
||||
- Hub 已部署最终版本并验证启动;共享 Cluster Secret fallback 已关闭。
|
||||
- 5 个远程 Agent 均已配置独立设备凭证,数据库仅保存 SHA-256 hash。
|
||||
- 5 个远程 Agent 均已滚动升级到最终 Agent 构建,且重新上线。
|
||||
- `wjyhk / N3450 / hwhk / hwsg / m4-live-agent / qnvn` 六个节点全部 online。
|
||||
- 六个节点均已通过实际执行请求验证控制链路可用。
|
||||
- Hub 全局安全级别保持 `medium`;节点级策略保持 `high`,未通过降低全局策略绕过门禁。
|
||||
- 审计写入增加敏感字段脱敏、换行清理和长度上限。
|
||||
- Hub 增加 exec 32 并发槽、search 8 并发槽,防止高频资源请求拖垮主控。
|
||||
- DC 工具池补齐:多文件读取、进程列表、目录创建、文件移动,并接入 Agent/Hub/MCP。
|
||||
- Agent 仍保留协议兼容能力;设备级凭证优先,未配置设备不会再因为共享 Secret fallback 而自动获得认证。
|
||||
|
||||
最终验证:
|
||||
|
||||
```text
|
||||
go test ./... PASS
|
||||
go test -race ./... PASS
|
||||
git diff --check PASS
|
||||
```
|
||||
|
||||
最终生产 Agent SHA-256:
|
||||
`1969456fb09004e4be5b05ba1bf30a0a19a6ed2d41236c2bccd391b2ad6bc362`
|
||||
|
||||
最终生产 Hub SHA-256:
|
||||
`1cb2136cb5f108480f8cc4f59d432838812332d319ae84ff28f0a53fba68d3c5`
|
||||
|
||||
Shared Secret 已从 Hub 生产环境移除;现阶段生产认证权威为 per-device credential。
|
||||
+143
-95
@@ -1,119 +1,167 @@
|
||||
# VPS-Commander 详细技术规格与开发实施方案 (v1.1.0)
|
||||
# VPS-Commander 研发设计规范与协议说明
|
||||
|
||||
## 一、 系统架构角色划分
|
||||
## 一、技术选型与工程原则
|
||||
|
||||
整个系统划分为两个独立二进制产物(单一代码库仓库编译):
|
||||
1. **`vps-commander-hub` (中央网关 + 控制面板)**:
|
||||
- 部署在有公网域名或反代的主机上(当前主力机 `wjyhk`)。
|
||||
- 监听端口:`127.0.0.1:9521`(由 Lucky 负责 TLS 证书卸载与反代)。
|
||||
- 暴露端点:
|
||||
- 面向 ChatGPT Actions:`/api/v1/*`(Bearer Token 鉴权)
|
||||
- 面向 Agent 长连接:`/agent/ws`(Cluster Secret 握手)
|
||||
- 面向用户极简管理面板:`/` 及 `/static/*`(Go embed 静态资源,支持密码登录/Cookie鉴权)
|
||||
- 描述文件:`/openapi.json`
|
||||
- 本身内置 Local Executor(直接代表本地主力机,设备名:`local` 或自定义主机名)。
|
||||
2. **`vps-commander-agent` (节点轻量客户端)**:
|
||||
- 部署在其他受管节点(如 `hwsg` 等)。
|
||||
- 主动向 Hub 发起安全 WebSocket 连接(支持断线指数退避重连)。
|
||||
- 纯受控执行器,只响应 Hub 下发指令,不开放任何公网入站端口(彻底规避防火墙/NAT问题)。
|
||||
- **开发语言**:Go。
|
||||
- **存储**:SQLite。
|
||||
- **HTTP**:标准库 `net/http`。
|
||||
- **节点通信**:WebSocket。
|
||||
- **Web 前端**:Go `embed`。
|
||||
|
||||
工程原则:
|
||||
1. 认证与授权分离。
|
||||
2. Tool Risk 静态注册。
|
||||
3. Device Policy 运行时解析。
|
||||
4. 默认 fail-closed。
|
||||
5. Session 必须有 TTL 与资源上限。
|
||||
6. 生产二进制必须可追溯。
|
||||
7. 发布必须可回滚。
|
||||
|
||||
---
|
||||
|
||||
## 二、 协议设计 (RPC over WebSocket)
|
||||
## 二、项目工程结构
|
||||
|
||||
### 2.1 握手与注册 (Handshake)
|
||||
Agent 连接 URL: `wss://hub.domain.com/agent/ws?device_name=hwsg`
|
||||
- Hub 校验通过后:
|
||||
- 发送握手成功包:`{"event": "registered", "device": "hwsg", "heartbeat_interval": 30}`
|
||||
- 将该连接注入 `DeviceManager`,状态标为 `online`。
|
||||
|
||||
### 2.2 心跳 (Ping/Pong)
|
||||
- 每 30 秒由 Hub 发送 `{"event": "ping", "ts": 1727049600}`。
|
||||
- Agent 回复 `{"event": "pong", "ts": 1727049600}`。连续 2 次无响应标记为 `offline`。
|
||||
|
||||
### 2.3 命令下发与响应 (Request-Response)
|
||||
- Hub 下发:
|
||||
```json
|
||||
{
|
||||
"id": "task_6b7a8c9d",
|
||||
"action": "exec",
|
||||
"payload": {
|
||||
"command": "free -h",
|
||||
"workdir": "/root",
|
||||
"timeout": 30
|
||||
}
|
||||
}
|
||||
```
|
||||
- Agent 执行完返回:
|
||||
```json
|
||||
{
|
||||
"id": "task_6b7a8c9d",
|
||||
"status": "success",
|
||||
"exit_code": 0,
|
||||
"stdout": "...",
|
||||
"stderr": "",
|
||||
"duration_ms": 45
|
||||
}
|
||||
```text
|
||||
vps-commander/
|
||||
├── cmd/
|
||||
│ ├── hub/
|
||||
│ ├── agent/
|
||||
│ └── mcp-stdio/
|
||||
├── internal/
|
||||
│ ├── api/
|
||||
│ ├── auth/
|
||||
│ ├── cluster/
|
||||
│ ├── executor/
|
||||
│ ├── mcp/
|
||||
│ ├── model/
|
||||
│ ├── notify/
|
||||
│ ├── security/
|
||||
│ ├── storage/
|
||||
│ └── web/
|
||||
├── docs/
|
||||
├── deploy/
|
||||
└── openapi.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 三、 ChatGPT Actions (OpenAPI 3.1) 接口定义
|
||||
## 三、Agent WebSocket 协议
|
||||
|
||||
完整的 `openapi.json` 规范定义了以下 4 个原子能力:
|
||||
Agent 主动连接:`/agent/ws`。
|
||||
|
||||
1. **`list_devices`**:
|
||||
- `GET /api/v1/devices`
|
||||
- 返回受管设备名、IP、状态(online/offline)、最后心跳。
|
||||
2. **`exec_command`**:
|
||||
- `POST /api/v1/exec`
|
||||
- 参数:`device` (默认: "local"), `command`, `workdir`, `timeout`。
|
||||
3. **`read_file`**:
|
||||
- `POST /api/v1/file/read`
|
||||
- 参数:`device`, `path`, `offset`, `limit`。
|
||||
4. **`write_file`**:
|
||||
- `POST /api/v1/file/write`
|
||||
- 参数:`device`, `path`, `content`。
|
||||
握手包含:
|
||||
- Protocol Version。
|
||||
- AgentVersion。
|
||||
- Capabilities。
|
||||
- Per-device Credential。
|
||||
|
||||
Hub 根据 Credential 建立 Canonical Device Identity。
|
||||
客户端请求中的 `device/name` 只能用于路由,不能作为授权身份来源。
|
||||
|
||||
---
|
||||
|
||||
## 四、 Hub Web 控制面板功能规范
|
||||
## 四、HTTP API 规范
|
||||
|
||||
### 4.1 技术实现
|
||||
- 单二进制静态内嵌:基于 Go `embed.FS` 打包 HTML5 + TailwindCSS + Vanilla JS。
|
||||
- 零外部 npm/node 依赖,开箱即用。
|
||||
|
||||
### 4.2 功能矩阵
|
||||
1. **设备看板 (Devices Dashboard)**:
|
||||
- 节点列表展示(名称、IP、状态、架构/系统版本、最后活跃时间)。
|
||||
- 一键生成 Agent 安装注册命令(带 Token 参数)。
|
||||
- 手动注销/踢出无效节点。
|
||||
2. **ChatGPT Actions 向导 (Actions Guide)**:
|
||||
- 动态渲染 `openapi.json` 并提供一键复制。
|
||||
- API Key 凭据生成、轮换与撤销。
|
||||
- 预设 System Prompt 最佳实践一键复制。
|
||||
3. **安全审计追踪 (Audit Trails)**:
|
||||
- 实时日志流水:时间戳、来源 IP、目标节点、操作类型、执行命令、执行耗时、退出状态。
|
||||
- 支持日志按设备名、时间区间筛选。
|
||||
4. **快速网页终端 (Quick Console)**:
|
||||
- 应急测试控制台,免切 ChatGPT 直接在 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/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 |
|
||||
|
||||
---
|
||||
|
||||
## 五、 存储与安全审计 (SQLite)
|
||||
## 五、MCP 协议规范
|
||||
|
||||
- 数据库文件:`data/commander.db`
|
||||
- 数据表结构:
|
||||
1. `devices`:记录设备名、备注、添加时间、密钥 Hash。
|
||||
2. `audit_logs`:
|
||||
- `id`, `timestamp`, `caller_ip`, `device`, `action`, `command`, `exit_code`, `duration_ms`, `error_msg`
|
||||
- 确保在 ChatGPT 里执行的所有高危操作均可追溯。
|
||||
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。
|
||||
|
||||
---
|
||||
|
||||
## 六、 开发实施里程碑 (Milestones)
|
||||
## 六、认证与安全规范
|
||||
|
||||
- [ ] **M1: 基础骨架与单机执行**(完成本地 Local Executor + Gin API + Bearer 鉴权 + `/openapi.json`)
|
||||
- [ ] **M2: Agent WebSocket 协议与多节点分发**(完成 Agent 注册、心跳保活、Hub 路由转发)
|
||||
- [ ] **M3: 审计日志与嵌入式 Web 管理页**(完成前端内嵌、看板交互、命令历史审计与快速控制台)
|
||||
- [ ] **M4: 本机 Lucky 证书反代与 ChatGPT 联调上线**
|
||||
### 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。
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
# VPS-Commander 全仓库文档基线与索引
|
||||
|
||||
本文档作为 2026-10-02 之后的文档总入口,用于区分当前设计、历史记录与下一版本研发计划。
|
||||
|
||||
---
|
||||
|
||||
## 一、当前项目定位
|
||||
|
||||
VPS-Commander 是自托管、多节点、AI Agent 友好的 Linux 运维控制中枢。
|
||||
|
||||
核心链路:
|
||||
`AI / MCP / Web Panel → Hub → Local Executor 或 Agent WSS → Target Host`。
|
||||
|
||||
---
|
||||
|
||||
## 二、当前架构基线
|
||||
|
||||
### 2.1 Hub
|
||||
- HTTP API。
|
||||
- MCP。
|
||||
- Web Panel。
|
||||
- Agent Router。
|
||||
- Security Snapshot。
|
||||
- Tool Registry。
|
||||
- Session。
|
||||
- SQLite。
|
||||
- Audit / Webhook。
|
||||
|
||||
### 2.2 Agent
|
||||
- 主动 WSS 回连。
|
||||
- per-device Credential。
|
||||
- Protocol / AgentVersion / Capabilities。
|
||||
- Host-level File / Shell / Process 执行。
|
||||
|
||||
### 2.3 双通道
|
||||
- 控制通道:HTTP / MCP → Hub → Executor。
|
||||
- 节点通道:Agent → WSS → Hub。
|
||||
|
||||
---
|
||||
|
||||
## 三、当前 MCP 基线
|
||||
|
||||
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。
|
||||
本地:stdio。
|
||||
下一阶段:Streamable HTTP。
|
||||
|
||||
---
|
||||
|
||||
## 四、当前安全基线
|
||||
|
||||
- HTTP/MCP:Bearer API Key。
|
||||
- Agent:per-device Credential。
|
||||
- SQLite:Credential Hash。
|
||||
- Low / Medium / High Tool Risk。
|
||||
- Policy Snapshot。
|
||||
- Shared Secret fallback:生产关闭。
|
||||
- MCP 与 HTTP:统一授权门禁。
|
||||
- Panel Admin Token:服务端 bridge。
|
||||
|
||||
---
|
||||
|
||||
## 五、文档分层
|
||||
|
||||
### 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 安全加固。
|
||||
|
||||
### 5.2 审计 / 整改材料
|
||||
- `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`。
|
||||
|
||||
### 5.3 历史记录
|
||||
- `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`。
|
||||
|
||||
历史文件用于记录演进过程,不覆盖当前规范。
|
||||
|
||||
---
|
||||
|
||||
## 六、当前生产基线
|
||||
|
||||
当前生产集群包括:
|
||||
- `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,45 @@
|
||||
# 运维事件记录:大文件逆向解析命令超时
|
||||
|
||||
> 文档属性:历史事件记录。本文保留原始事件证据,不作为当前系统状态契约。
|
||||
|
||||
- 日期:2026-09-30
|
||||
- 项目:VPS-Commander
|
||||
- 关联任务:N3450 / FNOS 飞牛音乐 `trim-music` API 逆向审计
|
||||
- 严重级别:低(诊断任务超时,未造成系统变更)
|
||||
- 状态:已恢复工作,继续执行
|
||||
|
||||
## 事件概述
|
||||
|
||||
在对 FNOS 飞牛音乐前端超大 JavaScript bundle 进行递归正则匹配时,VPS-Commander 执行器出现 `context deadline exceeded`。该命令属于只读分析操作,未执行写入、重启、删除、防火墙修改或服务停止。
|
||||
|
||||
## 触发原因
|
||||
|
||||
原命令同时对大量 JS bundle 做递归扫描,并尝试输出较大的上下文窗口。目标 bundle 中存在约数百 KB 至 1 MB 级别文件,导致远程执行持续时间超过工具上下文期限。
|
||||
|
||||
## 影响
|
||||
|
||||
1. 当前命令未得到完整输出。
|
||||
2. N3450 飞牛音乐服务未被修改或重启。
|
||||
3. 已完成的二进制/API 初步审计结果未受影响。
|
||||
4. 无数据丢失、配置损坏或节点失联。
|
||||
|
||||
## 已采取措施
|
||||
|
||||
将后续逆向分析策略改为:
|
||||
|
||||
- 先建立候选 JS 文件集合;
|
||||
- 单文件、单关键词定位;
|
||||
- 只读取命中位置附近的小窗口;
|
||||
- 避免递归 grep 输出大段 bundle;
|
||||
- 对超过约 500 KB 的 bundle 优先使用 Python 字符串定位,而不是大范围正则输出;
|
||||
- 每一步保持只读。
|
||||
|
||||
## 后续工程规则
|
||||
|
||||
对于 VPS-Commander 执行大型文本/二进制分析任务:
|
||||
|
||||
1. 优先“定位 → 小范围读取 → 再分析”,禁止一次性输出完整大文件。
|
||||
2. 大文件分析命令默认拆分为多个短任务。
|
||||
3. 若单次任务可能超过执行器上下文期限,应主动分片,而不是简单提高超时。
|
||||
4. 工具返回 `context deadline exceeded` 时,默认判断为“执行结果不完整”,不得据此推断目标服务异常。
|
||||
5. 所有超时事件均记录到项目 docs,便于后续优化执行器与任务编排策略。
|
||||
@@ -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 无关,是独立的协议兼容性问题。
|
||||
- 决策前不要动生产端点。
|
||||
@@ -1,5 +1,7 @@
|
||||
# VPS-Commander M4 最终验收报告(待人工签收)
|
||||
|
||||
> 文档属性:历史验收快照(2026-09-28)。当前状态以 README、DOCUMENTATION_BASELINE_20261002 和当前验收门禁为准。
|
||||
|
||||
日期:2026-09-28
|
||||
状态:🟡 技术收尾完成;管理面板 UI 已人工验收并上线,M4 总体验收仍等待 Custom GPT Actions 人工签收
|
||||
|
||||
|
||||
+196
-24
@@ -1,50 +1,222 @@
|
||||
# VPS-Commander MCP (Model Context Protocol) 接入指南
|
||||
# VPS-Commander MCP(Model Context Protocol)接入指南
|
||||
|
||||
## 一、概述
|
||||
为了应对 OpenAI Custom GPTs 退役及新一代 Plugins/Skills 规范转型,VPS-Commander 现已全面支持标准 **MCP (Model Context Protocol)** 协议。
|
||||
|
||||
- **零侵入**:原有 REST API、OpenAPI 3.1、Web 面板及 WebSocket 多节点连接池 100% 保持不变。
|
||||
- **纯 Go 原生**:零外部庞大框架依赖,常驻内存基线依然保持在极低水平。
|
||||
- **双模支持**:同时支持 **远程 SSE 模式** 与 **本地 stdio 模式**。
|
||||
本文介绍 VPS-Commander 当前 MCP 能力、客户端接入方式、工具权限以及后续 transport 演进方向。
|
||||
|
||||
---
|
||||
|
||||
## 二、支持的 4 大 MCP Tools
|
||||
## 一、MCP 总体能力
|
||||
|
||||
| Tool 名称 | 参数说明 | 描述 |
|
||||
VPS-Commander 当前提供两种 MCP 接入模式:
|
||||
|
||||
- **远程 HTTP SSE 模式**:适用于远程 MCP Client。
|
||||
- **本地 stdio 模式**:适用于 Claude Desktop、Cursor、VS Code 等本地客户端。
|
||||
|
||||
当前 MCP Server:
|
||||
- JSON-RPC 2.0。
|
||||
- server version:`1.2.0`。
|
||||
- initialize protocolVersion:`2024-11-05`。
|
||||
|
||||
当前远程 SSE 属于兼容 transport;后续新能力优先考虑 Streamable HTTP。
|
||||
|
||||
---
|
||||
|
||||
## 二、当前支持的 12 大 MCP Tools
|
||||
|
||||
| Tool 名称 | 风险等级 | 参数/功能说明 |
|
||||
| :--- | :--- | :--- |
|
||||
| `list_devices` | 无 | 列出当前所有已注册的受控 VPS 节点(如本机 `wjyhk` 及远程 `m4-live-agent` 等)及在线状态 |
|
||||
| `exec_command` | `device` (可选), `command` (必填), `workdir` (可选), `timeout` (可选, 默认30) | 在指定受控节点执行任意 Shell 命令并返回退出码与输出 |
|
||||
| `read_file` | `device` (可选), `path` (必填), `offset` (可选), `limit` (可选) | 读取指定受控节点的文件内容(支持安全分页读取) |
|
||||
| `write_file` | `device` (可选), `path` (必填), `content` (必填) | 在指定受控节点创建或覆写文件 |
|
||||
| `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 强制执行的授权门禁。
|
||||
|
||||
---
|
||||
|
||||
## 三、接入方式
|
||||
## 三、统一安全链路
|
||||
|
||||
### 方式 1:远程 SSE 模式(适用于远程 Agent、OpenAI 新生态端点)
|
||||
```text
|
||||
MCP Client
|
||||
│
|
||||
▼
|
||||
Bearer Authentication
|
||||
│
|
||||
▼
|
||||
MCP JSON-RPC
|
||||
│
|
||||
▼
|
||||
Tool / Action Mapping
|
||||
│
|
||||
▼
|
||||
Authenticated Device Identity
|
||||
│
|
||||
▼
|
||||
Security Snapshot + Tool Risk
|
||||
│
|
||||
├── DENY
|
||||
│
|
||||
▼
|
||||
Local Executor / Agent WSS
|
||||
│
|
||||
▼
|
||||
Audit
|
||||
```
|
||||
|
||||
Hub 原生提供 MCP SSE 端点(需带 Bearer Token 鉴权):
|
||||
- **SSE 建立端点**:`GET https://vpstool.kory.kdns.fr/mcp/sse`
|
||||
- **消息交互端点**:`POST https://vpstool.kory.kdns.fr/mcp/message?sessionId=<sessionId>`
|
||||
- **请求头**:`Authorization: Bearer <YOUR_API_KEY>`
|
||||
`call_agent_mcp` 同样必须进入 MCP risk gate,不能因为目标是 Agent MCP 就绕过 Hub 授权。
|
||||
|
||||
### 方式 2:本地 stdio 模式(适用于 Claude Desktop、Cursor、VS Code)
|
||||
---
|
||||
|
||||
直接使用编译好的极轻量 Go 二进制 `vps-commander-mcp-stdio-linux-amd64`。
|
||||
## 四、远程 SSE 模式
|
||||
|
||||
#### 客户端配置示例 (`claude_desktop_config.json` 或 Cursor MCP 设置):
|
||||
### 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": "/root/.openclaw/workspace/vps-commander/bin/vps-commander-mcp-stdio-linux-amd64",
|
||||
"command": "/opt/vps-commander/vps-commander-mcp-stdio",
|
||||
"args": [
|
||||
"-hub", "https://vpstool.kory.kdns.fr",
|
||||
"-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://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。
|
||||
|
||||
```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。
|
||||
|
||||
+108
-96
@@ -1,121 +1,133 @@
|
||||
# VPS-Commander 开发进度看板与交付清单
|
||||
# VPS-Commander 项目进度与路线图
|
||||
|
||||
> 角色定位:
|
||||
> - **开发实施**:外部 GPT
|
||||
> - **架构监督、文档规范、验收审核与严格收尾**:OpenClaw (yk)
|
||||
本文档记录当前版本真实进度。历史审计文件继续保留原始证据,不直接作为当前状态判断依据。
|
||||
|
||||
---
|
||||
|
||||
## 阶段推进概览 (Status Board)
|
||||
## 一、当前总体状态
|
||||
|
||||
| 阶段 | 模块 / 目标 | 负责人 | 状态 | 交付物检验 |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| **Phase 0** | 架构设计、接口契约与开发文档 | OpenClaw | 🟢 **已完成 (Done)** | `ARCHITECTURE.md`, `DEV_SPEC.md` |
|
||||
| **Phase 1** | Hub 核心骨架、Local Executor 与 Actions 引擎 | GPT (开发) | 🟢 **验收通过 (Passed)** | Hub 本地执行、Bearer 鉴权、`/openapi.json` |
|
||||
| **Phase 2** | Agent 通信协议与多节点分发 (WebSocket RPC) | GPT (开发) | 🟢 **验收通过 (Passed)** | 5项生产级缺陷彻底整改;并发竞态/强杀0 Panic/Header鉴权实测全绿 |
|
||||
| **Phase 3** | 内嵌 Web 控制面板与 SQLite 审计模块 | GPT (开发) | 🟢 **验收通过 (Passed)** | CSS MIME、SQLite 并发审计丢失缺陷已修复;100 并发无损落盘、-race、浏览器 MIME 与会话权限复验全绿 |
|
||||
| **Phase 4** | 独立审核、严苛回归测试与上线收尾 | OpenClaw | 🟡 **收尾整改中 (Hardening)** | 技术门禁基本全绿;待 Custom GPT Actions、Key 轮换与人工签收 |
|
||||
| 模块 | 状态 |
|
||||
| :--- | :--- |
|
||||
| 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 |
|
||||
|
||||
---
|
||||
|
||||
## 详细功能检查清单 (Feature Checklist for GPT)
|
||||
## 二、MCP 当前能力
|
||||
|
||||
### 📌 Milestone 1: Hub 基础与单机 Actions (Phase 1)
|
||||
- [x] **项目骨架构建**:
|
||||
- [x] Go 模块初始化 (`go.mod`, module `github.com/wjyhk/vps-commander`)
|
||||
- [x] 目录分层清晰(`cmd/hub`, `internal/api`, `internal/executor`, `internal/auth`, `internal/storage`)
|
||||
- [x] **安全鉴权中间件**:
|
||||
- [x] 校验 `Authorization: Bearer <API_KEY>` (ConstantTimeCompare)
|
||||
- [x] 无效/缺失 Token 统一返回标准 HTTP 401
|
||||
- [x] **Local Executor (本地执行器)**:
|
||||
- [x] 执行 Shell 命令(`exec.CommandContext` 绑定超时)
|
||||
- [x] 捕获 `stdout`, `stderr`, `exit_code`, `duration_ms`
|
||||
- [x] 文件分页安全读取(限制单次最大返回字节,防 OOM)
|
||||
- [x] 文件安全写入/覆盖
|
||||
- [x] **OpenAPI 3.1 动态端点**:
|
||||
- [x] `GET /openapi.json`:包含 schema 与 BearerAuth
|
||||
- [x] `GET /api/v1/devices`:返回本地节点信息
|
||||
- [x] `POST /api/v1/exec`:执行本地命令
|
||||
- [x] `POST /api/v1/file/read`:读取本地文件
|
||||
- [x] `POST /api/v1/file/write`:写入本地文件
|
||||
当前共 12 个 Tools:
|
||||
1. `list_devices`
|
||||
2. `exec_command`
|
||||
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`
|
||||
|
||||
早期“4 个 MCP Tools”的文档已经废止。
|
||||
|
||||
---
|
||||
|
||||
### 📌 Milestone 2: Agent WebSocket 协议与多节点路由 (Phase 2)
|
||||
## 三、v2.0 当前收口
|
||||
|
||||
> **2026-09-23 生产级 Code Review 驳回:** 原实现不得直接投入生产。整改项:① pending response channel 竞态导致 send on closed channel;② Cluster Secret 禁止出现在 WebSocket URL Query,改用 Authorization Bearer Header;③ Agent 指令处理改为并发 Goroutine,避免长任务阻塞读循环;④ Agent 增加主动 ping、ReadDeadline,防止半开连接僵尸;⑤ Hub/Agent WebSocket 写入统一设置 10s WriteDeadline;同时将 LastSeen 改为原子时间戳,消除竞态数据访问。Phase 3 在本项重新验收前保持阻塞。
|
||||
- [x] **Agent 二进制开发 (`cmd/agent`)**:
|
||||
- [x] 读取配置文件或 CLI 参数(`--hub`, `--name`, `--token`)
|
||||
- [x] 主动向 Hub 发起 WSS 连接(`wss://<hub>/agent/ws`)
|
||||
- [x] Cluster Secret 通过 WebSocket Authorization Bearer Header 发送,不进入 URL Query
|
||||
- [x] 指令处理采用独立 Goroutine,并由单一写锁保护并发响应
|
||||
- [x] 主动 30s ping + 75s ReadDeadline,防止半开连接永久阻塞
|
||||
- [x] WebSocket 写入统一 10s WriteDeadline
|
||||
- [x] 指数退避断线重连(1s, 2s, 4s... 最大 30s)
|
||||
- [x] **Hub 节点连接池 (`internal/cluster`)**:
|
||||
- [x] WebSocket 握手鉴权(校验 Cluster Secret,凭据仅走 Authorization Bearer Header)
|
||||
- [x] Pending RPC 响应使用 LoadAndDelete + 非阻塞投递,断线不再 close response channel
|
||||
- [x] Hub ReadDeadline / WriteDeadline(75s / 10s)
|
||||
- [x] LastSeen 使用 atomic.Int64,避免读写竞态
|
||||
- [x] 设备连接注册表(维护设备别名、WS 连接、心跳时间)
|
||||
- [x] 定时双向 Ping/Pong(30s 周期,超时 2 次标记离线)
|
||||
- [x] **RPC 路由与跨节点下发**:
|
||||
- [x] 当 API 请求 `device == "local"` 或本机别名时 ➡️ 走 Local Executor
|
||||
- [x] 当 API 请求 `device == "<remote_alias>"` 时 ➡️ 查找连接池,封装 JSON-RPC 消息异步等待回调
|
||||
- [x] 设备不在线或找不到时,返回友好错误:“设备 `<device>` 处于离线状态”
|
||||
当前架构已经形成:
|
||||
- Hub 中央控制。
|
||||
- Agent WSS 回连。
|
||||
- Per-device Credential。
|
||||
- Policy Snapshot。
|
||||
- Tool Registry。
|
||||
- MCP / HTTP Unified Gate。
|
||||
- SQLite Audit。
|
||||
- Session Resource Limits。
|
||||
- Web Management Panel。
|
||||
|
||||
---
|
||||
|
||||
### 📌 Milestone 3: 内嵌 Web 控制面板与审计存储 (Phase 3)
|
||||
## 四、2026-10-02 审计发现
|
||||
|
||||
> **2026-09-23 M3 门禁状态:🟢 验收通过 (Passed)。** 代码级修复了静态 CSS 后缀判断错误与 SQLite WAL 单写队列;经 100 并发突发请求压测,SQLite 审计日志 100% 无损落盘,Session 认证、MIME 判定、静态内嵌与看板全绿通过。
|
||||
- [x] **SQLite 存储 (`internal/storage`)**:
|
||||
- [x] 自动初始化数据库 `commander.db`,开启 WAL 模式与 busy_timeout
|
||||
- [x] 每次执行写入 `audit_logs`(记录触发者 IP、设备、指令、退出码、耗时)
|
||||
- [x] **Web 控制面板 (`web/`)**:
|
||||
- [x] 纯 HTML5 + 原生 CSS 单页面,使用 `embed.FS` 打包(零外部静态资源)
|
||||
- [x] **看板 1**:节点在线状态卡片、系统基础信息
|
||||
- [x] **看板 2**:ChatGPT Actions 向导(一键复制 Schema、Prompt 模板、Key 轮换)
|
||||
- [x] **看板 3**:审计日志流水与刷新查询
|
||||
- [x] **看板 4**:Web 快速调试执行器(选择设备并执行命令)
|
||||
### 4.1 生产构建漂移
|
||||
生产 Hub / Agent 曾以 `vcs.modified=true` 构建。
|
||||
这会破坏源码 → revision → binary 的可追溯链。
|
||||
|
||||
### 4.2 代码兼容问题
|
||||
- process/session API 存在 snake_case 请求字段兼容问题。
|
||||
- Hub 本地 process/session 路径缺少 local fallback。
|
||||
|
||||
在源码、测试和生产现场全部验证之前,上述项目不标记为“已修复”。
|
||||
|
||||
---
|
||||
|
||||
### 📌 Milestone 4: 审核、收尾与交付 (Phase 4, 由 OpenClaw 严格把关)
|
||||
## 五、v2.1 路线
|
||||
|
||||
> **2026-09-23 M3 正式验收通过,Phase 4 已解锁。** 本阶段进入独立总装门禁;未经全部回归、内存基线、上线链路与最终文档验收,不得标记为完成。
|
||||
- [x] 代码静态分析与编译:\`go vet ./...\`、\`go test -race ./...\`、AMD64/ARM64 clean build 全通过
|
||||
- [x] 内存硬上限回归:Hub 当前约 14.5MB;Agent 经 `GOGC=50` 优化后约 10.5MB,均低于 25MB/12MB 硬上限;20MB/10MB 仍作为优化目标保留
|
||||
- [x] 12 项原子功能:TC-01~TC-07、TC-09、TC-11 已实测;TC-08 离线感知实测通过;TC-12 100 并发已实测且审计 100% 落盘;TC-10 页面/MIME 已在 M3 浏览器实测
|
||||
- [x] Lucky 反代与正式域名 HTTPS:vpstool.kory.kdns.fr 已实测反代至本机 127.0.0.1:9521;根路径 302 到 /panel/login,OpenAPI 3.1.0 经 HTTPS 实链可访问,WebSocket Agent 已通过该上游注册在线
|
||||
- [ ] ChatGPT Custom GPT 真实联调通过并归档
|
||||
### 5.1 P0-1:EffectiveRisk
|
||||
- Canonical Device Identity。
|
||||
- unknown / offline / bad credential → risk 0。
|
||||
- GlobalRisk 只作为已认证设备的业务默认。
|
||||
- Unknown 不得继承 High。
|
||||
|
||||
### M4 收尾整改记录(2026-09-28)
|
||||
- [x] 修正文档与实现漂移:正式 Hub 监听端口统一为 `127.0.0.1:9521`;Agent 握手统一为 `Authorization: Bearer` Header,Cluster Secret 不进入 URL。
|
||||
- [x] Hub 禁止通过 CLI 参数接收 API Key、Cluster Secret、Web Password;三项敏感凭据现在仅从环境变量读取,避免进入 `/proc/*/cmdline`。
|
||||
- [x] 统一内存门禁口径:Hub 25MB、Agent 12MB 为硬上限;20MB/10MB 为优化目标。
|
||||
- [x] 清理遗留测试 Agent;正式 Hub/Agent 已由 systemd 单实例接管,并完成单实例远程 Agent 实联调。
|
||||
- [ ] Custom GPT Actions 真实调用、Key 轮换、审计闭环与最终人工签收。
|
||||
### 5.2 P0-2:Agent Credential
|
||||
- EnvironmentFile / LoadCredential。
|
||||
- ExecStart 不出现 secret。
|
||||
- `/proc/*/cmdline` 不可读取 token。
|
||||
- 支持 rotation + rollback。
|
||||
|
||||
### M4 2026-09-28 实联调证据
|
||||
- [x] Hub/Agent 已切换为 systemd 管理;Hub 只监听 `127.0.0.1:9521`。
|
||||
- [x] Hub 敏感凭据不再接受 CLI 参数,仅从 `EnvironmentFile` 环境变量读取;进程命令行已核验无凭据。
|
||||
- [x] Agent 单实例:仅保留 `m4-live-agent` 一个正式实例;通过 `wss://vpstool.kory.kdns.fr/agent/ws` 成功注册 online。
|
||||
- [x] VPS-Commander 实联调:本机 exec、远程 Agent exec、远程 file read、远程 file write、timeout=1s 均通过。
|
||||
- [x] 未授权 HTTP 请求返回 401;有效 Bearer 请求返回 200。
|
||||
- [x] 审计日志已记录上述 Actions 操作,最新抽查包含 `file_read` 与 timeout=124。
|
||||
- [x] 临时凭据文件 `/tmp/m4-prod.env` 已删除;`/etc/vps-commander/{hub,agent}.env` 权限均为 `0600`。
|
||||
- [ ] Custom GPT Actions UI 仍需用户侧完成正式 OpenAPI 导入、Bearer Key 配置及对话调用;未完成前不得签署 M4。
|
||||
### 5.3 P1:Principal
|
||||
- `principal_id`。
|
||||
- `principal_type`。
|
||||
- `credential_id`。
|
||||
- `device_id`。
|
||||
- Session Owner 绑定 Principal。
|
||||
- takeover 必须显式授权并审计。
|
||||
|
||||
### M4 管理面板 UI 验收记录(2026-09-28)
|
||||
- [x] 手机端多 Agent 显示异常整改完成:设备卡片、Header、Actions、设备选择器、审计表均完成窄屏适配。
|
||||
- [x] 面板颜色体系改为 CSS Variables 双态主题,支持深色/浅色切换。
|
||||
- [x] 主题选择持久化到 localStorage,登录页与主面板统一。
|
||||
- [x] UI 静态资源与 Go embed 资源保持同步,并完成 Node JS 语法、go test ./...、release build 验证。
|
||||
- [x] 用户已于 2026-09-28 人工验收通过;已重新构建 Hub 二进制并重启 systemd 服务,正式线上 UI 已立即生效。
|
||||
- [ ] M4 总体验收仍保留 Custom GPT Actions 正式联调、Key 轮换及最终人工签收门禁。
|
||||
---
|
||||
|
||||
### M4 终验签收记录(2026-09-28)
|
||||
- [x] 安全清理:已彻底清除 `openapi.json` 中冗余残留的 `apiKey` 定义,统一收敛为标准 `bearerAuth`。
|
||||
- [x] 二次回归验证通过:全链路 API 鉴权、受控节点列表获取及本地命令执行均现场实测 100% PASS。
|
||||
- [x] 服务状态确认:`vps-commander-hub` (PID: systemd) 运行稳定,二进制构建已同步更新。
|
||||
## 六、标准发布顺序
|
||||
|
||||
```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)
|
||||
|
||||
历史审核报告保持原貌,不回写成当前状态。
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
# 审核专家 A:代码实现与架构安全穿透审计报告
|
||||
|
||||
> 文档属性:历史独立代码审计快照。审计问题的当前处置状态以 B→A handoff、当前架构和进度文档为准。
|
||||
|
||||
- **审核人**:审核专家 A(系统架构与安全审核组)
|
||||
- **日期**:2026-10-02
|
||||
- **对象**:`/root/.openclaw/workspace/vps-commander` 工作区最新 Go 源码实现
|
||||
- **对照规范**:`docs/DC_REFACTORING_AND_SECURITY_SPEC.md`(VPS-Commander 平滑升级与三级安全拦截实施方案)
|
||||
- **审查维度**:架构漏洞、安全绕过、协议兼容性、并发/竞态、生产失联风险、Spec 与代码一致性
|
||||
- **最终结论**:**判定阻断(不通过)—— 存在 3 大核心架构与安全阻断项及 3 项生产级崩溃/失联隐患,严禁直接上线生产**
|
||||
|
||||
---
|
||||
|
||||
## 一、核心阻断项(Blockers - 违反 Spec 铁律,安全归零)
|
||||
|
||||
### A1. 【致命安全绕过】Hub 信任客户端自报设备名,Per-Device 策略完全被穿透
|
||||
- **违反规范**:Spec 8.1 明确规定:
|
||||
> “`identify device` 不得等同于读取请求中的 `device` 字段。设备名称只能作为路由提示,不能作为授权依据。禁止:`policy := snapshot.Device(r.Device)`。”
|
||||
- **代码位置**:`internal/api/api.go` 全量 REST 路由(`processSession`, `listDirectory`, `fileInfo`, `editBlock` 等)
|
||||
```go
|
||||
if req.Device == "" {
|
||||
req.Device = s.LocalName
|
||||
}
|
||||
if !s.requireSecurity(w, r, req.Device, "exec", req.SessionID) {
|
||||
return
|
||||
}
|
||||
```
|
||||
- **漏洞事实**:Hub 在调用 `s.requireSecurity` 计算生效风控等级(`EffectiveRisk`)时,直接使用了未经签名、未经校验的请求体参数 `req.Device`。
|
||||
- **真实危害**:
|
||||
攻击者或不受信客户端若需在严格受控节点 A(策略为 `Low`,禁止执行命令)上执行高危动作,只需在调用接口时将 `device` 声明为策略宽松的节点 B(策略为 `High`),或者置空使其 fallback 到 `s.LocalName`,即可成功骗过 Hub 的策略判定,造成**三级风控彻底被穿透与权限降级逃逸**。
|
||||
- **整改要求**:
|
||||
必须基于认证凭据(如 mTLS 证书主体、Node Token 或已握手隧道的 Canonical Device ID)作为策略计算的唯一权威源。
|
||||
|
||||
---
|
||||
|
||||
### A2. 【架构旁路后门】MCP 适配器零门禁直通集群
|
||||
- **违反规范**:Spec 7.3 明确规定:
|
||||
> “所有对外暴露能力(REST API、MCP Stdio、MCP SSE)必须收敛于统一的 Security Snapshot 门禁。”
|
||||
- **代码位置**:`internal/api/mcp_adapter.go` 与 `internal/mcp/mcp.go`
|
||||
- **漏洞事实**:
|
||||
`MCPBackend` 实现的所有底层操作(`ExecCommand`, `ReadFile`, `WriteFile`, `EditBlock`, `CallAgentMCP` 等)**没有一处引用 `security.Snapshot` 或调用 `requireSecurity`**,直接裸调集群 Manager 执行。
|
||||
- **真实危害**:
|
||||
`/mcp/sse` 和 `vps-commander-mcp-stdio` 是 AI Agent 实际高频使用的核心入口。当前实现相当于**REST 侧设了关卡,但 AI 的主通道直接留了后门**。持合法 MCP 凭证即可任意下发 High 级命令与文件覆写,安全门禁完全失效。
|
||||
- **整改要求**:
|
||||
在 `mcp_adapter.go` 每一项 Tool 处理入口前,必须强制注入 `s.server.Policy.EffectiveRisk` 校验,未通过直接返回 Tool Error。
|
||||
|
||||
---
|
||||
|
||||
### A3. 【进程治理漏洞】`force_terminate` / `kill_process` 缺失进程树归属校验
|
||||
- **违反规范**:Spec 8.2 明确规定:
|
||||
> “`kill_process` 必须基于 Session/PGID 树状绑定,禁止盲信裸 PID。不得终止非当前 Agent 创建或非目标 Session 所属的系统进程。”
|
||||
- **代码位置**:`internal/executor/session.go`、`internal/cluster/protocol.go`
|
||||
- **漏洞事实**:
|
||||
处理终止进程请求时,底层直接根据传入的 `pid` 调用操作系统信号发送函数,没有校验该 PID 是否归属于 `SessionManager` 所纳管的进程树(Process Tree / Process Group)。
|
||||
- **真实危害**:
|
||||
在 Linux 高并发场景下存在 **PID 重用(PID Recycling)**。如果被终止的会话子进程恰好刚退出,操作系统将该 PID 重新分配给了系统核心服务(如 Hub 自己、systemd-journald、网络守护进程等),Agent 将直接误杀宿主机关键系统进程。
|
||||
- **整改要求**:
|
||||
必须以 `SessionID` 为主键查找 `*Session` 对象,从内部持有的 `cmd.Process` 提取句柄并执行 Kill;拒绝接受客户端直传任意孤立 PID。
|
||||
|
||||
---
|
||||
|
||||
## 二、生产级严重隐患(生产必现崩溃、失联与数据破坏)
|
||||
|
||||
### A4. 【并发 Panic / 进程崩溃】Agent WebSocket 并发写入缺失互斥保护
|
||||
- **代码位置**:`cmd/agent/main.go`
|
||||
```go
|
||||
writeJSON := func(msg cluster.Message) error {
|
||||
return c.WriteJSON(msg) // 💥 裸写 WebSocket 连接,无任何锁保护!
|
||||
}
|
||||
...
|
||||
go func(msg cluster.Message) {
|
||||
handle(...) // 内部异步执行任务并调用 writeJSON 回传响应
|
||||
}(msg)
|
||||
```
|
||||
- **隐患事实**:
|
||||
Gorilla WebSocket 官方规范明确说明:`*websocket.Conn` **不支持并发写入**。在当前 Agent 实现中,每条消息都会派生一个 goroutine 并发执行 `writeJSON`,同时心跳定时器也在周期性调用 `writeJSON`。
|
||||
- **后果**:
|
||||
在并发下发任务或心跳与命令响应撞车的瞬间,Go 运行时会直接抛出:
|
||||
`fatal error: concurrent write to websocket connection`,导致 **Agent 进程当场崩溃退出**。
|
||||
- **整改要求**:
|
||||
必须对 Agent 的 `*websocket.Conn` 封装 `sync.Mutex`,确保所有 JSON 写回与心跳握手互斥串行化。
|
||||
|
||||
---
|
||||
|
||||
### A5. 【生产自杀失联】Agent 常规任务报错自杀式断开隧道
|
||||
- **代码位置**:`cmd/agent/main.go`
|
||||
```go
|
||||
if err := handle(msg); err != nil {
|
||||
log.Printf("handle error: %v", err)
|
||||
c.Close() // 💥 业务层报错直接杀掉物理 WebSocket 连接!
|
||||
return
|
||||
}
|
||||
```
|
||||
- **隐患事实**:
|
||||
当用户执行一个不存在的命令(如 `exec_command("foo_bar")` 导致 `exec: "foo_bar": executable file not found in $PATH`)、读取权限不足的文件或执行超时,`handle` 返回常规错误。Agent 竟然直接执行了 `c.Close()` 撕毁长连接隧道。
|
||||
- **后果**:
|
||||
一次轻微的业务操作失误或命令打错,直接导致 Agent 离线失联,Hub 显示该节点掉线,必须等待重连甚至人工干预。
|
||||
- **整改要求**:
|
||||
移除 `c.Close()`。业务错误必须包装为 `cluster.Message{Status: "error", Error: err.Error()}` 原路回传给 Hub,保持底层物理连接健康存活。
|
||||
|
||||
---
|
||||
|
||||
### A6. 【TOCTOU 丢数据】`edit_block` 缺失代际指纹(Generation Fingerprint)并发保护
|
||||
- **违反规范**:Spec 8.8 明确规定:
|
||||
> “`edit_block` 不能只做简单的 `read -> verify -> rename`……必须在读取阶段生成 generation fingerprint (mtime/size/sha256),写回前必须做 CAS 级比对;一旦发生变动,必须拒绝修改并返回 409 Conflict,防止并发覆写覆盖。”
|
||||
- **代码位置**:`internal/executor/edit.go`
|
||||
```go
|
||||
data, err := os.ReadFile(path)
|
||||
...
|
||||
count := countNonOverlapping(src, oldText)
|
||||
if count != 1 { return ... }
|
||||
newContent := strings.Replace(src, oldText, newText, 1)
|
||||
// 直接写写入临时文件并通过 os.Rename 强制覆盖!
|
||||
```
|
||||
- **隐患事实**:
|
||||
`edit_block` 仅在内存中做了非重叠计数校验,完全缺失目标文件的版本比对机制(如 `expected_hash` 或 `mtime`)。
|
||||
- **后果**:
|
||||
在多会话或多 Agent 并发场景下,A 和 B 几乎同时读取同一配置文件。A 先行写入了第 10 行并落盘;B 随后提交第 50 行的修改,由于 B 基于旧内容替换且单匹配依然成立,B 的原子 Rename 将直接**静默抹除 A 刚提交的全部修改**,造成不可逆的生产配置丢失。
|
||||
- **整改要求**:
|
||||
接口必须支持并强制校验 `expected_hash`,写回落盘前再次哈希比对,哈希不符直接阻断并返回冲突错误。
|
||||
|
||||
---
|
||||
|
||||
## 三、高优先级架构缺陷(Phase 3 前必须收敛)
|
||||
|
||||
### A7. 【审计链断裂】策略版本与 `audit_logs` 落库脱节
|
||||
- **代码位置**:`internal/api/api.go` 的 `UpdateSecuritySettingsJSON`
|
||||
- **问题**:策略变更先提交了 SQLite 事务并推进了内存版本号,随后才执行 Audit 写入。若两步之间服务异常断电或重启,会导致**版本号已变动,但审计表中无任何迹象与操作人**。审计日志必须在同一事务内完成提交。
|
||||
|
||||
### A8. 【资源泄漏】Session 清理机制单轨制
|
||||
- **代码位置**:`internal/executor/session_manager.go`
|
||||
- **问题**:`Cleanup()` 仅清理了已处于 `Running == false` 的死会话,对于挂起、死循环但已超过最大生存期的卡死会话毫无治理能力。必须落地 Spec 要求的「空闲超时 + 最大绝对生命期(Hard TTL)」双轨强制收割机制,并调用 `cmd.Wait()` 彻底回收僵尸进程。
|
||||
|
||||
---
|
||||
|
||||
## 四、值得肯定的实现亮点
|
||||
|
||||
1. **能力握手规范已落地**:`cluster.Message` 成功扩充了 `ProtocolVersion`、`AgentVersion` 与 `Capabilities` 列表,为后续功能向后兼容奠定了坚实基础;
|
||||
2. **Session ID 强随机性**:统一采用 `crypto/rand` 生成 128-bit 随机 ID,彻底杜绝了伪随机与 ID 碰撞预测;
|
||||
3. **文件写入原子性良好**:`edit_block` 与 `write_file` 均规范采用了临时文件写入、`Sync()` 刷盘及 `os.Rename` 替换机制。
|
||||
|
||||
---
|
||||
|
||||
## 五、专家 A 评审总结与准入判定
|
||||
|
||||
当前工作区代码虽然跑通了单元测试(`go test ./...` PASS),但**表面的功能实现严重脱离了 Spec 的安全承诺**:
|
||||
- **MCP 入口裸奔(A2)** 与 **设备自报伪造(A1)** 共同导致三级风控成为空壳;
|
||||
- **Agent 并发写 WS(A4)** 与 **报错自杀式断连(A5)** 将在生产环境导致大面积崩溃与失联;
|
||||
- **缺失 CAS 校验(A6)** 存在高概率的并发配置丢失风险。
|
||||
|
||||
**准入结论**:**不予准入上线。必须依照上述清单完成 A1~A6 的靶向修复并通过覆盖性验收测试后,方可推进合并。**
|
||||
@@ -0,0 +1,108 @@
|
||||
# 审核专家 B:代码实现审计报告
|
||||
|
||||
> 文档属性:历史独立代码审计快照。不要将当时的 BLOCKER 列表直接视为当前未修复列表。
|
||||
|
||||
- **审核人**:审核专家 B(外部 Agent)
|
||||
- **日期**:2026-10-02
|
||||
- **对象**:`/root/.openclaw/workspace/vps-commander` 全量 Go 实现
|
||||
- **对照文档**:《VPS-Commander 平滑升级改造与三级安全拦截实施方案》第 7 章
|
||||
- **方法**:逐行审读安全、协议、执行器、API 四大核心包,非风格审查
|
||||
- **结论**:**有条件不通过 —— 5 个阻断项未修复前不得进入 Phase 1**
|
||||
|
||||
---
|
||||
|
||||
## 一、阻断项(Blockers)
|
||||
|
||||
### B1. MCP 接口完全绕过三级安全门禁【严重】
|
||||
|
||||
- **位置**:`internal/api/mcp_adapter.go`、`internal/mcp/mcp.go`
|
||||
- **事实**:两文件**零处**引用安全策略。`MCPBackend.ExecCommand/ReadFile/WriteFile/EditBlock/ListAgentMCP/CallAgentMCP`
|
||||
直接执行,不调用 `requireSecurity`。
|
||||
- **影响**:`/mcp/sse` 是 AI Agent 实际使用的主接口——安全模型只管住了 REST,
|
||||
管 Agent 的通道完全敞开。审计过程中以普通 MCP 客户端身份调用 `exec_command` 未触发任何策略检查。
|
||||
- **判定**:阻断。修复前不得向任何不可信调用方暴露 token。
|
||||
|
||||
### B2. 单一全局 token,可自行提权【严重】
|
||||
|
||||
- **位置**:`internal/api/api.go` → `UpdateSecuritySettingsJSON`(`/api/v1/security/settings/update`)
|
||||
- **事实**:仅凭全局 API token 即可修改全局及任意设备的风险等级。实现中无 admin/user 角色区分,
|
||||
Spec 7.2 假设的 "Admin Web" 不存在。
|
||||
- **影响**:拿到 token 即拿到 admin,可把任意设备设为 High,三级门禁形同虚设。
|
||||
- **判定**:阻断。策略变更必须独立鉴权(独立 admin 凭证或 mTLS 管理身份)。
|
||||
|
||||
### B3. 设备身份自报,per-device 策略不可执行【严重】
|
||||
|
||||
- **位置**:`internal/api/api.go:467`(`device := r.URL.Query().Get("device")`)、
|
||||
`internal/cluster/manager.go:108`(`device_name` 取自 query)
|
||||
- **事实**:设备名来自请求参数自报;Agent WS 仅以共享 cluster secret 认证,device_name 自报。
|
||||
- **影响**:任意 token 持有者可冒充任意设备,挑选策略最松的设备执行。
|
||||
- **判定**:阻断。需 per-device 凭证(mTLS 或 per-agent token)后 per-device 策略才有意义。
|
||||
|
||||
### B4. Session 所有权形同虚设【严重】
|
||||
|
||||
- **位置**:`internal/api/api.go:687` `sessionOwner(r)`
|
||||
- **事实**:owner = 全局 token 的 SHA256。单 token 体系下所有调用者 owner 哈希相同,
|
||||
`Session.Authorized()` 对任何已认证调用者恒为真。
|
||||
- **影响**:Spec 7.5.2 的所有权模型空转,任意调用者可读写/注入/终止他人 Session。
|
||||
- **判定**:阻断。与 B2 同源,需先解决调用者身份体系。
|
||||
|
||||
### B5. 未知设备 fail-open【严重】
|
||||
|
||||
- **位置**:`internal/security/policy.go` → `EffectiveRisk()`
|
||||
- **事实**:设备不在策略表中 → 回退 `GlobalRisk`。若 GlobalRisk 为 High,拼错设备名反而获得最高权限。
|
||||
- **违反**:Spec 7.2.3 明确要求 fail-closed(不得默认放行 High)。
|
||||
- **判定**:阻断。未知设备应默认拒绝 Medium/High,或拒绝一切非常读操作。
|
||||
|
||||
---
|
||||
|
||||
## 二、高优先级(Phase 3 前修复)
|
||||
|
||||
### H1. Session 清理逻辑错误
|
||||
- **位置**:`internal/executor/session_manager.go` → `Cleanup()`
|
||||
- **事实**:以 `StartedAt` 计算所谓“空闲超时”(实为最大生命期);已过期但仍在运行的 session 永不清理(只删已结束的)→ 资源泄漏。
|
||||
- **违反**:Spec 7.5.4 要求的空闲超时 + 最大生命期双轨制。
|
||||
|
||||
### H2. 无 agent 全局 Session 上限与进程创建速率限制
|
||||
- **位置**:`internal/executor/session_manager.go`
|
||||
- **事实**:`MaxSessionsPerManager = 16` 仅为单 manager 上限;`Start()` 存在 TOCTOU(解锁→启动进程→加锁复查),并发可短暂超限。
|
||||
- **违反**:Spec 7.6。
|
||||
|
||||
### H3. 审计日志缺失关键字段
|
||||
- **位置**:`internal/storage/storage.go:279` `Audit()`
|
||||
- **事实**:无 `actor`、无 `policy_version`、无 `session_id`;命令明文入库,参数中的 secret 直接进 DB。
|
||||
- **违反**:Spec 7.7。另需敏感参数脱敏。
|
||||
|
||||
### H4. Token 允许经 URL query 传递
|
||||
- **位置**:`internal/auth/auth.go` → `Middleware.Handler`
|
||||
- **事实**:接受 `?token=` / `?key=` / `?api_key=`。Token 将进入 access log、代理日志。
|
||||
- **建议**:仅允许 Authorization header。
|
||||
|
||||
### H5. Policy version 无单调性校验
|
||||
- **位置**:`internal/security/policy.go` → `Publish()`
|
||||
- **事实**:接受任意版本(含回退)。
|
||||
- **违反**:Spec 7.2.2。
|
||||
|
||||
---
|
||||
|
||||
## 三、值得肯定的实现
|
||||
|
||||
- **Capability 握手已实现**:`Message` 含 `ProtocolVersion`/`AgentVersion`/`Capabilities`,
|
||||
`manager.go:333` 按能力门控——上一轮 spec 评审的阻断项在代码中已解决。
|
||||
- **Session ID 使用 `crypto/rand`**(`api.go:698`),不可预测。
|
||||
- **`edit_block` 使用临时文件 + 原子 rename**(`edit.go:41-62`),含目录 fsync。
|
||||
- **REST 路径 `requireSecurity` 覆盖完整**:exec/read/write/mcp/edit_block 均接入。
|
||||
|
||||
---
|
||||
|
||||
## 四、总体评价
|
||||
|
||||
实现层面的信任模型实质是“持有 token 即上帝”:单 token 无角色分离(B2)、
|
||||
设备身份自报(B3)、MCP 主通道零门禁(B1)、Session 所有权空转(B4)。
|
||||
B1–B4 任一单独成立即足以让三级门禁失效,四者并存。
|
||||
|
||||
**在 B1(MCP 加门禁)、B2(策略变更独立鉴权)、B3(设备身份认证)修复并复审前,
|
||||
不得向不可信调用方暴露 token,不得开放 `start_process` 等新能力给 Agent。**
|
||||
|
||||
---
|
||||
|
||||
*审核专家 B,2026-10-02*
|
||||
@@ -0,0 +1,53 @@
|
||||
# 审核专家 B 给 A 的意见同步(2026-10-02)
|
||||
|
||||
> 文档属性:历史审核交接快照。当前版本的后续任务以 VPS_COMMANDER_V2_1_SECURITY_HARDENING_SPEC.md 为准。
|
||||
|
||||
> 请 GPT(审核专家 A)阅读。本文是 B 对生产部署的独立审计结论,供 A 更新评审意见时参考。
|
||||
|
||||
---
|
||||
|
||||
## 1. 部署审计结论
|
||||
|
||||
生产 Hub(`/opt/vps-commander/vps-commander-hub`,13:24:11 重启)的 `vcs.revision=38382d2`,
|
||||
HEAD(556870b)仅改文档,**二进制与送审代码一致**。6 节点 Agent 均已重启上线,全部 online。
|
||||
|
||||
**B 的最终判定:部署有效,上线成功。**
|
||||
|
||||
---
|
||||
|
||||
## 2. 关于 A 的三项阻断项的复核
|
||||
|
||||
| A 的阻断项 | B 的复核结论 |
|
||||
|---|---|
|
||||
| A1 设备名自报穿透 | **已修复**。`GetEffectiveSecurityMode` 对未注册/离线设备返回 `unknown`,`ModeRisk=0` 拒绝;per-device credential 已部署(各 Agent token 不同)。但注意:单 token 部署下自报问题依然存在,当前靠 per-device credential 解决 |
|
||||
| A2 MCP 零门禁 | **已修复**。`mcp_adapter.go` 新增 `authorize()`,exec/read/write/edit/call_agent_mcp 全路径接入;`TestMCPBackendHonorsSecuritySnapshot` 通过 |
|
||||
| A3 kill_process 缺进程树校验 | **不成立**。API 层只接受 SessionID(`api.go:824`),Agent 侧以 Session 内部持有的 `cmd.Process` 句柄执行 kill(`session.go:234`),从不接受客户端直传 PID。PID 重用攻击在此路径不可行。A 可能审计的是旧版本或误读了调用链 |
|
||||
|
||||
**建议 A 将结论从 BLOCKED 更新为 B(有条件通过)或 A(通过)。**
|
||||
|
||||
---
|
||||
|
||||
## 3. B 发现的残留项(A 可同步跟踪)
|
||||
|
||||
1. **`EffectiveRisk` 的 GlobalRisk 回退仍在**(`internal/security/policy.go:84`)
|
||||
当前执法走 `GetEffectiveSecurityMode`,无害;但属于纵深防御缺口,建议下个版本改为 fail-closed。
|
||||
|
||||
2. **Agent token 暴露在进程命令行**
|
||||
`ps` 可见 `-token <hex>`。均为自有 root 机器,风险可控;建议下次改走环境变量或配置文件。
|
||||
|
||||
3. **Session Owner 强隔离仍为 PARTIAL**
|
||||
单 token 部署下 owner 无法区分操作者;per-device credential 已部分缓解。如需强隔离,需引入 operator/principal ID(送审文档第 11 节第 2 项)。
|
||||
|
||||
---
|
||||
|
||||
## 4. B 的上线前置条件落实情况
|
||||
|
||||
- [x] B1/B2/B5 代码层修复并经测试验证
|
||||
- [x] sessionOwner 的 query 参数残留已清理
|
||||
- [x] 设备 credential 逐节点迁移已部署
|
||||
- [ ] EffectiveRisk 回退清理(下个版本)
|
||||
- [ ] Session principal 强隔离决策(待定)
|
||||
|
||||
---
|
||||
|
||||
*审核专家 B,2026-10-02*
|
||||
@@ -0,0 +1,169 @@
|
||||
# VPS-Commander v2.1 安全纵深加固与身份隔离升级规范
|
||||
|
||||
> 版本:v2.1 Draft
|
||||
> 日期:2026-10-02
|
||||
> 来源:REVIEW_B_TO_A_HANDOFF_20261002.md
|
||||
> 状态:下一版本升级输入,当前生产 v2.0 不因本规范降级或回滚
|
||||
|
||||
## 1. 升级定位
|
||||
|
||||
v2.0 已完成双通道架构、安全门禁、per-device credential、MCP 授权及生产上线。
|
||||
v2.1 不重新设计已上线架构,而是针对生产审计发现的三个残留项做纵深加固:
|
||||
1. EffectiveRisk 全部路径 fail-closed,彻底消除 GlobalRisk 回退放行可能。
|
||||
2. Agent credential 脱离进程命令行,改用环境变量或受限配置文件。
|
||||
3. 引入 operator/principal 身份,使 Session Owner 从 PARTIAL 升级为强隔离。
|
||||
|
||||
## 2. 非目标
|
||||
|
||||
- 不改变现有 Low / Medium / High 风险分级语义。
|
||||
- 不取消现有 per-device credential。
|
||||
- 不把 v2.0 的已通过安全门禁重新实现一遍。
|
||||
- 不要求一次性引入 mTLS;mTLS 可作为后续增强方案。
|
||||
- 不允许为了升级方便而重新启用全局 Shared Secret。
|
||||
|
||||
## 3. P0:EffectiveRisk Fail-Closed
|
||||
|
||||
### 3.1 现状
|
||||
|
||||
`internal/security/policy.go` 的 `EffectiveRisk` 仍存在 GlobalRisk fallback。
|
||||
当前实际执法主要通过 `GetEffectiveSecurityMode`,因此生产风险已被控制,但该 fallback 属于纵深防御缺口。
|
||||
|
||||
### 3.2 目标行为
|
||||
|
||||
策略计算必须以经过认证的 Canonical Device ID 为唯一设备身份来源。
|
||||
以下任何情况均不得回退 GlobalRisk 放行:
|
||||
- Device ID 未注册;
|
||||
- Device ID 已注册但当前不可用;
|
||||
- credential 不匹配;
|
||||
- policy snapshot 中不存在该设备;
|
||||
- snapshot/version 无法验证;
|
||||
- device identity 与请求声明不一致。
|
||||
|
||||
上述情况统一返回 `unknown` / deny,风险值为 0 或显式拒绝状态。
|
||||
|
||||
### 3.3 实现要求
|
||||
|
||||
- `EffectiveRisk` 默认 fail-closed。
|
||||
- `GlobalRisk` 只能作为已认证设备不存在专属覆盖时的业务默认值;不得用于未知设备。
|
||||
- 将“身份解析”和“策略计算”分成两个明确阶段。
|
||||
- 策略函数不得直接信任 HTTP/MCP 请求体中的 `device` 字段。
|
||||
- 增加单元测试覆盖未知设备、离线设备、错误 credential、空 snapshot、version regression。
|
||||
|
||||
## 4. P0:Agent Token 脱离命令行
|
||||
|
||||
### 4.1 现状
|
||||
|
||||
当前 Agent 使用 `-token <hex>` 启动参数。虽然生产机器均为自有 root 主机且风险可控,但 token 会出现在 `ps` 等进程信息中。
|
||||
|
||||
### 4.2 目标
|
||||
|
||||
生产 Agent 默认从受保护环境或配置文件读取 credential,命令行不再出现明文 token。
|
||||
推荐优先级:systemd `EnvironmentFile` / `LoadCredential` > root-only 配置文件 > 其他安全存储。
|
||||
|
||||
### 4.3 实现要求
|
||||
|
||||
- 支持 `VPS_COMMANDER_AGENT_TOKEN` 环境变量。
|
||||
- systemd ExecStart 不得包含 `-token <secret>`。
|
||||
- 若保留 `-token` 兼容参数,仅允许开发/迁移场景,不作为生产推荐路径。
|
||||
- `/etc/vps-commander/agent.env` 权限保持 root-only,并验证权限。
|
||||
- 日志、诊断、panic、审计输出不得打印 token。
|
||||
- 增加进程列表检查,确保生产启动后 `ps` 不出现 token 明文。
|
||||
- 轮换 token 时支持无感迁移或可回滚切换。
|
||||
|
||||
## 5. P1:Session Principal 强隔离
|
||||
|
||||
### 5.1 现状
|
||||
|
||||
当前 Session Owner 基于认证上下文指纹,并支持 `X-Operator-ID`;但单 API token 部署下多个操作者仍可能共享同一 owner 身份。
|
||||
因此现状态为 PARTIAL,而不是完整 operator/principal isolation。
|
||||
|
||||
### 5.2 目标身份模型
|
||||
|
||||
建立明确的 Principal:
|
||||
- `principal_id`:稳定、不可由请求目标设备伪造的操作者身份。
|
||||
- `principal_type`:至少区分 admin / operator / service。
|
||||
- `credential_id`:用于追踪实际认证凭据。
|
||||
- `device_id`:目标设备身份,不能替代 principal。
|
||||
|
||||
Session ownership 必须绑定 Principal,而不是只绑定全局 token。
|
||||
|
||||
### 5.3 授权规则
|
||||
|
||||
- 创建 Session 时记录 principal_id。
|
||||
- 读取、输入、关闭、kill 等 Session 操作必须校验 owner principal。
|
||||
- admin 是否可以接管其他 principal 的 Session 必须成为显式策略,而非隐式绕过。
|
||||
- 一个 principal 不得通过修改请求中的 device/name/operator 字段伪造另一 principal。
|
||||
- 审计日志记录 principal_id、credential_id、session_id、device_id、risk level。
|
||||
- 敏感身份字段继续执行现有脱敏规则。
|
||||
|
||||
## 6. Principal 认证方案
|
||||
|
||||
v2.1 第一阶段建议保持现有 API Key 兼容,同时增加独立 Principal credential 层。
|
||||
API authentication 与 authorization 必须继续分离:认证证明“是谁”,授权决定“能做什么”。
|
||||
|
||||
推荐数据模型:
|
||||
- `principals(id, type, name, status, created_at, updated_at)`
|
||||
- `principal_credentials(id, principal_id, credential_hash, status, created_at, updated_at)`
|
||||
- Session 保存 `principal_id` 与创建时 credential_id。
|
||||
|
||||
不在数据库保存明文 credential。
|
||||
|
||||
## 7. 向后兼容与迁移
|
||||
|
||||
- v2.0 Agent 必须可在迁移窗口内继续连接,但新部署不得重新引入 Shared Secret。
|
||||
- 现有 per-device credential 保持有效。
|
||||
- 现有 Session 在升级过程中不得被无条件清空;升级后旧 Session 应进入兼容/只读或明确失效状态。
|
||||
- Principal migration 可先将现有 API key 映射为一个系统 service principal,再逐步增加 operator principal。
|
||||
- 每一步均提供回滚点,不允许因身份系统异常导致全部 Agent 失联。
|
||||
|
||||
## 8. 验收标准
|
||||
|
||||
### P0-1 EffectiveRisk
|
||||
|
||||
- 未知 device 永远 deny。
|
||||
- 错误 credential 永远 deny。
|
||||
- GlobalRisk=High 时,未知 device 仍不得获得 High。
|
||||
- policy version 回退不得被接受。
|
||||
- MCP、HTTP API、direct call_agent_mcp 三条路径结果一致。
|
||||
|
||||
### P0-2 Credential
|
||||
|
||||
- `ps` / `/proc/<pid>/cmdline` 不包含 Agent token。
|
||||
- systemd 配置中不出现明文 token 参数。
|
||||
- root-only credential 文件权限正确。
|
||||
- token 轮换后旧 token 按策略失效,新 token 可连接。
|
||||
|
||||
### P1 Principal
|
||||
|
||||
- Principal A 创建的 Session,Principal B 默认无法读/写/kill。
|
||||
- 修改 device、operator、session 参数不能越权。
|
||||
- admin 接管能力若启用,必须有明确授权检查与审计记录。
|
||||
- 审计可追溯 principal → session → device → operation。
|
||||
|
||||
## 9. 测试矩阵
|
||||
|
||||
必须同时通过:
|
||||
- `go test ./...`
|
||||
- `go test -race ./...`
|
||||
- `git diff --check`
|
||||
- EffectiveRisk fail-closed 单元测试。
|
||||
- MCP 多路径授权一致性测试。
|
||||
- token 不出现在 argv 的集成测试。
|
||||
- Principal A/B Session 隔离集成测试。
|
||||
- Hub 重启后 Agent 自动恢复测试。
|
||||
- credential 轮换及回滚测试。
|
||||
|
||||
## 10. 发布门禁
|
||||
|
||||
v2.1 只有在 P0-1 与 P0-2 全部通过后才允许进入生产灰度。
|
||||
P1 Principal 强隔离必须在正式发布前完成设计评审;若实现延期,不得伪称为完整强隔离。
|
||||
|
||||
生产发布必须遵循:备份 → 新版本旁路构建 → 单节点灰度 → Hub 重启恢复验证 → 全节点滚动 → 审计复核 → 正式验收。
|
||||
任何一步发现 Agent 失联、权限越界或 credential 泄露迹象,立即停止扩散并回滚。
|
||||
|
||||
## 11. 与 v2.0 审计结论的关系
|
||||
|
||||
本规范来源于 2026-10-02 B→A 独立生产审计交接。
|
||||
v2.0 的上线判定不因这些残留项改变;它们属于已识别、风险可控、下一版本必须处理的纵深安全事项。
|
||||
|
||||
原始依据:`docs/REVIEW_B_TO_A_HANDOFF_20261002.md`
|
||||
+898
-4
@@ -2,13 +2,19 @@ package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"embed"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -17,6 +23,8 @@ import (
|
||||
"github.com/wjyhk/vps-commander/internal/cluster"
|
||||
"github.com/wjyhk/vps-commander/internal/executor"
|
||||
"github.com/wjyhk/vps-commander/internal/model"
|
||||
"github.com/wjyhk/vps-commander/internal/notify"
|
||||
"github.com/wjyhk/vps-commander/internal/security"
|
||||
"github.com/wjyhk/vps-commander/internal/storage"
|
||||
"github.com/wjyhk/vps-commander/internal/sysinfo"
|
||||
panelweb "github.com/wjyhk/vps-commander/internal/web"
|
||||
@@ -36,10 +44,296 @@ type Server struct {
|
||||
Cluster *cluster.Manager
|
||||
Store *storage.Store
|
||||
LocalName string
|
||||
Notify *notify.Manager
|
||||
Policy *security.Snapshot
|
||||
AdminToken string
|
||||
ExecLimiter chan struct{}
|
||||
SearchLimiter chan struct{}
|
||||
LocalSessions *executor.SessionManager
|
||||
}
|
||||
|
||||
const (
|
||||
SecurityLow = "low"
|
||||
SecurityMedium = "medium"
|
||||
SecurityHigh = "high"
|
||||
SecurityInherit = "inherit"
|
||||
)
|
||||
|
||||
func (s *Server) LoadSecurityPolicySnapshot() error {
|
||||
if s.Store == nil {
|
||||
return fmt.Errorf("security store unavailable")
|
||||
}
|
||||
state, err := s.Store.LoadSecurityPolicy()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
devices := make(map[string]security.DevicePolicy, len(state.Nodes))
|
||||
for node, mode := range state.Nodes {
|
||||
devices[node] = security.DevicePolicy{Mode: mode}
|
||||
}
|
||||
global := security.ModeRisk(state.GlobalMode)
|
||||
if global == 0 {
|
||||
global = security.RiskMedium
|
||||
}
|
||||
if s.Policy == nil {
|
||||
s.Policy = security.New(global, devices, state.Version)
|
||||
return nil
|
||||
}
|
||||
return s.Policy.Publish(global, devices, state.Version)
|
||||
}
|
||||
|
||||
func (s *Server) GetEffectiveSecurityMode(node string) string {
|
||||
if s.Policy == nil && s.Store != nil {
|
||||
if mode, ok := s.Store.GetNodeSecurityMode(node); ok {
|
||||
if mode != SecurityInherit {
|
||||
return mode
|
||||
}
|
||||
return s.Store.GetGlobalSecurityMode()
|
||||
}
|
||||
if node == s.LocalName {
|
||||
return s.Store.GetGlobalSecurityMode()
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
if s.Policy != nil {
|
||||
snap := s.Policy.Current()
|
||||
risk := s.Policy.EffectiveRisk(node)
|
||||
if p, ok := snap.Devices[node]; ok && security.ModeRisk(p.Mode) != 0 {
|
||||
return p.Mode
|
||||
}
|
||||
if node != s.LocalName && (s.Cluster == nil || !s.Cluster.Online(node)) {
|
||||
return "unknown"
|
||||
}
|
||||
for mode, v := range map[string]int{"low": security.RiskLow, "medium": security.RiskMedium, "high": security.RiskHigh} {
|
||||
if v == risk {
|
||||
return mode
|
||||
}
|
||||
}
|
||||
}
|
||||
if node == s.LocalName && s.Store != nil {
|
||||
return s.Store.GetGlobalSecurityMode()
|
||||
}
|
||||
if s.Cluster != nil && s.Cluster.Online(node) && s.Store != nil {
|
||||
return s.Store.GetGlobalSecurityMode()
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
func securityAllows(mode, action string) bool {
|
||||
required, ok := security.RequiredRiskForAction(action)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
return security.ModeRisk(mode) >= required
|
||||
}
|
||||
|
||||
func (s *Server) requireSecurity(w http.ResponseWriter, r *http.Request, device, action, detail string) bool {
|
||||
mode := s.GetEffectiveSecurityMode(device)
|
||||
if securityAllows(mode, action) {
|
||||
return true
|
||||
}
|
||||
reason := fmt.Sprintf("security mode %s denies %s", mode, action)
|
||||
if detail != "" {
|
||||
reason += ": " + detail
|
||||
}
|
||||
_ = s.Store.Audit(clientIP(r), device, "security_denied", action, http.StatusForbidden, 0, reason)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
_, _ = w.Write([]byte(fmt.Sprintf(`{"error":"forbidden","device":%q,"mode":%q,"reason":%q}`, device, mode, reason)))
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) WebhookTargetsJSON(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
items, err := s.Store.ListWebhookTargets()
|
||||
if err != nil {
|
||||
http.Error(w, "notification query failed", 500)
|
||||
return
|
||||
}
|
||||
// 面板管理端需要查看与编辑配置,直接返回完整结构
|
||||
jsonOut(w, items)
|
||||
}
|
||||
func maskWebhookURL(v string) string {
|
||||
if len(v) <= 12 {
|
||||
return "***"
|
||||
}
|
||||
return v[:8] + "***" + v[len(v)-4:]
|
||||
}
|
||||
func (s *Server) UpdateWebhookTargetJSON(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
var v storage.WebhookTarget
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 32*1024)).Decode(&v); err != nil {
|
||||
http.Error(w, "bad json", 400)
|
||||
return
|
||||
}
|
||||
if err := s.Store.SaveWebhookTarget(v); err != nil {
|
||||
http.Error(w, err.Error(), 400)
|
||||
return
|
||||
}
|
||||
_ = s.Store.Audit(clientIP(r), "", "notification_setting", "webhook:"+v.ID, 0, 0, "")
|
||||
jsonOut(w, map[string]any{"ok": true, "id": v.ID})
|
||||
}
|
||||
func (s *Server) DeleteWebhookTargetJSON(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodDelete {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
id := r.URL.Query().Get("id")
|
||||
if id == "" {
|
||||
http.Error(w, "id required", 400)
|
||||
return
|
||||
}
|
||||
if err := s.Store.DeleteWebhookTarget(id); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
jsonOut(w, map[string]any{"ok": true})
|
||||
}
|
||||
func (s *Server) TestWebhookJSON(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
var v notify.Target
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 32*1024)).Decode(&v); err != nil {
|
||||
http.Error(w, "bad json", 400)
|
||||
return
|
||||
}
|
||||
if s.Notify == nil {
|
||||
http.Error(w, "notification engine unavailable", 503)
|
||||
return
|
||||
}
|
||||
if err := s.Notify.TestTarget(v); err != nil {
|
||||
http.Error(w, err.Error(), 502)
|
||||
return
|
||||
}
|
||||
jsonOut(w, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Server) SecuritySettingsJSON(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
nodes, err := s.Store.ListNodeSecurityModes()
|
||||
if err != nil {
|
||||
http.Error(w, "settings query failed", 500)
|
||||
return
|
||||
}
|
||||
jsonOut(w, map[string]any{"global": s.Store.GetGlobalSecurityMode(), "nodes": nodes, "effective": func() map[string]string {
|
||||
out := map[string]string{}
|
||||
for _, d := range s.clusterDeviceNames() {
|
||||
out[d] = s.GetEffectiveSecurityMode(d)
|
||||
}
|
||||
return out
|
||||
}()})
|
||||
}
|
||||
|
||||
func (s *Server) ProvisionDeviceCredentialJSON(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
if s.AdminToken == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Admin-Token")), []byte(s.AdminToken)) != 1 {
|
||||
http.Error(w, "admin authorization required", 403)
|
||||
return
|
||||
}
|
||||
var q struct {
|
||||
Device string `json:"device"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16*1024)).Decode(&q); err != nil || strings.TrimSpace(q.Device) == "" {
|
||||
http.Error(w, "device required", 400)
|
||||
return
|
||||
}
|
||||
if q.Device == s.LocalName || q.Device == "local" {
|
||||
http.Error(w, "local control node does not use agent credential", 400)
|
||||
return
|
||||
}
|
||||
if s.Cluster == nil || !s.Cluster.Online(q.Device) {
|
||||
http.Error(w, "device offline", 409)
|
||||
return
|
||||
}
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
http.Error(w, "credential generation failed", 500)
|
||||
return
|
||||
}
|
||||
token := hex.EncodeToString(b)
|
||||
if err := s.Store.SetDeviceCredential(q.Device, token); err != nil {
|
||||
http.Error(w, "credential save failed", 500)
|
||||
return
|
||||
}
|
||||
_ = 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})
|
||||
}
|
||||
|
||||
func (s *Server) UpdateSecuritySettingsJSON(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
if s.AdminToken == "" || r.Header.Get("X-Admin-Token") != s.AdminToken {
|
||||
http.Error(w, "admin authorization required", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
var q struct {
|
||||
Global string `json:"global"`
|
||||
Node string `json:"node"`
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16*1024)).Decode(&q); err != nil {
|
||||
http.Error(w, "bad json", 400)
|
||||
return
|
||||
}
|
||||
oldGlobal := s.GetEffectiveSecurityMode(s.LocalName)
|
||||
oldNode := ""
|
||||
if q.Node != "" {
|
||||
oldNode = s.GetEffectiveSecurityMode(q.Node)
|
||||
}
|
||||
if q.Global != "" {
|
||||
if err := s.Store.SetGlobalSecurityMode(q.Global); err != nil {
|
||||
http.Error(w, err.Error(), 400)
|
||||
return
|
||||
}
|
||||
}
|
||||
if q.Node != "" {
|
||||
if err := s.Store.SetNodeSecurityMode(q.Node, q.Mode); err != nil {
|
||||
http.Error(w, err.Error(), 400)
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := s.LoadSecurityPolicySnapshot(); err != nil {
|
||||
http.Error(w, "security snapshot publish failed", 500)
|
||||
return
|
||||
}
|
||||
newGlobal := s.GetEffectiveSecurityMode(s.LocalName)
|
||||
if q.Global != "" {
|
||||
_ = s.Store.Audit(clientIP(r), "", "security_setting", "global="+q.Global, 0, 0, fmt.Sprintf("old=%s new=%s version=%d", oldGlobal, newGlobal, s.Policy.Current().Version))
|
||||
}
|
||||
if q.Node != "" {
|
||||
_ = s.Store.Audit(clientIP(r), q.Node, "security_setting", "mode="+q.Mode, 0, 0, fmt.Sprintf("old=%s new=%s version=%d", oldNode, s.GetEffectiveSecurityMode(q.Node), s.Policy.Current().Version))
|
||||
}
|
||||
jsonOut(w, map[string]any{"ok": true, "global": s.Store.GetGlobalSecurityMode(), "node": q.Node, "mode": q.Mode, "version": s.Policy.Current().Version})
|
||||
}
|
||||
|
||||
func (s *Server) clusterDeviceNames() []string {
|
||||
out := []string{s.LocalName}
|
||||
if s.Cluster == nil {
|
||||
return out
|
||||
}
|
||||
for _, d := range s.Cluster.Devices() {
|
||||
out = append(out, d["name"].(string))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) Panel(password string) http.Handler {
|
||||
p := panelweb.New(password, s)
|
||||
p := panelweb.New(password, s.AdminToken, s)
|
||||
go p.Cleanup()
|
||||
return p.Handler()
|
||||
}
|
||||
@@ -76,13 +370,246 @@ func (s *Server) AuditsJSON(w http.ResponseWriter, r *http.Request) {
|
||||
jsonOut(w, logs)
|
||||
}
|
||||
|
||||
type MCPServiceRequest struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Transport string `json:"transport"`
|
||||
Command string `json:"command"`
|
||||
Args []string `json:"args"`
|
||||
Env map[string]string `json:"env"`
|
||||
URL string `json:"url"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
Scope string `json:"scope"`
|
||||
TargetNodes []string `json:"target_nodes"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
type MCPCallRequest struct {
|
||||
Device string `json:"device"`
|
||||
Server string `json:"server"`
|
||||
Tool string `json:"tool"`
|
||||
Arguments any `json:"arguments"`
|
||||
}
|
||||
|
||||
type MCPTestRequest struct {
|
||||
Device string `json:"device"`
|
||||
Service MCPServiceRequest `json:"service"`
|
||||
}
|
||||
|
||||
func (s *Server) TestMCPJSON(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
var q MCPTestRequest
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256*1024)).Decode(&q); err != nil {
|
||||
http.Error(w, "bad json", 400)
|
||||
return
|
||||
}
|
||||
if q.Device == "" {
|
||||
q.Device = s.LocalName
|
||||
}
|
||||
q.Service.Transport = strings.ToLower(strings.TrimSpace(q.Service.Transport))
|
||||
if q.Service.Transport == "" {
|
||||
http.Error(w, "transport required", 400)
|
||||
return
|
||||
}
|
||||
if q.Service.Transport == "stdio" {
|
||||
if strings.TrimSpace(q.Service.Command) == "" {
|
||||
http.Error(w, "stdio command required", 400)
|
||||
return
|
||||
}
|
||||
} else if q.Service.Transport == "http" || q.Service.Transport == "sse" {
|
||||
if strings.TrimSpace(q.Service.URL) == "" {
|
||||
http.Error(w, "HTTP/SSE URL required", 400)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
http.Error(w, "unsupported transport", 400)
|
||||
return
|
||||
}
|
||||
service := cluster.MCPService{ID: q.Service.ID, Name: q.Service.Name, Description: q.Service.Description, Transport: q.Service.Transport, Command: q.Service.Command, Args: q.Service.Args, Env: q.Service.Env, URL: q.Service.URL, Headers: q.Service.Headers}
|
||||
start := time.Now()
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
|
||||
defer cancel()
|
||||
var tools []map[string]any
|
||||
var err error
|
||||
if s.isRemote(q.Device) {
|
||||
if s.Cluster == nil || !s.Cluster.Online(q.Device) {
|
||||
err = fmt.Errorf("device %s is offline", q.Device)
|
||||
} else {
|
||||
tools, err = s.Cluster.TestMCP(ctx, q.Device, service)
|
||||
}
|
||||
} else {
|
||||
tools, err = cluster.ProbeMCP(ctx, service)
|
||||
}
|
||||
ms := time.Since(start).Milliseconds()
|
||||
if err != nil {
|
||||
_ = s.Store.Audit(clientIP(r), q.Device, "mcp_test", service.Name, 1, ms, err.Error())
|
||||
jsonOut(w, map[string]any{"success": false, "device": q.Device, "transport": service.Transport, "duration_ms": ms, "tool_count": 0, "tools": []any{}, "error": map[string]any{"code": "MCP_TEST_FAILED", "message": err.Error()}})
|
||||
return
|
||||
}
|
||||
_ = s.Store.Audit(clientIP(r), q.Device, "mcp_test", service.Name, 0, ms, "")
|
||||
jsonOut(w, map[string]any{"success": true, "device": q.Device, "transport": service.Transport, "duration_ms": ms, "tool_count": len(tools), "tools": tools, "error": nil})
|
||||
}
|
||||
|
||||
func (s *Server) MCPServicesJSON(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Store == nil {
|
||||
http.Error(w, "storage unavailable", 500)
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
v, err := s.Store.ListMCPServices()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
jsonOut(w, v)
|
||||
case http.MethodPost:
|
||||
var q MCPServiceRequest
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256*1024)).Decode(&q); err != nil {
|
||||
http.Error(w, "bad json", 400)
|
||||
return
|
||||
}
|
||||
if q.ID == "" || q.Name == "" || q.Transport == "stdio" && q.Command == "" || (q.Transport != "stdio" && q.URL == "") {
|
||||
http.Error(w, "invalid MCP service", 400)
|
||||
return
|
||||
}
|
||||
args, _ := json.Marshal(q.Args)
|
||||
env, _ := json.Marshal(q.Env)
|
||||
headers, _ := json.Marshal(q.Headers)
|
||||
nodes, _ := json.Marshal(q.TargetNodes)
|
||||
if q.Scope == "" {
|
||||
q.Scope = "all"
|
||||
}
|
||||
if q.Scope != "all" && q.Scope != "custom" {
|
||||
http.Error(w, "invalid scope", 400)
|
||||
return
|
||||
}
|
||||
v := storage.MCPService{ID: q.ID, Name: q.Name, Description: q.Description, Transport: q.Transport, Command: q.Command, ArgsJSON: string(args), EnvJSON: string(env), URL: q.URL, HeadersJSON: string(headers), Scope: q.Scope, TargetNodesJSON: string(nodes), Enabled: q.Enabled}
|
||||
if err := s.Store.SaveMCPService(v); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
if s.Cluster != nil {
|
||||
s.Cluster.SyncMCPServices()
|
||||
}
|
||||
_ = s.Store.Audit(clientIP(r), s.LocalName, "mcp_service_save", q.ID, 0, 0, "")
|
||||
jsonOut(w, v)
|
||||
default:
|
||||
http.Error(w, "method not allowed", 405)
|
||||
}
|
||||
}
|
||||
func (s *Server) DeleteMCPService(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodDelete {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
id := r.URL.Query().Get("id")
|
||||
if id == "" {
|
||||
http.Error(w, "id required", 400)
|
||||
return
|
||||
}
|
||||
if err := s.Store.DeleteMCPService(id); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
if s.Cluster != nil {
|
||||
s.Cluster.SyncMCPServices()
|
||||
}
|
||||
_ = s.Store.Audit(clientIP(r), s.LocalName, "mcp_service_delete", id, 0, 0, "")
|
||||
jsonOut(w, map[string]any{"ok": true})
|
||||
}
|
||||
func (s *Server) ListAgentMCPJSON(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
device := r.URL.Query().Get("device")
|
||||
if device == "" {
|
||||
http.Error(w, "device required", 400)
|
||||
return
|
||||
}
|
||||
if s.isRemote(device) && (s.Cluster == nil || !s.Cluster.Online(device)) {
|
||||
http.Error(w, "device offline", 409)
|
||||
return
|
||||
}
|
||||
if s.isRemote(device) {
|
||||
v, err := s.Cluster.ListMCP(device)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 404)
|
||||
return
|
||||
}
|
||||
jsonOut(w, map[string]any{"device": device, "services": v})
|
||||
return
|
||||
}
|
||||
jsonOut(w, map[string]any{"device": s.LocalName, "services": []any{}})
|
||||
}
|
||||
func (s *Server) CallAgentMCPJSON(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
var q MCPCallRequest
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256*1024)).Decode(&q); err != nil {
|
||||
http.Error(w, "bad json", 400)
|
||||
return
|
||||
}
|
||||
if q.Device == "" || q.Server == "" || q.Tool == "" {
|
||||
http.Error(w, "device, server and tool required", 400)
|
||||
return
|
||||
}
|
||||
if !s.requireSecurity(w, r, q.Device, "mcp", q.Server+"/"+q.Tool) {
|
||||
return
|
||||
}
|
||||
if s.isRemote(q.Device) && (s.Cluster == nil || !s.Cluster.Online(q.Device)) {
|
||||
if s.Store != nil {
|
||||
_ = s.Store.Audit(clientIP(r), q.Device, "mcp_call", q.Server+"/"+q.Tool, 1, 0, "device offline")
|
||||
}
|
||||
http.Error(w, "device offline", 409)
|
||||
return
|
||||
}
|
||||
if !s.isRemote(q.Device) {
|
||||
http.Error(w, "agent MCP requires a remote device", 400)
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
v, err := s.Cluster.CallMCP(r.Context(), q.Device, q.Server, q.Tool, q.Arguments)
|
||||
ms := time.Since(start).Milliseconds()
|
||||
if err != nil {
|
||||
_ = s.Store.Audit(clientIP(r), q.Device, "mcp_call", q.Server+"/"+q.Tool, 1, ms, err.Error())
|
||||
http.Error(w, err.Error(), 502)
|
||||
return
|
||||
}
|
||||
_ = s.Store.Audit(clientIP(r), q.Device, "mcp_call", q.Server+"/"+q.Tool, 0, ms, "")
|
||||
jsonOut(w, v)
|
||||
}
|
||||
|
||||
func (s *Server) Routes() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/healthz", s.health)
|
||||
mux.HandleFunc("/api/v1/devices", s.devices)
|
||||
mux.HandleFunc("/api/v1/exec", s.exec)
|
||||
mux.HandleFunc("/api/v1/file/read", s.fileRead)
|
||||
mux.HandleFunc("/api/v1/file/list", s.listDirectory)
|
||||
mux.HandleFunc("/api/v1/file/info", s.fileInfo)
|
||||
mux.HandleFunc("/api/v1/file/search", s.searchFiles)
|
||||
mux.HandleFunc("/api/v1/process/session", s.processSession)
|
||||
mux.HandleFunc("/api/v1/file/write", s.fileWrite)
|
||||
mux.HandleFunc("/api/v1/devices/file/edit_block", s.editBlock)
|
||||
mux.HandleFunc("/api/v1/mcp/services", s.MCPServicesJSON)
|
||||
mux.HandleFunc("/api/v1/mcp/service", s.DeleteMCPService)
|
||||
mux.HandleFunc("/api/v1/mcp/list", s.ListAgentMCPJSON)
|
||||
mux.HandleFunc("/api/v1/mcp/call", s.CallAgentMCPJSON)
|
||||
mux.HandleFunc("/api/v1/mcp/test", s.TestMCPJSON)
|
||||
mux.HandleFunc("/api/v1/security/settings", s.SecuritySettingsJSON)
|
||||
mux.HandleFunc("/api/v1/security/settings/update", s.UpdateSecuritySettingsJSON)
|
||||
mux.HandleFunc("/api/v1/security/device-credentials/provision", s.ProvisionDeviceCredentialJSON)
|
||||
mux.HandleFunc("/api/v1/notifications/webhooks", s.WebhookTargetsJSON)
|
||||
mux.HandleFunc("/api/v1/notifications/webhook/update", s.UpdateWebhookTargetJSON)
|
||||
mux.HandleFunc("/api/v1/notifications/webhook/delete", s.DeleteWebhookTargetJSON)
|
||||
mux.HandleFunc("/api/v1/notifications/webhook/test", s.TestWebhookJSON)
|
||||
mux.HandleFunc("/agent/ws", s.agentWS)
|
||||
mux.HandleFunc("/openapi.json", s.openapi)
|
||||
return mux
|
||||
@@ -106,15 +633,35 @@ func (s *Server) devices(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
localProf := sysinfo.Collect("CONTROL")
|
||||
out := []model.Device{{Name: s.LocalName, Status: "online", Local: true, Arch: runtime.GOARCH, OS: runtime.GOOS, Profile: &localProf}}
|
||||
localCC, localCountry := cluster.ResolveLocalPublicIP()
|
||||
localDev := model.Device{
|
||||
Name: s.LocalName,
|
||||
Status: "online",
|
||||
Local: true,
|
||||
Arch: runtime.GOARCH,
|
||||
OS: runtime.GOOS,
|
||||
CountryCode: localCC,
|
||||
Country: localCountry,
|
||||
Profile: &localProf,
|
||||
}
|
||||
|
||||
var remoteDevs []model.Device
|
||||
if s.Cluster != nil {
|
||||
for _, d := range s.Cluster.Devices() {
|
||||
b, _ := json.Marshal(d)
|
||||
var v model.Device
|
||||
_ = json.Unmarshal(b, &v)
|
||||
out = append(out, v)
|
||||
remoteDevs = append(remoteDevs, v)
|
||||
}
|
||||
}
|
||||
|
||||
// 稳定排序:远程节点按名称字典序排列
|
||||
sort.Slice(remoteDevs, func(i, j int) bool {
|
||||
return remoteDevs[i].Name < remoteDevs[j].Name
|
||||
})
|
||||
|
||||
// 本机永远钉死在第 1 位
|
||||
out := append([]model.Device{localDev}, remoteDevs...)
|
||||
jsonOut(w, out)
|
||||
}
|
||||
|
||||
@@ -151,6 +698,21 @@ func (s *Server) agentWS(w http.ResponseWriter, r *http.Request) {
|
||||
func (s *Server) isRemote(device string) bool {
|
||||
return device != "" && device != "local" && device != s.LocalName
|
||||
}
|
||||
func (s *Server) acquireExec() func() {
|
||||
if s.ExecLimiter == nil {
|
||||
return func() {}
|
||||
}
|
||||
s.ExecLimiter <- struct{}{}
|
||||
return func() { <-s.ExecLimiter }
|
||||
}
|
||||
func (s *Server) acquireSearch() func() {
|
||||
if s.SearchLimiter == nil {
|
||||
return func() {}
|
||||
}
|
||||
s.SearchLimiter <- struct{}{}
|
||||
return func() { <-s.SearchLimiter }
|
||||
}
|
||||
|
||||
func (s *Server) exec(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
@@ -168,6 +730,11 @@ func (s *Server) exec(w http.ResponseWriter, r *http.Request) {
|
||||
if req.Device == "" {
|
||||
req.Device = s.LocalName
|
||||
}
|
||||
if !s.requireSecurity(w, r, req.Device, "exec", req.Command) {
|
||||
return
|
||||
}
|
||||
releaseExec := s.acquireExec()
|
||||
defer releaseExec()
|
||||
if req.Timeout <= 0 {
|
||||
req.Timeout = 30
|
||||
}
|
||||
@@ -179,7 +746,7 @@ func (s *Server) exec(w http.ResponseWriter, r *http.Request) {
|
||||
var res executor.Result
|
||||
if s.isRemote(req.Device) {
|
||||
if s.Cluster == nil || !s.Cluster.Online(req.Device) {
|
||||
http.Error(w, "device offline", 404)
|
||||
http.Error(w, "device offline", 409)
|
||||
return
|
||||
}
|
||||
rr, err := s.Cluster.Exec(ctx, req.Device, cluster.ExecPayload{Command: req.Command, Workdir: req.Workdir, Timeout: req.Timeout})
|
||||
@@ -197,6 +764,269 @@ func (s *Server) exec(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
jsonOut(w, model.ExecResponse{Device: req.Device, ExitCode: res.ExitCode, Stdout: res.Stdout, Stderr: res.Stderr, DurationMS: res.DurationMS})
|
||||
}
|
||||
func sessionOwner(r *http.Request) string {
|
||||
v := r.Header.Get("Authorization") + "|" + r.Header.Get("X-Operator-ID") + "|" + clientIP(r)
|
||||
h := sha256.Sum256([]byte(v))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
func newSessionID() (string, error) {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
func (s *Server) processSession(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Device string `json:"device"`
|
||||
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"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256*1024)).Decode(&req); err != nil {
|
||||
http.Error(w, "bad json", 400)
|
||||
return
|
||||
}
|
||||
if req.Device == "" {
|
||||
req.Device = s.LocalName
|
||||
}
|
||||
if !s.requireSecurity(w, r, req.Device, "exec", req.SessionID) {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
action := r.URL.Query().Get("action")
|
||||
owner := sessionOwner(r)
|
||||
var result any
|
||||
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 {
|
||||
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
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 409)
|
||||
return
|
||||
}
|
||||
jsonOut(w, result)
|
||||
}
|
||||
|
||||
func (s *Server) listDirectory(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Device, Path string
|
||||
Recursive bool `json:"recursive"`
|
||||
MaxEntries int `json:"max_entries"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16*1024)).Decode(&req); err != nil {
|
||||
http.Error(w, "bad json", 400)
|
||||
return
|
||||
}
|
||||
if req.Device == "" {
|
||||
req.Device = s.LocalName
|
||||
}
|
||||
if !s.requireSecurity(w, r, req.Device, "read", req.Path) {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
var v []cluster.Entry
|
||||
var err error
|
||||
if s.isRemote(req.Device) {
|
||||
v, err = s.Cluster.ListDirectory(ctx, req.Device, cluster.ListDirectoryPayload{Path: req.Path, Recursive: req.Recursive, MaxEntries: req.MaxEntries})
|
||||
} else {
|
||||
var ev []executor.Entry
|
||||
ev, err = executor.ListDirectory(req.Path, req.Recursive, req.MaxEntries)
|
||||
if err == nil {
|
||||
b, _ := json.Marshal(ev)
|
||||
err = json.Unmarshal(b, &v)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 409)
|
||||
return
|
||||
}
|
||||
jsonOut(w, v)
|
||||
}
|
||||
func (s *Server) fileInfo(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
var req struct{ Device, Path string }
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16*1024)).Decode(&req); err != nil {
|
||||
http.Error(w, "bad json", 400)
|
||||
return
|
||||
}
|
||||
if req.Device == "" {
|
||||
req.Device = s.LocalName
|
||||
}
|
||||
if !s.requireSecurity(w, r, req.Device, "read", req.Path) {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
||||
defer cancel()
|
||||
var v cluster.FileInfo
|
||||
var err error
|
||||
if s.isRemote(req.Device) {
|
||||
v, err = s.Cluster.GetFileInfo(ctx, req.Device, cluster.FileInfoPayload{Path: req.Path})
|
||||
} else {
|
||||
var ev executor.FileInfo
|
||||
ev, err = executor.GetFileInfo(req.Path)
|
||||
if err == nil {
|
||||
b, _ := json.Marshal(ev)
|
||||
err = json.Unmarshal(b, &v)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 404)
|
||||
return
|
||||
}
|
||||
jsonOut(w, v)
|
||||
}
|
||||
func (s *Server) searchFiles(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Device, Root, Query string
|
||||
MaxResults int `json:"max_results"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16*1024)).Decode(&req); err != nil {
|
||||
http.Error(w, "bad json", 400)
|
||||
return
|
||||
}
|
||||
if req.Device == "" {
|
||||
req.Device = s.LocalName
|
||||
}
|
||||
if !s.requireSecurity(w, r, req.Device, "read", req.Root) {
|
||||
return
|
||||
}
|
||||
releaseSearch := s.acquireSearch()
|
||||
defer releaseSearch()
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
|
||||
defer cancel()
|
||||
var v []cluster.SearchResult
|
||||
var err error
|
||||
if s.isRemote(req.Device) {
|
||||
v, err = s.Cluster.Search(ctx, req.Device, cluster.SearchPayload{Root: req.Root, Query: req.Query, MaxResults: req.MaxResults})
|
||||
} else {
|
||||
var ev []executor.SearchResult
|
||||
ev, err = executor.Search(ctx, req.Root, req.Query, req.MaxResults)
|
||||
if err == nil {
|
||||
b, _ := json.Marshal(ev)
|
||||
err = json.Unmarshal(b, &v)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 409)
|
||||
return
|
||||
}
|
||||
jsonOut(w, v)
|
||||
}
|
||||
|
||||
func (s *Server) fileRead(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
@@ -210,6 +1040,9 @@ func (s *Server) fileRead(w http.ResponseWriter, r *http.Request) {
|
||||
if req.Device == "" {
|
||||
req.Device = s.LocalName
|
||||
}
|
||||
if !s.requireSecurity(w, r, req.Device, "read", req.Path) {
|
||||
return
|
||||
}
|
||||
if req.Path == "" || !validPath(req.Path) || req.Offset < 0 {
|
||||
http.Error(w, "invalid path or offset", 400)
|
||||
return
|
||||
@@ -269,6 +1102,64 @@ func (s *Server) fileRead(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
jsonOut(w, model.FileReadResponse{Device: req.Device, Path: req.Path, Offset: req.Offset, Content: content, Bytes: n, TotalSize: totalSize, HasMore: hasMore, EOF: eof})
|
||||
}
|
||||
func (s *Server) editBlock(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Device string `json:"device,omitempty"`
|
||||
Path string `json:"path"`
|
||||
OldText string `json:"old_text"`
|
||||
NewText string `json:"new_text"`
|
||||
}
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxFileLimit+64*1024)).Decode(&req); err != nil {
|
||||
http.Error(w, "bad json or content too large", 400)
|
||||
return
|
||||
}
|
||||
if req.Device == "" {
|
||||
req.Device = s.LocalName
|
||||
}
|
||||
if !s.requireSecurity(w, r, req.Device, "write", req.Path) {
|
||||
return
|
||||
}
|
||||
if req.Path == "" || !validPath(req.Path) || req.OldText == "" {
|
||||
http.Error(w, "path and old_text required", 400)
|
||||
return
|
||||
}
|
||||
if len(req.OldText) > int(maxFileLimit) || len(req.NewText) > int(maxFileLimit) {
|
||||
http.Error(w, "edit block too large", 413)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
var result executor.EditBlockResult
|
||||
if s.isRemote(req.Device) {
|
||||
if s.Cluster == nil || !s.Cluster.Online(req.Device) {
|
||||
http.Error(w, "device offline", 409)
|
||||
return
|
||||
}
|
||||
rr, err := s.Cluster.EditBlock(ctx, req.Device, cluster.EditBlockPayload{Path: req.Path, OldText: req.OldText, NewText: req.NewText})
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 409)
|
||||
return
|
||||
}
|
||||
result.BytesWritten = rr.BytesWritten
|
||||
} else {
|
||||
var err error
|
||||
result, err = executor.EditBlock(req.Path, req.OldText, req.NewText)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 409)
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := s.Store.Audit(clientIP(r), req.Device, "edit_block", req.Path, 0, 0, fmt.Sprintf("bytes_written=%d", result.BytesWritten)); err != nil {
|
||||
http.Error(w, "audit write failed", 500)
|
||||
return
|
||||
}
|
||||
jsonOut(w, map[string]any{"device": req.Device, "path": req.Path, "bytes_written": result.BytesWritten})
|
||||
}
|
||||
|
||||
func (s *Server) fileWrite(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
@@ -282,6 +1173,9 @@ func (s *Server) fileWrite(w http.ResponseWriter, r *http.Request) {
|
||||
if req.Device == "" {
|
||||
req.Device = s.LocalName
|
||||
}
|
||||
if !s.requireSecurity(w, r, req.Device, "write", req.Path) {
|
||||
return
|
||||
}
|
||||
if req.Path == "" || !validPath(req.Path) {
|
||||
http.Error(w, "path required", 400)
|
||||
return
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/wjyhk/vps-commander/internal/executor"
|
||||
"github.com/wjyhk/vps-commander/internal/storage"
|
||||
@@ -18,6 +22,9 @@ func TestExecConcurrent100AuditsPersisted(t *testing.T) {
|
||||
}
|
||||
defer store.DB.Close()
|
||||
|
||||
if err := store.SetGlobalSecurityMode("high"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := &Server{Exec: executor.Local{MaxOutput: 1024 * 1024}, Store: store, LocalName: "local"}
|
||||
|
||||
const n = 100
|
||||
@@ -48,3 +55,115 @@ func TestExecConcurrent100AuditsPersisted(t *testing.T) {
|
||||
t.Fatalf("audit loss: got %d rows, want %d", len(logs), n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityEffectiveModeAndExecGate(t *testing.T) {
|
||||
store, err := storage.Open(filepath.Join(t.TempDir(), "commander.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.DB.Close()
|
||||
s := &Server{Exec: executor.Local{MaxOutput: 1024 * 1024}, Store: store, LocalName: "local"}
|
||||
if got := s.GetEffectiveSecurityMode("node-a"); got != "unknown" {
|
||||
t.Fatalf("unknown mode=%s", got)
|
||||
}
|
||||
if err := store.SetNodeSecurityMode("node-a", "high"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.GetEffectiveSecurityMode("node-a"); got != "high" {
|
||||
t.Fatalf("override=%s", got)
|
||||
}
|
||||
if err := store.SetNodeSecurityMode("node-a", "inherit"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetGlobalSecurityMode("low"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.GetEffectiveSecurityMode("node-a"); got != "low" {
|
||||
t.Fatalf("inherit=%s", got)
|
||||
}
|
||||
req := httptest.NewRequest("POST", "/api/v1/exec", strings.NewReader(`{"device":"node-a","command":"true"}`))
|
||||
rec := httptest.NewRecorder()
|
||||
s.exec(rec, req)
|
||||
if rec.Code != 403 {
|
||||
t.Fatalf("low exec status=%d", rec.Code)
|
||||
}
|
||||
logs, _ := store.RecentAudits(10)
|
||||
if len(logs) == 0 || logs[0].Action != "security_denied" {
|
||||
t.Fatalf("missing denial audit: %+v", logs)
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
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("medium"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := &Server{Exec: executor.Local{MaxOutput: 1024 * 1024}, Store: store, LocalName: "local"}
|
||||
if err := s.LoadSecurityPolicySnapshot(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(dir, "config.txt")
|
||||
if err := os.WriteFile(path, []byte("alpha\nTARGET\nomega\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/devices/file/edit_block", strings.NewReader(fmt.Sprintf(`{"path":%q,"old_text":"TARGET","new_text":"CHANGED"}`, path)))
|
||||
w := httptest.NewRecorder()
|
||||
s.editBlock(w, r)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("edit status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
b, _ := os.ReadFile(path)
|
||||
if string(b) != "alpha\nCHANGED\nomega\n" {
|
||||
t.Fatalf("unexpected content: %q", b)
|
||||
}
|
||||
|
||||
if err := store.SetGlobalSecurityMode("low"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.LoadSecurityPolicySnapshot(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r = httptest.NewRequest(http.MethodPost, "/api/v1/devices/file/edit_block", strings.NewReader(fmt.Sprintf(`{"path":%q,"old_text":"CHANGED","new_text":"NO"}`, path)))
|
||||
w = httptest.NewRecorder()
|
||||
s.editBlock(w, r)
|
||||
if w.Code != 403 {
|
||||
t.Fatalf("low mode status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,20 @@ func (s *Server) NewMCPBackend() *MCPBackend {
|
||||
return &MCPBackend{server: s}
|
||||
}
|
||||
|
||||
func (b *MCPBackend) authorize(device, action, clientIP string) error {
|
||||
if device == "" {
|
||||
device = b.server.LocalName
|
||||
}
|
||||
mode := b.server.GetEffectiveSecurityMode(device)
|
||||
if !securityAllows(mode, action) {
|
||||
if b.server.Store != nil {
|
||||
_ = b.server.Store.Audit(clientIP, device, "security_denied", action, 403, 0, "MCP security gate")
|
||||
}
|
||||
return fmt.Errorf("security mode %s denies %s", mode, action)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *MCPBackend) ListDevices(ctx context.Context) (any, error) {
|
||||
out := []model.Device{{Name: b.server.LocalName, Status: "online", Local: true, Arch: runtime.GOARCH, OS: runtime.GOOS}}
|
||||
if b.server.Cluster != nil {
|
||||
@@ -44,6 +58,9 @@ func (b *MCPBackend) ExecCommand(ctx context.Context, clientIP, device, command,
|
||||
if device == "" {
|
||||
device = b.server.LocalName
|
||||
}
|
||||
if err := b.authorize(device, "exec", clientIP); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if timeout <= 0 {
|
||||
timeout = 30
|
||||
}
|
||||
@@ -81,10 +98,40 @@ func (b *MCPBackend) ExecCommand(ctx context.Context, clientIP, device, command,
|
||||
}, 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) {
|
||||
if device == "" {
|
||||
device = b.server.LocalName
|
||||
}
|
||||
if err := b.authorize(device, "read", clientIP); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if path == "" || !validPath(path) || offset < 0 {
|
||||
return nil, errors.New("invalid path or offset")
|
||||
}
|
||||
@@ -150,10 +197,45 @@ func (b *MCPBackend) ReadFile(ctx context.Context, clientIP, device, path string
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (b *MCPBackend) EditBlock(ctx context.Context, clientIP, device, path, oldText, newText string) (any, error) {
|
||||
if device == "" {
|
||||
device = b.server.LocalName
|
||||
}
|
||||
if err := b.authorize(device, "write", clientIP); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if path == "" || !validPath(path) || oldText == "" {
|
||||
return nil, errors.New("path and old_text required")
|
||||
}
|
||||
if len(oldText) > int(maxFileLimit) || len(newText) > int(maxFileLimit) {
|
||||
return nil, errors.New("edit block too large")
|
||||
}
|
||||
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.EditBlock(ctx, device, cluster.EditBlockPayload{Path: path, OldText: oldText, NewText: newText})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = b.server.Store.Audit(clientIP, device, "edit_block", path, 0, 0, fmt.Sprintf("bytes_written=%d", res.BytesWritten))
|
||||
return map[string]any{"device": device, "path": path, "bytes_written": res.BytesWritten}, nil
|
||||
}
|
||||
res, err := executor.EditBlock(path, oldText, newText)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = b.server.Store.Audit(clientIP, device, "edit_block", path, 0, 0, fmt.Sprintf("bytes_written=%d", res.BytesWritten))
|
||||
return map[string]any{"device": device, "path": path, "bytes_written": res.BytesWritten}, nil
|
||||
}
|
||||
|
||||
func (b *MCPBackend) WriteFile(ctx context.Context, clientIP, device, path, content string) (any, error) {
|
||||
if device == "" {
|
||||
device = b.server.LocalName
|
||||
}
|
||||
if err := b.authorize(device, "write", clientIP); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if path == "" || !validPath(path) {
|
||||
return nil, errors.New("path required")
|
||||
}
|
||||
@@ -188,3 +270,119 @@ func (b *MCPBackend) WriteFile(ctx context.Context, clientIP, device, path, cont
|
||||
Bytes: n,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (b *MCPBackend) ListAgentMCP(ctx context.Context, device string) (any, error) {
|
||||
if device == "" {
|
||||
return nil, errors.New("device required")
|
||||
}
|
||||
if b.server.isRemote(device) && (b.server.Cluster == nil || !b.server.Cluster.Online(device)) {
|
||||
return nil, fmt.Errorf("device %s is offline", device)
|
||||
}
|
||||
if !b.server.isRemote(device) {
|
||||
return map[string]any{"device": b.server.LocalName, "services": []any{}}, nil
|
||||
}
|
||||
return b.server.Cluster.ListMCP(device)
|
||||
}
|
||||
func (b *MCPBackend) CallAgentMCP(ctx context.Context, clientIP, device, server, tool string, args any) (any, error) {
|
||||
if device == "" || server == "" || tool == "" {
|
||||
return nil, errors.New("device, server and tool required")
|
||||
}
|
||||
if b.server.isRemote(device) && (b.server.Cluster == nil || !b.server.Cluster.Online(device)) {
|
||||
return nil, fmt.Errorf("device %s is offline", device)
|
||||
}
|
||||
if !b.server.isRemote(device) {
|
||||
return nil, errors.New("agent MCP requires a remote device")
|
||||
}
|
||||
start := time.Now()
|
||||
v, err := b.server.Cluster.CallMCP(ctx, device, server, tool, args)
|
||||
ms := time.Since(start).Milliseconds()
|
||||
if b.server.Store != nil {
|
||||
if err != nil {
|
||||
_ = b.server.Store.Audit(clientIP, device, "mcp_call", server+"/"+tool, 1, ms, err.Error())
|
||||
} else {
|
||||
_ = b.server.Store.Audit(clientIP, device, "mcp_call", server+"/"+tool, 0, ms, "")
|
||||
}
|
||||
}
|
||||
return v, err
|
||||
}
|
||||
|
||||
// AuthorizeMCP exposes the same Hub-side gate to the MCP transport layer.
|
||||
func (b *MCPBackend) AuthorizeMCP(device, action, clientIP string) error {
|
||||
return b.authorize(device, action, clientIP)
|
||||
}
|
||||
|
||||
func (b *MCPBackend) ReadMultipleFiles(ctx context.Context, clientIP, device string, paths []string, limit int64) (any, error) {
|
||||
if device == "" {
|
||||
device = b.server.LocalName
|
||||
}
|
||||
if err := b.authorize(device, "read", clientIP); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(paths) > 32 {
|
||||
return nil, errors.New("too many paths")
|
||||
}
|
||||
if b.server.isRemote(device) {
|
||||
if b.server.Cluster == nil || !b.server.Cluster.Online(device) {
|
||||
return nil, fmt.Errorf("device %s is offline", device)
|
||||
}
|
||||
return b.server.Cluster.ReadMultipleFiles(ctx, device, cluster.ReadMultipleFilesPayload{Paths: paths, Limit: limit})
|
||||
}
|
||||
return executor.ReadMultipleFiles(paths, limit), nil
|
||||
}
|
||||
func (b *MCPBackend) CreateDirectory(ctx context.Context, clientIP, device, path string) (any, error) {
|
||||
if device == "" {
|
||||
device = b.server.LocalName
|
||||
}
|
||||
if err := b.authorize(device, "write", clientIP); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if b.server.isRemote(device) {
|
||||
if b.server.Cluster == nil || !b.server.Cluster.Online(device) {
|
||||
return nil, fmt.Errorf("device %s is offline", device)
|
||||
}
|
||||
if err := b.server.Cluster.CreateDirectory(ctx, device, cluster.CreateDirectoryPayload{Path: path}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
if err := executor.CreateDirectory(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return map[string]any{"device": device, "path": path, "ok": true}, nil
|
||||
}
|
||||
func (b *MCPBackend) MoveFile(ctx context.Context, clientIP, device, source, destination string) (any, error) {
|
||||
if device == "" {
|
||||
device = b.server.LocalName
|
||||
}
|
||||
if err := b.authorize(device, "write", clientIP); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if b.server.isRemote(device) {
|
||||
if b.server.Cluster == nil || !b.server.Cluster.Online(device) {
|
||||
return nil, fmt.Errorf("device %s is offline", device)
|
||||
}
|
||||
if err := b.server.Cluster.MoveFile(ctx, device, cluster.MoveFilePayload{Source: source, Destination: destination}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
if err := executor.MoveFile(source, destination); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return map[string]any{"device": device, "source": source, "destination": destination, "ok": true}, nil
|
||||
}
|
||||
func (b *MCPBackend) ListProcesses(ctx context.Context, clientIP, device string) (any, error) {
|
||||
if device == "" {
|
||||
device = b.server.LocalName
|
||||
}
|
||||
if err := b.authorize(device, "read", clientIP); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if b.server.isRemote(device) {
|
||||
if b.server.Cluster == nil || !b.server.Cluster.Online(device) {
|
||||
return nil, fmt.Errorf("device %s is offline", device)
|
||||
}
|
||||
return b.server.Cluster.ListProcesses(ctx, device)
|
||||
}
|
||||
return executor.ListProcesses()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/wjyhk/vps-commander/internal/executor"
|
||||
"github.com/wjyhk/vps-commander/internal/storage"
|
||||
)
|
||||
|
||||
func TestMCPBackendHonorsSecuritySnapshot(t *testing.T) {
|
||||
store, err := storage.Open(filepath.Join(t.TempDir(), "commander.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.DB.Close()
|
||||
if err := store.SetGlobalSecurityMode("low"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := &Server{Store: store, LocalName: "local", Exec: executor.Local{MaxOutput: 1024 * 1024}}
|
||||
if err := s.LoadSecurityPolicySnapshot(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b := s.NewMCPBackend()
|
||||
if _, err := b.ExecCommand(context.Background(), "test", "local", "true", "", 5); err == nil {
|
||||
t.Fatal("MCP exec must be denied in low mode")
|
||||
}
|
||||
if _, err := b.ReadFile(context.Background(), "test", "local", "/etc/hosts", 0, 128); err != nil {
|
||||
t.Fatalf("MCP read should remain available in low mode: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownDeviceFailsClosed(t *testing.T) {
|
||||
store, err := storage.Open(filepath.Join(t.TempDir(), "commander.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.DB.Close()
|
||||
if err := store.SetGlobalSecurityMode("high"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := &Server{Store: store, LocalName: "local", Exec: executor.Local{MaxOutput: 1024 * 1024}}
|
||||
if err := s.LoadSecurityPolicySnapshot(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.GetEffectiveSecurityMode("not-registered"); got != "unknown" {
|
||||
t.Fatalf("unknown device mode=%q", got)
|
||||
}
|
||||
b := s.NewMCPBackend()
|
||||
if _, err := b.ExecCommand(context.Background(), "test", "not-registered", "true", "", 5); err == nil {
|
||||
t.Fatal("unknown device must not inherit high risk")
|
||||
}
|
||||
}
|
||||
@@ -157,6 +157,69 @@
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"MCPService": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"type": "string"
|
||||
},
|
||||
"transport": {
|
||||
"type": "string"
|
||||
},
|
||||
"command": {
|
||||
"type": "string"
|
||||
},
|
||||
"args_json": {
|
||||
"type": "string"
|
||||
},
|
||||
"env_json": {
|
||||
"type": "string"
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
},
|
||||
"headers_json": {
|
||||
"type": "string"
|
||||
},
|
||||
"scope": {
|
||||
"type": "string"
|
||||
},
|
||||
"target_nodes_json": {
|
||||
"type": "string"
|
||||
},
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
},
|
||||
"MCPCallRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"device",
|
||||
"server",
|
||||
"tool"
|
||||
],
|
||||
"properties": {
|
||||
"device": {
|
||||
"type": "string"
|
||||
},
|
||||
"server": {
|
||||
"type": "string"
|
||||
},
|
||||
"tool": {
|
||||
"type": "string"
|
||||
},
|
||||
"arguments": {
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -281,6 +344,408 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/mcp/services": {
|
||||
"get": {
|
||||
"operationId": "list_mcp_services",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "MCP services",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/MCPService"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"operationId": "save_mcp_service",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MCPService"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Saved MCP service"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/mcp/service": {
|
||||
"delete": {
|
||||
"operationId": "delete_mcp_service",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "query",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Deleted"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/mcp/list": {
|
||||
"get": {
|
||||
"operationId": "list_agent_mcp",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "device",
|
||||
"in": "query",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Mounted MCP services"
|
||||
},
|
||||
"409": {
|
||||
"description": "Device offline"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/mcp/call": {
|
||||
"post": {
|
||||
"operationId": "call_agent_mcp",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/MCPCallRequest"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "MCP result"
|
||||
},
|
||||
"409": {
|
||||
"description": "Device offline"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/security/settings": {
|
||||
"get": {
|
||||
"summary": "Get security policy",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Current global and per-node security policy"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/security/settings/update": {
|
||||
"post": {
|
||||
"summary": "Update security policy",
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"global": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"low",
|
||||
"medium",
|
||||
"high"
|
||||
]
|
||||
},
|
||||
"node": {
|
||||
"type": "string"
|
||||
},
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"inherit",
|
||||
"low",
|
||||
"medium",
|
||||
"high"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Updated"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/notifications/webhooks": {
|
||||
"get": {
|
||||
"summary": "List webhook targets",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/notifications/webhook/update": {
|
||||
"post": {
|
||||
"summary": "Create or update webhook target",
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"id",
|
||||
"name",
|
||||
"type",
|
||||
"url"
|
||||
],
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"generic",
|
||||
"telegram",
|
||||
"wecom"
|
||||
]
|
||||
},
|
||||
"url": {
|
||||
"type": "string"
|
||||
},
|
||||
"config_json": {
|
||||
"type": "string"
|
||||
},
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/notifications/webhook/delete": {
|
||||
"delete": {
|
||||
"summary": "Delete webhook target",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "query",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/notifications/webhook/test": {
|
||||
"post": {
|
||||
"summary": "Send webhook test message",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/devices/file/edit_block": {
|
||||
"post": {
|
||||
"summary": "Atomically replace a unique text block on a device",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"path",
|
||||
"old_text",
|
||||
"new_text"
|
||||
],
|
||||
"properties": {
|
||||
"device": {
|
||||
"type": "string"
|
||||
},
|
||||
"path": {
|
||||
"type": "string"
|
||||
},
|
||||
"old_text": {
|
||||
"type": "string"
|
||||
},
|
||||
"new_text": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Edited"
|
||||
},
|
||||
"403": {
|
||||
"description": "Security policy denied"
|
||||
},
|
||||
"409": {
|
||||
"description": "Device offline or edit conflict"
|
||||
},
|
||||
"413": {
|
||||
"description": "Edit block too large"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/process/session": {
|
||||
"post": {
|
||||
"summary": "Manage long-running process sessions",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "action",
|
||||
"in": "query",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"start",
|
||||
"read",
|
||||
"input",
|
||||
"stop",
|
||||
"list"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Session operation result"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/file/list": {
|
||||
"post": {
|
||||
"summary": "List directory",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful result"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/file/info": {
|
||||
"post": {
|
||||
"summary": "Get file metadata",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful result"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/file/search": {
|
||||
"post": {
|
||||
"summary": "Search files",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful result"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,12 +42,7 @@ func (m Middleware) Handler(next http.Handler) http.Handler {
|
||||
h := r.Header.Get("Authorization")
|
||||
if strings.HasPrefix(h, "Bearer ") {
|
||||
got = strings.TrimSpace(strings.TrimPrefix(h, "Bearer "))
|
||||
} else if q := r.URL.Query().Get("token"); q != "" {
|
||||
got = q
|
||||
} else if q := r.URL.Query().Get("key"); q != "" {
|
||||
got = q
|
||||
} else if q := r.URL.Query().Get("api_key"); q != "" {
|
||||
got = q
|
||||
|
||||
}
|
||||
|
||||
expected := m.Token
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type GeoLocation struct {
|
||||
CountryCode string `json:"countryCode"`
|
||||
Country string `json:"country"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
var (
|
||||
geoCache sync.Map
|
||||
client = &http.Client{Timeout: 4 * time.Second}
|
||||
)
|
||||
|
||||
func isPrivateIP(ipStr string) bool {
|
||||
ip := net.ParseIP(ipStr)
|
||||
if ip == nil {
|
||||
return false
|
||||
}
|
||||
if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ExtractIPFromRequest retrieves the real client IP from HTTP headers or RemoteAddr
|
||||
func ExtractIPFromRequest(r *http.Request) string {
|
||||
if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" {
|
||||
parts := strings.Split(fwd, ",")
|
||||
for _, p := range parts {
|
||||
clean := strings.TrimSpace(p)
|
||||
if clean != "" && !isPrivateIP(clean) {
|
||||
return clean
|
||||
}
|
||||
}
|
||||
if len(parts) > 0 {
|
||||
clean := strings.TrimSpace(parts[0])
|
||||
if clean != "" {
|
||||
return clean
|
||||
}
|
||||
}
|
||||
}
|
||||
if realIP := strings.TrimSpace(r.Header.Get("X-Real-IP")); realIP != "" {
|
||||
return realIP
|
||||
}
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err == nil {
|
||||
return host
|
||||
}
|
||||
return r.RemoteAddr
|
||||
}
|
||||
|
||||
// ResolveIP returns countryCode (e.g. "HK", "SG") and countryName (e.g. "Hong Kong", "Singapore")
|
||||
func ResolveIP(ipStr string) (string, string) {
|
||||
ipStr = strings.TrimSpace(ipStr)
|
||||
if ipStr == "" {
|
||||
return "", ""
|
||||
}
|
||||
if isPrivateIP(ipStr) {
|
||||
return "CN", "中国"
|
||||
}
|
||||
if v, ok := geoCache.Load(ipStr); ok {
|
||||
if g, ok := v.(GeoLocation); ok {
|
||||
return g.CountryCode, g.Country
|
||||
}
|
||||
}
|
||||
|
||||
url := "http://ip-api.com/json/" + ipStr + "?fields=status,country,countryCode"
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return "", ""
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var g GeoLocation
|
||||
if err := json.NewDecoder(resp.Body).Decode(&g); err != nil {
|
||||
return "", ""
|
||||
}
|
||||
if g.Status == "success" && g.CountryCode != "" {
|
||||
geoCache.Store(ipStr, g)
|
||||
return g.CountryCode, g.Country
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
// ResolveLocalPublicIP queries the hub host's public IP location
|
||||
func ResolveLocalPublicIP() (string, string) {
|
||||
if v, ok := geoCache.Load("__local__"); ok {
|
||||
if g, ok := v.(GeoLocation); ok {
|
||||
return g.CountryCode, g.Country
|
||||
}
|
||||
}
|
||||
resp, err := client.Get("http://ip-api.com/json/?fields=status,country,countryCode")
|
||||
if err != nil {
|
||||
return "HK", "中国香港"
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var g GeoLocation
|
||||
if err := json.NewDecoder(resp.Body).Decode(&g); err != nil {
|
||||
return "HK", "中国香港"
|
||||
}
|
||||
if g.Status == "success" && g.CountryCode != "" {
|
||||
geoCache.Store("__local__", g)
|
||||
return g.CountryCode, g.Country
|
||||
}
|
||||
return "HK", "中国香港"
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/wjyhk/vps-commander/internal/storage"
|
||||
"github.com/wjyhk/vps-commander/internal/sysinfo"
|
||||
)
|
||||
|
||||
func TestLifecycleAcceptance(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "acceptance.db")
|
||||
store, err := storage.Open(dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("storage.Open failed: %v", err)
|
||||
}
|
||||
defer store.DB.Close()
|
||||
|
||||
secret := "acc-secret"
|
||||
mgr := NewManager(secret, store)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/agent/ws", mgr.ServeWS)
|
||||
ts := httptest.NewServer(mux)
|
||||
defer ts.Close()
|
||||
|
||||
wsURL := "ws" + ts.URL[4:] + "/agent/ws?device_name=node-test"
|
||||
header := http.Header{"Authorization": []string{"Bearer " + secret}}
|
||||
|
||||
// [DoD 1] 初次注册持久化
|
||||
t.Run("DoD 1: Register and Persist", func(t *testing.T) {
|
||||
c, _, err := websocket.DefaultDialer.Dial(wsURL, header)
|
||||
if err != nil {
|
||||
t.Fatalf("dial failed: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
prof := sysinfo.Collect("APPLICATION")
|
||||
bProf, _ := json.Marshal(prof)
|
||||
_ = bProf
|
||||
|
||||
msg := Message{
|
||||
Event: "hello",
|
||||
Device: "node-test",
|
||||
Arch: "amd64",
|
||||
OS: "linux",
|
||||
Profile: &prof,
|
||||
TS: time.Now().Unix(),
|
||||
}
|
||||
if err := c.WriteJSON(msg); err != nil {
|
||||
t.Fatalf("writeJSON failed: %v", err)
|
||||
}
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
|
||||
rows, err := store.ListDevices()
|
||||
if err != nil || len(rows) != 1 {
|
||||
t.Fatalf("expected 1 row in DB, got: %d, err: %v", len(rows), err)
|
||||
}
|
||||
if rows[0].Status != "online" || rows[0].Arch != "amd64" || rows[0].OS != "linux" {
|
||||
t.Fatalf("DB device mismatch: %+v", rows[0])
|
||||
}
|
||||
})
|
||||
|
||||
// [DoD 2] 离线状态保留
|
||||
t.Run("DoD 2: Offline Persistence on Disconnect", func(t *testing.T) {
|
||||
// 上个连接已 defer c.Close(),休眠等待触发 readLoop defer
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
|
||||
if mgr.Online("node-test") {
|
||||
t.Fatalf("Online('node-test') should be false after disconnect")
|
||||
}
|
||||
|
||||
devs := mgr.Devices()
|
||||
var target map[string]any
|
||||
for _, d := range devs {
|
||||
if d["name"] == "node-test" {
|
||||
target = d
|
||||
break
|
||||
}
|
||||
}
|
||||
if target == nil {
|
||||
t.Fatalf("device vanished from mgr.Devices() on disconnect!")
|
||||
}
|
||||
if target["status"] != "offline" {
|
||||
t.Fatalf("device status expected 'offline', got: %v", target["status"])
|
||||
}
|
||||
|
||||
rows, _ := store.ListDevices()
|
||||
if len(rows) != 1 || rows[0].Status != "offline" {
|
||||
t.Fatalf("store device status expected 'offline', got: %+v", rows)
|
||||
}
|
||||
})
|
||||
|
||||
// [DoD 3] 离线执行防护
|
||||
t.Run("DoD 3: Offline Exec Guard", func(t *testing.T) {
|
||||
_, err := mgr.Exec(context.Background(), "node-test", ExecPayload{Command: "uname -a"})
|
||||
if err == nil || err.Error() != "device offline" {
|
||||
t.Fatalf("expected 'device offline' error, got: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
// [DoD 4] 自动重连恢复在线
|
||||
t.Run("DoD 4: Reconnect Restore Online", func(t *testing.T) {
|
||||
c, _, err := websocket.DefaultDialer.Dial(wsURL, header)
|
||||
if err != nil {
|
||||
t.Fatalf("dial failed: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
prof := sysinfo.Collect("APPLICATION")
|
||||
_ = c.WriteJSON(Message{
|
||||
Event: "ping",
|
||||
Device: "node-test",
|
||||
Profile: &prof,
|
||||
TS: time.Now().Unix(),
|
||||
})
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
|
||||
if !mgr.Online("node-test") {
|
||||
t.Fatalf("expected Online('node-test') to be true after reconnect")
|
||||
}
|
||||
devs := mgr.Devices()
|
||||
for _, d := range devs {
|
||||
if d["name"] == "node-test" && d["status"] != "online" {
|
||||
t.Fatalf("expected status 'online', got: %v", d["status"])
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// [DoD 5] Hub 重启数据不丢 (从 DB 恢复)
|
||||
t.Run("DoD 5: Hub Restart Restore from DB", func(t *testing.T) {
|
||||
mgrNew := NewManager(secret, store)
|
||||
devs := mgrNew.Devices()
|
||||
var found map[string]any
|
||||
for _, d := range devs {
|
||||
if d["name"] == "node-test" {
|
||||
found = d
|
||||
break
|
||||
}
|
||||
}
|
||||
if found == nil {
|
||||
t.Fatalf("restarted Hub failed to restore device from DB")
|
||||
}
|
||||
if found["status"] != "offline" {
|
||||
t.Fatalf("restarted Hub initial device status should be offline, got: %v", found["status"])
|
||||
}
|
||||
if found["profile"] == nil {
|
||||
t.Fatalf("restarted Hub should restore profile snapshot")
|
||||
}
|
||||
})
|
||||
|
||||
// [DoD 6] 主动注销清理与黑名单
|
||||
t.Run("DoD 6: Revoke Cleanup and Blacklist", func(t *testing.T) {
|
||||
if err := mgr.RevokeDevice("node-test", "admin action"); err != nil {
|
||||
t.Fatalf("RevokeDevice failed: %v", err)
|
||||
}
|
||||
if len(mgr.Devices()) != 0 {
|
||||
t.Fatalf("expected 0 devices in mgr, got: %d", len(mgr.Devices()))
|
||||
}
|
||||
rows, _ := store.ListDevices()
|
||||
if len(rows) != 0 {
|
||||
t.Fatalf("expected 0 devices in DB, got: %d", len(rows))
|
||||
}
|
||||
revoked, _ := store.IsRevoked("node-test")
|
||||
if !revoked {
|
||||
t.Fatalf("expected device to be recorded in revoked_devices")
|
||||
}
|
||||
})
|
||||
}
|
||||
+413
-37
@@ -7,15 +7,20 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/wjyhk/vps-commander/internal/executor"
|
||||
"github.com/wjyhk/vps-commander/internal/security"
|
||||
"github.com/wjyhk/vps-commander/internal/storage"
|
||||
"github.com/wjyhk/vps-commander/internal/sysinfo"
|
||||
)
|
||||
|
||||
const deviceOfflineAfter = 70 * time.Second
|
||||
|
||||
type Manager struct {
|
||||
Secret string
|
||||
Store *storage.Store
|
||||
@@ -26,10 +31,24 @@ type Manager struct {
|
||||
type Node struct {
|
||||
Name string
|
||||
Conn *websocket.Conn
|
||||
ConnectionID string
|
||||
WriteMu sync.Mutex
|
||||
OpMu sync.RWMutex
|
||||
Pending sync.Map
|
||||
LastSeen atomic.Int64
|
||||
LastHeartbeat atomic.Int64
|
||||
Connected atomic.Bool
|
||||
LastProfile *sysinfo.Profile
|
||||
Arch string
|
||||
OS string
|
||||
IsLocal bool
|
||||
RemoteIP string
|
||||
CountryCode string
|
||||
Country string
|
||||
MCP *MCPRuntime
|
||||
ProtocolVersion string
|
||||
AgentVersion string
|
||||
Capabilities map[string]bool
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
@@ -47,8 +66,30 @@ type FileResult struct {
|
||||
EOF bool `json:"eof"`
|
||||
}
|
||||
|
||||
func NewManager(secret string) *Manager {
|
||||
return &Manager{Secret: secret, nodes: make(map[string]*Node)}
|
||||
func NewManager(secret string, store *storage.Store) *Manager {
|
||||
m := &Manager{Secret: secret, Store: store, nodes: make(map[string]*Node)}
|
||||
if store != nil {
|
||||
if records, err := store.ListDevices(); err == nil {
|
||||
for _, d := range records {
|
||||
if d.IsLocal {
|
||||
continue
|
||||
}
|
||||
n := &Node{Name: d.Name, Arch: d.Arch, OS: d.OS, MCP: NewMCPRuntime()}
|
||||
n.LastSeen.Store(d.LastSeen * int64(time.Second))
|
||||
n.LastHeartbeat.Store(d.LastHeartbeat * int64(time.Second))
|
||||
if d.ProfileJSON != "" {
|
||||
var p sysinfo.Profile
|
||||
if json.Unmarshal([]byte(d.ProfileJSON), &p) == nil {
|
||||
n.LastProfile = &p
|
||||
}
|
||||
}
|
||||
n.Connected.Store(false)
|
||||
m.nodes[d.Name] = n
|
||||
_ = store.UpdateDeviceStatus(d.Name, "offline", d.LastHeartbeat)
|
||||
}
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *Manager) SetStore(s *storage.Store) {
|
||||
@@ -61,16 +102,31 @@ func (m *Manager) ServeWS(w http.ResponseWriter, r *http.Request) {
|
||||
if len(auth) >= 7 && auth[:7] == "Bearer " {
|
||||
provided = auth[7:]
|
||||
}
|
||||
if m.Secret == "" || subtle.ConstantTimeCompare([]byte(provided), []byte(m.Secret)) != 1 {
|
||||
http.Error(w, "unauthorized", 401)
|
||||
return
|
||||
}
|
||||
name := r.URL.Query().Get("device_name")
|
||||
if name == "" {
|
||||
http.Error(w, "device_name required", 400)
|
||||
return
|
||||
}
|
||||
|
||||
if m.Store != nil {
|
||||
configured, err := m.Store.HasDeviceCredential(name)
|
||||
if err != nil {
|
||||
http.Error(w, "credential lookup failed", 500)
|
||||
return
|
||||
}
|
||||
if configured {
|
||||
valid, err := m.Store.VerifyDeviceCredential(name, provided)
|
||||
if err != nil || !valid {
|
||||
http.Error(w, "unauthorized", 401)
|
||||
return
|
||||
}
|
||||
} else if m.Secret == "" || subtle.ConstantTimeCompare([]byte(provided), []byte(m.Secret)) != 1 {
|
||||
http.Error(w, "unauthorized", 401)
|
||||
return
|
||||
}
|
||||
} else if m.Secret == "" || subtle.ConstantTimeCompare([]byte(provided), []byte(m.Secret)) != 1 {
|
||||
http.Error(w, "unauthorized", 401)
|
||||
return
|
||||
}
|
||||
if m.Store != nil {
|
||||
if revoked, _ := m.Store.IsRevoked(name); revoked {
|
||||
http.Error(w, "device has been revoked by admin", 403)
|
||||
@@ -83,15 +139,30 @@ func (m *Manager) ServeWS(w http.ResponseWriter, r *http.Request) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
n := &Node{Name: name, Conn: c}
|
||||
n.LastSeen.Store(time.Now().UnixNano())
|
||||
m.mu.Lock()
|
||||
if old := m.nodes[name]; old != nil {
|
||||
_ = old.Conn.Close()
|
||||
clientIP := ExtractIPFromRequest(r)
|
||||
cc, countryName := ResolveIP(clientIP)
|
||||
n := &Node{
|
||||
Name: name,
|
||||
Conn: c,
|
||||
ConnectionID: fmt.Sprintf("%s-%d", name, time.Now().UnixNano()),
|
||||
RemoteIP: clientIP,
|
||||
CountryCode: cc,
|
||||
Country: countryName,
|
||||
MCP: NewMCPRuntime(),
|
||||
Capabilities: make(map[string]bool),
|
||||
}
|
||||
n.LastSeen.Store(time.Now().UnixNano())
|
||||
n.LastHeartbeat.Store(time.Now().UnixNano())
|
||||
n.Connected.Store(true)
|
||||
m.mu.Lock()
|
||||
old := m.nodes[name]
|
||||
m.nodes[name] = n
|
||||
m.mu.Unlock()
|
||||
if old != nil && old.Conn != nil {
|
||||
_ = old.Conn.Close()
|
||||
}
|
||||
_ = n.write(Message{Event: "registered", Device: name, TS: time.Now().Unix()})
|
||||
m.syncMCP(n)
|
||||
go m.heartbeat(n)
|
||||
go m.readLoop(n)
|
||||
}
|
||||
@@ -107,33 +178,71 @@ func (n *Node) write(msg Message) error {
|
||||
|
||||
func (m *Manager) readLoop(n *Node) {
|
||||
defer func() {
|
||||
m.mu.Lock()
|
||||
if m.nodes[n.Name] == n {
|
||||
delete(m.nodes, n.Name)
|
||||
n.Connected.Store(false)
|
||||
conn := n.Conn
|
||||
m.mu.RLock()
|
||||
current := m.nodes[n.Name] == n
|
||||
m.mu.RUnlock()
|
||||
if conn != nil {
|
||||
_ = conn.Close()
|
||||
}
|
||||
m.mu.Unlock()
|
||||
_ = n.Conn.Close()
|
||||
n.Pending.Range(func(key, v any) bool {
|
||||
if ch, ok := v.(chan Message); ok {
|
||||
select {
|
||||
case ch <- Message{Status: "error", Error: "device disconnected"}:
|
||||
default:
|
||||
}
|
||||
n.Pending.Delete(key)
|
||||
}
|
||||
n.Pending.Delete(key)
|
||||
return true
|
||||
})
|
||||
if current && m.Store != nil {
|
||||
_ = m.Store.UpdateDeviceStatus(n.Name, "offline", n.LastHeartbeat.Load()/int64(time.Second))
|
||||
}
|
||||
}()
|
||||
_ = n.Conn.SetReadDeadline(time.Now().Add(75 * time.Second))
|
||||
for {
|
||||
var msg Message
|
||||
if err := n.Conn.ReadJSON(&msg); err != nil {
|
||||
conn := n.Conn
|
||||
if conn == nil {
|
||||
return
|
||||
}
|
||||
n.LastSeen.Store(time.Now().UnixNano())
|
||||
_ = n.Conn.SetReadDeadline(time.Now().Add(75 * time.Second))
|
||||
_ = conn.SetReadDeadline(time.Now().Add(75 * time.Second))
|
||||
for {
|
||||
var msg Message
|
||||
if err := conn.ReadJSON(&msg); err != nil {
|
||||
return
|
||||
}
|
||||
now := time.Now().UnixNano()
|
||||
n.LastSeen.Store(now)
|
||||
_ = conn.SetReadDeadline(time.Now().Add(75 * time.Second))
|
||||
if msg.Arch != "" {
|
||||
n.Arch = msg.Arch
|
||||
}
|
||||
if msg.OS != "" {
|
||||
n.OS = msg.OS
|
||||
}
|
||||
if msg.ProtocolVersion != "" {
|
||||
n.ProtocolVersion = msg.ProtocolVersion
|
||||
}
|
||||
if msg.AgentVersion != "" {
|
||||
n.AgentVersion = msg.AgentVersion
|
||||
}
|
||||
if msg.Capabilities != nil {
|
||||
n.Capabilities = make(map[string]bool, len(msg.Capabilities))
|
||||
for _, c := range msg.Capabilities {
|
||||
n.Capabilities[c] = true
|
||||
}
|
||||
}
|
||||
if msg.Profile != nil {
|
||||
n.LastProfile = msg.Profile
|
||||
n.LastHeartbeat.Store(now)
|
||||
if m.Store != nil {
|
||||
b, _ := json.Marshal(msg.Profile)
|
||||
_ = m.Store.UpsertRemote(n.Name, "online", n.Arch, n.OS, now/int64(time.Second), string(b))
|
||||
}
|
||||
} else {
|
||||
n.LastHeartbeat.Store(now)
|
||||
if m.Store != nil {
|
||||
_ = m.Store.UpdateDeviceStatus(n.Name, "online", now/int64(time.Second))
|
||||
}
|
||||
}
|
||||
if msg.Event == "pong" || msg.Event == "ping" || msg.Event == "hello" || msg.Event == "profile" {
|
||||
continue
|
||||
@@ -153,21 +262,26 @@ func (m *Manager) readLoop(n *Node) {
|
||||
|
||||
func (m *Manager) Online(name string) bool {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
n := m.nodes[name]
|
||||
return n != nil && time.Since(time.Unix(0, n.LastSeen.Load())) < 70*time.Second
|
||||
m.mu.RUnlock()
|
||||
if n == nil || !n.Connected.Load() {
|
||||
return false
|
||||
}
|
||||
return time.Since(time.Unix(0, n.LastSeen.Load())) < deviceOfflineAfter
|
||||
}
|
||||
|
||||
func (m *Manager) RevokeDevice(name, reason string) error {
|
||||
m.mu.Lock()
|
||||
n, exists := m.nodes[name]
|
||||
if exists {
|
||||
n := m.nodes[name]
|
||||
delete(m.nodes, name)
|
||||
m.mu.Unlock()
|
||||
if n != nil {
|
||||
n.Connected.Store(false)
|
||||
if n.Conn != nil {
|
||||
_ = n.write(Message{Event: "revoked", Error: "revoked by admin"})
|
||||
_ = n.Conn.Close()
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
}
|
||||
if m.Store != nil {
|
||||
return m.Store.RevokeDevice(name, reason)
|
||||
}
|
||||
@@ -179,25 +293,51 @@ func (m *Manager) Devices() []map[string]any {
|
||||
defer m.mu.RUnlock()
|
||||
out := make([]map[string]any, 0, len(m.nodes))
|
||||
for name, n := range m.nodes {
|
||||
status := "online"
|
||||
status := "offline"
|
||||
lastSeen := time.Unix(0, n.LastSeen.Load())
|
||||
if time.Since(lastSeen) >= 70*time.Second {
|
||||
status = "offline"
|
||||
if n.Connected.Load() && time.Since(lastSeen) < deviceOfflineAfter {
|
||||
status = "online"
|
||||
}
|
||||
item := map[string]any{
|
||||
"name": name,
|
||||
"status": status,
|
||||
"is_local": false,
|
||||
"last_heartbeat": lastSeen.Unix(),
|
||||
"name": name, "status": status, "is_local": n.IsLocal,
|
||||
"arch": n.Arch, "os": n.OS,
|
||||
"remote_ip": n.RemoteIP,
|
||||
"country_code": n.CountryCode,
|
||||
"country": n.Country,
|
||||
"last_heartbeat": n.LastHeartbeat.Load() / int64(time.Second),
|
||||
}
|
||||
if n.LastProfile != nil {
|
||||
item["profile"] = n.LastProfile
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
nameI := fmt.Sprintf("%v", out[i]["name"])
|
||||
nameJ := fmt.Sprintf("%v", out[j]["name"])
|
||||
return nameI < nameJ
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func operationRisk(action string) int {
|
||||
if r, ok := security.RequiredRiskForAction(action); ok {
|
||||
return r
|
||||
}
|
||||
if spec, ok := security.Lookup(action); ok {
|
||||
return spec.RequiredRisk
|
||||
}
|
||||
return security.RiskHigh
|
||||
}
|
||||
|
||||
func (n *Node) acquireOperation(action string) func() {
|
||||
if operationRisk(action) <= security.RiskLow {
|
||||
n.OpMu.RLock()
|
||||
return n.OpMu.RUnlock
|
||||
}
|
||||
n.OpMu.Lock()
|
||||
return n.OpMu.Unlock
|
||||
}
|
||||
|
||||
func (m *Manager) call(ctx context.Context, name, action string, payload any) (Message, error) {
|
||||
m.mu.RLock()
|
||||
n := m.nodes[name]
|
||||
@@ -205,6 +345,12 @@ func (m *Manager) call(ctx context.Context, name, action string, payload any) (M
|
||||
if n == nil || !m.Online(name) {
|
||||
return Message{}, errors.New("device offline")
|
||||
}
|
||||
capability := actionCapability(action)
|
||||
if capability != "" && len(n.Capabilities) > 0 && !n.Capabilities[capability] {
|
||||
return Message{}, fmt.Errorf("capability missing: %s", capability)
|
||||
}
|
||||
release := n.acquireOperation(action)
|
||||
defer release()
|
||||
id := fmt.Sprintf("task_%d", time.Now().UnixNano())
|
||||
ch := make(chan Message, 1)
|
||||
n.Pending.Store(id, ch)
|
||||
@@ -227,6 +373,90 @@ func (m *Manager) call(ctx context.Context, name, action string, payload any) (M
|
||||
}
|
||||
}
|
||||
|
||||
func actionCapability(action string) string {
|
||||
switch action {
|
||||
case "exec":
|
||||
return "exec_command"
|
||||
case "file_read":
|
||||
return "read_file"
|
||||
case "file_write":
|
||||
return "write_file"
|
||||
default:
|
||||
return action
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) StartProcess(ctx context.Context, name string, p StartProcessPayload) (map[string]any, error) {
|
||||
msg, err := m.call(ctx, name, "start_process", p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out map[string]any
|
||||
b, _ := json.Marshal(msg.Payload)
|
||||
if err := json.Unmarshal(b, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (m *Manager) ReadProcessOutput(ctx context.Context, name, sessionID, owner string) (ProcessOutputPayload, error) {
|
||||
msg, err := m.call(ctx, name, "read_process_output", map[string]string{"session_id": sessionID, "owner": owner})
|
||||
if err != nil {
|
||||
return ProcessOutputPayload{}, err
|
||||
}
|
||||
var out ProcessOutputPayload
|
||||
b, _ := json.Marshal(msg.Payload)
|
||||
if err := json.Unmarshal(b, &out); err != nil {
|
||||
return out, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (m *Manager) InteractProcess(ctx context.Context, name, sessionID, data, owner string) error {
|
||||
_, err := m.call(ctx, name, "interact_with_process", ProcessInputPayload{SessionID: sessionID, Data: data, Owner: owner})
|
||||
return err
|
||||
}
|
||||
func (m *Manager) ForceTerminate(ctx context.Context, name, sessionID, owner string) error {
|
||||
_, err := m.call(ctx, name, "force_terminate", map[string]string{"session_id": sessionID, "owner": owner})
|
||||
return err
|
||||
}
|
||||
func (m *Manager) ListSessions(ctx context.Context, name string) (any, error) {
|
||||
msg, err := m.call(ctx, name, "list_sessions", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return msg.Payload, nil
|
||||
}
|
||||
|
||||
func (m *Manager) ListDirectory(ctx context.Context, name string, p ListDirectoryPayload) ([]Entry, error) {
|
||||
msg, err := m.call(ctx, name, "list_directory", p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var v []Entry
|
||||
b, _ := json.Marshal(msg.Payload)
|
||||
err = json.Unmarshal(b, &v)
|
||||
return v, err
|
||||
}
|
||||
func (m *Manager) GetFileInfo(ctx context.Context, name string, p FileInfoPayload) (FileInfo, error) {
|
||||
msg, err := m.call(ctx, name, "get_file_info", p)
|
||||
if err != nil {
|
||||
return FileInfo{}, err
|
||||
}
|
||||
var v FileInfo
|
||||
b, _ := json.Marshal(msg.Payload)
|
||||
err = json.Unmarshal(b, &v)
|
||||
return v, err
|
||||
}
|
||||
func (m *Manager) Search(ctx context.Context, name string, p SearchPayload) ([]SearchResult, error) {
|
||||
msg, err := m.call(ctx, name, "start_search", p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var v []SearchResult
|
||||
b, _ := json.Marshal(msg.Payload)
|
||||
err = json.Unmarshal(b, &v)
|
||||
return v, err
|
||||
}
|
||||
|
||||
func (m *Manager) Exec(ctx context.Context, name string, p ExecPayload) (Result, error) {
|
||||
msg, err := m.call(ctx, name, "exec", p)
|
||||
if err != nil {
|
||||
@@ -235,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
|
||||
}
|
||||
|
||||
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) {
|
||||
msg, err := m.call(ctx, name, "file_read", p)
|
||||
if err != nil {
|
||||
@@ -248,6 +491,41 @@ func (m *Manager) ReadFile(ctx context.Context, name string, p FileReadPayload)
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (m *Manager) EditBlock(ctx context.Context, name string, p EditBlockPayload) (EditBlockResult, error) {
|
||||
msg, err := m.call(ctx, name, "edit_block", p)
|
||||
if err != nil {
|
||||
return EditBlockResult{}, err
|
||||
}
|
||||
var v EditBlockResult
|
||||
b, _ := json.Marshal(msg.Payload)
|
||||
if err := json.Unmarshal(b, &v); err != nil {
|
||||
return EditBlockResult{}, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (m *Manager) ReadMultipleFiles(ctx context.Context, name string, p ReadMultipleFilesPayload) (any, error) {
|
||||
msg, err := m.call(ctx, name, "read_multiple_files", p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return msg.Payload, nil
|
||||
}
|
||||
func (m *Manager) CreateDirectory(ctx context.Context, name string, p CreateDirectoryPayload) error {
|
||||
_, err := m.call(ctx, name, "create_directory", p)
|
||||
return err
|
||||
}
|
||||
func (m *Manager) MoveFile(ctx context.Context, name string, p MoveFilePayload) error {
|
||||
_, err := m.call(ctx, name, "move_file", p)
|
||||
return err
|
||||
}
|
||||
func (m *Manager) ListProcesses(ctx context.Context, name string) (any, error) {
|
||||
msg, err := m.call(ctx, name, "list_processes", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return msg.Payload, nil
|
||||
}
|
||||
func (m *Manager) WriteFile(ctx context.Context, name string, p FileWritePayload) (int64, error) {
|
||||
msg, err := m.call(ctx, name, "file_write", p)
|
||||
if err != nil {
|
||||
@@ -263,6 +541,104 @@ func (m *Manager) WriteFile(ctx context.Context, name string, p FileWritePayload
|
||||
return v.Bytes, nil
|
||||
}
|
||||
|
||||
func (m *Manager) syncMCP(n *Node) {
|
||||
if n == nil || n.MCP == nil || m.Store == nil {
|
||||
return
|
||||
}
|
||||
stored, err := m.Store.ListMCPServicesForNode(n.Name)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
services := make([]MCPService, 0, len(stored))
|
||||
for _, v := range stored {
|
||||
services = append(services, decodeStoredMCPService(v))
|
||||
}
|
||||
_ = n.write(Message{Event: "mcp_sync", Payload: services, TS: time.Now().Unix()})
|
||||
}
|
||||
|
||||
func decodeStoredMCPService(v storage.MCPService) MCPService {
|
||||
out := MCPService{ID: v.ID, Name: v.Name, Description: v.Description, Transport: v.Transport, Command: v.Command, URL: v.URL}
|
||||
_ = json.Unmarshal([]byte(v.ArgsJSON), &out.Args)
|
||||
_ = json.Unmarshal([]byte(v.EnvJSON), &out.Env)
|
||||
_ = json.Unmarshal([]byte(v.HeadersJSON), &out.Headers)
|
||||
return out
|
||||
}
|
||||
|
||||
func (m *Manager) SyncMCPServices() {
|
||||
m.mu.RLock()
|
||||
nodes := make([]*Node, 0, len(m.nodes))
|
||||
for _, n := range m.nodes {
|
||||
nodes = append(nodes, n)
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
for _, n := range nodes {
|
||||
if n.Connected.Load() {
|
||||
m.syncMCP(n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) ListMCP(name string) ([]MCPService, error) {
|
||||
m.mu.RLock()
|
||||
n := m.nodes[name]
|
||||
m.mu.RUnlock()
|
||||
if n == nil || !m.Online(name) {
|
||||
return nil, fmt.Errorf("device %s is offline", name)
|
||||
}
|
||||
msg, err := m.call(context.Background(), name, "mcp_list", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []MCPService
|
||||
b, _ := json.Marshal(msg.Payload)
|
||||
if err := json.Unmarshal(b, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n.MCP == nil {
|
||||
n.MCP = NewMCPRuntime()
|
||||
}
|
||||
n.MCP.Sync(out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *Manager) CallMCP(ctx context.Context, name, server, tool string, args any) (MCPCallResult, error) {
|
||||
m.mu.RLock()
|
||||
n := m.nodes[name]
|
||||
m.mu.RUnlock()
|
||||
if n == nil || !m.Online(name) {
|
||||
return MCPCallResult{}, fmt.Errorf("device %s is offline", name)
|
||||
}
|
||||
msg, err := m.call(ctx, name, "mcp_call", map[string]any{"server": server, "tool": tool, "args": args})
|
||||
if err != nil {
|
||||
return MCPCallResult{}, err
|
||||
}
|
||||
var out MCPCallResult
|
||||
b, _ := json.Marshal(msg.Payload)
|
||||
if err := json.Unmarshal(b, &out); err != nil {
|
||||
return MCPCallResult{}, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *Manager) TestMCP(ctx context.Context, name string, service MCPService) ([]map[string]any, error) {
|
||||
m.mu.RLock()
|
||||
n := m.nodes[name]
|
||||
m.mu.RUnlock()
|
||||
if n == nil || !m.Online(name) {
|
||||
return nil, fmt.Errorf("device %s is offline", name)
|
||||
}
|
||||
msg, err := m.call(ctx, name, "mcp_test", service)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []map[string]any
|
||||
b, _ := json.Marshal(msg.Payload)
|
||||
if err := json.Unmarshal(b, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *Manager) heartbeat(n *Node) {
|
||||
t := time.NewTicker(30 * time.Second)
|
||||
defer t.Stop()
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNodeOperationGateAllowsReadsAndSerializesWrites(t *testing.T) {
|
||||
n := &Node{}
|
||||
release1 := n.acquireOperation("file_read")
|
||||
done := make(chan struct{})
|
||||
go func() { release2 := n.acquireOperation("edit_block"); close(done); release2() }()
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("write entered while read active")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
release1()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("write did not proceed")
|
||||
}
|
||||
}
|
||||
func TestNodeOperationGateAllowsConcurrentReads(t *testing.T) {
|
||||
n := &Node{}
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
for i := 0; i < 2; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
release := n.acquireOperation("file_read")
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
release()
|
||||
}()
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() { wg.Wait(); close(done) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("reads did not complete")
|
||||
}
|
||||
}
|
||||
func TestOperationRiskUnknownFailsClosed(t *testing.T) {
|
||||
if operationRisk("unknown-danger") != 3 {
|
||||
t.Fatal("unknown action must be high risk")
|
||||
}
|
||||
_ = context.Background()
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type MCPService struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Transport string `json:"transport"`
|
||||
Command string `json:"command,omitempty"`
|
||||
Args []string `json:"args,omitempty"`
|
||||
Env map[string]string `json:"env,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
}
|
||||
|
||||
type MCPCallResult struct {
|
||||
Server string `json:"server"`
|
||||
Tool string `json:"tool"`
|
||||
Result any `json:"result,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
DurationMS int64 `json:"duration_ms"`
|
||||
}
|
||||
|
||||
type mcpRPC struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID any `json:"id,omitempty"`
|
||||
Method string `json:"method"`
|
||||
Params any `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
type mcpRPCResponse struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID any `json:"id,omitempty"`
|
||||
Result json.RawMessage `json:"result,omitempty"`
|
||||
Error *struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data any `json:"data,omitempty"`
|
||||
} `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type MCPRuntime struct {
|
||||
mu sync.RWMutex
|
||||
services map[string]MCPService
|
||||
}
|
||||
|
||||
func NewMCPRuntime() *MCPRuntime { return &MCPRuntime{services: make(map[string]MCPService)} }
|
||||
|
||||
func (r *MCPRuntime) Sync(services []MCPService) {
|
||||
next := make(map[string]MCPService, len(services))
|
||||
for _, s := range services {
|
||||
if s.ID == "" || s.Transport == "" {
|
||||
continue
|
||||
}
|
||||
next[s.ID] = s
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.services = next
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
func (r *MCPRuntime) List() []MCPService {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
out := make([]MCPService, 0, len(r.services))
|
||||
for _, s := range r.services {
|
||||
out = append(out, s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *MCPRuntime) Get(id string) (MCPService, bool) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
s, ok := r.services[id]
|
||||
return s, ok
|
||||
}
|
||||
|
||||
func (r *MCPRuntime) Call(ctx context.Context, server, tool string, args any) (any, error) {
|
||||
s, ok := r.Get(server)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("MCP service %q is not mounted", server)
|
||||
}
|
||||
switch strings.ToLower(s.Transport) {
|
||||
case "stdio":
|
||||
return callStdio(ctx, s, tool, args)
|
||||
case "http", "sse":
|
||||
return callHTTP(ctx, s, tool, args)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported MCP transport %q", s.Transport)
|
||||
}
|
||||
}
|
||||
|
||||
func ProbeMCP(ctx context.Context, s MCPService) ([]map[string]any, error) {
|
||||
switch strings.ToLower(s.Transport) {
|
||||
case "stdio":
|
||||
return probeStdio(ctx, s)
|
||||
case "http", "sse":
|
||||
return probeHTTP(ctx, s)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported MCP transport %q", s.Transport)
|
||||
}
|
||||
}
|
||||
|
||||
func probeStdio(ctx context.Context, s MCPService) ([]map[string]any, error) {
|
||||
if s.Command == "" {
|
||||
return nil, errors.New("MCP stdio command is empty")
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, s.Command, s.Args...)
|
||||
if len(s.Env) > 0 {
|
||||
cmd.Env = append(os.Environ(), envList(s.Env)...)
|
||||
}
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cmd.Stderr = io.Discard
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }()
|
||||
enc := json.NewEncoder(stdin)
|
||||
dec := bufio.NewReaderSize(stdout, 64*1024)
|
||||
if err := enc.Encode(mcpRPC{JSONRPC: "2.0", ID: int64(1), Method: "initialize", Params: map[string]any{
|
||||
"protocolVersion": "2024-11-05", "capabilities": map[string]any{},
|
||||
"clientInfo": map[string]string{"name": "vps-commander-probe", "version": "1.0"},
|
||||
}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := readRPC(ctx, dec, 1); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := enc.Encode(mcpRPC{JSONRPC: "2.0", Method: "notifications/initialized", Params: map[string]any{}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := enc.Encode(mcpRPC{JSONRPC: "2.0", ID: int64(2), Method: "tools/list", Params: map[string]any{}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out, err := readRPC(ctx, dec, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return extractMCPTools(out)
|
||||
}
|
||||
|
||||
func probeHTTP(ctx context.Context, s MCPService) ([]map[string]any, error) {
|
||||
if s.URL == "" {
|
||||
return nil, errors.New("MCP HTTP URL is empty")
|
||||
}
|
||||
client := &http.Client{Timeout: 0}
|
||||
var session string
|
||||
post := func(req mcpRPC) (any, error) {
|
||||
b, _ := json.Marshal(req)
|
||||
hr, err := http.NewRequestWithContext(ctx, http.MethodPost, s.URL, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hr.Header.Set("Content-Type", "application/json")
|
||||
hr.Header.Set("Accept", "application/json, text/event-stream")
|
||||
for k, v := range s.Headers {
|
||||
hr.Header.Set(k, v)
|
||||
}
|
||||
if session != "" {
|
||||
hr.Header.Set("Mcp-Session-Id", session)
|
||||
}
|
||||
resp, err := client.Do(hr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("MCP HTTP status %s", resp.Status)
|
||||
}
|
||||
if v := resp.Header.Get("Mcp-Session-Id"); v != "" {
|
||||
session = v
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 4*1024*1024))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(bytes.TrimSpace(data)) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if bytes.Contains(data, []byte("event:")) {
|
||||
data = parseSSEData(data)
|
||||
}
|
||||
var rr mcpRPCResponse
|
||||
if err := json.Unmarshal(bytes.TrimSpace(data), &rr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rr.Error != nil {
|
||||
return nil, fmt.Errorf("MCP error %d: %s", rr.Error.Code, rr.Error.Message)
|
||||
}
|
||||
var out any
|
||||
if len(rr.Result) > 0 {
|
||||
if err := json.Unmarshal(rr.Result, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
if strings.EqualFold(s.Transport, "sse") {
|
||||
endpoint, err := discoverSSEEndpoint(ctx, s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.URL = endpoint
|
||||
}
|
||||
if _, err := post(mcpRPC{JSONRPC: "2.0", ID: int64(1), Method: "initialize", Params: map[string]any{
|
||||
"protocolVersion": "2024-11-05", "capabilities": map[string]any{},
|
||||
"clientInfo": map[string]string{"name": "vps-commander-probe", "version": "1.0"},
|
||||
}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := post(mcpRPC{JSONRPC: "2.0", Method: "notifications/initialized", Params: map[string]any{}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out, err := post(mcpRPC{JSONRPC: "2.0", ID: int64(2), Method: "tools/list", Params: map[string]any{}})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return extractMCPTools(out)
|
||||
}
|
||||
|
||||
func extractMCPTools(v any) ([]map[string]any, error) {
|
||||
obj, ok := v.(map[string]any)
|
||||
if !ok {
|
||||
return nil, errors.New("invalid tools/list response")
|
||||
}
|
||||
raw, ok := obj["tools"].([]any)
|
||||
if !ok {
|
||||
return []map[string]any{}, nil
|
||||
}
|
||||
out := make([]map[string]any, 0, len(raw))
|
||||
for _, item := range raw {
|
||||
if m, ok := item.(map[string]any); ok {
|
||||
tool := map[string]any{"name": m["name"], "description": m["description"]}
|
||||
out = append(out, tool)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func callStdio(ctx context.Context, s MCPService, tool string, args any) (any, error) {
|
||||
if s.Command == "" {
|
||||
return nil, errors.New("MCP stdio command is empty")
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, s.Command, s.Args...)
|
||||
if len(s.Env) > 0 {
|
||||
cmd.Env = append(os.Environ(), envList(s.Env)...)
|
||||
}
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cmd.Stderr = io.Discard
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }()
|
||||
|
||||
enc := json.NewEncoder(stdin)
|
||||
dec := bufio.NewReaderSize(stdout, 64*1024)
|
||||
id := int64(1)
|
||||
if err := enc.Encode(mcpRPC{JSONRPC: "2.0", ID: id, Method: "initialize", Params: map[string]any{
|
||||
"protocolVersion": "2024-11-05", "capabilities": map[string]any{},
|
||||
"clientInfo": map[string]string{"name": "vps-commander-agent", "version": "1.0"},
|
||||
}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := readRPC(ctx, dec, id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := enc.Encode(mcpRPC{JSONRPC: "2.0", Method: "notifications/initialized", Params: map[string]any{}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id++
|
||||
if err := enc.Encode(mcpRPC{JSONRPC: "2.0", ID: id, Method: "tools/call", Params: map[string]any{"name": tool, "arguments": args}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return readRPC(ctx, dec, id)
|
||||
}
|
||||
|
||||
func readRPC(ctx context.Context, r *bufio.Reader, wantID int64) (any, error) {
|
||||
for {
|
||||
lineCh := make(chan []byte, 1)
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
b, err := r.ReadBytes('\n')
|
||||
if err != nil && len(b) == 0 {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
lineCh <- bytes.TrimSpace(b)
|
||||
}()
|
||||
var line []byte
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case err := <-errCh:
|
||||
return nil, err
|
||||
case line = <-lineCh:
|
||||
}
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
var resp mcpRPCResponse
|
||||
if json.Unmarshal(line, &resp) != nil {
|
||||
continue
|
||||
}
|
||||
if resp.ID == nil {
|
||||
continue
|
||||
}
|
||||
if n, ok := resp.ID.(float64); !ok || int64(n) != wantID {
|
||||
continue
|
||||
}
|
||||
if resp.Error != nil {
|
||||
return nil, fmt.Errorf("MCP error %d: %s", resp.Error.Code, resp.Error.Message)
|
||||
}
|
||||
var out any
|
||||
if len(resp.Result) > 0 {
|
||||
if err := json.Unmarshal(resp.Result, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
|
||||
func callHTTP(ctx context.Context, s MCPService, tool string, args any) (any, error) {
|
||||
if s.URL == "" {
|
||||
return nil, errors.New("MCP HTTP URL is empty")
|
||||
}
|
||||
client := &http.Client{Timeout: 0}
|
||||
var session string
|
||||
post := func(req mcpRPC) (any, http.Header, error) {
|
||||
b, _ := json.Marshal(req)
|
||||
h := make(http.Header)
|
||||
h.Set("Content-Type", "application/json")
|
||||
h.Set("Accept", "application/json, text/event-stream")
|
||||
for k, v := range s.Headers {
|
||||
h.Set(k, v)
|
||||
}
|
||||
if session != "" {
|
||||
h.Set("Mcp-Session-Id", session)
|
||||
}
|
||||
hr, err := http.NewRequestWithContext(ctx, http.MethodPost, s.URL, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
hr.Header = h
|
||||
resp, err := client.Do(hr)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, resp.Header, fmt.Errorf("MCP HTTP status %s", resp.Status)
|
||||
}
|
||||
if v := resp.Header.Get("Mcp-Session-Id"); v != "" {
|
||||
session = v
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 4*1024*1024))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(bytes.TrimSpace(data)) == 0 {
|
||||
return nil, resp.Header, nil
|
||||
}
|
||||
if bytes.Contains(data, []byte("event:")) {
|
||||
data = parseSSEData(data)
|
||||
}
|
||||
var rr mcpRPCResponse
|
||||
if err := json.Unmarshal(bytes.TrimSpace(data), &rr); err != nil {
|
||||
return nil, resp.Header, err
|
||||
}
|
||||
if rr.Error != nil {
|
||||
return nil, resp.Header, fmt.Errorf("MCP error %d: %s", rr.Error.Code, rr.Error.Message)
|
||||
}
|
||||
var out any
|
||||
if len(rr.Result) > 0 {
|
||||
if err := json.Unmarshal(rr.Result, &out); err != nil {
|
||||
return nil, resp.Header, err
|
||||
}
|
||||
}
|
||||
return out, resp.Header, nil
|
||||
}
|
||||
if strings.EqualFold(s.Transport, "sse") {
|
||||
endpoint, err := discoverSSEEndpoint(ctx, s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
old := s.URL
|
||||
s.URL = endpoint
|
||||
defer func() { s.URL = old }()
|
||||
}
|
||||
if _, _, err := post(mcpRPC{JSONRPC: "2.0", ID: int64(1), Method: "initialize", Params: map[string]any{"protocolVersion": "2024-11-05", "capabilities": map[string]any{}, "clientInfo": map[string]string{"name": "vps-commander-agent", "version": "1.0"}}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, _, err := post(mcpRPC{JSONRPC: "2.0", Method: "notifications/initialized", Params: map[string]any{}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return func() (any, error) {
|
||||
v, _, err := post(mcpRPC{JSONRPC: "2.0", ID: int64(2), Method: "tools/call", Params: map[string]any{"name": tool, "arguments": args}})
|
||||
return v, err
|
||||
}()
|
||||
}
|
||||
|
||||
func discoverSSEEndpoint(ctx context.Context, s MCPService) (string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.URL, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for k, v := range s.Headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("MCP SSE status %s", resp.Status)
|
||||
}
|
||||
sc := bufio.NewScanner(io.LimitReader(resp.Body, 256*1024))
|
||||
isEndpoint := false
|
||||
for sc.Scan() {
|
||||
line := sc.Text()
|
||||
if strings.HasPrefix(line, "event:") {
|
||||
isEndpoint = strings.TrimSpace(strings.TrimPrefix(line, "event:")) == "endpoint"
|
||||
continue
|
||||
}
|
||||
if isEndpoint && strings.HasPrefix(line, "data:") {
|
||||
u := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
|
||||
if strings.HasPrefix(u, "/") {
|
||||
base := *resp.Request.URL
|
||||
base.Path = u
|
||||
base.RawQuery = ""
|
||||
return base.String(), nil
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
}
|
||||
return "", errors.New("MCP SSE endpoint event not received")
|
||||
}
|
||||
|
||||
func parseSSEData(b []byte) []byte {
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
if strings.HasPrefix(line, "data:") {
|
||||
return []byte(strings.TrimSpace(strings.TrimPrefix(line, "data:")))
|
||||
}
|
||||
}
|
||||
return b
|
||||
}
|
||||
func envList(m map[string]string) []string {
|
||||
out := make([]string, 0, len(m))
|
||||
for k, v := range m {
|
||||
out = append(out, k+"="+v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMCPRuntimeStdioOnDemand(t *testing.T) {
|
||||
if _, err := exec.LookPath("python3"); err != nil {
|
||||
t.Skip("python3 unavailable")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
script := dir + "/mcp.py"
|
||||
code := `import json,sys
|
||||
for line in sys.stdin:
|
||||
r=json.loads(line)
|
||||
if r.get("method")=="initialize":
|
||||
print(json.dumps({"jsonrpc":"2.0","id":r["id"],"result":{"protocolVersion":"2024-11-05"}}),flush=True)
|
||||
elif r.get("method")=="tools/call":
|
||||
a=r.get("params",{}).get("arguments",{})
|
||||
print(json.dumps({"jsonrpc":"2.0","id":r["id"],"result":{"content":[{"type":"text","text":"hello "+a.get("name","")}]}}),flush=True)
|
||||
`
|
||||
if err := os.WriteFile(script, []byte(code), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := NewMCPRuntime()
|
||||
r.Sync([]MCPService{{ID: "test", Transport: "stdio", Command: "python3", Args: []string{script}}})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
v, err := r.Call(ctx, "test", "hello", map[string]any{"name": "vpc"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := json.Marshal(v)
|
||||
if string(b) == "" {
|
||||
t.Fatal("empty result")
|
||||
}
|
||||
if !contains(string(b), "hello vpc") {
|
||||
t.Fatalf("unexpected %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPRuntimeHTTP(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
var q mcpRPC
|
||||
_ = json.Unmarshal(b, &q)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%s,"result":{"ok":true}}`, jsonID(q.ID))
|
||||
}))
|
||||
defer ts.Close()
|
||||
r := NewMCPRuntime()
|
||||
r.Sync([]MCPService{{ID: "http", Transport: "http", URL: ts.URL}})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
v, err := r.Call(ctx, "http", "ping", map[string]any{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !contains(fmt.Sprint(v), "true") {
|
||||
t.Fatalf("unexpected %v", v)
|
||||
}
|
||||
}
|
||||
func jsonID(v any) string { b, _ := json.Marshal(v); return string(b) }
|
||||
func contains(s, x string) bool {
|
||||
for i := 0; i+len(x) <= len(s); i++ {
|
||||
if s[i:i+len(x)] == x {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -6,7 +6,10 @@ type Message struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Event string `json:"event,omitempty"`
|
||||
Action string `json:"action,omitempty"`
|
||||
SubAction string `json:"sub_action,omitempty"`
|
||||
Device string `json:"device,omitempty"`
|
||||
Arch string `json:"arch,omitempty"`
|
||||
OS string `json:"os,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Payload any `json:"payload,omitempty"`
|
||||
Profile *sysinfo.Profile `json:"profile,omitempty"`
|
||||
@@ -16,6 +19,9 @@ type Message struct {
|
||||
DurationMS int64 `json:"duration_ms,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
TS int64 `json:"ts,omitempty"`
|
||||
ProtocolVersion string `json:"protocol_version,omitempty"`
|
||||
AgentVersion string `json:"agent_version,omitempty"`
|
||||
Capabilities []string `json:"capabilities,omitempty"`
|
||||
}
|
||||
|
||||
type ExecPayload struct {
|
||||
@@ -34,3 +40,80 @@ type FileWritePayload struct {
|
||||
Path string `json:"path"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
type EditBlockPayload struct {
|
||||
Path string `json:"path"`
|
||||
OldText string `json:"old_text"`
|
||||
NewText string `json:"new_text"`
|
||||
ExpectedHash string `json:"expected_hash,omitempty"`
|
||||
}
|
||||
|
||||
type EditBlockResult struct {
|
||||
BytesWritten int64 `json:"bytes_written"`
|
||||
}
|
||||
|
||||
type StartProcessPayload struct {
|
||||
Command string `json:"command"`
|
||||
Workdir string `json:"workdir,omitempty"`
|
||||
SessionID string `json:"session_id"`
|
||||
Owner string `json:"owner,omitempty"`
|
||||
RingCapacity int `json:"ring_capacity,omitempty"`
|
||||
}
|
||||
type ProcessInputPayload struct {
|
||||
SessionID string `json:"session_id"`
|
||||
Data string `json:"data"`
|
||||
Owner string `json:"owner"`
|
||||
}
|
||||
type ProcessOutputPayload struct {
|
||||
SessionID string `json:"session_id"`
|
||||
Stdout string `json:"stdout"`
|
||||
Stderr string `json:"stderr"`
|
||||
ExitCode int `json:"exit_code"`
|
||||
Running bool `json:"running"`
|
||||
}
|
||||
|
||||
type ListDirectoryPayload struct {
|
||||
Path string `json:"path"`
|
||||
Recursive bool `json:"recursive,omitempty"`
|
||||
MaxEntries int `json:"max_entries,omitempty"`
|
||||
}
|
||||
type FileInfoPayload struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
type ReadMultipleFilesPayload struct {
|
||||
Paths []string `json:"paths"`
|
||||
Limit int64 `json:"limit,omitempty"`
|
||||
}
|
||||
type CreateDirectoryPayload struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
type MoveFilePayload struct {
|
||||
Source string `json:"source"`
|
||||
Destination string `json:"destination"`
|
||||
}
|
||||
type SearchPayload struct {
|
||||
Root string `json:"root"`
|
||||
Query string `json:"query"`
|
||||
MaxResults int `json:"max_results,omitempty"`
|
||||
}
|
||||
|
||||
type Entry struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
IsDir bool `json:"is_dir"`
|
||||
Size int64 `json:"size"`
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
type FileInfo struct {
|
||||
Path string `json:"path"`
|
||||
Name string `json:"name"`
|
||||
IsDir bool `json:"is_dir"`
|
||||
Size int64 `json:"size"`
|
||||
Mode string `json:"mode"`
|
||||
ModTime int64 `json:"mod_time"`
|
||||
}
|
||||
type SearchResult struct {
|
||||
Path string `json:"path"`
|
||||
Line int `json:"line,omitempty"`
|
||||
Text string `json:"text,omitempty"`
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package executor
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var ErrBlockNotUnique = errors.New("old_text must occur exactly once")
|
||||
var ErrEditConflict = errors.New("file changed during edit")
|
||||
|
||||
var editMu sync.Mutex
|
||||
|
||||
type EditBlockResult struct {
|
||||
BytesWritten int64
|
||||
}
|
||||
|
||||
func EditBlock(path, oldText, newText string, expectedHash ...string) (EditBlockResult, error) {
|
||||
editMu.Lock()
|
||||
defer editMu.Unlock()
|
||||
|
||||
if path == "" {
|
||||
return EditBlockResult{}, errors.New("path required")
|
||||
}
|
||||
if oldText == "" {
|
||||
return EditBlockResult{}, errors.New("old_text required")
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return EditBlockResult{}, err
|
||||
}
|
||||
initial := sha256.Sum256(data)
|
||||
initialHash := hex.EncodeToString(initial[:])
|
||||
if len(expectedHash) > 0 && expectedHash[0] != "" && expectedHash[0] != initialHash {
|
||||
return EditBlockResult{}, ErrEditConflict
|
||||
}
|
||||
|
||||
src := string(data)
|
||||
count := countNonOverlapping(src, oldText)
|
||||
if count != 1 {
|
||||
if count == 0 {
|
||||
return EditBlockResult{}, fmt.Errorf("%w: found 0 matches", ErrBlockNotUnique)
|
||||
}
|
||||
return EditBlockResult{}, fmt.Errorf("%w: found %d matches", ErrBlockNotUnique, count)
|
||||
}
|
||||
updated := replaceOnce(src, oldText, newText)
|
||||
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return EditBlockResult{}, err
|
||||
}
|
||||
|
||||
// Re-read immediately before commit. This is the CAS check against
|
||||
// writers outside this process; editMu serializes our own writers.
|
||||
latest, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return EditBlockResult{}, err
|
||||
}
|
||||
latestSum := sha256.Sum256(latest)
|
||||
if hex.EncodeToString(latestSum[:]) != initialHash {
|
||||
return EditBlockResult{}, ErrEditConflict
|
||||
}
|
||||
|
||||
dir := filepath.Dir(path)
|
||||
tmp, err := os.CreateTemp(dir, ".vps-commander-edit-*")
|
||||
if err != nil {
|
||||
return EditBlockResult{}, err
|
||||
}
|
||||
tmpName := tmp.Name()
|
||||
defer os.Remove(tmpName)
|
||||
if err := tmp.Chmod(info.Mode().Perm()); err != nil {
|
||||
_ = tmp.Close()
|
||||
return EditBlockResult{}, err
|
||||
}
|
||||
if _, err := tmp.WriteString(updated); err != nil {
|
||||
_ = tmp.Close()
|
||||
return EditBlockResult{}, err
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
_ = tmp.Close()
|
||||
return EditBlockResult{}, err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return EditBlockResult{}, err
|
||||
}
|
||||
if err := os.Rename(tmpName, path); err != nil {
|
||||
return EditBlockResult{}, err
|
||||
}
|
||||
if d, err := os.Open(dir); err == nil {
|
||||
_ = d.Sync()
|
||||
_ = d.Close()
|
||||
}
|
||||
return EditBlockResult{BytesWritten: int64(len(updated))}, nil
|
||||
}
|
||||
|
||||
func countNonOverlapping(src, old string) int {
|
||||
n, count := 0, 0
|
||||
for {
|
||||
i := indexString(src[n:], old)
|
||||
if i < 0 {
|
||||
return count
|
||||
}
|
||||
count++
|
||||
n += i + len(old)
|
||||
if n > len(src) {
|
||||
return count
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func replaceOnce(src, old, new string) string {
|
||||
i := indexString(src, old)
|
||||
return src[:i] + new + src[i+len(old):]
|
||||
}
|
||||
|
||||
func indexString(src, needle string) int {
|
||||
if len(needle) == 0 {
|
||||
return 0
|
||||
}
|
||||
for i := 0; i+len(needle) <= len(src); i++ {
|
||||
if src[i:i+len(needle)] == needle {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package executor
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEditBlockUniqueAndAtomic(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.txt")
|
||||
if err := os.WriteFile(path, []byte("a\nTARGET\nz\n"), 0640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, err := EditBlock(path, "TARGET", "CHANGED")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.BytesWritten != int64(len("a\nCHANGED\nz\n")) {
|
||||
t.Fatalf("bytes=%d", res.BytesWritten)
|
||||
}
|
||||
got, _ := os.ReadFile(path)
|
||||
if string(got) != "a\nCHANGED\nz\n" {
|
||||
t.Fatalf("content=%q", got)
|
||||
}
|
||||
info, _ := os.Stat(path)
|
||||
if info.Mode().Perm() != 0640 {
|
||||
t.Fatalf("mode=%o, want 0640", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditBlockRejectsZeroAndMultipleMatchesWithoutMutation(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.txt")
|
||||
original := "TARGET\nother\nTARGET\n"
|
||||
if err := os.WriteFile(path, []byte(original), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err := EditBlock(path, "MISSING", "x")
|
||||
if !errors.Is(err, ErrBlockNotUnique) {
|
||||
t.Fatalf("missing match error=%v", err)
|
||||
}
|
||||
_, err = EditBlock(path, "TARGET", "x")
|
||||
if !errors.Is(err, ErrBlockNotUnique) {
|
||||
t.Fatalf("multiple match error=%v", err)
|
||||
}
|
||||
got, _ := os.ReadFile(path)
|
||||
if string(got) != original {
|
||||
t.Fatalf("file mutated after rejected edit: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package executor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Entry struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
IsDir bool `json:"is_dir"`
|
||||
Size int64 `json:"size"`
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
|
||||
type FileInfo struct {
|
||||
Path string `json:"path"`
|
||||
Name string `json:"name"`
|
||||
IsDir bool `json:"is_dir"`
|
||||
Size int64 `json:"size"`
|
||||
Mode string `json:"mode"`
|
||||
ModTime int64 `json:"mod_time"`
|
||||
}
|
||||
|
||||
type SearchResult struct {
|
||||
Path string `json:"path"`
|
||||
Line int `json:"line,omitempty"`
|
||||
Text string `json:"text,omitempty"`
|
||||
}
|
||||
|
||||
func ListDirectory(path string, recursive bool, maxEntries int) ([]Entry, error) {
|
||||
if path == "" {
|
||||
return nil, errors.New("path required")
|
||||
}
|
||||
if maxEntries <= 0 || maxEntries > 10000 {
|
||||
maxEntries = 1000
|
||||
}
|
||||
out := make([]Entry, 0, maxEntries)
|
||||
add := func(p string, d os.DirEntry) error {
|
||||
if len(out) >= maxEntries {
|
||||
return nil
|
||||
}
|
||||
info, err := d.Info()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out = append(out, Entry{Name: d.Name(), Path: p, IsDir: d.IsDir(), Size: info.Size(), Mode: info.Mode().String()})
|
||||
return nil
|
||||
}
|
||||
if !recursive {
|
||||
ds, err := os.ReadDir(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, d := range ds {
|
||||
if err := add(filepath.Join(path, d.Name()), d); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
err := filepath.WalkDir(path, func(p string, d os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if p == path {
|
||||
return nil
|
||||
}
|
||||
if len(out) >= maxEntries {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return add(p, d)
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
|
||||
func GetFileInfo(path string) (FileInfo, error) {
|
||||
if path == "" {
|
||||
return FileInfo{}, errors.New("path required")
|
||||
}
|
||||
i, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return FileInfo{}, err
|
||||
}
|
||||
return FileInfo{Path: path, Name: i.Name(), IsDir: i.IsDir(), Size: i.Size(), Mode: i.Mode().String(), ModTime: i.ModTime().Unix()}, nil
|
||||
}
|
||||
|
||||
func Search(ctx context.Context, root, query string, maxResults int) ([]SearchResult, error) {
|
||||
if root == "" || query == "" {
|
||||
return nil, errors.New("root and query required")
|
||||
}
|
||||
if maxResults <= 0 || maxResults > 1000 {
|
||||
maxResults = 100
|
||||
}
|
||||
out := make([]SearchResult, 0, maxResults)
|
||||
err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(out) >= maxResults {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
if d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
if d.Type()&os.ModeSymlink != 0 {
|
||||
return nil
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if strings.Contains(string(b), query) {
|
||||
for n, line := range strings.Split(string(b), "\n") {
|
||||
if strings.Contains(line, query) {
|
||||
out = append(out, SearchResult{Path: path, Line: n + 1, Text: line})
|
||||
if len(out) >= maxResults {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path })
|
||||
return out, err
|
||||
}
|
||||
|
||||
type FileReadItem struct {
|
||||
Path string `json:"path"`
|
||||
Content string `json:"content,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
type ProcessInfo struct {
|
||||
PID int `json:"pid"`
|
||||
Command string `json:"command"`
|
||||
CPU string `json:"cpu,omitempty"`
|
||||
MemoryKB uint64 `json:"memory_kb,omitempty"`
|
||||
}
|
||||
|
||||
func ReadMultipleFiles(paths []string, limit int64) []FileReadItem {
|
||||
if limit <= 0 || limit > 1024*1024 {
|
||||
limit = 256 * 1024
|
||||
}
|
||||
out := make([]FileReadItem, 0, len(paths))
|
||||
for _, p := range paths {
|
||||
v := FileReadItem{Path: p}
|
||||
b, e := os.ReadFile(p)
|
||||
if e != nil {
|
||||
v.Error = e.Error()
|
||||
} else {
|
||||
if int64(len(b)) > limit {
|
||||
b = b[:limit]
|
||||
}
|
||||
v.Content = string(b)
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
func CreateDirectory(path string) error {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return errors.New("path required")
|
||||
}
|
||||
return os.MkdirAll(path, 0755)
|
||||
}
|
||||
func MoveFile(src, dst string) error {
|
||||
if src == "" || dst == "" {
|
||||
return errors.New("source and destination required")
|
||||
}
|
||||
return os.Rename(src, dst)
|
||||
}
|
||||
func ListProcesses() ([]ProcessInfo, error) {
|
||||
ents, e := os.ReadDir("/proc")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out := make([]ProcessInfo, 0)
|
||||
for _, ent := range ents {
|
||||
if !ent.IsDir() {
|
||||
continue
|
||||
}
|
||||
pid, e := strconv.Atoi(ent.Name())
|
||||
if e != nil {
|
||||
continue
|
||||
}
|
||||
comm, _ := os.ReadFile(filepath.Join("/proc", ent.Name(), "comm"))
|
||||
stat, _ := os.ReadFile(filepath.Join("/proc", ent.Name(), "statm"))
|
||||
cmd, _ := os.ReadFile(filepath.Join("/proc", ent.Name(), "cmdline"))
|
||||
v := ProcessInfo{PID: pid, Command: strings.TrimSpace(string(comm))}
|
||||
if len(cmd) > 0 {
|
||||
v.Command = strings.ReplaceAll(string(cmd), "\x00", " ")
|
||||
v.Command = strings.TrimSpace(v.Command)
|
||||
}
|
||||
f := strings.Fields(string(stat))
|
||||
if len(f) >= 2 {
|
||||
if pages, e := strconv.ParseUint(f[1], 10, 64); e == nil {
|
||||
v.MemoryKB = pages * uint64(os.Getpagesize()) / 1024
|
||||
}
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
var _ = fmt.Sprintf
|
||||
var _ = exec.Command
|
||||
@@ -0,0 +1,36 @@
|
||||
package executor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestListDirectoryAndInfo(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(d, "a.txt"), []byte("hello"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(filepath.Join(d, "sub"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
es, err := ListDirectory(d, false, 10)
|
||||
if err != nil || len(es) != 2 {
|
||||
t.Fatalf("entries=%v err=%v", es, err)
|
||||
}
|
||||
fi, err := GetFileInfo(filepath.Join(d, "a.txt"))
|
||||
if err != nil || fi.Size != 5 {
|
||||
t.Fatalf("info=%+v err=%v", fi, err)
|
||||
}
|
||||
}
|
||||
func TestSearchHonorsContextAndLimit(t *testing.T) {
|
||||
d := t.TempDir()
|
||||
for i := 0; i < 3; i++ {
|
||||
_ = os.WriteFile(filepath.Join(d, string(rune('a'+i))+".txt"), []byte("needle\n"), 0600)
|
||||
}
|
||||
r, err := Search(context.Background(), d, "needle", 2)
|
||||
if err != nil || len(r) != 2 {
|
||||
t.Fatalf("results=%v err=%v", r, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package executor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os/exec"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultRingCapacity = 2 * 1024 * 1024
|
||||
MaxSessionInput = 64 * 1024
|
||||
DefaultSessionTTL = 30 * time.Minute
|
||||
SessionIdleTTL = 10 * time.Minute
|
||||
MaxSessionBufferTotal = 8 * 1024 * 1024
|
||||
)
|
||||
|
||||
type RingBuffer struct {
|
||||
mu sync.RWMutex
|
||||
buf []byte
|
||||
head int
|
||||
size int
|
||||
}
|
||||
|
||||
func NewRingBuffer(capacity int) *RingBuffer {
|
||||
if capacity <= 0 {
|
||||
capacity = DefaultRingCapacity
|
||||
}
|
||||
return &RingBuffer{buf: make([]byte, capacity)}
|
||||
}
|
||||
|
||||
func (r *RingBuffer) Write(p []byte) (int, error) {
|
||||
total := len(p)
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for len(p) > 0 {
|
||||
n := len(p)
|
||||
if n > len(r.buf) {
|
||||
p = p[n-len(r.buf):]
|
||||
n = len(p)
|
||||
}
|
||||
first := len(r.buf) - r.head
|
||||
if first > n {
|
||||
first = n
|
||||
}
|
||||
copy(r.buf[r.head:r.head+first], p[:first])
|
||||
if first < n {
|
||||
copy(r.buf[:n-first], p[first:n])
|
||||
}
|
||||
r.head = (r.head + n) % len(r.buf)
|
||||
r.size += n
|
||||
if r.size > len(r.buf) {
|
||||
r.size = len(r.buf)
|
||||
}
|
||||
p = p[n:]
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
func (r *RingBuffer) Snapshot() []byte {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
out := make([]byte, r.size)
|
||||
start := (r.head - r.size + len(r.buf)) % len(r.buf)
|
||||
first := len(r.buf) - start
|
||||
if first > r.size {
|
||||
first = r.size
|
||||
}
|
||||
copy(out, r.buf[start:start+first])
|
||||
if first < r.size {
|
||||
copy(out[first:], r.buf[:r.size-first])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
ID string
|
||||
Command string
|
||||
Owner string
|
||||
StartedAt time.Time
|
||||
ExpiresAt time.Time
|
||||
LastAccess time.Time
|
||||
cmd *exec.Cmd
|
||||
stdin io.WriteCloser
|
||||
stdout *RingBuffer
|
||||
stderr *RingBuffer
|
||||
done chan struct{}
|
||||
mu sync.RWMutex
|
||||
err error
|
||||
exitCode int
|
||||
}
|
||||
|
||||
func StartSession(ctx context.Context, id, command, workdir, owner string, capacity int) (*Session, error) {
|
||||
if id == "" || command == "" {
|
||||
return nil, errors.New("session id and command required")
|
||||
}
|
||||
cmd := exec.Command("/bin/sh", "-c", command)
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
if workdir != "" {
|
||||
cmd.Dir = workdir
|
||||
}
|
||||
stdout := NewRingBuffer(capacity)
|
||||
stderr := NewRingBuffer(capacity)
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
errOut, err := cmd.StderrPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
s := &Session{
|
||||
ID: id, Command: command, Owner: owner, StartedAt: now, LastAccess: now, ExpiresAt: now.Add(DefaultSessionTTL), cmd: cmd,
|
||||
stdin: stdin, stdout: stdout, stderr: stderr, done: make(chan struct{}), exitCode: -1,
|
||||
}
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
_ = stdin.Close()
|
||||
return nil, err
|
||||
}
|
||||
go s.copy(out, stdout)
|
||||
go s.copy(errOut, stderr)
|
||||
go s.wait()
|
||||
go func() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
s.Terminate()
|
||||
case <-s.done:
|
||||
}
|
||||
}()
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *Session) copy(src io.Reader, dst io.Writer) {
|
||||
_, _ = io.Copy(dst, src)
|
||||
}
|
||||
|
||||
func (s *Session) wait() {
|
||||
err := s.cmd.Wait()
|
||||
s.mu.Lock()
|
||||
s.err = err
|
||||
if err == nil {
|
||||
s.exitCode = 0
|
||||
} else if ee, ok := err.(*exec.ExitError); ok {
|
||||
s.exitCode = ee.ExitCode()
|
||||
} else {
|
||||
s.exitCode = 1
|
||||
}
|
||||
s.mu.Unlock()
|
||||
close(s.done)
|
||||
}
|
||||
|
||||
func (s *Session) Done() <-chan struct{} { return s.done }
|
||||
|
||||
func (s *Session) Status() (int, bool, error) {
|
||||
select {
|
||||
case <-s.done:
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.exitCode, true, s.err
|
||||
default:
|
||||
return -1, false, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Session) Output() (stdout, stderr string) {
|
||||
stdout, stderr = string(s.stdout.Snapshot()), string(s.stderr.Snapshot())
|
||||
s.mu.Lock()
|
||||
if time.Now().Before(s.ExpiresAt) {
|
||||
s.LastAccess = time.Now()
|
||||
}
|
||||
s.mu.Unlock()
|
||||
return stdout, stderr
|
||||
}
|
||||
|
||||
func (s *Session) Stdin(data []byte) error {
|
||||
if len(data) > MaxSessionInput {
|
||||
return errors.New("session input too large")
|
||||
}
|
||||
s.mu.RLock()
|
||||
stdin := s.stdin
|
||||
s.mu.RUnlock()
|
||||
if stdin == nil {
|
||||
return errors.New("session stdin unavailable")
|
||||
}
|
||||
_, err := stdin.Write(data)
|
||||
if err == nil {
|
||||
s.mu.Lock()
|
||||
s.LastAccess = time.Now()
|
||||
s.mu.Unlock()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Session) Authorized(owner string) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
now := time.Now()
|
||||
if owner == "" || s.Owner != owner || now.After(s.ExpiresAt) || now.Sub(s.LastAccess) > SessionIdleTTL {
|
||||
return false
|
||||
}
|
||||
s.LastAccess = now
|
||||
return true
|
||||
}
|
||||
func (s *Session) Expired() bool {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
now := time.Now()
|
||||
return now.After(s.ExpiresAt) || now.Sub(s.LastAccess) > SessionIdleTTL
|
||||
}
|
||||
|
||||
func (s *Session) Terminate() error {
|
||||
s.mu.RLock()
|
||||
pid := 0
|
||||
if s.cmd != nil && s.cmd.Process != nil {
|
||||
pid = s.cmd.Process.Pid
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
if pid == 0 {
|
||||
return nil
|
||||
}
|
||||
return syscall.Kill(-pid, syscall.SIGTERM)
|
||||
}
|
||||
|
||||
func (s *Session) Kill() error {
|
||||
s.mu.RLock()
|
||||
pid := 0
|
||||
if s.cmd != nil && s.cmd.Process != nil {
|
||||
pid = s.cmd.Process.Pid
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
if pid == 0 {
|
||||
return nil
|
||||
}
|
||||
return syscall.Kill(-pid, syscall.SIGKILL)
|
||||
}
|
||||
|
||||
// Compile-time sanity for the output writer contract.
|
||||
var _ io.Writer = (*RingBuffer)(nil)
|
||||
@@ -0,0 +1,104 @@
|
||||
package executor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const MaxSessionsPerManager = MaxSessionBufferTotal / DefaultRingCapacity
|
||||
|
||||
type SessionInfo struct {
|
||||
ID string `json:"id"`
|
||||
Command string `json:"command"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
Running bool `json:"running"`
|
||||
ExitCode int `json:"exit_code"`
|
||||
}
|
||||
|
||||
type SessionManager struct {
|
||||
mu sync.RWMutex
|
||||
sessions map[string]*Session
|
||||
limit int
|
||||
}
|
||||
|
||||
func NewSessionManager(limit int) *SessionManager {
|
||||
if limit <= 0 || limit > MaxSessionsPerManager {
|
||||
limit = MaxSessionsPerManager
|
||||
}
|
||||
return &SessionManager{sessions: make(map[string]*Session), limit: limit}
|
||||
}
|
||||
func (m *SessionManager) Start(ctx context.Context, id, command, workdir, owner string, capacity int) (*Session, error) {
|
||||
m.mu.Lock()
|
||||
if _, ok := m.sessions[id]; ok {
|
||||
m.mu.Unlock()
|
||||
return nil, errors.New("session already exists")
|
||||
}
|
||||
if len(m.sessions) >= m.limit {
|
||||
m.mu.Unlock()
|
||||
return nil, errors.New("session limit reached")
|
||||
}
|
||||
s, err := StartSession(ctx, id, command, workdir, owner, capacity)
|
||||
if err != nil {
|
||||
m.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
if _, exists := m.sessions[id]; exists {
|
||||
m.mu.Unlock()
|
||||
_ = s.Kill()
|
||||
return nil, errors.New("session already exists")
|
||||
}
|
||||
m.sessions[id] = s
|
||||
m.mu.Unlock()
|
||||
return s, nil
|
||||
}
|
||||
func (m *SessionManager) Get(id string) (*Session, bool) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
s, ok := m.sessions[id]
|
||||
return s, ok
|
||||
}
|
||||
func (m *SessionManager) Remove(id string) bool {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if _, ok := m.sessions[id]; !ok {
|
||||
return false
|
||||
}
|
||||
delete(m.sessions, id)
|
||||
return true
|
||||
}
|
||||
func (m *SessionManager) List() []SessionInfo {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
out := make([]SessionInfo, 0, len(m.sessions))
|
||||
for _, s := range m.sessions {
|
||||
code, done, _ := s.Status()
|
||||
out = append(out, SessionInfo{ID: s.ID, Command: s.Command, StartedAt: s.StartedAt, Running: !done, ExitCode: code})
|
||||
}
|
||||
return out
|
||||
}
|
||||
func (m *SessionManager) Stop(id string, force bool) error {
|
||||
s, ok := m.Get(id)
|
||||
if !ok {
|
||||
return errors.New("session not found")
|
||||
}
|
||||
if force {
|
||||
return s.Kill()
|
||||
}
|
||||
return s.Terminate()
|
||||
}
|
||||
func (m *SessionManager) Cleanup() {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for id, s := range m.sessions {
|
||||
if s.Expired() {
|
||||
_, done, _ := s.Status()
|
||||
if !done {
|
||||
_ = s.Kill()
|
||||
continue
|
||||
}
|
||||
delete(m.sessions, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package executor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRingBufferKeepsNewestData(t *testing.T) {
|
||||
r := NewRingBuffer(8)
|
||||
_, _ = r.Write([]byte("12345678"))
|
||||
_, _ = r.Write([]byte("90"))
|
||||
if got := string(r.Snapshot()); got != "34567890" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
}
|
||||
func TestSessionCapturesAndTerminates(t *testing.T) {
|
||||
s, err := StartSession(context.Background(), "t1", "printf hello; sleep 5", "", "owner", 1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
out, _ := s.Output()
|
||||
if !strings.Contains(out, "hello") {
|
||||
t.Fatalf("out=%q", out)
|
||||
}
|
||||
if err := s.Terminate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-s.Done():
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("session did not terminate")
|
||||
}
|
||||
}
|
||||
func TestSessionManagerDuplicateAndLimit(t *testing.T) {
|
||||
m := NewSessionManager(1)
|
||||
s, err := m.Start(context.Background(), "a", "sleep 1", "", "owner", 128)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Kill()
|
||||
if _, err := m.Start(context.Background(), "b", "true", "", "owner", 128); err == nil {
|
||||
t.Fatal("expected limit")
|
||||
}
|
||||
if _, err := m.Start(context.Background(), "a", "true", "", "owner", 128); err == nil {
|
||||
t.Fatal("expected duplicate")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionIdleAuthorizationTouch(t *testing.T) {
|
||||
s, err := StartSession(context.Background(), "idle-test", "sleep 2", "", "owner", 128)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Kill()
|
||||
|
||||
s.mu.Lock()
|
||||
s.LastAccess = time.Now().Add(-(SessionIdleTTL + time.Second))
|
||||
s.mu.Unlock()
|
||||
if s.Authorized("owner") {
|
||||
t.Fatal("idle-expired session must not authorize")
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
s.LastAccess = time.Now()
|
||||
s.mu.Unlock()
|
||||
if !s.Authorized("owner") {
|
||||
t.Fatal("active session should authorize")
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/wjyhk/vps-commander/internal/auth"
|
||||
"github.com/wjyhk/vps-commander/internal/executor"
|
||||
)
|
||||
|
||||
// MCP Protocol / JSON-RPC 2.0 Types
|
||||
@@ -74,6 +75,27 @@ type ActionBackend interface {
|
||||
ExecCommand(ctx context.Context, clientIP, device, command, workdir string, timeout int) (any, error)
|
||||
ReadFile(ctx context.Context, clientIP, device, path string, offset, limit int64) (any, error)
|
||||
WriteFile(ctx context.Context, clientIP, device, path, content 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 {
|
||||
ReadMultipleFiles(ctx context.Context, clientIP, device string, paths []string, limit int64) (any, error)
|
||||
CreateDirectory(ctx context.Context, clientIP, device, path string) (any, error)
|
||||
MoveFile(ctx context.Context, clientIP, device, source, destination string) (any, error)
|
||||
ListProcesses(ctx context.Context, clientIP, device string) (any, error)
|
||||
}
|
||||
|
||||
type AgentMCPBackend interface {
|
||||
ListAgentMCP(ctx context.Context, device string) (any, error)
|
||||
CallAgentMCP(ctx context.Context, clientIP, device, server, tool string, args any) (any, error)
|
||||
}
|
||||
|
||||
type SecurityGate interface {
|
||||
AuthorizeMCP(device, action, clientIP string) error
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
@@ -259,6 +281,16 @@ func (s *Server) handleRequest(ctx context.Context, r *http.Request, req JSONRPC
|
||||
Required: []string{"path"},
|
||||
},
|
||||
},
|
||||
{Name: "read_multiple_files", Description: "一次读取多个文件", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}, "paths": {Type: "array", Description: "文件路径数组"}, "limit": {Type: "integer", Description: "单文件最大字节数"}}, Required: []string{"paths"}}},
|
||||
{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: "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",
|
||||
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"}},
|
||||
},
|
||||
{
|
||||
Name: "write_file",
|
||||
Description: "向指定受控节点创建或覆写文件",
|
||||
@@ -272,6 +304,14 @@ func (s *Server) handleRequest(ctx context.Context, r *http.Request, req JSONRPC
|
||||
Required: []string{"path", "content"},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "list_agent_mcp", Description: "列出指定 Agent 当前通过 Hub 动态挂载的 MCP 服务及状态",
|
||||
InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标 Agent 节点名称"}}, Required: []string{"device"}},
|
||||
},
|
||||
{
|
||||
Name: "call_agent_mcp", Description: "通过 Hub 调度指定 Agent 上已挂载的 MCP 工具",
|
||||
InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标 Agent 节点名称"}, "server": {Type: "string", Description: "MCP 服务 ID"}, "tool": {Type: "string", Description: "MCP 工具名称"}, "arguments": {Type: "object", Description: "MCP 工具参数 JSON 对象"}}, Required: []string{"device", "server", "tool"}},
|
||||
},
|
||||
}
|
||||
return JSONRPCResponse{
|
||||
JSONRPC: "2.0",
|
||||
@@ -356,6 +396,90 @@ func (s *Server) callTool(ctx context.Context, clientIP string, params CallToolP
|
||||
}
|
||||
return res, false
|
||||
|
||||
case "read_multiple_files":
|
||||
var a struct {
|
||||
Device string `json:"device"`
|
||||
Paths []string `json:"paths"`
|
||||
Limit int64 `json:"limit"`
|
||||
}
|
||||
_ = json.Unmarshal(params.Arguments, &a)
|
||||
b, ok := s.Backend.(ExtendedBackend)
|
||||
if !ok {
|
||||
return map[string]string{"error": "extended tools unavailable"}, true
|
||||
}
|
||||
res, err := b.ReadMultipleFiles(ctx, clientIP, a.Device, a.Paths, a.Limit)
|
||||
if err != nil {
|
||||
return map[string]string{"error": err.Error()}, true
|
||||
}
|
||||
return res, false
|
||||
case "create_directory":
|
||||
var a struct{ Device, Path string }
|
||||
_ = json.Unmarshal(params.Arguments, &a)
|
||||
b, ok := s.Backend.(ExtendedBackend)
|
||||
if !ok {
|
||||
return map[string]string{"error": "extended tools unavailable"}, true
|
||||
}
|
||||
res, err := b.CreateDirectory(ctx, clientIP, a.Device, a.Path)
|
||||
if err != nil {
|
||||
return map[string]string{"error": err.Error()}, true
|
||||
}
|
||||
return res, false
|
||||
case "move_file":
|
||||
var a struct{ Device, Source, Destination string }
|
||||
_ = json.Unmarshal(params.Arguments, &a)
|
||||
b, ok := s.Backend.(ExtendedBackend)
|
||||
if !ok {
|
||||
return map[string]string{"error": "extended tools unavailable"}, true
|
||||
}
|
||||
res, err := b.MoveFile(ctx, clientIP, a.Device, a.Source, a.Destination)
|
||||
if err != nil {
|
||||
return map[string]string{"error": err.Error()}, true
|
||||
}
|
||||
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":
|
||||
var a struct {
|
||||
Device string `json:"device"`
|
||||
}
|
||||
_ = json.Unmarshal(params.Arguments, &a)
|
||||
b, ok := s.Backend.(ExtendedBackend)
|
||||
if !ok {
|
||||
return map[string]string{"error": "extended tools unavailable"}, true
|
||||
}
|
||||
res, err := b.ListProcesses(ctx, clientIP, a.Device)
|
||||
if err != nil {
|
||||
return map[string]string{"error": err.Error()}, true
|
||||
}
|
||||
return res, false
|
||||
case "edit_block":
|
||||
var args struct{ Device, Path, OldText, NewText string }
|
||||
_ = json.Unmarshal(params.Arguments, &args)
|
||||
if args.Path == "" || args.OldText == "" {
|
||||
return map[string]string{"error": "path and old_text are required"}, true
|
||||
}
|
||||
res, err := s.Backend.EditBlock(ctx, clientIP, args.Device, args.Path, args.OldText, args.NewText)
|
||||
if err != nil {
|
||||
return map[string]string{"error": err.Error()}, true
|
||||
}
|
||||
return res, false
|
||||
|
||||
case "write_file":
|
||||
var args struct {
|
||||
Device string `json:"device"`
|
||||
@@ -372,6 +496,53 @@ func (s *Server) callTool(ctx context.Context, clientIP string, params CallToolP
|
||||
}
|
||||
return res, false
|
||||
|
||||
case "list_agent_mcp":
|
||||
var args struct {
|
||||
Device string `json:"device"`
|
||||
}
|
||||
_ = json.Unmarshal(params.Arguments, &args)
|
||||
b, ok := s.Backend.(AgentMCPBackend)
|
||||
if !ok {
|
||||
return map[string]string{"error": "agent MCP unavailable"}, true
|
||||
}
|
||||
if gate, ok := s.Backend.(SecurityGate); ok {
|
||||
if err := gate.AuthorizeMCP(args.Device, "read", clientIP); err != nil {
|
||||
return map[string]string{"error": err.Error()}, true
|
||||
}
|
||||
}
|
||||
res, err := b.ListAgentMCP(ctx, args.Device)
|
||||
if err != nil {
|
||||
return map[string]string{"error": err.Error()}, true
|
||||
}
|
||||
return res, false
|
||||
|
||||
case "call_agent_mcp":
|
||||
var args struct {
|
||||
Device string `json:"device"`
|
||||
Server string `json:"server"`
|
||||
Tool string `json:"tool"`
|
||||
Arguments json.RawMessage `json:"arguments"`
|
||||
}
|
||||
_ = json.Unmarshal(params.Arguments, &args)
|
||||
b, ok := s.Backend.(AgentMCPBackend)
|
||||
if !ok {
|
||||
return map[string]string{"error": "agent MCP unavailable"}, true
|
||||
}
|
||||
var av any
|
||||
if len(args.Arguments) > 0 {
|
||||
_ = json.Unmarshal(args.Arguments, &av)
|
||||
}
|
||||
if gate, ok := s.Backend.(SecurityGate); ok {
|
||||
if err := gate.AuthorizeMCP(args.Device, "mcp", clientIP); err != nil {
|
||||
return map[string]string{"error": err.Error()}, true
|
||||
}
|
||||
}
|
||||
res, err := b.CallAgentMCP(ctx, clientIP, args.Device, args.Server, args.Tool, av)
|
||||
if err != nil {
|
||||
return map[string]string{"error": err.Error()}, true
|
||||
}
|
||||
return res, false
|
||||
|
||||
default:
|
||||
return map[string]string{"error": "unknown tool: " + params.Name}, true
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
@@ -24,6 +25,9 @@ func (m *mockBackend) ReadFile(ctx context.Context, clientIP, device, path strin
|
||||
func (m *mockBackend) WriteFile(ctx context.Context, clientIP, device, path, content string) (any, error) {
|
||||
return map[string]any{"device": device, "path": path, "bytes": len(content)}, nil
|
||||
}
|
||||
func (m *mockBackend) EditBlock(ctx context.Context, clientIP, device, path, oldText, newText string) (any, error) {
|
||||
return map[string]any{"device": device, "path": path, "bytes_written": len(newText)}, nil
|
||||
}
|
||||
|
||||
func TestMCPInitializeAndListTools(t *testing.T) {
|
||||
srv := NewServer(&mockBackend{}, nil)
|
||||
@@ -75,8 +79,25 @@ func TestMCPInitializeAndListTools(t *testing.T) {
|
||||
t.Fatalf("expected map result")
|
||||
}
|
||||
tools, ok := resMap["tools"].([]any)
|
||||
if !ok || len(tools) != 4 {
|
||||
t.Fatalf("expected 4 tools, got %d", len(tools))
|
||||
if !ok || len(tools) != 12 {
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,3 +131,47 @@ func TestMCPCallTool(t *testing.T) {
|
||||
t.Fatalf("expected stdout in result, got %s", contentStr)
|
||||
}
|
||||
}
|
||||
|
||||
type gatedMockBackend struct {
|
||||
mockBackend
|
||||
deniedAction string
|
||||
}
|
||||
|
||||
func (g *gatedMockBackend) AuthorizeMCP(device, action, clientIP string) error {
|
||||
if action == g.deniedAction {
|
||||
return fmt.Errorf("denied %s", action)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *gatedMockBackend) ListAgentMCP(ctx context.Context, device string) (any, error) {
|
||||
return map[string]any{"device": device}, nil
|
||||
}
|
||||
|
||||
func (g *gatedMockBackend) CallAgentMCP(ctx context.Context, clientIP, device, server, tool string, args any) (any, error) {
|
||||
return map[string]any{"device": device, "server": server, "tool": tool}, nil
|
||||
}
|
||||
|
||||
func TestMCPAgentCallUsesSecurityGate(t *testing.T) {
|
||||
backend := &gatedMockBackend{deniedAction: "mcp"}
|
||||
srv := NewServer(backend, nil)
|
||||
params := json.RawMessage("{\"name\":\"call_agent_mcp\",\"arguments\":{\"device\":\"node1\",\"server\":\"s\",\"tool\":\"t\"}}")
|
||||
req := JSONRPCRequest{JSONRPC: "2.0", ID: 10, Method: "tools/call", Params: params}
|
||||
resp := srv.HandleDirectRequest(context.Background(), req)
|
||||
result, ok := resp.Result.(CallToolResult)
|
||||
if !ok || !result.IsError || !strings.Contains(result.Content[0].Text, "denied mcp") {
|
||||
t.Fatalf("expected MCP denial, got %#v", resp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPListAgentUsesReadGate(t *testing.T) {
|
||||
backend := &gatedMockBackend{deniedAction: "read"}
|
||||
srv := NewServer(backend, nil)
|
||||
params := json.RawMessage("{\"name\":\"list_agent_mcp\",\"arguments\":{\"device\":\"node1\"}}")
|
||||
req := JSONRPCRequest{JSONRPC: "2.0", ID: 11, Method: "tools/call", Params: params}
|
||||
resp := srv.HandleDirectRequest(context.Background(), req)
|
||||
result, ok := resp.Result.(CallToolResult)
|
||||
if !ok || !result.IsError || !strings.Contains(result.Content[0].Text, "denied read") {
|
||||
t.Fatalf("expected MCP list denial, got %#v", resp)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,9 @@ type Device struct {
|
||||
Local bool `json:"is_local"`
|
||||
Arch string `json:"arch,omitempty"`
|
||||
OS string `json:"os,omitempty"`
|
||||
RemoteIP string `json:"remote_ip,omitempty"`
|
||||
CountryCode string `json:"country_code,omitempty"`
|
||||
Country string `json:"country,omitempty"`
|
||||
Profile *sysinfo.Profile `json:"profile,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/wjyhk/vps-commander/internal/storage"
|
||||
)
|
||||
|
||||
type Target struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
URL string `json:"url"`
|
||||
Config string `json:"config_json"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
type Event struct {
|
||||
Type string `json:"type"`
|
||||
Device string `json:"device,omitempty"`
|
||||
Severity string `json:"severity"`
|
||||
Message string `json:"message"`
|
||||
At int64 `json:"timestamp"`
|
||||
Data any `json:"data,omitempty"`
|
||||
}
|
||||
type Manager struct {
|
||||
Store *storage.Store
|
||||
Client *http.Client
|
||||
stop chan struct{}
|
||||
wg sync.WaitGroup
|
||||
mu sync.Mutex
|
||||
offline map[string]int64
|
||||
sent map[string]time.Time
|
||||
strikeCount map[string]int
|
||||
lastSchedule string
|
||||
}
|
||||
|
||||
func New(s *storage.Store) *Manager {
|
||||
m := &Manager{Store: s, Client: &http.Client{Timeout: 8 * time.Second}, stop: make(chan struct{}), offline: map[string]int64{}, sent: map[string]time.Time{}, strikeCount: map[string]int{}}
|
||||
m.importOpenClawWebhook()
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *Manager) importOpenClawWebhook() {
|
||||
if xs, err := m.Store.ListWebhookTargets(); err == nil && len(xs) > 0 {
|
||||
return
|
||||
}
|
||||
b, err := os.ReadFile("/root/.openclaw/workspace/check_exchange_rate.py")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
re := regexp.MustCompile(`WEBHOOK_URL\s*=\s*[\"']([^\"']+)[\"']`)
|
||||
match := re.FindSubmatch(b)
|
||||
if len(match) != 2 || len(match[1]) == 0 {
|
||||
return
|
||||
}
|
||||
_ = m.Store.SaveWebhookTarget(storage.WebhookTarget{ID: "openclaw-wecom", Name: "OpenClaw 企业微信", Type: "wecom", URL: string(match[1]), Config: "{}", Enabled: true})
|
||||
}
|
||||
func (m *Manager) Start() { m.wg.Add(1); go m.loop() }
|
||||
func (m *Manager) Stop() { close(m.stop); m.wg.Wait() }
|
||||
func (m *Manager) loop() {
|
||||
defer m.wg.Done()
|
||||
t := time.NewTicker(15 * time.Second)
|
||||
defer t.Stop()
|
||||
m.check()
|
||||
for {
|
||||
select {
|
||||
case <-t.C:
|
||||
m.check()
|
||||
case <-m.stop:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
func (m *Manager) check() {
|
||||
devices, _ := m.Store.ListDevices()
|
||||
now := time.Now().Unix()
|
||||
for _, d := range devices {
|
||||
if d.IsLocal {
|
||||
continue
|
||||
}
|
||||
if d.Status == "offline" && d.OfflineAt != nil {
|
||||
if now-*d.OfflineAt >= 60 {
|
||||
m.mu.Lock()
|
||||
m.offline[d.Name] = now
|
||||
m.mu.Unlock()
|
||||
m.emitOnce("offline:"+d.Name, Event{Type: "node_offline", Device: d.Name, Severity: "critical", Message: fmt.Sprintf("节点 %s 已离线超过 1 分钟", d.Name), At: now})
|
||||
}
|
||||
} else if d.Status == "online" {
|
||||
m.mu.Lock()
|
||||
was := m.offline[d.Name] > 0
|
||||
delete(m.offline, d.Name)
|
||||
m.mu.Unlock()
|
||||
if was {
|
||||
m.emit(Event{Type: "node_recovery", Device: d.Name, Severity: "info", Message: fmt.Sprintf("节点 %s 已恢复在线", d.Name), At: now})
|
||||
}
|
||||
}
|
||||
}
|
||||
m.checkSchedule(devices, now)
|
||||
for _, d := range devices {
|
||||
if d.ProfileJSON == "" {
|
||||
continue
|
||||
}
|
||||
var p map[string]any
|
||||
if json.Unmarshal([]byte(d.ProfileJSON), &p) != nil {
|
||||
continue
|
||||
}
|
||||
mem, _ := p["mem_percent"].(float64)
|
||||
disk, _ := p["disk_percent"].(float64)
|
||||
cpu, _ := p["cpu_usage_percent"].(float64)
|
||||
// 防抖逻辑:资源利用率需连续 3 次轮询(约 45 秒)超过阈值才触发告警
|
||||
checkStrike := func(metric string, val float64, threshold float64, msg string) {
|
||||
key := fmt.Sprintf("%s:%s", metric, d.Name)
|
||||
m.mu.Lock()
|
||||
if val >= threshold {
|
||||
m.strikeCount[key]++
|
||||
} else {
|
||||
m.strikeCount[key] = 0
|
||||
}
|
||||
count := m.strikeCount[key]
|
||||
m.mu.Unlock()
|
||||
|
||||
if count >= 3 {
|
||||
m.emitOnce(key, Event{
|
||||
Type: "resource_threshold",
|
||||
Device: d.Name,
|
||||
Severity: "warning",
|
||||
Message: msg,
|
||||
At: now,
|
||||
Data: map[string]any{"metric": metric, "value": val, "threshold": threshold, "strikes": count},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
checkStrike("mem", mem, 90, fmt.Sprintf("节点 %s 连续 45s 内存使用率超限: %.0f%%", d.Name, mem))
|
||||
checkStrike("disk", disk, 90, fmt.Sprintf("节点 %s 磁盘使用率 %.0f%%", d.Name, disk))
|
||||
checkStrike("cpu", cpu, 95, fmt.Sprintf("节点 %s 连续 45s CPU 使用率超限: %.0f%%", d.Name, cpu))
|
||||
}
|
||||
}
|
||||
func (m *Manager) emitOnce(key string, e Event) {
|
||||
m.mu.Lock()
|
||||
last := m.sent[key]
|
||||
if !last.IsZero() && time.Since(last) < 30*time.Minute {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
m.sent[key] = time.Now()
|
||||
m.mu.Unlock()
|
||||
m.emit(e)
|
||||
}
|
||||
func (m *Manager) emit(e Event) {
|
||||
targets, _ := m.Store.ListWebhookTargets()
|
||||
payload, _ := json.Marshal(e)
|
||||
for _, t := range targets {
|
||||
if !t.Enabled {
|
||||
continue
|
||||
}
|
||||
body := payload
|
||||
if t.Type == "telegram" {
|
||||
var c struct {
|
||||
ChatID string `json:"chat_id"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(t.Config), &c)
|
||||
body, _ = json.Marshal(map[string]any{"chat_id": c.ChatID, "text": e.Message})
|
||||
}
|
||||
if t.Type == "wecom" {
|
||||
body, _ = json.Marshal(map[string]any{"msgtype": "text", "text": map[string]any{"content": e.Message}})
|
||||
}
|
||||
req, _ := http.NewRequest(http.MethodPost, t.URL, bytes.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
|
||||
req = req.WithContext(ctx)
|
||||
resp, err := m.Client.Do(req)
|
||||
if err != nil {
|
||||
_ = m.Store.Audit("127.0.0.1", e.Device, "notification", "webhook:"+t.ID, 1, 0, err.Error())
|
||||
} else {
|
||||
resp.Body.Close()
|
||||
code := resp.StatusCode
|
||||
_ = m.Store.Audit("127.0.0.1", e.Device, "notification", "webhook:"+t.ID, func() int {
|
||||
if code >= 200 && code < 300 {
|
||||
return 0
|
||||
}
|
||||
return code
|
||||
}(), 0, "")
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
func (m *Manager) TestTarget(t Target) error {
|
||||
e := Event{Type: "test", Severity: "info", Message: "VPS-Commander Phase 3 Webhook 测试消息", At: time.Now().Unix()}
|
||||
b, _ := json.Marshal(e)
|
||||
req, _ := http.NewRequest(http.MethodPost, t.URL, bytes.NewReader(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := m.Client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("webhook http %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) checkSchedule(devices []storage.DeviceRecord, now int64) {
|
||||
t := time.Now()
|
||||
key := t.Format("2006-01-02") + ":" + t.Format("15:04")
|
||||
minute := t.Hour()*60 + t.Minute()
|
||||
if minute != 510 && minute != 1320 {
|
||||
return
|
||||
}
|
||||
m.mu.Lock()
|
||||
if m.lastSchedule == key {
|
||||
m.mu.Unlock()
|
||||
return
|
||||
}
|
||||
m.lastSchedule = key
|
||||
m.mu.Unlock()
|
||||
online, offline := 0, 0
|
||||
for _, d := range devices {
|
||||
if d.IsLocal {
|
||||
continue
|
||||
}
|
||||
if d.Status == "online" {
|
||||
online++
|
||||
} else {
|
||||
offline++
|
||||
}
|
||||
}
|
||||
m.emit(Event{Type: "scheduled_report", Severity: "info", Message: fmt.Sprintf("VPS-Commander %s 报告:远程节点在线 %d,离线 %d", map[bool]string{true: "早间", false: "晚间"}[minute == 510], online, offline), At: now, Data: map[string]any{"report": "daily", "period": map[bool]string{true: "morning", false: "evening"}[minute == 510], "online": online, "offline": offline}})
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"github.com/wjyhk/vps-commander/internal/storage"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTestTargetAndPayload(t *testing.T) {
|
||||
got := ""
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
t.Errorf("method=%s", r.Method)
|
||||
}
|
||||
b := make([]byte, 4096)
|
||||
n, _ := r.Body.Read(b)
|
||||
got = string(b[:n])
|
||||
w.WriteHeader(200)
|
||||
}))
|
||||
defer srv.Close()
|
||||
db := t.TempDir() + "/test.db"
|
||||
st, err := storage.Open(db)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer st.DB.Close()
|
||||
m := New(st)
|
||||
m.Client = srv.Client()
|
||||
if err := m.TestTarget(Target{ID: "t", Name: "test", Type: "generic", URL: srv.URL, Enabled: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) == 0 {
|
||||
t.Fatal("empty webhook body")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebhookStorage(t *testing.T) {
|
||||
st, err := storage.Open(t.TempDir() + "/test.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer st.DB.Close()
|
||||
if err := st.SaveWebhookTarget(storage.WebhookTarget{ID: "x", Name: "X", Type: "generic", URL: "http://127.0.0.1", Config: "{}", Enabled: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xs, err := st.ListWebhookTargets()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(xs) != 1 || xs[0].ID != "x" {
|
||||
t.Fatalf("unexpected targets: %#v", xs)
|
||||
}
|
||||
if err := st.DeleteWebhookTarget("x"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
RiskLow = 1
|
||||
RiskMedium = 2
|
||||
RiskHigh = 3
|
||||
)
|
||||
|
||||
type DevicePolicy struct {
|
||||
Mode string
|
||||
}
|
||||
|
||||
type PolicySnapshot struct {
|
||||
Version uint64
|
||||
GlobalRisk int
|
||||
Devices map[string]DevicePolicy
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
mu sync.RWMutex
|
||||
data PolicySnapshot
|
||||
}
|
||||
|
||||
func New(globalRisk int, devices map[string]DevicePolicy, version uint64) *Snapshot {
|
||||
if globalRisk < RiskLow || globalRisk > RiskHigh {
|
||||
globalRisk = RiskMedium
|
||||
}
|
||||
cp := make(map[string]DevicePolicy, len(devices))
|
||||
for k, v := range devices {
|
||||
cp[k] = v
|
||||
}
|
||||
return &Snapshot{data: PolicySnapshot{
|
||||
Version: version, GlobalRisk: globalRisk, Devices: cp, CreatedAt: time.Now(),
|
||||
}}
|
||||
}
|
||||
|
||||
func (s *Snapshot) Current() PolicySnapshot {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
cp := make(map[string]DevicePolicy, len(s.data.Devices))
|
||||
for k, v := range s.data.Devices {
|
||||
cp[k] = v
|
||||
}
|
||||
snap := s.data
|
||||
snap.Devices = cp
|
||||
return snap
|
||||
}
|
||||
|
||||
func (s *Snapshot) Publish(globalRisk int, devices map[string]DevicePolicy, version uint64) error {
|
||||
if globalRisk < RiskLow || globalRisk > RiskHigh {
|
||||
return errors.New("invalid global risk")
|
||||
}
|
||||
cp := make(map[string]DevicePolicy, len(devices))
|
||||
for k, v := range devices {
|
||||
cp[k] = v
|
||||
}
|
||||
s.mu.Lock()
|
||||
if version < s.data.Version {
|
||||
s.mu.Unlock()
|
||||
return errors.New("policy version regression")
|
||||
}
|
||||
s.data = PolicySnapshot{
|
||||
Version: version, GlobalRisk: globalRisk, Devices: cp, CreatedAt: time.Now(),
|
||||
}
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Snapshot) EffectiveRisk(device string) int {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
if p, ok := s.data.Devices[device]; ok {
|
||||
if risk := ModeRisk(p.Mode); risk != 0 {
|
||||
return risk
|
||||
}
|
||||
}
|
||||
return s.data.GlobalRisk
|
||||
}
|
||||
|
||||
func ModeRisk(mode string) int {
|
||||
switch mode {
|
||||
case "low":
|
||||
return RiskLow
|
||||
case "medium":
|
||||
return RiskMedium
|
||||
case "high":
|
||||
return RiskHigh
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package security
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSnapshotEffectiveRiskAndPublish(t *testing.T) {
|
||||
s := New(RiskMedium, map[string]DevicePolicy{"hwsg": {Mode: "high"}}, 7)
|
||||
if got := s.EffectiveRisk("hwsg"); got != RiskHigh {
|
||||
t.Fatalf("hwsg risk=%d, want %d", got, RiskHigh)
|
||||
}
|
||||
if got := s.EffectiveRisk("n3450"); got != RiskMedium {
|
||||
t.Fatalf("default risk=%d, want %d", got, RiskMedium)
|
||||
}
|
||||
if err := s.Publish(RiskLow, map[string]DevicePolicy{"n3450": {Mode: "medium"}}, 8); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cur := s.Current()
|
||||
if cur.Version != 8 {
|
||||
t.Fatalf("version=%d, want 8", cur.Version)
|
||||
}
|
||||
if got := s.EffectiveRisk("hwsg"); got != RiskLow {
|
||||
t.Fatalf("old node risk=%d, want %d", got, RiskLow)
|
||||
}
|
||||
if got := s.EffectiveRisk("n3450"); got != RiskMedium {
|
||||
t.Fatalf("override risk=%d, want %d", got, RiskMedium)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModeRiskRejectsUnknown(t *testing.T) {
|
||||
if got := ModeRisk("inherit"); got != 0 {
|
||||
t.Fatalf("inherit risk=%d, want 0", got)
|
||||
}
|
||||
if got := ModeRisk("root"); got != 0 {
|
||||
t.Fatalf("unknown risk=%d, want 0", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package security
|
||||
|
||||
type ToolSpec struct {
|
||||
Name string
|
||||
RequiredRisk int
|
||||
Category string
|
||||
ReadOnly bool
|
||||
}
|
||||
|
||||
var registry = map[string]ToolSpec{
|
||||
"read_file": {Name: "read_file", RequiredRisk: RiskLow, Category: "file", ReadOnly: true},
|
||||
"read_multiple_files": {Name: "read_multiple_files", RequiredRisk: RiskLow, Category: "file", ReadOnly: true},
|
||||
"list_directory": {Name: "list_directory", RequiredRisk: RiskLow, Category: "file", ReadOnly: true},
|
||||
"get_file_info": {Name: "get_file_info", RequiredRisk: RiskLow, Category: "file", 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},
|
||||
"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},
|
||||
"read_process_output": {Name: "read_process_output", RequiredRisk: RiskLow, Category: "process", ReadOnly: true},
|
||||
"edit_block": {Name: "edit_block", RequiredRisk: RiskMedium, Category: "file", ReadOnly: false},
|
||||
"write_file": {Name: "write_file", RequiredRisk: RiskMedium, Category: "file", ReadOnly: false},
|
||||
"create_directory": {Name: "create_directory", RequiredRisk: RiskMedium, Category: "file", ReadOnly: false},
|
||||
"move_file": {Name: "move_file", RequiredRisk: RiskMedium, Category: "file", ReadOnly: false},
|
||||
"exec_command": {Name: "exec_command", RequiredRisk: RiskHigh, Category: "process", ReadOnly: false},
|
||||
"start_process": {Name: "start_process", RequiredRisk: RiskHigh, Category: "process", ReadOnly: false},
|
||||
"interact_with_process": {Name: "interact_with_process", RequiredRisk: RiskHigh, Category: "process", ReadOnly: false},
|
||||
"kill_process": {Name: "kill_process", RequiredRisk: RiskHigh, Category: "process", ReadOnly: false},
|
||||
"force_terminate": {Name: "force_terminate", RequiredRisk: RiskHigh, Category: "process", ReadOnly: false},
|
||||
"mcp_call": {Name: "mcp_call", RequiredRisk: RiskMedium, Category: "mcp", ReadOnly: false},
|
||||
}
|
||||
|
||||
var actionTools = map[string]string{
|
||||
"read": "read_file", "probe": "read_file", "write": "write_file",
|
||||
"mcp": "mcp_call", "exec": "exec_command", "diagnostic": "diagnostic_command",
|
||||
}
|
||||
|
||||
func Lookup(name string) (ToolSpec, bool) {
|
||||
v, ok := registry[name]
|
||||
return v, ok
|
||||
}
|
||||
|
||||
func RequiredRiskForAction(action string) (int, bool) {
|
||||
name, ok := actionTools[action]
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
spec, ok := registry[name]
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
return spec.RequiredRisk, true
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDeviceLifecyclePersistence(t *testing.T) {
|
||||
s, err := Open(filepath.Join(t.TempDir(), "commander.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.DB.Close()
|
||||
|
||||
if err := s.UpsertRemote("node1", "online", "amd64", "linux", 100, "{\"role\":\"APPLICATION\"}"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows, err := s.ListDevices()
|
||||
if err != nil || len(rows) != 1 {
|
||||
t.Fatalf("rows=%d err=%v", len(rows), err)
|
||||
}
|
||||
if rows[0].Status != "online" || rows[0].Arch != "amd64" || rows[0].OS != "linux" {
|
||||
t.Fatalf("unexpected row: %+v", rows[0])
|
||||
}
|
||||
|
||||
if err := s.UpdateDeviceStatus("node1", "offline", 120); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows, err = s.ListDevices()
|
||||
if err != nil || len(rows) != 1 {
|
||||
t.Fatalf("rows=%d err=%v", len(rows), err)
|
||||
}
|
||||
if rows[0].Status != "offline" || rows[0].OfflineAt == nil {
|
||||
t.Fatalf("offline state not persisted: %+v", rows[0])
|
||||
}
|
||||
|
||||
if err := s.RevokeDevice("node1", "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows, err = s.ListDevices()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) != 0 {
|
||||
t.Fatalf("revoked device still present: %+v", rows)
|
||||
}
|
||||
revoked, err := s.IsRevoked("node1")
|
||||
if err != nil || !revoked {
|
||||
t.Fatalf("revoked=%v err=%v", revoked, err)
|
||||
}
|
||||
}
|
||||
+502
-33
@@ -1,10 +1,16 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
_ "modernc.org/sqlite"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -18,8 +24,6 @@ func Open(path string) (*Store, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// SQLite has a single-writer model. Keep one application connection so
|
||||
// concurrent callers queue instead of opening competing writer connections.
|
||||
db.SetMaxOpenConns(1)
|
||||
db.SetMaxIdleConns(1)
|
||||
s := &Store{db}
|
||||
@@ -31,28 +35,235 @@ func Open(path string) (*Store, error) {
|
||||
}
|
||||
|
||||
func (s *Store) init() error {
|
||||
if _, err := s.DB.Exec(`PRAGMA journal_mode = WAL`); err != nil {
|
||||
if _, err := s.DB.Exec("PRAGMA journal_mode = WAL"); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := s.DB.Exec(`PRAGMA busy_timeout = 5000`); err != nil {
|
||||
if _, err := s.DB.Exec("PRAGMA busy_timeout = 5000"); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := s.DB.Exec(`CREATE TABLE IF NOT EXISTS devices (
|
||||
name TEXT PRIMARY KEY, status TEXT NOT NULL, is_local INTEGER NOT NULL,
|
||||
arch TEXT, os TEXT, updated_at INTEGER NOT NULL
|
||||
); CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER NOT NULL,
|
||||
caller_ip TEXT, device TEXT, action TEXT, command TEXT,
|
||||
exit_code INTEGER, duration_ms INTEGER, error_msg TEXT
|
||||
);`)
|
||||
_, err := s.DB.Exec("CREATE TABLE IF NOT EXISTS webhook_targets (id TEXT PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, url TEXT NOT NULL, config_json TEXT, enabled INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS idx_webhook_targets_enabled ON webhook_targets(enabled); CREATE TABLE IF NOT EXISTS devices (" +
|
||||
"name TEXT PRIMARY KEY, status TEXT NOT NULL DEFAULT 'offline', is_local INTEGER NOT NULL DEFAULT 0, " +
|
||||
"arch TEXT, os TEXT, last_seen INTEGER NOT NULL DEFAULT 0, last_heartbeat INTEGER NOT NULL DEFAULT 0, " +
|
||||
"offline_at INTEGER, profile_json TEXT, created_at INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL DEFAULT 0); " +
|
||||
"CREATE TABLE IF NOT EXISTS audit_logs (" +
|
||||
"id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER NOT NULL, caller_ip TEXT, device TEXT, action TEXT, command TEXT, " +
|
||||
"exit_code INTEGER, duration_ms INTEGER, error_msg TEXT); " +
|
||||
"CREATE TABLE IF NOT EXISTS revoked_devices (name TEXT PRIMARY KEY, revoked_at INTEGER NOT NULL, reason TEXT); CREATE TABLE IF NOT EXISTS device_credentials (name TEXT PRIMARY KEY, token_hash TEXT NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS security_settings (node_name TEXT PRIMARY KEY, mode TEXT NOT NULL, updated_at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS security_policy_meta (id INTEGER PRIMARY KEY CHECK(id=1), version INTEGER NOT NULL); INSERT OR IGNORE INTO security_policy_meta(id,version) VALUES(1,1); CREATE TABLE IF NOT EXISTS mcp_services (id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT, transport TEXT NOT NULL, command TEXT, args_json TEXT, env_json TEXT, url TEXT, headers_json TEXT, scope TEXT NOT NULL DEFAULT 'all', target_nodes_json TEXT, enabled INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS idx_mcp_services_enabled ON mcp_services(enabled);")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.migrateDevices()
|
||||
}
|
||||
|
||||
type MCPService struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Transport string `json:"transport"`
|
||||
Command string `json:"command,omitempty"`
|
||||
ArgsJSON string `json:"args_json,omitempty"`
|
||||
EnvJSON string `json:"env_json,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
HeadersJSON string `json:"headers_json,omitempty"`
|
||||
Scope string `json:"scope"`
|
||||
TargetNodesJSON string `json:"target_nodes_json,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (s *Store) SaveMCPService(v MCPService) error {
|
||||
now := time.Now().Unix()
|
||||
if v.CreatedAt <= 0 {
|
||||
v.CreatedAt = now
|
||||
}
|
||||
v.UpdatedAt = now
|
||||
if v.Scope == "" {
|
||||
v.Scope = "all"
|
||||
}
|
||||
if v.Transport == "" {
|
||||
return errors.New("transport required")
|
||||
}
|
||||
_, err := s.DB.Exec(`INSERT INTO mcp_services(id,name,description,transport,command,args_json,env_json,url,headers_json,scope,target_nodes_json,enabled,created_at,updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,description=excluded.description,transport=excluded.transport,command=excluded.command,args_json=excluded.args_json,env_json=excluded.env_json,url=excluded.url,headers_json=excluded.headers_json,scope=excluded.scope,target_nodes_json=excluded.target_nodes_json,enabled=excluded.enabled,updated_at=excluded.updated_at`,
|
||||
v.ID, v.Name, v.Description, v.Transport, v.Command, v.ArgsJSON, v.EnvJSON, v.URL, v.HeadersJSON, v.Scope, v.TargetNodesJSON, boolInt(v.Enabled), v.CreatedAt, v.UpdatedAt)
|
||||
return err
|
||||
}
|
||||
func boolInt(v bool) int {
|
||||
if v {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
func (s *Store) DeleteMCPService(id string) error {
|
||||
_, err := s.DB.Exec(`DELETE FROM mcp_services WHERE id=?`, id)
|
||||
return err
|
||||
}
|
||||
func (s *Store) ListMCPServices() ([]MCPService, error) {
|
||||
return s.listMCP(`SELECT id,name,description,transport,COALESCE(command,''),COALESCE(args_json,''),COALESCE(env_json,''),COALESCE(url,''),COALESCE(headers_json,''),scope,COALESCE(target_nodes_json,''),enabled,created_at,updated_at FROM mcp_services ORDER BY id`)
|
||||
}
|
||||
func (s *Store) ListMCPServicesForNode(node string) ([]MCPService, error) {
|
||||
all, err := s.listMCP(`SELECT id,name,description,transport,COALESCE(command,''),COALESCE(args_json,''),COALESCE(env_json,''),COALESCE(url,''),COALESCE(headers_json,''),scope,COALESCE(target_nodes_json,''),enabled,created_at,updated_at FROM mcp_services WHERE enabled=1 ORDER BY id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]MCPService, 0, len(all))
|
||||
for _, v := range all {
|
||||
if v.Scope != "custom" || containsNode(v.TargetNodesJSON, node) {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func containsNode(raw, node string) bool {
|
||||
var a []string
|
||||
if json.Unmarshal([]byte(raw), &a) != nil {
|
||||
return false
|
||||
}
|
||||
for _, v := range a {
|
||||
if v == node {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (s *Store) listMCP(q string) ([]MCPService, error) {
|
||||
rows, err := s.DB.Query(q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []MCPService{}
|
||||
for rows.Next() {
|
||||
var v MCPService
|
||||
var en int
|
||||
if err := rows.Scan(&v.ID, &v.Name, &v.Description, &v.Transport, &v.Command, &v.ArgsJSON, &v.EnvJSON, &v.URL, &v.HeadersJSON, &v.Scope, &v.TargetNodesJSON, &en, &v.CreatedAt, &v.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v.Enabled = en != 0
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) migrateDevices() error {
|
||||
cols := map[string]bool{}
|
||||
rows, err := s.DB.Query("PRAGMA table_info(devices)")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var cid, notnull, pk int
|
||||
var name, typ string
|
||||
var dflt sql.NullString
|
||||
if err := rows.Scan(&cid, &name, &typ, ¬null, &dflt, &pk); err != nil {
|
||||
return err
|
||||
}
|
||||
cols[name] = true
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
migrations := []struct{ name, sql string }{
|
||||
{"last_seen", "ALTER TABLE devices ADD COLUMN last_seen INTEGER NOT NULL DEFAULT 0"},
|
||||
{"last_heartbeat", "ALTER TABLE devices ADD COLUMN last_heartbeat INTEGER NOT NULL DEFAULT 0"},
|
||||
{"offline_at", "ALTER TABLE devices ADD COLUMN offline_at INTEGER"},
|
||||
{"profile_json", "ALTER TABLE devices ADD COLUMN profile_json TEXT"},
|
||||
{"created_at", "ALTER TABLE devices ADD COLUMN created_at INTEGER NOT NULL DEFAULT 0"},
|
||||
}
|
||||
for _, m := range migrations {
|
||||
if !cols[m.name] {
|
||||
if _, err := s.DB.Exec(m.sql); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
_, err = s.DB.Exec("UPDATE devices SET created_at=CASE WHEN created_at=0 THEN updated_at ELSE created_at END, " +
|
||||
"last_seen=CASE WHEN last_seen=0 THEN updated_at ELSE last_seen END, " +
|
||||
"last_heartbeat=CASE WHEN last_heartbeat=0 THEN updated_at ELSE last_heartbeat END " +
|
||||
"WHERE created_at=0 OR last_seen=0 OR last_heartbeat=0")
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) UpsertLocal(name, arch, osName string) error {
|
||||
_, err := s.DB.Exec(`INSERT INTO devices(name,status,is_local,arch,os,updated_at)
|
||||
VALUES(?,?,?,?,?,?) ON CONFLICT(name) DO UPDATE SET status=excluded.status,
|
||||
arch=excluded.arch, os=excluded.os, updated_at=excluded.updated_at`,
|
||||
name, "online", 1, arch, osName, time.Now().Unix())
|
||||
now := time.Now().Unix()
|
||||
_, err := s.DB.Exec("INSERT INTO devices(name,status,is_local,arch,os,last_seen,last_heartbeat,offline_at,profile_json,created_at,updated_at) "+
|
||||
"VALUES(?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(name) DO UPDATE SET status='online', is_local=1, arch=excluded.arch, os=excluded.os, offline_at=NULL, updated_at=excluded.updated_at",
|
||||
name, "online", 1, arch, osName, now, now, nil, nil, now, now)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) UpsertRemote(name, status, arch, osName string, lastHeartbeat int64, profileJSON string) error {
|
||||
now := time.Now().Unix()
|
||||
if lastHeartbeat <= 0 {
|
||||
lastHeartbeat = now
|
||||
}
|
||||
_, err := s.DB.Exec("INSERT INTO devices(name,status,is_local,arch,os,last_seen,last_heartbeat,offline_at,profile_json,created_at,updated_at) "+
|
||||
"VALUES(?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(name) DO UPDATE SET status=excluded.status, is_local=0, arch=excluded.arch, os=excluded.os, "+
|
||||
"last_seen=excluded.last_seen, last_heartbeat=excluded.last_heartbeat, offline_at=NULL, profile_json=excluded.profile_json, updated_at=excluded.updated_at",
|
||||
name, status, 0, arch, osName, lastHeartbeat, lastHeartbeat, nil, profileJSON, now, now)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) UpdateRemoteProfile(name string, lastHeartbeat int64, arch, osName, profileJSON string) error {
|
||||
now := time.Now().Unix()
|
||||
if lastHeartbeat <= 0 {
|
||||
lastHeartbeat = now
|
||||
}
|
||||
_, err := s.DB.Exec("UPDATE devices SET status='online', arch=?, os=?, last_seen=?, last_heartbeat=?, offline_at=NULL, profile_json=?, updated_at=? WHERE name=? AND is_local=0",
|
||||
arch, osName, lastHeartbeat, lastHeartbeat, profileJSON, now, name)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) UpdateDeviceStatus(name, status string, lastHeartbeat int64) error {
|
||||
now := time.Now().Unix()
|
||||
if lastHeartbeat <= 0 {
|
||||
lastHeartbeat = now
|
||||
}
|
||||
var offlineAt any
|
||||
if status == "offline" {
|
||||
offlineAt = now
|
||||
}
|
||||
_, err := s.DB.Exec("UPDATE devices SET status=?, last_seen=?, last_heartbeat=?, offline_at=?, updated_at=? WHERE name=? AND is_local=0",
|
||||
status, lastHeartbeat, lastHeartbeat, offlineAt, now, name)
|
||||
return err
|
||||
}
|
||||
|
||||
type DeviceRecord struct {
|
||||
Name, Status, Arch, OS, ProfileJSON string
|
||||
IsLocal bool
|
||||
LastSeen, LastHeartbeat int64
|
||||
OfflineAt *int64
|
||||
UpdatedAt int64
|
||||
}
|
||||
|
||||
func (s *Store) ListDevices() ([]DeviceRecord, error) {
|
||||
rows, err := s.DB.Query("SELECT name,status,is_local,COALESCE(arch,''),COALESCE(os,''),last_seen,last_heartbeat,offline_at,COALESCE(profile_json,''),updated_at FROM devices ORDER BY name")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []DeviceRecord
|
||||
for rows.Next() {
|
||||
var d DeviceRecord
|
||||
var local int
|
||||
var offline sql.NullInt64
|
||||
if err := rows.Scan(&d.Name, &d.Status, &local, &d.Arch, &d.OS, &d.LastSeen, &d.LastHeartbeat, &offline, &d.ProfileJSON, &d.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.IsLocal = local != 0
|
||||
if offline.Valid {
|
||||
v := offline.Int64
|
||||
d.OfflineAt = &v
|
||||
}
|
||||
out = append(out, d)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) DeleteDevice(name string) error {
|
||||
_, err := s.DB.Exec("DELETE FROM devices WHERE name=? AND is_local=0", name)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -68,12 +279,69 @@ type AuditLog struct {
|
||||
ErrorMsg string `json:"error_msg"`
|
||||
}
|
||||
|
||||
var auditSecretRE = regexp.MustCompile(`(?i)(authorization|bearer|token|api[_-]?key|password|secret|cookie)(\s*[:=]\s+)([^\s,;]+)`)
|
||||
|
||||
func redactAudit(v string) string {
|
||||
v = auditSecretRE.ReplaceAllString(v, `$1$2[REDACTED]`)
|
||||
v = strings.ReplaceAll(v, "\r", " ")
|
||||
v = strings.ReplaceAll(v, "\n", " ")
|
||||
if len(v) > 8192 {
|
||||
v = v[:8192]
|
||||
}
|
||||
return v
|
||||
}
|
||||
func (s *Store) Audit(ip, device, action, command string, code int, ms int64, msg string) error {
|
||||
_, err := s.DB.Exec(`INSERT INTO audit_logs(timestamp,caller_ip,device,action,command,exit_code,duration_ms,error_msg)
|
||||
VALUES(?,?,?,?,?,?,?,?)`, time.Now().Unix(), ip, device, action, command, code, ms, msg)
|
||||
_, err := s.DB.Exec("INSERT INTO audit_logs(timestamp,caller_ip,device,action,command,exit_code,duration_ms,error_msg) VALUES(?,?,?,?,?,?,?,?)",
|
||||
time.Now().Unix(), ip, device, action, redactAudit(command), code, ms, redactAudit(msg))
|
||||
return err
|
||||
}
|
||||
|
||||
type WebhookTarget struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
URL string `json:"url"`
|
||||
Config string `json:"config_json"`
|
||||
Enabled bool `json:"enabled"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (s *Store) SaveWebhookTarget(v WebhookTarget) error {
|
||||
now := time.Now().Unix()
|
||||
if v.ID == "" || v.Name == "" || v.Type == "" || v.URL == "" {
|
||||
return errors.New("id, name, type and url required")
|
||||
}
|
||||
if v.CreatedAt <= 0 {
|
||||
v.CreatedAt = now
|
||||
}
|
||||
v.UpdatedAt = now
|
||||
_, err := s.DB.Exec(`INSERT INTO webhook_targets(id,name,type,url,config_json,enabled,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,type=excluded.type,url=excluded.url,config_json=excluded.config_json,enabled=excluded.enabled,updated_at=excluded.updated_at`, v.ID, v.Name, v.Type, v.URL, v.Config, boolInt(v.Enabled), v.CreatedAt, v.UpdatedAt)
|
||||
return err
|
||||
}
|
||||
func (s *Store) DeleteWebhookTarget(id string) error {
|
||||
_, err := s.DB.Exec(`DELETE FROM webhook_targets WHERE id=?`, id)
|
||||
return err
|
||||
}
|
||||
func (s *Store) ListWebhookTargets() ([]WebhookTarget, error) {
|
||||
rows, err := s.DB.Query(`SELECT id,name,type,url,COALESCE(config_json,''),enabled,created_at,updated_at FROM webhook_targets ORDER BY id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []WebhookTarget{}
|
||||
for rows.Next() {
|
||||
var v WebhookTarget
|
||||
var en int
|
||||
if err := rows.Scan(&v.ID, &v.Name, &v.Type, &v.URL, &v.Config, &en, &v.CreatedAt, &v.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v.Enabled = en != 0
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) RecentAudits(limit int) ([]AuditLog, error) {
|
||||
if limit <= 0 {
|
||||
limit = 100
|
||||
@@ -81,8 +349,7 @@ func (s *Store) RecentAudits(limit int) ([]AuditLog, error) {
|
||||
if limit > 500 {
|
||||
limit = 500
|
||||
}
|
||||
rows, err := s.DB.Query(`SELECT id,timestamp,caller_ip,device,action,command,exit_code,duration_ms,error_msg
|
||||
FROM audit_logs ORDER BY id DESC LIMIT ?`, limit)
|
||||
rows, err := s.DB.Query("SELECT id,timestamp,caller_ip,device,action,command,exit_code,duration_ms,error_msg FROM audit_logs ORDER BY id DESC LIMIT ?", limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -98,29 +365,231 @@ func (s *Store) RecentAudits(limit int) ([]AuditLog, error) {
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) InitRevocationTable() error {
|
||||
_, err := s.DB.Exec(`CREATE TABLE IF NOT EXISTS revoked_devices (
|
||||
name TEXT PRIMARY KEY,
|
||||
revoked_at INTEGER NOT NULL,
|
||||
reason TEXT
|
||||
);`)
|
||||
func (s *Store) RevokeDevice(name, reason string) error {
|
||||
tx, err := s.DB.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) RevokeDevice(name, reason string) error {
|
||||
_, err := s.DB.Exec(`INSERT INTO revoked_devices(name, revoked_at, reason)
|
||||
VALUES(?, ?, ?) ON CONFLICT(name) DO UPDATE SET revoked_at=excluded.revoked_at, reason=excluded.reason`,
|
||||
name, time.Now().Unix(), reason)
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.Exec("INSERT INTO revoked_devices(name,revoked_at,reason) VALUES(?,?,?) ON CONFLICT(name) DO UPDATE SET revoked_at=excluded.revoked_at,reason=excluded.reason",
|
||||
name, time.Now().Unix(), reason); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec("DELETE FROM devices WHERE name=? AND is_local=0", name); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) UnrevokeDevice(name string) error {
|
||||
_, err := s.DB.Exec(`DELETE FROM revoked_devices WHERE name = ?`, name)
|
||||
_, err := s.DB.Exec("DELETE FROM revoked_devices WHERE name = ?", name)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) IsRevoked(name string) (bool, error) {
|
||||
var count int
|
||||
err := s.DB.QueryRow(`SELECT COUNT(*) FROM revoked_devices WHERE name = ?`, name).Scan(&count)
|
||||
err := s.DB.QueryRow("SELECT COUNT(*) FROM revoked_devices WHERE name = ?", name).Scan(&count)
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
func normalizeSecurityMode(mode string) string {
|
||||
mode = strings.ToLower(strings.TrimSpace(mode))
|
||||
switch mode {
|
||||
case "inherit", "low", "medium", "high":
|
||||
return mode
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type SecurityPolicyState struct {
|
||||
GlobalMode string
|
||||
Nodes map[string]string
|
||||
Version uint64
|
||||
}
|
||||
|
||||
func (s *Store) LoadSecurityPolicy() (SecurityPolicyState, error) {
|
||||
state := SecurityPolicyState{GlobalMode: "medium", Nodes: map[string]string{}, Version: 1}
|
||||
if err := s.DB.QueryRow("SELECT mode FROM security_settings WHERE node_name='' LIMIT 1").Scan(&state.GlobalMode); err != nil && err != sql.ErrNoRows {
|
||||
return state, err
|
||||
}
|
||||
if m := normalizeSecurityMode(state.GlobalMode); m != "" && m != "inherit" {
|
||||
state.GlobalMode = m
|
||||
} else {
|
||||
state.GlobalMode = "medium"
|
||||
}
|
||||
var version int64
|
||||
if err := s.DB.QueryRow("SELECT version FROM security_policy_meta WHERE id=1").Scan(&version); err != nil {
|
||||
return state, err
|
||||
}
|
||||
if version > 0 {
|
||||
state.Version = uint64(version)
|
||||
}
|
||||
rows, err := s.DB.Query("SELECT node_name,mode FROM security_settings WHERE node_name<>''")
|
||||
if err != nil {
|
||||
return state, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var node, mode string
|
||||
if err := rows.Scan(&node, &mode); err != nil {
|
||||
return state, err
|
||||
}
|
||||
if m := normalizeSecurityMode(mode); m != "" {
|
||||
state.Nodes[node] = m
|
||||
}
|
||||
}
|
||||
return state, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) bumpSecurityPolicyVersion(tx *sql.Tx) error {
|
||||
_, err := tx.Exec("UPDATE security_policy_meta SET version=version+1 WHERE id=1")
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) SecurityPolicyVersion() uint64 {
|
||||
var version int64
|
||||
if err := s.DB.QueryRow("SELECT version FROM security_policy_meta WHERE id=1").Scan(&version); err != nil || version < 1 {
|
||||
return 1
|
||||
}
|
||||
return uint64(version)
|
||||
}
|
||||
|
||||
func (s *Store) GetGlobalSecurityMode() string {
|
||||
var mode string
|
||||
err := s.DB.QueryRow("SELECT mode FROM security_settings WHERE node_name='' LIMIT 1").Scan(&mode)
|
||||
if err != nil {
|
||||
return "medium"
|
||||
}
|
||||
if m := normalizeSecurityMode(mode); m != "" && m != "inherit" {
|
||||
return m
|
||||
}
|
||||
return "medium"
|
||||
}
|
||||
|
||||
func (s *Store) SetGlobalSecurityMode(mode string) error {
|
||||
mode = normalizeSecurityMode(mode)
|
||||
if mode == "" || mode == "inherit" {
|
||||
return errors.New("invalid global security mode")
|
||||
}
|
||||
tx, err := s.DB.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err = tx.Exec("INSERT INTO security_settings(node_name,mode,updated_at) VALUES('',?,?) ON CONFLICT(node_name) DO UPDATE SET mode=excluded.mode,updated_at=excluded.updated_at", mode, time.Now().Unix()); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = s.bumpSecurityPolicyVersion(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (s *Store) GetNodeSecurityMode(node string) (string, bool) {
|
||||
var mode string
|
||||
err := s.DB.QueryRow("SELECT mode FROM security_settings WHERE node_name=?", node).Scan(&mode)
|
||||
if err != nil {
|
||||
return "inherit", false
|
||||
}
|
||||
m := normalizeSecurityMode(mode)
|
||||
if m == "" {
|
||||
return "inherit", false
|
||||
}
|
||||
return m, true
|
||||
}
|
||||
|
||||
func (s *Store) SetNodeSecurityMode(node, mode string) error {
|
||||
if node == "" {
|
||||
return errors.New("node name required")
|
||||
}
|
||||
mode = normalizeSecurityMode(mode)
|
||||
if mode == "" {
|
||||
return errors.New("invalid security mode")
|
||||
}
|
||||
tx, err := s.DB.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err = tx.Exec("INSERT INTO security_settings(node_name,mode,updated_at) VALUES(?,?,?) ON CONFLICT(node_name) DO UPDATE SET mode=excluded.mode,updated_at=excluded.updated_at", node, mode, time.Now().Unix()); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = s.bumpSecurityPolicyVersion(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
type SecuritySetting struct {
|
||||
Node string `json:"node"`
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
|
||||
func (s *Store) ListNodeSecurityModes() ([]SecuritySetting, error) {
|
||||
rows, err := s.DB.Query("SELECT node_name,mode FROM security_settings WHERE node_name<>'' ORDER BY node_name")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []SecuritySetting{}
|
||||
for rows.Next() {
|
||||
var v SecuritySetting
|
||||
if err := rows.Scan(&v.Node, &v.Mode); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func hashDeviceToken(token string) string {
|
||||
h := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
// SetDeviceCredential stores only a SHA-256 hash of the per-device token.
|
||||
func (s *Store) DeviceCredentialConfigured(name string) (bool, error) {
|
||||
return s.HasDeviceCredential(name)
|
||||
}
|
||||
|
||||
func (s *Store) SetDeviceCredential(name, token string) error {
|
||||
if strings.TrimSpace(name) == "" || token == "" {
|
||||
return errors.New("device name and token required")
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
_, err := s.DB.Exec(`INSERT INTO device_credentials(name,token_hash,created_at,updated_at)
|
||||
VALUES(?,?,?,?) ON CONFLICT(name) DO UPDATE SET token_hash=excluded.token_hash,updated_at=excluded.updated_at`, name, hashDeviceToken(token), now, now)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) VerifyDeviceCredential(name, token string) (bool, error) {
|
||||
if name == "" || token == "" {
|
||||
return false, nil
|
||||
}
|
||||
var stored string
|
||||
err := s.DB.QueryRow("SELECT token_hash FROM device_credentials WHERE name=?", name).Scan(&stored)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return subtleConstantTimeEqual(stored, hashDeviceToken(token)), nil
|
||||
}
|
||||
|
||||
func subtleConstantTimeEqual(a, b string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
var v byte
|
||||
for i := range a {
|
||||
v |= a[i] ^ b[i]
|
||||
}
|
||||
return v == 0
|
||||
}
|
||||
|
||||
func (s *Store) HasDeviceCredential(name string) (bool, error) {
|
||||
var count int
|
||||
err := s.DB.QueryRow("SELECT COUNT(*) FROM device_credentials WHERE name=?", name).Scan(&count)
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
@@ -58,3 +58,38 @@ func TestAuditConcurrent100NoLoss(t *testing.T) {
|
||||
t.Fatalf("busy_timeout=%d, want >=5000", busy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeviceCredentialHashAndRotation(t *testing.T) {
|
||||
s, err := Open(filepath.Join(t.TempDir(), "commander.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.DB.Close()
|
||||
|
||||
if err := s.SetDeviceCredential("node-1", "secret-one"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
configured, err := s.HasDeviceCredential("node-1")
|
||||
if err != nil || !configured {
|
||||
t.Fatalf("credential should be configured: %v", err)
|
||||
}
|
||||
valid, err := s.VerifyDeviceCredential("node-1", "secret-one")
|
||||
if err != nil || !valid {
|
||||
t.Fatalf("valid credential rejected: %v", err)
|
||||
}
|
||||
valid, err = s.VerifyDeviceCredential("node-1", "wrong")
|
||||
if err != nil || valid {
|
||||
t.Fatal("wrong credential accepted")
|
||||
}
|
||||
if err := s.SetDeviceCredential("node-1", "secret-two"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
valid, err = s.VerifyDeviceCredential("node-1", "secret-one")
|
||||
if err != nil || valid {
|
||||
t.Fatal("old credential accepted after rotation")
|
||||
}
|
||||
valid, err = s.VerifyDeviceCredential("node-1", "secret-two")
|
||||
if err != nil || !valid {
|
||||
t.Fatal("rotated credential rejected")
|
||||
}
|
||||
}
|
||||
|
||||
+134
-21
@@ -7,15 +7,37 @@ import (
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
var netMu sync.Mutex
|
||||
var lastNet = struct {
|
||||
rx, tx uint64
|
||||
at time.Time
|
||||
}{}
|
||||
|
||||
var cpuMu sync.Mutex
|
||||
var lastCPU = struct {
|
||||
idle, total uint64
|
||||
at time.Time
|
||||
usage int
|
||||
}{}
|
||||
|
||||
type Profile struct {
|
||||
Role string `json:"role,omitempty"`
|
||||
CPUCores int `json:"cpu_cores"`
|
||||
CPUUsagePercent int `json:"cpu_usage_percent"`
|
||||
Load1M float64 `json:"load_1m"`
|
||||
Load5M float64 `json:"load_5m"`
|
||||
Load15M float64 `json:"load_15m"`
|
||||
NetRXRate float64 `json:"net_rx_rate"`
|
||||
NetTXRate float64 `json:"net_tx_rate"`
|
||||
NetRXTotal uint64 `json:"net_rx_total"`
|
||||
NetTXTotal uint64 `json:"net_tx_total"`
|
||||
UptimeSeconds float64 `json:"uptime_seconds"`
|
||||
BootTime int64 `json:"boot_time"`
|
||||
MemPercent int `json:"mem_percent"`
|
||||
MemAvailable string `json:"mem_available"`
|
||||
DiskPercent int `json:"disk_percent"`
|
||||
@@ -36,7 +58,9 @@ func Collect(defaultRole string) Profile {
|
||||
|
||||
cores := runtime.NumCPU()
|
||||
cpuPercent := getCPUUsage()
|
||||
load1m := getLoad1M()
|
||||
load1m, load5m, load15m := getLoads()
|
||||
netRX, netTX, netRXT, netTXT := getNetwork()
|
||||
uptime, boot := getUptime()
|
||||
memPct, memAvl := getMemInfo()
|
||||
diskPct, diskFree := getDiskInfo()
|
||||
psi := getIOPSI()
|
||||
@@ -47,6 +71,14 @@ func Collect(defaultRole string) Profile {
|
||||
CPUCores: cores,
|
||||
CPUUsagePercent: cpuPercent,
|
||||
Load1M: load1m,
|
||||
Load5M: load5m,
|
||||
Load15M: load15m,
|
||||
NetRXRate: netRX,
|
||||
NetTXRate: netTX,
|
||||
NetRXTotal: netRXT,
|
||||
NetTXTotal: netTXT,
|
||||
UptimeSeconds: uptime,
|
||||
BootTime: boot,
|
||||
MemPercent: memPct,
|
||||
MemAvailable: memAvl,
|
||||
DiskPercent: diskPct,
|
||||
@@ -57,16 +89,70 @@ func Collect(defaultRole string) Profile {
|
||||
}
|
||||
}
|
||||
|
||||
func getLoad1M() float64 {
|
||||
if data, err := os.ReadFile("/proc/loadavg"); err == nil {
|
||||
fields := strings.Fields(string(data))
|
||||
if len(fields) > 0 {
|
||||
if val, err := strconv.ParseFloat(fields[0], 64); err == nil {
|
||||
return val
|
||||
func getLoads() (float64, float64, float64) {
|
||||
data, err := os.ReadFile("/proc/loadavg")
|
||||
if err != nil {
|
||||
return 0, 0, 0
|
||||
}
|
||||
f := strings.Fields(string(data))
|
||||
if len(f) < 3 {
|
||||
return 0, 0, 0
|
||||
}
|
||||
v := func(i int) float64 { x, _ := strconv.ParseFloat(f[i], 64); return x }
|
||||
return v(0), v(1), v(2)
|
||||
}
|
||||
|
||||
func getNetwork() (float64, float64, uint64, uint64) {
|
||||
data, err := os.ReadFile("/proc/net/dev")
|
||||
if err != nil {
|
||||
return 0, 0, 0, 0
|
||||
}
|
||||
var rx, tx uint64
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
parts := strings.SplitN(line, ":", 2)
|
||||
if len(parts) != 2 || strings.TrimSpace(parts[0]) == "lo" {
|
||||
continue
|
||||
}
|
||||
f := strings.Fields(parts[1])
|
||||
if len(f) < 9 {
|
||||
continue
|
||||
}
|
||||
r, e1 := strconv.ParseUint(f[0], 10, 64)
|
||||
t, e2 := strconv.ParseUint(f[8], 10, 64)
|
||||
if e1 == nil && e2 == nil {
|
||||
rx += r
|
||||
tx += t
|
||||
}
|
||||
}
|
||||
now := time.Now()
|
||||
netMu.Lock()
|
||||
defer netMu.Unlock()
|
||||
var rr, tr float64
|
||||
if !lastNet.at.IsZero() && now.After(lastNet.at) && rx >= lastNet.rx && tx >= lastNet.tx {
|
||||
d := now.Sub(lastNet.at).Seconds()
|
||||
if d > 0 {
|
||||
rr = float64(rx-lastNet.rx) / d
|
||||
tr = float64(tx-lastNet.tx) / d
|
||||
}
|
||||
return 0.0
|
||||
}
|
||||
lastNet.rx, lastNet.tx, lastNet.at = rx, tx, now
|
||||
return rr, tr, rx, tx
|
||||
}
|
||||
|
||||
func getUptime() (float64, int64) {
|
||||
data, err := os.ReadFile("/proc/uptime")
|
||||
if err != nil {
|
||||
return 0, time.Now().Unix()
|
||||
}
|
||||
f := strings.Fields(string(data))
|
||||
if len(f) == 0 {
|
||||
return 0, time.Now().Unix()
|
||||
}
|
||||
u, err := strconv.ParseFloat(f[0], 64)
|
||||
if err != nil {
|
||||
return 0, time.Now().Unix()
|
||||
}
|
||||
return u, time.Now().Add(-time.Duration(u * float64(time.Second))).Unix()
|
||||
}
|
||||
|
||||
func getCPUUsage() int {
|
||||
@@ -116,20 +202,19 @@ func sampleCPUStat() int {
|
||||
return 0, 0, false
|
||||
}
|
||||
|
||||
idle1, total1, ok1 := readStat()
|
||||
if !ok1 {
|
||||
idleCurr, totalCurr, ok := readStat()
|
||||
if !ok {
|
||||
return -1
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
idle2, total2, ok2 := readStat()
|
||||
if !ok2 || total2 <= total1 {
|
||||
return -1
|
||||
}
|
||||
deltaTotal := total2 - total1
|
||||
deltaIdle := idle2 - idle1
|
||||
if deltaTotal == 0 {
|
||||
return 0
|
||||
}
|
||||
now := time.Now()
|
||||
|
||||
cpuMu.Lock()
|
||||
defer cpuMu.Unlock()
|
||||
|
||||
if lastCPU.total > 0 && totalCurr > lastCPU.total && now.Sub(lastCPU.at) >= 500*time.Millisecond {
|
||||
deltaTotal := totalCurr - lastCPU.total
|
||||
deltaIdle := idleCurr - lastCPU.idle
|
||||
if deltaTotal > 0 && deltaTotal >= deltaIdle {
|
||||
busy := float64(deltaTotal-deltaIdle) / float64(deltaTotal) * 100
|
||||
if busy < 0 {
|
||||
busy = 0
|
||||
@@ -137,7 +222,35 @@ func sampleCPUStat() int {
|
||||
if busy > 100 {
|
||||
busy = 100
|
||||
}
|
||||
return int(busy)
|
||||
lastCPU.usage = int(busy)
|
||||
lastCPU.idle = idleCurr
|
||||
lastCPU.total = totalCurr
|
||||
lastCPU.at = now
|
||||
return lastCPU.usage
|
||||
}
|
||||
}
|
||||
|
||||
if lastCPU.total == 0 {
|
||||
// 初次初始化基线
|
||||
lastCPU.idle = idleCurr
|
||||
lastCPU.total = totalCurr
|
||||
lastCPU.at = now
|
||||
// 用 200ms 短采样作为初始值
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
if idle2, total2, ok2 := readStat(); ok2 && total2 > totalCurr {
|
||||
dTotal := total2 - totalCurr
|
||||
dIdle := idle2 - idleCurr
|
||||
if dTotal > 0 && dTotal >= dIdle {
|
||||
busy := float64(dTotal-dIdle) / float64(dTotal) * 100
|
||||
lastCPU.usage = int(busy)
|
||||
lastCPU.idle = idle2
|
||||
lastCPU.total = total2
|
||||
lastCPU.at = time.Now()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return lastCPU.usage
|
||||
}
|
||||
|
||||
func getMemInfo() (memPct int, memAvl string) {
|
||||
|
||||
+139
-3
@@ -25,28 +25,146 @@ type Runner interface {
|
||||
|
||||
type Panel struct {
|
||||
Password string
|
||||
AdminToken string
|
||||
Runner Runner
|
||||
mu sync.RWMutex
|
||||
sessions map[string]time.Time
|
||||
}
|
||||
|
||||
func New(password string, runner Runner) *Panel {
|
||||
return &Panel{Password: password, Runner: runner, sessions: make(map[string]time.Time)}
|
||||
func New(password, adminToken string, runner Runner) *Panel {
|
||||
return &Panel{Password: password, AdminToken: adminToken, Runner: runner, sessions: make(map[string]time.Time)}
|
||||
}
|
||||
|
||||
func (p *Panel) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/panel/login", p.login)
|
||||
mux.HandleFunc("/panel/logout", p.logout)
|
||||
mux.HandleFunc("/panel", p.index)
|
||||
mux.HandleFunc("/panel/", p.index)
|
||||
mux.HandleFunc("/probe/summary", p.probeSummary)
|
||||
mux.HandleFunc("/static/", p.static)
|
||||
mux.HandleFunc("/panel/api/devices", p.protected(p.handleDevices))
|
||||
mux.HandleFunc("/panel/api/audits", p.protected(p.Runner.AuditsJSON))
|
||||
mux.HandleFunc("/panel/api/exec", p.protected(p.Runner.PanelExec))
|
||||
mux.HandleFunc("/panel/api/key/rotate", p.protected(p.Runner.RotateAPIKey))
|
||||
mux.HandleFunc("/", p.index)
|
||||
mux.HandleFunc("/panel/api/mcp/services", p.protected(p.mcpServices))
|
||||
mux.HandleFunc("/panel/api/mcp/service", p.protected(p.deleteMCPService))
|
||||
mux.HandleFunc("/panel/api/mcp/list", p.protected(p.listAgentMCP))
|
||||
mux.HandleFunc("/panel/api/mcp/call", p.protected(p.callAgentMCP))
|
||||
mux.HandleFunc("/panel/api/mcp/test", p.protected(p.testMCP))
|
||||
mux.HandleFunc("/panel/api/security/settings", p.protected(p.securitySettings))
|
||||
mux.HandleFunc("/panel/api/security/settings/update", p.protected(p.updateSecuritySettings))
|
||||
mux.HandleFunc("/panel/api/notifications/webhooks", p.protected(p.webhookTargets))
|
||||
mux.HandleFunc("/panel/api/notifications/webhook/update", p.protected(p.updateWebhookTarget))
|
||||
mux.HandleFunc("/panel/api/notifications/webhook/delete", p.protected(p.deleteWebhookTarget))
|
||||
mux.HandleFunc("/panel/api/notifications/webhook/test", p.protected(p.testWebhook))
|
||||
mux.HandleFunc("/", p.probe)
|
||||
return mux
|
||||
}
|
||||
|
||||
type securityPanelRunner interface {
|
||||
SecuritySettingsJSON(http.ResponseWriter, *http.Request)
|
||||
UpdateSecuritySettingsJSON(http.ResponseWriter, *http.Request)
|
||||
}
|
||||
|
||||
type mcpPanelRunner interface {
|
||||
MCPServicesJSON(http.ResponseWriter, *http.Request)
|
||||
DeleteMCPService(http.ResponseWriter, *http.Request)
|
||||
ListAgentMCPJSON(http.ResponseWriter, *http.Request)
|
||||
CallAgentMCPJSON(http.ResponseWriter, *http.Request)
|
||||
TestMCPJSON(http.ResponseWriter, *http.Request)
|
||||
}
|
||||
|
||||
func (p *Panel) mcpServices(w http.ResponseWriter, r *http.Request) {
|
||||
if v, ok := p.Runner.(mcpPanelRunner); ok {
|
||||
v.MCPServicesJSON(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "MCP API unavailable", 501)
|
||||
}
|
||||
func (p *Panel) deleteMCPService(w http.ResponseWriter, r *http.Request) {
|
||||
if v, ok := p.Runner.(mcpPanelRunner); ok {
|
||||
v.DeleteMCPService(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "MCP API unavailable", 501)
|
||||
}
|
||||
func (p *Panel) listAgentMCP(w http.ResponseWriter, r *http.Request) {
|
||||
if v, ok := p.Runner.(mcpPanelRunner); ok {
|
||||
v.ListAgentMCPJSON(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "MCP API unavailable", 501)
|
||||
}
|
||||
func (p *Panel) callAgentMCP(w http.ResponseWriter, r *http.Request) {
|
||||
if v, ok := p.Runner.(mcpPanelRunner); ok {
|
||||
v.CallAgentMCPJSON(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "MCP API unavailable", 501)
|
||||
}
|
||||
func (p *Panel) securitySettings(w http.ResponseWriter, r *http.Request) {
|
||||
if v, ok := p.Runner.(securityPanelRunner); ok {
|
||||
v.SecuritySettingsJSON(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "security API unavailable", 501)
|
||||
}
|
||||
func (p *Panel) updateSecuritySettings(w http.ResponseWriter, r *http.Request) {
|
||||
if p.AdminToken != "" {
|
||||
r.Header.Set("X-Admin-Token", p.AdminToken)
|
||||
}
|
||||
if v, ok := p.Runner.(securityPanelRunner); ok {
|
||||
v.UpdateSecuritySettingsJSON(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "security API unavailable", 501)
|
||||
}
|
||||
|
||||
func (p *Panel) testMCP(w http.ResponseWriter, r *http.Request) {
|
||||
if v, ok := p.Runner.(mcpPanelRunner); ok {
|
||||
v.TestMCPJSON(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "MCP API unavailable", 501)
|
||||
}
|
||||
|
||||
type notificationPanelRunner interface {
|
||||
WebhookTargetsJSON(http.ResponseWriter, *http.Request)
|
||||
UpdateWebhookTargetJSON(http.ResponseWriter, *http.Request)
|
||||
DeleteWebhookTargetJSON(http.ResponseWriter, *http.Request)
|
||||
TestWebhookJSON(http.ResponseWriter, *http.Request)
|
||||
}
|
||||
|
||||
func (p *Panel) webhookTargets(w http.ResponseWriter, r *http.Request) {
|
||||
if v, ok := p.Runner.(notificationPanelRunner); ok {
|
||||
v.WebhookTargetsJSON(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "notification API unavailable", 501)
|
||||
}
|
||||
func (p *Panel) updateWebhookTarget(w http.ResponseWriter, r *http.Request) {
|
||||
if v, ok := p.Runner.(notificationPanelRunner); ok {
|
||||
v.UpdateWebhookTargetJSON(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "notification API unavailable", 501)
|
||||
}
|
||||
func (p *Panel) deleteWebhookTarget(w http.ResponseWriter, r *http.Request) {
|
||||
if v, ok := p.Runner.(notificationPanelRunner); ok {
|
||||
v.DeleteWebhookTargetJSON(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "notification API unavailable", 501)
|
||||
}
|
||||
func (p *Panel) testWebhook(w http.ResponseWriter, r *http.Request) {
|
||||
if v, ok := p.Runner.(notificationPanelRunner); ok {
|
||||
v.TestWebhookJSON(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "notification API unavailable", 501)
|
||||
}
|
||||
|
||||
func (p *Panel) handleDevices(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodDelete {
|
||||
p.Runner.DeleteDevice(w, r)
|
||||
@@ -55,6 +173,24 @@ func (p *Panel) handleDevices(w http.ResponseWriter, r *http.Request) {
|
||||
p.Runner.DevicesJSON(w, r)
|
||||
}
|
||||
|
||||
func (p *Panel) probeSummary(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", 405)
|
||||
return
|
||||
}
|
||||
p.Runner.DevicesJSON(w, r)
|
||||
}
|
||||
|
||||
func (p *Panel) probe(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
data, _ := staticFS.ReadFile("static/probe.html")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
func (p *Panel) index(w http.ResponseWriter, r *http.Request) {
|
||||
if !p.valid(r) {
|
||||
http.Redirect(w, r, "/panel/login", http.StatusFound)
|
||||
|
||||
@@ -16,7 +16,7 @@ func (testRunner) RotateAPIKey(w http.ResponseWriter, r *http.Request) {}
|
||||
func (testRunner) DeleteDevice(w http.ResponseWriter, r *http.Request) {}
|
||||
|
||||
func TestStaticCSSContentType(t *testing.T) {
|
||||
p := New("test-password", testRunner{})
|
||||
p := New("test-password", "admin", testRunner{})
|
||||
req := httptest.NewRequest("GET", "/static/app.css", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
|
||||
+726
-35
@@ -1,40 +1,731 @@
|
||||
*{box-sizing:border-box}
|
||||
:root{color-scheme:dark;--bg-body:#0b1020;--bg-card:#111a2d;--bg-sub:#0d1526;--border:#24304a;--border-strong:#34415d;--text-main:#e7ebf3;--text-muted:#7f8ba3;--text-status:#9aabc5;--pre-text:#b9c5da;--thead:#91a0bb;--dot-online:#4ade80;--dot-offline:#f87171;--shadow:0 8px 30px rgba(0,0,0,.2)}
|
||||
:root[data-theme="light"]{color-scheme:light;--bg-body:#f4f6fa;--bg-card:#fff;--bg-sub:#eef2f7;--border:#d1d9e4;--border-strong:#b8c3d3;--text-main:#172033;--text-muted:#647089;--text-status:#58657a;--pre-text:#26344b;--thead:#53627a;--dot-online:#16833d;--dot-offline:#c62828;--shadow:0 8px 26px rgba(28,45,72,.08)}
|
||||
html,body{min-height:100%}body{margin:0;background:var(--bg-body);color:var(--text-main);font:14px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}header{min-height:64px;padding:0 24px;display:flex;align-items:center;justify-content:space-between;gap:14px;border-bottom:1px solid var(--border);background:var(--bg-card);position:sticky;top:0;z-index:2}
|
||||
.brand-wrap{display:flex;align-items:center;gap:12px;min-width:0}
|
||||
.brand-logo{width:36px;height:36px;border-radius:8px;object-fit:cover;flex:none;box-shadow:0 2px 8px rgba(0,0,0,.15)}
|
||||
header strong{font-size:18px}header span{margin-left:12px;color:var(--text-muted);font-size:12px}.header-actions{display:flex;align-items:center;gap:8px;flex-shrink:0}main{max-width:1400px;margin:auto;padding:22px}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.wide{grid-column:1/-1}.card{min-width:0;background:var(--bg-card);border:1px solid var(--border);border-radius:14px;padding:18px;box-shadow:var(--shadow)}.cardhead{display:flex;align-items:center;justify-content:space-between;gap:12px;min-width:0}.cardhead>h2{min-width:0}h2{margin:0 0 14px;font-size:16px}button,select,input,textarea{border:1px solid var(--border-strong);border-radius:9px;background:var(--bg-sub);color:var(--text-main);padding:9px 12px;font:inherit;max-width:100%}button{cursor:pointer}button:hover{filter:brightness(1.05)}button:focus-visible,select:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--border-strong);outline-offset:2px}textarea{width:100%;height:110px;resize:vertical;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;margin:8px 0}pre{white-space:pre-wrap;overflow:auto;background:var(--bg-sub);border:1px solid var(--border);border-radius:9px;padding:12px;color:var(--pre-text)}.devices{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px}.device{min-width:0;padding:14px;border:1px solid var(--border);border-radius:10px;background:var(--bg-sub)}.device b{display:block;min-width:0;overflow-wrap:anywhere;word-break:break-all}.dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--dot-online);vertical-align:middle;flex:none;margin-right:7px}.offline .dot{background:var(--dot-offline)}.muted{color:var(--text-muted)}.status{margin-top:3px;font-size:12px;color:var(--text-status);overflow-wrap:anywhere;word-break:break-word}.actions{display:flex;flex-wrap:wrap;gap:8px}.actions button{flex:1 1 150px}#device{min-width:180px}.tablewrap{width:100%;max-width:100%;overflow-x:auto;overscroll-behavior-x:contain}table{width:100%;min-width:760px;border-collapse:collapse}th,td{text-align:left;padding:9px;border-bottom:1px solid var(--border);font-size:12px;white-space:nowrap}th{color:var(--thead)}.login{display:grid;place-items:center;min-height:100vh;padding:20px}.login form{width:min(380px,90vw);background:var(--bg-card);border:1px solid var(--border);border-radius:16px;padding:28px;box-shadow:var(--shadow)}.login input,.login button{width:100%;margin-top:10px}.login h1{margin:0}.login p,#error{color:var(--text-muted)}
|
||||
@media(max-width:800px){.grid{grid-template-columns:1fr}.wide{grid-column:auto}main{padding:12px}header{padding:0 14px}.header-actions{gap:6px}.card{padding:15px}.cardhead{flex-wrap:wrap}.cardhead>#device{width:100%;min-width:0}.actions button{flex:1 1 140px}}
|
||||
@media(max-width:680px){header{align-items:flex-start;padding-top:12px;padding-bottom:12px}header span{display:none}.brand-wrap{padding-top:2px}.brand-logo{width:32px;height:32px}.header-actions{flex-direction:column;align-items:stretch;width:112px}.header-actions button{width:100%;padding:8px 9px}.devices{grid-template-columns:1fr}.cardhead{flex-direction:column;align-items:stretch;gap:8px}.cardhead h2{margin-bottom:0}.cardhead button,#device{width:100%;min-width:0}.actions button{flex:1 1 calc(50% - 4px)}}
|
||||
@media(max-width:450px){main{padding:9px}.card{padding:13px;border-radius:12px}.actions{display:grid;grid-template-columns:1fr 1fr}.actions button{width:100%;min-width:0}.login form{padding:22px}.header-actions{width:104px}}
|
||||
@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important}}
|
||||
/**
|
||||
* Apple Design System - VPS Commander Console (app.css)
|
||||
* Grounded in Apple HIG (macOS / iPadOS) & Liquid Glass Design Specs
|
||||
*/
|
||||
|
||||
/* 主题切换极简矢量图标按钮 */
|
||||
.btn-icon{display:inline-flex;align-items:center;justify-content:center;width:38px;height:38px;padding:0;border-radius:9px;background:var(--bg-sub);border:1px solid var(--border-strong);color:var(--text-main);cursor:pointer;transition:background .2s,border-color .2s}
|
||||
.btn-icon:hover{filter:brightness(1.1)}
|
||||
.theme-svg{display:none;width:18px;height:18px}
|
||||
:root[data-theme="dark"] .svg-sun{display:block;color:#facc15}
|
||||
:root[data-theme="light"] .svg-moon{display:block;color:#475569}
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
|
||||
/* 设备卡片与画像升级 (方案 1: 经典主副标题分行) */
|
||||
.devices{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:12px}
|
||||
.device-card{min-width:0;padding:16px;border:1px solid var(--border);border-radius:12px;background:var(--bg-sub);display:flex;flex-direction:column;gap:12px}
|
||||
/* macOS Dark Semantic Colors */
|
||||
--bg-body: #000000;
|
||||
--bg-card: #16181d;
|
||||
--bg-sub: #1f232b;
|
||||
--bg-input: #121418;
|
||||
|
||||
.v1-head{display:flex;flex-direction:column;gap:4px;min-width:0}
|
||||
.v1-row1{display:flex;align-items:center;justify-content:space-between;gap:8px;min-width:0}
|
||||
.v1-title{display:flex;align-items:center;gap:8px;min-width:0;flex:1}
|
||||
.v1-name{font-size:16px;font-weight:700;color:var(--text-main);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block}
|
||||
.v1-row2{font-size:12px;color:var(--text-muted);padding-left:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
--border: rgba(255, 255, 255, 0.08);
|
||||
--border-strong: rgba(255, 255, 255, 0.14);
|
||||
--border-subtle: rgba(255, 255, 255, 0.04);
|
||||
|
||||
.btn-revoke{padding:2px 8px;font-size:11px;border-radius:5px;background:transparent;border:1px solid var(--border-strong);color:var(--dot-offline);cursor:pointer;flex-shrink:0}
|
||||
.btn-revoke:hover{background:rgba(239,68,68,.15);border-color:var(--dot-offline)}
|
||||
--text-main: #f5f5f7;
|
||||
--text-muted: #86868b;
|
||||
--text-status: #a1a1a6;
|
||||
--pre-text: #e5e5ea;
|
||||
--thead: #86868b;
|
||||
|
||||
/* 资源画像 2列紧凑栅格 */
|
||||
.profile-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:6px 12px;padding:10px 12px;background:var(--bg-card);border:1px solid var(--border);border-radius:8px;font-size:12px}
|
||||
.p-item{display:flex;justify-content:space-between;align-items:center;gap:6px;min-height:20px}
|
||||
.p-label{color:var(--text-muted);font-weight:500;font-size:11px}
|
||||
.p-val{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;font-weight:600;font-size:12px;color:var(--text-main);white-space:nowrap}
|
||||
.badge-docker-text{padding:1px 6px;border-radius:4px;font-size:11px;font-weight:700}
|
||||
.badge-docker-text.yes{background:rgba(34,197,94,.15);color:var(--dot-online);border:1px solid rgba(34,197,94,.3)}
|
||||
.badge-docker-text.no{background:rgba(148,163,184,.15);color:var(--text-muted);border:1px solid var(--border)}
|
||||
--accent: #0a84ff;
|
||||
--accent-subtle: rgba(10, 132, 255, 0.15);
|
||||
--accent-hover: #0071e3;
|
||||
|
||||
--dot-online: #30d158;
|
||||
--dot-offline: #ff453a;
|
||||
--dot-warn: #ffd60a;
|
||||
|
||||
--shadow: 0 4px 20px rgba(0, 0, 0, 0.35);
|
||||
--shadow-hover: 0 8px 30px rgba(0, 0, 0, 0.5);
|
||||
|
||||
--font-system: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||
--font-mono: "SF Mono", ui-monospace, Menlo, Monaco, Consolas, monospace;
|
||||
|
||||
--card: var(--bg-card);
|
||||
--line: var(--border);
|
||||
|
||||
--radius-lg: 16px;
|
||||
--radius-md: 10px;
|
||||
--radius-sm: 6px;
|
||||
|
||||
--ease-apple: cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
|
||||
:root[data-theme="light"] {
|
||||
color-scheme: light;
|
||||
|
||||
/* macOS Light Semantic Colors */
|
||||
--bg-body: #f5f5f7;
|
||||
--bg-card: #ffffff;
|
||||
--bg-sub: #f0f0f4;
|
||||
--bg-input: #ffffff;
|
||||
|
||||
--border: rgba(0, 0, 0, 0.08);
|
||||
--border-strong: rgba(0, 0, 0, 0.14);
|
||||
--border-subtle: rgba(0, 0, 0, 0.04);
|
||||
|
||||
--text-main: #1d1d1f;
|
||||
--text-muted: #86868b;
|
||||
--text-status: #6e6e73;
|
||||
--pre-text: #1d1d1f;
|
||||
--thead: #86868b;
|
||||
|
||||
--accent: #0071e3;
|
||||
--accent-subtle: rgba(0, 113, 227, 0.12);
|
||||
--accent-hover: #0077ed;
|
||||
|
||||
--dot-online: #34c759;
|
||||
--dot-offline: #ff3b30;
|
||||
--dot-warn: #ff9500;
|
||||
|
||||
--shadow: 0 2px 14px rgba(0, 0, 0, 0.06);
|
||||
--shadow-hover: 0 6px 20px rgba(0, 0, 0, 0.12);
|
||||
|
||||
--card: var(--bg-card);
|
||||
--line: var(--border);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html, body {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg-body);
|
||||
color: var(--text-main);
|
||||
font: 13px/1.5 var(--font-system);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
macOS Style Header (Liquid Glass Floating Topbar)
|
||||
========================================================================== */
|
||||
header {
|
||||
min-height: 56px;
|
||||
padding: 0 24px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: rgba(22, 24, 29, 0.75);
|
||||
backdrop-filter: blur(24px) saturate(190%);
|
||||
-webkit-backdrop-filter: blur(24px) saturate(190%);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
transition: all 0.2s var(--ease-apple);
|
||||
}
|
||||
|
||||
:root[data-theme="light"] header {
|
||||
background: rgba(255, 255, 255, 0.8);
|
||||
}
|
||||
|
||||
.brand-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.brand-logo {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
object-fit: cover;
|
||||
flex: none;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
header strong {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.015em;
|
||||
color: var(--text-main);
|
||||
}
|
||||
|
||||
header span {
|
||||
margin-left: 10px;
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Main Grid Layout & Content Cards
|
||||
========================================================================== */
|
||||
main {
|
||||
max-width: 1400px;
|
||||
margin: auto;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.card {
|
||||
min-width: 0;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: 20px 22px;
|
||||
box-shadow: var(--shadow);
|
||||
transition: border-color 0.2s var(--ease-apple), box-shadow 0.2s var(--ease-apple);
|
||||
}
|
||||
|
||||
.cardhead {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.cardhead > h2 {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0 0 16px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.01em;
|
||||
color: var(--text-main);
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Controls: Buttons, Inputs, Selects
|
||||
========================================================================== */
|
||||
button, select, input, textarea {
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 8px;
|
||||
background: var(--bg-sub);
|
||||
color: var(--text-main);
|
||||
padding: 7px 12px;
|
||||
font-family: var(--font-system);
|
||||
font-size: 13px;
|
||||
max-width: 100%;
|
||||
transition: all 0.15s ease-out;
|
||||
}
|
||||
|
||||
button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
font-weight: 500;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background: var(--bg-card);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
button:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
button:focus-visible, select:focus-visible, input:focus-visible, textarea:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
/* Primary Action Buttons */
|
||||
#run, #mcpSave, #webhookSave, #saveGlobalSecurity {
|
||||
background: var(--accent);
|
||||
color: #ffffff;
|
||||
border-color: transparent;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
#run:hover, #mcpSave:hover, #webhookSave:hover, #saveGlobalSecurity:hover {
|
||||
background: var(--accent-hover);
|
||||
border-color: transparent;
|
||||
}
|
||||
|
||||
/* Secondary & Action Buttons */
|
||||
#logout {
|
||||
background: transparent;
|
||||
border-color: var(--border);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
#logout:hover {
|
||||
color: var(--dot-offline);
|
||||
border-color: rgba(255, 69, 58, 0.4);
|
||||
background: rgba(255, 69, 58, 0.1);
|
||||
}
|
||||
|
||||
/* Icon Button (Theme Toggle) */
|
||||
.btn-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
padding: 0;
|
||||
border-radius: 8px;
|
||||
background: var(--bg-sub);
|
||||
border: 1px solid var(--border);
|
||||
color: var(--text-main);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.btn-icon:hover {
|
||||
border-color: var(--border-strong);
|
||||
background: var(--bg-card);
|
||||
}
|
||||
|
||||
.theme-svg {
|
||||
display: none;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] .svg-sun {
|
||||
display: block;
|
||||
color: #ffd60a;
|
||||
}
|
||||
|
||||
:root[data-theme="light"] .svg-moon {
|
||||
display: block;
|
||||
color: #1d1d1f;
|
||||
}
|
||||
|
||||
/* Console & Code Blocks */
|
||||
textarea {
|
||||
width: 100%;
|
||||
height: 110px;
|
||||
resize: vertical;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
margin: 10px 0;
|
||||
background: var(--bg-input);
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
pre {
|
||||
white-space: pre-wrap;
|
||||
overflow: auto;
|
||||
background: var(--bg-input);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 14px;
|
||||
color: var(--pre-text);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Devices Grid & Cards (Content Layer)
|
||||
========================================================================== */
|
||||
.devices {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.device-card {
|
||||
min-width: 0;
|
||||
padding: 16px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
background: var(--bg-sub);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
|
||||
transition: transform 0.2s var(--ease-apple), border-color 0.2s var(--ease-apple);
|
||||
}
|
||||
|
||||
.device-card:hover {
|
||||
transform: translateY(-1.5px);
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
.v1-head {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.v1-row1 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.v1-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.v1-name {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.01em;
|
||||
color: var(--text-main);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.v1-row2 {
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
padding-left: 15px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.dot {
|
||||
display: inline-block;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--dot-online);
|
||||
vertical-align: middle;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.offline .dot {
|
||||
background: var(--dot-offline);
|
||||
}
|
||||
|
||||
.btn-revoke {
|
||||
padding: 2px 8px;
|
||||
font-size: 11px;
|
||||
border-radius: 5px;
|
||||
background: transparent;
|
||||
border: 1px solid var(--border);
|
||||
color: var(--dot-offline);
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.btn-revoke:hover {
|
||||
background: rgba(255, 69, 58, 0.14);
|
||||
border-color: var(--dot-offline);
|
||||
}
|
||||
|
||||
/* Node Profile Grid (Compact 2-Column Metrics) */
|
||||
.profile-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 6px 12px;
|
||||
padding: 10px 12px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.p-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-height: 20px;
|
||||
}
|
||||
|
||||
.p-label {
|
||||
color: var(--text-muted);
|
||||
font-weight: 500;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.p-val {
|
||||
font-family: var(--font-mono);
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
color: var(--text-main);
|
||||
white-space: nowrap;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.badge-docker-text {
|
||||
padding: 1px 6px;
|
||||
border-radius: 4px;
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.badge-docker-text.yes {
|
||||
background: rgba(48, 209, 88, 0.15);
|
||||
color: var(--dot-online);
|
||||
border: 1px solid rgba(48, 209, 88, 0.3);
|
||||
}
|
||||
|
||||
.badge-docker-text.no {
|
||||
background: rgba(142, 142, 147, 0.15);
|
||||
color: var(--text-muted);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.device-card.offline {
|
||||
opacity: 0.65;
|
||||
filter: saturate(0.5);
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
MCP Toolbar, Grid & Forms
|
||||
========================================================================== */
|
||||
.mcp-toolbar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.mcp-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.mcp-item {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 16px;
|
||||
background: var(--bg-sub);
|
||||
}
|
||||
|
||||
.mcp-item h3 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--text-main);
|
||||
}
|
||||
|
||||
.mcp-meta {
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.mcp-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
|
||||
.mcp-form {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.mcp-form .full {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.mcp-form label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.mcp-form input, .mcp-form select, .mcp-form textarea {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.mcp-form textarea {
|
||||
min-height: 72px;
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
.mcp-nodes {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
.mcp-nodes label {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.mcp-status {
|
||||
font-size: 12px;
|
||||
margin-top: 8px;
|
||||
min-height: 18px;
|
||||
}
|
||||
|
||||
.mcp-test-result {
|
||||
margin-top: 12px;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--bg-input);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.mcp-test-result.ok {
|
||||
border-color: rgba(48, 209, 88, 0.4);
|
||||
}
|
||||
|
||||
.mcp-test-result.fail {
|
||||
border-color: rgba(255, 69, 58, 0.4);
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Data Tables (macOS Table Standard)
|
||||
========================================================================== */
|
||||
.tablewrap {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
min-width: 760px;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
th, td {
|
||||
text-align: left;
|
||||
padding: 10px 14px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
th {
|
||||
background: var(--bg-sub);
|
||||
color: var(--thead);
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
td {
|
||||
color: var(--text-main);
|
||||
}
|
||||
|
||||
tr:last-child td {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
tr:hover td {
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
|
||||
/* Security Policies */
|
||||
.security-grid {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
align-items: flex-end;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.security-grid label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.security-grid button {
|
||||
height: 32px;
|
||||
}
|
||||
|
||||
/* Login Page (Apple Centered Card) */
|
||||
.login {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-height: 100vh;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.login form {
|
||||
width: min(360px, 90vw);
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: 32px 28px;
|
||||
box-shadow: var(--shadow-hover);
|
||||
}
|
||||
|
||||
.login input, .login button {
|
||||
width: 100%;
|
||||
margin-top: 14px;
|
||||
height: 38px;
|
||||
}
|
||||
|
||||
.login h1 {
|
||||
margin: 0 0 8px;
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.015em;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.login p, #error {
|
||||
color: var(--text-muted);
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
#error {
|
||||
color: var(--dot-offline);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* Responsive */
|
||||
@media (max-width: 800px) {
|
||||
.grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.wide {
|
||||
grid-column: auto;
|
||||
}
|
||||
main {
|
||||
padding: 16px 12px;
|
||||
}
|
||||
header {
|
||||
padding: 0 16px;
|
||||
}
|
||||
}
|
||||
|
||||
+287
-11
@@ -11,7 +11,8 @@ const $=s=>document.querySelector(s);
|
||||
})();
|
||||
|
||||
async function api(path,opt={}){
|
||||
let r=await fetch("/panel/api"+path,opt);
|
||||
const fetchOpt = Object.assign({ cache: "no-store" }, opt);
|
||||
let r=await fetch("/panel/api"+path, fetchOpt);
|
||||
if(r.status===401){location.href="/panel/login";throw Error("unauthorized")}
|
||||
if(!r.ok)throw Error(await r.text());
|
||||
return r.json()
|
||||
@@ -31,14 +32,11 @@ async function removeDevice(name){
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDevices(){
|
||||
let all=await api("/devices");
|
||||
let ds=all.filter(d=>!d.is_local);
|
||||
$("#devices").innerHTML=ds.map(d=>{
|
||||
function renderSingleCard(d) {
|
||||
const p = d.profile || {};
|
||||
const role = p.role || "APPLICATION";
|
||||
const isOnline = d.status === "online";
|
||||
const statusText = isOnline ? "在线" : "离线";
|
||||
const lastText = d.last_heartbeat ? new Date(d.last_heartbeat*1000).toLocaleString() : "";
|
||||
const archOs = (d.arch || d.os) ? `${esc(d.arch||"")}/${esc(d.os||"")} · ` : "";
|
||||
const cpuStr = p.cpu_cores ? `${p.cpu_cores}C · ${p.cpu_usage_percent ?? 0}%` : '-';
|
||||
const loadStr = p.load_1m !== undefined ? p.load_1m.toFixed(2) : '-';
|
||||
@@ -49,7 +47,6 @@ async function loadDevices(){
|
||||
const dockerClass = p.docker ? 'yes' : 'no';
|
||||
|
||||
return `
|
||||
<div class="device-card ${isOnline ? "online" : "offline"}">
|
||||
<div class="v1-head">
|
||||
<div class="v1-row1">
|
||||
<div class="v1-title">
|
||||
@@ -58,7 +55,7 @@ async function loadDevices(){
|
||||
</div>
|
||||
<button class="btn-revoke" onclick="removeDevice('${esc(d.name)}')">注销</button>
|
||||
</div>
|
||||
<div class="v1-row2">${archOs}${statusText}</div>
|
||||
<div class="v1-row2">${archOs}${statusText}${isOnline ? "" : (lastText ? " · 最后活跃: "+lastText : "")}</div>
|
||||
</div>
|
||||
<div class="profile-grid">
|
||||
<div class="p-item"><span class="p-label">CPU</span><span class="p-val">${cpuStr}</span></div>
|
||||
@@ -68,11 +65,43 @@ async function loadDevices(){
|
||||
<div class="p-item"><span class="p-label">IO PSI</span><span class="p-val">${psiStr}</span></div>
|
||||
<div class="p-item"><span class="p-label">DOCKER</span><span class="p-val badge-docker-text ${dockerClass}">${dockerVal}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
$("#device").innerHTML=ds.map(d=>'<option>'+esc(d.name)+'</option>').join("");
|
||||
async function loadDevices(){
|
||||
let all = await api("/devices");
|
||||
let ds = all.filter(d => !d.is_local);
|
||||
// 严格固定名称字典序排列,杜绝乱跳
|
||||
ds.sort((a, b) => String(a.name || "").localeCompare(String(b.name || "")));
|
||||
|
||||
const container = $("#devices");
|
||||
const currentCardElements = container.querySelectorAll(".device-card[data-node]");
|
||||
const currentNodes = Array.from(currentCardElements).map(el => el.getAttribute("data-node"));
|
||||
const newNodes = ds.map(d => d.name);
|
||||
|
||||
// 如果节点列表结构未变,采用就地局部更新,卡片物理位置丝毫不动
|
||||
const sameOrder = currentNodes.length === newNodes.length && currentNodes.every((n, i) => n === newNodes[i]);
|
||||
if (sameOrder) {
|
||||
ds.forEach(d => {
|
||||
const card = container.querySelector(`.device-card[data-node="${CSS.escape(d.name)}"]`);
|
||||
if (card) {
|
||||
const isOnline = d.status === "online";
|
||||
card.className = `device-card ${isOnline ? "online" : "offline"}`;
|
||||
card.innerHTML = renderSingleCard(d);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// 首次渲染或增删节点时渲染
|
||||
container.innerHTML = ds.map(d => {
|
||||
const isOnline = d.status === "online";
|
||||
return `<div class="device-card ${isOnline ? "online" : "offline"}" data-node="${esc(d.name)}">${renderSingleCard(d)}</div>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
// 保持控制台 select 选项
|
||||
const select = $("#device");
|
||||
const selectedVal = select.value;
|
||||
select.innerHTML = ds.map(d => `<option value="${esc(d.name)}" ${d.status==="offline" ? "disabled" : ""} ${d.name===selectedVal ? "selected" : ""}>${esc(d.name)}${d.status==="offline" ? " [离线]" : ""}</option>`).join("");
|
||||
}
|
||||
|
||||
async function loadAudits(){
|
||||
@@ -108,3 +137,250 @@ $("#logout").onclick=async()=>{
|
||||
location.href="/panel/login"
|
||||
};
|
||||
loadDevices().then(loadAudits).catch(console.error);
|
||||
|
||||
let mcpEditingId="";
|
||||
function mcpFieldError(id,message){
|
||||
const el=$("#"+id); el.classList.add("mcp-field-error"); el.title=message;
|
||||
const status=$("#mcpStatus"); status.textContent=message; status.style.color="#e05252";
|
||||
el.focus();
|
||||
}
|
||||
function mcpClearErrors(){
|
||||
["mcpId","mcpName","mcpCommand","mcpUrl","mcpArgs","mcpHeaders","mcpEnv"].forEach(id=>{const el=$("#"+id);if(el){el.classList.remove("mcp-field-error");el.removeAttribute("title")}});
|
||||
$("#mcpStatus").textContent=""; $("#mcpStatus").style.color="";
|
||||
}
|
||||
function parseMCPField(id,label,kind){
|
||||
const el=$("#"+id); let value;
|
||||
try{value=JSON.parse(el.value||"");}catch(e){mcpFieldError(id,label+" 必须是合法的 JSON "+kind+",请检查格式。");throw e}
|
||||
if(kind==="数组" && !Array.isArray(value)){mcpFieldError(id,label+" 必须是合法的 JSON 数组,如 []。");throw Error("invalid "+id)}
|
||||
if(kind==="对象" && (value===null||Array.isArray(value)||typeof value!=="object")){mcpFieldError(id,label+" 必须是合法的 JSON 对象,如 {}。");throw Error("invalid "+id)}
|
||||
return value;
|
||||
}
|
||||
function showMCPToast(message){
|
||||
let t=$("#mcpToast"); if(!t){t=document.createElement("div");t.id="mcpToast";t.style.cssText="position:fixed;right:18px;top:18px;z-index:9999;padding:10px 14px;border:1px solid var(--border);border-radius:8px;background:var(--bg-sub);box-shadow:0 8px 30px rgba(0,0,0,.25)";document.body.appendChild(t)}
|
||||
t.textContent=message; t.hidden=false; clearTimeout(t._timer); t._timer=setTimeout(()=>t.hidden=true,2600);
|
||||
}
|
||||
async function loadMCPServices(){
|
||||
const services=await api("/mcp/services");
|
||||
const allDevices=await api("/devices");
|
||||
const devices=allDevices.filter(d=>!d.is_local);
|
||||
$("#mcpTestNode").innerHTML='<option value="local">Hub 本机</option>'+devices.filter(d=>d.status==="online").map(d=>'<option value="'+esc(d.name)+'">'+esc(d.name)+'(在线)</option>').join("");
|
||||
$("#mcpNodes").innerHTML=devices.map(d=>`<label><input type="checkbox" value="${esc(d.name)}">${esc(d.name)}</label>`).join("");
|
||||
$("#mcpList").innerHTML=services.map(s=>`<div class="mcp-item"><h3>${esc(s.name)} <small>${esc(s.id)}</small></h3><div class="mcp-meta">${esc(s.transport)} · ${s.scope==='custom'?'指定节点':'全部节点'} · ${s.enabled?'启用':'停用'}${s.url?' · '+esc(s.url):s.command?' · '+esc(s.command):''}</div><div class="mcp-actions"><button type="button" onclick="editMCP('${esc(s.id)}')">编辑</button><button type="button" onclick="deleteMCP('${esc(s.id)}')">删除</button></div></div>`).join("")||'<div class="mcp-meta">暂无 MCP 服务配置。</div>';
|
||||
}
|
||||
function resetMCPForm(){
|
||||
mcpEditingId=""; $("#mcpEditor").hidden=false; $("#mcpId").disabled=false; ["mcpId","mcpName","mcpCommand","mcpUrl"].forEach(id=>$("#"+id).value=""); $("#mcpTransport").value="stdio"; $("#mcpEnabled").value="1"; $("#mcpArgs").value="[]"; $("#mcpHeaders").value="{}"; $("#mcpEnv").value="{}"; $("#mcpScope").value="all"; $("#mcpStatus").textContent=""; $("#mcpTestResult").hidden=true; $("#mcpTestResult").textContent=""; $("#mcpNodes").querySelectorAll("input").forEach(x=>x.checked=false);
|
||||
}
|
||||
async function editMCP(id){
|
||||
const services=await api("/mcp/services"); const s=services.find(x=>x.id===id); if(!s)return; resetMCPForm(); mcpEditingId=id; $("#mcpId").value=s.id; $("#mcpId").disabled=true; $("#mcpName").value=s.name||""; $("#mcpTransport").value=s.transport; $("#mcpEnabled").value=s.enabled?"1":"0"; $("#mcpCommand").value=s.command||""; $("#mcpUrl").value=s.url||""; $("#mcpArgs").value=s.args_json||"[]"; $("#mcpHeaders").value=s.headers_json||"{}"; $("#mcpEnv").value=s.env_json||"{}"; $("#mcpScope").value=s.scope||"all"; let nodes=[];try{nodes=JSON.parse(s.target_nodes_json||"[]")}catch(e){};$("#mcpNodes").querySelectorAll("input").forEach(x=>x.checked=nodes.includes(x.value));
|
||||
}
|
||||
async function deleteMCP(id){if(!confirm(`确认删除 MCP 服务 [${id}]?`))return;try{await api("/mcp/service?id="+encodeURIComponent(id),{method:"DELETE"});await loadMCPServices()}catch(e){alert("删除失败: "+e.message)}}
|
||||
$("#mcpNew").onclick=resetMCPForm; $("#mcpCancel").onclick=()=>$("#mcpEditor").hidden=true;
|
||||
$("#mcpSave").onclick=async()=>{
|
||||
mcpClearErrors();
|
||||
try{
|
||||
const transport=$("#mcpTransport").value;
|
||||
const body={id:$("#mcpId").value.trim(),name:$("#mcpName").value.trim(),transport,command:$("#mcpCommand").value.trim(),url:$("#mcpUrl").value.trim(),scope:$("#mcpScope").value,enabled:$("#mcpEnabled").value==="1",args:parseMCPField("mcpArgs","Arguments","数组"),headers:parseMCPField("mcpHeaders","Headers","对象"),env:parseMCPField("mcpEnv","环境变量","对象"),target_nodes:[...$("#mcpNodes").querySelectorAll("input:checked")].map(x=>x.value)};
|
||||
if(!body.id){mcpFieldError("mcpId","服务标识不能为空。");return}
|
||||
if(!body.name){mcpFieldError("mcpName","显示名称不能为空。");return}
|
||||
if(transport==="stdio"&&!body.command){mcpFieldError("mcpCommand","stdio 模式必须填写 Command。");return}
|
||||
if(transport!=="stdio"&&!body.url){mcpFieldError("mcpUrl","HTTP/SSE 模式必须填写 URL。");return}
|
||||
await api("/mcp/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});
|
||||
showMCPToast("MCP ["+body.id+"] 已保存并同步到在线节点");
|
||||
$("#mcpEditor").hidden=true;
|
||||
await loadMCPServices();
|
||||
}catch(e){if(!$("#mcpStatus").textContent)$("#mcpStatus").textContent="保存失败: "+e.message}
|
||||
};
|
||||
$("#mcpTest").onclick=async()=>{
|
||||
mcpClearErrors();
|
||||
const result=$("#mcpTestResult"); result.hidden=false; result.className="mcp-test-result"; result.textContent="正在测试连通性…";
|
||||
try{
|
||||
const transport=$("#mcpTransport").value;
|
||||
const service={id:$("#mcpId").value.trim(),name:$("#mcpName").value.trim(),transport,command:$("#mcpCommand").value.trim(),url:$("#mcpUrl").value.trim(),args:parseMCPField("mcpArgs","Arguments","数组"),headers:parseMCPField("mcpHeaders","Headers","对象"),env:parseMCPField("mcpEnv","环境变量","对象")};
|
||||
if(transport==="stdio"&&!service.command){mcpFieldError("mcpCommand","stdio 模式必须填写 Command。");result.hidden=true;return}
|
||||
if(transport!=="stdio"&&!service.url){mcpFieldError("mcpUrl","HTTP/SSE 模式必须填写 URL。");result.hidden=true;return}
|
||||
let node=$("#mcpTestNode").value;
|
||||
if(node==="auto"||!node){const ds=(await api("/devices")).filter(d=>d.status==="online");node=ds.find(d=>!d.is_local)?.name||"local"}
|
||||
const x=await api("/mcp/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device:node,service})});
|
||||
if(!x.success)throw Error((x.error&&x.error.message)||"连通失败");
|
||||
result.className="mcp-test-result ok";
|
||||
result.innerHTML="<strong>✓ 连通成功!</strong> "+esc(x.device)+" · "+esc(x.transport)+" · "+x.duration_ms+"ms · 检测到 "+x.tool_count+" 个可用工具";
|
||||
if(x.tool_count){result.innerHTML+='<ul class="mcp-test-tools">'+x.tools.map(t=>"<li><code>"+esc(t.name||"")+"</code>"+(t.description?" — "+esc(t.description):"")+"</li>").join("")+"</ul>"}
|
||||
}catch(e){
|
||||
result.className="mcp-test-result fail";
|
||||
result.innerHTML='<strong>✗ 连通失败</strong><div class="mcp-test-detail">'+esc(e.message)+"</div>";
|
||||
}
|
||||
};
|
||||
$("#mcpTransport").onchange=()=>{const stdio=$("#mcpTransport").value==="stdio";$("#mcpCommand").parentElement.style.display=stdio?"":"none";$("#mcpArgs").parentElement.style.display=stdio?"":"none";$("#mcpUrl").parentElement.style.display=stdio?"none":""};
|
||||
loadMCPServices().catch(console.error);
|
||||
|
||||
async function loadSecuritySettings(){const x=await api("/security/settings"),nodes=x.nodes||[],effective=x.effective||{},configured=new Map(nodes.map(n=>[n.node,n.mode])),devices=await api("/devices");$("#globalSecurity").value=x.global||"medium";$("#securityNodes").innerHTML=devices.map(d=>{const mode=configured.get(d.name)||"inherit",eff=effective[d.name]||x.global||"medium";return `<tr><td>${esc(d.name)}</td><td><select data-security-node="${esc(d.name)}"><option value="inherit" ${mode==='inherit'?'selected':''}>跟随全局</option><option value="low" ${mode==='low'?'selected':''}>低 · Low</option><option value="medium" ${mode==='medium'?'selected':''}>中 · Medium</option><option value="high" ${mode==='high'?'selected':''}>高 · High</option></select></td><td>${esc(eff)}</td><td><button type="button" onclick="saveNodeSecurity('${esc(d.name)}')">保存</button></td></tr>`}).join("")}
|
||||
async function saveNodeSecurity(node){const el=document.querySelector(`[data-security-node="${CSS.escape(node)}"]`);if(!el)return;try{await api("/security/settings/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({node,mode:el.value})});$("#securityStatus").textContent=`${node} 策略已保存。`;await loadSecuritySettings()}catch(e){$("#securityStatus").textContent="保存失败: "+e.message}}
|
||||
$("#saveGlobalSecurity").onclick=async()=>{try{await api("/security/settings/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({global:$("#globalSecurity").value})});$("#securityStatus").textContent="全局安全策略已保存。";await loadSecuritySettings()}catch(e){$("#securityStatus").textContent="保存失败: "+e.message}};$("#securityRefresh").onclick=()=>loadSecuritySettings().catch(console.error);loadSecuritySettings().catch(console.error);
|
||||
|
||||
|
||||
let webhookEditingId = "";
|
||||
|
||||
async function loadWebhooks() {
|
||||
const list = await api("/notifications/webhooks");
|
||||
const el = $("#webhookList");
|
||||
if (!el) return;
|
||||
if (!list || list.length === 0) {
|
||||
el.innerHTML = '<div class="mcp-meta">暂无 Webhook 配置。</div>';
|
||||
return;
|
||||
}
|
||||
el.innerHTML = list.map(x => `
|
||||
<div class="mcp-item">
|
||||
<h3>${esc(x.name)} <small>${esc(x.id)}</small></h3>
|
||||
<div class="mcp-meta">
|
||||
${esc(x.type)} · ${x.enabled ? '<span style="color:var(--dot-online)">启用</span>' : '<span style="color:var(--text-muted)">停用</span>'}<br>
|
||||
<code>${esc(x.url)}</code>
|
||||
</div>
|
||||
<div class="mcp-actions">
|
||||
<button type="button" onclick="editWebhook('${esc(x.id)}')">编辑</button>
|
||||
<button type="button" onclick="deleteWebhook('${esc(x.id)}')">删除</button>
|
||||
</div>
|
||||
</div>
|
||||
`).join("");
|
||||
}
|
||||
|
||||
function resetWebhookForm() {
|
||||
webhookEditingId = "";
|
||||
const editor = $("#webhookEditor");
|
||||
if (!editor) return;
|
||||
editor.hidden = false;
|
||||
$("#webhookId").disabled = false;
|
||||
$("#webhookId").value = "";
|
||||
$("#webhookName").value = "";
|
||||
$("#webhookType").value = "wecom";
|
||||
$("#webhookEnabled").value = "1";
|
||||
$("#webhookUrl").value = "";
|
||||
$("#webhookConfig").value = "{}";
|
||||
$("#webhookStatus").textContent = "";
|
||||
}
|
||||
|
||||
async function editWebhook(id) {
|
||||
const list = await api("/notifications/webhooks");
|
||||
const item = list.find(x => x.id === id);
|
||||
if (!item) return;
|
||||
resetWebhookForm();
|
||||
webhookEditingId = id;
|
||||
$("#webhookId").value = item.id;
|
||||
$("#webhookId").disabled = true;
|
||||
$("#webhookName").value = item.name || "";
|
||||
$("#webhookType").value = item.type || "wecom";
|
||||
$("#webhookEnabled").value = item.enabled ? "1" : "0";
|
||||
$("#webhookUrl").value = item.url || "";
|
||||
$("#webhookConfig").value = item.config_json || "{}";
|
||||
}
|
||||
|
||||
async function deleteWebhook(id) {
|
||||
if (!confirm(`确认删除 Webhook [${id}]?`)) return;
|
||||
try {
|
||||
await api("/notifications/webhook/delete?id=" + encodeURIComponent(id), { method: "DELETE" });
|
||||
await loadWebhooks();
|
||||
} catch (e) {
|
||||
alert("删除失败: " + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
if ($("#webhookNew")) $("#webhookNew").onclick = resetWebhookForm;
|
||||
if ($("#webhookCancel")) $("#webhookCancel").onclick = () => {
|
||||
const editor = $("#webhookEditor");
|
||||
if (editor) editor.hidden = true;
|
||||
};
|
||||
|
||||
if ($("#webhookSave")) $("#webhookSave").onclick = async () => {
|
||||
try {
|
||||
const id = $("#webhookId").value.trim();
|
||||
const name = $("#webhookName").value.trim();
|
||||
const url = $("#webhookUrl").value.trim();
|
||||
if (!id) throw Error("标识 (ID) 不能为空");
|
||||
if (!name) throw Error("名称不能为空");
|
||||
if (!url) throw Error("Webhook URL 不能为空");
|
||||
|
||||
let cfg = {};
|
||||
try {
|
||||
cfg = JSON.parse($("#webhookConfig").value || "{}");
|
||||
} catch (e) {
|
||||
throw Error("配置 JSON 格式不正确");
|
||||
}
|
||||
|
||||
const body = {
|
||||
id: id,
|
||||
name: name,
|
||||
type: $("#webhookType").value,
|
||||
url: url,
|
||||
config_json: JSON.stringify(cfg),
|
||||
enabled: $("#webhookEnabled").value === "1"
|
||||
};
|
||||
|
||||
await api("/notifications/webhook/update", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
|
||||
$("#webhookStatus").textContent = "Webhook [" + id + "] 已保存。";
|
||||
const editor = $("#webhookEditor");
|
||||
if (editor) editor.hidden = true;
|
||||
await loadWebhooks();
|
||||
} catch (e) {
|
||||
$("#webhookStatus").textContent = "保存失败: " + e.message;
|
||||
}
|
||||
};
|
||||
|
||||
if ($("#webhookTest")) $("#webhookTest").onclick = async () => {
|
||||
try {
|
||||
const id = $("#webhookId").value.trim();
|
||||
const name = $("#webhookName").value.trim();
|
||||
const url = $("#webhookUrl").value.trim();
|
||||
if (!url) throw Error("Webhook URL 不能为空");
|
||||
|
||||
let cfg = {};
|
||||
try {
|
||||
cfg = JSON.parse($("#webhookConfig").value || "{}");
|
||||
} catch (e) {
|
||||
throw Error("配置 JSON 格式不正确");
|
||||
}
|
||||
|
||||
const body = {
|
||||
id: id || "test",
|
||||
name: name || "测试目标",
|
||||
type: $("#webhookType").value,
|
||||
url: url,
|
||||
config_json: JSON.stringify(cfg),
|
||||
enabled: true
|
||||
};
|
||||
|
||||
$("#webhookStatus").textContent = "正在发送测试消息...";
|
||||
await api("/notifications/webhook/test", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
$("#webhookStatus").textContent = "✓ 测试消息发送成功!";
|
||||
} catch (e) {
|
||||
$("#webhookStatus").textContent = "✗ 测试失败: " + e.message;
|
||||
}
|
||||
};
|
||||
|
||||
if ($("#notificationRefresh")) $("#notificationRefresh").onclick = () => loadWebhooks().catch(console.error);
|
||||
|
||||
// 开启 5 秒平滑实时自动轮询
|
||||
let devicePollTimer = null;
|
||||
function startDevicePolling() {
|
||||
if (devicePollTimer) clearInterval(devicePollTimer);
|
||||
devicePollTimer = setInterval(() => {
|
||||
if (!document.hidden) {
|
||||
loadDevices().catch(console.error);
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
startDevicePolling();
|
||||
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (!document.hidden) {
|
||||
loadDevices().catch(console.error);
|
||||
}
|
||||
});
|
||||
loadWebhooks().catch(console.error);
|
||||
|
||||
@@ -1 +1,38 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander</title><link rel="stylesheet" href="/static/app.css"></head><body><header><div class="brand-wrap"><img src="/static/icon.png" alt="logo" class="brand-logo"><div><strong>VPS-Commander</strong><span>Private Infrastructure Console</span></div></div><div class="header-actions"><button id="themeToggle" type="button" class="btn-icon" title="切换主题" aria-label="切换主题"><svg class="theme-svg svg-sun" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg><svg class="theme-svg svg-moon" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg></button><button id="logout" type="button">退出</button></div></header><main><section class="grid"><article class="card wide"><div class="cardhead"><h2>设备看板</h2><button id="refresh" type="button">刷新</button></div><div id="devices" class="devices"></div></article><article class="card"><h2>Actions 向导</h2><p>当前 Hub 的 OpenAPI Schema:</p><div class="actions"><button id="copySchema" type="button">复制 Schema 地址</button><button id="copyPrompt" type="button">复制 System Prompt</button><button id="rotateKey" type="button">轮换 API Key</button></div><pre id="schemaHint">/openapi.json</pre><pre id="newKey"></pre></article><article class="card wide"><div class="cardhead"><h2>快速控制台</h2><select id="device"></select></div><textarea id="command" placeholder="输入 Shell 命令,例如 uname -a"></textarea><div><button id="run" type="button">执行</button></div><pre id="output"></pre></article><article class="card wide"><div class="cardhead"><h2>审计日志</h2><button id="auditRefresh" type="button">刷新</button></div><div class="tablewrap"><table><thead><tr><th>时间</th><th>设备</th><th>动作</th><th>命令/路径</th><th>退出码</th><th>耗时</th><th>来源</th></tr></thead><tbody id="audits"></tbody></table></div></article></section></main><script src="/static/app.js"></script></body></html>
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander</title><link rel="stylesheet" href="/static/app.css"></head><body><header><div class="brand-wrap"><img src="/static/icon.png" alt="logo" class="brand-logo"><div><strong>VPS-Commander</strong><span>Private Infrastructure Console</span></div></div><div class="header-actions"><button id="themeToggle" type="button" class="btn-icon" title="切换主题" aria-label="切换主题"><svg class="theme-svg svg-sun" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg><svg class="theme-svg svg-moon" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg></button><button id="logout" type="button">退出</button></div></header><main><section class="grid"><article class="card wide"><div class="cardhead"><h2>设备看板</h2><button id="refresh" type="button">刷新</button></div><div id="devices" class="devices"></div></article><article class="card"><h2>Actions 向导</h2><p>当前 Hub 的 OpenAPI Schema:</p><div class="actions"><button id="copySchema" type="button">复制 Schema 地址</button><button id="copyPrompt" type="button">复制 System Prompt</button><button id="rotateKey" type="button">轮换 API Key</button></div><pre id="schemaHint">/openapi.json</pre><pre id="newKey"></pre></article><article class="card wide"><div class="mcp-toolbar"><h2>MCP</h2><button id="mcpNew" type="button">新增 MCP</button></div><div id="mcpList" class="mcp-grid"></div><div id="mcpEditor" hidden><div class="mcp-form"><label>服务标识<input id="mcpId" placeholder="docker"></label><label>显示名称<input id="mcpName" placeholder="Docker 容器管理"></label><label>传输类型<select id="mcpTransport"><option value="stdio">命令行 / stdio</option><option value="http">HTTP / Streamable HTTP</option><option value="sse">SSE</option></select></label><label>启用<select id="mcpEnabled"><option value="1">启用</option><option value="0">停用</option></select></label><label class="full">Command<input id="mcpCommand" placeholder="docker-mcp"></label><label class="full">Arguments(JSON 数组)<textarea id="mcpArgs">[]</textarea></label><label class="full">URL<input id="mcpUrl" placeholder="http://127.0.0.1:8080/mcp"></label><label class="full">Headers(JSON 对象,可选)<textarea id="mcpHeaders">{}</textarea></label><label class="full">环境变量(JSON 对象,可选)<textarea id="mcpEnv">{}</textarea></label><label>生效范围<select id="mcpScope"><option value="all">全部节点</option><option value="custom">指定节点</option></select></label><div><span>指定节点</span><div id="mcpNodes" class="mcp-nodes"></div></div><label>测试节点<select id="mcpTestNode"><option value="local">Hub 本机</option></select></label></div><div class="mcp-actions"><button id="mcpSave" type="button">保存并热更新</button><button id="mcpTest" type="button">测试连通性</button><button id="mcpCancel" type="button">取消</button></div><div id="mcpStatus" class="mcp-status"></div><div id="mcpTestResult" class="mcp-test-result" hidden></div></div></article>
|
||||
<article class="card wide"><div class="cardhead"><h2>快速控制台</h2><select id="device"></select></div><textarea id="command" placeholder="输入 Shell 命令,例如 uname -a"></textarea><div><button id="run" type="button">执行</button></div><pre id="output"></pre></article><article class="card wide"><div class="cardhead"><h2>安全</h2><button id="securityRefresh" type="button">刷新</button></div><div class="security-grid"><label>全局安全等级<select id="globalSecurity"><option value="low">低 · Low</option><option value="medium">中 · Medium</option><option value="high">高 · High</option></select></label><button id="saveGlobalSecurity" type="button">保存全局策略</button></div><div class="tablewrap"><table><thead><tr><th>节点</th><th>单机策略</th><th>有效策略</th><th>操作</th></tr></thead><tbody id="securityNodes"></tbody></table></div><p id="securityStatus"></p></article><article class="card wide">
|
||||
<div class="mcp-toolbar">
|
||||
<h2>通知</h2>
|
||||
<div style="display:flex;gap:8px">
|
||||
<button id="webhookNew" type="button">新增 Webhook</button>
|
||||
<button id="notificationRefresh" type="button">刷新</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="webhookList" class="mcp-grid"></div>
|
||||
<div id="webhookEditor" hidden style="margin-top:14px;border-top:1px solid var(--border);padding-top:14px">
|
||||
<div class="mcp-form">
|
||||
<label>标识 (ID)<input id="webhookId" placeholder="如 openclaw-wecom"></label>
|
||||
<label>名称<input id="webhookName" placeholder="如 运维告警群"></label>
|
||||
<label>类型
|
||||
<select id="webhookType">
|
||||
<option value="wecom">企业微信 (WeCom)</option>
|
||||
<option value="telegram">Telegram</option>
|
||||
<option value="generic">通用 JSON Webhook</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>状态
|
||||
<select id="webhookEnabled">
|
||||
<option value="1">启用</option>
|
||||
<option value="0">停用</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="full">Webhook URL<input id="webhookUrl" placeholder="https://qyapi.weixin.qq.com/..."></label>
|
||||
<label class="full">配置 JSON (Telegram 需填 {"chat_id":"-100..."})<textarea id="webhookConfig">{}</textarea></label>
|
||||
</div>
|
||||
<div class="mcp-actions">
|
||||
<button id="webhookSave" type="button">保存 Webhook</button>
|
||||
<button id="webhookTest" type="button">测试连通性</button>
|
||||
<button id="webhookCancel" type="button">取消</button>
|
||||
</div>
|
||||
<div id="webhookStatus" class="mcp-status"></div>
|
||||
</div>
|
||||
</article><article class="card wide"><div class="cardhead"><h2>日志</h2><button id="auditRefresh" type="button">刷新</button></div><div class="tablewrap"><table><thead><tr><th>时间</th><th>设备</th><th>动作</th><th>命令/路径</th><th>退出码</th><th>耗时</th><th>来源</th></tr></thead><tbody id="audits"></tbody></table></div></article></section></main><script src="/static/app.js"></script></body></html>
|
||||
|
||||
@@ -1 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander Login</title><link rel="stylesheet" href="/static/app.css"></head><body class="login"><form id="login"><h1>VPS-Commander</h1><p>Private Infrastructure Console</p><input id="password" type="password" placeholder="面板密码" autocomplete="current-password"><button type="submit">登录</button><div id="error"></div></form><script>document.querySelector("#login").onsubmit=async e=>{e.preventDefault();let r=await fetch("/panel/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:document.querySelector("#password").value})});if(r.ok)location.href="/";else document.querySelector("#error").textContent="密码错误或未配置面板密码"};</script></body></html>
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander Login</title><link rel="stylesheet" href="/static/app.css"></head><body class="login"><form id="login"><h1>VPS-Commander</h1><p>Private Infrastructure Console</p><input id="password" type="password" placeholder="面板密码" autocomplete="current-password"><button type="submit">登录</button><div id="error"></div></form><script>document.querySelector("#login").onsubmit=async e=>{e.preventDefault();let r=await fetch("/panel/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:document.querySelector("#password").value})});if(r.ok)location.href="/panel";else document.querySelector("#error").textContent="密码错误或未配置面板密码"};</script></body></html>
|
||||
|
||||
@@ -0,0 +1,615 @@
|
||||
/**
|
||||
* Apple Design System - VPS Probe
|
||||
* Grounded in Apple HIG (macOS / iOS) & Liquid Glass Design Specs
|
||||
*/
|
||||
|
||||
:root {
|
||||
/* Dynamic System Colors - Dark (Default) */
|
||||
--system-bg: #000000;
|
||||
--secondary-system-bg: #16181d;
|
||||
--tertiary-system-bg: #21252d;
|
||||
|
||||
/* Materials & Overlays */
|
||||
--liquid-glass-bg: rgba(22, 24, 29, 0.72);
|
||||
--liquid-glass-border: rgba(255, 255, 255, 0.09);
|
||||
--hairline-border: rgba(255, 255, 255, 0.08);
|
||||
--hairline-border-hover: rgba(255, 255, 255, 0.16);
|
||||
--hairline-highlight: rgba(255, 255, 255, 0.04);
|
||||
|
||||
/* Apple Semantic Labels */
|
||||
--label-primary: #f5f5f7;
|
||||
--label-secondary: #98989d;
|
||||
--label-tertiary: #636366;
|
||||
--label-quaternary: #48484a;
|
||||
|
||||
/* Apple System Accents & Status */
|
||||
--accent: #0a84ff;
|
||||
--accent-subtle: rgba(10, 132, 255, 0.15);
|
||||
|
||||
--system-green: #30d158;
|
||||
--system-green-subtle: rgba(48, 209, 88, 0.14);
|
||||
--system-yellow: #ffd60a;
|
||||
--system-yellow-subtle: rgba(255, 214, 10, 0.14);
|
||||
--system-red: #ff453a;
|
||||
--system-red-subtle: rgba(255, 69, 58, 0.14);
|
||||
--system-purple: #bf5af2;
|
||||
|
||||
/* Typography Stacks */
|
||||
--font-system: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||
--font-mono: "SF Mono", ui-monospace, Menlo, Monaco, Consolas, monospace;
|
||||
|
||||
/* Radii & Shadows */
|
||||
--radius-lg: 16px;
|
||||
--radius-md: 10px;
|
||||
--radius-sm: 6px;
|
||||
--shadow-subtle: 0 4px 20px rgba(0, 0, 0, 0.35);
|
||||
--shadow-hover: 0 8px 30px rgba(0, 0, 0, 0.5);
|
||||
|
||||
/* Animation */
|
||||
--ease-apple: cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
|
||||
/* Light Appearance */
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root {
|
||||
--system-bg: #f5f5f7;
|
||||
--secondary-system-bg: #ffffff;
|
||||
--tertiary-system-bg: #e5e5ea;
|
||||
|
||||
--liquid-glass-bg: rgba(255, 255, 255, 0.78);
|
||||
--liquid-glass-border: rgba(0, 0, 0, 0.08);
|
||||
--hairline-border: rgba(0, 0, 0, 0.07);
|
||||
--hairline-border-hover: rgba(0, 0, 0, 0.14);
|
||||
--hairline-highlight: rgba(0, 0, 0, 0.02);
|
||||
|
||||
--label-primary: #1d1d1f;
|
||||
--label-secondary: #86868b;
|
||||
--label-tertiary: #a1a1a6;
|
||||
--label-quaternary: #d1d1d6;
|
||||
|
||||
--accent: #0071e3;
|
||||
--accent-subtle: rgba(0, 113, 227, 0.1);
|
||||
|
||||
--system-green: #34c759;
|
||||
--system-green-subtle: rgba(52, 199, 89, 0.12);
|
||||
--system-yellow: #ff9500;
|
||||
--system-yellow-subtle: rgba(255, 149, 0, 0.12);
|
||||
--system-red: #ff3b30;
|
||||
--system-red-subtle: rgba(255, 59, 48, 0.12);
|
||||
|
||||
--shadow-subtle: 0 2px 14px rgba(0, 0, 0, 0.06);
|
||||
--shadow-hover: 0 6px 20px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: var(--system-bg);
|
||||
color: var(--label-primary);
|
||||
font-family: var(--font-system);
|
||||
font-size: 13px;
|
||||
line-height: 1.45;
|
||||
min-height: 100vh;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
.layout {
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
padding: 0 24px 48px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Header & Liquid Glass Navbar
|
||||
========================================================================== */
|
||||
.navbar {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
margin: 0 -24px 28px;
|
||||
padding: 14px 24px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 16px;
|
||||
background: var(--liquid-glass-bg);
|
||||
backdrop-filter: blur(24px) saturate(190%);
|
||||
-webkit-backdrop-filter: blur(24px) saturate(190%);
|
||||
border-bottom: 1px solid var(--liquid-glass-border);
|
||||
transition: all 0.2s var(--ease-apple);
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.logo-dot {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
background: var(--accent);
|
||||
border-radius: 3px;
|
||||
box-shadow: 0 0 10px var(--accent-subtle);
|
||||
}
|
||||
|
||||
.brand-text {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.brand-text h1 {
|
||||
font-size: 17px;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.015em;
|
||||
color: var(--label-primary);
|
||||
}
|
||||
|
||||
.brand-text .sub {
|
||||
font-size: 12px;
|
||||
color: var(--label-secondary);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
/* Cluster Summary Pill */
|
||||
.summary-badge {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
background: var(--hairline-highlight);
|
||||
border: 1px solid var(--hairline-border);
|
||||
padding: 5px 12px;
|
||||
border-radius: 980px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--label-secondary);
|
||||
}
|
||||
|
||||
.dot-online {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--system-green);
|
||||
box-shadow: 0 0 6px var(--system-green);
|
||||
}
|
||||
|
||||
/* macOS-Style Segmented Control */
|
||||
.view-switch {
|
||||
display: flex;
|
||||
background: var(--tertiary-system-bg);
|
||||
border: 1px solid var(--hairline-border);
|
||||
border-radius: 8px;
|
||||
padding: 2px;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.view-switch .btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
height: 26px;
|
||||
padding: 0 12px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--label-secondary);
|
||||
font-family: var(--font-system);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease-out;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.view-switch .btn:hover {
|
||||
color: var(--label-primary);
|
||||
}
|
||||
|
||||
.view-switch .btn.active {
|
||||
background: var(--secondary-system-bg);
|
||||
color: var(--label-primary);
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 0.5px 1px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Content Grid & Node Card (Content Layer)
|
||||
========================================================================== */
|
||||
.card-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.node-card {
|
||||
background: var(--secondary-system-bg);
|
||||
border: 1px solid var(--hairline-border);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: 18px 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
box-shadow: var(--shadow-subtle);
|
||||
transition: transform 0.25s var(--ease-apple), border-color 0.25s var(--ease-apple), box-shadow 0.25s var(--ease-apple);
|
||||
}
|
||||
|
||||
.node-card:hover {
|
||||
transform: translateY(-1.5px);
|
||||
border-color: var(--hairline-border-hover);
|
||||
box-shadow: var(--shadow-hover);
|
||||
}
|
||||
|
||||
.card-top {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.node-title {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.node-name-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.flag-icon {
|
||||
font-size: 15px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.node-name {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.01em;
|
||||
color: var(--label-primary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.local-badge {
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
padding: 2px 6px;
|
||||
border-radius: 5px;
|
||||
background: var(--accent-subtle);
|
||||
color: var(--accent);
|
||||
border: 1px solid rgba(10, 132, 255, 0.25);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.node-meta {
|
||||
font-size: 11px;
|
||||
color: var(--label-secondary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.meta-pill {
|
||||
background: var(--hairline-highlight);
|
||||
border: 1px solid var(--hairline-border);
|
||||
padding: 1px 6px;
|
||||
border-radius: 4px;
|
||||
color: var(--label-secondary);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* Status Pill */
|
||||
.status-badge {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
padding: 2px 8px;
|
||||
border-radius: 980px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.status-badge.online {
|
||||
background: var(--system-green-subtle);
|
||||
color: var(--system-green);
|
||||
border: 1px solid rgba(48, 209, 88, 0.22);
|
||||
}
|
||||
|
||||
.status-badge.offline {
|
||||
background: var(--system-red-subtle);
|
||||
color: var(--system-red);
|
||||
border: 1px solid rgba(255, 69, 58, 0.22);
|
||||
}
|
||||
|
||||
.status-badge .dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: currentColor;
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Metrics & Progress Bars (San Francisco Metrics)
|
||||
========================================================================== */
|
||||
.metrics-bars {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.metric-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.metric-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.metric-label {
|
||||
color: var(--label-secondary);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.metric-value {
|
||||
color: var(--label-primary);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.progress-track {
|
||||
height: 5px;
|
||||
background: var(--tertiary-system-bg);
|
||||
border-radius: 980px;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
border-radius: 980px;
|
||||
transition: width 0.4s var(--ease-apple), background 0.3s ease;
|
||||
}
|
||||
|
||||
.progress-fill.normal {
|
||||
background: var(--system-green);
|
||||
}
|
||||
|
||||
.progress-fill.warn {
|
||||
background: var(--system-yellow);
|
||||
}
|
||||
|
||||
.progress-fill.danger {
|
||||
background: var(--system-red);
|
||||
}
|
||||
|
||||
/* Secondary Stat Widget (Inset Grouped) */
|
||||
.card-stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
background: var(--hairline-highlight);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--hairline-border);
|
||||
}
|
||||
|
||||
.stat-box {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.stat-title {
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
color: var(--label-secondary);
|
||||
}
|
||||
|
||||
.stat-desc {
|
||||
font-size: 12px;
|
||||
color: var(--label-secondary);
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.stat-desc b {
|
||||
color: var(--label-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.traffic-in { color: var(--accent) !important; font-weight: 600; }
|
||||
.traffic-out { color: var(--system-purple) !important; font-weight: 600; }
|
||||
|
||||
/* ==========================================================================
|
||||
Compact Table View (macOS Table Standard)
|
||||
========================================================================== */
|
||||
.table-wrapper {
|
||||
background: var(--secondary-system-bg);
|
||||
border: 1px solid var(--hairline-border);
|
||||
border-radius: var(--radius-lg);
|
||||
overflow-x: auto;
|
||||
box-shadow: var(--shadow-subtle);
|
||||
}
|
||||
|
||||
.probe-table {
|
||||
width: 100%;
|
||||
min-width: 960px;
|
||||
border-collapse: collapse;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.probe-table th {
|
||||
background: var(--tertiary-system-bg);
|
||||
padding: 10px 16px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--label-secondary);
|
||||
border-bottom: 1px solid var(--hairline-border);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.probe-table td {
|
||||
padding: 12px 16px;
|
||||
border-bottom: 1px solid var(--hairline-border);
|
||||
font-size: 12px;
|
||||
vertical-align: middle;
|
||||
color: var(--label-primary);
|
||||
}
|
||||
|
||||
.probe-table tr:last-child td {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.probe-table tr:hover td {
|
||||
background: var(--hairline-highlight);
|
||||
}
|
||||
|
||||
.col-mono {
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.mini-bar-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 110px;
|
||||
}
|
||||
|
||||
.mini-bar {
|
||||
flex: 1;
|
||||
height: 5px;
|
||||
background: var(--tertiary-system-bg);
|
||||
border-radius: 980px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.mini-bar-fill {
|
||||
height: 100%;
|
||||
border-radius: 980px;
|
||||
}
|
||||
|
||||
.table-node {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.table-node .name {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--label-primary);
|
||||
}
|
||||
|
||||
.table-node .sub {
|
||||
font-size: 11px;
|
||||
color: var(--label-secondary);
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Footer
|
||||
========================================================================== */
|
||||
.footer {
|
||||
margin-top: auto;
|
||||
padding-top: 32px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
font-size: 12px;
|
||||
color: var(--label-secondary);
|
||||
border-top: 1px solid var(--hairline-border);
|
||||
}
|
||||
|
||||
.update-time {
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* Error State */
|
||||
.error-msg {
|
||||
text-align: center;
|
||||
padding: 40px;
|
||||
color: var(--system-red);
|
||||
background: var(--system-red-subtle);
|
||||
border: 1px dashed rgba(255, 69, 58, 0.3);
|
||||
border-radius: var(--radius-lg);
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Responsive Adaptations
|
||||
========================================================================== */
|
||||
@media (max-width: 768px) {
|
||||
.layout {
|
||||
padding: 0 16px 36px;
|
||||
}
|
||||
|
||||
.navbar {
|
||||
margin: 0 -16px 20px;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
.brand-text h1 {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.controls {
|
||||
width: 100%;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.card-grid {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.node-card {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.card-stats-grid {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.footer {
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
text-align: center;
|
||||
padding-top: 24px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<title>VPS Probe - 节点监控探针</title>
|
||||
<link rel="stylesheet" href="/static/probe.css?v=20261001">
|
||||
</head>
|
||||
<body>
|
||||
<div class="layout">
|
||||
<header class="navbar">
|
||||
<div class="brand">
|
||||
<div class="logo-dot"></div>
|
||||
<div class="brand-text">
|
||||
<h1>VPS Probe</h1>
|
||||
<span class="sub">服务器集群实时监控</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<div class="summary-badge" id="clusterSummary">
|
||||
<span class="dot-online"></span>
|
||||
<span id="summaryText">检测中...</span>
|
||||
</div>
|
||||
<div class="view-switch">
|
||||
<button id="cardBtn" class="btn active" title="卡片视图">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect></svg>
|
||||
卡片
|
||||
</button>
|
||||
<button id="compactBtn" class="btn" title="表格视图">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
|
||||
表格
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main id="content" class="card-view"></main>
|
||||
|
||||
<footer class="footer">
|
||||
<span>VPS-Commander Cluster Monitor</span>
|
||||
<span id="lastUpdated" class="update-time">自动刷新中...</span>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/static/probe.js?v=20261001"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,289 @@
|
||||
(() => {
|
||||
const root = document.querySelector('#content');
|
||||
const summaryEl = document.querySelector('#summaryText');
|
||||
const lastUpdatedEl = document.querySelector('#lastUpdated');
|
||||
|
||||
const fmtBytes = n => {
|
||||
if (!Number.isFinite(n) || n <= 0) return '0 B';
|
||||
const u = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
let i = 0, v = n;
|
||||
while (v >= 1024 && i < u.length - 1) {
|
||||
v /= 1024;
|
||||
i++;
|
||||
}
|
||||
return `${v.toFixed(i === 0 ? 0 : 1)} ${u[i]}`;
|
||||
};
|
||||
|
||||
const fmtRate = n => `${fmtBytes(n)}/s`;
|
||||
|
||||
const fmtUp = n => {
|
||||
let s = Math.max(0, Math.floor(n || 0));
|
||||
if (s <= 0) return '--';
|
||||
const d = Math.floor(s / 86400);
|
||||
s %= 86400;
|
||||
const h = Math.floor(s / 3600);
|
||||
s %= 3600;
|
||||
const m = Math.floor(s / 60);
|
||||
if (d > 0) return `${d}天 ${h}时`;
|
||||
if (h > 0) return `${h}小时 ${m}分`;
|
||||
return `${m} 分钟`;
|
||||
};
|
||||
|
||||
const esc = s => String(s ?? '-').replace(/[&<>"']/g, c => ({
|
||||
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
|
||||
}[c]));
|
||||
|
||||
const getFlag = (cc, country) => {
|
||||
if (!cc || typeof cc !== 'string' || cc.length !== 2) return '';
|
||||
const code = cc.toUpperCase();
|
||||
const flag = String.fromCodePoint(...[...code].map(c => 0x1F1E6 - 65 + c.charCodeAt(0)));
|
||||
const title = country ? `${country} (${code})` : code;
|
||||
return `<span class="flag-icon" title="${esc(title)}">${flag}</span>`;
|
||||
};
|
||||
|
||||
const getStatusLevel = pct => {
|
||||
const val = Number(pct || 0);
|
||||
if (val >= 85) return 'danger';
|
||||
if (val >= 65) return 'warn';
|
||||
return 'normal';
|
||||
};
|
||||
|
||||
let mode = localStorage.getItem('vpc_probe_view') || 'card';
|
||||
|
||||
const setMode = m => {
|
||||
mode = m;
|
||||
localStorage.setItem('vpc_probe_view', m);
|
||||
render(window.__data || []);
|
||||
};
|
||||
|
||||
document.querySelector('#cardBtn').onclick = () => setMode('card');
|
||||
document.querySelector('#compactBtn').onclick = () => setMode('compact');
|
||||
|
||||
const renderCard = d => {
|
||||
const p = d.profile || {};
|
||||
const isOnline = d.status === 'online';
|
||||
const cpuPct = p.cpu_usage_percent != null ? Number(p.cpu_usage_percent) : 0;
|
||||
const memPct = p.mem_percent != null ? Number(p.mem_percent) : 0;
|
||||
const diskPct = p.disk_percent != null ? Number(p.disk_percent) : 0;
|
||||
const loadStr = [p.load_1m, p.load_5m, p.load_15m].map(x => Number(x || 0).toFixed(2)).join(', ');
|
||||
|
||||
return `
|
||||
<div class="node-card">
|
||||
<div class="card-top">
|
||||
<div class="node-title">
|
||||
<div class="node-name-wrap">
|
||||
${getFlag(d.country_code, d.country)}
|
||||
<span class="node-name">${esc(d.name)}</span>
|
||||
${d.is_local ? '<span class="local-badge">本机</span>' : ''}
|
||||
</div>
|
||||
<div class="node-meta">
|
||||
<span class="meta-pill">${p.cpu_cores || 1} 核</span>
|
||||
<span class="meta-pill">${esc(d.os || 'Linux')}</span>
|
||||
<span>${fmtUp(p.uptime_seconds)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="status-badge ${isOnline ? 'online' : 'offline'}">
|
||||
<span class="dot"></span>
|
||||
${isOnline ? '在线' : '离线'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="metrics-bars">
|
||||
<div class="metric-item">
|
||||
<div class="metric-header">
|
||||
<span class="metric-label">CPU 负载</span>
|
||||
<span class="metric-value">${p.cpu_usage_percent != null ? `${cpuPct}%` : '--'}</span>
|
||||
</div>
|
||||
<div class="progress-track">
|
||||
<div class="progress-fill ${getStatusLevel(cpuPct)}" style="width: ${Math.min(100, Math.max(0, cpuPct))}%"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="metric-item">
|
||||
<div class="metric-header">
|
||||
<span class="metric-label">内存 (空闲 ${esc(p.mem_available || '--')})</span>
|
||||
<span class="metric-value">${p.mem_percent != null ? `${memPct}%` : '--'}</span>
|
||||
</div>
|
||||
<div class="progress-track">
|
||||
<div class="progress-fill ${getStatusLevel(memPct)}" style="width: ${Math.min(100, Math.max(0, memPct))}%"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="metric-item">
|
||||
<div class="metric-header">
|
||||
<span class="metric-label">磁盘 (空闲 ${esc(p.disk_free || '--')})</span>
|
||||
<span class="metric-value">${p.disk_percent != null ? `${diskPct}%` : '--'}</span>
|
||||
</div>
|
||||
<div class="progress-track">
|
||||
<div class="progress-fill ${getStatusLevel(diskPct)}" style="width: ${Math.min(100, Math.max(0, diskPct))}%"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card-stats-grid">
|
||||
<div class="stat-box">
|
||||
<span class="stat-title">实时网络 (↓ / ↑)</span>
|
||||
<span class="stat-desc">
|
||||
<b class="traffic-in">↓ ${fmtRate(p.net_rx_rate)}</b> /
|
||||
<b class="traffic-out">↑ ${fmtRate(p.net_tx_rate)}</b>
|
||||
</span>
|
||||
</div>
|
||||
<div class="stat-box">
|
||||
<span class="stat-title">总流量 (↓ / ↑)</span>
|
||||
<span class="stat-desc">
|
||||
↓ ${fmtBytes(p.net_rx_total)} / ↑ ${fmtBytes(p.net_tx_total)}
|
||||
</span>
|
||||
</div>
|
||||
<div class="stat-box">
|
||||
<span class="stat-title">系统平均负载 (1/5/15m)</span>
|
||||
<span class="stat-desc">${loadStr}</span>
|
||||
</div>
|
||||
<div class="stat-box">
|
||||
<span class="stat-title">IO PSI / Docker</span>
|
||||
<span class="stat-desc">${p.io_psi != null ? Number(p.io_psi).toFixed(2) : '0.00'} / ${p.docker ? '有' : '无'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
};
|
||||
|
||||
const renderTable = list => {
|
||||
const rows = list.map(d => {
|
||||
const p = d.profile || {};
|
||||
const isOnline = d.status === 'online';
|
||||
const cpuPct = p.cpu_usage_percent != null ? Number(p.cpu_usage_percent) : 0;
|
||||
const memPct = p.mem_percent != null ? Number(p.mem_percent) : 0;
|
||||
const diskPct = p.disk_percent != null ? Number(p.disk_percent) : 0;
|
||||
const loadStr = [p.load_1m, p.load_5m, p.load_15m].map(x => Number(x || 0).toFixed(2)).join(' / ');
|
||||
|
||||
return `
|
||||
<tr>
|
||||
<td>
|
||||
<div class="table-node">
|
||||
<span class="name">
|
||||
${getFlag(d.country_code, d.country)}
|
||||
${esc(d.name)}
|
||||
${d.is_local ? '<span class="local-badge">本机</span>' : ''}
|
||||
</span>
|
||||
<span class="sub">${p.cpu_cores || 1}核 | ${esc(d.os || 'Linux')}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<span class="status-badge ${isOnline ? 'online' : 'offline'}">
|
||||
<span class="dot"></span>
|
||||
${isOnline ? '在线' : '离线'}
|
||||
</span>
|
||||
</td>
|
||||
<td class="col-mono">${fmtUp(p.uptime_seconds)}</td>
|
||||
<td class="col-mono">${loadStr}</td>
|
||||
<td>
|
||||
<div class="mini-bar-wrap">
|
||||
<div class="mini-bar">
|
||||
<div class="mini-bar-fill progress-fill ${getStatusLevel(cpuPct)}" style="width: ${Math.min(100, Math.max(0, cpuPct))}%"></div>
|
||||
</div>
|
||||
<span class="col-mono">${p.cpu_usage_percent != null ? `${cpuPct}%` : '--'}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div class="mini-bar-wrap">
|
||||
<div class="mini-bar">
|
||||
<div class="mini-bar-fill progress-fill ${getStatusLevel(memPct)}" style="width: ${Math.min(100, Math.max(0, memPct))}%"></div>
|
||||
</div>
|
||||
<span class="col-mono">${p.mem_percent != null ? `${memPct}%` : '--'}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td class="col-mono">
|
||||
<span class="traffic-in">↓ ${fmtRate(p.net_rx_rate)}</span><br>
|
||||
<span class="traffic-out">↑ ${fmtRate(p.net_tx_rate)}</span>
|
||||
</td>
|
||||
<td class="col-mono">
|
||||
↓ ${fmtBytes(p.net_rx_total)}<br>
|
||||
↑ ${fmtBytes(p.net_tx_total)}
|
||||
</td>
|
||||
<td>
|
||||
<div class="mini-bar-wrap">
|
||||
<div class="mini-bar">
|
||||
<div class="mini-bar-fill progress-fill ${getStatusLevel(diskPct)}" style="width: ${Math.min(100, Math.max(0, diskPct))}%"></div>
|
||||
</div>
|
||||
<span class="col-mono">${p.disk_percent != null ? `${diskPct}%` : '--'}</span>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
return `
|
||||
<div class="table-wrapper">
|
||||
<table class="probe-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>节点名称</th>
|
||||
<th>状态</th>
|
||||
<th>运行时间</th>
|
||||
<th>负载 (1/5/15m)</th>
|
||||
<th>CPU</th>
|
||||
<th>内存</th>
|
||||
<th>实时网速</th>
|
||||
<th>累计流量</th>
|
||||
<th>磁盘</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${rows}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
};
|
||||
|
||||
function render(data) {
|
||||
document.querySelector('#cardBtn').classList.toggle('active', mode === 'card');
|
||||
document.querySelector('#compactBtn').classList.toggle('active', mode === 'compact');
|
||||
|
||||
const total = data.length;
|
||||
const onlineCount = data.filter(x => x.status === 'online').length;
|
||||
if (summaryEl) {
|
||||
summaryEl.textContent = `${onlineCount} / ${total} 节点在线`;
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
root.innerHTML = '<div class="error-msg">暂无节点数据</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
if (mode === 'card') {
|
||||
root.className = 'card-view';
|
||||
root.innerHTML = `<div class="card-grid">${data.map(renderCard).join('')}</div>`;
|
||||
} else {
|
||||
root.className = 'table-view';
|
||||
root.innerHTML = renderTable(data);
|
||||
}
|
||||
}
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const r = await fetch('/probe/summary', { cache: 'no-store' });
|
||||
if (!r.ok) throw Error();
|
||||
let rawData = await r.json();
|
||||
if (Array.isArray(rawData)) {
|
||||
rawData.sort((a, b) => {
|
||||
if (a.is_local && !b.is_local) return -1;
|
||||
if (!a.is_local && b.is_local) return 1;
|
||||
return String(a.name || "").localeCompare(String(b.name || ""));
|
||||
});
|
||||
}
|
||||
window.__data = rawData;
|
||||
render(window.__data);
|
||||
if (lastUpdatedEl) {
|
||||
const now = new Date();
|
||||
const timeStr = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
|
||||
lastUpdatedEl.textContent = `更新于 ${timeStr}`;
|
||||
}
|
||||
} catch (e) {
|
||||
root.innerHTML = '<div class="error-msg">探针数据暂时不可用,正在重试...</div>';
|
||||
}
|
||||
}
|
||||
|
||||
load();
|
||||
setInterval(load, 5000);
|
||||
})();
|
||||
+145
-76
@@ -2,7 +2,8 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "VPS-Commander",
|
||||
"version": "1.1.0"
|
||||
"version": "2.0.0",
|
||||
"description": "Current VPS-Commander HTTP contract. MCP tools are documented in docs/MCP_INTEGRATION.md."
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
@@ -163,121 +164,189 @@
|
||||
"paths": {
|
||||
"/api/v1/devices": {
|
||||
"get": {
|
||||
"operationId": "list_devices",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Devices",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/Device"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/exec": {
|
||||
"post": {
|
||||
"operationId": "exec_command",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ExecRequest"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Execution result",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ExecResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/file/read": {
|
||||
"post": {
|
||||
"operationId": "read_file",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/FileReadRequest"
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/file/list": {
|
||||
"post": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "File content",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/FileReadResponse"
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/file/info": {
|
||||
"post": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/file/search": {
|
||||
"post": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/process/session": {
|
||||
"post": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/file/write": {
|
||||
"post": {
|
||||
"operationId": "write_file",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/FileWriteRequest"
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/devices/file/edit_block": {
|
||||
"post": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Write result",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/FileWriteResponse"
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/mcp/services": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/mcp/service": {
|
||||
"delete": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/mcp/list": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/mcp/call": {
|
||||
"post": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/mcp/test": {
|
||||
"post": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/security/settings": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/security/settings/update": {
|
||||
"post": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/security/device-credentials/provision": {
|
||||
"post": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/notifications/webhooks": {
|
||||
"get": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/notifications/webhook/update": {
|
||||
"post": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/notifications/webhook/delete": {
|
||||
"delete": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/notifications/webhook/test": {
|
||||
"post": {
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user