claudroid-bridge 0.0.0-stage → 0.1.1

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.
package/README.md CHANGED
@@ -1,3 +1,182 @@
1
- # Temporary Holding Version
1
+ # claudroid-bridge
2
2
 
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.
3
+ 主机侧守护进程:让 Claudroid 手机的 Claude Code 会话在**这台主机**上执行。
4
+ 手机负责界面、会话与逐条权限确认;守护进程负责运行 Claude Code、转发事件、文件访问与
5
+ Cloudflare Tunnel。
6
+
7
+ - 协议:[`docs/BRIDGE_CONTRACT.md`](../docs/BRIDGE_CONTRACT.md) §6.9(v1)
8
+ - 部署与安全模型:[`docs/REMOTE_HOST.md`](../docs/REMOTE_HOST.md)
9
+ - 运行 Claude Code 的是主机自己的登录态 / API Key / Base URL / 模型配置;手机不会发送
10
+ 任何供应商凭据。
11
+
12
+ ## 环境要求
13
+
14
+ - Node.js **20 或更高**(`engines` 已约束)。
15
+ - 主机上已能运行 Claude Code:执行过 `claude login`,或环境里配置了
16
+ `ANTHROPIC_API_KEY` 等。默认使用 Agent SDK 自带的 CLI;也可用
17
+ `claudeExecutable` / `--config` 指向系统安装的 `claude`。
18
+ - 使用隧道时无需预先安装 `cloudflared`:首次启用会自动下载官方版本并校验 sha256(见下文)。
19
+
20
+ ## 安装
21
+
22
+ ```bash
23
+ # 从 npm
24
+ npm install -g claudroid-bridge
25
+
26
+ # 从源码(开发/未发布版本)
27
+ git clone <repo> && cd claudroid/bridge
28
+ npm ci
29
+ npm run build
30
+ npm link # 把 claudroid-bridge 命令链到当前构建
31
+ ```
32
+
33
+ ## 快速开始
34
+
35
+ ```bash
36
+ claudroid-bridge init # 写入 ~/.config/claudroid-bridge/config.json
37
+ $EDITOR ~/.config/claudroid-bridge/config.json # 至少改 roots / defaultCwd
38
+ claudroid-bridge doctor # 检查 Node、配置、工作区与 cloudflared
39
+ claudroid-bridge start # 启动并打印配对码与主机地址
40
+ ```
41
+
42
+ `start` 打印的 8 位配对码 10 分钟内有效、只能使用一次;配对成功后 daemon 会轮换下一个
43
+ 配对码并重新打印。配对码过期后重启 `start` 生成新码。手机端在
44
+ **设置 → 远程主机 → 添加远程主机** 填入主机地址和配对码。
45
+
46
+ 常用命令:
47
+
48
+ ```bash
49
+ claudroid-bridge pair # 查看当前配对码、有效期与主机地址
50
+ claudroid-bridge devices # 列出已配对设备
51
+ claudroid-bridge devices revoke <id> # 吊销设备令牌
52
+ ```
53
+
54
+ ## 配置
55
+
56
+ 默认 `~/.config/claudroid-bridge/config.json`;`CLAUDROID_BRIDGE_HOME` 改变根目录
57
+ (`config.json` / `devices.json` / `pair.json` 都放这里),`--config <path>` 单独指定文件。
58
+ 所有字段都有安全默认值,配置损坏时按默认值启动。
59
+
60
+ ```json
61
+ {
62
+ "bind": "127.0.0.1",
63
+ "port": 8787,
64
+ "roots": ["/home/me", "/srv/projects"],
65
+ "defaultCwd": "/home/me",
66
+ "permissionTimeoutMs": 120000,
67
+ "maxUploadBytes": 104857600,
68
+ "allowBypassPermissions": false,
69
+ "claudeExecutable": "/usr/local/bin/claude",
70
+ "tunnel": {
71
+ "mode": "off",
72
+ "token": "",
73
+ "hostname": "",
74
+ "cloudflaredPath": "/usr/local/bin/cloudflared"
75
+ }
76
+ }
77
+ ```
78
+
79
+ | 字段 | 说明 |
80
+ | --- | --- |
81
+ | `bind` / `port` | 默认 `127.0.0.1:8787`。**不要直接暴露到公网**;公网访问走隧道或自己的反代 |
82
+ | `roots` | App 可浏览、可执行 Claude Code 的绝对路径白名单 |
83
+ | `defaultCwd` | 手机未指定目录时的工作目录,必须落在 `roots` 内 |
84
+ | `permissionTimeoutMs` | 权限确认等待上限(1000 毫秒 – 1 小时),超时即拒绝 |
85
+ | `maxUploadBytes` | 单次上传 / 下载与请求体的大小上限 |
86
+ | `allowBypassPermissions` | 默认 `false`;只有信任 App 侧操作时才允许 `bypassPermissions` |
87
+ | `claudeExecutable` | 可选;不填时使用 Agent SDK 随包的 CLI |
88
+ | `tunnel.mode` | `off` / `quick` / `named` |
89
+ | `tunnel.token` / `hostname` | named 隧道必填 |
90
+ | `tunnel.cloudflaredPath` | 可选;指定自定义 cloudflared。留空时先复用 `PATH`,缺失则自动下载到 `~/.config/claudroid-bridge/bin/` |
91
+
92
+ `start` 的等价参数:`--bind`、`--port`、`--root`(可重复)、`--tunnel`、
93
+ `--tunnel-token`、`--tunnel-hostname`、`--allow-bypass`、`--config`。
94
+
95
+ ## Cloudflare Tunnel
96
+
97
+ ```bash
98
+ # quick:每次启动生成新的 *.trycloudflare.com 地址,适合临时试用
99
+ claudroid-bridge start --tunnel quick
100
+
101
+ # named:在 Cloudflare 创建隧道后使用固定域名
102
+ claudroid-bridge start --tunnel named \
103
+ --tunnel-token <token> \
104
+ --tunnel-hostname claude.example.com
105
+ ```
106
+
107
+ **cloudflared 无需手动安装。** 首次启用隧道时,daemon 会从 Cloudflare 官方 GitHub
108
+ Release 下载固定版本的连接器,按内置 SHA-256 校验后安装到
109
+ `~/.config/claudroid-bridge/bin/cloudflared`(Windows 为 `cloudflared.exe`),之后复用。
110
+ 若 `PATH` 里已有 cloudflared,会优先使用;`tunnel.cloudflaredPath` 可强制指定。
111
+ 下载失败或校验不符时隧道进入错误状态并在 App 中显示原因,不会带病启动。
112
+
113
+ daemon 负责启动与监督 `cloudflared`,异常退出按指数退避重启;隧道状态与公网地址通过
114
+ `/v1/tunnel` 和 SSE 推给 App,也可以在手机的主机详情页开关。quick 地址会变化,长期使用
115
+ 请配置 named tunnel。
116
+
117
+ ## 作为系统服务运行
118
+
119
+ ```ini
120
+ # /etc/systemd/system/claudroid-bridge.service
121
+ [Unit]
122
+ Description=Claudroid Bridge
123
+ After=network-online.target
124
+
125
+ [Service]
126
+ Type=simple
127
+ User=me
128
+ Environment=HOME=/home/me
129
+ ExecStart=/usr/local/bin/claudroid-bridge start
130
+ Restart=on-failure
131
+ RestartSec=3
132
+
133
+ [Install]
134
+ WantedBy=default.target
135
+ ```
136
+
137
+ `claudroid-bridge start` 在前台运行并处理 `SIGINT` / `SIGTERM`。配对码写入
138
+ `~/.config/claudroid-bridge/pair.json`(0600),需要时用 `claudroid-bridge pair` 查看。
139
+
140
+ ## 安全模型
141
+
142
+ - 默认只绑定 `127.0.0.1`;公网暴露必须经 Cloudflare Tunnel 或你自己控制的反代。
143
+ - 配对码一次性、10 分钟有效、限速;设备令牌 32 字节随机,daemon 只保存 SHA-256,
144
+ 常量时间比较。
145
+ - 所有文件路径先 `realpath`,必须落在 `roots` 内;拒绝 `..` 与 symlink 逃逸。
146
+ - 权限请求默认拒绝:App 断连或超过 `permissionTimeoutMs` 未响应,工具调用即被拒绝。
147
+ - token、配对码、prompt 与 Access secret 不写日志。设备令牌可用
148
+ `devices revoke` 吊销。
149
+
150
+ ## 开发
151
+
152
+ ```bash
153
+ npm ci
154
+ npm run dev # tsx src/cli.ts,直接跑 TypeScript
155
+ npm test # vitest:鉴权、事件缓冲、权限、文件路径、隧道、HTTP 协议
156
+ npm run typecheck
157
+ npm run build # 产出 dist/(CLI 入口 dist/cli.js)
158
+ ```
159
+
160
+ 源码结构:
161
+
162
+ ```
163
+ src/cli.ts 命令解析、启动/配对/doctor/devices
164
+ src/server.ts HTTP + SSE 路由
165
+ src/auth.ts 配对码、设备令牌哈希、设备存储
166
+ src/turns.ts turn 生命周期与有界事件缓冲
167
+ src/sdk-runner.ts Agent SDK query() 封装(stream-json 透传、resume、abort)
168
+ src/permissions.ts canUseTool → SSE → 等待手机决定
169
+ src/files.ts roots 校验与文件 RPC
170
+ src/tunnel.ts cloudflared 启动、URL 解析与监督
171
+ src/cloudflared.ts 固定版本下载、sha256 校验与托管路径
172
+ src/config.ts 配置文件读写与归一化
173
+ src/events.ts SSE 事件总线
174
+ test/ vitest;用假 runner 覆盖协议、权限、重连与路径逃逸
175
+ ```
176
+
177
+ ## 发布新版本
178
+
179
+ 1. `npm version 0.1.1 --no-git-tag-version`,并同步 `src/version.ts` 的 `DAEMON_VERSION`。
180
+ 2. `npm test && npm run build`。
181
+ 3. `npx npm@11 stage publish --access public`(当前 granular token 为 stage-only)。
182
+ 4. 在 npmjs.com 的 **Account settings → Staged Packages** 用 2FA 批准。
package/dist/auth.js ADDED
@@ -0,0 +1,182 @@
1
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { writeFilePrivate } from "./config.js";
4
+ const CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
5
+ const CODE_LENGTH = 8;
6
+ export class AuthError extends Error {
7
+ status;
8
+ constructor(message, status) {
9
+ super(message);
10
+ this.status = status;
11
+ this.name = "AuthError";
12
+ }
13
+ }
14
+ function hashToken(token) {
15
+ return createHash("sha256").update(token, "utf8").digest("hex");
16
+ }
17
+ function constantTimeEqual(a, b) {
18
+ const left = Buffer.from(a, "utf8");
19
+ const right = Buffer.from(b, "utf8");
20
+ if (left.length !== right.length)
21
+ return false;
22
+ return timingSafeEqual(left, right);
23
+ }
24
+ function newPairingCode() {
25
+ const bytes = randomBytes(CODE_LENGTH);
26
+ let out = "";
27
+ for (let i = 0; i < CODE_LENGTH; i += 1) {
28
+ out += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length];
29
+ }
30
+ return out;
31
+ }
32
+ export class DeviceStore {
33
+ path;
34
+ devices;
35
+ constructor(path) {
36
+ this.path = path;
37
+ this.devices = this.load();
38
+ }
39
+ load() {
40
+ if (!existsSync(this.path))
41
+ return [];
42
+ try {
43
+ const parsed = JSON.parse(readFileSync(this.path, "utf8"));
44
+ if (!Array.isArray(parsed.devices))
45
+ return [];
46
+ return parsed.devices.filter((d) => d !== null &&
47
+ typeof d === "object" &&
48
+ typeof d.id === "string" &&
49
+ typeof d.name === "string" &&
50
+ typeof d.tokenHash === "string" &&
51
+ typeof d.createdAt === "number");
52
+ }
53
+ catch {
54
+ // A corrupted device list must not lock the operator out of the daemon.
55
+ return [];
56
+ }
57
+ }
58
+ save() {
59
+ writeFilePrivate(this.path, `${JSON.stringify({ devices: this.devices }, null, 2)}\n`);
60
+ }
61
+ list() {
62
+ return this.devices.map(({ id, name, createdAt, lastSeenAt }) => ({
63
+ id,
64
+ name,
65
+ createdAt,
66
+ lastSeenAt,
67
+ }));
68
+ }
69
+ add(device) {
70
+ this.devices.push(device);
71
+ this.save();
72
+ }
73
+ remove(id) {
74
+ const before = this.devices.length;
75
+ this.devices = this.devices.filter((d) => d.id !== id);
76
+ if (this.devices.length === before)
77
+ return false;
78
+ this.save();
79
+ return true;
80
+ }
81
+ findByToken(token) {
82
+ const hash = hashToken(token);
83
+ return this.devices.find((d) => constantTimeEqual(d.tokenHash, hash));
84
+ }
85
+ touch(id, now) {
86
+ const device = this.devices.find((d) => d.id === id);
87
+ if (!device)
88
+ return;
89
+ device.lastSeenAt = now;
90
+ try {
91
+ this.save();
92
+ }
93
+ catch {
94
+ // Last-seen bookkeeping must never fail an authenticated request.
95
+ }
96
+ }
97
+ }
98
+ export class AuthService {
99
+ store;
100
+ pairing = null;
101
+ attempts = new Map();
102
+ pairingTtlMs;
103
+ maxAttempts;
104
+ attemptWindowMs;
105
+ constructor(store, options = {}) {
106
+ this.store = store;
107
+ this.pairingTtlMs = options.pairingTtlMs ?? 10 * 60_000;
108
+ this.maxAttempts = options.maxAttempts ?? 5;
109
+ this.attemptWindowMs = options.attemptWindowMs ?? 10 * 60_000;
110
+ }
111
+ issuePairingCode(now = Date.now()) {
112
+ this.pairing = { code: newPairingCode(), expiresAt: now + this.pairingTtlMs };
113
+ return this.pairing;
114
+ }
115
+ currentPairingInfo(now = Date.now()) {
116
+ if (this.pairing && this.pairing.expiresAt <= now)
117
+ this.pairing = null;
118
+ return this.pairing;
119
+ }
120
+ allowed(ip, now) {
121
+ const window = this.attempts.get(ip);
122
+ if (!window || window.resetAt <= now)
123
+ return true;
124
+ return window.count < this.maxAttempts;
125
+ }
126
+ recordFailure(ip, now) {
127
+ const window = this.attempts.get(ip);
128
+ if (!window || window.resetAt <= now) {
129
+ this.attempts.set(ip, { count: 1, resetAt: now + this.attemptWindowMs });
130
+ return;
131
+ }
132
+ window.count += 1;
133
+ }
134
+ pair(code, deviceName, ip, now = Date.now()) {
135
+ if (!this.allowed(ip, now)) {
136
+ throw new AuthError("配对尝试过于频繁,请稍后再试。", 429);
137
+ }
138
+ const pairing = this.currentPairingInfo(now);
139
+ const normalized = code.trim().toUpperCase();
140
+ if (!pairing ||
141
+ normalized.length !== CODE_LENGTH ||
142
+ !constantTimeEqual(normalized, pairing.code)) {
143
+ this.recordFailure(ip, now);
144
+ throw new AuthError("配对码无效或已过期。", 401);
145
+ }
146
+ const token = randomBytes(32).toString("base64url");
147
+ const record = {
148
+ id: randomUUID(),
149
+ name: deviceName.trim().slice(0, 64) || "Android",
150
+ tokenHash: hashToken(token),
151
+ createdAt: now,
152
+ lastSeenAt: now,
153
+ };
154
+ this.store.add(record);
155
+ // Single use: the operator gets a fresh code for the next device.
156
+ this.pairing = null;
157
+ this.attempts.delete(ip);
158
+ return {
159
+ token,
160
+ device: {
161
+ id: record.id,
162
+ name: record.name,
163
+ createdAt: record.createdAt,
164
+ lastSeenAt: record.lastSeenAt,
165
+ },
166
+ };
167
+ }
168
+ verify(token, now = Date.now()) {
169
+ if (!token)
170
+ return null;
171
+ const device = this.store.findByToken(token);
172
+ if (device)
173
+ this.store.touch(device.id, now);
174
+ return device ?? null;
175
+ }
176
+ listDevices() {
177
+ return this.store.list();
178
+ }
179
+ revokeDevice(id) {
180
+ return this.store.remove(id);
181
+ }
182
+ }