pi-hub-server 0.3.2 → 0.4.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 +171 -40
- package/bin/pi-hub.mjs +176 -22
- package/docs/AUTH.md +128 -9
- package/package.json +4 -1
- package/src/config.mjs +8 -2
- package/src/listen.mjs +207 -0
- package/src/net-allow.mjs +134 -0
- package/src/pairing.mjs +252 -2
- package/src/pi-args.mjs +35 -12
- package/src/pi-session.mjs +48 -3
- package/src/pi-version.mjs +116 -0
- package/src/proxy-auth.mjs +57 -0
- package/src/registry.mjs +10 -1
- package/src/rpc-once.mjs +22 -2
- package/src/server.mjs +132 -42
- package/src/session-lock-fallback.mjs +203 -0
- package/src/session-lock.mjs +77 -25
- package/systemd/pi-hub.service +18 -0
- package/web/app.js +384 -17
- package/web/index.html +11 -1
- package/web/style.css +201 -1
- package/web/sw.js +6 -10
package/docs/AUTH.md
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
# 鉴权
|
|
2
2
|
|
|
3
3
|
pi-hub 是单用户、自托管、**无 TLS** 的 HTTP+SSE 后端。默认只监听 `127.0.0.1`;对外必须走
|
|
4
|
-
Tailscale / WireGuard
|
|
5
|
-
|
|
4
|
+
Tailscale / WireGuard(见文末「威胁边界」)。监听地址/端口由 `serve --host/--port` > `PI_HUB_HOST/PORT`
|
|
5
|
+
> `~/.config/pi-hub/listen.json` > 首次交互询问 > 默认决定,`pi-hub listen` 可查看/设置(0600)。本文件是各鉴权方式的选型、失败码、吊销/轮换与边界说明;
|
|
6
|
+
实现见 `src/web-auth.mjs`(cookie/CSRF)、`src/pairing.mjs`(6 位码配对 / 设备 token / legacy 签名)、`src/otp.mjs`(一次性码)、
|
|
6
7
|
`src/totp.mjs`(TOTP)、`src/proxy-auth.mjs`(反代身份)与 `src/server.mjs` 的接线。
|
|
7
8
|
|
|
8
9
|
## 选哪种
|
|
9
10
|
|
|
10
11
|
| 场景 | 用哪个 | 怎么开 |
|
|
11
12
|
|---|---|---|
|
|
12
|
-
| 个人手机上的 App | **M2**
|
|
13
|
+
| 个人手机上的 App | **M2** 6 位码配对 + 设备 token(默认只带 Bearer) | 电脑 banner 的配对码(或 `pi-hub pair-code`)→ 手机 `POST /v1/pair/claim` |
|
|
14
|
+
| 旧版 App(至少保留一个版本) | **M2-legacy** 设备令牌 + ECDSA P-256 签名(Android Keystore) | 手机发起配对 → 主机 SSH/TTY 里 `pi-hub pair --approve <code>`(无终端的 agent 通道加 `--force`) |
|
|
13
15
|
| 浏览器(本机或同网段手机) | **M3** 网页会话 cookie(+ CSRF),配合 **M4** 一次性登录码免抄令牌 | `pi-hub web-login` 打印 `http://<host>:<port>/#code=XXXX-XXXX`,浏览器输入 8 位码兑换 |
|
|
14
16
|
| 已配 Tailscale Serve / Cloudflare Access 隧道 | **M6** 反向代理可信身份头 | hub 环境里设 `PI_HUB_TRUST_PROXY=1` + `PI_HUB_PROXY_SECRET=<shared secret>` |
|
|
15
17
|
| curl / CI / 桌面脚本 / 机器对机器 | **M1** 主令牌 Bearer(`~/.config/pi-hub/token`) | `pi-hub token` |
|
|
@@ -27,10 +29,42 @@ curl -s -H "authorization: Bearer $(pi-hub token)" http://127.0.0.1:6768/v1/sess
|
|
|
27
29
|
|
|
28
30
|
恒时比较(`timingSafeEqual`);关掉鉴权只用 `PI_HUB_NO_AUTH=1`(本机调试)。
|
|
29
31
|
|
|
30
|
-
##
|
|
32
|
+
## 6 位码配对 + 设备 token(M2,默认)
|
|
31
33
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
+
电脑屏幕上的一次性 6 位码 + 手机自己生成的 32 B 随机 token,一次交互换长期凭据:
|
|
35
|
+
|
|
36
|
+
1. 电脑:`pi-hub serve` 启动 banner 打印 `配对码 123456(5 分钟内有效,一次性)`;也可随时
|
|
37
|
+
`pi-hub pair-code` 再生成(本机 loopback + 主令牌,agent 可调)。
|
|
38
|
+
2. 手机:`token = base64url(SecureRandom(32 B))`(43 字符),然后
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
curl -s -X POST http://<host>:<port>/v1/pair/claim \
|
|
42
|
+
-H 'content-type: application/json' \
|
|
43
|
+
-d '{"code":"123456","name":"HUAWEI ELS-AN00","platform":"android","token":"<43 字符>"}'
|
|
44
|
+
# 200 {"ok":true,"deviceId":"…","deviceName":"HUAWEI ELS-AN00"}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
3. 服务端只存 `tokenSha256`(`devices.json`,0600,`source:"code"`,无 `publicKeyPem`),
|
|
48
|
+
码标记已用并立即从可兑换集合移除;响应不回显 token。
|
|
49
|
+
4. 之后请求只带 `Authorization: Bearer <token>`。默认**不要求签名**,`x-pi-device`/`x-pi-ts`/
|
|
50
|
+
`x-pi-nonce`/`x-pi-sig` 等头一律忽略。
|
|
51
|
+
|
|
52
|
+
码的边界:TTL 固定 5 min、单次消费、同时最多 8 个未消费码(第 9 个 `429 too_many_codes`)、
|
|
53
|
+
生成与兑换各每 IP 10 次/分;同一码(或同一码字串)失败 5 次即 `429 code_locked`。
|
|
54
|
+
失败码见文末失败码表。
|
|
55
|
+
|
|
56
|
+
### 签名是可选的(`PI_HUB_REQUIRE_SIGNATURE`)
|
|
57
|
+
|
|
58
|
+
- 默认关:设备 token 只做 `sha256` 恒时比较 + 未吊销判定,通过即放行。
|
|
59
|
+
- `PI_HUB_REQUIRE_SIGNATURE=1`:第 3 步之后仍走 `verifyDeviceSignature()`(ts ±180 s、nonce 10 min 去重、
|
|
60
|
+
ECDSA 验签),失败 `401 bad_signature`。这是旧版 App 的口径,保留一个版本。
|
|
61
|
+
- 主令牌与网页 cookie 从不要求签名。
|
|
62
|
+
|
|
63
|
+
## 设备令牌 + ECDSA 签名(M2-legacy)
|
|
64
|
+
|
|
65
|
+
旧版 App 的链路,协议与配对流程见 README「设备配对(legacy)」。要点:只存 `sha256(token)`,
|
|
66
|
+
私钥不可导出,签名覆盖 `METHOD/PATH/TS/NONCE/SHA256(body)`,ts ±180 s、nonce 10 min 去重。
|
|
67
|
+
默认已不要求签名;只有 `PI_HUB_REQUIRE_SIGNATURE=1` 时才恢复强制验签。
|
|
34
68
|
|
|
35
69
|
## 网页会话 cookie(M3)
|
|
36
70
|
|
|
@@ -91,6 +125,82 @@ hub 启动时读一次 env,请求入口在常规鉴权**之前**尝试解析
|
|
|
91
125
|
命中后 `req.auth = {kind:"proxy", user}`,权限等价主令牌(可读 `/v1/devices`、`/v1/web/sessions` 等)。
|
|
92
126
|
`/v1/web/otp` 仍要求 loopback + 主权限,所以反代机器上生成一次性码仍要走本机 CLI。
|
|
93
127
|
|
|
128
|
+
## 公网模式(Tailscale 不可用时)
|
|
129
|
+
|
|
130
|
+
Tailscale 装不了、tailnet 掉了、或者只是想把 hub 分享给一个临时浏览器 —— 这时只能把 hub 暴露到公网。
|
|
131
|
+
安全前提只有一条:**TLS 必须在某个终止点结束,hub 自己永远只听回环**。
|
|
132
|
+
|
|
133
|
+
### 拓扑
|
|
134
|
+
|
|
135
|
+
```
|
|
136
|
+
客户端(任何设备,无需装 Tailscale)
|
|
137
|
+
│ HTTPS
|
|
138
|
+
▼
|
|
139
|
+
反代/隧道(cloudflared / caddy / nginx / frp) ← 证书在这里
|
|
140
|
+
│ http://127.0.0.1:6768
|
|
141
|
+
▼
|
|
142
|
+
hub(PI_HUB_HOST=127.0.0.1)
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### 三条可以过公网的鉴权通道
|
|
146
|
+
|
|
147
|
+
| 通道 | 公网上能做什么 | 为什么安全 |
|
|
148
|
+
|---|---|---|
|
|
149
|
+
| 设备配对 M2 | `POST /v1/pair/request` 拿一个 6 位码,`GET /v1/pair/status` 轮询 | 申请匿名但限速(10 次/分/IP)+ 待批准表封顶(`PI_HUB_PAIR_MAX_PENDING`,默认 32);**批准只能在主机本机做**(`pi-hub pair --approve`);token 只交付一次 |
|
|
150
|
+
| 一次性码 M4 | 浏览器直接打开 `https://<域名>/#code=XXXX-XXXX` | 码只能在主机 TTY 生成、8 位/40 bit、2 min、单次、每码 5 次失败上限 |
|
|
151
|
+
| 反代身份 M6 | Cloudflare Access / oauth2-proxy 等把用户身份交给 hub | hub 只认 `x-pi-proxy-secret`(恒时比较)+ 来源在 `PI_HUB_PROXY_CIDRS` 内;两者缺一即拒 |
|
|
152
|
+
|
|
153
|
+
**建议同时开 TOTP(M5)**:`PI_HUB_TOTP_SECRET` 一设,`/v1/web/login` 与 `/v1/web/otp/redeem` 都必须带验证器码,
|
|
154
|
+
主令牌 / 一次性码泄漏也不至于直接被用。
|
|
155
|
+
|
|
156
|
+
### 必须打开的一个开关
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
Environment=PI_HUB_TRUST_FORWARDED_FOR=1
|
|
160
|
+
Environment=PI_HUB_PROXY_CIDRS=127.0.0.1/32 # 反代跑在本机就这样写
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
原因:反代在本机时 hub 看到的对端恒为 `127.0.0.1`,所有限速器会退化成**全客户端共用一个桶**——
|
|
164
|
+
一个人刷 `/v1/web/login` 就能把其他人全部锁在外面(429)。
|
|
165
|
+
开启后仅当对端在 `PI_HUB_PROXY_CIDRS` 内才采信 `x-forwarded-for`,且取**最右一跳**:
|
|
166
|
+
Caddy / nginx 默认把客户端地址**追加**到已有 XFF 右侧,左边那截是客户端自己送的、可伪造。
|
|
167
|
+
多级反代链要按跳数自行收窄。对端不可信或值非法一律回退对端地址(`test/public-proxy.mjs` 逐条钉住)。
|
|
168
|
+
|
|
169
|
+
> 实测(Tailscale Serve/Funnel):客户端自己带 `x-forwarded-for: 9.9.9.9` 打进来,hub 记下的仍是真实
|
|
170
|
+
> 对端 IP —— Serve 会整个覆盖 XFF,不存在伪造窗口。
|
|
171
|
+
|
|
172
|
+
`PI_HUB_ALLOW_CIDRS` 保持默认即可:反代从回环进来,对端落在 `127.0.0.0/8` 里。
|
|
173
|
+
|
|
174
|
+
### 本机反代 **不能** 穿透管理鉴权
|
|
175
|
+
|
|
176
|
+
`/v1/pair/pending|approve|deny` 与 `/v1/web/otp` 要求的是「**本机直连**」:
|
|
177
|
+
对端是回环 **且** 不带任何代理头(`x-forwarded-for` / `x-forwarded-proto` / `x-forwarded-host` / `x-real-ip` / `forwarded`)。
|
|
178
|
+
|
|
179
|
+
这条区分不是洁癖:cloudflared / caddy 跑在本机时也从 `127.0.0.1` 进来,只判回环地址的话,
|
|
180
|
+
公网请求就会被当成「主机 CLI」,从而拿到批准配对、生成一次性码的能力(只要它同时拿到了主令牌)。
|
|
181
|
+
`test/public-proxy.mjs` 的两个 403 用例就是钉这个边界。
|
|
182
|
+
|
|
183
|
+
### 两条实际部署命令
|
|
184
|
+
|
|
185
|
+
```bash
|
|
186
|
+
# A. Cloudflare Tunnel(需要有域名托管在 Cloudflare;隧道是出站的,不用开端口)
|
|
187
|
+
cloudflared tunnel --url http://127.0.0.1:6768 # 临时试用
|
|
188
|
+
cloudflared tunnel create pi-hub # 正式:配 CNAME + ingress 到 127.0.0.1:6768
|
|
189
|
+
|
|
190
|
+
# B. Caddy(有公网 80/443 或能做 DNS-01 时)
|
|
191
|
+
caddy reverse-proxy --from hub.example.com --to 127.0.0.1:6768
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
两者都会自己办证书并带 `x-forwarded-proto: https`(hub 据此给 cookie 加 `Secure`)。
|
|
195
|
+
Cloudflare 上建议再叠一层 Access(配合 M6)或至少 WAF 速率限制。
|
|
196
|
+
|
|
197
|
+
### 暴露后的额外风险
|
|
198
|
+
|
|
199
|
+
- 这台机器上的 pi 能执行任意命令:公网暴露 = 把 shell 挂到互联网门口。只给可信设备开。
|
|
200
|
+
- 无鉴权端点只剩 `/v1/health`、`/v1/pair/claim`、`/v1/pair/request`(legacy)、`/v1/pair/status`(legacy)、
|
|
201
|
+
`/v1/web/login`、`/v1/web/otp/redeem`,全部有限速;配对申请另有待批准表封顶,6 位码另有失败锁定。
|
|
202
|
+
- 主令牌一旦泄漏,公网侧立即可用:轮换见下节,`rm ~/.config/pi-hub/token` 后重启即换。
|
|
203
|
+
|
|
94
204
|
## 失败码表
|
|
95
205
|
|
|
96
206
|
| 状态 | `error.code` | 出现在 | 含义 |
|
|
@@ -98,15 +208,22 @@ hub 启动时读一次 env,请求入口在常规鉴权**之前**尝试解析
|
|
|
98
208
|
| 401 | `unauthorized` | 所有需鉴权路由 | 没带凭据 / cookie 过期或被吊销 |
|
|
99
209
|
| 401 | `invalid_token` | `POST /v1/web/login` | 主令牌不对(有 ≥250 ms 失败延迟) |
|
|
100
210
|
| 401 | `bad_totp` | `POST /v1/web/login`、`/v1/web/otp/redeem` | 设了 TOTP 但没带 / 码错 / 同窗口重放 |
|
|
101
|
-
| 401 | `bad_signature` / `stale_timestamp` / `replay` / `device_revoked` |
|
|
211
|
+
| 401 | `bad_signature` / `stale_timestamp` / `replay` / `device_revoked` | `PI_HUB_REQUIRE_SIGNATURE=1` 时的设备请求 | 签名不对 / 时间偏差 >180 s / nonce 重放 / 设备已吊销 |
|
|
212
|
+
| 400 | `invalid_name` / `invalid_platform` / `invalid_token` / `invalid_code` | `POST /v1/pair/claim` | 字段形状非法(name/platform 空或 >64;token 非 43 字符 base64url;code 非 6 位数字) |
|
|
213
|
+
| 401 | `invalid_code` | `POST /v1/pair/claim` | 该 6 位码不存在 |
|
|
214
|
+
| 409 | `code_used` | `POST /v1/pair/claim` | 该码已被兑换(单次消费,重放即此码) |
|
|
215
|
+
| 410 | `code_expired` | `POST /v1/pair/claim` | 超过 5 min TTL |
|
|
216
|
+
| 429 | `code_locked` | `POST /v1/pair/claim` | 该码失败次数达到 5(防暴力猜码) |
|
|
217
|
+
| 429 | `too_many_codes` | `POST /v1/pair/code` | 同时未消费的码已达 8 个 |
|
|
102
218
|
| 403 | `csrf` | cookie 鉴权的非 GET 请求 | 缺 `x-pi-csrf` 或不匹配 |
|
|
103
219
|
| 403 | `primary_token_required` | `/v1/devices`、`/v1/web/otp` | 该动作只给主令牌(设备令牌/cookie 不够) |
|
|
104
|
-
| 403 | `local_only` | `/v1/pair
|
|
220
|
+
| 403 | `local_only` | `/v1/pair/*`(管理路由)、`/v1/web/otp` | 不是「本机直连」:对端非回环,**或带了任何代理头**(防本地反代穿透) |
|
|
105
221
|
| 400 | `invalid_code` | `POST /v1/web/otp/redeem` | 一次性码不存在/格式非法 |
|
|
106
222
|
| 410 | `code_expired` | `POST /v1/web/otp/redeem` | 一次性码超过 2 min |
|
|
107
223
|
| 410 | `code_used` | `POST /v1/web/otp/redeem` | 一次性码已被兑换 |
|
|
108
224
|
| 429 | `too_many_attempts` | `POST /v1/web/otp/redeem` | 该码失败次数用尽(≥5),码作废 |
|
|
109
|
-
| 429 | `rate_limited` | 登录 / 配对 / OTP | 每 IP
|
|
225
|
+
| 429 | `rate_limited` | 登录 / 配对 / OTP | 每 IP 每分钟额度用尽(开了 `PI_HUB_TRUST_FORWARDED_FOR` 时按 xff 首跳分桶) |
|
|
226
|
+
| 429 | `pair_queue_full` | `POST /v1/pair/request` | 待批准配对表到顶(`PI_HUB_PAIR_MAX_PENDING`,默认 32),先批准/拒绝再申请 |
|
|
110
227
|
| 400 | `invalid_session_ttl` | `POST /v1/web/otp/redeem` | `sessionTtlMs` 不在 60s..90d |
|
|
111
228
|
| 404 | `session_not_found` | `DELETE /v1/web/sessions/:id` | 会话 id 不存在(已被吊销/重启后内存清空) |
|
|
112
229
|
|
|
@@ -132,6 +249,8 @@ pi-hub totp setup # 轮换 TOTP:重新生成 secre
|
|
|
132
249
|
hub 只信显式配置的代理头 + shared secret,且来源必须在 `PI_HUB_PROXY_CIDRS` 内(默认 loopback)。
|
|
133
250
|
- **cookie 无 `Secure`**:明文 http 下浏览器不会给不带 `Secure` 的 cookie 加密传输;`x-forwarded-proto: https`
|
|
134
251
|
时 hub 自动加 `Secure`。
|
|
252
|
+
- **配对码 6 位(1e6 空间)**:5 min 窗口 + 单次消费 + 每码 5 次失败锁定 + 每 IP 10 次/分 ⇒
|
|
253
|
+
单 IP 在窗口内命中概率 < 1e-2 且失败即锁码;生成只在 loopback + 主令牌。
|
|
135
254
|
- **一次性码 40 bit**:2 min 窗口 + 单次消费 + 每码 5 次失败 + 每 IP 10 次/分 ⇒ 命中概率 < 1e-9;
|
|
136
255
|
但它仍是「短时 bearer」,只应通过 TTY/SSH 生成、不要贴到聊天记录里。
|
|
137
256
|
- **TOTP 防的是口令泄漏,不防已控主机**:secret 在 hub 进程环境里,能读 `systemd` unit 或 `/proc/<pid>/environ`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-hub-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "HTTP+SSE hub over pi RPC mode with a built-in web UI: one writer per session, many readers",
|
|
6
6
|
"license": "MIT",
|
|
@@ -37,6 +37,9 @@
|
|
|
37
37
|
"bin": {
|
|
38
38
|
"pi-hub": "./bin/pi-hub.mjs"
|
|
39
39
|
},
|
|
40
|
+
"optionalDependencies": {
|
|
41
|
+
"pi-session-lock": "^0.3.1"
|
|
42
|
+
},
|
|
40
43
|
"scripts": {
|
|
41
44
|
"start": "node bin/pi-hub.mjs serve",
|
|
42
45
|
"token": "node bin/pi-hub.mjs token",
|
package/src/config.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import os from "node:os";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { randomBytes } from "node:crypto";
|
|
5
|
+
import { resolveListen } from "./listen.mjs";
|
|
5
6
|
|
|
6
7
|
export const HOME = os.homedir();
|
|
7
8
|
export const CONFIG_DIR = process.env.PI_HUB_CONFIG_DIR || path.join(HOME, ".config", "pi-hub");
|
|
@@ -12,8 +13,13 @@ export const SESSIONS_DIR =
|
|
|
12
13
|
process.env.PI_CODING_AGENT_SESSION_DIR || path.join(HOME, ".pi", "agent", "sessions");
|
|
13
14
|
|
|
14
15
|
export const PI_BIN = process.env.PI_HUB_PI_BIN || "pi";
|
|
15
|
-
|
|
16
|
-
|
|
16
|
+
// HOST/PORT 走与 CLI 同一套解析(env > listen.json > 默认;--host/--port 由 bin 覆盖)。
|
|
17
|
+
// 导出名与类型保持不变:仍然是 string / number,旧调用方无需改动。
|
|
18
|
+
const LISTEN = resolveListen({ env: process.env, configDir: CONFIG_DIR, interactive: false });
|
|
19
|
+
export const PORT = LISTEN.port;
|
|
20
|
+
export const HOST = LISTEN.host;
|
|
21
|
+
/** 生效来源:flag(模块层不参与)/ env / file / default,broadcast 到 banner 与 `pi-hub listen`。 */
|
|
22
|
+
export const LISTEN_SOURCE = LISTEN.source;
|
|
17
23
|
export const IDLE_MS = Number(process.env.PI_HUB_IDLE_MS || 10 * 60 * 1000);
|
|
18
24
|
export const MAX_LIVE = Number(process.env.PI_HUB_MAX_LIVE || 3);
|
|
19
25
|
/** SSE 心跳间隔(注释帧 + data 帧各一条)。 */
|
package/src/listen.mjs
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// 监听地址/端口解析与持久化(PLAN auth-simple §2 / C2)。
|
|
2
|
+
// 优先级:serve --host/--port > PI_HUB_HOST/PORT > listen.json > 交互询问 > 默认。
|
|
3
|
+
// 纯函数 resolveListen 供测试;只有 writeListenFile/removeListenFile 碰磁盘。
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
|
|
8
|
+
export const DEFAULT_HOST = "127.0.0.1";
|
|
9
|
+
export const DEFAULT_PORT = 6768;
|
|
10
|
+
export const LISTEN_FILE_NAME = "listen.json";
|
|
11
|
+
/** 层优先级(高 → 低),用于把多字段来源收敛成一个 `source`。 */
|
|
12
|
+
const SOURCE_ORDER = ["flag", "env", "file", "prompt", "default"];
|
|
13
|
+
|
|
14
|
+
/** config.mjs 的 CONFIG_DIR 与本文件必须同源;这里单独算一份,避免循环 import。 */
|
|
15
|
+
export function defaultConfigDir() {
|
|
16
|
+
return process.env.PI_HUB_CONFIG_DIR || path.join(os.homedir(), ".config", "pi-hub");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class ListenError extends Error {
|
|
20
|
+
constructor(message, { exitCode = 1 } = {}) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.name = "ListenError";
|
|
23
|
+
this.exitCode = exitCode;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function listenFile(configDir = defaultConfigDir()) {
|
|
28
|
+
return path.join(configDir, LISTEN_FILE_NAME);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** `"6768"` / 6768 → 6768;非整数或越界 → null。 */
|
|
32
|
+
export function parsePort(value) {
|
|
33
|
+
if (value === null || value === undefined || value === "") return null;
|
|
34
|
+
const n = typeof value === "number" ? value : Number(String(value).trim());
|
|
35
|
+
if (!Number.isInteger(n) || n < 1 || n > 65535) return null;
|
|
36
|
+
return n;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function cleanText(value) {
|
|
40
|
+
if (typeof value !== "string") return null;
|
|
41
|
+
const text = value.trim();
|
|
42
|
+
return text || null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 读 listen.json;不存在/坏 JSON/字段非法都当「文件不提供这一层」,绝不因此起不来。 */
|
|
46
|
+
export function readListenFile(configDir = defaultConfigDir()) {
|
|
47
|
+
let raw;
|
|
48
|
+
try {
|
|
49
|
+
raw = fs.readFileSync(listenFile(configDir), "utf8");
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
let parsed;
|
|
54
|
+
try {
|
|
55
|
+
parsed = JSON.parse(raw);
|
|
56
|
+
} catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
60
|
+
const host = cleanText(parsed.host);
|
|
61
|
+
const port = parsePort(parsed.port);
|
|
62
|
+
if (host === null && port === null) return null;
|
|
63
|
+
return { host, port };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 写 listen.json(目录 0700、文件 0600、tmp+rename 原子替换)。返回文件路径。 */
|
|
67
|
+
export function writeListenFile({ host, port }, configDir = defaultConfigDir()) {
|
|
68
|
+
const cleanHost = cleanText(host);
|
|
69
|
+
const cleanPort = parsePort(port);
|
|
70
|
+
if (!cleanHost) throw new ListenError("host 不能为空");
|
|
71
|
+
if (cleanPort === null) throw new ListenError(`端口无效:${port}(应为 1..65535)`);
|
|
72
|
+
const file = listenFile(configDir);
|
|
73
|
+
fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
|
|
74
|
+
const data = `${JSON.stringify({ host: cleanHost, port: cleanPort }, null, 2)}\n`;
|
|
75
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
76
|
+
fs.writeFileSync(tmp, data, { mode: 0o600 });
|
|
77
|
+
fs.chmodSync(tmp, 0o600);
|
|
78
|
+
fs.renameSync(tmp, file);
|
|
79
|
+
return file;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 删除 listen.json;返回是否真的删了。 */
|
|
83
|
+
export function removeListenFile(configDir = defaultConfigDir()) {
|
|
84
|
+
try {
|
|
85
|
+
fs.rmSync(listenFile(configDir));
|
|
86
|
+
return true;
|
|
87
|
+
} catch (err) {
|
|
88
|
+
if (err.code === "ENOENT") return false;
|
|
89
|
+
throw err;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function hostPromptText() {
|
|
94
|
+
return `监听地址(127.0.0.1 = 只有本机;0.0.0.0 = 局域网可连)[${DEFAULT_HOST}]: `;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function portPromptText() {
|
|
98
|
+
return `端口 [${DEFAULT_PORT}]: `;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** IPv6 字面量在 URL 里要加方括号。 */
|
|
102
|
+
export function formatListenUrl(host, port) {
|
|
103
|
+
const text = String(host ?? "");
|
|
104
|
+
const bracketed = text.includes(":") ? `[${text}]` : text;
|
|
105
|
+
return `http://${bracketed}:${port}`;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function highestSource(sources) {
|
|
109
|
+
let best = "default";
|
|
110
|
+
let bestIndex = SOURCE_ORDER.length;
|
|
111
|
+
for (const source of sources) {
|
|
112
|
+
const index = SOURCE_ORDER.indexOf(source);
|
|
113
|
+
if (index >= 0 && index < bestIndex) {
|
|
114
|
+
best = source;
|
|
115
|
+
bestIndex = index;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return best;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 解析生效的 host/port(纯函数,除读一次 listen.json 外无副作用)。
|
|
123
|
+
*
|
|
124
|
+
* @param {object} opts
|
|
125
|
+
* @param {string|null} opts.argvHost --host
|
|
126
|
+
* @param {string|number|null} opts.argvPort --port
|
|
127
|
+
* @param {Record<string,string|undefined>} opts.env 默认 process.env
|
|
128
|
+
* @param {string} opts.configDir
|
|
129
|
+
* @param {boolean} opts.interactive 仅当 true 且 listen.json 不存在才会调用 ask
|
|
130
|
+
* @param {(prompt:string)=>string} [opts.ask] 交互问答回调;测试注入
|
|
131
|
+
* @returns {{host:string, port:number, source:string, sources:{host:string,port:string},
|
|
132
|
+
* file:string, fileExists:boolean, prompted:boolean}}
|
|
133
|
+
*/
|
|
134
|
+
export function resolveListen({
|
|
135
|
+
argvHost = null,
|
|
136
|
+
argvPort = null,
|
|
137
|
+
env = process.env,
|
|
138
|
+
configDir = defaultConfigDir(),
|
|
139
|
+
interactive = false,
|
|
140
|
+
ask = null,
|
|
141
|
+
} = {}) {
|
|
142
|
+
const file = listenFile(configDir);
|
|
143
|
+
const fileExists = fs.existsSync(file);
|
|
144
|
+
const fromFile = fileExists ? readListenFile(configDir) : null;
|
|
145
|
+
|
|
146
|
+
const layers = [
|
|
147
|
+
["flag", { host: cleanText(argvHost), port: parsePort(argvPort) }],
|
|
148
|
+
["env", { host: cleanText(env?.PI_HUB_HOST), port: parsePort(env?.PI_HUB_PORT) }],
|
|
149
|
+
["file", { host: fromFile?.host ?? null, port: fromFile?.port ?? null }],
|
|
150
|
+
];
|
|
151
|
+
const pick = (field) => {
|
|
152
|
+
for (const [source, values] of layers) {
|
|
153
|
+
if (values[field] !== null && values[field] !== undefined) return { value: values[field], source };
|
|
154
|
+
}
|
|
155
|
+
return null;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
let hostPick = pick("host");
|
|
159
|
+
let portPick = pick("port");
|
|
160
|
+
let prompted = false;
|
|
161
|
+
|
|
162
|
+
// 交互只在「stdin 是 TTY(调用方判定)且 listen.json 不存在」时发生。
|
|
163
|
+
if (interactive && !fileExists && typeof ask === "function") {
|
|
164
|
+
if (!hostPick) {
|
|
165
|
+
const answer = cleanText(ask(hostPromptText()));
|
|
166
|
+
hostPick = { value: answer ?? DEFAULT_HOST, source: "prompt" };
|
|
167
|
+
prompted = true;
|
|
168
|
+
}
|
|
169
|
+
if (!portPick) {
|
|
170
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
171
|
+
const answer = cleanText(ask(portPromptText()));
|
|
172
|
+
if (answer === null) {
|
|
173
|
+
portPick = { value: DEFAULT_PORT, source: "prompt" };
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
const parsed = parsePort(answer);
|
|
177
|
+
if (parsed !== null) {
|
|
178
|
+
portPick = { value: parsed, source: "prompt" };
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
if (attempt === 1) throw new ListenError(`端口无效:${answer}(应为 1..65535)`);
|
|
182
|
+
}
|
|
183
|
+
prompted = true;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (!hostPick) hostPick = { value: DEFAULT_HOST, source: "default" };
|
|
188
|
+
if (!portPick) portPick = { value: DEFAULT_PORT, source: "default" };
|
|
189
|
+
|
|
190
|
+
return {
|
|
191
|
+
host: hostPick.value,
|
|
192
|
+
port: portPick.value,
|
|
193
|
+
source: highestSource([hostPick.source, portPick.source]),
|
|
194
|
+
sources: { host: hostPick.source, port: portPick.source },
|
|
195
|
+
file,
|
|
196
|
+
fileExists,
|
|
197
|
+
prompted,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export const SOURCE_LABELS = Object.freeze({
|
|
202
|
+
flag: "命令行 --host/--port",
|
|
203
|
+
env: "环境变量 PI_HUB_HOST/PI_HUB_PORT",
|
|
204
|
+
file: LISTEN_FILE_NAME,
|
|
205
|
+
prompt: "本次交互输入",
|
|
206
|
+
default: "默认值",
|
|
207
|
+
});
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// 入站来源网段白名单(只做「谁能连到这个 hub」这一件事,与鉴权正交)。
|
|
2
|
+
//
|
|
3
|
+
// 为什么需要:hub 经常以 `PI_HUB_HOST=0.0.0.0` 起在笔记本上,而笔记本会同时挂在
|
|
4
|
+
// 校园网/宿舍网/咖啡厅 Wi-Fi 上。pi 以当前用户全权限执行模型生成的命令,明文 HTTP
|
|
5
|
+
// 一旦被同网段的人拿到就等 RCE;而 Tailscale/私有网/USB 网络共享这些正常路径全部
|
|
6
|
+
// 落在私有地址段里。所以默认只放行「不可能直接路由到公网」的来源:
|
|
7
|
+
// 本机回环 + RFC1918 + CGNAT(Tailscale 100.64/10)+ 链路本地
|
|
8
|
+
// 真要放开(例如放在已配好的反代后面、或自己的公网测试机)就设 `PI_HUB_ALLOW_CIDRS=*`。
|
|
9
|
+
import net from "node:net";
|
|
10
|
+
|
|
11
|
+
/** 默认放行集合:回环 + RFC1918 + CGNAT + 链路本地(IPv4/IPv6 各一套)。 */
|
|
12
|
+
export const DEFAULT_ALLOW_CIDRS = Object.freeze([
|
|
13
|
+
"127.0.0.0/8",
|
|
14
|
+
"::1/128",
|
|
15
|
+
"10.0.0.0/8",
|
|
16
|
+
"172.16.0.0/12",
|
|
17
|
+
"192.168.0.0/16",
|
|
18
|
+
"169.254.0.0/16",
|
|
19
|
+
"100.64.0.0/10",
|
|
20
|
+
"fc00::/7",
|
|
21
|
+
"fe80::/10",
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 解析 `PI_HUB_ALLOW_CIDRS`:逗号分隔,裸 IP 当 /32(v4)或 /128(v6)。
|
|
26
|
+
* `*` 表示不限制(返回 `null`);解析不了的条目抛错(宁可起不来,也不要静默变成"全放行")。
|
|
27
|
+
*/
|
|
28
|
+
export function parseAllowCidrs(raw) {
|
|
29
|
+
if (raw === undefined || raw === null) return DEFAULT_ALLOW_CIDRS.map((c) => parseCidr(c));
|
|
30
|
+
const text = String(raw).trim();
|
|
31
|
+
if (text === "*") return null;
|
|
32
|
+
if (!text) return [];
|
|
33
|
+
return text
|
|
34
|
+
.split(",")
|
|
35
|
+
.map((s) => s.trim())
|
|
36
|
+
.filter(Boolean)
|
|
37
|
+
.map((s) => {
|
|
38
|
+
try {
|
|
39
|
+
return parseCidr(s);
|
|
40
|
+
} catch (err) {
|
|
41
|
+
throw new Error(`PI_HUB_ALLOW_CIDRS 里的 "${s}" 不是合法网段:${err.message}`);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 单条 CIDR → `{bits, network(BigInt), family}`。 */
|
|
47
|
+
export function parseCidr(token) {
|
|
48
|
+
const [addr, prefixRaw] = String(token).split("/");
|
|
49
|
+
const family = net.isIP(addr);
|
|
50
|
+
if (family === 0) throw new Error(`不是 IP:${addr}`);
|
|
51
|
+
const width = family === 4 ? 32 : 128;
|
|
52
|
+
const prefix = prefixRaw === undefined ? width : Number(prefixRaw);
|
|
53
|
+
if (!Number.isInteger(prefix) || prefix < 0 || prefix > width) {
|
|
54
|
+
throw new Error(`掩码位数不合法:${prefixRaw}`);
|
|
55
|
+
}
|
|
56
|
+
const value = family === 4 ? ipv4ToBigInt(addr) : ipv6ToBigInt(addr);
|
|
57
|
+
const shift = BigInt(width - prefix);
|
|
58
|
+
const network = shift === 0n ? value : (value >> shift) << shift;
|
|
59
|
+
return { family, prefix, network, width };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function ipv4ToBigInt(addr) {
|
|
63
|
+
const parts = addr.split(".").map(Number);
|
|
64
|
+
let out = 0n;
|
|
65
|
+
for (const p of parts) out = (out << 8n) | BigInt(p);
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** IPv6 → BigInt(支持 `::` 压缩与末尾内嵌 IPv4)。 */
|
|
70
|
+
function ipv6ToBigInt(addr) {
|
|
71
|
+
let text = addr.toLowerCase();
|
|
72
|
+
// 末尾内嵌 IPv4:`::ffff:127.0.0.1` 之类
|
|
73
|
+
if (text.includes(".")) {
|
|
74
|
+
const lastColon = text.lastIndexOf(":");
|
|
75
|
+
const v4 = text.slice(lastColon + 1);
|
|
76
|
+
const hex = ipv4ToBigInt(v4).toString(16).padStart(8, "0");
|
|
77
|
+
text = `${text.slice(0, lastColon + 1)}${hex.slice(0, 4)}:${hex.slice(4)}`;
|
|
78
|
+
}
|
|
79
|
+
const [head, tail] = text.split("::");
|
|
80
|
+
const headParts = head ? head.split(":") : [];
|
|
81
|
+
const tailParts = tail === undefined ? [] : tail ? tail.split(":") : [];
|
|
82
|
+
const missing = 8 - headParts.length - tailParts.length;
|
|
83
|
+
if (tail === undefined ? headParts.length !== 8 : missing < 0) throw new Error(`IPv6 形态不合法:${addr}`);
|
|
84
|
+
const groups = [...headParts, ...Array(tail === undefined ? 0 : missing).fill("0"), ...tailParts];
|
|
85
|
+
let out = 0n;
|
|
86
|
+
for (const g of groups) {
|
|
87
|
+
if (!/^[0-9a-f]{1,4}$/.test(g)) throw new Error(`IPv6 段不合法:${g}`);
|
|
88
|
+
out = (out << 16n) | BigInt(parseInt(g, 16));
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 归一化 socket 里拿到的远端地址:去掉 zone、把 IPv4-mapped IPv6 折叠回 IPv4。
|
|
95
|
+
* 返回 `{family, value(BigInt)}`,无法解析返回 null。
|
|
96
|
+
*/
|
|
97
|
+
export function normalizePeer(raw) {
|
|
98
|
+
if (!raw) return null;
|
|
99
|
+
let addr = String(raw).trim();
|
|
100
|
+
const zoneAt = addr.indexOf("%");
|
|
101
|
+
if (zoneAt >= 0) addr = addr.slice(0, zoneAt);
|
|
102
|
+
if (addr.toLowerCase().startsWith("::ffff:")) {
|
|
103
|
+
const v4 = addr.slice(7);
|
|
104
|
+
if (net.isIP(v4) === 4) return { family: 4, value: ipv4ToBigInt(v4) };
|
|
105
|
+
}
|
|
106
|
+
const family = net.isIP(addr);
|
|
107
|
+
if (family === 0) return null;
|
|
108
|
+
try {
|
|
109
|
+
return family === 4
|
|
110
|
+
? { family: 4, value: ipv4ToBigInt(addr) }
|
|
111
|
+
: { family: 6, value: ipv6ToBigInt(addr) };
|
|
112
|
+
} catch {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 该来源地址是否在白名单里(`cidrs === null` 表示不限制)。解析不了的地址一律拒绝。 */
|
|
118
|
+
export function isPeerAllowed(rawAddr, cidrs) {
|
|
119
|
+
if (cidrs === null) return true;
|
|
120
|
+
const peer = normalizePeer(rawAddr);
|
|
121
|
+
if (!peer) return false;
|
|
122
|
+
for (const c of cidrs) {
|
|
123
|
+
if (c.family !== peer.family) continue;
|
|
124
|
+
const shift = BigInt(c.width - c.prefix);
|
|
125
|
+
const masked = shift === 0n ? peer.value : (peer.value >> shift) << shift;
|
|
126
|
+
if (masked === c.network) return true;
|
|
127
|
+
}
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** env → 放行集合(`null` = 不限制)。非法配置直接抛错,由调用方决定是否致命。 */
|
|
132
|
+
export function allowCidrsFromEnv(env = process.env) {
|
|
133
|
+
return parseAllowCidrs(env.PI_HUB_ALLOW_CIDRS);
|
|
134
|
+
}
|