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.
@@ -0,0 +1,181 @@
1
+ // 反向代理可信身份头(Tailscale Serve / Cloudflare Access / nginx)。
2
+ // 设计口径见 .pi/plans/auth-multi/PLAN.md M6 与威胁模型「代理头伪造」:
3
+ // 只有 PI_HUB_TRUST_PROXY=1 + 共享 secret 命中 + 来源在可信网段里,才认身份头。只用 node 内置模块。
4
+ import { createHash, timingSafeEqual } from "node:crypto";
5
+
6
+ /** 默认身份头名(Node 的 req.headers 恒为小写)。 */
7
+ export const DEFAULT_PROXY_USER_HEADER = "x-pi-proxy-user";
8
+ /** 共享 secret 头名。 */
9
+ export const PROXY_SECRET_HEADER = "x-pi-proxy-secret";
10
+
11
+ function splitList(value) {
12
+ return String(value ?? "")
13
+ .split(",")
14
+ .map((item) => item.trim())
15
+ .filter(Boolean);
16
+ }
17
+
18
+ /** 读取 env 配置;`PI_HUB_PROXY_CIDRS` 逗号分隔,裸 IP 视为 /32 或 /128。 */
19
+ export function parseTrustProxyEnv(env = process.env) {
20
+ const header = String(env.PI_HUB_PROXY_USER_HEADER ?? "").trim().toLowerCase();
21
+ return {
22
+ enabled: String(env.PI_HUB_TRUST_PROXY ?? "") === "1",
23
+ secret: String(env.PI_HUB_PROXY_SECRET ?? ""),
24
+ allowCidrs: splitList(env.PI_HUB_PROXY_CIDRS),
25
+ userHeader: header || DEFAULT_PROXY_USER_HEADER,
26
+ };
27
+ }
28
+
29
+ /** 请求来源地址;去掉 IPv4-mapped 前缀,行为与 server.mjs 的 clientIp 一致。 */
30
+ export function clientIp(req) {
31
+ return normalizeIp(String(req?.socket?.remoteAddress ?? "unknown"));
32
+ }
33
+
34
+ function normalizeIp(raw) {
35
+ let ip = String(raw ?? "").trim().toLowerCase();
36
+ if (ip.startsWith("[") && ip.endsWith("]")) ip = ip.slice(1, -1);
37
+ const zone = ip.indexOf("%");
38
+ if (zone >= 0) ip = ip.slice(0, zone);
39
+ const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/.exec(ip);
40
+ if (mapped) return mapped[1];
41
+ return ip;
42
+ }
43
+
44
+ function parseIpv4(text) {
45
+ const parts = text.split(".");
46
+ if (parts.length !== 4) return null;
47
+ let value = 0n;
48
+ for (const part of parts) {
49
+ if (!/^\d{1,3}$/.test(part)) return null;
50
+ const octet = Number(part);
51
+ if (octet > 255) return null;
52
+ value = (value << 8n) | BigInt(octet);
53
+ }
54
+ return { version: 4, value };
55
+ }
56
+
57
+ function parseIpv6(text) {
58
+ if (!/^[0-9a-f:.]+$/.test(text)) return null;
59
+ // 末尾内嵌 IPv4(::ffff:1.2.3.4 会被 normalizeIp 归一化,这里兜住其它写法)。
60
+ let body = text;
61
+ if (body.includes(".")) {
62
+ const lastColon = body.lastIndexOf(":");
63
+ if (lastColon < 0) return null;
64
+ const embedded = parseIpv4(body.slice(lastColon + 1));
65
+ if (!embedded) return null;
66
+ const high = ((embedded.value >> 16n) & 0xffffn).toString(16);
67
+ const low = (embedded.value & 0xffffn).toString(16);
68
+ body = `${body.slice(0, lastColon + 1)}${high}:${low}`;
69
+ }
70
+ const halves = body.split("::");
71
+ if (halves.length > 2) return null;
72
+ const groupsOf = (part) => {
73
+ if (part === "") return [];
74
+ const groups = [];
75
+ for (const group of part.split(":")) {
76
+ if (!/^[0-9a-f]{1,4}$/.test(group)) return null;
77
+ groups.push(parseInt(group, 16));
78
+ }
79
+ return groups;
80
+ };
81
+ const front = groupsOf(halves[0]);
82
+ const back = halves.length === 2 ? groupsOf(halves[1]) : [];
83
+ if (!front || !back) return null;
84
+ let groups;
85
+ if (halves.length === 2) {
86
+ const missing = 8 - front.length - back.length;
87
+ if (missing < 1) return null; // "::" 至少要压缩一组
88
+ groups = [...front, ...Array(missing).fill(0), ...back];
89
+ } else {
90
+ groups = front;
91
+ if (groups.length !== 8) return null;
92
+ }
93
+ let value = 0n;
94
+ for (const group of groups) value = (value << 16n) | BigInt(group);
95
+ return { version: 6, value };
96
+ }
97
+
98
+ /** 解析 IPv4/IPv6 字面量为 BigInt;无法解析返回 null。 */
99
+ function parseIp(raw) {
100
+ const ip = normalizeIp(raw);
101
+ if (ip.includes(":")) return parseIpv6(ip);
102
+ return parseIpv4(ip);
103
+ }
104
+
105
+ /** 本机回环:127.0.0.0/8、::1(含 IPv4-mapped 形式)。 */
106
+ export function isLoopback(ip) {
107
+ const normalized = normalizeIp(ip);
108
+ if (normalized === "::1" || normalized === "localhost") return true;
109
+ const parsed = parseIpv4(normalized);
110
+ if (!parsed) return false;
111
+ return (parsed.value >> 24n) === 127n;
112
+ }
113
+
114
+ function parseCidr(entry) {
115
+ const text = String(entry ?? "").trim();
116
+ if (!text) return null;
117
+ const slash = text.lastIndexOf("/");
118
+ const address = slash >= 0 ? text.slice(0, slash) : text;
119
+ const parsed = parseIp(address);
120
+ if (!parsed) return null;
121
+ const bits = parsed.version === 4 ? 32 : 128;
122
+ let prefix = bits;
123
+ if (slash >= 0) {
124
+ const raw = text.slice(slash + 1);
125
+ if (!/^\d{1,3}$/.test(raw)) return null;
126
+ prefix = Number(raw);
127
+ if (prefix > bits) return null;
128
+ }
129
+ return { version: parsed.version, bits, prefix, network: parsed.value };
130
+ }
131
+
132
+ /** 地址是否落在任一 CIDR 里;非法 CIDR 条目忽略(不会放宽信任)。 */
133
+ export function ipInCidrs(ip, cidrs) {
134
+ const parsed = parseIp(ip);
135
+ if (!parsed) return false;
136
+ for (const entry of cidrs ?? []) {
137
+ const cidr = parseCidr(entry);
138
+ if (!cidr || cidr.version !== parsed.version) continue;
139
+ const shift = BigInt(cidr.bits - cidr.prefix);
140
+ if (parsed.value >> shift === cidr.network >> shift) return true;
141
+ }
142
+ return false;
143
+ }
144
+
145
+ /** 恒时比较;长度不等时先各自 sha256,避免长度差异成为计时侧信道。 */
146
+ function secretMatches(given, expected) {
147
+ const left = Buffer.from(String(given ?? ""));
148
+ const right = Buffer.from(String(expected ?? ""));
149
+ if (left.length === right.length) return timingSafeEqual(left, right);
150
+ const leftHash = createHash("sha256").update(left).digest();
151
+ const rightHash = createHash("sha256").update(right).digest();
152
+ timingSafeEqual(leftHash, rightHash);
153
+ return false;
154
+ }
155
+
156
+ function headerValue(headers, name) {
157
+ const raw = headers?.[name] ?? headers?.[name.toLowerCase()];
158
+ const value = Array.isArray(raw) ? raw[0] : raw;
159
+ return typeof value === "string" ? value : "";
160
+ }
161
+
162
+ /**
163
+ * 判定代理身份。任何一项不满足都拒绝,`reason` 是稳定的机器码:
164
+ * `disabled` / `ip_not_allowed` / `secret_mismatch` / `identity_missing` / `identity_invalid`。
165
+ */
166
+ export function resolveProxyIdentity(headers, remoteIp, cfg) {
167
+ const config = cfg ?? parseTrustProxyEnv();
168
+ if (!config.enabled) return { ok: false, reason: "disabled" };
169
+ const ip = normalizeIp(remoteIp);
170
+ const allowed = config.allowCidrs?.length ? ipInCidrs(ip, config.allowCidrs) : isLoopback(ip);
171
+ if (!allowed) return { ok: false, reason: "ip_not_allowed" };
172
+ if (!config.secret) return { ok: false, reason: "secret_mismatch" };
173
+ if (!secretMatches(headerValue(headers, PROXY_SECRET_HEADER), config.secret)) {
174
+ return { ok: false, reason: "secret_mismatch" };
175
+ }
176
+ const user = headerValue(headers, config.userHeader ?? DEFAULT_PROXY_USER_HEADER).trim();
177
+ if (!user) return { ok: false, reason: "identity_missing" };
178
+ // 身份头会进日志/会话归属,拒绝控制字符与超长值。
179
+ if (user.length > 256 || /[\u0000-\u001f\u007f]/.test(user)) return { ok: false, reason: "identity_invalid" };
180
+ return { ok: true, user };
181
+ }
@@ -0,0 +1,145 @@
1
+ import { MAX_LIVE, EVICT_IDLE_MS } from "./config.mjs";
2
+ import { LiveSession } from "./pi-session.mjs";
3
+
4
+ export class HttpError extends Error {
5
+ constructor(status, message, code = undefined) {
6
+ super(message);
7
+ this.status = status;
8
+ this.code = code;
9
+ }
10
+ }
11
+
12
+ export class Registry {
13
+ /** @param {{log?:(...a:any[])=>void, createSession?:(opts:any)=>any}} [deps] */
14
+ constructor({ log = () => {}, createSession = (opts) => new LiveSession(opts) } = {}) {
15
+ this.log = log;
16
+ this.createSession = createSession;
17
+ /** @type {Map<string, LiveSession>} */
18
+ this.live = new Map();
19
+ }
20
+
21
+ /**
22
+ * 空闲即可淘汰:不在跑、不在压缩、且已 settled。
23
+ * 注意真实 `LiveSession` 把这三项放在 `this.state` 里(`pi-session.mjs:42`),
24
+ * 没有同名实例属性;这里必须走 `state ?? session`,否则生产路径 evict 恒为空操作。
25
+ */
26
+ #isEvictableIdle(session) {
27
+ const st = session.state ?? session;
28
+ return st.status === "idle" && !st.isStreaming && !st.isCompacting;
29
+ }
30
+
31
+ /**
32
+ * 唯一一份阈值逻辑:按 lastActivity 升序返回超过 thresholdMs 未活动的会话。
33
+ * onlyIdle=true 时只算空闲会话(evictIdle);false 时全部超时项(reap)。
34
+ */
35
+ #expired(thresholdMs, now = Date.now(), { onlyIdle = false } = {}) {
36
+ const out = [];
37
+ for (const [id, session] of this.live) {
38
+ if (now - session.lastActivity < thresholdMs) continue;
39
+ if (onlyIdle && !this.#isEvictableIdle(session)) continue;
40
+ out.push({ id, session });
41
+ }
42
+ out.sort((a, b) => a.session.lastActivity - b.session.lastActivity);
43
+ return out;
44
+ }
45
+
46
+ /**
47
+ * 撞 MAX_LIVE 时的腾位:淘汰最久空闲的一个会话。
48
+ * @param {number} thresholdMs 空闲多久才算可淘汰
49
+ * @param {{dryRun?:boolean}} [opts] dryRun 只返回会淘汰的 id,不停不删
50
+ * @returns {string|null} 被淘汰(或将被淘汰)的 id;无可淘汰项返回 null
51
+ */
52
+ evictIdle(thresholdMs, { dryRun = false } = {}) {
53
+ const [candidate] = this.#expired(thresholdMs, Date.now(), { onlyIdle: true });
54
+ if (!candidate) return null;
55
+ if (dryRun) return candidate.id;
56
+ const idleSec = Math.round((Date.now() - candidate.session.lastActivity) / 1000);
57
+ this.log("evict", candidate.id, `idle ${idleSec}s`);
58
+ try {
59
+ candidate.session.stop("evicted");
60
+ } catch (err) {
61
+ this.log("evict error", candidate.id, err.message);
62
+ }
63
+ this.live.delete(candidate.id);
64
+ return candidate.id;
65
+ }
66
+
67
+ get(id) {
68
+ const s = this.live.get(id);
69
+ return s && !s.closed ? s : null;
70
+ }
71
+
72
+ list() {
73
+ return [...this.live.values()].map((s) => s.snapshot());
74
+ }
75
+
76
+ /**
77
+ * 打开(或复用)一个会话子进程。「一写」由 registry + lock 文件共同保证。
78
+ * @param {{id:string, cwd:string, name?:string|null, model?:string|null}} opts
79
+ */
80
+ async open(opts) {
81
+ const existing = this.get(opts.id);
82
+ if (existing) return existing;
83
+ if (this.live.size >= MAX_LIVE) {
84
+ const evicted = this.evictIdle(EVICT_IDLE_MS);
85
+ if (evicted) this.log("open", opts.id, `evicted ${evicted}`);
86
+ }
87
+ if (this.live.size >= MAX_LIVE) {
88
+ const evictable = this.#expired(EVICT_IDLE_MS, Date.now(), { onlyIdle: true }).length;
89
+ const idle = [...this.live.values()].filter((s) => this.#isEvictableIdle(s)).length;
90
+ throw new HttpError(
91
+ 429,
92
+ `too many live sessions (max ${MAX_LIVE}); evictable ${evictable}, idle ${idle} (eviction needs ${EVICT_IDLE_MS}ms idle); close a session or wait for idle eviction`,
93
+ "too_many_live",
94
+ );
95
+ }
96
+ const session = this.createSession({ ...opts, log: this.log });
97
+ session.onClose = () => {
98
+ if (this.live.get(session.id) === session) this.live.delete(session.id);
99
+ };
100
+ this.live.set(opts.id, session);
101
+ try {
102
+ await session.start();
103
+ } catch (err) {
104
+ this.live.delete(opts.id);
105
+ throw err;
106
+ }
107
+ return session;
108
+ }
109
+
110
+ /** fork 后把同一个子进程从旧 id 改挂到新 id。 */
111
+ rekey(oldId, newId, session) {
112
+ if (this.live.get(oldId) === session) this.live.delete(oldId);
113
+ this.live.set(newId, session);
114
+ }
115
+
116
+ /** 空闲回收:长时间无活动的会话子进程退出,历史留在会话文件里。返回淘汰数量。 */
117
+ reap(idleMs) {
118
+ let reaped = 0;
119
+ for (;;) {
120
+ const [candidate] = this.#expired(idleMs, Date.now(), { onlyIdle: false });
121
+ if (!candidate) break;
122
+ const idleSec = Math.round((Date.now() - candidate.session.lastActivity) / 1000);
123
+ this.log("reap", candidate.id, `idle ${idleSec}s`);
124
+ try {
125
+ candidate.session.stop("idle");
126
+ } catch (err) {
127
+ this.log("reap error", candidate.id, err.message);
128
+ }
129
+ this.live.delete(candidate.id);
130
+ reaped++;
131
+ }
132
+ return reaped;
133
+ }
134
+
135
+ closeAll() {
136
+ for (const [id, session] of [...this.live]) {
137
+ try {
138
+ session.stop("shutdown");
139
+ } catch (err) {
140
+ this.log("closeAll error", id, err.message);
141
+ }
142
+ this.live.delete(id);
143
+ }
144
+ }
145
+ }
@@ -0,0 +1,83 @@
1
+ import { spawn } from "node:child_process";
2
+ import { PI_BIN } from "./config.mjs";
3
+ import { piArgs } from "./pi-args.mjs";
4
+
5
+ /**
6
+ * 一次性 pi RPC 调用(用于取模型表等不属于某会话的信息)。
7
+ * @param {string} type
8
+ * @param {Record<string, unknown>} [payload]
9
+ * @param {{cwd?:string, timeoutMs?:number}} [opts]
10
+ */
11
+ export function rpcOnce(type, payload = {}, opts = {}) {
12
+ const timeoutMs = opts.timeoutMs ?? 20000;
13
+ return new Promise((resolve, reject) => {
14
+ const child = spawn(PI_BIN, piArgs({ noSession: true }), {
15
+ cwd: opts.cwd ?? process.cwd(),
16
+ env: { ...process.env, PI_HUB: "1" },
17
+ stdio: ["pipe", "pipe", "ignore"],
18
+ });
19
+ let buf = "";
20
+ let settled = false;
21
+ const done = (err, value) => {
22
+ if (settled) return;
23
+ settled = true;
24
+ clearTimeout(timer);
25
+ try {
26
+ child.kill("SIGTERM");
27
+ } catch {
28
+ // ignore
29
+ }
30
+ err ? reject(err) : resolve(value);
31
+ };
32
+ const timer = setTimeout(() => done(new Error(`pi rpc timeout: ${type}`)), timeoutMs);
33
+ child.on("error", (err) => done(new Error(`spawn pi failed: ${err.message}`)));
34
+ child.on("exit", (code) => {
35
+ if (!settled) done(new Error(`pi exited (${code}) before answering ${type}`));
36
+ });
37
+ child.stdout.on("data", (chunk) => {
38
+ buf += chunk.toString("utf8");
39
+ let idx;
40
+ while ((idx = buf.indexOf("\n")) >= 0) {
41
+ const line = buf.slice(0, idx).replace(/\r$/, "");
42
+ buf = buf.slice(idx + 1);
43
+ if (!line.trim()) continue;
44
+ let rec;
45
+ try {
46
+ rec = JSON.parse(line);
47
+ } catch {
48
+ continue;
49
+ }
50
+ if (rec.type === "extension_ui_request") {
51
+ child.stdin.write(`${JSON.stringify({ type: "extension_ui_response", id: rec.id, cancelled: true })}\n`);
52
+ continue;
53
+ }
54
+ if (rec.type === "response" && rec.command === type) {
55
+ if (rec.success === false) done(new Error(rec.error ?? `${type} failed`));
56
+ else done(null, rec.data ?? null);
57
+ return;
58
+ }
59
+ }
60
+ });
61
+ child.stdin.write(`${JSON.stringify({ id: "one", type, ...payload })}\n`);
62
+ });
63
+ }
64
+
65
+ let modelsCache = { at: 0, value: null };
66
+
67
+ /** 缓存 5 分钟的可选模型列表。 */
68
+ export async function listModels({ cwd } = {}) {
69
+ if (Date.now() - modelsCache.at < 5 * 60 * 1000 && modelsCache.value) return modelsCache.value;
70
+ const data = await rpcOnce("get_available_models", {}, { cwd });
71
+ const models = (data?.models ?? []).map((m) => ({
72
+ provider: m.provider,
73
+ id: m.id,
74
+ name: m.name ?? m.id,
75
+ contextWindow: m.contextWindow ?? null,
76
+ reasoning: Boolean(m.reasoning),
77
+ input: m.input ?? [],
78
+ cost: m.cost ?? null,
79
+ maxTokens: m.maxTokens ?? null,
80
+ }));
81
+ modelsCache = { at: Date.now(), value: models };
82
+ return models;
83
+ }