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,42 @@
1
+ /**
2
+ * 会话锁 —— 只是 `~/pi-plugins/pi-session-lock/core.mjs` 的转发层。
3
+ *
4
+ * 唯一实现(含判定口径)在 plugin 里;pi 侧扩展与进程外调用方(pi-hub)共用它,
5
+ * 避免两份算法漂移。找不到就直接报错:宁可 hub 起不来,也不要无锁写会话文件。
6
+ */
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { pathToFileURL } from "node:url";
10
+ import { HOME } from "./config.mjs";
11
+
12
+ const candidates = [
13
+ process.env.PI_HUB_SESSION_LOCK_CORE,
14
+ path.join(HOME, "pi-plugins", "pi-session-lock", "core.mjs"),
15
+ path.join(HOME, ".pi", "agent", "npm", "node_modules", "pi-session-lock", "core.mjs"),
16
+ ].filter(Boolean);
17
+
18
+ const found = candidates.find((p) => {
19
+ try {
20
+ return fs.existsSync(p);
21
+ } catch {
22
+ return false;
23
+ }
24
+ });
25
+
26
+ if (!found) {
27
+ throw new Error(
28
+ `pi-session-lock core not found (looked in: ${candidates.join(", ")}).\n` +
29
+ `Install the plugin at ~/pi-plugins/pi-session-lock or set PI_HUB_SESSION_LOCK_CORE.`,
30
+ );
31
+ }
32
+
33
+ const core = await import(pathToFileURL(found).href);
34
+
35
+ export const corePath = found;
36
+ export const identity = core.identity;
37
+ export const lockDirFor = core.lockDirFor;
38
+ export const peek = core.peek;
39
+ export const claim = core.claim;
40
+ export const release = core.release;
41
+ export const classify = core.classify;
42
+ export const readOwner = core.readOwner;
@@ -0,0 +1,179 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { SESSIONS_DIR } from "./config.mjs";
4
+
5
+ const HEAD_BYTES = 64 * 1024;
6
+ const CACHE_TTL_MS = 3000;
7
+
8
+ /** @type {{at:number, entries:any[]}} */
9
+ let cache = { at: 0, entries: [] };
10
+ /** file -> {mtimeMs, size, meta} */
11
+ const fileCache = new Map();
12
+
13
+ function readHead(file) {
14
+ const fd = fs.openSync(file, "r");
15
+ try {
16
+ const buf = Buffer.alloc(HEAD_BYTES);
17
+ const n = fs.readSync(fd, buf, 0, HEAD_BYTES, 0);
18
+ return buf.subarray(0, n).toString("utf8");
19
+ } finally {
20
+ fs.closeSync(fd);
21
+ }
22
+ }
23
+
24
+ /** 只解析头部若干行;遇半行/坏行即停(读者安全:不猜)。 */
25
+ function parseHead(text) {
26
+ const meta = { id: null, cwd: null, name: null, createdAt: null, preview: null, model: null };
27
+ for (const line of text.split("\n")) {
28
+ if (!line.trim()) continue;
29
+ let rec;
30
+ try {
31
+ rec = JSON.parse(line);
32
+ } catch {
33
+ break;
34
+ }
35
+ if (rec.type === "session") {
36
+ meta.id = rec.id ?? null;
37
+ meta.cwd = rec.cwd ?? null;
38
+ meta.createdAt = rec.timestamp ?? null;
39
+ } else if (rec.type === "model_change") {
40
+ meta.model = rec.model?.id ?? rec.modelId ?? meta.model;
41
+ } else if (rec.type === "session_info") {
42
+ if (rec.name) meta.name = rec.name;
43
+ } else if (rec.type === "message" && rec.message?.role === "user") {
44
+ const content = rec.message.content;
45
+ const text =
46
+ typeof content === "string"
47
+ ? content
48
+ : (content ?? [])
49
+ .filter((b) => b?.type === "text")
50
+ .map((b) => b.text)
51
+ .join("\n");
52
+ if (text) meta.preview = text.slice(0, 160);
53
+ if (meta.name && meta.id) break;
54
+ }
55
+ }
56
+ return meta;
57
+ }
58
+
59
+ function readFileMeta(file, stat) {
60
+ const cached = fileCache.get(file);
61
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached.meta;
62
+ let meta = { id: null, cwd: null, name: null, createdAt: null, preview: null, model: null };
63
+ try {
64
+ meta = parseHead(readHead(file));
65
+ } catch {
66
+ // 忽略损坏/被并发重写的文件
67
+ }
68
+ fileCache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, meta });
69
+ return meta;
70
+ }
71
+
72
+ /**
73
+ * 列出会话库里的一级会话文件(不追 subagent 嵌套目录)。
74
+ * @param {{limit?:number}} [opts]
75
+ */
76
+ export function listSessions(opts = {}) {
77
+ const limit = opts.limit ?? 200;
78
+ const now = Date.now();
79
+ if (now - cache.at < CACHE_TTL_MS && !opts.force) return cache.entries.slice(0, limit);
80
+
81
+ const entries = [];
82
+ let dirs = [];
83
+ try {
84
+ dirs = fs.readdirSync(SESSIONS_DIR, { withFileTypes: true });
85
+ } catch {
86
+ cache = { at: now, entries };
87
+ return entries;
88
+ }
89
+ for (const dir of dirs) {
90
+ if (!dir.isDirectory() || !dir.name.startsWith("--")) continue;
91
+ const dirPath = path.join(SESSIONS_DIR, dir.name);
92
+ let files = [];
93
+ try {
94
+ files = fs.readdirSync(dirPath, { withFileTypes: true });
95
+ } catch {
96
+ continue;
97
+ }
98
+ for (const f of files) {
99
+ if (!f.isFile() || !f.name.endsWith(".jsonl")) continue;
100
+ const file = path.join(dirPath, f.name);
101
+ let stat;
102
+ try {
103
+ stat = fs.statSync(file);
104
+ } catch {
105
+ continue;
106
+ }
107
+ const meta = readFileMeta(file, stat);
108
+ entries.push({
109
+ id: meta.id ?? f.name.replace(/\.jsonl$/, "").split("_").pop(),
110
+ cwd: meta.cwd,
111
+ name: meta.name,
112
+ preview: meta.preview,
113
+ model: meta.model,
114
+ createdAt: meta.createdAt,
115
+ updatedAt: new Date(stat.mtimeMs).toISOString(),
116
+ updatedAtMs: stat.mtimeMs,
117
+ file,
118
+ size: stat.size,
119
+ projectDir: dir.name.replace(/^--/, "").replace(/--$/, ""),
120
+ });
121
+ }
122
+ }
123
+ entries.sort((a, b) => b.updatedAtMs - a.updatedAtMs);
124
+ cache = { at: now, entries };
125
+ return entries.slice(0, limit);
126
+ }
127
+
128
+ export function findSession(sessionId) {
129
+ const wanted = String(sessionId);
130
+ return listSessions({ limit: 5000 }).find((e) => e.id === wanted) ?? null;
131
+ }
132
+
133
+ /**
134
+ * 从会话文件读取历史消息(只读;按完整 JSONL 行解析,半行丢弃)。
135
+ * @param {string} file
136
+ * @param {{limit?:number}} [opts]
137
+ */
138
+ export function readHistory(file, opts = {}) {
139
+ const limit = opts.limit ?? 0; // 0 = 全部
140
+ let text;
141
+ try {
142
+ text = fs.readFileSync(file, "utf8");
143
+ } catch {
144
+ return [];
145
+ }
146
+ const out = [];
147
+ for (const line of text.split("\n")) {
148
+ if (!line.trim()) continue;
149
+ let rec;
150
+ try {
151
+ rec = JSON.parse(line);
152
+ } catch {
153
+ continue; // 半行丢弃
154
+ }
155
+ if (rec.type !== "message") continue;
156
+ const m = rec.message;
157
+ if (!m) continue;
158
+ const blocks = Array.isArray(m.content) ? m.content : [{ type: "text", text: m.content ?? "" }];
159
+ const textParts = [];
160
+ const toolCalls = [];
161
+ for (const b of blocks) {
162
+ if (b?.type === "text" && b.text) textParts.push(b.text);
163
+ else if (b?.type === "toolCall") toolCalls.push({ id: b.id, name: b.name, args: b.args });
164
+ }
165
+ out.push({
166
+ entryId: rec.id,
167
+ role: m.role,
168
+ text: textParts.join("\n"),
169
+ toolCalls,
170
+ ts: m.timestamp ? new Date(m.timestamp).toISOString() : rec.timestamp,
171
+ usage: m.usage ?? null,
172
+ model: m.model ?? null,
173
+ provider: m.provider ?? null,
174
+ durationMs: m.durationMs ?? null,
175
+ stopReason: m.stopReason ?? null,
176
+ });
177
+ }
178
+ return limit > 0 ? out.slice(-limit) : out;
179
+ }
package/src/static.mjs ADDED
@@ -0,0 +1,148 @@
1
+ // 同源网页(web/)的静态文件服务:白名单路由 + 路径穿越防护 + ETag。
2
+ // 只用 Node 内置模块;mime 表由本文件唯一持有(server.mjs 的 /v1/files 也从这里取)。
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ /** web/ 根目录(相对本文件定位,安装到 node_modules 后同样有效)。 */
8
+ export const WEB_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "web");
9
+
10
+ export const MIME_BY_EXT = {
11
+ ".html": "text/html; charset=utf-8",
12
+ ".htm": "text/html; charset=utf-8",
13
+ ".md": "text/markdown; charset=utf-8",
14
+ ".txt": "text/plain; charset=utf-8",
15
+ ".json": "application/json; charset=utf-8",
16
+ ".webmanifest": "application/manifest+json; charset=utf-8",
17
+ ".js": "text/javascript; charset=utf-8",
18
+ ".mjs": "text/javascript; charset=utf-8",
19
+ ".css": "text/css; charset=utf-8",
20
+ ".svg": "image/svg+xml",
21
+ ".pdf": "application/pdf",
22
+ ".png": "image/png",
23
+ ".jpg": "image/jpeg",
24
+ ".jpeg": "image/jpeg",
25
+ ".webp": "image/webp",
26
+ ".zip": "application/zip",
27
+ };
28
+
29
+ export function mimeForFile(file) {
30
+ return MIME_BY_EXT[path.extname(file).toLowerCase()] ?? "application/octet-stream";
31
+ }
32
+
33
+ /** HTML/JS 响应用的 CSP:无 CDN、无内联脚本(style 允许内联属性,UI 需要动态样式)。 */
34
+ export const CONTENT_SECURITY_POLICY =
35
+ "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'";
36
+
37
+ /** 只暴露 SPA 需要的那几个名字;其余路径一律 404(不目录列举、不兜底 index)。 */
38
+ const EXACT_ROUTES = new Map([
39
+ ["/", "index.html"],
40
+ ["/index.html", "index.html"],
41
+ ["/app.js", "app.js"],
42
+ ["/style.css", "style.css"],
43
+ ["/manifest.webmanifest", "manifest.webmanifest"],
44
+ ["/sw.js", "sw.js"],
45
+ ]);
46
+
47
+ const ICON_ROUTE = /^\/icons\/[A-Za-z0-9][A-Za-z0-9._-]*$/;
48
+
49
+ /**
50
+ * 路由名 → web/ 内的相对路径;不在白名单里返回 null。
51
+ * 白名单本身已排除 `..` 与绝对路径,这里仍复核一次(防未来改表引入穿越)。
52
+ */
53
+ export function resolveStaticPath(pathname, root = WEB_ROOT) {
54
+ let rel = EXACT_ROUTES.get(pathname) ?? null;
55
+ if (rel === null && ICON_ROUTE.test(pathname)) rel = pathname.slice(1);
56
+ if (rel === null) return null;
57
+ if (rel.includes("..") || path.isAbsolute(rel) || rel.includes("\0")) return null;
58
+ return path.join(root, rel);
59
+ }
60
+
61
+ function etagOf(stat) {
62
+ return `"${stat.size.toString(16)}-${Math.floor(stat.mtimeMs).toString(16)}"`;
63
+ }
64
+
65
+ /** text/html 不强缓存(SPA 入口要跟着版本走),其余静态 5 分钟。 */
66
+ export function cacheControlFor(file) {
67
+ return path.extname(file).toLowerCase() === ".html" ? "no-cache" : "public, max-age=300";
68
+ }
69
+
70
+ function send(res, status, body, headers) {
71
+ res.writeHead(status, headers);
72
+ res.end(body);
73
+ }
74
+
75
+ /**
76
+ * 静态路由:命中返回 true(响应已写完),未命中返回 false(交给 /v1 路由)。
77
+ * 出界(realpath 不在 web/ 内)、符号链接失效、非普通文件一律 404,不泄漏是否存在。
78
+ */
79
+ export function serveStatic(req, res, url, { root = WEB_ROOT, method = req.method ?? "GET" } = {}) {
80
+ if (method !== "GET" && method !== "HEAD") return false;
81
+ const file = resolveStaticPath(url.pathname, root);
82
+ if (!file) return false;
83
+
84
+ const notFound = () =>
85
+ send(res, 404, method === "HEAD" ? undefined : "not found", {
86
+ "content-type": "text/plain; charset=utf-8",
87
+ "cache-control": "no-store",
88
+ });
89
+
90
+ let realRoot;
91
+ let real;
92
+ let stat;
93
+ try {
94
+ realRoot = fs.realpathSync(root);
95
+ real = fs.realpathSync(file);
96
+ } catch {
97
+ notFound();
98
+ return true;
99
+ }
100
+ // 符号链接出界(web/icons 里放到别处的链接)也按不存在处理
101
+ if (real !== realRoot && !real.startsWith(realRoot + path.sep)) {
102
+ notFound();
103
+ return true;
104
+ }
105
+ try {
106
+ stat = fs.statSync(real);
107
+ } catch {
108
+ notFound();
109
+ return true;
110
+ }
111
+ if (!stat.isFile()) {
112
+ notFound();
113
+ return true;
114
+ }
115
+
116
+ const ext = path.extname(real).toLowerCase();
117
+ const etag = etagOf(stat);
118
+ const headers = {
119
+ "content-type": mimeForFile(real),
120
+ "cache-control": cacheControlFor(real),
121
+ etag,
122
+ "x-content-type-options": "nosniff",
123
+ };
124
+ if (ext === ".html" || ext === ".js" || ext === ".mjs") {
125
+ headers["content-security-policy"] = CONTENT_SECURITY_POLICY;
126
+ headers["referrer-policy"] = "no-referrer";
127
+ }
128
+
129
+ const inm = req.headers["if-none-match"];
130
+ if (typeof inm === "string" && inm.split(",").some((v) => v.trim() === etag || v.trim() === "*")) {
131
+ send(res, 304, undefined, headers);
132
+ return true;
133
+ }
134
+ headers["content-length"] = stat.size;
135
+ if (method === "HEAD") {
136
+ send(res, 200, undefined, headers);
137
+ return true;
138
+ }
139
+ let body;
140
+ try {
141
+ body = fs.readFileSync(real);
142
+ } catch {
143
+ notFound();
144
+ return true;
145
+ }
146
+ send(res, 200, body, headers);
147
+ return true;
148
+ }
package/src/totp.mjs ADDED
@@ -0,0 +1,151 @@
1
+ // TOTP 2FA:RFC 6238(HOTP 见 RFC 4226)+ RFC 4648 base32。只用 node 内置模块。
2
+ // 用途边界见 .pi/plans/auth-multi/PLAN.md M5:cookie/密码类登录的第二因子。
3
+ import { createHmac, timingSafeEqual } from "node:crypto";
4
+
5
+ /** 默认时间步长与位数(RFC 6238 推荐的 SHA1 口径)。 */
6
+ export const TOTP_STEP_SECONDS = 30;
7
+ export const TOTP_DIGITS = 6;
8
+ /** 默认允许 ±1 个时间步(30 s)的时钟漂移。 */
9
+ export const TOTP_WINDOW = 1;
10
+
11
+ const BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
12
+
13
+ /**
14
+ * RFC 4648 base32 编码,输出大写、**不加 `=` 填充**(otpauth URI 的惯例)。
15
+ */
16
+ export function base32Encode(buffer) {
17
+ const data = Buffer.from(buffer ?? Buffer.alloc(0));
18
+ let out = "";
19
+ let bits = 0;
20
+ let value = 0;
21
+ for (const byte of data) {
22
+ value = (value << 8) | byte;
23
+ bits += 8;
24
+ while (bits >= 5) {
25
+ out += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];
26
+ bits -= 5;
27
+ }
28
+ }
29
+ if (bits > 0) out += BASE32_ALPHABET[(value << (5 - bits)) & 31];
30
+ return out;
31
+ }
32
+
33
+ /**
34
+ * RFC 4648 base32 解码。容忍小写、空格/换行/连字符分隔、缺失或多余的 `=` 填充。
35
+ * 非法字符或残缺的尾位(非 8/5 的整数倍且剩余位非零)抛错,避免静默解出错误密钥。
36
+ */
37
+ export function base32Decode(text) {
38
+ const cleaned = String(text ?? "")
39
+ .replace(/[\s-]/g, "")
40
+ .replace(/=+$/g, "")
41
+ .toUpperCase();
42
+ const bytes = [];
43
+ let bits = 0;
44
+ let value = 0;
45
+ for (const char of cleaned) {
46
+ const index = BASE32_ALPHABET.indexOf(char);
47
+ if (index < 0) throw new Error(`base32Decode: 非法字符 ${JSON.stringify(char)}`);
48
+ value = (value << 5) | index;
49
+ bits += 5;
50
+ if (bits >= 8) {
51
+ bytes.push((value >>> (bits - 8)) & 0xff);
52
+ bits -= 8;
53
+ }
54
+ }
55
+ // 剩下的不足 8 位必须是零,否则说明字符串被截断。
56
+ if (bits > 0 && (value & ((1 << bits) - 1)) !== 0) {
57
+ throw new Error("base32Decode: 尾部填充位非零(输入被截断)");
58
+ }
59
+ return Buffer.from(bytes);
60
+ }
61
+
62
+ /** 时间 → 时间步号(RFC 6238 §4.2: T = floor((now - T0) / X),T0 = 0)。 */
63
+ function counterAt(nowMs, stepSeconds) {
64
+ return Math.floor(nowMs / 1000 / stepSeconds);
65
+ }
66
+
67
+ function normalizeDigits(digits) {
68
+ const value = digits ?? TOTP_DIGITS;
69
+ if (!Number.isInteger(value) || value < 6 || value > 10) {
70
+ throw new Error(`digits 必须是 6..10 的整数,收到 ${digits}`);
71
+ }
72
+ return value;
73
+ }
74
+
75
+ /**
76
+ * HOTP(RFC 4226 §5.3):HMAC-SHA1 + 动态截断,返回补零后的字符串码。
77
+ */
78
+ export function hotp(secretBuffer, counter, digits = TOTP_DIGITS) {
79
+ const place = normalizeDigits(digits);
80
+ if (!Number.isSafeInteger(counter) || counter < 0) {
81
+ throw new Error(`counter 必须是非负整数,收到 ${counter}`);
82
+ }
83
+ const secret = Buffer.from(secretBuffer ?? Buffer.alloc(0));
84
+ if (secret.length === 0) throw new Error("HOTP 密钥不能为空");
85
+ const message = Buffer.alloc(8);
86
+ message.writeBigUInt64BE(BigInt(counter));
87
+ const mac = createHmac("sha1", secret).update(message).digest();
88
+ const offset = mac[mac.length - 1] & 0x0f;
89
+ const binary =
90
+ ((mac[offset] & 0x7f) << 24) |
91
+ ((mac[offset + 1] & 0xff) << 16) |
92
+ ((mac[offset + 2] & 0xff) << 8) |
93
+ (mac[offset + 3] & 0xff);
94
+ return String(binary % 10 ** place).padStart(place, "0");
95
+ }
96
+
97
+ /** TOTP(RFC 6238):按当前时间取 TOTP 码。 */
98
+ export function totp(secretBuffer, { now = Date.now(), step = TOTP_STEP_SECONDS, digits = TOTP_DIGITS } = {}) {
99
+ return hotp(secretBuffer, counterAt(now, step), digits);
100
+ }
101
+
102
+ function safeCodeEqual(a, b) {
103
+ const left = Buffer.from(a);
104
+ const right = Buffer.from(b);
105
+ if (left.length !== right.length) return false;
106
+ return timingSafeEqual(left, right);
107
+ }
108
+
109
+ /**
110
+ * 校验 TOTP 码:默认 ±window 个时间步(±30 s),命中后拒绝已被用过的步号。
111
+ * `usedCounters` 传 Set/Map 由调用方持有(落盘或进程内),命中时会写入当前步号。
112
+ */
113
+ export function verifyTotp(
114
+ secretBuffer,
115
+ code,
116
+ { now = Date.now(), step = TOTP_STEP_SECONDS, digits = TOTP_DIGITS, window = TOTP_WINDOW, usedCounters } = {},
117
+ ) {
118
+ const given = String(code ?? "").replace(/[\s-]/g, "");
119
+ const place = normalizeDigits(digits);
120
+ if (!new RegExp(`^\\d{${place}}$`).test(given)) return false;
121
+ const current = counterAt(now, step);
122
+ for (let offset = -window; offset <= window; offset++) {
123
+ const counter = current + offset;
124
+ if (counter < 0) continue;
125
+ if (!safeCodeEqual(given, hotp(secretBuffer, counter, place))) continue;
126
+ if (usedCounters?.has?.(counter)) return false;
127
+ usedCounters?.add?.(counter);
128
+ return true;
129
+ }
130
+ return false;
131
+ }
132
+
133
+ /**
134
+ * `otpauth://totp/...` 配置 URI(Key URI Format),供二维码/手工录入使用。
135
+ * `secret` 接受 base32 字符串或 Buffer(自动编码)。
136
+ */
137
+ export function otpauthUri({ issuer, account, secret, digits = TOTP_DIGITS, step = TOTP_STEP_SECONDS }) {
138
+ if (!issuer || !account) throw new Error("otpauthUri: issuer 与 account 必填");
139
+ const encoded =
140
+ typeof secret === "string" ? base32Encode(base32Decode(secret)) : base32Encode(secret ?? Buffer.alloc(0));
141
+ if (!encoded) throw new Error("otpauthUri: secret 不能为空");
142
+ const label = `${encodeURIComponent(issuer)}:${encodeURIComponent(account)}`;
143
+ const params = new URLSearchParams({
144
+ secret: encoded,
145
+ issuer,
146
+ algorithm: "SHA1",
147
+ digits: String(digits),
148
+ period: String(step),
149
+ });
150
+ return `otpauth://totp/${label}?${params.toString()}`;
151
+ }