homeagent-runner 0.0.0-stage → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +137 -0
  2. package/CONTRIBUTING.md +65 -0
  3. package/LICENSE +21 -0
  4. package/README.en.md +329 -0
  5. package/README.md +271 -2
  6. package/SECURITY.md +59 -0
  7. package/THIRD_PARTY_NOTICES.md +45 -0
  8. package/bin/runner.mjs +2 -0
  9. package/dist/runner/agent.js +254 -0
  10. package/dist/runner/cli.js +66 -0
  11. package/dist/runner/config-location.js +67 -0
  12. package/dist/runner/config.js +43 -0
  13. package/dist/runner/context.js +86 -0
  14. package/dist/runner/credentials.js +68 -0
  15. package/dist/runner/editor.js +262 -0
  16. package/dist/runner/files.js +298 -0
  17. package/dist/runner/git.js +333 -0
  18. package/dist/runner/lock.js +28 -0
  19. package/dist/runner/output-log.js +59 -0
  20. package/dist/runner/patch.js +103 -0
  21. package/dist/runner/permissions.js +93 -0
  22. package/dist/runner/policy.js +87 -0
  23. package/dist/runner/process-tree.js +28 -0
  24. package/dist/runner/processes.js +367 -0
  25. package/dist/runner/service.js +53 -0
  26. package/dist/runner/setup.js +79 -0
  27. package/dist/runner/tools.js +118 -0
  28. package/dist/shared/permissions.js +40 -0
  29. package/dist/shared/protocol.js +98 -0
  30. package/dist/shared/tools.js +108 -0
  31. package/docs/ARCHITECTURE.md +92 -0
  32. package/docs/CLIENTS.md +130 -0
  33. package/docs/COMPARISON.md +36 -0
  34. package/docs/DEPLOYMENT.md +295 -0
  35. package/docs/DEVELOPMENT_WORKFLOW.md +126 -0
  36. package/docs/OPEN_SOURCE.md +129 -0
  37. package/docs/README.md +26 -0
  38. package/docs/TOOLS.md +105 -0
  39. package/docs/VALIDATION.md +172 -0
  40. package/docs/WEBCODEX_CODE_AUDIT.md +107 -0
  41. package/docs/screenshots/dashboard.png +0 -0
  42. package/docs/screenshots/jobs.png +0 -0
  43. package/docs/screenshots/permissions.png +0 -0
  44. package/docs/webcodex-parity-map.json +75 -0
  45. package/docs/webcodex-source-inventory.json +2254 -0
  46. package/licenses/npm-runtime.txt +3673 -0
  47. package/package.json +45 -4
  48. package/public/icon.png +0 -0
  49. package/runtime/windows-process-tree.cs +105 -0
  50. package/runtime/windows-process-tree.ps1 +19 -0
package/README.md CHANGED
@@ -1,3 +1,272 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <img src="public/icon.png" width="128" height="128" alt="HomeAgent 图标">
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ <h1 align="center">HomeAgent</h1>
6
+
7
+ <p align="center">
8
+ <strong>让 AI 连接你的开发机器。</strong><br>
9
+ 自托管 MCP 中继 · 本地执行 · 权限由你掌控
10
+ </p>
11
+
12
+ <p align="center">
13
+ <a href="https://github.com/jhxxr/HomeAgent/actions/workflows/ci.yml"><img src="https://github.com/jhxxr/HomeAgent/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
14
+ <a href="https://www.npmjs.com/package/homeagent-server"><img src="https://img.shields.io/npm/v/homeagent-server?label=server&amp;color=0755ff" alt="Server npm version"></a>
15
+ <a href="https://www.npmjs.com/package/homeagent-runner"><img src="https://img.shields.io/npm/v/homeagent-runner?label=runner&amp;color=0755ff" alt="Runner npm version"></a>
16
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-147a57" alt="MIT License"></a>
17
+ <a href="CONTRIBUTING.md"><img src="https://img.shields.io/badge/Node.js-%E2%89%A524.14-339933" alt="Node.js 24.14 or newer"></a>
18
+ </p>
19
+
20
+ <p align="center">
21
+ 简体中文 · <a href="README.en.md">English</a>
22
+ </p>
23
+
24
+ <p align="center">
25
+ <a href="#快速开始">快速开始</a> ·
26
+ <a href="docs/DEPLOYMENT.md">部署指南</a> ·
27
+ <a href="docs/CLIENTS.md">连接 AI 客户端</a> ·
28
+ <a href="docs/README.md">完整文档</a> ·
29
+ <a href="CHANGELOG.md">更新日志</a>
30
+ </p>
31
+
32
+ ---
33
+
34
+ HomeAgent 让 Claude、ChatGPT、Cursor 等 MCP 客户端,通过你部署的 Server 操作自己的 Linux / Windows 开发机器。Runner 主动连出,在本地执行授权的文件、命令和 Git 操作,无需开放被控端入站端口。
35
+
36
+ 系统运行无需模型 API Key、第三方中继、遥测或付费云服务;工具结果会返回给你选择的 AI 客户端。当前版本 **v0.4.5**,支持单管理员、多设备。
37
+
38
+ ## 为什么使用 HomeAgent
39
+
40
+ | 自己的机器,自己的控制权 | 面向日常开发 |
41
+ | --- | --- |
42
+ | **自托管中继**:Server、SQLite 和审计记录部署在自己的服务器或局域网。 | **文件与代码编辑**:35 个工具覆盖项目上下文、批量按行读取、搜索、严格 diff 和多文件编辑。 |
43
+ | **Runner 主动连接**:通过认证的 WebSocket 通道接入,支持 Linux / Windows。 | **可观察的任务**:短命令直接返回,长任务可等待、读取输出、停止,并保留执行记录。 |
44
+ | **按项目授权**:管理设备、客户端、只读或完整开发权限,支持临时提权与到期收回。 | **完整 Git 流程**:查看差异、按文件安全提交,以及独立控制的 fetch / pull / push。 |
45
+
46
+ ## 界面预览
47
+
48
+ 真实 Web Dashboard 截图,使用本地隔离环境中的示例设备与项目。
49
+
50
+ ![HomeAgent 控制台:设备状态、MCP 接入和项目管理](docs/screenshots/dashboard.png)
51
+
52
+ <details>
53
+ <summary><strong>查看设备权限设置与任务输出</strong></summary>
54
+
55
+ **设备权限** · 在网页中配置项目目录、访问档位、Git 开关和授权时长。
56
+
57
+ ![设备权限设置:项目目录、完整开发与 Git 权限](docs/screenshots/permissions.png)
58
+
59
+ **任务与输出** · 观察 Runner 上真实执行的命令,读取测试输出。
60
+
61
+ ![任务管理:执行记录与测试输出](docs/screenshots/jobs.png)
62
+
63
+ </details>
64
+
65
+ ## 工作原理
66
+
67
+ ```mermaid
68
+ flowchart TB
69
+ Clients["Claude / ChatGPT / Cursor"] -->|"HTTPS · MCP · OAuth / Token"| Server["HomeAgent Server"]
70
+ Server --- Console["Web Dashboard · SQLite · 审计"]
71
+ Runner["Linux / Windows Runner"] -->|"主动连接 · WSS"| Server
72
+ Runner --- Files["项目文件与代码编辑"]
73
+ Runner --- Commands["本地命令与任务"]
74
+ Runner --- Git["Git 工作流"]
75
+ ```
76
+
77
+ 使用 MCP 官方 SDK v2,提供 Streamable HTTP `/mcp`,支持 2026-07-28 discovery/envelope 与 2025 协议兼容;认证包括 OAuth 授权码流程、S256 PKCE、限权 Bearer Token 和一次性设备配对。
78
+
79
+ ## 快速开始
80
+
81
+ Server 和 Runner 已拆成两个 npm 包,分别安装在中继服务器和需要被操作的开发机器上:
82
+
83
+ | 组件 | npm 包 | 命令 |
84
+ | --- | --- | --- |
85
+ | Server / Web Dashboard | `homeagent-server` | `homeagent-server` |
86
+ | Runner | `homeagent-runner` | `homeagent` |
87
+
88
+ | 场景 | 部署方式 |
89
+ | --- | --- |
90
+ | Linux 服务器长期运行 | Docker Compose + 自有域名 + Caddy 自动 HTTPS |
91
+ | 已有 Node.js 环境,或先在本机试用 | npm 安装,运行 `homeagent-server` |
92
+ | 已有 Nginx / Caddy | Server 监听回环地址,由现有反向代理提供 HTTPS |
93
+
94
+ 部署顺序:**启动 Server → 打开 Dashboard → 安装并配对 Runner → 在 AI 客户端连接 `/mcp`**。Server 使用内置 SQLite,无需额外安装数据库。
95
+
96
+ ### 1. 部署 Server
97
+
98
+ **方式 A:Docker Compose + Caddy,适合 Linux 公网服务器。**
99
+
100
+ 准备 Docker Engine、Compose v2 和 Git,将自己的域名解析到服务器,并放行 TCP 80/443。下面以 `mcp.example.com` 为例,执行前替换成自己的域名。
101
+
102
+ ```sh
103
+ git clone --branch v0.4.5 --depth 1 https://github.com/jhxxr/HomeAgent.git
104
+ cd HomeAgent
105
+
106
+ # 用容器生成随机密码和会话密钥,无需在宿主机安装 Node.js
107
+ docker run --rm --user "$(id -u):$(id -g)" \
108
+ -v "$PWD:/work" -w /work \
109
+ node:24.22.1-bookworm-slim node scripts/init.mjs
110
+ ```
111
+
112
+ 编辑刚生成的 `.env`,保留随机生成的 `ADMIN_PASSWORD` 和 `SESSION_SECRET`,修改或添加:
113
+
114
+ ```dotenv
115
+ PUBLIC_URL=https://mcp.example.com
116
+ DOMAIN=mcp.example.com
117
+ TRUST_PROXY_HOPS=1
118
+ ```
119
+
120
+ ```sh
121
+ docker compose --profile proxy up -d --build
122
+ docker compose --profile proxy ps
123
+ docker compose logs --tail=100 server
124
+ curl --fail https://mcp.example.com/health
125
+ ```
126
+
127
+ Caddy 自动申请证书并代理 HTTP/WebSocket。打开 `https://mcp.example.com`,使用 `.env` 中的 `ADMIN_PASSWORD` 登录 Dashboard。Server 端口 `3210` 默认只映射到宿主机 `127.0.0.1`,不需要向公网开放;镜像从源码在本机构建,没有预发布镜像要求。
128
+
129
+ SQLite 保存在 `server-data` 命名卷,Compose 配置了 `restart: unless-stopped`。升级前备份数据库和 `.env`;保留 `SESSION_SECRET`,不要用 `docker compose down --volumes` 作为普通重启命令。备份、恢复和已有 Nginx 的配置见 [部署文档](docs/DEPLOYMENT.md)。
130
+
131
+ **方式 B:npm 原生运行,适合 Linux / Windows 本机试用或已有 Node.js 的服务器。**
132
+
133
+ 需要 Node.js 24(最低 24.14.0,仓库固定的验证补丁版见 `.nvmrc`)和 npm。以下命令可在 Linux shell 或 Windows PowerShell 中执行:
134
+
135
+ ```sh
136
+ npm install -g homeagent-server@latest
137
+ mkdir homeagent-server
138
+ cd homeagent-server
139
+ homeagent-server init
140
+ homeagent-server
141
+ ```
142
+
143
+ 本机访问 `http://localhost:3210`,管理员密码在当前目录 `.env` 的 `ADMIN_PASSWORD` 中;初始化命令不打印密码,也不会覆盖已有配置。数据库默认位于当前目录的 `data/server.sqlite`。
144
+
145
+ 公网部署时,先将 `.env` 的 `PUBLIC_URL` 改成固定 HTTPS 域名;一层可信反向代理时设 `TRUST_PROXY_HOPS=1`,再由 Nginx/Caddy 代理到 `127.0.0.1:3210`。`homeagent-server` 在前台运行,并从**当前工作目录**读取 `.env`;长期运行需配置服务管理器。Linux systemd 示例见 [原生 Server 部署](docs/DEPLOYMENT.md#原生部署-server)。
146
+
147
+ ### 2. 安装并配对 Runner
148
+
149
+ 在需要被 AI 操作的开发机器上安装 Node.js 24、npm;Git 工具还需要本机 Git。推荐直接使用交互式登录:
150
+
151
+ ```sh
152
+ npm install -g homeagent-runner@latest
153
+ homeagent login
154
+ ```
155
+
156
+ 终端只询问 Web URL 和设备名称,自动生成 `$HOME/.homeagent/runner.json`,然后显示一个 10 分钟有效的浏览器登录链接。在网页中核对设备名称、填写被控端的项目目录并批准,也可以稍后在 Dashboard 的“管理设备权限”中添加项目。
157
+
158
+ **项目目录和权限只由 Server 保存**,本地配置不接受 `projects/root`。本地 `stateDir` 仅用于保存设备凭据和任务状态,不是项目目录。未配置项目时,Runner 不开放任何项目访问。首次项目设置默认永久保存;临时开放可在权限编辑器中另外选择。
159
+
160
+ ```sh
161
+ # 登录完成后,直接启动:
162
+ homeagent run
163
+ ```
164
+
165
+ Runner 自动记录成功登录或启动时的配置位置,切换工作目录后仍可直接使用 `homeagent run`。可通过 `homeagent run --config <路径>` 显式切换;查找顺序是显式路径、已记录路径、`~/.homeagent/runner.json`。首次登录也可使用 `homeagent login --run` 在批准后直接启动。
166
+
167
+ Windows 的项目根目录可在网页中填为 `E:/Projects/my-app`。Runner 配置和 stateDir 都必须位于所有暴露项目之外。本地只维护连接信息、设备凭据和任务状态。
168
+
169
+ 需要自启动时,完成配对并停止前台 Runner,再运行 `homeagent service-install`。Linux 安装用户 systemd 服务;Windows 安装当前用户登录时启动的计划任务。安装时自动识别配置位置,生成的服务固定使用该路径。
170
+
171
+ 默认不允许执行命令或 Git 写入。需要这些能力时,在 Dashboard 的设备权限中开启,并给客户端对应 scope。命令别名、环境 profile 和 linked worktree 目录同样在网页设备权限中配置。清空项目或断线后会收回全部项目访问;Server 与 Runner 应升级到相同版本。完整示例见 [日常开发工作流](docs/DEVELOPMENT_WORKFLOW.md)。
172
+
173
+ ### 3. 连接 AI 客户端
174
+
175
+ | 用途 | 公网部署示例 |
176
+ | --- | --- |
177
+ | Dashboard | `https://mcp.example.com` |
178
+ | AI 客户端 MCP 地址 | `https://mcp.example.com/mcp` |
179
+ | Runner 配置的 `server` | `https://mcp.example.com`,不要加 `/mcp` |
180
+ | 健康检查 | `https://mcp.example.com/health` |
181
+
182
+ 客户端可通过 OAuth 连接,在浏览器确认设备和项目权限;也可在 Dashboard 为已配对设备创建客户端令牌,选择 `read / write / execute / git` scope,再以 Bearer token 连接。令牌仅展示一次,设备凭据不能代替客户端令牌。
183
+
184
+ 本机验证时地址换成 `http://localhost:3210`;远程必须使用固定 HTTPS origin,不支持将 Server 挂在某个 URL 子路径下。各客户端配置见 [AI 客户端连接](docs/CLIENTS.md)。
185
+
186
+ ### 从源码开发
187
+
188
+ 需要修改源码时再选择此方式;日常安装使用上面的 npm 包或 Compose:
189
+
190
+ ```sh
191
+ git clone https://github.com/jhxxr/HomeAgent.git
192
+ cd HomeAgent
193
+ npm ci
194
+ npm run build
195
+ npm run init
196
+ npm run server
197
+ ```
198
+
199
+ 源码 Runner 使用 `npm run runner -- login` 和 `npm run runner -- run`,配置及配对流程相同。
200
+
201
+ ## 已实现的工具
202
+
203
+ | 类别 | 工具 |
204
+ | --- | --- |
205
+ | 发现与接续 | `list_devices`, `get_project_context`, `save_project_note` |
206
+ | 文件 | `list_directory`, `read_file`, `read_files`, `write_file`, `create_directory`, `move_file`, `get_file_info`, `search_files`, `edit_block`, `edit_files`, `apply_unified_diff`, `get_edit_transactions`, `recover_edit_transaction` |
207
+ | 终端 | `start_process`, `run_command`, `wait_process`, `read_process_output`, `tail_process_output`, `write_process_input`, `list_processes`, `stop_process` |
208
+ | Git | `git_status`, `git_diff`, `git_log`, `git_add`, `git_commit`, `git_commit_paths`, `git_branches`, `git_switch_branch`, `git_fetch`, `git_pull`, `git_push` |
209
+
210
+ 所有机器工具使用 `projectId`。多台有权限的设备同时在线时必须指定 `deviceId`,防止误操作另一台机器。进程使用任务 UUID,由启动它的客户端主体和项目共同拥有,不接受任意系统 PID。
211
+
212
+ Dashboard 可查看任务状态、输出和停止执行;Server 仅保存有界任务元数据,输出保留在 Runner。`start_process` 可提供稳定 `idempotencyKey`,避免不确定响应后的重试再次执行。同一 stateDir 的 Runner/配对进程互斥;Windows 用 Job Object、Linux 用进程组管理子孙进程。
213
+
214
+ v0.3 以日常开发为重点:短命令同步返回、长任务等待、环形尾部日志、本机命令别名/环境配置、按行批量读取、带恢复日志的多文件编辑与严格 Diff,以及保留用户其他暂存内容的指定文件提交。完整调用顺序、配置和边界见 [日常开发工作流](docs/DEVELOPMENT_WORKFLOW.md)。
215
+
216
+ ### Web 权限管理
217
+
218
+ v0.4 的权限分为两层,最终能力取设备上限与客户端授权的交集:
219
+
220
+ - **设备权限**:在 Dashboard 为每个项目设置项目目录或设备范围文件访问、命令 allowlist 或任意程序、Git 本地写入、fetch/pull 网络访问和单独的 push 权限。
221
+ - **客户端权限**:修改已有 PAT 或 OAuth 授权的设备、项目、scope、具体工具,以及“目录外文件”和“任意程序”高级开关,不需要重新复制凭据。
222
+ - **临时开放**:设备和客户端权限都可设置分钟级有效期;到期会停止相关托管任务并恢复原权限。权限 revision 冲突会被拒绝,避免覆盖他人的更新。
223
+
224
+ 任意程序仍以 Runner 运行账户的权限执行,不会自动获得管理员或 root 权限。设备权限修改会取消在途调用并停止托管任务,已经产生的文件修改不会自动回滚。旧 Runner 无法应用已保存的 Web 覆盖,升级 Server 和 Runner 到同一 `0.4.x` 后再使用。
225
+
226
+ ## 文档与项目结构
227
+
228
+ - [文档索引](docs/README.md):按使用、开发、安全与设计资料导航。
229
+ - [参考项目对比](docs/COMPARISON.md):源码修订、架构、协议、工具、安全与取舍。
230
+ - [WebCodex 逐工具源码审计](docs/WEBCODEX_CODE_AUDIT.md):29 个工具域、192 条声明的逐项映射,已修正缺口和仍未实现的能力;不宣称全量功能对等。
231
+ - [架构与技术选型](docs/ARCHITECTURE.md):模块、信任边界、消息协议、持久化及并发。
232
+ - [部署与运维](docs/DEPLOYMENT.md):Docker、Caddy、Nginx、可选 Cloudflare Tunnel、配对、自启动、备份恢复。
233
+ - [AI 客户端连接](docs/CLIENTS.md):ChatGPT、Claude、Cursor 及 MCP SDK 调试。
234
+ - [工具与配置参考](docs/TOOLS.md):调用格式、范围、分页、进程行为和权限。
235
+ - [安全模型](SECURITY.md):命令执行的真实权限、默认限制与尚未提供的隔离能力。
236
+ - [验证记录](docs/VALIDATION.md):已经执行的验证和未执行的环境验收。
237
+ - [日常开发工作流](docs/DEVELOPMENT_WORKFLOW.md):从失败测试到安全提交、断线接续;同时列明仍未实现的交互终端与预览能力。
238
+
239
+ ```text
240
+ bin/ # npm CLI entry points
241
+ src/
242
+ shared/ # versioned wire schemas, tool contracts, scopes
243
+ server/ # MCP, WS hub, pairing, OAuth, browser auth, SQLite, admin API
244
+ runner/ # outbound agent, local policy, files, processes, Git, services
245
+ public/ # Dashboard JS/CSS, no CDN or external fonts
246
+ deploy/ # Caddy and Nginx examples
247
+ scripts/ # secret initialization and SQLite online backup
248
+ tests/ # security/tool tests + real SDK/WS/OAuth integration
249
+ runtime/ # Windows process-tree supervisor sources
250
+ licenses/ # locked runtime dependency license texts
251
+ .github/ # Linux/Windows/Docker checks and npm/GitHub Release publishing
252
+ ```
253
+
254
+ ## 验证
255
+
256
+ ```sh
257
+ npm run verify
258
+ npm run notices:check
259
+ npm audit --omit=dev --audit-level=high
260
+ ```
261
+
262
+ 服务端和 Runner 的进程、文件策略是可信组件。目录策略保护内置文件工具;一旦授权通用运行时、shell 或构建工具,命令具有运行账户的实际权限,目录白名单不构成 OS 沙箱。生产环境请用独立低权限账户或只挂载必要目录的容器。项目包含可部署实现与自动化检查,但本地测试通过不等同于独立安全审计或所有客户端、所有平台验收完成。
263
+
264
+ ## 贡献与许可证
265
+
266
+ 欢迎提交可复现的问题和聚焦的改动,开发方式见 [CONTRIBUTING.md](CONTRIBUTING.md),版本范围见 [CHANGELOG.md](CHANGELOG.md)。安全问题按 [SECURITY.md](SECURITY.md) 私下报告。
267
+
268
+ 原始源码使用 [MIT License](LICENSE)。依赖保留自己的许可,见 [第三方声明](THIRD_PARTY_NOTICES.md)。本项目独立开发,不代表 WebCodex、Desktop Commander 或任何 AI 客户端厂商。
269
+
270
+ 发布前执行 [开源与发布检查](docs/OPEN_SOURCE.md)。npm 发布会生成两个包:`homeagent-server` 只包含 Server/Web Dashboard,`homeagent-runner` 只包含 Runner、共享协议和 Windows 辅助程序;两者都采用明确的发布文件白名单。
271
+
272
+ `v0.4.5` 的发布配置会分别生成 `homeagent-server` 和 `homeagent-runner`;本地发布命令不会自动上传 npm 或推送 GitHub。后续发布递增版本,更新版本文件和 changelog 后推送匹配标签;预发布使用 npm `next`,正式版本使用 `latest`。Token 权限、OIDC 切换和重试行为见 [自动发布说明](docs/OPEN_SOURCE.md#github-actions-自动发布)。
package/SECURITY.md ADDED
@@ -0,0 +1,59 @@
1
+ # 安全模型
2
+
3
+ v0.3 的多文件编辑使用摘要预检和私有恢复日志,冲突恢复不会覆盖与 after-image 不符的外部内容;不是跨文件快照隔离。指定文件提交保护其他暂存条目,ref/index 更新之间的故障仍需检查保留锁,不能盲目重试。v0.4 增加 Dashboard 可编辑的设备上限和客户端临时授权;命令别名和 environment profile 由管理员在 Server 的设备权限中配置。通用解释器依然拥有其运行账户权限。具体边界见 [日常开发工作流](docs/DEVELOPMENT_WORKFLOW.md)。
4
+
5
+ Runner 连接文件与私有状态必须位于暴露项目之外,应用 Server 项目设置时会检查配置文件的输入路径和 canonical 路径。本机文件不存储项目权限、命令别名或环境 profile;这些设置由 Server 保存。路径保护约束普通文件工具,已授权的系统命令仍使用操作系统账户权限。
6
+
7
+ 本项目具备认证、授权、本地路径策略、审计、设备撤销和资源限额;没有声称这些措施构成容器或内核级沙箱。
8
+
9
+ ## 信任模型
10
+
11
+ - 信任 Server、Runner、本地配置及运行它们的系统账户。Server 被攻陷可向 Runner 伪造调用主体,必须像管理入口一样保护。
12
+ - AI 客户端凭据只能访问授权设备、项目和 scopes;项目内容、模型生成参数、网络请求不可信。
13
+ - 设备凭据仅用于 `/runner`,浏览器登录仅用于管理 API,MCP 必须使用 OAuth/PAT。
14
+ - Runner 只连出,不开入站端口;长期凭据不会放在 URL 参数。禁止 TLS 凭据向重定向目标转发。
15
+ - MCP 结果会发送到所选 AI 客户端。无遥测和第三方中继不等于所用模型服务看不到返回内容。
16
+
17
+ ## 默认限制
18
+
19
+ - 公网 PUBLIC_URL 必须 HTTPS;Origin/Host 校验,Dashboard Cookie HttpOnly/SameSite,HTTPS 时 Secure/__Host- 前缀。
20
+ - 修改管理状态需 CSRF token,登录校验 Origin,失败限流。OAuth、配对、MCP 也有限流和请求大小限制。
21
+ - 自动生成高熵密码与 SESSION_SECRET,凭据不提交 Git。Server token 和配对凭据保存 SHA-256,OAuth confidential secrets 加密。
22
+ - commands 默认空;Git 写入默认关闭;readOnly 可禁止所有写入与命令。
23
+ - Runner 只接受 Server 的项目设置,设备权限与客户端授权仍分别需要授予;临时权限到期会停止对应托管任务并恢复永久权限。
24
+ - 设备范围文件访问、任意程序执行、Git 网络访问和 Git push 都是独立开关;设备范围访问仍保护 Runner 配置、stateDir 和显式 protected paths。
25
+ - 内置文件工具拒绝越界、symlink/junction、普通文件硬链接、Windows ADS/设备名别名;默认排除 .git/.env/.ssh/.aws/.homeagent。
26
+ - stateDir 必须与所有项目分离。Linux 凭据目录/文件权限 0700/0600,Windows CLI 施加当前账户和 SYSTEM ACL。
27
+ - 进程只能由其客户端主体、项目通过任务 UUID 管理,不能凭系统 PID 控制任意进程。
28
+ - 新 OAuth grant 固定选择的设备/项目,令牌刷新不扩权;同名项目在另一设备不自动获权。dispatch 再验证当前令牌,族撤销会取消仍在排队的调用。
29
+ - Runner 和配对进程对 stateDir 持有 OS-backed SQLite 互斥锁,崩溃释放,不根据历史 PID 删除锁或误杀进程。
30
+ - Windows 子进程在 suspended 状态加入 Kill-on-close Job Object 后才运行,supervisor 监视 Runner 死亡;Linux 清理原进程组。没有 supervisor 时不会悄悄降级。
31
+ - 输出、并发、扫描、帧大小、请求时间、历史任务都有上限。
32
+ - Git hooks、签名、diff/textconv、fsmonitor 被关闭;配置 clean/process filter 的仓库拒绝 Git 写入。
33
+ - 暂停或撤销在线设备会关闭连接并要求 Runner 停止其托管任务;撤销后新调用立即失败。已经完成的修改无法回滚。
34
+
35
+ ## 必须理解的边界
36
+
37
+ **允许解释器、shell 或构建工具就允许其使用运行账户的权限。** 它们可以通过绝对路径、网络、库或项目脚本绕过文件工具 API;commands 允许列表只限制入口可执行文件,不能约束其内部行为。即使未允许命令,对可写项目的文件修改也可能被其他自动构建/监视进程执行。不要把一个高权限热加载生产目录当作普通项目暴露。
38
+
39
+ 路径检查和 O_NOFOLLOW 降低链接绕过风险,但跨平台 Node API 不能提供所有 openat2/句柄相对操作的保证。具有本机并发文件替换能力的恶意进程仍可能制造检查/使用竞争;NTFS mount、Git 元数据、工具链配置也不受完整 OS 隔离。请用专用低权限账户、只挂载必要目录的容器/VM,并隔离凭据、生产密钥、SSH agent 和 Docker socket。
40
+
41
+ Runner 的命令在 Server 暂时断线时继续运行。设备撤销要求在线 Runner 停止;完全离线时 Server 无法远程强制杀进程。Windows supervisor 监视 Runner 进程死亡并关闭 Job;Linux Runner 被强制杀死仍需 systemd control-group/容器约束。重启不会根据旧 PID 杀进程。客户端令牌撤销不自动回滚已经产生的副作用或停止已经返回任务 ID 的长任务;可通过管理员任务界面显式停止。
42
+
43
+ Server 的任务镜像只有身份、状态、revision、退出信息与字节计数,不保存 argv、输出或错误正文。离线和缺失的观察状态不会被伪装成成功。管理员输出读取会通过正确的 Runner 实例和原任务主体执行,并以 admin 审计。管理员浏览器会话可单独撤销,不返回其他会话的 CSRF。
44
+
45
+ start_process 的幂等键只在已声明的 48 小时、主体/项目和同参数窗口内阻止重复准入,不是外部副作用的事务或所有工具的 exactly-once。文件 revision 基于元数据,不抵御能精确伪造本机文件元数据的恶意系统进程。
46
+
47
+ 审计存于本机 SQLite,能追溯调用,但不是防管理员篡改的外部账本。参数仅存 SHA-256 摘要,输出仅在 Runner 任务文件内保留。通过命令自身写出的日志和文件不受本项目输出限额控制,须有 OS 磁盘/内存/CPU 配额。
48
+
49
+ 当前为单管理员单 Server;没有多租户、MFA、端到端加密中继、外部 WORM 审计、自动证书固定、沙箱证明或任意客户端版本兼容保证。SQLite 以及 HTTP/WS 是单节点模型,不应多副本共享同一数据库文件。部署前应在自己的环境完成恢复演练和最小权限检查;本仓库测试不能替代独立安全评估。
50
+
51
+ ## 发现问题与响应
52
+
53
+ 先暂停或撤销设备与客户端凭据,再停止受影响的 Runner。检查 Dashboard 审计、Runner 任务输出和 Git 差异,轮换受影响凭据。SESSION_SECRET 轮换会让现有浏览器会话和 OAuth 客户端加密信息失效,需重新注册客户端;已泄露的 PAT/设备凭据仍需显式撤销。
54
+
55
+ 报告漏洞时不要在公开 issue 附带真实令牌、配对码、数据库、.env 或敏感输出;先提供可在临时目录复现的最小案例。
56
+
57
+ 在 GitHub 等平台托管后,优先使用该仓库启用的私有安全报告入口(GitHub 的 Security → Advisories → Report a vulnerability)。如果尚未开启私有入口,先公开询问维护者的私下联系方式,不公开漏洞利用细节。本仓库不预填不存在的联系地址。
58
+
59
+ 当前维护基线为 0.4.x;发布说明中的可运行和测试结果不等同于独立安全审计、服务等级承诺或对所有部署环境的支持。
@@ -0,0 +1,45 @@
1
+ # Third-party notices
2
+
3
+ HomeAgent's original source is released under the MIT License in [LICENSE](LICENSE).
4
+ Dependency packages, container base images, Git, Node.js and optional deployment
5
+ tools retain their own licenses. The HomeAgent license does not replace them.
6
+
7
+ ## Runtime npm dependencies
8
+
9
+ The complete inventory for the locked production dependency tree, with the license
10
+ and notice files distributed in the installed packages, is generated in
11
+ [licenses/npm-runtime.txt](licenses/npm-runtime.txt).
12
+
13
+ ```sh
14
+ npm ci
15
+ npm run notices
16
+ npm run notices:check
17
+ ```
18
+
19
+ The generator includes transitive production packages and preserves the supplied
20
+ license/notice text. Development-only packages are not redistributed in the
21
+ production Docker image; their license metadata and files remain in the installed
22
+ packages. A modified dependency tree requires regenerating the inventory.
23
+
24
+ The Docker image contains the HomeAgent license, this notice and the runtime
25
+ inventory. Node.js, the Debian base system and packages installed by apt retain
26
+ their license files in the image. Caddy and cloudflared are optional separate
27
+ images and are distributed under their respective upstream terms.
28
+
29
+ ## Design references
30
+
31
+ - WebCodex, `yyjeqhc/webcodex`, is a reference for Server/Runner separation,
32
+ project authorization and observable development jobs.
33
+ - Better Remote Commander, `shahidx0x/better-remote-commander`, is a reference for
34
+ outbound agents, pairing, a lightweight relay and practical file/process tools.
35
+ - Desktop Commander is a reference for tool naming and common file/terminal
36
+ workflows.
37
+
38
+ These are design acknowledgements. Their source repositories and binaries are not
39
+ vendored or redistributed in this repository. The comparison inventory records
40
+ tool identifiers, source locations and our own descriptions, rather than including
41
+ their implementations. See [the comparison](docs/COMPARISON.md) and
42
+ [source audit](docs/WEBCODEX_CODE_AUDIT.md) for pinned revisions.
43
+
44
+ HomeAgent is an independent project and does not imply endorsement by those
45
+ projects or by any AI client vendor.
package/bin/runner.mjs ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ await import('../dist/runner/cli.js');
@@ -0,0 +1,254 @@
1
+ import { WebSocket } from 'ws';
2
+ import { AppError, MAX_FRAME, RUNNER_PROTOCOL, VERSION, relayMessageSchema, result } from '../shared/protocol.js';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { toolSchemas } from '../shared/tools.js';
5
+ import { Tools } from './tools.js';
6
+ import { RunnerLock } from './lock.js';
7
+ import { RunnerPermissions } from './permissions.js';
8
+ export class Agent {
9
+ config;
10
+ credential;
11
+ log;
12
+ tools;
13
+ socket;
14
+ stopped = false;
15
+ retry;
16
+ watchdog;
17
+ attempt = 0;
18
+ active = new Map();
19
+ permissions;
20
+ permissionsReady = false;
21
+ requestedRevision = -1;
22
+ lock;
23
+ instanceId = randomUUID();
24
+ ready = false;
25
+ syncing = false;
26
+ dirty = new Map();
27
+ flushTimer;
28
+ closing;
29
+ constructor(config, credential, log = console.log) {
30
+ this.config = config;
31
+ this.credential = credential;
32
+ this.log = log;
33
+ if (credential.server !== config.server)
34
+ throw new AppError('server_changed', 'Credential server mismatch');
35
+ config.projects = [];
36
+ this.lock = new RunnerLock(config.stateDir);
37
+ try {
38
+ this.tools = new Tools(config, credential.deviceId);
39
+ }
40
+ catch (error) {
41
+ this.lock.close();
42
+ throw error;
43
+ }
44
+ this.permissions = new RunnerPermissions(config, this.tools, async () => {
45
+ this.permissionsReady = false;
46
+ for (const call of this.active.values())
47
+ call.controller.abort();
48
+ await Promise.all([...this.active.values()].map(call => call.done.catch(() => { })));
49
+ }, (revision, error) => this.reportPermissions(revision, error));
50
+ this.tools.processes.on('change', job => {
51
+ this.dirty.set(job.id, job);
52
+ if (!this.flushTimer)
53
+ this.flushTimer = setTimeout(() => { this.flushTimer = undefined; this.flushJobs(); }, 250).unref();
54
+ });
55
+ }
56
+ start() { this.connect(); }
57
+ projectViews() {
58
+ return this.config.projects.map(({ id, name, readOnly, commands, allowGitWrite, allowGitNetwork, allowGitPush, commandMode, filesystemScope, commandAliases, environmentProfiles }) => ({ id, name, readOnly, commands, allowGitWrite, allowGitNetwork, allowGitPush, commandMode, filesystemScope, commandAliasNames: Object.keys(commandAliases), environmentNames: Object.keys(environmentProfiles) }));
59
+ }
60
+ reportPermissions(revision, error) {
61
+ if (revision !== this.requestedRevision)
62
+ return;
63
+ this.permissionsReady = !error;
64
+ if (error)
65
+ this.log(`设备权限应用失败:${error}`);
66
+ else
67
+ this.log(this.config.projects.length
68
+ ? `当前生效项目目录(权限版本 ${revision}):\n${this.config.projects.map(project => ` ${project.id}: ${project.root}`).join('\n')}`
69
+ : '尚未配置项目目录,请在网页端为此设备添加项目。');
70
+ if (this.ready && this.socket?.readyState === WebSocket.OPEN)
71
+ this.socket.send(JSON.stringify({ type: 'permissions_applied', revision, projects: this.projectViews(), ...(error ? { error: error.slice(0, 512) } : {}) }));
72
+ }
73
+ applyPermissions(policy) {
74
+ this.requestedRevision = policy.revision;
75
+ this.permissionsReady = false;
76
+ void this.permissions.apply(policy).then(() => this.reportPermissions(policy.revision)).catch(error => this.reportPermissions(policy.revision, error instanceof Error ? error.message : 'Permission update failed'));
77
+ }
78
+ connect() {
79
+ if (this.stopped)
80
+ return;
81
+ const url = new URL('/runner', this.config.server);
82
+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
83
+ const socket = new WebSocket(url, { headers: { Authorization: `Bearer ${this.credential.token}`, 'X-Device-ID': this.credential.deviceId }, maxPayload: MAX_FRAME, perMessageDeflate: false, handshakeTimeout: 15000, followRedirects: false });
84
+ this.socket = socket;
85
+ const resetWatchdog = () => {
86
+ if (this.watchdog)
87
+ clearTimeout(this.watchdog);
88
+ this.watchdog = setTimeout(() => socket.terminate(), 45000).unref();
89
+ };
90
+ socket.on('open', () => {
91
+ resetWatchdog();
92
+ socket.send(JSON.stringify({
93
+ type: 'hello', protocol: RUNNER_PROTOCOL, name: this.config.name, platform: `${process.platform}/${process.arch}`, version: VERSION,
94
+ instanceId: this.instanceId, capabilities: Object.keys(toolSchemas),
95
+ projects: [],
96
+ }));
97
+ });
98
+ socket.on('ping', resetWatchdog);
99
+ socket.on('message', raw => {
100
+ try {
101
+ const message = relayMessageSchema.parse(JSON.parse(raw.toString()));
102
+ if (message.type === 'welcome') {
103
+ if (this.ready || message.deviceId !== this.credential.deviceId)
104
+ throw new Error('Unexpected device welcome');
105
+ this.ready = true;
106
+ this.attempt = 0;
107
+ void this.tools.processes.syncAuthorizations(message.authorizations).then(() => {
108
+ if (!this.ready || this.socket !== socket)
109
+ return;
110
+ this.applyPermissions(message.permissions);
111
+ }).catch(() => socket.terminate());
112
+ this.log(`Runner connected · ${message.deviceId}`);
113
+ void this.sendSnapshot(socket).catch(() => socket.terminate());
114
+ return;
115
+ }
116
+ if (!this.ready)
117
+ throw new Error('Welcome required');
118
+ if (message.type === 'cancel') {
119
+ this.active.get(message.id)?.controller.abort();
120
+ return;
121
+ }
122
+ if (message.type === 'permissions') {
123
+ this.applyPermissions(message.permissions);
124
+ return;
125
+ }
126
+ if (message.type === 'authorization_changed') {
127
+ for (const call of this.active.values())
128
+ if (call.authorizationId === message.authorizationId)
129
+ call.controller.abort();
130
+ void this.tools.processes.stopAuthorization(message.authorizationId).catch(error => this.log(`Authorization job stop failed: ${String(error)}`));
131
+ return;
132
+ }
133
+ if (!this.permissionsReady) {
134
+ socket.send(JSON.stringify({ type: 'result', id: message.id, result: result({ error: 'permissions_updating', message: 'Device permissions are being applied; retry after the Dashboard shows applied.' }, true) }));
135
+ return;
136
+ }
137
+ if (this.active.has(message.id) || this.active.size >= 32) {
138
+ socket.close(4400, 'Duplicate call or concurrency limit');
139
+ return;
140
+ }
141
+ if (message.principal.devices && !message.principal.devices.includes(this.credential.deviceId)) {
142
+ socket.close(4400, 'Device grant mismatch');
143
+ return;
144
+ }
145
+ const controller = new AbortController();
146
+ const deadline = Math.min(message.principal.authorizationExpiresAt ?? Infinity, this.tools.policy.expiresAt ?? Infinity);
147
+ const leaseTimer = Number.isFinite(deadline) ? setTimeout(() => controller.abort(), Math.max(1, deadline - Date.now())).unref() : undefined;
148
+ if (deadline <= Date.now())
149
+ controller.abort();
150
+ const done = this.tools.invoke(message.tool, message.args, message.principal, controller.signal).then(result => {
151
+ if (socket.readyState === WebSocket.OPEN)
152
+ socket.send(JSON.stringify({ type: 'result', id: message.id, result }));
153
+ }).finally(() => { if (leaseTimer)
154
+ clearTimeout(leaseTimer); this.active.delete(message.id); });
155
+ this.active.set(message.id, { controller, done, authorizationId: message.principal.authorizationId });
156
+ }
157
+ catch {
158
+ socket.close(4400, 'Invalid relay frame');
159
+ }
160
+ });
161
+ socket.on('unexpected-response', (_request, response) => {
162
+ response.resume();
163
+ if (response.statusCode === 401) {
164
+ this.stopped = true;
165
+ this.log('设备凭据被拒绝。请检查撤销状态;需要时显式重新配对。');
166
+ void this.close().catch(error => this.log(`Runner shutdown failed: ${String(error)}`));
167
+ }
168
+ if (response.statusCode === 403)
169
+ void this.tools.processes.stopAll().catch(error => this.log(`Process stop failed: ${String(error)}`));
170
+ socket.terminate();
171
+ });
172
+ socket.on('error', () => { });
173
+ socket.on('close', code => {
174
+ if (this.watchdog)
175
+ clearTimeout(this.watchdog);
176
+ this.ready = false;
177
+ this.syncing = false;
178
+ this.permissionsReady = false;
179
+ void this.tools.processes.stopTemporaryAuthorizations().catch(error => this.log(`Temporary authorization shutdown failed: ${String(error)}`));
180
+ void this.permissions.reset().catch(error => this.log(`Permission reset failed: ${String(error)}`));
181
+ for (const call of this.active.values())
182
+ call.controller.abort();
183
+ if (code === 4401 || code === 4000) {
184
+ this.stopped = true;
185
+ this.log(code === 4401 ? '设备已撤销,请重新配对。' : '设备连接已被另一 Runner 替换,停止本实例以避免重复执行。');
186
+ void this.close().catch(error => this.log(`Runner shutdown failed: ${String(error)}`));
187
+ }
188
+ if (code === 4403)
189
+ void this.tools.processes.stopAll().catch(error => this.log(`Process stop failed: ${String(error)}`));
190
+ if (!this.stopped) {
191
+ const delay = Math.min(30000, 1000 * 2 ** Math.min(this.attempt++, 5)) + Math.random() * 500;
192
+ this.log(`Runner disconnected; reconnecting in ${Math.round(delay / 1000)}s`);
193
+ this.retry = setTimeout(() => this.connect(), delay);
194
+ }
195
+ });
196
+ }
197
+ async sendSnapshot(socket) {
198
+ this.syncing = true;
199
+ const jobs = this.tools.processes.snapshot(), snapshotId = randomUUID();
200
+ this.dirty.clear();
201
+ try {
202
+ for (let offset = 0, page = 0; offset < jobs.length || page === 0; offset += 100, page++) {
203
+ if (this.socket !== socket || !this.ready || this.stopped)
204
+ return;
205
+ await new Promise((resolve, reject) => socket.send(JSON.stringify({ type: 'jobs_snapshot', snapshotId, page, done: offset + 100 >= jobs.length, jobs: jobs.slice(offset, offset + 100) }), error => error ? reject(error) : resolve()));
206
+ }
207
+ }
208
+ finally {
209
+ if (this.socket === socket) {
210
+ this.syncing = false;
211
+ this.flushJobs();
212
+ }
213
+ }
214
+ }
215
+ flushJobs() {
216
+ const socket = this.socket;
217
+ if (!socket || socket.readyState !== WebSocket.OPEN || !this.ready || this.syncing || this.stopped)
218
+ return;
219
+ for (const [id, job] of this.dirty) {
220
+ if (socket.bufferedAmount > MAX_FRAME * 2) {
221
+ socket.terminate();
222
+ return;
223
+ }
224
+ socket.send(JSON.stringify({ type: 'job_update', job }), error => { if (error)
225
+ socket.terminate(); });
226
+ this.dirty.delete(id);
227
+ }
228
+ }
229
+ close() {
230
+ if (this.closing)
231
+ return this.closing;
232
+ this.stopped = true;
233
+ this.ready = false;
234
+ if (this.retry)
235
+ clearTimeout(this.retry);
236
+ if (this.watchdog)
237
+ clearTimeout(this.watchdog);
238
+ if (this.flushTimer)
239
+ clearTimeout(this.flushTimer);
240
+ this.closing = (async () => {
241
+ for (const call of this.active.values())
242
+ call.controller.abort();
243
+ this.socket?.close(1000, 'Runner shutdown');
244
+ this.socket?.terminate();
245
+ await Promise.all([...this.active.values()].map(call => call.done));
246
+ await this.permissions.reset();
247
+ this.permissions.close();
248
+ await this.tools.close();
249
+ this.lock.close();
250
+ })();
251
+ return this.closing;
252
+ }
253
+ }
254
+ //# sourceMappingURL=agent.js.map