pi-hub-server 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +516 -2
- package/bin/pi-hub.mjs +473 -0
- package/docs/AUTH.md +260 -0
- package/package.json +45 -4
- package/src/config.mjs +60 -0
- package/src/listen.mjs +207 -0
- package/src/net-allow.mjs +134 -0
- package/src/otp.mjs +162 -0
- package/src/pairing.mjs +653 -0
- package/src/pi-args.mjs +74 -0
- package/src/pi-session.mjs +638 -0
- package/src/proxy-auth.mjs +238 -0
- package/src/registry.mjs +145 -0
- package/src/rpc-once.mjs +83 -0
- package/src/server.mjs +1603 -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 +40 -0
- package/web/app.js +1699 -0
- package/web/icons/icon.svg +7 -0
- package/web/index.html +131 -0
- package/web/manifest.webmanifest +20 -0
- package/web/style.css +982 -0
- package/web/sw.js +41 -0
package/src/pairing.mjs
ADDED
|
@@ -0,0 +1,653 @@
|
|
|
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
|
+
randomInt,
|
|
10
|
+
randomUUID,
|
|
11
|
+
timingSafeEqual,
|
|
12
|
+
verify as cryptoVerify,
|
|
13
|
+
} from "node:crypto";
|
|
14
|
+
import { CONFIG_DIR } from "./config.mjs";
|
|
15
|
+
|
|
16
|
+
/** 配对码 TTL:5 min。 */
|
|
17
|
+
export const PAIR_TTL_MS = 5 * 60 * 1000;
|
|
18
|
+
/** 已批准后 token 交付窗口:首次取走后 60 s 内可重取,之后 410。 */
|
|
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}$/;
|
|
28
|
+
/** 配对申请限速:每 IP 每 60 s 最多 10 次。 */
|
|
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;
|
|
36
|
+
export const PAIR_RATE_WINDOW_MS = 60 * 1000;
|
|
37
|
+
/** 签名时间戳允许偏差:±180 s。 */
|
|
38
|
+
export const SIGNATURE_SKEW_MS = 180 * 1000;
|
|
39
|
+
/** nonce 去重窗口:10 min。 */
|
|
40
|
+
export const NONCE_TTL_MS = 10 * 60 * 1000;
|
|
41
|
+
/** lastSeenAt 落盘节流:≥60 s。 */
|
|
42
|
+
export const LAST_SEEN_THROTTLE_MS = 60 * 1000;
|
|
43
|
+
export const DEVICES_VERSION = 1;
|
|
44
|
+
/** 过期很久的 pending 记录从内存里清掉(保留 10 min 供 status 查询到 expired)。 */
|
|
45
|
+
const PENDING_GC_MS = 10 * 60 * 1000;
|
|
46
|
+
|
|
47
|
+
export class PairingError extends Error {
|
|
48
|
+
constructor(status, code, message) {
|
|
49
|
+
super(message);
|
|
50
|
+
this.status = status;
|
|
51
|
+
this.code = code;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* 批准动作只允许来自「主机侧的人」:SSH 会话、SSH 的 tty、或主机本地终端。
|
|
57
|
+
* 手机端不跑 SSH 客户端,所以这条判定就是「人在这台机器上」。
|
|
58
|
+
*
|
|
59
|
+
* `force`(CLI `--force`)是**显式**放宽:给无 TTY 的主机侧通道(agent / 无头会话 / 裸管道)。
|
|
60
|
+
* 它只跳过「有终端」这一条,其余防线不变(本机 loopback 管理路由 + 主令牌 + 6 位码 + 5 min TTL)。
|
|
61
|
+
* 默认关;需要时逐次显式加 flag,不落任何持久配置。
|
|
62
|
+
*/
|
|
63
|
+
export function isTrustedApprovalChannel(env = process.env, stdin = process.stdin, { force = false } = {}) {
|
|
64
|
+
if (force) return true;
|
|
65
|
+
return Boolean(env.SSH_CONNECTION || env.SSH_TTY || stdin?.isTTY === true);
|
|
66
|
+
}
|
|
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
|
+
|
|
78
|
+
function sha256hex(data) {
|
|
79
|
+
return createHash("sha256").update(data).digest("hex");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function headerValue(headers, name) {
|
|
83
|
+
const value = headers?.[name];
|
|
84
|
+
return Array.isArray(value) ? value[0] : value;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 设备条目对外形状(不含公钥/token hash)。 */
|
|
88
|
+
function publicDevice(device) {
|
|
89
|
+
return {
|
|
90
|
+
id: device.id,
|
|
91
|
+
name: device.name,
|
|
92
|
+
platform: device.platform,
|
|
93
|
+
createdAt: device.createdAt,
|
|
94
|
+
lastSeenAt: device.lastSeenAt ?? null,
|
|
95
|
+
revoked: device.revoked === true,
|
|
96
|
+
fingerprintShort: String(device.fingerprint ?? "").slice(0, 16),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export { publicDevice };
|
|
101
|
+
|
|
102
|
+
export class PairingStore {
|
|
103
|
+
constructor({ configDir = CONFIG_DIR, now = () => Date.now(), log = () => {}, maxPending = null } = {}) {
|
|
104
|
+
this.configDir = configDir;
|
|
105
|
+
this.devicesFile = path.join(configDir, "devices.json");
|
|
106
|
+
this.now = now;
|
|
107
|
+
this.log = log;
|
|
108
|
+
/** pairId → 待批准/已批准请求(只在内存,不落盘) */
|
|
109
|
+
this.pending = new Map();
|
|
110
|
+
/** ip → 最近 60 s 内的申请时间戳 */
|
|
111
|
+
this.rate = new Map();
|
|
112
|
+
/** `${deviceId}:${nonce}` → 首次出现时间 */
|
|
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();
|
|
121
|
+
/** devices.json 按 mtime 重载,外部 revoke/手改也生效 */
|
|
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;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// ---------- 限速 / 清理 ----------
|
|
140
|
+
|
|
141
|
+
/** 返回 true 表示该 IP 本轮被限速(调用即计数)。 */
|
|
142
|
+
rateLimited(ip) {
|
|
143
|
+
const now = this.now();
|
|
144
|
+
const key = ip || "unknown";
|
|
145
|
+
const hits = (this.rate.get(key) ?? []).filter((t) => now - t < PAIR_RATE_WINDOW_MS);
|
|
146
|
+
if (hits.length >= PAIR_RATE_LIMIT) {
|
|
147
|
+
this.rate.set(key, hits);
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
hits.push(now);
|
|
151
|
+
this.rate.set(key, hits);
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
sweep() {
|
|
156
|
+
const now = this.now();
|
|
157
|
+
for (const [pairId, p] of this.pending) {
|
|
158
|
+
const done = p.status !== "pending" || now > p.expiresAt;
|
|
159
|
+
if (done && now - p.createdAt > PAIR_TTL_MS + PENDING_GC_MS) this.pending.delete(pairId);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
pruneNonces() {
|
|
164
|
+
const now = this.now();
|
|
165
|
+
for (const [key, at] of this.nonces) {
|
|
166
|
+
if (now - at > NONCE_TTL_MS) this.nonces.delete(key);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ---------- 配对请求 ----------
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* 手机端发起配对:只接受 EC P-256 的 SPKI DER 公钥(base64)。
|
|
174
|
+
* 返回 {pairId, code, expiresAt};expiresAt 为 ISO 时间串(与 /v1/sessions 的 createdAt 一致)。
|
|
175
|
+
*/
|
|
176
|
+
createRequest({ name, platform, publicKey }) {
|
|
177
|
+
const deviceName = typeof name === "string" ? name.trim() : "";
|
|
178
|
+
const devicePlatform = typeof platform === "string" ? platform.trim() : "";
|
|
179
|
+
if (!deviceName || deviceName.length > 64) {
|
|
180
|
+
throw new PairingError(400, "invalid_name", "name must be a non-empty string (≤64 chars)");
|
|
181
|
+
}
|
|
182
|
+
if (!devicePlatform || devicePlatform.length > 64) {
|
|
183
|
+
throw new PairingError(400, "invalid_platform", "platform must be a non-empty string (≤64 chars)");
|
|
184
|
+
}
|
|
185
|
+
let key;
|
|
186
|
+
let der;
|
|
187
|
+
try {
|
|
188
|
+
der = Buffer.from(String(publicKey ?? ""), "base64");
|
|
189
|
+
if (!der.length) throw new Error("empty");
|
|
190
|
+
key = createPublicKey({ key: der, format: "der", type: "spki" });
|
|
191
|
+
} catch {
|
|
192
|
+
throw new PairingError(400, "invalid_public_key", "publicKey must be base64 X.509 (SPKI) DER");
|
|
193
|
+
}
|
|
194
|
+
if (key.asymmetricKeyType !== "ec" || key.asymmetricKeyDetails?.namedCurve !== "prime256v1") {
|
|
195
|
+
throw new PairingError(400, "invalid_public_key", "publicKey must be an EC P-256 key");
|
|
196
|
+
}
|
|
197
|
+
|
|
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
|
+
}
|
|
206
|
+
const now = this.now();
|
|
207
|
+
const pairId = randomUUID();
|
|
208
|
+
let code = null;
|
|
209
|
+
for (let i = 0; i < 20 && !code; i++) {
|
|
210
|
+
const candidate = String(Math.floor(100000 + Math.random() * 900000));
|
|
211
|
+
if (![...this.pending.values()].some((p) => p.code === candidate && p.status === "pending")) code = candidate;
|
|
212
|
+
}
|
|
213
|
+
if (!code) throw new PairingError(503, "pair_code_exhausted", "too many pending pairing requests");
|
|
214
|
+
|
|
215
|
+
const expiresAt = now + PAIR_TTL_MS;
|
|
216
|
+
this.pending.set(pairId, {
|
|
217
|
+
pairId,
|
|
218
|
+
code,
|
|
219
|
+
name: deviceName,
|
|
220
|
+
platform: devicePlatform,
|
|
221
|
+
publicKeyPem: key.export({ type: "spki", format: "pem" }),
|
|
222
|
+
fingerprint: sha256hex(der),
|
|
223
|
+
createdAt: now,
|
|
224
|
+
expiresAt,
|
|
225
|
+
status: "pending",
|
|
226
|
+
deviceId: null,
|
|
227
|
+
token: null,
|
|
228
|
+
tokenFirstReadAt: null,
|
|
229
|
+
});
|
|
230
|
+
return { pairId, code, expiresAt: new Date(expiresAt).toISOString() };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
findByCode(code) {
|
|
234
|
+
const needle = String(code ?? "").trim();
|
|
235
|
+
if (!needle) return null;
|
|
236
|
+
let found = null;
|
|
237
|
+
for (const p of this.pending.values()) {
|
|
238
|
+
if (p.code === needle && (!found || p.createdAt > found.createdAt)) found = p;
|
|
239
|
+
}
|
|
240
|
+
return found;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** 待批准列表(CLI `pi-hub pair`);activity 时间都是 ISO 串。 */
|
|
244
|
+
listPending() {
|
|
245
|
+
this.sweep();
|
|
246
|
+
const now = this.now();
|
|
247
|
+
return [...this.pending.values()]
|
|
248
|
+
.filter((p) => p.status === "pending" && now <= p.expiresAt)
|
|
249
|
+
.sort((a, b) => a.createdAt - b.createdAt)
|
|
250
|
+
.map((p) => ({
|
|
251
|
+
pairId: p.pairId,
|
|
252
|
+
code: p.code,
|
|
253
|
+
name: p.name,
|
|
254
|
+
platform: p.platform,
|
|
255
|
+
createdAt: new Date(p.createdAt).toISOString(),
|
|
256
|
+
expiresAt: new Date(p.expiresAt).toISOString(),
|
|
257
|
+
status: p.status,
|
|
258
|
+
}));
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** 手机端轮询:token 只交付一次(首取后 60 s 内可重取,之后 410)。 */
|
|
262
|
+
status(pairId) {
|
|
263
|
+
this.sweep();
|
|
264
|
+
const p = this.pending.get(String(pairId ?? ""));
|
|
265
|
+
if (!p) throw new PairingError(404, "unknown_pair", `unknown pairId ${pairId}`);
|
|
266
|
+
const now = this.now();
|
|
267
|
+
if (p.status === "pending") return { status: now > p.expiresAt ? "expired" : "pending" };
|
|
268
|
+
if (p.status === "denied") return { status: "denied" };
|
|
269
|
+
if (p.tokenFirstReadAt === null) p.tokenFirstReadAt = now;
|
|
270
|
+
else if (now - p.tokenFirstReadAt > PAIR_TOKEN_GRACE_MS) {
|
|
271
|
+
throw new PairingError(410, "pair_token_expired", "pairing token was already delivered");
|
|
272
|
+
}
|
|
273
|
+
return { status: "approved", deviceId: p.deviceId, token: p.token, deviceName: p.name };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** 批准:生成 deviceId + 32 B token,写 devices.json(0600),明文 token 只回给调用方一次。 */
|
|
277
|
+
approveCode(code) {
|
|
278
|
+
this.sweep();
|
|
279
|
+
const p = this.findByCode(code);
|
|
280
|
+
if (!p) throw new PairingError(404, "unknown_pair_code", `no pending pairing with code ${code}`);
|
|
281
|
+
if (p.status === "approved") throw new PairingError(409, "already_approved", "pairing was already approved");
|
|
282
|
+
if (p.status === "denied") throw new PairingError(409, "already_denied", "pairing was already denied");
|
|
283
|
+
if (this.now() > p.expiresAt) throw new PairingError(410, "pair_expired", "pairing code expired");
|
|
284
|
+
|
|
285
|
+
const now = this.now();
|
|
286
|
+
const token = randomBytes(32).toString("base64url");
|
|
287
|
+
const device = {
|
|
288
|
+
id: randomUUID(),
|
|
289
|
+
name: p.name,
|
|
290
|
+
platform: p.platform,
|
|
291
|
+
publicKeyPem: p.publicKeyPem,
|
|
292
|
+
tokenSha256: sha256hex(token),
|
|
293
|
+
fingerprint: p.fingerprint,
|
|
294
|
+
createdAt: new Date(now).toISOString(),
|
|
295
|
+
lastSeenAt: null,
|
|
296
|
+
revoked: false,
|
|
297
|
+
};
|
|
298
|
+
const devices = this.loadDevices();
|
|
299
|
+
devices.push(device);
|
|
300
|
+
this.saveDevices(devices);
|
|
301
|
+
|
|
302
|
+
p.status = "approved";
|
|
303
|
+
p.deviceId = device.id;
|
|
304
|
+
p.token = token;
|
|
305
|
+
p.tokenFirstReadAt = null;
|
|
306
|
+
return { device, token };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
denyCode(code) {
|
|
310
|
+
this.sweep();
|
|
311
|
+
const p = this.findByCode(code);
|
|
312
|
+
if (!p) throw new PairingError(404, "unknown_pair_code", `no pending pairing with code ${code}`);
|
|
313
|
+
if (p.status === "approved") throw new PairingError(409, "already_approved", "pairing was already approved");
|
|
314
|
+
if (p.status === "denied") throw new PairingError(409, "already_denied", "pairing was already denied");
|
|
315
|
+
p.status = "denied";
|
|
316
|
+
return { status: "denied" };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// ---------- devices.json ----------
|
|
320
|
+
|
|
321
|
+
loadDevices() {
|
|
322
|
+
let stat;
|
|
323
|
+
try {
|
|
324
|
+
stat = fs.statSync(this.devicesFile);
|
|
325
|
+
} catch {
|
|
326
|
+
this.cache = { mtimeMs: -1, size: -1, devices: [] };
|
|
327
|
+
return this.cache.devices;
|
|
328
|
+
}
|
|
329
|
+
if (stat.mtimeMs === this.cache.mtimeMs && stat.size === this.cache.size) return this.cache.devices;
|
|
330
|
+
const raw = fs.readFileSync(this.devicesFile, "utf8");
|
|
331
|
+
let parsed;
|
|
332
|
+
try {
|
|
333
|
+
parsed = JSON.parse(raw);
|
|
334
|
+
} catch {
|
|
335
|
+
throw new PairingError(500, "devices_file_corrupt", `devices.json is not valid JSON: ${this.devicesFile}`);
|
|
336
|
+
}
|
|
337
|
+
const devices = Array.isArray(parsed?.devices) ? parsed.devices : [];
|
|
338
|
+
this.cache = { mtimeMs: stat.mtimeMs, size: stat.size, devices };
|
|
339
|
+
return devices;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
saveDevices(devices) {
|
|
343
|
+
fs.mkdirSync(this.configDir, { recursive: true, mode: 0o700 });
|
|
344
|
+
const data = `${JSON.stringify({ version: DEVICES_VERSION, devices }, null, 2)}\n`;
|
|
345
|
+
const tmp = `${this.devicesFile}.${process.pid}.tmp`;
|
|
346
|
+
fs.writeFileSync(tmp, data, { mode: 0o600 });
|
|
347
|
+
fs.chmodSync(tmp, 0o600);
|
|
348
|
+
fs.renameSync(tmp, this.devicesFile);
|
|
349
|
+
const stat = fs.statSync(this.devicesFile);
|
|
350
|
+
this.cache = { mtimeMs: stat.mtimeMs, size: stat.size, devices };
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
listDevices() {
|
|
354
|
+
return this.loadDevices().map(publicDevice);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** 按 id 或 name 吊销(name 必须是精确匹配;重名时要求用 id)。 */
|
|
358
|
+
revokeDevice(idOrName) {
|
|
359
|
+
const needle = String(idOrName ?? "").trim();
|
|
360
|
+
if (!needle) throw new PairingError(400, "invalid_device", "device id or name is required");
|
|
361
|
+
const devices = this.loadDevices();
|
|
362
|
+
// id 支持唯一前缀(手机端只显示前 8 位,UI 提示里的就是前缀,别让用户去翻全 id)。
|
|
363
|
+
const byIdExact = devices.find((d) => d.id === needle);
|
|
364
|
+
const byIdPrefix = needle.length >= 6 ? devices.filter((d) => d.id.startsWith(needle)) : [];
|
|
365
|
+
const byName = devices.filter((d) => d.name === needle);
|
|
366
|
+
if (!byIdExact && byIdPrefix.length > 1) {
|
|
367
|
+
throw new PairingError(409, "ambiguous_device", `${byIdPrefix.length} devices match id prefix ${needle}; use more characters`);
|
|
368
|
+
}
|
|
369
|
+
const byId = byIdExact ?? byIdPrefix[0];
|
|
370
|
+
if (!byId && byName.length > 1) {
|
|
371
|
+
throw new PairingError(409, "ambiguous_device", `${byName.length} devices named ${needle}; revoke by id`);
|
|
372
|
+
}
|
|
373
|
+
const device = byId ?? byName[0];
|
|
374
|
+
if (!device) throw new PairingError(404, "unknown_device", `no device matches ${needle}`);
|
|
375
|
+
if (!device.revoked) {
|
|
376
|
+
device.revoked = true;
|
|
377
|
+
device.revokedAt = new Date(this.now()).toISOString();
|
|
378
|
+
this.saveDevices(devices);
|
|
379
|
+
}
|
|
380
|
+
return publicDevice(device);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** 设备请求成功后刷新 lastSeenAt(节流 ≥60 s)。 */
|
|
384
|
+
touchDevice(deviceId) {
|
|
385
|
+
const devices = this.loadDevices();
|
|
386
|
+
const device = devices.find((d) => d.id === deviceId);
|
|
387
|
+
if (!device) return;
|
|
388
|
+
const now = this.now();
|
|
389
|
+
const last = device.lastSeenAt ? Date.parse(device.lastSeenAt) : NaN;
|
|
390
|
+
if (Number.isFinite(last) && now - last < LAST_SEEN_THROTTLE_MS) return;
|
|
391
|
+
device.lastSeenAt = new Date(now).toISOString();
|
|
392
|
+
this.saveDevices(devices);
|
|
393
|
+
}
|
|
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
|
+
|
|
422
|
+
// ---------- 设备签名 ----------
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* 校验设备令牌 + 签名。校验顺序逐字照 PLAN §2:
|
|
426
|
+
* token 命中设备 → 未吊销 → ts 偏差 → nonce 未用 → 公钥验签。
|
|
427
|
+
* @returns {{ok:true, device:object} | {ok:false, code:string, message:string}}
|
|
428
|
+
*/
|
|
429
|
+
verifyDeviceSignature({ method = "GET", path: reqPath = "/", headers = {}, rawBody = Buffer.alloc(0), token } = {}) {
|
|
430
|
+
const fail = (code, message) => ({ ok: false, code, message });
|
|
431
|
+
if (!token) return fail("bad_signature", "missing bearer token");
|
|
432
|
+
|
|
433
|
+
// token 命中设备:恒时比较 sha256(token) 与落盘的 tokenSha256(不提前 break)。
|
|
434
|
+
const givenHash = Buffer.from(sha256hex(token), "utf8");
|
|
435
|
+
let device = null;
|
|
436
|
+
for (const candidate of this.loadDevices()) {
|
|
437
|
+
const stored = Buffer.from(String(candidate.tokenSha256 ?? ""), "utf8");
|
|
438
|
+
if (stored.length === givenHash.length && timingSafeEqual(stored, givenHash)) device = candidate;
|
|
439
|
+
}
|
|
440
|
+
if (!device) return fail("bad_signature", "unknown device token");
|
|
441
|
+
|
|
442
|
+
const deviceId = headerValue(headers, "x-pi-device");
|
|
443
|
+
if (!deviceId || String(deviceId) !== device.id) {
|
|
444
|
+
return fail("bad_signature", "x-pi-device does not match the device token");
|
|
445
|
+
}
|
|
446
|
+
// 吊销检查每次请求都做(不在缓存里短路)
|
|
447
|
+
if (device.revoked === true) return fail("device_revoked", `device ${device.name ?? device.id} is revoked`);
|
|
448
|
+
|
|
449
|
+
const tsText = String(headerValue(headers, "x-pi-ts") ?? "");
|
|
450
|
+
if (!/^\d+$/.test(tsText)) return fail("bad_signature", "x-pi-ts must be epoch millis");
|
|
451
|
+
if (Math.abs(this.now() - Number(tsText)) > SIGNATURE_SKEW_MS) {
|
|
452
|
+
return fail("stale_timestamp", "x-pi-ts is outside ±180 s");
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
const nonce = String(headerValue(headers, "x-pi-nonce") ?? "");
|
|
456
|
+
if (!/^[A-Za-z0-9_-]{16,64}$/.test(nonce)) return fail("bad_signature", "x-pi-nonce must be base64url");
|
|
457
|
+
this.pruneNonces();
|
|
458
|
+
const nonceKey = `${device.id}:${nonce}`;
|
|
459
|
+
if (this.nonces.has(nonceKey)) return fail("replay", "nonce was already used");
|
|
460
|
+
this.nonces.set(nonceKey, this.now());
|
|
461
|
+
|
|
462
|
+
const signature = String(headerValue(headers, "x-pi-sig") ?? "");
|
|
463
|
+
if (!signature) return fail("bad_signature", "missing x-pi-sig");
|
|
464
|
+
const payload = [
|
|
465
|
+
"PIHUB1",
|
|
466
|
+
String(method).toUpperCase(),
|
|
467
|
+
reqPath,
|
|
468
|
+
tsText,
|
|
469
|
+
nonce,
|
|
470
|
+
sha256hex(rawBody),
|
|
471
|
+
].join("\n");
|
|
472
|
+
|
|
473
|
+
let key;
|
|
474
|
+
try {
|
|
475
|
+
key = createPublicKey(device.publicKeyPem);
|
|
476
|
+
} catch {
|
|
477
|
+
return fail("bad_signature", "stored public key is unreadable");
|
|
478
|
+
}
|
|
479
|
+
let verified = false;
|
|
480
|
+
try {
|
|
481
|
+
verified = cryptoVerify("sha256", Buffer.from(payload, "utf8"), key, Buffer.from(signature, "base64"));
|
|
482
|
+
} catch {
|
|
483
|
+
verified = false;
|
|
484
|
+
}
|
|
485
|
+
if (!verified) return fail("bad_signature", "signature does not verify");
|
|
486
|
+
return { ok: true, device };
|
|
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
|
+
}
|
|
653
|
+
}
|