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/README.md +153 -40
- package/bin/pi-hub.mjs +129 -9
- package/docs/AUTH.md +128 -9
- package/package.json +1 -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 +4 -1
- package/src/proxy-auth.mjs +57 -0
- package/src/server.mjs +110 -39
- package/systemd/pi-hub.service +18 -0
- package/web/app.js +374 -14
- package/web/index.html +11 -1
- package/web/style.css +201 -1
- package/web/sw.js +6 -10
package/src/pairing.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
createHash,
|
|
7
7
|
createPublicKey,
|
|
8
8
|
randomBytes,
|
|
9
|
+
randomInt,
|
|
9
10
|
randomUUID,
|
|
10
11
|
timingSafeEqual,
|
|
11
12
|
verify as cryptoVerify,
|
|
@@ -16,8 +17,22 @@ import { CONFIG_DIR } from "./config.mjs";
|
|
|
16
17
|
export const PAIR_TTL_MS = 5 * 60 * 1000;
|
|
17
18
|
/** 已批准后 token 交付窗口:首次取走后 60 s 内可重取,之后 410。 */
|
|
18
19
|
export const PAIR_TOKEN_GRACE_MS = 60 * 1000;
|
|
20
|
+
/** 6 位码同时未消费的上限。 */
|
|
21
|
+
export const PAIR_MAX_ACTIVE_CODES = 8;
|
|
22
|
+
/** 同一码/同一码字串的失败尝试上限(达到即 code_locked)。 */
|
|
23
|
+
export const PAIR_CODE_FAILURE_LIMIT = 5;
|
|
24
|
+
/** 生成码与兑换的限速:每 IP 每 60 s 最多 10 次。 */
|
|
25
|
+
export const PAIR_CODE_RATE_LIMIT = 10;
|
|
26
|
+
/** 客户端自生成 token 的形状:32 字节随机 = base64url 43 字符(无填充)。 */
|
|
27
|
+
export const PAIR_TOKEN_RE = /^[A-Za-z0-9_-]{43}$/;
|
|
19
28
|
/** 配对申请限速:每 IP 每 60 s 最多 10 次。 */
|
|
20
29
|
export const PAIR_RATE_LIMIT = 10;
|
|
30
|
+
/**
|
|
31
|
+
* 待批准表上限。公网暴露时 `POST /v1/pair/request` 是**无鉴权**的,
|
|
32
|
+
* 不封顶就等于让任何人往 hub 内存和主机 `pi-hub pair` 列表里灌条目。
|
|
33
|
+
* 默认 32(一个人配几台设备远远用不到),可用 `PI_HUB_PAIR_MAX_PENDING` 调。
|
|
34
|
+
*/
|
|
35
|
+
export const PAIR_MAX_PENDING_DEFAULT = 32;
|
|
21
36
|
export const PAIR_RATE_WINDOW_MS = 60 * 1000;
|
|
22
37
|
/** 签名时间戳允许偏差:±180 s。 */
|
|
23
38
|
export const SIGNATURE_SKEW_MS = 180 * 1000;
|
|
@@ -40,11 +55,26 @@ export class PairingError extends Error {
|
|
|
40
55
|
/**
|
|
41
56
|
* 批准动作只允许来自「主机侧的人」:SSH 会话、SSH 的 tty、或主机本地终端。
|
|
42
57
|
* 手机端不跑 SSH 客户端,所以这条判定就是「人在这台机器上」。
|
|
58
|
+
*
|
|
59
|
+
* `force`(CLI `--force`)是**显式**放宽:给无 TTY 的主机侧通道(agent / 无头会话 / 裸管道)。
|
|
60
|
+
* 它只跳过「有终端」这一条,其余防线不变(本机 loopback 管理路由 + 主令牌 + 6 位码 + 5 min TTL)。
|
|
61
|
+
* 默认关;需要时逐次显式加 flag,不落任何持久配置。
|
|
43
62
|
*/
|
|
44
|
-
export function isTrustedApprovalChannel(env = process.env, stdin = process.stdin) {
|
|
63
|
+
export function isTrustedApprovalChannel(env = process.env, stdin = process.stdin, { force = false } = {}) {
|
|
64
|
+
if (force) return true;
|
|
45
65
|
return Boolean(env.SSH_CONNECTION || env.SSH_TTY || stdin?.isTTY === true);
|
|
46
66
|
}
|
|
47
67
|
|
|
68
|
+
/**
|
|
69
|
+
* 是否需要设备签名(PLAN auth-simple §1.3)。
|
|
70
|
+
* 默认 **不需要**:设备 token 只验 sha256;设 `PI_HUB_REQUIRE_SIGNATURE=1` 才回到旧口径
|
|
71
|
+
* (ts/nonce/sig 齐全 + ECDSA 验签)。
|
|
72
|
+
*/
|
|
73
|
+
export function requireSignature(env = process.env) {
|
|
74
|
+
const raw = String(env.PI_HUB_REQUIRE_SIGNATURE ?? "").trim().toLowerCase();
|
|
75
|
+
return raw === "1" || raw === "true" || raw === "yes" || raw === "on";
|
|
76
|
+
}
|
|
77
|
+
|
|
48
78
|
function sha256hex(data) {
|
|
49
79
|
return createHash("sha256").update(data).digest("hex");
|
|
50
80
|
}
|
|
@@ -70,7 +100,7 @@ function publicDevice(device) {
|
|
|
70
100
|
export { publicDevice };
|
|
71
101
|
|
|
72
102
|
export class PairingStore {
|
|
73
|
-
constructor({ configDir = CONFIG_DIR, now = () => Date.now(), log = () => {} } = {}) {
|
|
103
|
+
constructor({ configDir = CONFIG_DIR, now = () => Date.now(), log = () => {}, maxPending = null } = {}) {
|
|
74
104
|
this.configDir = configDir;
|
|
75
105
|
this.devicesFile = path.join(configDir, "devices.json");
|
|
76
106
|
this.now = now;
|
|
@@ -81,8 +111,29 @@ export class PairingStore {
|
|
|
81
111
|
this.rate = new Map();
|
|
82
112
|
/** `${deviceId}:${nonce}` → 首次出现时间 */
|
|
83
113
|
this.nonces = new Map();
|
|
114
|
+
/** 6 位码表:code → {code, createdAt, expiresAt, usedAt, failures, deviceId}(只在内存) */
|
|
115
|
+
this.codes = new Map();
|
|
116
|
+
/** 生成码 / 兑换各自的每 IP 限速桶 */
|
|
117
|
+
this.codeRate = new Map();
|
|
118
|
+
this.redeemRate = new Map();
|
|
119
|
+
/** 不存在的码字串的失败计数(防 6 位码暴力枚举):code → {count, at} */
|
|
120
|
+
this.codeFailures = new Map();
|
|
84
121
|
/** devices.json 按 mtime 重载,外部 revoke/手改也生效 */
|
|
85
122
|
this.cache = { mtimeMs: -1, size: -1, devices: [] };
|
|
123
|
+
const fromEnv = Number(process.env.PI_HUB_PAIR_MAX_PENDING ?? "");
|
|
124
|
+
this.maxPending =
|
|
125
|
+
Number.isFinite(maxPending) && maxPending !== null
|
|
126
|
+
? maxPending
|
|
127
|
+
: Number.isInteger(fromEnv) && fromEnv > 0
|
|
128
|
+
? fromEnv
|
|
129
|
+
: PAIR_MAX_PENDING_DEFAULT;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** 当前仍在等批准的条目数(已批准/已拒绝/过期的不算)。 */
|
|
133
|
+
pendingCount() {
|
|
134
|
+
let n = 0;
|
|
135
|
+
for (const p of this.pending.values()) if (p.status === "pending" && this.now() <= p.expiresAt) n += 1;
|
|
136
|
+
return n;
|
|
86
137
|
}
|
|
87
138
|
|
|
88
139
|
// ---------- 限速 / 清理 ----------
|
|
@@ -145,6 +196,13 @@ export class PairingStore {
|
|
|
145
196
|
}
|
|
146
197
|
|
|
147
198
|
this.sweep();
|
|
199
|
+
if (this.pendingCount() >= this.maxPending) {
|
|
200
|
+
throw new PairingError(
|
|
201
|
+
429,
|
|
202
|
+
"pair_queue_full",
|
|
203
|
+
`too many pending pairing requests (max ${this.maxPending}); approve or deny them first`,
|
|
204
|
+
);
|
|
205
|
+
}
|
|
148
206
|
const now = this.now();
|
|
149
207
|
const pairId = randomUUID();
|
|
150
208
|
let code = null;
|
|
@@ -334,6 +392,33 @@ export class PairingStore {
|
|
|
334
392
|
this.saveDevices(devices);
|
|
335
393
|
}
|
|
336
394
|
|
|
395
|
+
// ---------- 设备令牌(默认口径,不要求签名) ----------
|
|
396
|
+
|
|
397
|
+
/** 按 sha256(token) 恒时比较找设备;找不到返回 null,吊销状态由调用方判定。 */
|
|
398
|
+
findDeviceByToken(token) {
|
|
399
|
+
if (typeof token !== "string" || !token) return null;
|
|
400
|
+
const givenHash = Buffer.from(sha256hex(token), "utf8");
|
|
401
|
+
let device = null;
|
|
402
|
+
for (const candidate of this.loadDevices()) {
|
|
403
|
+
const stored = Buffer.from(String(candidate.tokenSha256 ?? ""), "utf8");
|
|
404
|
+
if (stored.length === givenHash.length && timingSafeEqual(stored, givenHash)) device = candidate;
|
|
405
|
+
}
|
|
406
|
+
return device;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* 只验设备 token(sha256 + 未吊销),不看任何 `x-pi-*` 头。
|
|
411
|
+
* @returns {{ok:true, device:object} | {ok:false, code:string, message:string}}
|
|
412
|
+
*/
|
|
413
|
+
verifyDeviceToken(token) {
|
|
414
|
+
const device = this.findDeviceByToken(token);
|
|
415
|
+
if (!device) return { ok: false, code: "unauthorized", message: "unknown device token" };
|
|
416
|
+
if (device.revoked === true) {
|
|
417
|
+
return { ok: false, code: "device_revoked", message: `device ${device.name ?? device.id} is revoked` };
|
|
418
|
+
}
|
|
419
|
+
return { ok: true, device };
|
|
420
|
+
}
|
|
421
|
+
|
|
337
422
|
// ---------- 设备签名 ----------
|
|
338
423
|
|
|
339
424
|
/**
|
|
@@ -400,4 +485,169 @@ export class PairingStore {
|
|
|
400
485
|
if (!verified) return fail("bad_signature", "signature does not verify");
|
|
401
486
|
return { ok: true, device };
|
|
402
487
|
}
|
|
488
|
+
|
|
489
|
+
// ---------- 6 位配对码(C1:简化后的默认链路) ----------
|
|
490
|
+
// 与上面的 ECDSA 签名请求协议(legacy)并存:code 链路拿到 token 后只带 Bearer 即可。
|
|
491
|
+
|
|
492
|
+
/** 生成码的每 IP 限速(10 次/分)。返回 true 表示本次被限。 */
|
|
493
|
+
codeRateLimited(ip) {
|
|
494
|
+
return this.#windowLimited(this.codeRate, ip);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/** 兑换的每 IP 限速(10 次/分)。返回 true 表示本次被限。 */
|
|
498
|
+
redeemRateLimited(ip) {
|
|
499
|
+
return this.#windowLimited(this.redeemRate, ip);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
#windowLimited(map, ip) {
|
|
503
|
+
const now = this.now();
|
|
504
|
+
const key = ip || "unknown";
|
|
505
|
+
const hits = (map.get(key) ?? []).filter((t) => now - t < PAIR_RATE_WINDOW_MS);
|
|
506
|
+
if (hits.length >= PAIR_CODE_RATE_LIMIT) {
|
|
507
|
+
map.set(key, hits);
|
|
508
|
+
return true;
|
|
509
|
+
}
|
|
510
|
+
hits.push(now);
|
|
511
|
+
map.set(key, hits);
|
|
512
|
+
return false;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** 清掉过期很久的码与失败计数(保留 TTL+10 min,让过期/已用还能回 410/409)。 */
|
|
516
|
+
pruneCodes() {
|
|
517
|
+
const now = this.now();
|
|
518
|
+
for (const [code, record] of this.codes) {
|
|
519
|
+
if (now - record.expiresAt > PENDING_GC_MS) this.codes.delete(code);
|
|
520
|
+
}
|
|
521
|
+
for (const [code, record] of this.codeFailures) {
|
|
522
|
+
if (now - record.at > NONCE_TTL_MS) this.codeFailures.delete(code);
|
|
523
|
+
}
|
|
524
|
+
// 上限兜底:公网/多 IP 刷不出来无限增长的 Map。
|
|
525
|
+
while (this.codeFailures.size > 2048) {
|
|
526
|
+
const first = this.codeFailures.keys().next().value;
|
|
527
|
+
this.codeFailures.delete(first);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
activeCodeCount() {
|
|
532
|
+
const now = this.now();
|
|
533
|
+
let active = 0;
|
|
534
|
+
for (const record of this.codes.values()) {
|
|
535
|
+
if (record.usedAt === null && now <= record.expiresAt) active += 1;
|
|
536
|
+
}
|
|
537
|
+
return active;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/** 生成 6 位码(字符串,允许前导 0)。返回值只含码与 ISO 过期时间。 */
|
|
541
|
+
createCode() {
|
|
542
|
+
this.pruneCodes();
|
|
543
|
+
const now = this.now();
|
|
544
|
+
if (this.activeCodeCount() >= PAIR_MAX_ACTIVE_CODES) {
|
|
545
|
+
throw new PairingError(
|
|
546
|
+
429,
|
|
547
|
+
"too_many_codes",
|
|
548
|
+
`too many unconsumed pairing codes (max ${PAIR_MAX_ACTIVE_CODES})`,
|
|
549
|
+
);
|
|
550
|
+
}
|
|
551
|
+
let code = null;
|
|
552
|
+
for (let i = 0; i < 50 && !code; i += 1) {
|
|
553
|
+
const candidate = String(randomInt(0, 1_000_000)).padStart(6, "0");
|
|
554
|
+
if (!this.codes.has(candidate)) code = candidate;
|
|
555
|
+
}
|
|
556
|
+
if (!code) throw new PairingError(503, "code_exhausted", "cannot allocate a pairing code");
|
|
557
|
+
const record = {
|
|
558
|
+
code,
|
|
559
|
+
createdAt: now,
|
|
560
|
+
expiresAt: now + PAIR_TTL_MS,
|
|
561
|
+
usedAt: null,
|
|
562
|
+
failures: 0,
|
|
563
|
+
deviceId: null,
|
|
564
|
+
};
|
|
565
|
+
this.codes.set(code, record);
|
|
566
|
+
return { code, expiresAt: new Date(record.expiresAt).toISOString() };
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/** 不存在的码字串的失败计数(加一后返回当前值)。 */
|
|
570
|
+
noteCodeFailure(code) {
|
|
571
|
+
const now = this.now();
|
|
572
|
+
const record = this.codeFailures.get(code) ?? { count: 0, at: now };
|
|
573
|
+
record.count += 1;
|
|
574
|
+
record.at = now;
|
|
575
|
+
this.codeFailures.set(code, record);
|
|
576
|
+
return record.count;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* 手机兑换:客户端自己生成 32 B token,服务端只存 `tokenSha256`,响应不回显 token。
|
|
581
|
+
* 校验顺序逐字按 PLAN §1.2;成功即单次消费(重放同一码 → 409 code_used)。
|
|
582
|
+
* 失败尝试计到该码上(存在则 record.failures,不存在按码字串计数),≥5 → 429 code_locked。
|
|
583
|
+
* @returns {{ok:true, deviceId:string, deviceName:string}}
|
|
584
|
+
*/
|
|
585
|
+
claimCode({ code, name, platform, token } = {}) {
|
|
586
|
+
this.pruneCodes();
|
|
587
|
+
const now = this.now();
|
|
588
|
+
const needle = typeof code === "string" ? code.trim() : "";
|
|
589
|
+
const wellFormed = /^\d{6}$/.test(needle);
|
|
590
|
+
const record = wellFormed ? (this.codes.get(needle) ?? null) : null;
|
|
591
|
+
|
|
592
|
+
// 400 级校验失败也计入该码的失败次数(防对单个已知码刷字段)。
|
|
593
|
+
const reject = (status, errorCode, message) => {
|
|
594
|
+
if (record) record.failures += 1;
|
|
595
|
+
else if (wellFormed) this.noteCodeFailure(needle);
|
|
596
|
+
throw new PairingError(status, errorCode, message);
|
|
597
|
+
};
|
|
598
|
+
|
|
599
|
+
const deviceName = typeof name === "string" ? name.trim() : "";
|
|
600
|
+
const devicePlatform = typeof platform === "string" ? platform.trim() : "";
|
|
601
|
+
const deviceToken = typeof token === "string" ? token : "";
|
|
602
|
+
|
|
603
|
+
// 1. name / platform
|
|
604
|
+
if (!deviceName || deviceName.length > 64) {
|
|
605
|
+
reject(400, "invalid_name", "name must be a non-empty string (≤64 chars)");
|
|
606
|
+
}
|
|
607
|
+
if (!devicePlatform || devicePlatform.length > 64) {
|
|
608
|
+
reject(400, "invalid_platform", "platform must be a non-empty string (≤64 chars)");
|
|
609
|
+
}
|
|
610
|
+
// 2. token:必须由客户端生成 32 B(base64url 43 字符)
|
|
611
|
+
if (!PAIR_TOKEN_RE.test(deviceToken)) {
|
|
612
|
+
reject(400, "invalid_token", "token must be 32 random bytes as base64url (43 chars)");
|
|
613
|
+
}
|
|
614
|
+
// 3. code 形状
|
|
615
|
+
if (!wellFormed) throw new PairingError(400, "invalid_code", "code must be 6 digits");
|
|
616
|
+
|
|
617
|
+
// 4. 码状态
|
|
618
|
+
if (!record) {
|
|
619
|
+
const failures = this.noteCodeFailure(needle);
|
|
620
|
+
if (failures >= PAIR_CODE_FAILURE_LIMIT) {
|
|
621
|
+
throw new PairingError(429, "code_locked", "too many failed attempts for this code");
|
|
622
|
+
}
|
|
623
|
+
throw new PairingError(401, "invalid_code", "unknown pairing code");
|
|
624
|
+
}
|
|
625
|
+
if (record.usedAt !== null) throw new PairingError(409, "code_used", "pairing code was already used");
|
|
626
|
+
if (now > record.expiresAt) throw new PairingError(410, "code_expired", "pairing code expired");
|
|
627
|
+
|
|
628
|
+
// 5. 失败次数锁定
|
|
629
|
+
if (record.failures >= PAIR_CODE_FAILURE_LIMIT) {
|
|
630
|
+
throw new PairingError(429, "code_locked", "pairing code is locked after too many failed attempts");
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// 6. 成功:写设备(只存 tokenSha256;publicKeyPem 只有 legacy 签名协议才写),码立刻作废
|
|
634
|
+
const device = {
|
|
635
|
+
id: randomUUID(),
|
|
636
|
+
name: deviceName,
|
|
637
|
+
platform: devicePlatform,
|
|
638
|
+
tokenSha256: sha256hex(deviceToken),
|
|
639
|
+
source: "code",
|
|
640
|
+
createdAt: new Date(now).toISOString(),
|
|
641
|
+
lastSeenAt: null,
|
|
642
|
+
revoked: false,
|
|
643
|
+
};
|
|
644
|
+
const devices = this.loadDevices();
|
|
645
|
+
devices.push(device);
|
|
646
|
+
this.saveDevices(devices);
|
|
647
|
+
|
|
648
|
+
record.usedAt = now;
|
|
649
|
+
record.deviceId = device.id;
|
|
650
|
+
this.codeFailures.delete(needle);
|
|
651
|
+
return { ok: true, deviceId: device.id, deviceName: device.name };
|
|
652
|
+
}
|
|
403
653
|
}
|
package/src/pi-args.mjs
CHANGED
|
@@ -3,19 +3,40 @@ import path from "node:path";
|
|
|
3
3
|
import { HOME, PI_BIN } from "./config.mjs";
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
|
-
* hub 启动 pi
|
|
6
|
+
* hub 启动 pi 时的扩展加载口径(PLAN auth-simple §3 / C3)。
|
|
7
7
|
*
|
|
8
|
-
* `--no-extensions
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* "Model not found"(实测)。
|
|
8
|
+
* 默认 **不再** 传 `--no-extensions`:pi 按自己的规则发现 `~/.pi/agent/extensions/*`、
|
|
9
|
+
* settings 里 `pi install` 的包、npm/local-packages。手机上触发的会话因此能用桌面扩展
|
|
10
|
+
* 注册的 slash 命令/工具。
|
|
12
11
|
*
|
|
13
|
-
*
|
|
12
|
+
* 三种模式(`extensionsMode()`):
|
|
13
|
+
* - `all`(默认):不加 `--no-extensions`;`extensionPaths()` 命中的显式 `-e` 仍作为补充列表
|
|
14
|
+
* (`better-custom-provider` 注册本机自定义 provider,缺了 `--model custom.*` 会报 Model not found)。
|
|
15
|
+
* - `explicit`(`PI_HUB_EXTENSIONS=/path/a.ts:/path/b.ts`):`--no-extensions` + 每个路径一个 `-e`(旧白名单语义)。
|
|
16
|
+
* - `none`(`PI_HUB_EXTENSIONS=off` / `none` / 空串):只传 `--no-extensions`,不加载任何扩展(旧行为一行回退)。
|
|
14
17
|
*/
|
|
15
|
-
export
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
18
|
+
export const OFF_VALUES = Object.freeze(["off", "none"]);
|
|
19
|
+
|
|
20
|
+
/** 当前生效的扩展模式:`all` | `explicit` | `none`。 */
|
|
21
|
+
export function extensionsMode(env = process.env) {
|
|
22
|
+
const raw = env.PI_HUB_EXTENSIONS;
|
|
23
|
+
if (raw === undefined) return "all";
|
|
24
|
+
const text = String(raw).trim().toLowerCase();
|
|
25
|
+
if (text === "" || OFF_VALUES.includes(text)) return "none";
|
|
26
|
+
return "explicit";
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* hub 启动 pi 时要显式加载的扩展路径。
|
|
31
|
+
*
|
|
32
|
+
* 显式配置(`PI_HUB_EXTENSIONS=a.ts:b.ts`)逐字使用;`off`/`none`/空串返回空;
|
|
33
|
+
* 默认探测 `better-custom-provider`(自定义 provider 必需)。
|
|
34
|
+
*/
|
|
35
|
+
export function extensionPaths(env = process.env) {
|
|
36
|
+
const mode = extensionsMode(env);
|
|
37
|
+
if (mode === "none") return [];
|
|
38
|
+
if (mode === "explicit") {
|
|
39
|
+
return String(env.PI_HUB_EXTENSIONS ?? "")
|
|
19
40
|
.split(":")
|
|
20
41
|
.map((s) => s.trim())
|
|
21
42
|
.filter(Boolean);
|
|
@@ -37,7 +58,9 @@ export function extensionPaths() {
|
|
|
37
58
|
* @returns {string[]}
|
|
38
59
|
*/
|
|
39
60
|
export function piArgs(opts = {}) {
|
|
40
|
-
const
|
|
61
|
+
const mode = extensionsMode();
|
|
62
|
+
const args = ["--mode", "rpc"];
|
|
63
|
+
if (mode !== "all") args.push("--no-extensions");
|
|
41
64
|
for (const ext of extensionPaths()) args.push("-e", ext);
|
|
42
65
|
if (opts.noSession) args.push("--no-session");
|
|
43
66
|
// 不给 --session-dir:默认目录会按 cwd 分到 --<path>-- 子目录,与桌面 TUI 共用同一批会话。
|
|
@@ -48,4 +71,4 @@ export function piArgs(opts = {}) {
|
|
|
48
71
|
return args;
|
|
49
72
|
}
|
|
50
73
|
|
|
51
|
-
export { PI_BIN };
|
|
74
|
+
export { PI_BIN };
|
package/src/pi-session.mjs
CHANGED
|
@@ -89,7 +89,10 @@ export class LiveSession {
|
|
|
89
89
|
this.log("spawn", PI_BIN, args.join(" "), "cwd=", this.cwd);
|
|
90
90
|
this.child = spawn(PI_BIN, args, {
|
|
91
91
|
cwd: this.cwd,
|
|
92
|
-
|
|
92
|
+
// hub 自己就是进程外的锁管理者(#claimLock):子进程若也加载 host 的 session-lock 扩展,
|
|
93
|
+
// 它会在 session_start 先认领会话锁,hub 再认领就得到 conflict(默认加载全部扩展后实测)。
|
|
94
|
+
// PI_SESSION_LOCK=off 只关掉**子进程内**的扩展认领,hub 侧的 claim/peek 不受影响。
|
|
95
|
+
env: { ...process.env, PI_HUB: "1", PI_SESSION_LOCK: "off" },
|
|
93
96
|
stdio: ["pipe", "pipe", "pipe"],
|
|
94
97
|
});
|
|
95
98
|
|
package/src/proxy-auth.mjs
CHANGED
|
@@ -23,9 +23,66 @@ export function parseTrustProxyEnv(env = process.env) {
|
|
|
23
23
|
secret: String(env.PI_HUB_PROXY_SECRET ?? ""),
|
|
24
24
|
allowCidrs: splitList(env.PI_HUB_PROXY_CIDRS),
|
|
25
25
|
userHeader: header || DEFAULT_PROXY_USER_HEADER,
|
|
26
|
+
// 公网反代后面采信 `x-forwarded-for` 首跳做限速/审计用客户端 IP(默认关)。
|
|
27
|
+
trustForwardedFor: String(env.PI_HUB_TRUST_FORWARDED_FOR ?? "") === "1",
|
|
26
28
|
};
|
|
27
29
|
}
|
|
28
30
|
|
|
31
|
+
/** 任何“我是代理”的迹象。用来把「本机 CLI」与「本地反代转进来的公网请求」区分开。 */
|
|
32
|
+
export const FORWARDED_HEADERS = Object.freeze([
|
|
33
|
+
"x-forwarded-for",
|
|
34
|
+
"x-forwarded-proto",
|
|
35
|
+
"x-forwarded-host",
|
|
36
|
+
"x-real-ip",
|
|
37
|
+
"forwarded",
|
|
38
|
+
]);
|
|
39
|
+
|
|
40
|
+
export function hasForwardedHeaders(headers) {
|
|
41
|
+
for (const name of FORWARDED_HEADERS) {
|
|
42
|
+
const value = headerValue(headers, name);
|
|
43
|
+
if (value) return true;
|
|
44
|
+
}
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 限速/审计用的客户端 IP。
|
|
50
|
+
*
|
|
51
|
+
* 默认只看 socket 对端。公网模式的典型拓扑是「cloudflared / caddy 跑在本机、hub 只听回环」,
|
|
52
|
+
* 这时对端恒为 127.0.0.1 —— 若拿它当限速键,全世界共用一个桶:一个人刷就能把别人锁在外面。
|
|
53
|
+
* 所以 `PI_HUB_TRUST_FORWARDED_FOR=1` 时,**仅当对端在 `PI_HUB_PROXY_CIDRS` 内**才采信
|
|
54
|
+
* `x-forwarded-for`;对端不可信 / 值非法 一律回退到对端地址。
|
|
55
|
+
*
|
|
56
|
+
* 取**最右一跳**而不是最左:Caddy/nginx 默认是把客户端地址**追加**到已有 XFF 右边,
|
|
57
|
+
* 左边那截是客户端自己送的、可伪造(实测 Tailscale Serve/Funnel 会整个覆盖 XFF,
|
|
58
|
+
* 此时最右一跳同样是真实客户端)。多级反代链要按跳数自行收窄,别指望这里猜。
|
|
59
|
+
*/
|
|
60
|
+
export function resolveClientIp(req, cfg = {}) {
|
|
61
|
+
const peer = normalizeIp(String(req?.socket?.remoteAddress ?? "unknown"));
|
|
62
|
+
const config = cfg ?? parseTrustProxyEnv();
|
|
63
|
+
if (!config.trustForwardedFor) return peer;
|
|
64
|
+
const allowed = config.allowCidrs?.length ? ipInCidrs(peer, config.allowCidrs) : isLoopback(peer);
|
|
65
|
+
if (!allowed) return peer;
|
|
66
|
+
const raw = headerValue(req?.headers, "x-forwarded-for");
|
|
67
|
+
if (!raw) return peer;
|
|
68
|
+
const hops = raw.split(",").map((h) => normalizeIp(h)).filter(Boolean);
|
|
69
|
+
if (!hops.length) return peer;
|
|
70
|
+
// 最右一跳 = 紧邻我们的代理追加的那个地址(左边可能被客户端伪造)。
|
|
71
|
+
const nearest = hops[hops.length - 1];
|
|
72
|
+
return parseIp(nearest) ? nearest : peer;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 是否为“本机直连”(给 `/v1/pair/*`、`/v1/web/otp` 这类管理路由用)。
|
|
77
|
+
*
|
|
78
|
+
* 只判回环地址不够:cloudflared / caddy 跑在本机时也从 127.0.0.1 进来,
|
|
79
|
+
* 那样公网请求就能冒充“本机 CLI”。所以再要求**不带任何代理头**。
|
|
80
|
+
*/
|
|
81
|
+
export function isLocalRequest(req) {
|
|
82
|
+
const peer = normalizeIp(String(req?.socket?.remoteAddress ?? ""));
|
|
83
|
+
return isLoopback(peer) && !hasForwardedHeaders(req?.headers);
|
|
84
|
+
}
|
|
85
|
+
|
|
29
86
|
/** 请求来源地址;去掉 IPv4-mapped 前缀,行为与 server.mjs 的 clientIp 一致。 */
|
|
30
87
|
export function clientIp(req) {
|
|
31
88
|
return normalizeIp(String(req?.socket?.remoteAddress ?? "unknown"));
|