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/src/rpc-once.mjs
CHANGED
|
@@ -30,6 +30,26 @@ export function rpcOnce(type, payload = {}, opts = {}) {
|
|
|
30
30
|
err ? reject(err) : resolve(value);
|
|
31
31
|
};
|
|
32
32
|
const timer = setTimeout(() => done(new Error(`pi rpc timeout: ${type}`)), timeoutMs);
|
|
33
|
+
/**
|
|
34
|
+
* 写一行到子进程 stdin,失败只判本次调用失败(→ 上层 5xx)。
|
|
35
|
+
* 裸 write 在子进程已退出 / spawn 失败时只会得到 EPIPE,而 stdin 没有 error 监听
|
|
36
|
+
* 就是未捕获异常 —— 实测 `PI_HUB_PI_BIN=/bin/true` 下一个 /v1/models 就能带走整个 hub。
|
|
37
|
+
*/
|
|
38
|
+
const writeLine = (rec) => {
|
|
39
|
+
const stdin = child.stdin;
|
|
40
|
+
if (!stdin || stdin.destroyed || !stdin.writable) {
|
|
41
|
+
done(new Error(`pi stdin is not writable (${type})`));
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
stdin.write(`${JSON.stringify(rec)}\n`);
|
|
46
|
+
return true;
|
|
47
|
+
} catch (err) {
|
|
48
|
+
done(new Error(`pi stdin write failed (${type}): ${err.message}`));
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
child.stdin.on("error", (err) => done(new Error(`pi stdin failed (${type}): ${err.message}`)));
|
|
33
53
|
child.on("error", (err) => done(new Error(`spawn pi failed: ${err.message}`)));
|
|
34
54
|
child.on("exit", (code) => {
|
|
35
55
|
if (!settled) done(new Error(`pi exited (${code}) before answering ${type}`));
|
|
@@ -48,7 +68,7 @@ export function rpcOnce(type, payload = {}, opts = {}) {
|
|
|
48
68
|
continue;
|
|
49
69
|
}
|
|
50
70
|
if (rec.type === "extension_ui_request") {
|
|
51
|
-
|
|
71
|
+
writeLine({ type: "extension_ui_response", id: rec.id, cancelled: true });
|
|
52
72
|
continue;
|
|
53
73
|
}
|
|
54
74
|
if (rec.type === "response" && rec.command === type) {
|
|
@@ -58,7 +78,7 @@ export function rpcOnce(type, payload = {}, opts = {}) {
|
|
|
58
78
|
}
|
|
59
79
|
}
|
|
60
80
|
});
|
|
61
|
-
|
|
81
|
+
writeLine({ id: "one", type, ...payload });
|
|
62
82
|
});
|
|
63
83
|
}
|
|
64
84
|
|
package/src/server.mjs
CHANGED
|
@@ -2,19 +2,21 @@ import http from "node:http";
|
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
5
|
-
import { AUTH_DISABLED, CONFIG_DIR, HEARTBEAT_MS, HOME, HOST, IDLE_MS, PORT, SESSIONS_DIR, UPLOAD_DIR, ensureToken, readToken } from "./config.mjs";
|
|
5
|
+
import { AUTH_DISABLED, CONFIG_DIR, HEARTBEAT_MS, HOME, HOST, IDLE_MS, PI_BIN, PORT, SESSIONS_DIR, UPLOAD_DIR, ensureToken, readToken } from "./config.mjs";
|
|
6
6
|
import { findSession, listSessions, readHistory } from "./sessions-index.mjs";
|
|
7
7
|
import { HttpError, Registry } from "./registry.mjs";
|
|
8
8
|
import { listModels, rpcOnce } from "./rpc-once.mjs";
|
|
9
|
-
import { extensionPaths, piArgs } from "./pi-args.mjs";
|
|
10
|
-
import { peek as peekSessionLock } from "./session-lock.mjs";
|
|
11
|
-
import { PairingStore, publicDevice } from "./pairing.mjs";
|
|
9
|
+
import { extensionPaths, extensionsMode, piArgs } from "./pi-args.mjs";
|
|
10
|
+
import { peek as peekSessionLock, corePath as sessionLockCorePath, lockSource as sessionLockSource } from "./session-lock.mjs";
|
|
11
|
+
import { PairingStore, publicDevice, requireSignature } from "./pairing.mjs";
|
|
12
12
|
import { mimeForFile, serveStatic } from "./static.mjs";
|
|
13
13
|
import { WebAuth, clearSessionCookie, handleWebSessionRevoke, handleWebSessionsList, isSecureRequest, sessionCookie } from "./web-auth.mjs";
|
|
14
14
|
import { createOtpStore } from "./otp.mjs";
|
|
15
15
|
import { base32Decode, verifyTotp } from "./totp.mjs";
|
|
16
|
-
import { parseTrustProxyEnv, resolveProxyIdentity } from "./proxy-auth.mjs";
|
|
16
|
+
import { isLocalRequest, parseTrustProxyEnv, resolveClientIp, resolveProxyIdentity } from "./proxy-auth.mjs";
|
|
17
|
+
import { allowCidrsFromEnv, isPeerAllowed } from "./net-allow.mjs";
|
|
17
18
|
import { HUB_VERSION, UpdateChecker } from "./update-check.mjs";
|
|
19
|
+
import { piVersionSnapshot, startPiVersionRefresh } from "./pi-version.mjs";
|
|
18
20
|
|
|
19
21
|
const MAX_BODY = 16 * 1024 * 1024; // prompt 里带 base64 图片
|
|
20
22
|
const MAX_UPLOAD = 32 * 1024 * 1024;
|
|
@@ -107,25 +109,35 @@ function matchesPrimaryToken(given, token) {
|
|
|
107
109
|
}
|
|
108
110
|
|
|
109
111
|
/**
|
|
110
|
-
*
|
|
111
|
-
* - 带了 Bearer 就只按 Bearer
|
|
112
|
+
* 鉴权优先级(PLAN auth-simple §1.3):主令牌(Bearer)> 设备令牌(只验 sha256)> Web 会话 cookie。
|
|
113
|
+
* - 带了 Bearer 就只按 Bearer/设备令牌判(失败不回落 cookie,否则令牌错误会被静默降级)。
|
|
114
|
+
* - 设备令牌默认只比 `sha256(token)` + 未吊销,**不要求任何签名头**;
|
|
115
|
+
* `PI_HUB_REQUIRE_SIGNATURE=1` 时才额外走旧的 `verifyDeviceSignature()`(ts/nonce/sig 齐全)。
|
|
112
116
|
* - cookie 只承载「浏览器登录态」,因此非 GET/HEAD 必须再带 `x-pi-csrf`(与 cookie 绑定)。
|
|
113
117
|
* 设备签名覆盖 SHA256(body),所以调用前 req.rawBody 必须已就绪。
|
|
114
118
|
*/
|
|
115
|
-
function authenticate(req, token, rawBody, pairing, webAuth) {
|
|
119
|
+
function authenticate(req, token, rawBody, pairing, webAuth, { requireSignature: needSignature = false } = {}) {
|
|
116
120
|
if (AUTH_DISABLED) return { ok: true, primary: true, device: null, via: "disabled" };
|
|
117
121
|
const given = bearerToken(req);
|
|
118
122
|
if (given) {
|
|
119
123
|
if (matchesPrimaryToken(given, token)) return { ok: true, primary: true, device: null, via: "bearer" };
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
124
|
+
const tokenVerdict = pairing.verifyDeviceToken(given);
|
|
125
|
+
const signed = () =>
|
|
126
|
+
pairing.verifyDeviceSignature({
|
|
127
|
+
method: req.method ?? "GET",
|
|
128
|
+
path: req.url ?? "/",
|
|
129
|
+
headers: req.headers,
|
|
130
|
+
rawBody,
|
|
131
|
+
token: given,
|
|
132
|
+
});
|
|
133
|
+
if (!needSignature) {
|
|
134
|
+
if (tokenVerdict.ok) return { ok: true, primary: false, device: tokenVerdict.device, via: "device" };
|
|
135
|
+
return { ok: false, code: tokenVerdict.code ?? "unauthorized", message: tokenVerdict.message ?? "unauthorized" };
|
|
136
|
+
}
|
|
137
|
+
// 强制签名模式(旧口径):签名失败的错误码(replay/stale_timestamp/device_revoked)保持不变。
|
|
138
|
+
const verdict = signed();
|
|
127
139
|
if (!verdict.ok) return { ok: false, code: verdict.code, message: verdict.message };
|
|
128
|
-
return { ok: true, primary: false, device: verdict.device, via: "
|
|
140
|
+
return { ok: true, primary: false, device: verdict.device, via: "device_signature" };
|
|
129
141
|
}
|
|
130
142
|
const cookie = webAuth.cookieValue(req);
|
|
131
143
|
const web = webAuth.session(cookie);
|
|
@@ -137,16 +149,6 @@ function authenticate(req, token, rawBody, pairing, webAuth) {
|
|
|
137
149
|
return { ok: true, primary: false, device: null, via: "cookie" };
|
|
138
150
|
}
|
|
139
151
|
|
|
140
|
-
function clientIp(req) {
|
|
141
|
-
return String(req.socket?.remoteAddress ?? "unknown").replace(/^::ffff:/, "");
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
/** 配对管理路由只允许本机(CLI)访问,非 loopback 一律 403 local_only。 */
|
|
145
|
-
function isLoopback(req) {
|
|
146
|
-
const addr = clientIp(req);
|
|
147
|
-
return addr === "127.0.0.1" || addr === "::1" || addr === "localhost";
|
|
148
|
-
}
|
|
149
|
-
|
|
150
152
|
/** 请求入口一次性读完整 body:设备签名要算 SHA256(body),鉴权前拿不到原文就没法验签。 */
|
|
151
153
|
async function bufferBody(req, max) {
|
|
152
154
|
const chunks = [];
|
|
@@ -255,10 +257,12 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
|
|
|
255
257
|
|
|
256
258
|
/**
|
|
257
259
|
* `GET /v1/extensions` 的正文:当前进程拉 pi 时真正会加载的扩展。
|
|
258
|
-
*
|
|
259
|
-
*
|
|
260
|
+
* 默认 mode: "all"(不传 --no-extensions,pi 自己发现扩展);PI_HUB_EXTENSIONS=off ⇒ mode: "none";
|
|
261
|
+
* 显式路径 ⇒ mode: "explicit"(--no-extensions + 每个 -e,旧白名单语义)。
|
|
262
|
+
* `extensions` 是 `-e` 显式列表(真源 pi-args.extensionPaths());extras 是除扩展之外的启动参数。
|
|
260
263
|
*/
|
|
261
264
|
function describeExtensions() {
|
|
265
|
+
const mode = extensionsMode();
|
|
262
266
|
const extensions = extensionPaths().map((p) => {
|
|
263
267
|
try {
|
|
264
268
|
if (!fs.statSync(p).isFile()) return { path: p, ok: false, error: "not a file" };
|
|
@@ -280,6 +284,7 @@ function describeExtensions() {
|
|
|
280
284
|
extensions,
|
|
281
285
|
extras,
|
|
282
286
|
source: process.env.PI_HUB_EXTENSIONS === undefined ? "default" : "env",
|
|
287
|
+
mode,
|
|
283
288
|
};
|
|
284
289
|
}
|
|
285
290
|
|
|
@@ -712,10 +717,13 @@ function sse(req, res, session, since) {
|
|
|
712
717
|
});
|
|
713
718
|
const write = (ev) => res.write(`id: ${ev.seq}\ndata: ${JSON.stringify(ev)}\n\n`);
|
|
714
719
|
const unsubscribe = session.subscribe(write, since);
|
|
715
|
-
// 回放结束的边界:客户端首次订阅时用它区分「历史回放」与「新事件」。
|
|
716
|
-
res.write(": live\n\n");
|
|
717
720
|
// 重连补状态:仍在校的工具(无 `id:` 行、不占 seq,避免污染 since 回放)
|
|
718
721
|
for (const ev of session.activeToolEvents?.() ?? []) res.write(`data: ${JSON.stringify(ev)}\n\n`);
|
|
722
|
+
// 回放结束的边界:客户端首次订阅时用它区分「历史回放」与「新事件」。
|
|
723
|
+
// 注释帧只对自解帧的客户端(安卓)可见;EventSource 的内置解析器不交付注释,
|
|
724
|
+
// 所以再补一帧无 `id:` 的 data 边界(不占 seq、不进环形缓冲,老客户端按未知类型忽略)。
|
|
725
|
+
res.write(": live\n\n");
|
|
726
|
+
res.write(`data: ${JSON.stringify({ type: "live", since, ts: Date.now() })}\n\n`);
|
|
719
727
|
const heartbeat = setInterval(() => {
|
|
720
728
|
// 注释帧给老客户端保活;data 帧给 EventSource 类客户端做静默判死(注释对它是不可见的)
|
|
721
729
|
res.write(": ping\n\n");
|
|
@@ -733,6 +741,8 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
733
741
|
const registry = new Registry({ log });
|
|
734
742
|
const token = AUTH_DISABLED ? null : (readToken() ?? ensureToken());
|
|
735
743
|
const pairing = new PairingStore({ configDir: CONFIG_DIR, log });
|
|
744
|
+
// 签名口径在进程启动时读一次 env:默认只验设备 token 的 sha256;=1 才强制 ECDSA。
|
|
745
|
+
const needSignature = requireSignature(process.env);
|
|
736
746
|
// Web 会话只在内存:hub 重启 = 所有浏览器重新登录(不落盘就没有 session 文件泄漏面)
|
|
737
747
|
const webAuth = new WebAuth({ token, log });
|
|
738
748
|
// 一次性登录码(M4):只在内存,单次消费、2 min TTL(otp.mjs 的 OTP_TTL_MS)
|
|
@@ -742,6 +752,21 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
742
752
|
// 反代可信身份(M6)与 TOTP(M5)在进程启动时各读一次 env:
|
|
743
753
|
// PI_HUB_TRUST_PROXY / PI_HUB_PROXY_SECRET / PI_HUB_PROXY_CIDRS / PI_HUB_PROXY_USER_HEADER、PI_HUB_TOTP_SECRET
|
|
744
754
|
const proxyTrust = parseTrustProxyEnv(process.env);
|
|
755
|
+
// 入站来源网段白名单(独立于鉴权):默认只放行回环 + RFC1918 + CGNAT + 链路本地,
|
|
756
|
+
// `PI_HUB_ALLOW_CIDRS=*` 关闭限制。写错了就让进程起不来,不要静默变成“全放行”。
|
|
757
|
+
let allowCidrs;
|
|
758
|
+
try {
|
|
759
|
+
allowCidrs = allowCidrsFromEnv(process.env);
|
|
760
|
+
} catch (err) {
|
|
761
|
+
log("PI_HUB_ALLOW_CIDRS invalid:", err.message);
|
|
762
|
+
throw err;
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* 限速/审计用的客户端 IP。默认是 socket 对端;`PI_HUB_TRUST_FORWARDED_FOR=1` 且对端在
|
|
766
|
+
* `PI_HUB_PROXY_CIDRS` 内时改用 `x-forwarded-for` 首跳(公网反代场景,否则全世界共用一个桶)。
|
|
767
|
+
* 注意:`PI_HUB_ALLOW_CIDRS` 的判定仍用**对端**地址,不受这里影响。
|
|
768
|
+
*/
|
|
769
|
+
const peerIp = (req) => resolveClientIp(req, proxyTrust);
|
|
745
770
|
const totpSecret = loadTotpSecret(process.env.PI_HUB_TOTP_SECRET);
|
|
746
771
|
/** TOTP 已用步号(防同窗口重放):步号 → 命中时间,60 s 清理。 */
|
|
747
772
|
const totpCounters = new Map();
|
|
@@ -783,14 +808,34 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
783
808
|
);
|
|
784
809
|
}
|
|
785
810
|
const updates = new UpdateChecker(fetchJson ? { fetchJson } : {});
|
|
811
|
+
// pi 版本可见性(PLAN 约束 5):后台探测一次并每 10 min 刷新,`/v1/health` 读快照。
|
|
812
|
+
// 不 await:pi 挂死时 health 不能跟着挂;拿不到版本就只是字段为 null。
|
|
813
|
+
startPiVersionRefresh(PI_BIN);
|
|
786
814
|
const reaper = setInterval(() => registry.reap(IDLE_MS), 60000);
|
|
787
815
|
reaper.unref();
|
|
788
816
|
|
|
817
|
+
// 可选访问日志(`PI_HUB_ACCESS_LOG=1`):一行一个请求,带状态码与耗时。
|
|
818
|
+
// 只用来量首屏到底发了多少请求、哪几个是串行的;默认关。
|
|
819
|
+
const accessLog = process.env.PI_HUB_ACCESS_LOG === "1";
|
|
820
|
+
|
|
789
821
|
const server = http.createServer(async (req, res) => {
|
|
790
822
|
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
|
|
791
823
|
const parts = url.pathname.split("/").filter(Boolean);
|
|
792
824
|
const method = req.method ?? "GET";
|
|
825
|
+
const t0 = accessLog ? process.hrtime.bigint() : 0n;
|
|
826
|
+
if (accessLog) {
|
|
827
|
+
res.on("finish", () => {
|
|
828
|
+
const ms = Number(process.hrtime.bigint() - t0) / 1e6;
|
|
829
|
+
log("access", method, url.pathname, res.statusCode, `${ms.toFixed(1)}ms`);
|
|
830
|
+
});
|
|
831
|
+
}
|
|
793
832
|
try {
|
|
833
|
+
// 来源网段白名单:先于静态资源与鉴权(明文 HTTP 下“谁连得上”比“令牌对不对”更靠前)。
|
|
834
|
+
// 默认只放行回环 + RFC1918 + CGNAT + 链路本地,公网可路由的地址一律 403。
|
|
835
|
+
if (!isPeerAllowed(req.socket?.remoteAddress, allowCidrs)) {
|
|
836
|
+
log("peer not allowed", req.socket?.remoteAddress ?? "unknown", url.pathname);
|
|
837
|
+
return json(res, 403, { error: { message: "peer address not in PI_HUB_ALLOW_CIDRS", code: "ip_not_allowed" } });
|
|
838
|
+
}
|
|
794
839
|
// 静态资源必须先于鉴权:登录页本身不能要求 cookie(否则浏览器永远进不来)。
|
|
795
840
|
// 路由白名单在 src/static.mjs,未命中返回 false 继续走 /v1。
|
|
796
841
|
if (serveStatic(req, res, url)) return;
|
|
@@ -802,13 +847,14 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
802
847
|
: await bufferBody(req, url.pathname === "/v1/upload" ? MAX_UPLOAD : MAX_BODY);
|
|
803
848
|
|
|
804
849
|
// 反向代理可信身份(M6):命中就等价主令牌,未启用或头不匹配时完全不影响后面的鉴权链。
|
|
805
|
-
|
|
850
|
+
// 代理身份的可信度按**对端**地址判(不是 xff 里的客户端地址),否则采信 xff 后就永远对不上 CIDR。
|
|
851
|
+
const proxyIdentity = resolveProxyIdentity(req.headers, req.socket?.remoteAddress, proxyTrust);
|
|
806
852
|
if (proxyIdentity.ok) req.auth = { kind: "proxy", user: proxyIdentity.user };
|
|
807
853
|
|
|
808
854
|
// ---------- 同源 Web 会话(cookie 注入鉴权,PLAN C5) ----------
|
|
809
855
|
// POST /v1/web/login {token, totp?}:主令牌换 session cookie(每 IP 10 次/分;失败延迟 250 ms)
|
|
810
856
|
if (method === "POST" && url.pathname === "/v1/web/login") {
|
|
811
|
-
const ip =
|
|
857
|
+
const ip = peerIp(req);
|
|
812
858
|
if (webAuth.rateLimited(ip)) {
|
|
813
859
|
throw new HttpError(429, "too many login attempts", "rate_limited");
|
|
814
860
|
}
|
|
@@ -867,7 +913,7 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
867
913
|
|
|
868
914
|
// POST /v1/web/otp/redeem {code, totp?, sessionTtlMs?}:无鉴权但限速(每 IP 10 次/分)
|
|
869
915
|
if (method === "POST" && url.pathname === "/v1/web/otp/redeem") {
|
|
870
|
-
const ip =
|
|
916
|
+
const ip = peerIp(req);
|
|
871
917
|
if (otpRedeemLimited(ip)) throw new HttpError(429, "too many otp redeem attempts", "rate_limited");
|
|
872
918
|
const body = readJsonBody(req);
|
|
873
919
|
// TOTP 先于兑换:错码不能把一次性码消耗掉
|
|
@@ -895,7 +941,7 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
895
941
|
if (method === "GET" && url.pathname === "/v1/web/sessions") {
|
|
896
942
|
const out = handleWebSessionsList(req, {
|
|
897
943
|
webAuth,
|
|
898
|
-
ip:
|
|
944
|
+
ip: peerIp(req),
|
|
899
945
|
secure: isSecureRequest(req),
|
|
900
946
|
primary: proxyIdentity.ok || (!AUTH_DISABLED && matchesPrimaryToken(bearerToken(req), token)),
|
|
901
947
|
});
|
|
@@ -906,7 +952,7 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
906
952
|
if (method === "DELETE" && parts[0] === "v1" && parts[1] === "web" && parts[2] === "sessions" && parts[3]) {
|
|
907
953
|
const out = handleWebSessionRevoke(req, {
|
|
908
954
|
webAuth,
|
|
909
|
-
ip:
|
|
955
|
+
ip: peerIp(req),
|
|
910
956
|
secure: isSecureRequest(req),
|
|
911
957
|
params: { id: decodeURIComponent(parts[3]) },
|
|
912
958
|
primary: proxyIdentity.ok || (!AUTH_DISABLED && matchesPrimaryToken(bearerToken(req), token)),
|
|
@@ -916,7 +962,7 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
916
962
|
|
|
917
963
|
// POST /v1/pair/request (无鉴权;TTL 5 min;每 IP 10 次/分)
|
|
918
964
|
if (method === "POST" && url.pathname === "/v1/pair/request") {
|
|
919
|
-
if (pairing.rateLimited(
|
|
965
|
+
if (pairing.rateLimited(peerIp(req))) {
|
|
920
966
|
throw new HttpError(429, "too many pairing requests", "rate_limited");
|
|
921
967
|
}
|
|
922
968
|
const body = readJsonBody(req);
|
|
@@ -930,14 +976,42 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
930
976
|
return json(res, 200, pairing.status(pairId));
|
|
931
977
|
}
|
|
932
978
|
|
|
979
|
+
// POST /v1/pair/claim (无鉴权;每 IP 10 次/分;客户端自生成 token,响应不回显)
|
|
980
|
+
if (method === "POST" && url.pathname === "/v1/pair/claim") {
|
|
981
|
+
if (pairing.redeemRateLimited(peerIp(req))) {
|
|
982
|
+
throw new HttpError(429, "too many pairing claims", "rate_limited");
|
|
983
|
+
}
|
|
984
|
+
const body = readJsonBody(req);
|
|
985
|
+
const claimed = pairing.claimCode({
|
|
986
|
+
code: body.code,
|
|
987
|
+
name: body.name,
|
|
988
|
+
platform: body.platform,
|
|
989
|
+
token: body.token,
|
|
990
|
+
});
|
|
991
|
+
log("pair claim", claimed.deviceId, body.name);
|
|
992
|
+
return json(res, 200, claimed);
|
|
993
|
+
}
|
|
994
|
+
|
|
933
995
|
const auth = proxyIdentity.ok
|
|
934
996
|
? { ok: true, primary: true, device: null, via: "proxy", user: proxyIdentity.user }
|
|
935
|
-
: authenticate(req, token, req.rawBody, pairing, webAuth);
|
|
997
|
+
: authenticate(req, token, req.rawBody, pairing, webAuth, { requireSignature: needSignature });
|
|
936
998
|
if (!auth.ok) throw new HttpError(auth.status ?? 401, auth.message, auth.code);
|
|
937
999
|
|
|
1000
|
+
// POST /v1/pair/code:生成 6 位配对码(仅 loopback + 主令牌,与 /v1/pair/pending 同口径)
|
|
1001
|
+
if (method === "POST" && url.pathname === "/v1/pair/code") {
|
|
1002
|
+
if (!isLocalRequest(req)) throw new HttpError(403, "pairing admin routes are local-only", "local_only");
|
|
1003
|
+
if (!auth.primary) throw new HttpError(403, "primary token required", "primary_token_required");
|
|
1004
|
+
if (pairing.codeRateLimited(peerIp(req))) {
|
|
1005
|
+
throw new HttpError(429, "too many pairing code requests", "rate_limited");
|
|
1006
|
+
}
|
|
1007
|
+
const created = pairing.createCode();
|
|
1008
|
+
log("pair code created", peerIp(req));
|
|
1009
|
+
return json(res, 201, created);
|
|
1010
|
+
}
|
|
1011
|
+
|
|
938
1012
|
// 本地管理路由(仅 loopback + 主令牌,给 CLI 用;pending 只在 hub 内存)
|
|
939
1013
|
if (url.pathname === "/v1/pair/pending" || url.pathname === "/v1/pair/approve" || url.pathname === "/v1/pair/deny") {
|
|
940
|
-
if (!
|
|
1014
|
+
if (!isLocalRequest(req)) throw new HttpError(403, "pairing admin routes are local-only", "local_only");
|
|
941
1015
|
if (!auth.primary) throw new HttpError(403, "primary token required", "primary_token_required");
|
|
942
1016
|
if (method === "GET" && url.pathname === "/v1/pair/pending") {
|
|
943
1017
|
return json(res, 200, { pending: pairing.listPending() });
|
|
@@ -963,11 +1037,11 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
963
1037
|
|
|
964
1038
|
// POST /v1/web/otp:生成一次性登录码(仅 loopback + 主令牌,同 /v1/pair/pending 口径;每 IP 10 次/分)
|
|
965
1039
|
if (method === "POST" && url.pathname === "/v1/web/otp") {
|
|
966
|
-
if (!
|
|
1040
|
+
if (!isLocalRequest(req)) throw new HttpError(403, "otp generation is local-only", "local_only");
|
|
967
1041
|
if (!auth.primary) throw new HttpError(403, "primary token required", "primary_token_required");
|
|
968
|
-
if (otpCreateLimited(
|
|
1042
|
+
if (otpCreateLimited(peerIp(req))) throw new HttpError(429, "too many otp requests", "rate_limited");
|
|
969
1043
|
const created = otpStore.create();
|
|
970
|
-
log("web otp created",
|
|
1044
|
+
log("web otp created", peerIp(req));
|
|
971
1045
|
return json(res, 201, { code: created.code, expiresAt: new Date(created.expiresAt).toISOString() });
|
|
972
1046
|
}
|
|
973
1047
|
|
|
@@ -990,7 +1064,20 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
990
1064
|
|
|
991
1065
|
// GET /v1/health
|
|
992
1066
|
if (method === "GET" && url.pathname === "/v1/health") {
|
|
993
|
-
|
|
1067
|
+
const piVersion = piVersionSnapshot();
|
|
1068
|
+
return json(res, 200, {
|
|
1069
|
+
ok: true,
|
|
1070
|
+
version: HUB_VERSION,
|
|
1071
|
+
liveSessions: registry.list().length,
|
|
1072
|
+
idleMs: IDLE_MS,
|
|
1073
|
+
// 升级后第一眼看见契约漂移:不认识的事件数(进程级累计)。
|
|
1074
|
+
unknownEvents: registry.unknownEvents(),
|
|
1075
|
+
// 锁的实际来源:plugin = pi-session-lock,fallback = 仓内最小实现(与 doctor/banner 同口径)。
|
|
1076
|
+
sessionLock: sessionLockSource,
|
|
1077
|
+
// pi 实测版本(后台探测);未探到时为 null。
|
|
1078
|
+
piVersion: piVersion.version,
|
|
1079
|
+
piVersionCheckedAt: piVersion.checkedAt,
|
|
1080
|
+
});
|
|
994
1081
|
}
|
|
995
1082
|
|
|
996
1083
|
// GET /v1/update[?android=<当前客户端版本>] 最新版本(缓存 1 h;上游失败也回 200 + error)
|
|
@@ -1517,7 +1604,10 @@ export function createHubServer({ fetchJson } = {}) {
|
|
|
1517
1604
|
return {
|
|
1518
1605
|
server,
|
|
1519
1606
|
registry,
|
|
1607
|
+
pairing,
|
|
1520
1608
|
token,
|
|
1609
|
+
/** 实际使用的锁来源与插件路径(banner / 测试读它,避免每处各自重新解析)。 */
|
|
1610
|
+
sessionLock: { source: sessionLockSource, corePath: sessionLockCorePath },
|
|
1521
1611
|
listen({ port = PORT, host = HOST } = {}) {
|
|
1522
1612
|
return new Promise((resolve) => {
|
|
1523
1613
|
server.listen(port, host, () => resolve(server.address()));
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 内置的最小会话锁 —— 没装 `pi-session-lock` 插件时的降级实现。
|
|
3
|
+
*
|
|
4
|
+
* 为什么要有它:pi-hub 的唯一硬要求是「同一个 session .jsonl 只有一个写者」,
|
|
5
|
+
* 而插件只是这个判定的*首选*实现(它还带让锁/fork 策略)。全新机器上没装插件时
|
|
6
|
+
* 不能因此让 `pi-hub doctor` / `pi-hub serve` 崩掉,所以这里保留最小的一份。
|
|
7
|
+
*
|
|
8
|
+
* 与插件**共用同一个命名空间**:`<agentDir>/session-locks/<sha256(realpath(session))>.lock/owner.json`,
|
|
9
|
+
* 装了插件之后两边看到的是同一把锁,可以互相判活。判定口径也只保留插件文档里的那几条:
|
|
10
|
+
* 1. mkdir 的 O_EXCL 语义给出原子认领(并发抢锁只有一个成功)
|
|
11
|
+
* 2. owner.json 记录**实际写盘进程**的 pid / starttime / boot_id(hub 代管时是 pi 子进程)
|
|
12
|
+
* 3. 只有能证明 owner 已死(pid 没了 / pid 被复用 / 关机重启)才回收,其余一律 fail-open
|
|
13
|
+
* 降级不放宽互斥:抢到手的锁靠 mkdir 原子性保证,不依赖任何进程内状态。
|
|
14
|
+
* 删掉的是插件的额外策略(yield 请求、paseo 轮次、follow 转发),那些不影响互斥。
|
|
15
|
+
*/
|
|
16
|
+
import fs from "node:fs";
|
|
17
|
+
import os from "node:os";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import crypto from "node:crypto";
|
|
20
|
+
|
|
21
|
+
const HOST = os.hostname();
|
|
22
|
+
|
|
23
|
+
/** 与插件同一个 globalThis 键:真插件与 fallback 同进程加载时不会互相判成「别人」。 */
|
|
24
|
+
const IDENTITY = Symbol.for("pi.session-lock.identity");
|
|
25
|
+
|
|
26
|
+
export function resolveAgentDir(explicit) {
|
|
27
|
+
return explicit || process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 逃生阀:`PI_SESSION_LOCK=off`(插件口径)/ `PI_HUB_NO_SESSION_LOCK=1` 都关锁。 */
|
|
31
|
+
export function enabled() {
|
|
32
|
+
if ((process.env.PI_SESSION_LOCK ?? "").toLowerCase() === "off") return false;
|
|
33
|
+
if (process.env.PI_HUB_NO_SESSION_LOCK === "1") return false;
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function readBootId() {
|
|
38
|
+
try {
|
|
39
|
+
return fs.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
|
|
40
|
+
} catch {
|
|
41
|
+
return "";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function readStartTicks(pid) {
|
|
46
|
+
try {
|
|
47
|
+
const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
48
|
+
// 字段从 "pid (comm) " 之后从 #3(state) 开始;starttime 是 #22 → 下标 19。
|
|
49
|
+
const rest = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
50
|
+
return rest[19] ?? "";
|
|
51
|
+
} catch {
|
|
52
|
+
return "";
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function isAlive(pid) {
|
|
57
|
+
try {
|
|
58
|
+
process.kill(pid, 0);
|
|
59
|
+
return true;
|
|
60
|
+
} catch (error) {
|
|
61
|
+
return error.code === "EPERM";
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 本进程的稳定身份(Symbol 复用:同进程多次 import / 扩展 reload 不改 instanceId)。 */
|
|
66
|
+
export function identity() {
|
|
67
|
+
const g = globalThis;
|
|
68
|
+
if (!g[IDENTITY]) {
|
|
69
|
+
g[IDENTITY] = {
|
|
70
|
+
v: 1,
|
|
71
|
+
pid: process.pid,
|
|
72
|
+
host: HOST,
|
|
73
|
+
bootId: readBootId(),
|
|
74
|
+
startTicks: readStartTicks(process.pid),
|
|
75
|
+
instanceId: crypto.randomUUID(),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
return g[IDENTITY];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 与插件逐字一致的锁目录:sha256(realpath(session)),文件还没落盘时退化为 path.resolve。 */
|
|
82
|
+
export function lockDirFor(sessionFile, opts = {}) {
|
|
83
|
+
const canonical = (() => {
|
|
84
|
+
try {
|
|
85
|
+
return fs.realpathSync(sessionFile);
|
|
86
|
+
} catch {
|
|
87
|
+
return path.resolve(sessionFile);
|
|
88
|
+
}
|
|
89
|
+
})();
|
|
90
|
+
const hash = crypto.createHash("sha256").update(canonical).digest("hex");
|
|
91
|
+
return path.join(resolveAgentDir(opts.agentDir), "session-locks", `${hash}.lock`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function readOwner(dir) {
|
|
95
|
+
try {
|
|
96
|
+
return JSON.parse(fs.readFileSync(path.join(dir, "owner.json"), "utf8"));
|
|
97
|
+
} catch {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** live = 证明有另一个活进程;dead = 证明所有者已消失;unknown = 说不清(→ fail-open)。 */
|
|
103
|
+
export function classify(owner) {
|
|
104
|
+
const me = identity();
|
|
105
|
+
if (owner?.instanceId === me.instanceId) return { kind: "self", reason: "owned by this process" };
|
|
106
|
+
if (owner?.host !== HOST) return { kind: "unknown", reason: `owner on another host (${owner?.host})` };
|
|
107
|
+
if (owner?.bootId !== me.bootId) return { kind: "dead", reason: "host rebooted since lock was taken" };
|
|
108
|
+
if (typeof owner?.pid !== "number") return { kind: "unknown", reason: "owner has no pid" };
|
|
109
|
+
if (!isAlive(owner.pid)) return { kind: "dead", reason: `pid ${owner.pid} is gone` };
|
|
110
|
+
if (owner.startTicks && owner.startTicks !== readStartTicks(owner.pid))
|
|
111
|
+
return { kind: "dead", reason: `pid ${owner.pid} was reused (starttime mismatch)` };
|
|
112
|
+
return { kind: "live", reason: `pid ${owner.pid} is alive` };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* 认领锁:mkdir 的 O_EXCL 语义是唯一原子点;死锁回收后重试(最多 3 次)。
|
|
117
|
+
*
|
|
118
|
+
* @param {string} sessionFile
|
|
119
|
+
* @param {{agentDir?:string, writerPid?:number, source?:string}} [opts]
|
|
120
|
+
* writerPid = 实际写盘进程(hub 传 pi 子进程 pid;不传则记自身)
|
|
121
|
+
* @returns {{ok:boolean, state:"owned"|"conflict"|"unknown"|"off", dir:string|null, reason:string, owner?:any}}
|
|
122
|
+
*/
|
|
123
|
+
export function claim(sessionFile, opts = {}) {
|
|
124
|
+
if (!enabled()) return { ok: true, state: "off", dir: null, reason: "disabled" };
|
|
125
|
+
const dir = lockDirFor(sessionFile, opts);
|
|
126
|
+
const me = identity();
|
|
127
|
+
const writer = opts.writerPid ?? me.pid;
|
|
128
|
+
|
|
129
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
130
|
+
let taken = false;
|
|
131
|
+
try {
|
|
132
|
+
fs.mkdirSync(path.dirname(dir), { recursive: true, mode: 0o700 });
|
|
133
|
+
fs.mkdirSync(dir, { mode: 0o700 });
|
|
134
|
+
taken = true;
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (error.code !== "EEXIST") return { ok: false, state: "unknown", dir, reason: String(error) };
|
|
137
|
+
}
|
|
138
|
+
if (taken) {
|
|
139
|
+
const owner = {
|
|
140
|
+
...me,
|
|
141
|
+
pid: writer,
|
|
142
|
+
startTicks: readStartTicks(writer),
|
|
143
|
+
source: opts.source ?? "pi-hub-fallback",
|
|
144
|
+
sessionFile,
|
|
145
|
+
acquiredAt: new Date().toISOString(),
|
|
146
|
+
};
|
|
147
|
+
// hub 代管时 pid 是 pi 子进程:hub 被 SIGKILL 后子进程也走了,锁随之判死;
|
|
148
|
+
// ownerPid 只为排查「谁认领的」。
|
|
149
|
+
if (me.pid !== writer) owner.ownerPid = me.pid;
|
|
150
|
+
try {
|
|
151
|
+
fs.writeFileSync(path.join(dir, "owner.json"), `${JSON.stringify(owner, null, 2)}\n`, { mode: 0o600 });
|
|
152
|
+
} catch (error) {
|
|
153
|
+
// 目录建了但 owner.json 写不进去:清掉,别留一把谁也认不出的锁。
|
|
154
|
+
try {
|
|
155
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
156
|
+
} catch {
|
|
157
|
+
/* best effort */
|
|
158
|
+
}
|
|
159
|
+
return { ok: false, state: "unknown", dir, reason: `owner.json write failed: ${error.message}` };
|
|
160
|
+
}
|
|
161
|
+
return { ok: true, state: "owned", dir, reason: "claimed", owner };
|
|
162
|
+
}
|
|
163
|
+
const owner = readOwner(dir);
|
|
164
|
+
if (!owner || typeof owner.pid !== "number") {
|
|
165
|
+
return { ok: false, state: "unknown", dir, reason: "owner.json missing or malformed" };
|
|
166
|
+
}
|
|
167
|
+
const verdict = classify(owner);
|
|
168
|
+
if (verdict.kind === "self") return { ok: true, state: "owned", dir, reason: "already ours", owner };
|
|
169
|
+
if (verdict.kind === "unknown") return { ok: false, state: "unknown", dir, reason: verdict.reason, owner };
|
|
170
|
+
if (verdict.kind === "live") return { ok: false, state: "conflict", dir, reason: verdict.reason, owner };
|
|
171
|
+
// dead → 回收后重试
|
|
172
|
+
try {
|
|
173
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
174
|
+
} catch {
|
|
175
|
+
return { ok: false, state: "unknown", dir, reason: "stale lock could not be removed" };
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return { ok: false, state: "unknown", dir, reason: "lock reclaim retried 3x" };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** 只读探测:不创建、不回收(DELETE ?delete=1 的 409 前置检查用)。 */
|
|
182
|
+
export function peek(sessionFile, opts = {}) {
|
|
183
|
+
if (!enabled()) return { state: "off", dir: null, owner: null, reason: "disabled" };
|
|
184
|
+
const dir = lockDirFor(sessionFile, opts);
|
|
185
|
+
if (!fs.existsSync(dir)) return { state: "none", dir, owner: null, reason: "no lock" };
|
|
186
|
+
const owner = readOwner(dir);
|
|
187
|
+
if (!owner || typeof owner.pid !== "number") {
|
|
188
|
+
return { state: "unknown", dir, owner: null, reason: "owner.json missing or malformed" };
|
|
189
|
+
}
|
|
190
|
+
const verdict = classify(owner);
|
|
191
|
+
return { state: verdict.kind, dir, owner, reason: verdict.reason };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** 只释放自己持有的锁(按 instanceId 认),绝不误删别人的。 */
|
|
195
|
+
export function release(dir) {
|
|
196
|
+
if (!dir) return;
|
|
197
|
+
try {
|
|
198
|
+
const owner = readOwner(dir);
|
|
199
|
+
if (owner && owner.instanceId === identity().instanceId) fs.rmSync(dir, { recursive: true, force: true });
|
|
200
|
+
} catch {
|
|
201
|
+
/* best effort */
|
|
202
|
+
}
|
|
203
|
+
}
|