pi-hub-server 0.0.0-stage → 0.3.2

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/bin/pi-hub.mjs ADDED
@@ -0,0 +1,353 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import { randomBytes } from "node:crypto";
5
+ import { AUTH_DISABLED, PI_BIN, PORT, HOST, SESSIONS_DIR, ensureToken, readToken } from "../src/config.mjs";
6
+ import { createHubServer } from "../src/server.mjs";
7
+ import { listSessions } from "../src/sessions-index.mjs";
8
+ import { PairingStore, isTrustedApprovalChannel } from "../src/pairing.mjs";
9
+ import { base32Decode, base32Encode, otpauthUri, verifyTotp } from "../src/totp.mjs";
10
+
11
+ const argv = process.argv.slice(2);
12
+ const command = argv.find((a) => !a.startsWith("-")) ?? "serve";
13
+ const flag = (name, fallback) => {
14
+ const i = argv.indexOf(name);
15
+ return i >= 0 ? argv[i + 1] : fallback;
16
+ };
17
+ const has = (name) => argv.includes(name);
18
+
19
+ /** `--ttl` 的会话有效期上下界(与 server.mjs 的 sessionTtlMs 校验一致)。 */
20
+ const SESSION_TTL_MIN_MS = 60 * 1000;
21
+ const SESSION_TTL_MAX_MS = 90 * 24 * 60 * 60 * 1000;
22
+
23
+ /** `60s` / `30m` / `2h` / `90d` → 毫秒;无法解析返回 null。 */
24
+ function parseDurationMs(text) {
25
+ const match = /^(\d+)(s|m|h|d)$/i.exec(String(text ?? "").trim());
26
+ if (!match) return null;
27
+ const unit = { s: 1000, m: 60 * 1000, h: 60 * 60 * 1000, d: 24 * 60 * 60 * 1000 }[match[2].toLowerCase()];
28
+ const value = Number(match[1]) * unit;
29
+ return Number.isSafeInteger(value) ? value : null;
30
+ }
31
+
32
+ function describeDuration(ms) {
33
+ if (ms % 86400000 === 0) return `${ms / 86400000}d`;
34
+ if (ms % 3600000 === 0) return `${ms / 3600000}h`;
35
+ if (ms % 60000 === 0) return `${ms / 60000}m`;
36
+ return `${Math.round(ms / 1000)}s`;
37
+ }
38
+
39
+ /** `--ttl` 缺省返回 null(让 hub 用 PI_HUB_WEB_TTL_MS 默认值);越界/格式错直接退出 1。 */
40
+ function readTtlFlag() {
41
+ const raw = flag("--ttl", null);
42
+ if (raw === null) return null;
43
+ const value = parseDurationMs(raw);
44
+ if (value === null) {
45
+ console.error("--ttl 格式:60s / 30m / 2h / 90d");
46
+ process.exit(1);
47
+ }
48
+ if (value < SESSION_TTL_MIN_MS || value > SESSION_TTL_MAX_MS) {
49
+ console.error(`--ttl 超出范围:60s .. ${describeDuration(SESSION_TTL_MAX_MS)}`);
50
+ process.exit(1);
51
+ }
52
+ return value;
53
+ }
54
+
55
+ /** 配对/设备命令打本机 hub:pending 只活在 hub 进程里,CLI 是另一进程必须走 HTTP。 */
56
+ async function hubApi(method, apiPath, body) {
57
+ const token = readToken();
58
+ if (!token) throw new Error("token 不存在:先运行一次 pi-hub serve 生成 ~/.config/pi-hub/token");
59
+ const port = Number(flag("--port", PORT));
60
+ const res = await fetch(`http://127.0.0.1:${port}${apiPath}`, {
61
+ method,
62
+ headers: {
63
+ authorization: `Bearer ${token}`,
64
+ ...(body ? { "content-type": "application/json" } : {}),
65
+ },
66
+ body: body ? JSON.stringify(body) : undefined,
67
+ signal: AbortSignal.timeout(5000),
68
+ });
69
+ const text = await res.text();
70
+ let data = null;
71
+ try {
72
+ data = text ? JSON.parse(text) : null;
73
+ } catch {
74
+ data = { raw: text };
75
+ }
76
+ return { ok: res.ok, status: res.status, data };
77
+ }
78
+
79
+ function reportHubError(status, data, fallback) {
80
+ const code = data?.error?.code ? ` ${data.error.code}` : "";
81
+ console.error(`${fallback}(HTTP ${status}${code}):${data?.error?.message ?? ""}`.trim());
82
+ process.exit(1);
83
+ }
84
+
85
+ if (command === "token") {
86
+ const token = readToken() ?? ensureToken();
87
+ console.log(token);
88
+ process.exit(0);
89
+ }
90
+
91
+ if (command === "pair") {
92
+ const approve = flag("--approve", null);
93
+ const deny = flag("--deny", null);
94
+ if (approve !== null || deny !== null) {
95
+ if (!isTrustedApprovalChannel()) {
96
+ console.error("拒绝:批准/拒绝配对必须在 SSH 会话或主机 TTY 里执行(SSH_CONNECTION / SSH_TTY / 终端)。");
97
+ process.exit(1);
98
+ }
99
+ if (approve !== null && !approve) {
100
+ console.error("用法: pi-hub pair --approve <code>");
101
+ process.exit(2);
102
+ }
103
+ if (deny !== null && !deny) {
104
+ console.error("用法: pi-hub pair --deny <code>");
105
+ process.exit(2);
106
+ }
107
+ let result;
108
+ try {
109
+ result = approve !== null
110
+ ? await hubApi("POST", "/v1/pair/approve", { code: approve })
111
+ : await hubApi("POST", "/v1/pair/deny", { code: deny });
112
+ } catch (err) {
113
+ console.error(`无法连接 hub(127.0.0.1:${Number(flag("--port", PORT))}):${err.message};serve 是否在跑?`);
114
+ process.exit(1);
115
+ }
116
+ if (!result.ok) reportHubError(result.status, result.data, "配对操作失败");
117
+ if (approve !== null) {
118
+ const d = result.data;
119
+ console.log(`已批准:${d.name}(${d.platform})`);
120
+ console.log(` device id: ${d.deviceId}`);
121
+ console.log(` fingerprint: ${d.fingerprintShort}`);
122
+ console.log(` token: ${d.token}`);
123
+ console.log("(token 只显示这一次;手机端会自动通过 /v1/pair/status 收到)");
124
+ } else {
125
+ console.log(`已拒绝配对码 ${deny}`);
126
+ }
127
+ process.exit(0);
128
+ }
129
+
130
+ let pending;
131
+ try {
132
+ const result = await hubApi("GET", "/v1/pair/pending");
133
+ if (!result.ok) reportHubError(result.status, result.data, "读取待批准列表失败");
134
+ pending = result.data?.pending ?? [];
135
+ } catch (err) {
136
+ console.error(`无法连接 hub(127.0.0.1:${Number(flag("--port", PORT))}):${err.message};serve 是否在跑?`);
137
+ process.exit(1);
138
+ }
139
+ if (!pending.length) {
140
+ console.log("没有待批准的配对请求");
141
+ process.exit(0);
142
+ }
143
+ console.log("code pair name platform created 剩余");
144
+ for (const p of pending) {
145
+ const left = Math.max(0, Math.round((Date.parse(p.expiresAt) - Date.now()) / 1000));
146
+ console.log(
147
+ `${p.code} ${String(p.pairId).slice(0, 8)} ${String(p.name).slice(0, 20).padEnd(20)} ${String(p.platform).slice(0, 16).padEnd(16)} ${p.createdAt} ${left}s`,
148
+ );
149
+ }
150
+ process.exit(0);
151
+ }
152
+
153
+ if (command === "devices") {
154
+ const revoke = flag("--revoke", null);
155
+ if (revoke !== null) {
156
+ if (!revoke) {
157
+ console.error("用法: pi-hub devices --revoke <id|name>");
158
+ process.exit(2);
159
+ }
160
+ let result;
161
+ try {
162
+ result = await hubApi("DELETE", `/v1/devices/${encodeURIComponent(revoke)}`);
163
+ } catch {
164
+ // hub 没跑:直接改 devices.json(hub 按 mtime 重载,外部 revoke 同样生效)
165
+ let device;
166
+ try {
167
+ device = new PairingStore().revokeDevice(revoke);
168
+ } catch (err) {
169
+ console.error(`吊销失败:${err.message}`);
170
+ process.exit(1);
171
+ }
172
+ console.log(`hub 未运行,已直接改 devices.json 吊销:${device.name}(${device.id})`);
173
+ process.exit(0);
174
+ }
175
+ if (!result.ok) reportHubError(result.status, result.data, "吊销失败");
176
+ console.log(`已吊销:${result.data.device?.name ?? revoke}(${result.data.device?.id ?? ""})`);
177
+ process.exit(0);
178
+ }
179
+
180
+ let devices;
181
+ let source = "hub";
182
+ try {
183
+ const result = await hubApi("GET", "/v1/devices");
184
+ if (!result.ok) reportHubError(result.status, result.data, "读取设备列表失败");
185
+ devices = result.data?.devices ?? [];
186
+ } catch {
187
+ devices = new PairingStore().listDevices();
188
+ source = "devices.json";
189
+ }
190
+ if (!devices.length) {
191
+ console.log(`没有已配对设备(来源:${source})`);
192
+ process.exit(0);
193
+ }
194
+ console.log(`设备列表(来源:${source})`);
195
+ for (const d of devices) {
196
+ console.log(
197
+ `${d.revoked ? "REVOKED" : "active "} ${d.id} ${String(d.name).slice(0, 20).padEnd(20)} ${String(d.platform).slice(0, 16).padEnd(16)} fp=${d.fingerprintShort} created=${d.createdAt} lastSeen=${d.lastSeenAt ?? "never"}`,
198
+ );
199
+ }
200
+ process.exit(0);
201
+ }
202
+
203
+ if (command === "sessions") {
204
+ const rows = listSessions({ limit: Number(flag("--limit", 20)), force: true });
205
+ console.log(`sessions dir: ${SESSIONS_DIR}`);
206
+ for (const row of rows) {
207
+ console.log(`${row.updatedAt} ${row.id.slice(0, 8)} ${row.name ?? row.preview ?? "(untitled)"}`.slice(0, 160));
208
+ }
209
+ process.exit(0);
210
+ }
211
+
212
+ if (command === "doctor") {
213
+ const checks = [];
214
+ checks.push(["pi binary", PI_BIN]);
215
+ checks.push(["sessions dir", `${SESSIONS_DIR} ${fs.existsSync(SESSIONS_DIR) ? "ok" : "MISSING"}`]);
216
+ checks.push(["token", readToken() ? "present" : "will be created on first serve"]);
217
+ checks.push(["devices", `${new PairingStore().listDevices().length} paired`]);
218
+ checks.push(["sessions visible", String(listSessions({ limit: 5000, force: true }).length)]);
219
+ for (const [k, v] of checks) console.log(`${k}: ${v}`);
220
+ process.exit(0);
221
+ }
222
+
223
+ if (command === "web-login") {
224
+ const ttlMs = readTtlFlag();
225
+ let result;
226
+ try {
227
+ result = await hubApi("POST", "/v1/web/otp", ttlMs === null ? {} : { sessionTtlMs: ttlMs });
228
+ } catch (err) {
229
+ console.error(`无法连接 hub(127.0.0.1:${Number(flag("--port", PORT))}):${err.message};serve 是否在跑?`);
230
+ process.exit(1);
231
+ }
232
+ if (!result.ok) reportHubError(result.status, result.data, "生成一次性登录码失败");
233
+ const code = result.data?.code ?? "";
234
+ const expiresAt = Date.parse(result.data?.expiresAt ?? "");
235
+ const seconds = Number.isFinite(expiresAt) ? Math.max(0, Math.round((expiresAt - Date.now()) / 1000)) : 0;
236
+ console.log(`一次性登录码:${code}(${seconds}s 内有效,单次使用)`);
237
+ console.log(` 浏览器打开:http://${flag("--host", HOST)}:${Number(flag("--port", PORT))}/#code=${code}`);
238
+ if (ttlMs !== null) console.log(` 兑换出的浏览器会话有效期:${describeDuration(ttlMs)}(--ttl,不是码的有效期)`);
239
+ console.log(" 码只显示这一次;兑换接口 POST /v1/web/otp/redeem {code}");
240
+ process.exit(0);
241
+ }
242
+
243
+ if (command === "web-sessions") {
244
+ const revoke = flag("--revoke", null);
245
+ let result;
246
+ try {
247
+ result = await hubApi("GET", "/v1/web/sessions");
248
+ } catch (err) {
249
+ console.error(`无法连接 hub(127.0.0.1:${Number(flag("--port", PORT))}):${err.message};serve 是否在跑?`);
250
+ process.exit(1);
251
+ }
252
+ if (!result.ok) reportHubError(result.status, result.data, "读取网页会话失败");
253
+ const sessions = result.data?.sessions ?? [];
254
+ if (revoke !== null) {
255
+ if (!revoke) {
256
+ console.error("用法: pi-hub web-sessions --revoke <id|all>");
257
+ process.exit(2);
258
+ }
259
+ const targets = revoke === "all" ? sessions.map((s) => s.id) : [revoke];
260
+ let revoked = 0;
261
+ for (const id of targets) {
262
+ const res = await hubApi("DELETE", `/v1/web/sessions/${encodeURIComponent(id)}`);
263
+ if (res.ok) revoked += 1;
264
+ else if (res.status === 404) console.error(`会话不存在:${id}`);
265
+ else reportHubError(res.status, res.data, "吊销网页会话失败");
266
+ }
267
+ console.log(`已吊销 ${revoked} 个网页会话`);
268
+ process.exit(0);
269
+ }
270
+ if (!sessions.length) {
271
+ console.log("没有网页会话");
272
+ process.exit(0);
273
+ }
274
+ console.log("id created lastSeen expires ip");
275
+ for (const s of sessions) {
276
+ console.log(`${s.id} ${s.createdAt} ${s.lastSeenAt} ${s.expiresAt} ${s.ip ?? "-"}`);
277
+ }
278
+ process.exit(0);
279
+ }
280
+
281
+ if (command === "totp") {
282
+ const sub = argv[argv.indexOf("totp") + 1];
283
+ if (sub === "setup") {
284
+ const secret = base32Encode(randomBytes(20));
285
+ const account = flag("--account", os.userInfo().username || "pi-hub");
286
+ const issuer = flag("--issuer", "pi-hub");
287
+ console.log("TOTP 密钥已生成(20 字节随机,只打印一次;本命令不写任何文件)");
288
+ console.log(` secret: ${secret}`);
289
+ console.log(` otpauth URI: ${otpauthUri({ issuer, account, secret })}`);
290
+ console.log("写进 hub 的启动环境(systemd 用户单元:systemctl --user edit pi-hub 加一行 Environment=):");
291
+ console.log(` PI_HUB_TOTP_SECRET=${secret}`);
292
+ process.exit(0);
293
+ }
294
+ if (sub === "verify") {
295
+ const code = argv[argv.indexOf("totp") + 2];
296
+ if (!code) {
297
+ console.error("用法: pi-hub totp verify <code>");
298
+ process.exit(2);
299
+ }
300
+ const raw = process.env.PI_HUB_TOTP_SECRET;
301
+ if (!raw) {
302
+ console.error("PI_HUB_TOTP_SECRET 未设置;先运行 pi-hub totp setup 并把 secret 写进 hub 的环境");
303
+ process.exit(1);
304
+ }
305
+ let secret;
306
+ try {
307
+ secret = base32Decode(raw);
308
+ } catch (err) {
309
+ console.error(`PI_HUB_TOTP_SECRET 不是合法 base32:${err.message}`);
310
+ process.exit(1);
311
+ }
312
+ const ok = verifyTotp(secret, code);
313
+ console.log(ok ? "TOTP ok" : "TOTP bad");
314
+ process.exit(ok ? 0 : 1);
315
+ }
316
+ console.error("用法: pi-hub totp setup | pi-hub totp verify <code>");
317
+ process.exit(2);
318
+ }
319
+
320
+ if (command !== "serve") {
321
+ console.error(
322
+ `unknown command: ${command}\nusage: pi-hub [serve|token|sessions|doctor|pair|devices|web-login|web-sessions|totp] [--port N] [--host H] [--no-auth]`,
323
+ );
324
+ process.exit(2);
325
+ }
326
+
327
+ // serve
328
+ if (has("--no-auth")) process.env.PI_HUB_NO_AUTH = "1";
329
+ const port = Number(flag("--port", PORT));
330
+ const host = flag("--host", HOST);
331
+ const hub = createHubServer();
332
+
333
+ const address = await hub.listen({ port, host });
334
+ const token = hub.token;
335
+ console.log(`pi-hub listening on http://${host}:${address.port}`);
336
+ console.log(` auth: ${AUTH_DISABLED ? "DISABLED" : "bearer token"}`);
337
+ if (token) console.log(` token: ${token.length} chars (file: ~/.config/pi-hub/token) — 查看用 \`pi-hub token\``);
338
+ console.log(` sessions dir: ${SESSIONS_DIR}`);
339
+ console.log(` pairing: ssh host 'pi-hub pair' (设备配对见 README「设备配对」)`);
340
+ console.log(
341
+ ` try: curl -s -H "authorization: Bearer $(pi-hub token)" http://127.0.0.1:${address.port}/v1/sessions | head -c 400`,
342
+ );
343
+
344
+ let closing = false;
345
+ for (const signal of ["SIGINT", "SIGTERM"]) {
346
+ process.on(signal, async () => {
347
+ if (closing) return;
348
+ closing = true;
349
+ console.log(`\n${signal}: closing hub + child sessions`);
350
+ await hub.close();
351
+ process.exit(0);
352
+ });
353
+ }
package/docs/AUTH.md ADDED
@@ -0,0 +1,141 @@
1
+ # 鉴权
2
+
3
+ pi-hub 是单用户、自托管、**无 TLS** 的 HTTP+SSE 后端。默认只监听 `127.0.0.1`;对外必须走
4
+ Tailscale / WireGuard(见文末「威胁边界」)。本文件是各鉴权方式的选型、失败码、吊销/轮换与边界说明;
5
+ 实现见 `src/web-auth.mjs`(cookie/CSRF)、`src/pairing.mjs`(设备签名)、`src/otp.mjs`(一次性码)、
6
+ `src/totp.mjs`(TOTP)、`src/proxy-auth.mjs`(反代身份)与 `src/server.mjs` 的接线。
7
+
8
+ ## 选哪种
9
+
10
+ | 场景 | 用哪个 | 怎么开 |
11
+ |---|---|---|
12
+ | 个人手机上的 App | **M2** 设备令牌 + ECDSA P-256 签名(Android Keystore) | 手机发起配对 → 主机 SSH/TTY 里 `pi-hub pair --approve <code>` |
13
+ | 浏览器(本机或同网段手机) | **M3** 网页会话 cookie(+ CSRF),配合 **M4** 一次性登录码免抄令牌 | `pi-hub web-login` 打印 `http://<host>:<port>/#code=XXXX-XXXX`,浏览器输入 8 位码兑换 |
14
+ | 已配 Tailscale Serve / Cloudflare Access 隧道 | **M6** 反向代理可信身份头 | hub 环境里设 `PI_HUB_TRUST_PROXY=1` + `PI_HUB_PROXY_SECRET=<shared secret>` |
15
+ | curl / CI / 桌面脚本 / 机器对机器 | **M1** 主令牌 Bearer(`~/.config/pi-hub/token`) | `pi-hub token` |
16
+ | 想给 cookie/码类登录加第二因子 | **M5** TOTP(RFC 6238) | `pi-hub totp setup` 打印 secret → 写进 hub 启动环境 `PI_HUB_TOTP_SECRET=<base32>` |
17
+
18
+ 硬约束:**主令牌永远可用**(M1 是兜底根凭据,任何新方式出问题都不会把用户锁在外面)。
19
+ Passkey/WebAuthn(M7)与 mTLS(M8)本批只有设计,没有实现。
20
+
21
+ ## 主令牌(M1)
22
+
23
+ ```bash
24
+ pi-hub token # 只读展示(首次 serve 时生成,0600)
25
+ curl -s -H "authorization: Bearer $(pi-hub token)" http://127.0.0.1:6768/v1/sessions
26
+ ```
27
+
28
+ 恒时比较(`timingSafeEqual`);关掉鉴权只用 `PI_HUB_NO_AUTH=1`(本机调试)。
29
+
30
+ ## 设备令牌 + 签名(M2)
31
+
32
+ 协议与配对流程见 README「设备配对」。要点:只存 `sha256(token)`,私钥不可导出,
33
+ 签名覆盖 `METHOD/PATH/TS/NONCE/SHA256(body)`,ts ±180 s、nonce 10 min 去重。
34
+
35
+ ## 网页会话 cookie(M3)
36
+
37
+ ```bash
38
+ pi-hub web-login # 一次性码(见 M4),也可直接 POST /v1/web/login {token}
39
+ pi-hub web-sessions # id / createdAt / lastSeenAt / expiresAt / ip
40
+ pi-hub web-sessions --revoke <id> # 吊销一条(浏览器会立即掉线)
41
+ pi-hub web-sessions --revoke all # 吊销全部
42
+ ```
43
+
44
+ - cookie 名 `pihub_session`,`HttpOnly; SameSite=Strict; Path=/`(https 反代时自动加 `Secure`)。
45
+ - 服务端内存只存 `sha256(session)`;**hub 重启 = 所有浏览器重新登录**(不落盘就没有 session 文件泄漏面)。
46
+ - 默认 30 天,`PI_HUB_WEB_TTL_MS` 改;距到期不足 7 天时滑动续期。
47
+ - 非 GET/HEAD 必须带 `x-pi-csrf`(`GET /v1/web/csrf` 下发,与会话绑定,double-submit)。
48
+ - 登录失败每 IP 10 次/分 + ≥250 ms 失败延迟;错令牌 `401 invalid_token`,超限 `429 rate_limited`。
49
+
50
+ ### 一次性登录码(M4)
51
+
52
+ `pi-hub web-login [--ttl 30m]` 只在 **loopback + 主令牌** 下限时生成(同 `/v1/pair/pending` 口径):
53
+
54
+ - 8 位 Crockford base32(`XXXX-XXXX`,40 bit),**固定 2 min TTL、单次消费**、每码最多 5 次失败;
55
+ - 每 IP 10 次/分;生成时**不绑定 User-Agent**(码是人工从 TTY 抄到浏览器的,UA 必然不同);
56
+ - **`--ttl` 是兑换出的浏览器会话有效期**(60s..90d,缺省用 `PI_HUB_WEB_TTL_MS`),
57
+ **不是一次性码的有效期**——码永远是 2 min。对应接口参数是 `POST /v1/web/otp/redeem` 的 `sessionTtlMs`。
58
+
59
+ ```bash
60
+ pi-hub web-login # 码默认 2 min,兑换出的会话默认 30 天
61
+ pi-hub web-login --ttl 30m # 临时设备:会话 30 分钟后自动失效
62
+ curl -s -X POST http://127.0.0.1:6768/v1/web/otp/redeem \
63
+ -H 'content-type: application/json' -d '{"code":"XXXX-XXXX","sessionTtlMs":1800000}'
64
+ ```
65
+
66
+ ## TOTP 二因子(M5)
67
+
68
+ ```bash
69
+ pi-hub totp setup # 打印 base32 secret + otpauth:// URI(不写任何文件)
70
+ pi-hub totp verify 123456 # 用当前 env 里的 PI_HUB_TOTP_SECRET 校验 → ok/bad
71
+ ```
72
+
73
+ 把 secret 写进 hub 的启动环境(systemd 用户单元:`systemctl --user edit pi-hub`,加
74
+ `Environment=PI_HUB_TOTP_SECRET=<base32>`),重启 `pi-hub`。设了 `PI_HUB_TOTP_SECRET` 后,
75
+ `POST /v1/web/login` 与 `/v1/web/otp/redeem` **都必须带 `totp` 字段**,缺失/错误 → `401 bad_totp`。
76
+ 未设 env 时完全跳过(向后兼容)。校验用 ±1 步(30 s)窗口 + 进程内已用步号去重(60 s 清理),
77
+ 所以同一 6 位码不能在同一窗口内用两次。secret 写坏(非 base32)时只停用 TOTP,不会把登录挡死。
78
+
79
+ ## 反向代理可信身份(M6)
80
+
81
+ hub 启动时读一次 env,请求入口在常规鉴权**之前**尝试解析代理身份;命中即等价主令牌,失败完全不影响
82
+ 后续的 Bearer / 设备签名 / cookie 鉴权链。
83
+
84
+ | 变量 | 说明 |
85
+ |---|---|
86
+ | `PI_HUB_TRUST_PROXY=1` | 总开关(不设 = 完全不看代理头) |
87
+ | `PI_HUB_PROXY_SECRET` | 必须与请求头 `x-pi-proxy-secret` 恒时相等;为空直接拒绝 |
88
+ | `PI_HUB_PROXY_CIDRS` | 逗号分隔的可信来源网段(裸 IP 视为 /32 或 /128);不设只允许 loopback |
89
+ | `PI_HUB_PROXY_USER_HEADER` | 身份头名,默认 `x-pi-proxy-user` |
90
+
91
+ 命中后 `req.auth = {kind:"proxy", user}`,权限等价主令牌(可读 `/v1/devices`、`/v1/web/sessions` 等)。
92
+ `/v1/web/otp` 仍要求 loopback + 主权限,所以反代机器上生成一次性码仍要走本机 CLI。
93
+
94
+ ## 失败码表
95
+
96
+ | 状态 | `error.code` | 出现在 | 含义 |
97
+ |---|---|---|---|
98
+ | 401 | `unauthorized` | 所有需鉴权路由 | 没带凭据 / cookie 过期或被吊销 |
99
+ | 401 | `invalid_token` | `POST /v1/web/login` | 主令牌不对(有 ≥250 ms 失败延迟) |
100
+ | 401 | `bad_totp` | `POST /v1/web/login`、`/v1/web/otp/redeem` | 设了 TOTP 但没带 / 码错 / 同窗口重放 |
101
+ | 401 | `bad_signature` / `stale_timestamp` / `replay` / `device_revoked` | 所有带设备签名的请求 | 签名不对 / 时间偏差 >180 s / nonce 重放 / 设备已吊销 |
102
+ | 403 | `csrf` | cookie 鉴权的非 GET 请求 | 缺 `x-pi-csrf` 或不匹配 |
103
+ | 403 | `primary_token_required` | `/v1/devices`、`/v1/web/otp` | 该动作只给主令牌(设备令牌/cookie 不够) |
104
+ | 403 | `local_only` | `/v1/pair/*`、`/v1/web/otp` | 非 loopback 来源 |
105
+ | 400 | `invalid_code` | `POST /v1/web/otp/redeem` | 一次性码不存在/格式非法 |
106
+ | 410 | `code_expired` | `POST /v1/web/otp/redeem` | 一次性码超过 2 min |
107
+ | 410 | `code_used` | `POST /v1/web/otp/redeem` | 一次性码已被兑换 |
108
+ | 429 | `too_many_attempts` | `POST /v1/web/otp/redeem` | 该码失败次数用尽(≥5),码作废 |
109
+ | 429 | `rate_limited` | 登录 / 配对 / OTP | 每 IP 每分钟额度用尽 |
110
+ | 400 | `invalid_session_ttl` | `POST /v1/web/otp/redeem` | `sessionTtlMs` 不在 60s..90d |
111
+ | 404 | `session_not_found` | `DELETE /v1/web/sessions/:id` | 会话 id 不存在(已被吊销/重启后内存清空) |
112
+
113
+ ## 吊销与轮换
114
+
115
+ ```bash
116
+ pi-hub devices --revoke <id|name> # 丢手机:吊销设备令牌(下次请求 401 device_revoked)
117
+ pi-hub web-sessions --revoke <id> # 单个浏览器会话
118
+ pi-hub web-sessions --revoke all # 全部浏览器会话(等价于让所有人重新登录)
119
+ systemctl --user restart pi-hub # 清空所有网页会话(会话只在内存)
120
+ rm ~/.config/pi-hub/token && pi-hub serve # 轮换主令牌:所有 M1 客户端立刻失效,需重新取 token
121
+ pi-hub totp setup # 轮换 TOTP:重新生成 secret 并改 systemd Environment=
122
+ ```
123
+
124
+ 主令牌轮换不影响已配对设备;设备吊销不影响主令牌。hub 按 mtime 重载 `devices.json`,
125
+ 所以外部改文件同样生效。
126
+
127
+ ## 威胁边界
128
+
129
+ - **无 TLS**:明文 HTTP 在同网段可被嗅探。抓到 `Authorization` 头 ≈ 拿到你的 shell(pi 以当前用户全权限
130
+ 执行模型生成的命令)。因此默认只监听 `127.0.0.1`,**出门必须走 Tailscale / WireGuard**;
131
+ 不要在共享网络里 `PI_HUB_HOST=0.0.0.0` 裸跑。反代终止 TLS(Cloudflare Access / Tailscale Serve)时
132
+ hub 只信显式配置的代理头 + shared secret,且来源必须在 `PI_HUB_PROXY_CIDRS` 内(默认 loopback)。
133
+ - **cookie 无 `Secure`**:明文 http 下浏览器不会给不带 `Secure` 的 cookie 加密传输;`x-forwarded-proto: https`
134
+ 时 hub 自动加 `Secure`。
135
+ - **一次性码 40 bit**:2 min 窗口 + 单次消费 + 每码 5 次失败 + 每 IP 10 次/分 ⇒ 命中概率 < 1e-9;
136
+ 但它仍是「短时 bearer」,只应通过 TTY/SSH 生成、不要贴到聊天记录里。
137
+ - **TOTP 防的是口令泄漏,不防已控主机**:secret 在 hub 进程环境里,能读 `systemd` unit 或 `/proc/<pid>/environ`
138
+ 的攻击者已经拿到主机权限。
139
+ - **XSS / CSRF**:内容渲染自研 markdown 已转义;HTML/JS 响应带 CSP `default-src 'self'`;
140
+ cookie `HttpOnly` + `SameSite=Strict` + `x-pi-csrf` double-submit。
141
+ - **会话不落盘**:`sha256(session)` 只在内存,重启即清空;这也意味着重启后一次性码全部失效(码同样只在内存)。
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "pi-hub-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.2",
4
+ "type": "module",
5
+ "description": "HTTP+SSE hub over pi RPC mode with a built-in web UI: one writer per session, many readers",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/xiaquwan1001/pi-hub.git"
10
+ },
11
+ "homepage": "https://github.com/xiaquwan1001/pi-hub#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/xiaquwan1001/pi-hub/issues"
14
+ },
15
+ "keywords": [
16
+ "pi",
17
+ "agent",
18
+ "android",
19
+ "self-hosted",
20
+ "sse"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "files": [
26
+ "bin",
27
+ "src",
28
+ "web",
29
+ "systemd",
30
+ "LICENSE",
31
+ "docs",
32
+ "README.md"
33
+ ],
34
+ "engines": {
35
+ "node": ">=22.19"
36
+ },
37
+ "bin": {
38
+ "pi-hub": "./bin/pi-hub.mjs"
39
+ },
40
+ "scripts": {
41
+ "start": "node bin/pi-hub.mjs serve",
42
+ "token": "node bin/pi-hub.mjs token",
43
+ "doctor": "node bin/pi-hub.mjs doctor",
44
+ "smoke": "node test/smoke.mjs",
45
+ "prepublishOnly": "node --check bin/pi-hub.mjs && for f in src/*.mjs; do node --check \"$f\"; done"
46
+ }
47
+ }
package/src/config.mjs ADDED
@@ -0,0 +1,54 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { randomBytes } from "node:crypto";
5
+
6
+ export const HOME = os.homedir();
7
+ export const CONFIG_DIR = process.env.PI_HUB_CONFIG_DIR || path.join(HOME, ".config", "pi-hub");
8
+ export const LOCK_DIR = path.join(CONFIG_DIR, "locks");
9
+ export const UPLOAD_DIR =
10
+ process.env.PI_HUB_UPLOAD_DIR || path.join(HOME, ".cache", "pi-hub", "uploads");
11
+ export const SESSIONS_DIR =
12
+ process.env.PI_CODING_AGENT_SESSION_DIR || path.join(HOME, ".pi", "agent", "sessions");
13
+
14
+ export const PI_BIN = process.env.PI_HUB_PI_BIN || "pi";
15
+ export const PORT = Number(process.env.PI_HUB_PORT || 6768);
16
+ export const HOST = process.env.PI_HUB_HOST || "127.0.0.1";
17
+ export const IDLE_MS = Number(process.env.PI_HUB_IDLE_MS || 10 * 60 * 1000);
18
+ export const MAX_LIVE = Number(process.env.PI_HUB_MAX_LIVE || 3);
19
+ /** SSE 心跳间隔(注释帧 + data 帧各一条)。 */
20
+ export const HEARTBEAT_MS = Number(process.env.PI_HUB_HEARTBEAT_MS || 15000);
21
+ export const EVICT_IDLE_MS = Number(process.env.PI_HUB_EVICT_IDLE_MS || 30000);
22
+ export const AUTH_DISABLED = process.env.PI_HUB_NO_AUTH === "1";
23
+
24
+ export function ensureDirs() {
25
+ fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
26
+ fs.mkdirSync(LOCK_DIR, { recursive: true, mode: 0o700 });
27
+ }
28
+
29
+ export function tokenFile() {
30
+ return path.join(CONFIG_DIR, "token");
31
+ }
32
+
33
+ export function readToken() {
34
+ try {
35
+ const token = fs.readFileSync(tokenFile(), "utf8").trim();
36
+ return token || null;
37
+ } catch {
38
+ return null;
39
+ }
40
+ }
41
+
42
+ /** 首次启动生成 token 并落盘(0600)。返回当前有效 token。 */
43
+ export function ensureToken() {
44
+ const existing = readToken();
45
+ if (existing) return existing;
46
+ ensureDirs();
47
+ const token = randomBytes(24).toString("base64url");
48
+ fs.writeFileSync(tokenFile(), `${token}\n`, { mode: 0o600 });
49
+ return token;
50
+ }
51
+
52
+ export function lockFile(sessionId) {
53
+ return path.join(LOCK_DIR, `${sessionId}.lock`);
54
+ }