pi-hub-server 0.0.0-stage → 0.4.0

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,473 @@
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, CONFIG_DIR, PI_BIN, PORT, HOST, SESSIONS_DIR, ensureToken, readToken, tokenFile } from "../src/config.mjs";
6
+ import { createHubServer } from "../src/server.mjs";
7
+ import { SOURCE_LABELS, formatListenUrl, listenFile, removeListenFile, resolveListen, writeListenFile } from "../src/listen.mjs";
8
+ import { listSessions } from "../src/sessions-index.mjs";
9
+ import { PairingStore, isTrustedApprovalChannel } from "../src/pairing.mjs";
10
+ import { base32Decode, base32Encode, otpauthUri, verifyTotp } from "../src/totp.mjs";
11
+
12
+ const argv = process.argv.slice(2);
13
+ const command = argv.find((a) => !a.startsWith("-")) ?? "serve";
14
+ const flag = (name, fallback) => {
15
+ const i = argv.indexOf(name);
16
+ return i >= 0 ? argv[i + 1] : fallback;
17
+ };
18
+ const has = (name) => argv.includes(name);
19
+
20
+ /** 同步读一行(serve 首次启动的 listen.json 交互)。空输入 = 取默认。 */
21
+ function readPromptSync(prompt) {
22
+ process.stdout.write(prompt);
23
+ const buf = Buffer.alloc(256);
24
+ let text = "";
25
+ while (!text.includes("\n")) {
26
+ let n;
27
+ try {
28
+ n = fs.readSync(0, buf, 0, buf.length, null);
29
+ } catch (err) {
30
+ if (err.code === "EAGAIN") continue;
31
+ if (err.code === "EOF") break;
32
+ throw err;
33
+ }
34
+ if (n === 0) break;
35
+ text += buf.toString("utf8", 0, n);
36
+ }
37
+ return text.split("\n")[0];
38
+ }
39
+
40
+ /** 本机是否有 Tailscale TUN(没有 TUN 时 serve 的 stderr 提一句出门怎么连)。 */
41
+ function hasTailscaleTun() {
42
+ try {
43
+ return fs.readdirSync("/sys/class/net").some((name) => name.startsWith("tailscale"));
44
+ } catch {
45
+ return false;
46
+ }
47
+ }
48
+
49
+ /** `--ttl` 的会话有效期上下界(与 server.mjs 的 sessionTtlMs 校验一致)。 */
50
+ const SESSION_TTL_MIN_MS = 60 * 1000;
51
+ const SESSION_TTL_MAX_MS = 90 * 24 * 60 * 60 * 1000;
52
+
53
+ /** `60s` / `30m` / `2h` / `90d` → 毫秒;无法解析返回 null。 */
54
+ function parseDurationMs(text) {
55
+ const match = /^(\d+)(s|m|h|d)$/i.exec(String(text ?? "").trim());
56
+ if (!match) return null;
57
+ const unit = { s: 1000, m: 60 * 1000, h: 60 * 60 * 1000, d: 24 * 60 * 60 * 1000 }[match[2].toLowerCase()];
58
+ const value = Number(match[1]) * unit;
59
+ return Number.isSafeInteger(value) ? value : null;
60
+ }
61
+
62
+ function describeDuration(ms) {
63
+ if (ms % 86400000 === 0) return `${ms / 86400000}d`;
64
+ if (ms % 3600000 === 0) return `${ms / 3600000}h`;
65
+ if (ms % 60000 === 0) return `${ms / 60000}m`;
66
+ return `${Math.round(ms / 1000)}s`;
67
+ }
68
+
69
+ /** `--ttl` 缺省返回 null(让 hub 用 PI_HUB_WEB_TTL_MS 默认值);越界/格式错直接退出 1。 */
70
+ function readTtlFlag() {
71
+ const raw = flag("--ttl", null);
72
+ if (raw === null) return null;
73
+ const value = parseDurationMs(raw);
74
+ if (value === null) {
75
+ console.error("--ttl 格式:60s / 30m / 2h / 90d");
76
+ process.exit(1);
77
+ }
78
+ if (value < SESSION_TTL_MIN_MS || value > SESSION_TTL_MAX_MS) {
79
+ console.error(`--ttl 超出范围:60s .. ${describeDuration(SESSION_TTL_MAX_MS)}`);
80
+ process.exit(1);
81
+ }
82
+ return value;
83
+ }
84
+
85
+ /** 配对/设备命令打本机 hub:pending 只活在 hub 进程里,CLI 是另一进程必须走 HTTP。 */
86
+ async function hubApi(method, apiPath, body) {
87
+ const token = readToken();
88
+ if (!token) throw new Error("token 不存在:先运行一次 pi-hub serve 生成 ~/.config/pi-hub/token");
89
+ const port = Number(flag("--port", PORT));
90
+ const res = await fetch(`http://127.0.0.1:${port}${apiPath}`, {
91
+ method,
92
+ headers: {
93
+ authorization: `Bearer ${token}`,
94
+ ...(body ? { "content-type": "application/json" } : {}),
95
+ },
96
+ body: body ? JSON.stringify(body) : undefined,
97
+ signal: AbortSignal.timeout(5000),
98
+ });
99
+ const text = await res.text();
100
+ let data = null;
101
+ try {
102
+ data = text ? JSON.parse(text) : null;
103
+ } catch {
104
+ data = { raw: text };
105
+ }
106
+ return { ok: res.ok, status: res.status, data };
107
+ }
108
+
109
+ function reportHubError(status, data, fallback) {
110
+ const code = data?.error?.code ? ` ${data.error.code}` : "";
111
+ console.error(`${fallback}(HTTP ${status}${code}):${data?.error?.message ?? ""}`.trim());
112
+ process.exit(1);
113
+ }
114
+
115
+ if (command === "token") {
116
+ const token = readToken() ?? ensureToken();
117
+ console.log(token);
118
+ process.exit(0);
119
+ }
120
+
121
+ if (command === "pair") {
122
+ const approve = flag("--approve", null);
123
+ const deny = flag("--deny", null);
124
+ const force = has("--force");
125
+ if (approve !== null || deny !== null) {
126
+ if (!isTrustedApprovalChannel(process.env, process.stdin, { force })) {
127
+ console.error("拒绝:批准/拒绝配对必须在 SSH 会话或主机 TTY 里执行(SSH_CONNECTION / SSH_TTY / 终端)。");
128
+ console.error(" 无终端的主机侧通道(agent/无头会话)可显式加 --force 跳过这条判定;其余防线不变。");
129
+ process.exit(1);
130
+ }
131
+ if (force && !(process.env.SSH_CONNECTION || process.env.SSH_TTY || process.stdin?.isTTY === true)) {
132
+ console.error("注意:--force 跳过了「有终端」判定(无 SSH/TTY 会话)。其余防线不变:loopback + 主令牌 + 6 位码 + 5 min TTL。");
133
+ }
134
+ if (approve !== null && !approve) {
135
+ console.error("用法: pi-hub pair --approve <code>");
136
+ process.exit(2);
137
+ }
138
+ if (deny !== null && !deny) {
139
+ console.error("用法: pi-hub pair --deny <code>");
140
+ process.exit(2);
141
+ }
142
+ let result;
143
+ try {
144
+ result = approve !== null
145
+ ? await hubApi("POST", "/v1/pair/approve", { code: approve })
146
+ : await hubApi("POST", "/v1/pair/deny", { code: deny });
147
+ } catch (err) {
148
+ console.error(`无法连接 hub(127.0.0.1:${Number(flag("--port", PORT))}):${err.message};serve 是否在跑?`);
149
+ process.exit(1);
150
+ }
151
+ if (!result.ok) reportHubError(result.status, result.data, "配对操作失败");
152
+ if (approve !== null) {
153
+ const d = result.data;
154
+ console.log(`已批准:${d.name}(${d.platform})`);
155
+ console.log(` device id: ${d.deviceId}`);
156
+ console.log(` fingerprint: ${d.fingerprintShort}`);
157
+ console.log(` token: ${d.token}`);
158
+ console.log("(token 只显示这一次;手机端会自动通过 /v1/pair/status 收到)");
159
+ } else {
160
+ console.log(`已拒绝配对码 ${deny}`);
161
+ }
162
+ process.exit(0);
163
+ }
164
+
165
+ let pending;
166
+ try {
167
+ const result = await hubApi("GET", "/v1/pair/pending");
168
+ if (!result.ok) reportHubError(result.status, result.data, "读取待批准列表失败");
169
+ pending = result.data?.pending ?? [];
170
+ } catch (err) {
171
+ console.error(`无法连接 hub(127.0.0.1:${Number(flag("--port", PORT))}):${err.message};serve 是否在跑?`);
172
+ process.exit(1);
173
+ }
174
+ if (!pending.length) {
175
+ console.log("没有待批准的配对请求");
176
+ process.exit(0);
177
+ }
178
+ console.log("code pair name platform created 剩余");
179
+ for (const p of pending) {
180
+ const left = Math.max(0, Math.round((Date.parse(p.expiresAt) - Date.now()) / 1000));
181
+ console.log(
182
+ `${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`,
183
+ );
184
+ }
185
+ process.exit(0);
186
+ }
187
+
188
+ if (command === "pair-code") {
189
+ let result;
190
+ try {
191
+ result = await hubApi("POST", "/v1/pair/code");
192
+ } catch (err) {
193
+ console.error(`无法连接 hub(127.0.0.1:${Number(flag("--port", PORT))}):${err.message};serve 是否在跑?`);
194
+ process.exit(1);
195
+ }
196
+ if (!result.ok) reportHubError(result.status, result.data, "生成配对码失败");
197
+ const code = result.data?.code ?? "";
198
+ const expiresAt = Date.parse(result.data?.expiresAt ?? "");
199
+ const seconds = Number.isFinite(expiresAt) ? Math.max(0, Math.round((expiresAt - Date.now()) / 1000)) : 0;
200
+ console.log(`配对码 ${code}(${seconds}s 内有效,一次性)`);
201
+ console.log(` 手机 App 设置页输入这 6 位数字`);
202
+ process.exit(0);
203
+ }
204
+
205
+ if (command === "listen") {
206
+ if (has("--reset")) {
207
+ const removed = removeListenFile(CONFIG_DIR);
208
+ console.log(removed ? `已删除 ${listenFile(CONFIG_DIR)}` : `${listenFile(CONFIG_DIR)} 不存在,无需重置`);
209
+ process.exit(0);
210
+ }
211
+ const argvHost = flag("--host", null);
212
+ const argvPort = flag("--port", null);
213
+ if (argvHost !== null || argvPort !== null) {
214
+ const current = resolveListen({ env: process.env, configDir: CONFIG_DIR, interactive: false });
215
+ const host = argvHost ?? current.host;
216
+ const port = argvPort ?? current.port;
217
+ let file;
218
+ try {
219
+ file = writeListenFile({ host, port }, CONFIG_DIR);
220
+ } catch (err) {
221
+ console.error(`写 ${listenFile(CONFIG_DIR)} 失败:${err.message}`);
222
+ process.exit(1);
223
+ }
224
+ console.log(`已保存 ${file}`);
225
+ console.log(` ${host}:${port}(下次 \`pi-hub serve\` 生效;运行中的 hub 需重启)`);
226
+ process.exit(0);
227
+ }
228
+ const current = resolveListen({ env: process.env, configDir: CONFIG_DIR, interactive: false });
229
+ console.log(`监听地址:${formatListenUrl(current.host, current.port)}`);
230
+ console.log(` 来源:${SOURCE_LABELS[current.source] ?? current.source}(host=${current.sources.host}, port=${current.sources.port})`);
231
+ console.log(` 配置文件:${current.file}${current.fileExists ? "" : "(不存在)"}`);
232
+ process.exit(0);
233
+ }
234
+
235
+ if (command === "devices") {
236
+ const revoke = flag("--revoke", null);
237
+ if (revoke !== null) {
238
+ if (!revoke) {
239
+ console.error("用法: pi-hub devices --revoke <id|name>");
240
+ process.exit(2);
241
+ }
242
+ let result;
243
+ try {
244
+ result = await hubApi("DELETE", `/v1/devices/${encodeURIComponent(revoke)}`);
245
+ } catch {
246
+ // hub 没跑:直接改 devices.json(hub 按 mtime 重载,外部 revoke 同样生效)
247
+ let device;
248
+ try {
249
+ device = new PairingStore().revokeDevice(revoke);
250
+ } catch (err) {
251
+ console.error(`吊销失败:${err.message}`);
252
+ process.exit(1);
253
+ }
254
+ console.log(`hub 未运行,已直接改 devices.json 吊销:${device.name}(${device.id})`);
255
+ process.exit(0);
256
+ }
257
+ if (!result.ok) reportHubError(result.status, result.data, "吊销失败");
258
+ console.log(`已吊销:${result.data.device?.name ?? revoke}(${result.data.device?.id ?? ""})`);
259
+ process.exit(0);
260
+ }
261
+
262
+ let devices;
263
+ let source = "hub";
264
+ try {
265
+ const result = await hubApi("GET", "/v1/devices");
266
+ if (!result.ok) reportHubError(result.status, result.data, "读取设备列表失败");
267
+ devices = result.data?.devices ?? [];
268
+ } catch {
269
+ devices = new PairingStore().listDevices();
270
+ source = "devices.json";
271
+ }
272
+ if (!devices.length) {
273
+ console.log(`没有已配对设备(来源:${source})`);
274
+ process.exit(0);
275
+ }
276
+ console.log(`设备列表(来源:${source})`);
277
+ for (const d of devices) {
278
+ console.log(
279
+ `${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"}`,
280
+ );
281
+ }
282
+ process.exit(0);
283
+ }
284
+
285
+ if (command === "sessions") {
286
+ const rows = listSessions({ limit: Number(flag("--limit", 20)), force: true });
287
+ console.log(`sessions dir: ${SESSIONS_DIR}`);
288
+ for (const row of rows) {
289
+ console.log(`${row.updatedAt} ${row.id.slice(0, 8)} ${row.name ?? row.preview ?? "(untitled)"}`.slice(0, 160));
290
+ }
291
+ process.exit(0);
292
+ }
293
+
294
+ if (command === "doctor") {
295
+ const checks = [];
296
+ checks.push(["pi binary", PI_BIN]);
297
+ checks.push(["sessions dir", `${SESSIONS_DIR} ${fs.existsSync(SESSIONS_DIR) ? "ok" : "MISSING"}`]);
298
+ checks.push(["token", readToken() ? "present" : "will be created on first serve"]);
299
+ checks.push(["devices", `${new PairingStore().listDevices().length} paired`]);
300
+ checks.push(["sessions visible", String(listSessions({ limit: 5000, force: true }).length)]);
301
+ for (const [k, v] of checks) console.log(`${k}: ${v}`);
302
+ process.exit(0);
303
+ }
304
+
305
+ if (command === "web-login") {
306
+ const ttlMs = readTtlFlag();
307
+ let result;
308
+ try {
309
+ result = await hubApi("POST", "/v1/web/otp", ttlMs === null ? {} : { sessionTtlMs: ttlMs });
310
+ } catch (err) {
311
+ console.error(`无法连接 hub(127.0.0.1:${Number(flag("--port", PORT))}):${err.message};serve 是否在跑?`);
312
+ process.exit(1);
313
+ }
314
+ if (!result.ok) reportHubError(result.status, result.data, "生成一次性登录码失败");
315
+ const code = result.data?.code ?? "";
316
+ const expiresAt = Date.parse(result.data?.expiresAt ?? "");
317
+ const seconds = Number.isFinite(expiresAt) ? Math.max(0, Math.round((expiresAt - Date.now()) / 1000)) : 0;
318
+ console.log(`一次性登录码:${code}(${seconds}s 内有效,单次使用)`);
319
+ console.log(` 浏览器打开:http://${flag("--host", HOST)}:${Number(flag("--port", PORT))}/#code=${code}`);
320
+ if (ttlMs !== null) console.log(` 兑换出的浏览器会话有效期:${describeDuration(ttlMs)}(--ttl,不是码的有效期)`);
321
+ console.log(" 码只显示这一次;兑换接口 POST /v1/web/otp/redeem {code}");
322
+ process.exit(0);
323
+ }
324
+
325
+ if (command === "web-sessions") {
326
+ const revoke = flag("--revoke", null);
327
+ let result;
328
+ try {
329
+ result = await hubApi("GET", "/v1/web/sessions");
330
+ } catch (err) {
331
+ console.error(`无法连接 hub(127.0.0.1:${Number(flag("--port", PORT))}):${err.message};serve 是否在跑?`);
332
+ process.exit(1);
333
+ }
334
+ if (!result.ok) reportHubError(result.status, result.data, "读取网页会话失败");
335
+ const sessions = result.data?.sessions ?? [];
336
+ if (revoke !== null) {
337
+ if (!revoke) {
338
+ console.error("用法: pi-hub web-sessions --revoke <id|all>");
339
+ process.exit(2);
340
+ }
341
+ const targets = revoke === "all" ? sessions.map((s) => s.id) : [revoke];
342
+ let revoked = 0;
343
+ for (const id of targets) {
344
+ const res = await hubApi("DELETE", `/v1/web/sessions/${encodeURIComponent(id)}`);
345
+ if (res.ok) revoked += 1;
346
+ else if (res.status === 404) console.error(`会话不存在:${id}`);
347
+ else reportHubError(res.status, res.data, "吊销网页会话失败");
348
+ }
349
+ console.log(`已吊销 ${revoked} 个网页会话`);
350
+ process.exit(0);
351
+ }
352
+ if (!sessions.length) {
353
+ console.log("没有网页会话");
354
+ process.exit(0);
355
+ }
356
+ console.log("id created lastSeen expires ip");
357
+ for (const s of sessions) {
358
+ console.log(`${s.id} ${s.createdAt} ${s.lastSeenAt} ${s.expiresAt} ${s.ip ?? "-"}`);
359
+ }
360
+ process.exit(0);
361
+ }
362
+
363
+ if (command === "totp") {
364
+ const sub = argv[argv.indexOf("totp") + 1];
365
+ if (sub === "setup") {
366
+ const secret = base32Encode(randomBytes(20));
367
+ const account = flag("--account", os.userInfo().username || "pi-hub");
368
+ const issuer = flag("--issuer", "pi-hub");
369
+ console.log("TOTP 密钥已生成(20 字节随机,只打印一次;本命令不写任何文件)");
370
+ console.log(` secret: ${secret}`);
371
+ console.log(` otpauth URI: ${otpauthUri({ issuer, account, secret })}`);
372
+ console.log("写进 hub 的启动环境(systemd 用户单元:systemctl --user edit pi-hub 加一行 Environment=):");
373
+ console.log(` PI_HUB_TOTP_SECRET=${secret}`);
374
+ process.exit(0);
375
+ }
376
+ if (sub === "verify") {
377
+ const code = argv[argv.indexOf("totp") + 2];
378
+ if (!code) {
379
+ console.error("用法: pi-hub totp verify <code>");
380
+ process.exit(2);
381
+ }
382
+ const raw = process.env.PI_HUB_TOTP_SECRET;
383
+ if (!raw) {
384
+ console.error("PI_HUB_TOTP_SECRET 未设置;先运行 pi-hub totp setup 并把 secret 写进 hub 的环境");
385
+ process.exit(1);
386
+ }
387
+ let secret;
388
+ try {
389
+ secret = base32Decode(raw);
390
+ } catch (err) {
391
+ console.error(`PI_HUB_TOTP_SECRET 不是合法 base32:${err.message}`);
392
+ process.exit(1);
393
+ }
394
+ const ok = verifyTotp(secret, code);
395
+ console.log(ok ? "TOTP ok" : "TOTP bad");
396
+ process.exit(ok ? 0 : 1);
397
+ }
398
+ console.error("用法: pi-hub totp setup | pi-hub totp verify <code>");
399
+ process.exit(2);
400
+ }
401
+
402
+ if (command !== "serve") {
403
+ console.error(
404
+ `unknown command: ${command}\nusage: pi-hub [serve|token|sessions|doctor|pair|pair-code|devices|listen|web-login|web-sessions|totp] [--port N] [--host H] [--no-auth]`,
405
+ );
406
+ process.exit(2);
407
+ }
408
+
409
+ // serve
410
+ if (has("--no-auth")) process.env.PI_HUB_NO_AUTH = "1";
411
+ let listen;
412
+ try {
413
+ listen = resolveListen({
414
+ argvHost: flag("--host", null),
415
+ argvPort: flag("--port", null),
416
+ env: process.env,
417
+ configDir: CONFIG_DIR,
418
+ // 只有 stdin 是 TTY 且 listen.json 不存在时 resolveListen 才会真提问
419
+ interactive: process.stdin?.isTTY === true,
420
+ ask: readPromptSync,
421
+ });
422
+ } catch (err) {
423
+ console.error(err.message);
424
+ process.exit(err.exitCode ?? 1);
425
+ }
426
+ if (listen.prompted) {
427
+ try {
428
+ const file = writeListenFile({ host: listen.host, port: listen.port }, CONFIG_DIR);
429
+ console.log(`已保存 ${file}`);
430
+ } catch (err) {
431
+ console.error(`写 ${listenFile(CONFIG_DIR)} 失败:${err.message}`);
432
+ }
433
+ }
434
+ const port = listen.port;
435
+ const host = listen.host;
436
+ const hub = createHubServer();
437
+
438
+ const address = await hub.listen({ port, host });
439
+ const token = hub.token;
440
+ console.log(`pi-hub listening on ${formatListenUrl(listen.host, address.port)}`);
441
+ console.log(` auth: ${AUTH_DISABLED ? "DISABLED" : "bearer token"}`);
442
+ // 路径必须走 CONFIG_DIR:PI_HUB_CONFIG_DIR 换目录时写死 ~/.config 会误导(V1 验收实测)。
443
+ if (token) console.log(` token: ${token.length} chars (file: ${tokenFile()}) — 查看用 \`pi-hub token\``);
444
+ console.log(` sessions dir: ${SESSIONS_DIR}`);
445
+ // 启动即生成一次性 6 位配对码(C1.4);生成失败不影响 serve。
446
+ let startupCode = null;
447
+ try {
448
+ startupCode = hub.pairing.createCode();
449
+ } catch (err) {
450
+ console.error(`生成配对码失败:${err.message}(可用 pi-hub pair-code 重试)`);
451
+ }
452
+ if (startupCode) {
453
+ console.log(`配对码 ${startupCode.code}(5 分钟内有效,一次性)`);
454
+ }
455
+ console.log(` 浏览器/App 打开 ${formatListenUrl(listen.host, address.port)}`);
456
+ console.log(` legacy 设备配对: ssh host 'pi-hub pair' (见 README「设备配对」)`);
457
+ if (["127.0.0.1", "localhost", "::1"].includes(host) && !hasTailscaleTun()) {
458
+ console.error("提示:未检测到 Tailscale TUN,当前只监听回环;要在手机上连,走 Tailscale/WireGuard 或 `pi-hub listen --host 0.0.0.0`。");
459
+ }
460
+ console.log(
461
+ ` try: curl -s -H "authorization: Bearer $(pi-hub token)" ${formatListenUrl("127.0.0.1", address.port)}/v1/sessions | head -c 400`,
462
+ );
463
+
464
+ let closing = false;
465
+ for (const signal of ["SIGINT", "SIGTERM"]) {
466
+ process.on(signal, async () => {
467
+ if (closing) return;
468
+ closing = true;
469
+ console.log(`\n${signal}: closing hub + child sessions`);
470
+ await hub.close();
471
+ process.exit(0);
472
+ });
473
+ }