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
package/src/otp.mjs
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// 一次性登录码(PLAN M4):主机 TTY 生成、2 min TTL、单次消费、可选 meta(如 UA hash)绑定。
|
|
2
|
+
// 纯模块:零依赖、不碰 HTTP;只用 node: 内置模块。接线见 W1(src/server.mjs 的 /v1/web/otp)。
|
|
3
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
4
|
+
|
|
5
|
+
/** Crockford base32:去掉 I/L/O/U,避免 0/O、1/I/L 认错。 */
|
|
6
|
+
export const CROCKFORD_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
7
|
+
export const OTP_CODE_LENGTH = 8;
|
|
8
|
+
/** 展示为 XXXX-XXXX。 */
|
|
9
|
+
export const OTP_CODE_GROUP = 4;
|
|
10
|
+
export const OTP_TTL_MS = 2 * 60 * 1000;
|
|
11
|
+
export const OTP_MAX_FAILURES = 5;
|
|
12
|
+
export const OTP_MAX_ENTRIES = 64;
|
|
13
|
+
|
|
14
|
+
const ALPHABET_SET = new Set(CROCKFORD_ALPHABET);
|
|
15
|
+
|
|
16
|
+
function sha256hex(data) {
|
|
17
|
+
return createHash("sha256").update(data).digest("hex");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 用户输入 → 内部码:去掉 `-` 与空白、转大写。
|
|
22
|
+
* 不做 0/O、1/I/L 的模糊映射:字符集外的输入直接当未知码处理,避免把错码猜成对码。
|
|
23
|
+
*/
|
|
24
|
+
export function normalizeOtpCode(input) {
|
|
25
|
+
if (typeof input !== "string") return "";
|
|
26
|
+
return input.replace(/[\s-]/g, "").toUpperCase();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 内部码 → 展示形式 XXXX-XXXX。 */
|
|
30
|
+
export function formatOtpCode(code) {
|
|
31
|
+
const normalized = normalizeOtpCode(code);
|
|
32
|
+
const groups = [];
|
|
33
|
+
for (let i = 0; i < normalized.length; i += OTP_CODE_GROUP) {
|
|
34
|
+
groups.push(normalized.slice(i, i + OTP_CODE_GROUP));
|
|
35
|
+
}
|
|
36
|
+
return groups.join("-");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 8 位 Crockford base32:每字节 % 32(256 是 32 的整数倍,无取模偏置)→ 40 bit 随机码。 */
|
|
40
|
+
function generateCode() {
|
|
41
|
+
const bytes = randomBytes(OTP_CODE_LENGTH);
|
|
42
|
+
let code = "";
|
|
43
|
+
for (const byte of bytes) code += CROCKFORD_ALPHABET[byte % 32];
|
|
44
|
+
return code;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function isValidCode(normalized) {
|
|
48
|
+
if (normalized.length !== OTP_CODE_LENGTH) return false;
|
|
49
|
+
for (const char of normalized) if (!ALPHABET_SET.has(char)) return false;
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function sameValue(a, b) {
|
|
54
|
+
if (a === b) return true;
|
|
55
|
+
if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
|
|
56
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 绑定键全部命中才算通过;记录有绑定但调用方没给 meta → 拒绝(fail closed)。 */
|
|
60
|
+
function metaMatches(bound, provided) {
|
|
61
|
+
const keys = Object.keys(bound ?? {});
|
|
62
|
+
if (keys.length === 0) return true;
|
|
63
|
+
if (provided === null || typeof provided !== "object") return false;
|
|
64
|
+
return keys.every((key) => sameValue(bound[key], provided[key]));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 内存态 OTP 存储。内部只留 sha256(code) 与元数据,明文码仅在 `create()` 返回值里出现一次。
|
|
69
|
+
* 淘汰口径:先删已过期,再按插入顺序(最旧)删到 maxEntries 以内。
|
|
70
|
+
*/
|
|
71
|
+
export function createOtpStore({
|
|
72
|
+
now = Date.now,
|
|
73
|
+
ttlMs = OTP_TTL_MS,
|
|
74
|
+
maxFailures = OTP_MAX_FAILURES,
|
|
75
|
+
maxEntries = OTP_MAX_ENTRIES,
|
|
76
|
+
} = {}) {
|
|
77
|
+
/** sha256(code) → { id, createdAt, expiresAt, usedAt, failures, meta },Map 插入顺序即生成顺序。 */
|
|
78
|
+
const entries = new Map();
|
|
79
|
+
let seq = 0;
|
|
80
|
+
|
|
81
|
+
function prune() {
|
|
82
|
+
const at = now();
|
|
83
|
+
let removed = 0;
|
|
84
|
+
for (const [hash, record] of entries) {
|
|
85
|
+
if (at >= record.expiresAt) {
|
|
86
|
+
entries.delete(hash);
|
|
87
|
+
removed += 1;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return removed;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function enforceMaxEntries(keepHash) {
|
|
94
|
+
prune();
|
|
95
|
+
while (entries.size > maxEntries) {
|
|
96
|
+
let victim = null;
|
|
97
|
+
for (const hash of entries.keys()) {
|
|
98
|
+
if (hash !== keepHash) {
|
|
99
|
+
victim = hash;
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (victim === null) break;
|
|
104
|
+
entries.delete(victim);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 生成一次性码。返回值里的 `code` 是明文展示形式,只此一次。 */
|
|
109
|
+
function create({ meta = {} } = {}) {
|
|
110
|
+
const code = generateCode();
|
|
111
|
+
const hash = sha256hex(code);
|
|
112
|
+
const createdAt = now();
|
|
113
|
+
seq += 1;
|
|
114
|
+
const record = {
|
|
115
|
+
id: `otp_${seq.toString(36)}${randomBytes(4).toString("hex")}`,
|
|
116
|
+
createdAt,
|
|
117
|
+
expiresAt: createdAt + ttlMs,
|
|
118
|
+
usedAt: null,
|
|
119
|
+
failures: 0,
|
|
120
|
+
meta: { ...meta },
|
|
121
|
+
};
|
|
122
|
+
entries.set(hash, record);
|
|
123
|
+
enforceMaxEntries(hash);
|
|
124
|
+
return { id: record.id, code: formatOtpCode(code), expiresAt: record.expiresAt };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 兑换。reason 取值:`unknown`(不存在/格式非法)、`used`、`expired`、
|
|
129
|
+
* `too_many`(该码失败次数用尽,码作废)、`meta_mismatch`(绑定不符,计入 failures)。
|
|
130
|
+
*/
|
|
131
|
+
function redeem(code, { meta } = {}) {
|
|
132
|
+
const normalized = normalizeOtpCode(code);
|
|
133
|
+
if (!isValidCode(normalized)) return { ok: false, reason: "unknown" };
|
|
134
|
+
const record = entries.get(sha256hex(normalized));
|
|
135
|
+
if (!record) return { ok: false, reason: "unknown" };
|
|
136
|
+
if (record.failures >= maxFailures) return { ok: false, reason: "too_many" };
|
|
137
|
+
if (record.usedAt !== null) return { ok: false, reason: "used" };
|
|
138
|
+
if (now() >= record.expiresAt) return { ok: false, reason: "expired" };
|
|
139
|
+
if (!metaMatches(record.meta, meta)) {
|
|
140
|
+
record.failures += 1;
|
|
141
|
+
return { ok: false, reason: record.failures >= maxFailures ? "too_many" : "meta_mismatch" };
|
|
142
|
+
}
|
|
143
|
+
record.usedAt = now();
|
|
144
|
+
return { ok: true, meta: { ...record.meta }, expiresAt: record.expiresAt };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** 管理视图:不含明文码、不含 hash。 */
|
|
148
|
+
function list() {
|
|
149
|
+
const at = now();
|
|
150
|
+
return [...entries.values()].map((record) => ({
|
|
151
|
+
id: record.id,
|
|
152
|
+
createdAt: record.createdAt,
|
|
153
|
+
expiresAt: record.expiresAt,
|
|
154
|
+
usedAt: record.usedAt,
|
|
155
|
+
failures: record.failures,
|
|
156
|
+
expired: at >= record.expiresAt,
|
|
157
|
+
meta: { ...record.meta },
|
|
158
|
+
}));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return { create, redeem, list, prune };
|
|
162
|
+
}
|
package/src/pairing.mjs
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
// 设备配对:SSH/TTY 一次性批准 + 设备令牌 + ECDSA 签名校验。
|
|
2
|
+
// 协议与存储契约见 .pi/plans/pairing/PLAN.md §2/§3。只用 Node 内置模块。
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import {
|
|
6
|
+
createHash,
|
|
7
|
+
createPublicKey,
|
|
8
|
+
randomBytes,
|
|
9
|
+
randomUUID,
|
|
10
|
+
timingSafeEqual,
|
|
11
|
+
verify as cryptoVerify,
|
|
12
|
+
} from "node:crypto";
|
|
13
|
+
import { CONFIG_DIR } from "./config.mjs";
|
|
14
|
+
|
|
15
|
+
/** 配对码 TTL:5 min。 */
|
|
16
|
+
export const PAIR_TTL_MS = 5 * 60 * 1000;
|
|
17
|
+
/** 已批准后 token 交付窗口:首次取走后 60 s 内可重取,之后 410。 */
|
|
18
|
+
export const PAIR_TOKEN_GRACE_MS = 60 * 1000;
|
|
19
|
+
/** 配对申请限速:每 IP 每 60 s 最多 10 次。 */
|
|
20
|
+
export const PAIR_RATE_LIMIT = 10;
|
|
21
|
+
export const PAIR_RATE_WINDOW_MS = 60 * 1000;
|
|
22
|
+
/** 签名时间戳允许偏差:±180 s。 */
|
|
23
|
+
export const SIGNATURE_SKEW_MS = 180 * 1000;
|
|
24
|
+
/** nonce 去重窗口:10 min。 */
|
|
25
|
+
export const NONCE_TTL_MS = 10 * 60 * 1000;
|
|
26
|
+
/** lastSeenAt 落盘节流:≥60 s。 */
|
|
27
|
+
export const LAST_SEEN_THROTTLE_MS = 60 * 1000;
|
|
28
|
+
export const DEVICES_VERSION = 1;
|
|
29
|
+
/** 过期很久的 pending 记录从内存里清掉(保留 10 min 供 status 查询到 expired)。 */
|
|
30
|
+
const PENDING_GC_MS = 10 * 60 * 1000;
|
|
31
|
+
|
|
32
|
+
export class PairingError extends Error {
|
|
33
|
+
constructor(status, code, message) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.status = status;
|
|
36
|
+
this.code = code;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 批准动作只允许来自「主机侧的人」:SSH 会话、SSH 的 tty、或主机本地终端。
|
|
42
|
+
* 手机端不跑 SSH 客户端,所以这条判定就是「人在这台机器上」。
|
|
43
|
+
*/
|
|
44
|
+
export function isTrustedApprovalChannel(env = process.env, stdin = process.stdin) {
|
|
45
|
+
return Boolean(env.SSH_CONNECTION || env.SSH_TTY || stdin?.isTTY === true);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function sha256hex(data) {
|
|
49
|
+
return createHash("sha256").update(data).digest("hex");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function headerValue(headers, name) {
|
|
53
|
+
const value = headers?.[name];
|
|
54
|
+
return Array.isArray(value) ? value[0] : value;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 设备条目对外形状(不含公钥/token hash)。 */
|
|
58
|
+
function publicDevice(device) {
|
|
59
|
+
return {
|
|
60
|
+
id: device.id,
|
|
61
|
+
name: device.name,
|
|
62
|
+
platform: device.platform,
|
|
63
|
+
createdAt: device.createdAt,
|
|
64
|
+
lastSeenAt: device.lastSeenAt ?? null,
|
|
65
|
+
revoked: device.revoked === true,
|
|
66
|
+
fingerprintShort: String(device.fingerprint ?? "").slice(0, 16),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export { publicDevice };
|
|
71
|
+
|
|
72
|
+
export class PairingStore {
|
|
73
|
+
constructor({ configDir = CONFIG_DIR, now = () => Date.now(), log = () => {} } = {}) {
|
|
74
|
+
this.configDir = configDir;
|
|
75
|
+
this.devicesFile = path.join(configDir, "devices.json");
|
|
76
|
+
this.now = now;
|
|
77
|
+
this.log = log;
|
|
78
|
+
/** pairId → 待批准/已批准请求(只在内存,不落盘) */
|
|
79
|
+
this.pending = new Map();
|
|
80
|
+
/** ip → 最近 60 s 内的申请时间戳 */
|
|
81
|
+
this.rate = new Map();
|
|
82
|
+
/** `${deviceId}:${nonce}` → 首次出现时间 */
|
|
83
|
+
this.nonces = new Map();
|
|
84
|
+
/** devices.json 按 mtime 重载,外部 revoke/手改也生效 */
|
|
85
|
+
this.cache = { mtimeMs: -1, size: -1, devices: [] };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ---------- 限速 / 清理 ----------
|
|
89
|
+
|
|
90
|
+
/** 返回 true 表示该 IP 本轮被限速(调用即计数)。 */
|
|
91
|
+
rateLimited(ip) {
|
|
92
|
+
const now = this.now();
|
|
93
|
+
const key = ip || "unknown";
|
|
94
|
+
const hits = (this.rate.get(key) ?? []).filter((t) => now - t < PAIR_RATE_WINDOW_MS);
|
|
95
|
+
if (hits.length >= PAIR_RATE_LIMIT) {
|
|
96
|
+
this.rate.set(key, hits);
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
hits.push(now);
|
|
100
|
+
this.rate.set(key, hits);
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
sweep() {
|
|
105
|
+
const now = this.now();
|
|
106
|
+
for (const [pairId, p] of this.pending) {
|
|
107
|
+
const done = p.status !== "pending" || now > p.expiresAt;
|
|
108
|
+
if (done && now - p.createdAt > PAIR_TTL_MS + PENDING_GC_MS) this.pending.delete(pairId);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
pruneNonces() {
|
|
113
|
+
const now = this.now();
|
|
114
|
+
for (const [key, at] of this.nonces) {
|
|
115
|
+
if (now - at > NONCE_TTL_MS) this.nonces.delete(key);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ---------- 配对请求 ----------
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 手机端发起配对:只接受 EC P-256 的 SPKI DER 公钥(base64)。
|
|
123
|
+
* 返回 {pairId, code, expiresAt};expiresAt 为 ISO 时间串(与 /v1/sessions 的 createdAt 一致)。
|
|
124
|
+
*/
|
|
125
|
+
createRequest({ name, platform, publicKey }) {
|
|
126
|
+
const deviceName = typeof name === "string" ? name.trim() : "";
|
|
127
|
+
const devicePlatform = typeof platform === "string" ? platform.trim() : "";
|
|
128
|
+
if (!deviceName || deviceName.length > 64) {
|
|
129
|
+
throw new PairingError(400, "invalid_name", "name must be a non-empty string (≤64 chars)");
|
|
130
|
+
}
|
|
131
|
+
if (!devicePlatform || devicePlatform.length > 64) {
|
|
132
|
+
throw new PairingError(400, "invalid_platform", "platform must be a non-empty string (≤64 chars)");
|
|
133
|
+
}
|
|
134
|
+
let key;
|
|
135
|
+
let der;
|
|
136
|
+
try {
|
|
137
|
+
der = Buffer.from(String(publicKey ?? ""), "base64");
|
|
138
|
+
if (!der.length) throw new Error("empty");
|
|
139
|
+
key = createPublicKey({ key: der, format: "der", type: "spki" });
|
|
140
|
+
} catch {
|
|
141
|
+
throw new PairingError(400, "invalid_public_key", "publicKey must be base64 X.509 (SPKI) DER");
|
|
142
|
+
}
|
|
143
|
+
if (key.asymmetricKeyType !== "ec" || key.asymmetricKeyDetails?.namedCurve !== "prime256v1") {
|
|
144
|
+
throw new PairingError(400, "invalid_public_key", "publicKey must be an EC P-256 key");
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
this.sweep();
|
|
148
|
+
const now = this.now();
|
|
149
|
+
const pairId = randomUUID();
|
|
150
|
+
let code = null;
|
|
151
|
+
for (let i = 0; i < 20 && !code; i++) {
|
|
152
|
+
const candidate = String(Math.floor(100000 + Math.random() * 900000));
|
|
153
|
+
if (![...this.pending.values()].some((p) => p.code === candidate && p.status === "pending")) code = candidate;
|
|
154
|
+
}
|
|
155
|
+
if (!code) throw new PairingError(503, "pair_code_exhausted", "too many pending pairing requests");
|
|
156
|
+
|
|
157
|
+
const expiresAt = now + PAIR_TTL_MS;
|
|
158
|
+
this.pending.set(pairId, {
|
|
159
|
+
pairId,
|
|
160
|
+
code,
|
|
161
|
+
name: deviceName,
|
|
162
|
+
platform: devicePlatform,
|
|
163
|
+
publicKeyPem: key.export({ type: "spki", format: "pem" }),
|
|
164
|
+
fingerprint: sha256hex(der),
|
|
165
|
+
createdAt: now,
|
|
166
|
+
expiresAt,
|
|
167
|
+
status: "pending",
|
|
168
|
+
deviceId: null,
|
|
169
|
+
token: null,
|
|
170
|
+
tokenFirstReadAt: null,
|
|
171
|
+
});
|
|
172
|
+
return { pairId, code, expiresAt: new Date(expiresAt).toISOString() };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
findByCode(code) {
|
|
176
|
+
const needle = String(code ?? "").trim();
|
|
177
|
+
if (!needle) return null;
|
|
178
|
+
let found = null;
|
|
179
|
+
for (const p of this.pending.values()) {
|
|
180
|
+
if (p.code === needle && (!found || p.createdAt > found.createdAt)) found = p;
|
|
181
|
+
}
|
|
182
|
+
return found;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** 待批准列表(CLI `pi-hub pair`);activity 时间都是 ISO 串。 */
|
|
186
|
+
listPending() {
|
|
187
|
+
this.sweep();
|
|
188
|
+
const now = this.now();
|
|
189
|
+
return [...this.pending.values()]
|
|
190
|
+
.filter((p) => p.status === "pending" && now <= p.expiresAt)
|
|
191
|
+
.sort((a, b) => a.createdAt - b.createdAt)
|
|
192
|
+
.map((p) => ({
|
|
193
|
+
pairId: p.pairId,
|
|
194
|
+
code: p.code,
|
|
195
|
+
name: p.name,
|
|
196
|
+
platform: p.platform,
|
|
197
|
+
createdAt: new Date(p.createdAt).toISOString(),
|
|
198
|
+
expiresAt: new Date(p.expiresAt).toISOString(),
|
|
199
|
+
status: p.status,
|
|
200
|
+
}));
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** 手机端轮询:token 只交付一次(首取后 60 s 内可重取,之后 410)。 */
|
|
204
|
+
status(pairId) {
|
|
205
|
+
this.sweep();
|
|
206
|
+
const p = this.pending.get(String(pairId ?? ""));
|
|
207
|
+
if (!p) throw new PairingError(404, "unknown_pair", `unknown pairId ${pairId}`);
|
|
208
|
+
const now = this.now();
|
|
209
|
+
if (p.status === "pending") return { status: now > p.expiresAt ? "expired" : "pending" };
|
|
210
|
+
if (p.status === "denied") return { status: "denied" };
|
|
211
|
+
if (p.tokenFirstReadAt === null) p.tokenFirstReadAt = now;
|
|
212
|
+
else if (now - p.tokenFirstReadAt > PAIR_TOKEN_GRACE_MS) {
|
|
213
|
+
throw new PairingError(410, "pair_token_expired", "pairing token was already delivered");
|
|
214
|
+
}
|
|
215
|
+
return { status: "approved", deviceId: p.deviceId, token: p.token, deviceName: p.name };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** 批准:生成 deviceId + 32 B token,写 devices.json(0600),明文 token 只回给调用方一次。 */
|
|
219
|
+
approveCode(code) {
|
|
220
|
+
this.sweep();
|
|
221
|
+
const p = this.findByCode(code);
|
|
222
|
+
if (!p) throw new PairingError(404, "unknown_pair_code", `no pending pairing with code ${code}`);
|
|
223
|
+
if (p.status === "approved") throw new PairingError(409, "already_approved", "pairing was already approved");
|
|
224
|
+
if (p.status === "denied") throw new PairingError(409, "already_denied", "pairing was already denied");
|
|
225
|
+
if (this.now() > p.expiresAt) throw new PairingError(410, "pair_expired", "pairing code expired");
|
|
226
|
+
|
|
227
|
+
const now = this.now();
|
|
228
|
+
const token = randomBytes(32).toString("base64url");
|
|
229
|
+
const device = {
|
|
230
|
+
id: randomUUID(),
|
|
231
|
+
name: p.name,
|
|
232
|
+
platform: p.platform,
|
|
233
|
+
publicKeyPem: p.publicKeyPem,
|
|
234
|
+
tokenSha256: sha256hex(token),
|
|
235
|
+
fingerprint: p.fingerprint,
|
|
236
|
+
createdAt: new Date(now).toISOString(),
|
|
237
|
+
lastSeenAt: null,
|
|
238
|
+
revoked: false,
|
|
239
|
+
};
|
|
240
|
+
const devices = this.loadDevices();
|
|
241
|
+
devices.push(device);
|
|
242
|
+
this.saveDevices(devices);
|
|
243
|
+
|
|
244
|
+
p.status = "approved";
|
|
245
|
+
p.deviceId = device.id;
|
|
246
|
+
p.token = token;
|
|
247
|
+
p.tokenFirstReadAt = null;
|
|
248
|
+
return { device, token };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
denyCode(code) {
|
|
252
|
+
this.sweep();
|
|
253
|
+
const p = this.findByCode(code);
|
|
254
|
+
if (!p) throw new PairingError(404, "unknown_pair_code", `no pending pairing with code ${code}`);
|
|
255
|
+
if (p.status === "approved") throw new PairingError(409, "already_approved", "pairing was already approved");
|
|
256
|
+
if (p.status === "denied") throw new PairingError(409, "already_denied", "pairing was already denied");
|
|
257
|
+
p.status = "denied";
|
|
258
|
+
return { status: "denied" };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// ---------- devices.json ----------
|
|
262
|
+
|
|
263
|
+
loadDevices() {
|
|
264
|
+
let stat;
|
|
265
|
+
try {
|
|
266
|
+
stat = fs.statSync(this.devicesFile);
|
|
267
|
+
} catch {
|
|
268
|
+
this.cache = { mtimeMs: -1, size: -1, devices: [] };
|
|
269
|
+
return this.cache.devices;
|
|
270
|
+
}
|
|
271
|
+
if (stat.mtimeMs === this.cache.mtimeMs && stat.size === this.cache.size) return this.cache.devices;
|
|
272
|
+
const raw = fs.readFileSync(this.devicesFile, "utf8");
|
|
273
|
+
let parsed;
|
|
274
|
+
try {
|
|
275
|
+
parsed = JSON.parse(raw);
|
|
276
|
+
} catch {
|
|
277
|
+
throw new PairingError(500, "devices_file_corrupt", `devices.json is not valid JSON: ${this.devicesFile}`);
|
|
278
|
+
}
|
|
279
|
+
const devices = Array.isArray(parsed?.devices) ? parsed.devices : [];
|
|
280
|
+
this.cache = { mtimeMs: stat.mtimeMs, size: stat.size, devices };
|
|
281
|
+
return devices;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
saveDevices(devices) {
|
|
285
|
+
fs.mkdirSync(this.configDir, { recursive: true, mode: 0o700 });
|
|
286
|
+
const data = `${JSON.stringify({ version: DEVICES_VERSION, devices }, null, 2)}\n`;
|
|
287
|
+
const tmp = `${this.devicesFile}.${process.pid}.tmp`;
|
|
288
|
+
fs.writeFileSync(tmp, data, { mode: 0o600 });
|
|
289
|
+
fs.chmodSync(tmp, 0o600);
|
|
290
|
+
fs.renameSync(tmp, this.devicesFile);
|
|
291
|
+
const stat = fs.statSync(this.devicesFile);
|
|
292
|
+
this.cache = { mtimeMs: stat.mtimeMs, size: stat.size, devices };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
listDevices() {
|
|
296
|
+
return this.loadDevices().map(publicDevice);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** 按 id 或 name 吊销(name 必须是精确匹配;重名时要求用 id)。 */
|
|
300
|
+
revokeDevice(idOrName) {
|
|
301
|
+
const needle = String(idOrName ?? "").trim();
|
|
302
|
+
if (!needle) throw new PairingError(400, "invalid_device", "device id or name is required");
|
|
303
|
+
const devices = this.loadDevices();
|
|
304
|
+
// id 支持唯一前缀(手机端只显示前 8 位,UI 提示里的就是前缀,别让用户去翻全 id)。
|
|
305
|
+
const byIdExact = devices.find((d) => d.id === needle);
|
|
306
|
+
const byIdPrefix = needle.length >= 6 ? devices.filter((d) => d.id.startsWith(needle)) : [];
|
|
307
|
+
const byName = devices.filter((d) => d.name === needle);
|
|
308
|
+
if (!byIdExact && byIdPrefix.length > 1) {
|
|
309
|
+
throw new PairingError(409, "ambiguous_device", `${byIdPrefix.length} devices match id prefix ${needle}; use more characters`);
|
|
310
|
+
}
|
|
311
|
+
const byId = byIdExact ?? byIdPrefix[0];
|
|
312
|
+
if (!byId && byName.length > 1) {
|
|
313
|
+
throw new PairingError(409, "ambiguous_device", `${byName.length} devices named ${needle}; revoke by id`);
|
|
314
|
+
}
|
|
315
|
+
const device = byId ?? byName[0];
|
|
316
|
+
if (!device) throw new PairingError(404, "unknown_device", `no device matches ${needle}`);
|
|
317
|
+
if (!device.revoked) {
|
|
318
|
+
device.revoked = true;
|
|
319
|
+
device.revokedAt = new Date(this.now()).toISOString();
|
|
320
|
+
this.saveDevices(devices);
|
|
321
|
+
}
|
|
322
|
+
return publicDevice(device);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** 设备请求成功后刷新 lastSeenAt(节流 ≥60 s)。 */
|
|
326
|
+
touchDevice(deviceId) {
|
|
327
|
+
const devices = this.loadDevices();
|
|
328
|
+
const device = devices.find((d) => d.id === deviceId);
|
|
329
|
+
if (!device) return;
|
|
330
|
+
const now = this.now();
|
|
331
|
+
const last = device.lastSeenAt ? Date.parse(device.lastSeenAt) : NaN;
|
|
332
|
+
if (Number.isFinite(last) && now - last < LAST_SEEN_THROTTLE_MS) return;
|
|
333
|
+
device.lastSeenAt = new Date(now).toISOString();
|
|
334
|
+
this.saveDevices(devices);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// ---------- 设备签名 ----------
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* 校验设备令牌 + 签名。校验顺序逐字照 PLAN §2:
|
|
341
|
+
* token 命中设备 → 未吊销 → ts 偏差 → nonce 未用 → 公钥验签。
|
|
342
|
+
* @returns {{ok:true, device:object} | {ok:false, code:string, message:string}}
|
|
343
|
+
*/
|
|
344
|
+
verifyDeviceSignature({ method = "GET", path: reqPath = "/", headers = {}, rawBody = Buffer.alloc(0), token } = {}) {
|
|
345
|
+
const fail = (code, message) => ({ ok: false, code, message });
|
|
346
|
+
if (!token) return fail("bad_signature", "missing bearer token");
|
|
347
|
+
|
|
348
|
+
// token 命中设备:恒时比较 sha256(token) 与落盘的 tokenSha256(不提前 break)。
|
|
349
|
+
const givenHash = Buffer.from(sha256hex(token), "utf8");
|
|
350
|
+
let device = null;
|
|
351
|
+
for (const candidate of this.loadDevices()) {
|
|
352
|
+
const stored = Buffer.from(String(candidate.tokenSha256 ?? ""), "utf8");
|
|
353
|
+
if (stored.length === givenHash.length && timingSafeEqual(stored, givenHash)) device = candidate;
|
|
354
|
+
}
|
|
355
|
+
if (!device) return fail("bad_signature", "unknown device token");
|
|
356
|
+
|
|
357
|
+
const deviceId = headerValue(headers, "x-pi-device");
|
|
358
|
+
if (!deviceId || String(deviceId) !== device.id) {
|
|
359
|
+
return fail("bad_signature", "x-pi-device does not match the device token");
|
|
360
|
+
}
|
|
361
|
+
// 吊销检查每次请求都做(不在缓存里短路)
|
|
362
|
+
if (device.revoked === true) return fail("device_revoked", `device ${device.name ?? device.id} is revoked`);
|
|
363
|
+
|
|
364
|
+
const tsText = String(headerValue(headers, "x-pi-ts") ?? "");
|
|
365
|
+
if (!/^\d+$/.test(tsText)) return fail("bad_signature", "x-pi-ts must be epoch millis");
|
|
366
|
+
if (Math.abs(this.now() - Number(tsText)) > SIGNATURE_SKEW_MS) {
|
|
367
|
+
return fail("stale_timestamp", "x-pi-ts is outside ±180 s");
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const nonce = String(headerValue(headers, "x-pi-nonce") ?? "");
|
|
371
|
+
if (!/^[A-Za-z0-9_-]{16,64}$/.test(nonce)) return fail("bad_signature", "x-pi-nonce must be base64url");
|
|
372
|
+
this.pruneNonces();
|
|
373
|
+
const nonceKey = `${device.id}:${nonce}`;
|
|
374
|
+
if (this.nonces.has(nonceKey)) return fail("replay", "nonce was already used");
|
|
375
|
+
this.nonces.set(nonceKey, this.now());
|
|
376
|
+
|
|
377
|
+
const signature = String(headerValue(headers, "x-pi-sig") ?? "");
|
|
378
|
+
if (!signature) return fail("bad_signature", "missing x-pi-sig");
|
|
379
|
+
const payload = [
|
|
380
|
+
"PIHUB1",
|
|
381
|
+
String(method).toUpperCase(),
|
|
382
|
+
reqPath,
|
|
383
|
+
tsText,
|
|
384
|
+
nonce,
|
|
385
|
+
sha256hex(rawBody),
|
|
386
|
+
].join("\n");
|
|
387
|
+
|
|
388
|
+
let key;
|
|
389
|
+
try {
|
|
390
|
+
key = createPublicKey(device.publicKeyPem);
|
|
391
|
+
} catch {
|
|
392
|
+
return fail("bad_signature", "stored public key is unreadable");
|
|
393
|
+
}
|
|
394
|
+
let verified = false;
|
|
395
|
+
try {
|
|
396
|
+
verified = cryptoVerify("sha256", Buffer.from(payload, "utf8"), key, Buffer.from(signature, "base64"));
|
|
397
|
+
} catch {
|
|
398
|
+
verified = false;
|
|
399
|
+
}
|
|
400
|
+
if (!verified) return fail("bad_signature", "signature does not verify");
|
|
401
|
+
return { ok: true, device };
|
|
402
|
+
}
|
|
403
|
+
}
|
package/src/pi-args.mjs
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { HOME, PI_BIN } from "./config.mjs";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* hub 启动 pi 时要显式加载的扩展。
|
|
7
|
+
*
|
|
8
|
+
* `--no-extensions` 会关掉全局扩展(loop/wechat/context-meter 等不该在手机上被触发),
|
|
9
|
+
* 但自定义 provider(本机 custom.ustc-pool / custom.nexavlinks-com)也是由扩展
|
|
10
|
+
* `better-custom-provider` 注册的 —— 不加载它,`--model custom.ustc-pool/ustc-dsf` 会报
|
|
11
|
+
* "Model not found"(实测)。
|
|
12
|
+
*
|
|
13
|
+
* 覆盖:PI_HUB_EXTENSIONS=/path/a.ts:/path/b.ts(冒号分隔)。
|
|
14
|
+
*/
|
|
15
|
+
export function extensionPaths() {
|
|
16
|
+
const fromEnv = process.env.PI_HUB_EXTENSIONS;
|
|
17
|
+
if (fromEnv !== undefined) {
|
|
18
|
+
return fromEnv
|
|
19
|
+
.split(":")
|
|
20
|
+
.map((s) => s.trim())
|
|
21
|
+
.filter(Boolean);
|
|
22
|
+
}
|
|
23
|
+
const candidates = [
|
|
24
|
+
path.join(HOME, ".pi", "agent", "npm", "node_modules", "better-custom-provider", "index.ts"),
|
|
25
|
+
];
|
|
26
|
+
return candidates.filter((p) => {
|
|
27
|
+
try {
|
|
28
|
+
return fs.existsSync(p);
|
|
29
|
+
} catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @param {{cwd?:string, sessionId?:string, name?:string|null, model?:string|null, noSession?:boolean}} opts
|
|
37
|
+
* @returns {string[]}
|
|
38
|
+
*/
|
|
39
|
+
export function piArgs(opts = {}) {
|
|
40
|
+
const args = ["--mode", "rpc", "--no-extensions"];
|
|
41
|
+
for (const ext of extensionPaths()) args.push("-e", ext);
|
|
42
|
+
if (opts.noSession) args.push("--no-session");
|
|
43
|
+
// 不给 --session-dir:默认目录会按 cwd 分到 --<path>-- 子目录,与桌面 TUI 共用同一批会话。
|
|
44
|
+
// 显式传 --session-dir 会让 pi 把会话文件平铺在根目录(实测),手机与桌面就不共享了。
|
|
45
|
+
if (opts.sessionId) args.push("--session-id", opts.sessionId);
|
|
46
|
+
if (opts.name) args.push("--name", opts.name);
|
|
47
|
+
if (opts.model) args.push("--model", opts.model);
|
|
48
|
+
return args;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export { PI_BIN };
|