pi-hub-server 0.3.2 → 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/src/server.mjs CHANGED
@@ -6,14 +6,15 @@ import { AUTH_DISABLED, CONFIG_DIR, HEARTBEAT_MS, HOME, HOST, IDLE_MS, PORT, SES
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";
9
+ import { extensionPaths, extensionsMode, piArgs } from "./pi-args.mjs";
10
10
  import { peek as peekSessionLock } from "./session-lock.mjs";
11
- import { PairingStore, publicDevice } from "./pairing.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";
18
19
 
19
20
  const MAX_BODY = 16 * 1024 * 1024; // prompt 里带 base64 图片
@@ -107,25 +108,35 @@ function matchesPrimaryToken(given, token) {
107
108
  }
108
109
 
109
110
  /**
110
- * 鉴权优先级:主令牌(Bearer)> 设备令牌 + 完整签名 > Web 会话 cookie。
111
- * - 带了 Bearer 就只按 Bearer/设备签名判(失败不回落 cookie,否则令牌错误会被静默降级)。
111
+ * 鉴权优先级(PLAN auth-simple §1.3):主令牌(Bearer)> 设备令牌(只验 sha256)> Web 会话 cookie。
112
+ * - 带了 Bearer 就只按 Bearer/设备令牌判(失败不回落 cookie,否则令牌错误会被静默降级)。
113
+ * - 设备令牌默认只比 `sha256(token)` + 未吊销,**不要求任何签名头**;
114
+ * `PI_HUB_REQUIRE_SIGNATURE=1` 时才额外走旧的 `verifyDeviceSignature()`(ts/nonce/sig 齐全)。
112
115
  * - cookie 只承载「浏览器登录态」,因此非 GET/HEAD 必须再带 `x-pi-csrf`(与 cookie 绑定)。
113
116
  * 设备签名覆盖 SHA256(body),所以调用前 req.rawBody 必须已就绪。
114
117
  */
115
- function authenticate(req, token, rawBody, pairing, webAuth) {
118
+ function authenticate(req, token, rawBody, pairing, webAuth, { requireSignature: needSignature = false } = {}) {
116
119
  if (AUTH_DISABLED) return { ok: true, primary: true, device: null, via: "disabled" };
117
120
  const given = bearerToken(req);
118
121
  if (given) {
119
122
  if (matchesPrimaryToken(given, token)) return { ok: true, primary: true, device: null, via: "bearer" };
120
- const verdict = pairing.verifyDeviceSignature({
121
- method: req.method ?? "GET",
122
- path: req.url ?? "/",
123
- headers: req.headers,
124
- rawBody,
125
- token: given,
126
- });
123
+ const tokenVerdict = pairing.verifyDeviceToken(given);
124
+ const signed = () =>
125
+ pairing.verifyDeviceSignature({
126
+ method: req.method ?? "GET",
127
+ path: req.url ?? "/",
128
+ headers: req.headers,
129
+ rawBody,
130
+ token: given,
131
+ });
132
+ if (!needSignature) {
133
+ if (tokenVerdict.ok) return { ok: true, primary: false, device: tokenVerdict.device, via: "device" };
134
+ return { ok: false, code: tokenVerdict.code ?? "unauthorized", message: tokenVerdict.message ?? "unauthorized" };
135
+ }
136
+ // 强制签名模式(旧口径):签名失败的错误码(replay/stale_timestamp/device_revoked)保持不变。
137
+ const verdict = signed();
127
138
  if (!verdict.ok) return { ok: false, code: verdict.code, message: verdict.message };
128
- return { ok: true, primary: false, device: verdict.device, via: "device" };
139
+ return { ok: true, primary: false, device: verdict.device, via: "device_signature" };
129
140
  }
130
141
  const cookie = webAuth.cookieValue(req);
131
142
  const web = webAuth.session(cookie);
@@ -137,16 +148,6 @@ function authenticate(req, token, rawBody, pairing, webAuth) {
137
148
  return { ok: true, primary: false, device: null, via: "cookie" };
138
149
  }
139
150
 
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
151
  /** 请求入口一次性读完整 body:设备签名要算 SHA256(body),鉴权前拿不到原文就没法验签。 */
151
152
  async function bufferBody(req, max) {
152
153
  const chunks = [];
@@ -255,10 +256,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
256
 
256
257
  /**
257
258
  * `GET /v1/extensions` 的正文:当前进程拉 pi 时真正会加载的扩展。
258
- * hub 用 `--no-extensions -e <path>` 起 pi,生效列表就是 extensionPaths() 的结果;
259
- * 每个路径做一次存在性探测(缺失=加载必然失败)。extras 是除扩展之外的启动参数。
259
+ * 默认 mode: "all"(不传 --no-extensions,pi 自己发现扩展);PI_HUB_EXTENSIONS=off ⇒ mode: "none";
260
+ * 显式路径 ⇒ mode: "explicit"(--no-extensions + 每个 -e,旧白名单语义)。
261
+ * `extensions` 是 `-e` 显式列表(真源 pi-args.extensionPaths());extras 是除扩展之外的启动参数。
260
262
  */
261
263
  function describeExtensions() {
264
+ const mode = extensionsMode();
262
265
  const extensions = extensionPaths().map((p) => {
263
266
  try {
264
267
  if (!fs.statSync(p).isFile()) return { path: p, ok: false, error: "not a file" };
@@ -280,6 +283,7 @@ function describeExtensions() {
280
283
  extensions,
281
284
  extras,
282
285
  source: process.env.PI_HUB_EXTENSIONS === undefined ? "default" : "env",
286
+ mode,
283
287
  };
284
288
  }
285
289
 
@@ -712,10 +716,13 @@ function sse(req, res, session, since) {
712
716
  });
713
717
  const write = (ev) => res.write(`id: ${ev.seq}\ndata: ${JSON.stringify(ev)}\n\n`);
714
718
  const unsubscribe = session.subscribe(write, since);
715
- // 回放结束的边界:客户端首次订阅时用它区分「历史回放」与「新事件」。
716
- res.write(": live\n\n");
717
719
  // 重连补状态:仍在校的工具(无 `id:` 行、不占 seq,避免污染 since 回放)
718
720
  for (const ev of session.activeToolEvents?.() ?? []) res.write(`data: ${JSON.stringify(ev)}\n\n`);
721
+ // 回放结束的边界:客户端首次订阅时用它区分「历史回放」与「新事件」。
722
+ // 注释帧只对自解帧的客户端(安卓)可见;EventSource 的内置解析器不交付注释,
723
+ // 所以再补一帧无 `id:` 的 data 边界(不占 seq、不进环形缓冲,老客户端按未知类型忽略)。
724
+ res.write(": live\n\n");
725
+ res.write(`data: ${JSON.stringify({ type: "live", since, ts: Date.now() })}\n\n`);
719
726
  const heartbeat = setInterval(() => {
720
727
  // 注释帧给老客户端保活;data 帧给 EventSource 类客户端做静默判死(注释对它是不可见的)
721
728
  res.write(": ping\n\n");
@@ -733,6 +740,8 @@ export function createHubServer({ fetchJson } = {}) {
733
740
  const registry = new Registry({ log });
734
741
  const token = AUTH_DISABLED ? null : (readToken() ?? ensureToken());
735
742
  const pairing = new PairingStore({ configDir: CONFIG_DIR, log });
743
+ // 签名口径在进程启动时读一次 env:默认只验设备 token 的 sha256;=1 才强制 ECDSA。
744
+ const needSignature = requireSignature(process.env);
736
745
  // Web 会话只在内存:hub 重启 = 所有浏览器重新登录(不落盘就没有 session 文件泄漏面)
737
746
  const webAuth = new WebAuth({ token, log });
738
747
  // 一次性登录码(M4):只在内存,单次消费、2 min TTL(otp.mjs 的 OTP_TTL_MS)
@@ -742,6 +751,21 @@ export function createHubServer({ fetchJson } = {}) {
742
751
  // 反代可信身份(M6)与 TOTP(M5)在进程启动时各读一次 env:
743
752
  // PI_HUB_TRUST_PROXY / PI_HUB_PROXY_SECRET / PI_HUB_PROXY_CIDRS / PI_HUB_PROXY_USER_HEADER、PI_HUB_TOTP_SECRET
744
753
  const proxyTrust = parseTrustProxyEnv(process.env);
754
+ // 入站来源网段白名单(独立于鉴权):默认只放行回环 + RFC1918 + CGNAT + 链路本地,
755
+ // `PI_HUB_ALLOW_CIDRS=*` 关闭限制。写错了就让进程起不来,不要静默变成“全放行”。
756
+ let allowCidrs;
757
+ try {
758
+ allowCidrs = allowCidrsFromEnv(process.env);
759
+ } catch (err) {
760
+ log("PI_HUB_ALLOW_CIDRS invalid:", err.message);
761
+ throw err;
762
+ }
763
+ /**
764
+ * 限速/审计用的客户端 IP。默认是 socket 对端;`PI_HUB_TRUST_FORWARDED_FOR=1` 且对端在
765
+ * `PI_HUB_PROXY_CIDRS` 内时改用 `x-forwarded-for` 首跳(公网反代场景,否则全世界共用一个桶)。
766
+ * 注意:`PI_HUB_ALLOW_CIDRS` 的判定仍用**对端**地址,不受这里影响。
767
+ */
768
+ const peerIp = (req) => resolveClientIp(req, proxyTrust);
745
769
  const totpSecret = loadTotpSecret(process.env.PI_HUB_TOTP_SECRET);
746
770
  /** TOTP 已用步号(防同窗口重放):步号 → 命中时间,60 s 清理。 */
747
771
  const totpCounters = new Map();
@@ -786,11 +810,28 @@ export function createHubServer({ fetchJson } = {}) {
786
810
  const reaper = setInterval(() => registry.reap(IDLE_MS), 60000);
787
811
  reaper.unref();
788
812
 
813
+ // 可选访问日志(`PI_HUB_ACCESS_LOG=1`):一行一个请求,带状态码与耗时。
814
+ // 只用来量首屏到底发了多少请求、哪几个是串行的;默认关。
815
+ const accessLog = process.env.PI_HUB_ACCESS_LOG === "1";
816
+
789
817
  const server = http.createServer(async (req, res) => {
790
818
  const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
791
819
  const parts = url.pathname.split("/").filter(Boolean);
792
820
  const method = req.method ?? "GET";
821
+ const t0 = accessLog ? process.hrtime.bigint() : 0n;
822
+ if (accessLog) {
823
+ res.on("finish", () => {
824
+ const ms = Number(process.hrtime.bigint() - t0) / 1e6;
825
+ log("access", method, url.pathname, res.statusCode, `${ms.toFixed(1)}ms`);
826
+ });
827
+ }
793
828
  try {
829
+ // 来源网段白名单:先于静态资源与鉴权(明文 HTTP 下“谁连得上”比“令牌对不对”更靠前)。
830
+ // 默认只放行回环 + RFC1918 + CGNAT + 链路本地,公网可路由的地址一律 403。
831
+ if (!isPeerAllowed(req.socket?.remoteAddress, allowCidrs)) {
832
+ log("peer not allowed", req.socket?.remoteAddress ?? "unknown", url.pathname);
833
+ return json(res, 403, { error: { message: "peer address not in PI_HUB_ALLOW_CIDRS", code: "ip_not_allowed" } });
834
+ }
794
835
  // 静态资源必须先于鉴权:登录页本身不能要求 cookie(否则浏览器永远进不来)。
795
836
  // 路由白名单在 src/static.mjs,未命中返回 false 继续走 /v1。
796
837
  if (serveStatic(req, res, url)) return;
@@ -802,13 +843,14 @@ export function createHubServer({ fetchJson } = {}) {
802
843
  : await bufferBody(req, url.pathname === "/v1/upload" ? MAX_UPLOAD : MAX_BODY);
803
844
 
804
845
  // 反向代理可信身份(M6):命中就等价主令牌,未启用或头不匹配时完全不影响后面的鉴权链。
805
- const proxyIdentity = resolveProxyIdentity(req.headers, clientIp(req), proxyTrust);
846
+ // 代理身份的可信度按**对端**地址判(不是 xff 里的客户端地址),否则采信 xff 后就永远对不上 CIDR。
847
+ const proxyIdentity = resolveProxyIdentity(req.headers, req.socket?.remoteAddress, proxyTrust);
806
848
  if (proxyIdentity.ok) req.auth = { kind: "proxy", user: proxyIdentity.user };
807
849
 
808
850
  // ---------- 同源 Web 会话(cookie 注入鉴权,PLAN C5) ----------
809
851
  // POST /v1/web/login {token, totp?}:主令牌换 session cookie(每 IP 10 次/分;失败延迟 250 ms)
810
852
  if (method === "POST" && url.pathname === "/v1/web/login") {
811
- const ip = clientIp(req);
853
+ const ip = peerIp(req);
812
854
  if (webAuth.rateLimited(ip)) {
813
855
  throw new HttpError(429, "too many login attempts", "rate_limited");
814
856
  }
@@ -867,7 +909,7 @@ export function createHubServer({ fetchJson } = {}) {
867
909
 
868
910
  // POST /v1/web/otp/redeem {code, totp?, sessionTtlMs?}:无鉴权但限速(每 IP 10 次/分)
869
911
  if (method === "POST" && url.pathname === "/v1/web/otp/redeem") {
870
- const ip = clientIp(req);
912
+ const ip = peerIp(req);
871
913
  if (otpRedeemLimited(ip)) throw new HttpError(429, "too many otp redeem attempts", "rate_limited");
872
914
  const body = readJsonBody(req);
873
915
  // TOTP 先于兑换:错码不能把一次性码消耗掉
@@ -895,7 +937,7 @@ export function createHubServer({ fetchJson } = {}) {
895
937
  if (method === "GET" && url.pathname === "/v1/web/sessions") {
896
938
  const out = handleWebSessionsList(req, {
897
939
  webAuth,
898
- ip: clientIp(req),
940
+ ip: peerIp(req),
899
941
  secure: isSecureRequest(req),
900
942
  primary: proxyIdentity.ok || (!AUTH_DISABLED && matchesPrimaryToken(bearerToken(req), token)),
901
943
  });
@@ -906,7 +948,7 @@ export function createHubServer({ fetchJson } = {}) {
906
948
  if (method === "DELETE" && parts[0] === "v1" && parts[1] === "web" && parts[2] === "sessions" && parts[3]) {
907
949
  const out = handleWebSessionRevoke(req, {
908
950
  webAuth,
909
- ip: clientIp(req),
951
+ ip: peerIp(req),
910
952
  secure: isSecureRequest(req),
911
953
  params: { id: decodeURIComponent(parts[3]) },
912
954
  primary: proxyIdentity.ok || (!AUTH_DISABLED && matchesPrimaryToken(bearerToken(req), token)),
@@ -916,7 +958,7 @@ export function createHubServer({ fetchJson } = {}) {
916
958
 
917
959
  // POST /v1/pair/request (无鉴权;TTL 5 min;每 IP 10 次/分)
918
960
  if (method === "POST" && url.pathname === "/v1/pair/request") {
919
- if (pairing.rateLimited(clientIp(req))) {
961
+ if (pairing.rateLimited(peerIp(req))) {
920
962
  throw new HttpError(429, "too many pairing requests", "rate_limited");
921
963
  }
922
964
  const body = readJsonBody(req);
@@ -930,14 +972,42 @@ export function createHubServer({ fetchJson } = {}) {
930
972
  return json(res, 200, pairing.status(pairId));
931
973
  }
932
974
 
975
+ // POST /v1/pair/claim (无鉴权;每 IP 10 次/分;客户端自生成 token,响应不回显)
976
+ if (method === "POST" && url.pathname === "/v1/pair/claim") {
977
+ if (pairing.redeemRateLimited(peerIp(req))) {
978
+ throw new HttpError(429, "too many pairing claims", "rate_limited");
979
+ }
980
+ const body = readJsonBody(req);
981
+ const claimed = pairing.claimCode({
982
+ code: body.code,
983
+ name: body.name,
984
+ platform: body.platform,
985
+ token: body.token,
986
+ });
987
+ log("pair claim", claimed.deviceId, body.name);
988
+ return json(res, 200, claimed);
989
+ }
990
+
933
991
  const auth = proxyIdentity.ok
934
992
  ? { ok: true, primary: true, device: null, via: "proxy", user: proxyIdentity.user }
935
- : authenticate(req, token, req.rawBody, pairing, webAuth);
993
+ : authenticate(req, token, req.rawBody, pairing, webAuth, { requireSignature: needSignature });
936
994
  if (!auth.ok) throw new HttpError(auth.status ?? 401, auth.message, auth.code);
937
995
 
996
+ // POST /v1/pair/code:生成 6 位配对码(仅 loopback + 主令牌,与 /v1/pair/pending 同口径)
997
+ if (method === "POST" && url.pathname === "/v1/pair/code") {
998
+ if (!isLocalRequest(req)) throw new HttpError(403, "pairing admin routes are local-only", "local_only");
999
+ if (!auth.primary) throw new HttpError(403, "primary token required", "primary_token_required");
1000
+ if (pairing.codeRateLimited(peerIp(req))) {
1001
+ throw new HttpError(429, "too many pairing code requests", "rate_limited");
1002
+ }
1003
+ const created = pairing.createCode();
1004
+ log("pair code created", peerIp(req));
1005
+ return json(res, 201, created);
1006
+ }
1007
+
938
1008
  // 本地管理路由(仅 loopback + 主令牌,给 CLI 用;pending 只在 hub 内存)
939
1009
  if (url.pathname === "/v1/pair/pending" || url.pathname === "/v1/pair/approve" || url.pathname === "/v1/pair/deny") {
940
- if (!isLoopback(req)) throw new HttpError(403, "pairing admin routes are loopback-only", "local_only");
1010
+ if (!isLocalRequest(req)) throw new HttpError(403, "pairing admin routes are local-only", "local_only");
941
1011
  if (!auth.primary) throw new HttpError(403, "primary token required", "primary_token_required");
942
1012
  if (method === "GET" && url.pathname === "/v1/pair/pending") {
943
1013
  return json(res, 200, { pending: pairing.listPending() });
@@ -963,11 +1033,11 @@ export function createHubServer({ fetchJson } = {}) {
963
1033
 
964
1034
  // POST /v1/web/otp:生成一次性登录码(仅 loopback + 主令牌,同 /v1/pair/pending 口径;每 IP 10 次/分)
965
1035
  if (method === "POST" && url.pathname === "/v1/web/otp") {
966
- if (!isLoopback(req)) throw new HttpError(403, "otp generation is loopback-only", "local_only");
1036
+ if (!isLocalRequest(req)) throw new HttpError(403, "otp generation is local-only", "local_only");
967
1037
  if (!auth.primary) throw new HttpError(403, "primary token required", "primary_token_required");
968
- if (otpCreateLimited(clientIp(req))) throw new HttpError(429, "too many otp requests", "rate_limited");
1038
+ if (otpCreateLimited(peerIp(req))) throw new HttpError(429, "too many otp requests", "rate_limited");
969
1039
  const created = otpStore.create();
970
- log("web otp created", clientIp(req));
1040
+ log("web otp created", peerIp(req));
971
1041
  return json(res, 201, { code: created.code, expiresAt: new Date(created.expiresAt).toISOString() });
972
1042
  }
973
1043
 
@@ -1517,6 +1587,7 @@ export function createHubServer({ fetchJson } = {}) {
1517
1587
  return {
1518
1588
  server,
1519
1589
  registry,
1590
+ pairing,
1520
1591
  token,
1521
1592
  listen({ port = PORT, host = HOST } = {}) {
1522
1593
  return new Promise((resolve) => {
@@ -14,6 +14,24 @@ Environment=PATH=%h/.pi/agent/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/
14
14
  Environment=PI_HUB_PORT=6768
15
15
  # 只监听局域网/校园网地址时可改成具体 IP
16
16
  Environment=PI_HUB_HOST=0.0.0.0
17
+ # 入站来源网段白名单(先于鉴权):默认已是 回环+RFC1918+CGNAT+链路本地,
18
+ # 即绑 0.0.0.0 也只是对私有网/Tailscale 可达,公网可路由来源一律 403。
19
+ # 前面有反代并自己负责 TLS/访问控制时再放开:
20
+ #Environment=PI_HUB_ALLOW_CIDRS=*
21
+ #
22
+ # 有 TLS 的推荐组合(Tailscale Serve 当 HTTPS 入口,hub 只听回环):
23
+ # tailscale serve --bg http://127.0.0.1:6768 # 需先在 tailnet 控制台启用 HTTPS Certificates
24
+ # 然后下面两行同时启用(服务地址改成 https://<节点名>.<tailnet>.ts.net/)
25
+ #Environment=PI_HUB_HOST=127.0.0.1
26
+ #Environment=PI_HUB_ALLOW_CIDRS=127.0.0.0/8,::1/128 # Serve 从本机回环转发进来
27
+ #
28
+ # 还要从**公网**(客户端不装 Tailscale)访问时,把同一入口改成 Funnel,并打开 xff 采信:
29
+ # tailscale funnel --bg http://127.0.0.1:6768 # 公网 HTTPS;关闭:tailscale funnel --https=443 off
30
+ #Environment=PI_HUB_HOST=127.0.0.1
31
+ #Environment=PI_HUB_TRUST_FORWARDED_FOR=1
32
+ #Environment=PI_HUB_PROXY_CIDRS=127.0.0.1/32 # 反代/Funnel 跑在本机就是这个
33
+ # 公网模式下建议同时开 TOTP(PI_HUB_TOTP_SECRET=`,pi-hub totp setup` 生成);
34
+ # 配对批准与一次性码生成仍然只在主机本机可用(带代理头的请求一律 403 local_only)。
17
35
  # 每个 pi 子进程 200-300MB,按机器内存调
18
36
  Environment=PI_HUB_MAX_LIVE=5
19
37
  Environment=PI_HUB_IDLE_MS=600000