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.
- package/LICENSE +21 -0
- package/README.md +403 -2
- package/bin/pi-hub.mjs +353 -0
- package/docs/AUTH.md +141 -0
- package/package.json +45 -4
- package/src/config.mjs +54 -0
- package/src/otp.mjs +162 -0
- package/src/pairing.mjs +403 -0
- package/src/pi-args.mjs +51 -0
- package/src/pi-session.mjs +635 -0
- package/src/proxy-auth.mjs +181 -0
- package/src/registry.mjs +145 -0
- package/src/rpc-once.mjs +83 -0
- package/src/server.mjs +1532 -0
- package/src/session-lock.mjs +42 -0
- package/src/sessions-index.mjs +179 -0
- package/src/static.mjs +148 -0
- package/src/totp.mjs +151 -0
- package/src/update-check.mjs +218 -0
- package/src/web-auth.mjs +450 -0
- package/systemd/pi-hub.service +22 -0
- package/web/app.js +1339 -0
- package/web/icons/icon.svg +7 -0
- package/web/index.html +121 -0
- package/web/manifest.webmanifest +20 -0
- package/web/style.css +782 -0
- package/web/sw.js +45 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
// 更新检查:GET /v1/update 背后的纯函数 + 上游取数(缓存 1 h)。
|
|
2
|
+
// 取数顺序:spawn `curl -fsS --max-time 8`(继承宿主代理 env)→ Node https 直连兜底;
|
|
3
|
+
// 全失败回 {error},绝不抛、绝不 500(PLAN C4)。
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import https from "node:https";
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
|
|
10
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
11
|
+
|
|
12
|
+
/** 服务端版本以 package.json 为唯一真源(/v1/health 与 /v1/update 都读它)。 */
|
|
13
|
+
export const HUB_VERSION = JSON.parse(fs.readFileSync(path.join(HERE, "..", "package.json"), "utf8")).version;
|
|
14
|
+
|
|
15
|
+
export const HUB_RELEASES_URL = "https://github.com/xiaquwan1001/pi-hub/releases/latest";
|
|
16
|
+
export const ANDROID_RELEASES_URL = "https://github.com/xiaquwan1001/pi-hub-android/releases/latest";
|
|
17
|
+
const HUB_API_URL = "https://api.github.com/repos/xiaquwan1001/pi-hub/releases/latest";
|
|
18
|
+
const ANDROID_API_URL = "https://api.github.com/repos/xiaquwan1001/pi-hub-android/releases/latest";
|
|
19
|
+
|
|
20
|
+
export const UPDATE_TTL_MS = 60 * 60 * 1000;
|
|
21
|
+
export const UPDATE_FETCH_TIMEOUT_MS = 8000;
|
|
22
|
+
|
|
23
|
+
const SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/;
|
|
24
|
+
|
|
25
|
+
function parseVersion(value) {
|
|
26
|
+
const text = String(value ?? "").trim().replace(/^[vV]/, "");
|
|
27
|
+
const match = SEMVER_RE.exec(text);
|
|
28
|
+
if (!match) return null;
|
|
29
|
+
return { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]), pre: match[4] ?? null };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** semver 简化:数字标识比字母标识小,标识多者(前缀相同时)更大。 */
|
|
33
|
+
function comparePrerelease(a, b) {
|
|
34
|
+
const left = a.split(".");
|
|
35
|
+
const right = b.split(".");
|
|
36
|
+
for (let i = 0; i < Math.max(left.length, right.length); i += 1) {
|
|
37
|
+
const l = left[i];
|
|
38
|
+
const r = right[i];
|
|
39
|
+
if (l === undefined) return -1;
|
|
40
|
+
if (r === undefined) return 1;
|
|
41
|
+
const ln = /^\d+$/.test(l);
|
|
42
|
+
const rn = /^\d+$/.test(r);
|
|
43
|
+
if (ln && rn) {
|
|
44
|
+
const diff = Number(l) - Number(r);
|
|
45
|
+
if (diff !== 0) return diff < 0 ? -1 : 1;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (ln !== rn) return ln ? -1 : 1;
|
|
49
|
+
if (l !== r) return l < r ? -1 : 1;
|
|
50
|
+
}
|
|
51
|
+
return 0;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* `compareVersions(a,b)` → -1 / 0 / 1。
|
|
56
|
+
* `x.y.z` + 可选 `-pre`;带 pre 的小于同号正式版。解析不了的按字符串比较(行为确定,不抛)。
|
|
57
|
+
*/
|
|
58
|
+
export function compareVersions(a, b) {
|
|
59
|
+
const left = parseVersion(a);
|
|
60
|
+
const right = parseVersion(b);
|
|
61
|
+
if (!left || !right) {
|
|
62
|
+
const ls = String(a ?? "");
|
|
63
|
+
const rs = String(b ?? "");
|
|
64
|
+
if (ls === rs) return 0;
|
|
65
|
+
return ls < rs ? -1 : 1;
|
|
66
|
+
}
|
|
67
|
+
for (const key of ["major", "minor", "patch"]) {
|
|
68
|
+
if (left[key] !== right[key]) return left[key] < right[key] ? -1 : 1;
|
|
69
|
+
}
|
|
70
|
+
if (left.pre === right.pre) return 0;
|
|
71
|
+
if (left.pre === null) return 1;
|
|
72
|
+
if (right.pre === null) return -1;
|
|
73
|
+
return comparePrerelease(left.pre, right.pre);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** `tag_name` / `name` → 去掉前导 v 的版本串;取不到返回 null。 */
|
|
77
|
+
export function tagToVersion(release) {
|
|
78
|
+
const raw = release?.tag_name ?? release?.name ?? null;
|
|
79
|
+
if (typeof raw !== "string" || !raw.trim()) return null;
|
|
80
|
+
return raw.trim().replace(/^[vV]/, "");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** curl 优先(继承 HTTPS_PROXY);失败抛错,由调用方决定是否走 Node 兜底。 */
|
|
84
|
+
function curlJson(url, { timeoutMs = UPDATE_FETCH_TIMEOUT_MS } = {}) {
|
|
85
|
+
return new Promise((resolve, reject) => {
|
|
86
|
+
const child = spawn(
|
|
87
|
+
"curl",
|
|
88
|
+
[
|
|
89
|
+
"-fsS",
|
|
90
|
+
"--max-time",
|
|
91
|
+
String(Math.ceil(timeoutMs / 1000)),
|
|
92
|
+
"-H",
|
|
93
|
+
"accept: application/vnd.github+json",
|
|
94
|
+
"-H",
|
|
95
|
+
"user-agent: pi-hub-update-check",
|
|
96
|
+
url,
|
|
97
|
+
],
|
|
98
|
+
{ stdio: ["ignore", "pipe", "pipe"] },
|
|
99
|
+
);
|
|
100
|
+
const out = [];
|
|
101
|
+
const err = [];
|
|
102
|
+
child.stdout.on("data", (chunk) => out.push(chunk));
|
|
103
|
+
child.stderr.on("data", (chunk) => err.push(chunk));
|
|
104
|
+
child.on("error", (e) => reject(e));
|
|
105
|
+
child.on("close", (code) => {
|
|
106
|
+
if (code !== 0) {
|
|
107
|
+
const detail = Buffer.concat(err).toString("utf8").trim().slice(0, 200);
|
|
108
|
+
reject(new Error(`curl exit ${code}${detail ? `: ${detail}` : ""}`));
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
resolve(JSON.parse(Buffer.concat(out).toString("utf8")));
|
|
113
|
+
} catch (e) {
|
|
114
|
+
reject(new Error(`curl returned non-JSON: ${e.message}`));
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function httpsJson(url, { timeoutMs = UPDATE_FETCH_TIMEOUT_MS } = {}) {
|
|
121
|
+
return new Promise((resolve, reject) => {
|
|
122
|
+
const req = https.get(
|
|
123
|
+
url,
|
|
124
|
+
{ headers: { accept: "application/vnd.github+json", "user-agent": "pi-hub-update-check" } },
|
|
125
|
+
(res) => {
|
|
126
|
+
const chunks = [];
|
|
127
|
+
res.on("data", (chunk) => chunks.push(chunk));
|
|
128
|
+
res.on("end", () => {
|
|
129
|
+
const status = res.statusCode ?? 0;
|
|
130
|
+
if (status !== 200) {
|
|
131
|
+
reject(new Error(`http ${status}`));
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
try {
|
|
135
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
136
|
+
} catch (e) {
|
|
137
|
+
reject(new Error(`non-JSON response: ${e.message}`));
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
res.on("error", reject);
|
|
141
|
+
},
|
|
142
|
+
);
|
|
143
|
+
req.setTimeout(timeoutMs, () => req.destroy(new Error(`timeout after ${timeoutMs} ms`)));
|
|
144
|
+
req.on("error", reject);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** 默认取数:curl 优先,失败再 https 直连。 */
|
|
149
|
+
export async function fetchJsonCurlThenHttps(url, options = {}) {
|
|
150
|
+
try {
|
|
151
|
+
return await curlJson(url, options);
|
|
152
|
+
} catch (curlErr) {
|
|
153
|
+
try {
|
|
154
|
+
return await httpsJson(url, options);
|
|
155
|
+
} catch (httpsErr) {
|
|
156
|
+
throw new Error(`${curlErr.message} / https: ${httpsErr.message}`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function errorText(err) {
|
|
162
|
+
return String(err?.message ?? err).slice(0, 200);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* 1 h 缓存的上游结果(只缓存「最新版本 + 错误」,当前版本每次现算)。
|
|
167
|
+
* 一个仓库失败不影响另一个;两者都失败仍然返回 200 + error。
|
|
168
|
+
*/
|
|
169
|
+
export class UpdateChecker {
|
|
170
|
+
constructor({ fetchJson = fetchJsonCurlThenHttps, now = () => Date.now(), ttlMs = UPDATE_TTL_MS } = {}) {
|
|
171
|
+
this.fetchJson = fetchJson;
|
|
172
|
+
this.now = now;
|
|
173
|
+
this.ttlMs = ttlMs;
|
|
174
|
+
/** {at, serverLatest, androidLatest, error} */
|
|
175
|
+
this.cache = null;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async upstream() {
|
|
179
|
+
const now = this.now();
|
|
180
|
+
if (this.cache && now - this.cache.at < this.ttlMs) return this.cache;
|
|
181
|
+
const [hub, android] = await Promise.all([
|
|
182
|
+
this.fetchJson(HUB_API_URL).catch((e) => ({ __error: `pi-hub: ${errorText(e)}` })),
|
|
183
|
+
this.fetchJson(ANDROID_API_URL).catch((e) => ({ __error: `pi-hub-android: ${errorText(e)}` })),
|
|
184
|
+
]);
|
|
185
|
+
const errors = [hub.__error, android.__error].filter(Boolean);
|
|
186
|
+
this.cache = {
|
|
187
|
+
at: now,
|
|
188
|
+
serverLatest: hub.__error ? null : tagToVersion(hub),
|
|
189
|
+
androidLatest: android.__error ? null : tagToVersion(android),
|
|
190
|
+
error: errors.length ? errors.join("; ") : null,
|
|
191
|
+
};
|
|
192
|
+
return this.cache;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** 对外的 /v1/update 响应(形状见 PLAN C4);只读操作,任何失败都不抛。 */
|
|
196
|
+
async get({ androidCurrent = null } = {}) {
|
|
197
|
+
const upstream = await this.upstream().catch((e) => ({
|
|
198
|
+
at: this.now(),
|
|
199
|
+
serverLatest: null,
|
|
200
|
+
androidLatest: null,
|
|
201
|
+
error: errorText(e),
|
|
202
|
+
}));
|
|
203
|
+
return {
|
|
204
|
+
checkedAt: new Date(upstream.at).toISOString(),
|
|
205
|
+
source: "github",
|
|
206
|
+
error: upstream.error,
|
|
207
|
+
server: { current: HUB_VERSION, latest: upstream.serverLatest, url: HUB_RELEASES_URL },
|
|
208
|
+
android: { current: androidCurrent ?? null, latest: upstream.androidLatest, url: ANDROID_RELEASES_URL },
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export const updateChecker = new UpdateChecker();
|
|
214
|
+
|
|
215
|
+
/** 便捷入口(进程内单例缓存)。 */
|
|
216
|
+
export function getUpdateInfo(options = {}) {
|
|
217
|
+
return updateChecker.get(options);
|
|
218
|
+
}
|
package/src/web-auth.mjs
ADDED
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
// Web 会话:同源 SPA 用 cookie 注入鉴权(Bearer / 设备签名继续有效)。
|
|
2
|
+
// 契约见 .pi/plans/mobile-r4/PLAN.md C5 与 .pi/plans/auth-multi/PLAN.md M3:只存 sha256(session),CSRF 与 cookie 绑定(double-submit)。
|
|
3
|
+
//
|
|
4
|
+
// 路由助手的形式(W1 接线口径,二选一取「纯函数」):
|
|
5
|
+
// handleWebLogin / handleWebSession / handleWebLogout / handleWebCsrf / handleWebSessionsList / handleWebSessionRevoke
|
|
6
|
+
// 统一签名 `(req, ctx) => {status, headers, body}`:
|
|
7
|
+
// - req:Node 的 http.IncomingMessage(只读 method / headers);
|
|
8
|
+
// - ctx:{ webAuth, ip?, secure?, body?, params?, primary? },body 是已解析的 JSON 对象,params 是路由参数;
|
|
9
|
+
// - 返回体 `body` 是 JSON 可序列化的值(不是字符串),由 W1 用 `json(res, status, body, headers)` 输出;
|
|
10
|
+
// - `headers` 里可能含 `set-cookie`,原样透传。
|
|
11
|
+
// 这样本模块不碰 res,可纯单测(test/web-auth.mjs 不 spawn、不联网)。
|
|
12
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
13
|
+
import { AUTH_DISABLED } from "./config.mjs";
|
|
14
|
+
|
|
15
|
+
export const SESSION_COOKIE = "pihub_session";
|
|
16
|
+
const DEFAULT_WEB_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
17
|
+
/** PI_HUB_WEB_TTL_MS 校验:非正数 / 非数字一律回落到 30 天(不让坏 env 把所有人立刻登出)。 */
|
|
18
|
+
function parseTtlMs(raw) {
|
|
19
|
+
const value = Number(raw);
|
|
20
|
+
return Number.isFinite(value) && value > 0 ? Math.floor(value) : DEFAULT_WEB_TTL_MS;
|
|
21
|
+
}
|
|
22
|
+
/** 会话 TTL:默认 30 天,PI_HUB_WEB_TTL_MS 覆盖(测试可传 ttlMs 注入)。 */
|
|
23
|
+
export const WEB_TTL_MS = parseTtlMs(process.env.PI_HUB_WEB_TTL_MS);
|
|
24
|
+
/** 登录限速:每 IP 每 60 s 最多 10 次失败。 */
|
|
25
|
+
export const WEB_LOGIN_RATE_LIMIT = 10;
|
|
26
|
+
export const WEB_LOGIN_RATE_WINDOW_MS = 60 * 1000;
|
|
27
|
+
/** 滑动续期窗口:validate 时距到期不足 7 天就延长到 now + TTL。 */
|
|
28
|
+
export const WEB_RENEW_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
|
29
|
+
/** lastSeenAt 写节流:≥60 s 才更新一次,避免每个请求都写台账。 */
|
|
30
|
+
export const WEB_LAST_SEEN_THROTTLE_MS = 60 * 1000;
|
|
31
|
+
|
|
32
|
+
function sha256hex(value) {
|
|
33
|
+
return createHash("sha256").update(value).digest("hex");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** UA 只留 16 hex 指纹(够区分设备,不可逆)。 */
|
|
37
|
+
function uaHashOf(ua) {
|
|
38
|
+
if (typeof ua !== "string" || !ua) return null;
|
|
39
|
+
return sha256hex(ua).slice(0, 16);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function headerValue(headers, name) {
|
|
43
|
+
const raw = headers?.[name];
|
|
44
|
+
return Array.isArray(raw) ? raw[0] : raw;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function equalSecret(a, b) {
|
|
48
|
+
if (typeof a !== "string" || typeof b !== "string" || !a || !b) return false;
|
|
49
|
+
const left = Buffer.from(a);
|
|
50
|
+
const right = Buffer.from(b);
|
|
51
|
+
if (left.length !== right.length) return false;
|
|
52
|
+
return timingSafeEqual(left, right);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** `a=1; b=2` → Map(值里的引号与空白按浏览器实际发送的形态处理)。 */
|
|
56
|
+
export function parseCookies(header) {
|
|
57
|
+
const out = new Map();
|
|
58
|
+
if (typeof header !== "string" || !header) return out;
|
|
59
|
+
for (const part of header.split(";")) {
|
|
60
|
+
const idx = part.indexOf("=");
|
|
61
|
+
if (idx < 0) continue;
|
|
62
|
+
const name = part.slice(0, idx).trim();
|
|
63
|
+
if (!name) continue;
|
|
64
|
+
out.set(name, part.slice(idx + 1).trim().replace(/^"(.*)"$/, "$1"));
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 请求是否走 https(直连 TLS 或反向代理转发的 x-forwarded-proto)。 */
|
|
70
|
+
export function isSecureRequest(req) {
|
|
71
|
+
if (req?.socket?.encrypted === true) return true;
|
|
72
|
+
return String(headerValue(req?.headers, "x-forwarded-proto") ?? "").split(",")[0].trim().toLowerCase() === "https";
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function sessionCookie(value, { secure = false, maxAgeSeconds = Math.floor(WEB_TTL_MS / 1000) } = {}) {
|
|
76
|
+
const parts = [`${SESSION_COOKIE}=${value}`, "HttpOnly", "SameSite=Strict", "Path=/", `Max-Age=${maxAgeSeconds}`];
|
|
77
|
+
if (secure) parts.push("Secure");
|
|
78
|
+
return parts.join("; ");
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function clearSessionCookie({ secure = false } = {}) {
|
|
82
|
+
const parts = [`${SESSION_COOKIE}=`, "HttpOnly", "SameSite=Strict", "Path=/", "Max-Age=0"];
|
|
83
|
+
if (secure) parts.push("Secure");
|
|
84
|
+
return parts.join("; ");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 把台账内条目投影成对外元数据(不含 session 值 / sha256 / csrf)。 */
|
|
88
|
+
function publicSession(entry) {
|
|
89
|
+
return {
|
|
90
|
+
id: entry.id,
|
|
91
|
+
createdAt: new Date(entry.createdAt).toISOString(),
|
|
92
|
+
lastSeenAt: new Date(entry.lastSeenAt).toISOString(),
|
|
93
|
+
expiresAt: new Date(entry.expiresAt).toISOString(),
|
|
94
|
+
ip: entry.ip,
|
|
95
|
+
uaHash: entry.uaHash,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 登录限速器:每 IP 60 s 内最多 10 次失败;超限给出 retryAfterMs,成功登录清零。
|
|
101
|
+
* now 可注入(测试用固定时钟)。契约:
|
|
102
|
+
* before(ip) → null | {ok:false, code:"rate_limited", retryAfterMs}
|
|
103
|
+
* fail(ip) / succeed(ip) / reset(ip?)
|
|
104
|
+
*/
|
|
105
|
+
export class LoginLimiter {
|
|
106
|
+
constructor({ limit = WEB_LOGIN_RATE_LIMIT, windowMs = WEB_LOGIN_RATE_WINDOW_MS, now = () => Date.now() } = {}) {
|
|
107
|
+
this.limit = limit;
|
|
108
|
+
this.windowMs = windowMs;
|
|
109
|
+
this.now = now;
|
|
110
|
+
/** ip → 窗口内失败时间戳(升序) */
|
|
111
|
+
this.failures = new Map();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
#hits(ip) {
|
|
115
|
+
const key = ip || "unknown";
|
|
116
|
+
const now = this.now();
|
|
117
|
+
const hits = (this.failures.get(key) ?? []).filter((t) => now - t < this.windowMs);
|
|
118
|
+
if (hits.length) this.failures.set(key, hits);
|
|
119
|
+
else this.failures.delete(key);
|
|
120
|
+
return { key, hits, now };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** 已超限则返回拒因(不计数);未超限返回 null,调用方登录失败后要自己 fail()。 */
|
|
124
|
+
before(ip) {
|
|
125
|
+
const { hits, now } = this.#hits(ip);
|
|
126
|
+
if (hits.length < this.limit) return null;
|
|
127
|
+
return { ok: false, code: "rate_limited", retryAfterMs: Math.max(0, hits[0] + this.windowMs - now) };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
fail(ip) {
|
|
131
|
+
const { key, hits, now } = this.#hits(ip);
|
|
132
|
+
hits.push(now);
|
|
133
|
+
this.failures.set(key, hits);
|
|
134
|
+
return hits.length;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
succeed(ip) {
|
|
138
|
+
this.failures.delete(ip || "unknown");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
reset(ip) {
|
|
142
|
+
if (ip === undefined) return this.failures.clear();
|
|
143
|
+
return this.failures.delete(ip || "unknown");
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** 便捷工厂:`loginLimiter({ now })`。 */
|
|
148
|
+
export function loginLimiter(options) {
|
|
149
|
+
return new LoginLimiter(options);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** CSRF 强制助手:非 GET/HEAD 必须带与会话绑定的 x-pi-csrf(恒时比较)。 */
|
|
153
|
+
export function checkCsrf(req, session) {
|
|
154
|
+
const method = String(req?.method ?? "GET").toUpperCase();
|
|
155
|
+
if (method === "GET" || method === "HEAD") return { ok: true };
|
|
156
|
+
if (!session?.csrf) return { ok: false, code: "csrf" };
|
|
157
|
+
const given = headerValue(req?.headers, "x-pi-csrf");
|
|
158
|
+
if (!equalSecret(given, session.csrf)) return { ok: false, code: "csrf" };
|
|
159
|
+
return { ok: true };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* 内存会话台账:key 是 sha256(session),不存明文;cookie 泄漏以外的场景(内存 dump)也拿不到可用值。
|
|
164
|
+
* 每条:{id, createdAt, lastSeenAt, expiresAt, ip, uaHash, csrf},对外只经 listSessions() 暴露元数据。
|
|
165
|
+
*/
|
|
166
|
+
export class WebAuth {
|
|
167
|
+
constructor({
|
|
168
|
+
token = null,
|
|
169
|
+
authDisabled = AUTH_DISABLED,
|
|
170
|
+
ttlMs = WEB_TTL_MS,
|
|
171
|
+
now = () => Date.now(),
|
|
172
|
+
log = () => {},
|
|
173
|
+
limiter = null,
|
|
174
|
+
} = {}) {
|
|
175
|
+
this.token = token;
|
|
176
|
+
this.authDisabled = authDisabled;
|
|
177
|
+
this.ttlMs = ttlMs;
|
|
178
|
+
this.now = now;
|
|
179
|
+
this.log = log;
|
|
180
|
+
this.limiter = limiter ?? loginLimiter({ now });
|
|
181
|
+
/** sha256(session) → {id, createdAt, lastSeenAt, expiresAt, ip, uaHash, csrf} */
|
|
182
|
+
this.sessions = new Map();
|
|
183
|
+
/** ip → 最近 60 s 内的登录尝试时间戳(未接线前的旧口径,保留给 server.mjs 现状) */
|
|
184
|
+
this.rate = new Map();
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
get ttlSeconds() {
|
|
188
|
+
return Math.floor(this.ttlMs / 1000);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** 返回 true 表示该 IP 本轮被限速(调用即计数;旧口径,登录失败计数请用 this.limiter)。 */
|
|
192
|
+
rateLimited(ip) {
|
|
193
|
+
const now = this.now();
|
|
194
|
+
const key = ip || "unknown";
|
|
195
|
+
const hits = (this.rate.get(key) ?? []).filter((t) => now - t < WEB_LOGIN_RATE_WINDOW_MS);
|
|
196
|
+
if (hits.length >= WEB_LOGIN_RATE_LIMIT) {
|
|
197
|
+
this.rate.set(key, hits);
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
hits.push(now);
|
|
201
|
+
this.rate.set(key, hits);
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
cookieValue(req) {
|
|
206
|
+
return parseCookies(req?.headers?.cookie).get(SESSION_COOKIE) ?? null;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** 建会话(不校验令牌,调用方已判定);ip/ua 只落台账元数据,ua 存 16 hex 指纹。 */
|
|
210
|
+
createSession({ ip = null, ua = null } = {}) {
|
|
211
|
+
const session = randomBytes(32).toString("base64url");
|
|
212
|
+
const csrf = randomBytes(32).toString("base64url");
|
|
213
|
+
const now = this.now();
|
|
214
|
+
let id = randomBytes(4).toString("hex");
|
|
215
|
+
while ([...this.sessions.values()].some((entry) => entry.id === id)) id = randomBytes(4).toString("hex");
|
|
216
|
+
this.sessions.set(sha256hex(session), {
|
|
217
|
+
id,
|
|
218
|
+
createdAt: now,
|
|
219
|
+
lastSeenAt: now,
|
|
220
|
+
expiresAt: now + this.ttlMs,
|
|
221
|
+
ip: ip ?? null,
|
|
222
|
+
uaHash: uaHashOf(ua),
|
|
223
|
+
csrf,
|
|
224
|
+
});
|
|
225
|
+
this.sweep();
|
|
226
|
+
return { session, csrf, expiresAt: now + this.ttlMs, id };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* 登录:`{token}` 与主令牌恒时比较。
|
|
231
|
+
* AUTH_DISABLED 时直接放行(`disabled:true` 交给路由说明),不建会话。
|
|
232
|
+
*/
|
|
233
|
+
login({ token = "", ip = null, ua = null } = {}) {
|
|
234
|
+
if (this.authDisabled) return { ok: true, disabled: true, session: null, csrf: null, expiresAt: null };
|
|
235
|
+
if (!this.token || !equalSecret(token, this.token)) {
|
|
236
|
+
this.log("web login rejected", ip ?? "unknown");
|
|
237
|
+
return { ok: false, code: "invalid_token", message: "invalid token" };
|
|
238
|
+
}
|
|
239
|
+
return { ok: true, disabled: false, ...this.createSession({ ip, ua }) };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** 查会话:`{ok, expiresAt, csrf}`;过期即删(不做续期,续期在 validate)。 */
|
|
243
|
+
session(cookieValue) {
|
|
244
|
+
if (typeof cookieValue !== "string" || !cookieValue) return { ok: false };
|
|
245
|
+
const key = sha256hex(cookieValue);
|
|
246
|
+
const entry = this.sessions.get(key);
|
|
247
|
+
if (!entry) return { ok: false };
|
|
248
|
+
if (entry.expiresAt <= this.now()) {
|
|
249
|
+
this.sessions.delete(key);
|
|
250
|
+
return { ok: false, expired: true };
|
|
251
|
+
}
|
|
252
|
+
return { ok: true, expiresAt: entry.expiresAt, csrf: entry.csrf };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* 台账校验(W1 用它替代 session):过期/被吊销 → null。
|
|
257
|
+
* 滑动续期:距到期 < 7 天则延长到 now + TTL(返回的 renewed 为 true);
|
|
258
|
+
* lastSeenAt 每 ≥60 s 才写一次。返回的是副本,改它不会影响台账。
|
|
259
|
+
*/
|
|
260
|
+
validate(cookieValue) {
|
|
261
|
+
if (typeof cookieValue !== "string" || !cookieValue) return null;
|
|
262
|
+
const key = sha256hex(cookieValue);
|
|
263
|
+
const entry = this.sessions.get(key);
|
|
264
|
+
if (!entry) return null;
|
|
265
|
+
const now = this.now();
|
|
266
|
+
if (entry.expiresAt <= now) {
|
|
267
|
+
this.sessions.delete(key);
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
let renewed = false;
|
|
271
|
+
if (entry.expiresAt - now < WEB_RENEW_WINDOW_MS) {
|
|
272
|
+
entry.expiresAt = now + this.ttlMs;
|
|
273
|
+
renewed = true;
|
|
274
|
+
}
|
|
275
|
+
if (now - entry.lastSeenAt >= WEB_LAST_SEEN_THROTTLE_MS) entry.lastSeenAt = now;
|
|
276
|
+
return {
|
|
277
|
+
id: entry.id,
|
|
278
|
+
createdAt: entry.createdAt,
|
|
279
|
+
lastSeenAt: entry.lastSeenAt,
|
|
280
|
+
expiresAt: entry.expiresAt,
|
|
281
|
+
ip: entry.ip,
|
|
282
|
+
uaHash: entry.uaHash,
|
|
283
|
+
csrf: entry.csrf,
|
|
284
|
+
renewed,
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** 状态变更请求的 CSRF 校验(cookie 鉴权时才用)。 */
|
|
289
|
+
verifyCsrf(cookieValue, headerValue) {
|
|
290
|
+
const found = this.session(cookieValue);
|
|
291
|
+
if (!found.ok) return false;
|
|
292
|
+
const given = Array.isArray(headerValue) ? headerValue[0] : headerValue;
|
|
293
|
+
return equalSecret(given, found.csrf);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** 台账元数据(新增在前),不含 session 值 / sha256 / csrf。 */
|
|
297
|
+
listSessions() {
|
|
298
|
+
this.sweep();
|
|
299
|
+
return [...this.sessions.values()]
|
|
300
|
+
.sort((a, b) => b.createdAt - a.createdAt)
|
|
301
|
+
.map(publicSession);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** 按短 id 吊销;返回是否命中。 */
|
|
305
|
+
revokeSession(id) {
|
|
306
|
+
if (typeof id !== "string" || !id) return false;
|
|
307
|
+
for (const [key, entry] of this.sessions) {
|
|
308
|
+
if (entry.id === id) return this.sessions.delete(key);
|
|
309
|
+
}
|
|
310
|
+
return false;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** 吊销全部会话(停用所有浏览器登录态),返回吊销条数。 */
|
|
314
|
+
revokeAll() {
|
|
315
|
+
const count = this.sessions.size;
|
|
316
|
+
this.sessions.clear();
|
|
317
|
+
return count;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
logout(cookieValue) {
|
|
321
|
+
if (typeof cookieValue !== "string" || !cookieValue) return false;
|
|
322
|
+
return this.sessions.delete(sha256hex(cookieValue));
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
sweep() {
|
|
326
|
+
const now = this.now();
|
|
327
|
+
for (const [key, entry] of this.sessions) {
|
|
328
|
+
if (entry.expiresAt <= now) this.sessions.delete(key);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// ---------- 路由助手(纯函数:不碰 res,返回 {status, headers, body}) ----------
|
|
334
|
+
|
|
335
|
+
function errorBody(code, message, extra = {}) {
|
|
336
|
+
return { error: { code, message, ...extra } };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function cookieOptions(req, ctx, webAuth) {
|
|
340
|
+
return { secure: ctx?.secure ?? isSecureRequest(req), maxAgeSeconds: webAuth.ttlSeconds };
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** POST /v1/web/login {token} → {ok, expiresAt} + Set-Cookie;失败计数进 loginLimiter,成功清零。 */
|
|
344
|
+
export function handleWebLogin(req, ctx) {
|
|
345
|
+
const webAuth = ctx.webAuth;
|
|
346
|
+
const ip = ctx.ip ?? null;
|
|
347
|
+
const limited = webAuth.limiter.before(ip);
|
|
348
|
+
if (limited) {
|
|
349
|
+
return {
|
|
350
|
+
status: 429,
|
|
351
|
+
headers: {},
|
|
352
|
+
body: errorBody("rate_limited", "too many login attempts", { retryAfterMs: limited.retryAfterMs }),
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
const token = typeof ctx.body?.token === "string" ? ctx.body.token : "";
|
|
356
|
+
const verdict = webAuth.login({ token, ip, ua: headerValue(req?.headers, "user-agent") ?? null });
|
|
357
|
+
if (!verdict.ok) {
|
|
358
|
+
webAuth.limiter.fail(ip);
|
|
359
|
+
return { status: 401, headers: {}, body: errorBody(verdict.code, verdict.message) };
|
|
360
|
+
}
|
|
361
|
+
webAuth.limiter.succeed(ip);
|
|
362
|
+
if (verdict.disabled) return { status: 200, headers: {}, body: { ok: true, authDisabled: true, expiresAt: null } };
|
|
363
|
+
return {
|
|
364
|
+
status: 200,
|
|
365
|
+
headers: { "set-cookie": sessionCookie(verdict.session, cookieOptions(req, ctx, webAuth)) },
|
|
366
|
+
body: { ok: true, disabled: false, sessionId: verdict.id, expiresAt: new Date(verdict.expiresAt).toISOString() },
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** GET /v1/web/session → {ok, expiresAt};无 cookie 时 Bearer 也算登录。滑动续期会重下 cookie。 */
|
|
371
|
+
export function handleWebSession(req, ctx) {
|
|
372
|
+
const webAuth = ctx.webAuth;
|
|
373
|
+
const found = webAuth.validate(webAuth.cookieValue(req));
|
|
374
|
+
if (found) {
|
|
375
|
+
const headers = found.renewed
|
|
376
|
+
? { "set-cookie": sessionCookie(webAuth.cookieValue(req), cookieOptions(req, ctx, webAuth)) }
|
|
377
|
+
: {};
|
|
378
|
+
return {
|
|
379
|
+
status: 200,
|
|
380
|
+
headers,
|
|
381
|
+
body: { ok: true, sessionId: found.id, expiresAt: new Date(found.expiresAt).toISOString() },
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
if (webAuth.authDisabled) return { status: 200, headers: {}, body: { ok: true, expiresAt: null, authDisabled: true } };
|
|
385
|
+
const bearer = /^Bearer\s+(.+)$/i.exec(String(headerValue(req?.headers, "authorization") ?? ""));
|
|
386
|
+
if (bearer && webAuth.token && equalSecret(bearer[1].trim(), webAuth.token)) {
|
|
387
|
+
return { status: 200, headers: {}, body: { ok: true, expiresAt: null } };
|
|
388
|
+
}
|
|
389
|
+
return { status: 200, headers: {}, body: { ok: false, expiresAt: null } };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** POST /v1/web/logout → 删会话 + 清 cookie(cookie 鉴权下仍需 CSRF)。 */
|
|
393
|
+
export function handleWebLogout(req, ctx) {
|
|
394
|
+
const webAuth = ctx.webAuth;
|
|
395
|
+
const cookie = webAuth.cookieValue(req);
|
|
396
|
+
const found = cookie ? webAuth.validate(cookie) : null;
|
|
397
|
+
const csrf = checkCsrf(req, found);
|
|
398
|
+
if (!csrf.ok) return { status: 403, headers: {}, body: errorBody("csrf", "x-pi-csrf header required") };
|
|
399
|
+
webAuth.logout(cookie);
|
|
400
|
+
return {
|
|
401
|
+
status: 200,
|
|
402
|
+
headers: { "set-cookie": clearSessionCookie({ secure: ctx?.secure ?? isSecureRequest(req) }) },
|
|
403
|
+
body: { ok: true },
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** GET /v1/web/csrf → {csrf, expiresAt}(与 cookie 绑定的 double-submit 值)。 */
|
|
408
|
+
export function handleWebCsrf(req, ctx) {
|
|
409
|
+
const webAuth = ctx.webAuth;
|
|
410
|
+
const found = webAuth.validate(webAuth.cookieValue(req));
|
|
411
|
+
if (!found) {
|
|
412
|
+
if (webAuth.authDisabled) return { status: 200, headers: {}, body: { csrf: null, authDisabled: true } };
|
|
413
|
+
return { status: 401, headers: {}, body: errorBody("unauthorized", "unauthorized") };
|
|
414
|
+
}
|
|
415
|
+
return {
|
|
416
|
+
status: 200,
|
|
417
|
+
headers: {},
|
|
418
|
+
body: { csrf: found.csrf, sessionId: found.id, expiresAt: new Date(found.expiresAt).toISOString() },
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** GET /v1/web/sessions → {ok, sessions};需 cookie 会话或 ctx.primary(主令牌已通过 Bearer 校验)。 */
|
|
423
|
+
export function handleWebSessionsList(req, ctx) {
|
|
424
|
+
const webAuth = ctx.webAuth;
|
|
425
|
+
const found = webAuth.validate(webAuth.cookieValue(req));
|
|
426
|
+
if (!found && !ctx.primary) {
|
|
427
|
+
if (webAuth.authDisabled) return { status: 200, headers: {}, body: { ok: true, sessions: webAuth.listSessions() } };
|
|
428
|
+
return { status: 401, headers: {}, body: errorBody("unauthorized", "unauthorized") };
|
|
429
|
+
}
|
|
430
|
+
return { status: 200, headers: {}, body: { ok: true, sessions: webAuth.listSessions(), currentId: found?.id ?? null } };
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** DELETE /v1/web/sessions/:id → 吊销一条;吊销自己时顺带清 cookie。 */
|
|
434
|
+
export function handleWebSessionRevoke(req, ctx) {
|
|
435
|
+
const webAuth = ctx.webAuth;
|
|
436
|
+
const found = webAuth.validate(webAuth.cookieValue(req));
|
|
437
|
+
if (!found && !ctx.primary) {
|
|
438
|
+
return { status: 401, headers: {}, body: errorBody("unauthorized", "unauthorized") };
|
|
439
|
+
}
|
|
440
|
+
if (found) {
|
|
441
|
+
const csrf = checkCsrf(req, found);
|
|
442
|
+
if (!csrf.ok) return { status: 403, headers: {}, body: errorBody("csrf", "x-pi-csrf header required") };
|
|
443
|
+
}
|
|
444
|
+
const id = ctx.params?.id ?? null;
|
|
445
|
+
if (!id) return { status: 400, headers: {}, body: errorBody("invalid_session_id", "session id is required") };
|
|
446
|
+
const revoked = webAuth.revokeSession(id);
|
|
447
|
+
if (!revoked) return { status: 404, headers: {}, body: errorBody("session_not_found", "unknown session id") };
|
|
448
|
+
const headers = id === found?.id ? { "set-cookie": clearSessionCookie({ secure: ctx?.secure ?? isSecureRequest(req) }) } : {};
|
|
449
|
+
return { status: 200, headers, body: { ok: true, id } };
|
|
450
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
[Unit]
|
|
2
|
+
Description=pi-hub (minimal HTTP+SSE hub over pi RPC sessions)
|
|
3
|
+
After=network-online.target
|
|
4
|
+
Wants=network-online.target
|
|
5
|
+
|
|
6
|
+
[Service]
|
|
7
|
+
Type=simple
|
|
8
|
+
WorkingDirectory=%h/pi-hub-suite/pi-hub
|
|
9
|
+
ExecStart=%h/.local/share/fnm/node-versions/v24.22.0/installation/bin/node %h/pi-hub-suite/pi-hub/bin/pi-hub.mjs serve
|
|
10
|
+
Restart=on-failure
|
|
11
|
+
RestartSec=3
|
|
12
|
+
# systemd 默认 PATH 里没有 ~/.pi/agent/bin(重启后 spawn pi ENOENT),显式补上
|
|
13
|
+
Environment=PATH=%h/.pi/agent/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
|
14
|
+
Environment=PI_HUB_PORT=6768
|
|
15
|
+
# 只监听局域网/校园网地址时可改成具体 IP
|
|
16
|
+
Environment=PI_HUB_HOST=0.0.0.0
|
|
17
|
+
# 每个 pi 子进程 200-300MB,按机器内存调
|
|
18
|
+
Environment=PI_HUB_MAX_LIVE=5
|
|
19
|
+
Environment=PI_HUB_IDLE_MS=600000
|
|
20
|
+
|
|
21
|
+
[Install]
|
|
22
|
+
WantedBy=default.target
|