dsh-mobile-ios 0.2.6 → 0.2.8
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 -21
- package/README.md +284 -284
- package/cordis.patch.yml +20 -20
- package/entries/plugin.mjs +246 -246
- package/entries/sidecar.mjs +111 -111
- package/lib/client.js +1294 -1193
- package/lib/vendor/qrcode-generator.cjs +2297 -2297
- package/lib/vendor/qrcode-utf8.cjs +26 -26
- package/package.json +53 -53
- package/src/adapter/artifacts.mjs +235 -235
- package/src/adapter/cordis-host.mjs +1225 -1225
- package/src/adapter/mock-host.mjs +437 -437
- package/src/adapter/mux-host.mjs +99 -99
- package/src/adapter/session-history.mjs +241 -241
- package/src/cloudflare.mjs +628 -628
- package/src/cloudflared-install.mjs +139 -0
- package/src/dns-label.mjs +32 -32
- package/src/dns-probe.mjs +90 -90
- package/src/file-log.mjs +68 -68
- package/src/gateway.mjs +285 -285
- package/src/pairing.mjs +300 -300
- package/src/protocol.mjs +59 -59
- package/src/provision-local.mjs +309 -309
- package/src/rest.mjs +812 -786
- package/src/ring.mjs +148 -148
- package/src/server.mjs +219 -219
- package/src/tunnel.mjs +523 -504
- package/src/version.mjs +24 -24
- package/src/ws.mjs +332 -332
package/src/pairing.mjs
CHANGED
|
@@ -1,300 +1,300 @@
|
|
|
1
|
-
// pairing.mjs — 配对与设备凭证(GW-4 / GW-7)
|
|
2
|
-
// 安全约束(不可放松):
|
|
3
|
-
// · 配对码 6 位数字、TTL 120s、单次有效、生成 5 次/分钟;
|
|
4
|
-
// · 错 5 次锁定 60s,且锁定期间不泄露"码对不对";
|
|
5
|
-
// · 凭证只存哈希,内存里不保留明文副本;
|
|
6
|
-
// · 撤销是"整设备"语义,客户端收到 4009 必须清本地凭证并停止重连。
|
|
7
|
-
|
|
8
|
-
import crypto from 'node:crypto';
|
|
9
|
-
import fs from 'node:fs';
|
|
10
|
-
import path from 'node:path';
|
|
11
|
-
import { fail } from './protocol.mjs';
|
|
12
|
-
|
|
13
|
-
const CODE_TTL_SEC = 120;
|
|
14
|
-
const CODE_MAX_ATTEMPTS = 5;
|
|
15
|
-
const CODE_RATE_LIMIT = 5;
|
|
16
|
-
const CODE_RATE_WINDOW_MS = 60_000;
|
|
17
|
-
const LOCK_MS = 60_000;
|
|
18
|
-
const TOKEN_TTL_SEC = 30 * 24 * 3600;
|
|
19
|
-
// 活跃设备上限:一台电脑的可信手机就那么几台;不设上限的话,每次重装 App
|
|
20
|
-
// / 重新配对都会新增一条记录(历史上堆到过 60 条),面板数字失去意义。
|
|
21
|
-
const MAX_ACTIVE_DEVICES = 5;
|
|
22
|
-
|
|
23
|
-
const SCOPES = ['tasks.read', 'tasks.write', 'todos.answer', 'artifacts.read'];
|
|
24
|
-
const sha256 = (s) => crypto.createHash('sha256').update(s).digest('hex');
|
|
25
|
-
|
|
26
|
-
// 持久化(借鉴 dsh-plugin-mobile-gateway 的 gateway-state 原子写模式):
|
|
27
|
-
// · tmp 文件 + rename,写一半进程死掉不会留下半截 JSON;
|
|
28
|
-
// · 目录 0700 / 文件 0600,只存 token 哈希,不存明文;
|
|
29
|
-
// · 有意偏离第三方的「损坏即 fail-fast」:我们的插件跑在宿主进程内(R12),
|
|
30
|
-
// 状态文件损坏不该带崩宿主——改成备份损坏文件后空表启动。
|
|
31
|
-
function loadDevices(file, log) {
|
|
32
|
-
let raw;
|
|
33
|
-
try {
|
|
34
|
-
raw = fs.readFileSync(file, 'utf8');
|
|
35
|
-
} catch (err) {
|
|
36
|
-
if (err.code === 'ENOENT') return [];
|
|
37
|
-
throw err;
|
|
38
|
-
}
|
|
39
|
-
try {
|
|
40
|
-
const parsed = JSON.parse(raw);
|
|
41
|
-
if (!parsed || parsed.version !== 1 || !Array.isArray(parsed.devices)) throw new Error('结构不符');
|
|
42
|
-
const now = Date.now();
|
|
43
|
-
// 过期设备加载时即丢弃(撤销的保留:audit 语义 + 4009 响应需要知道它存在过)
|
|
44
|
-
return parsed.devices.filter((d) => d && typeof d.deviceTokenHash === 'string'
|
|
45
|
-
&& (!d.expiresAt || Date.parse(d.expiresAt) > now));
|
|
46
|
-
} catch (err) {
|
|
47
|
-
const backup = `${file}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`;
|
|
48
|
-
try {
|
|
49
|
-
fs.renameSync(file, backup);
|
|
50
|
-
log(`pair 设备注册表损坏,已备份到 ${path.basename(backup)} 并空表启动(${err.message})`);
|
|
51
|
-
} catch {
|
|
52
|
-
log(`pair 设备注册表损坏且备份失败,空表启动(${err.message})`);
|
|
53
|
-
}
|
|
54
|
-
return [];
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
function saveDevices(file, devices) {
|
|
59
|
-
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
60
|
-
const tmp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
|
|
61
|
-
const payload = JSON.stringify({ version: 1, savedAt: new Date().toISOString(), devices }, null, 2);
|
|
62
|
-
try {
|
|
63
|
-
fs.writeFileSync(tmp, payload, { mode: 0o600, flag: 'wx' });
|
|
64
|
-
fs.renameSync(tmp, file);
|
|
65
|
-
try { fs.chmodSync(file, 0o600); } catch { /* 刚写的文件权限已正确 */ }
|
|
66
|
-
} finally {
|
|
67
|
-
try { fs.unlinkSync(tmp); } catch { /* rename 成功时 tmp 已不存在 */ }
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
export class PairingService {
|
|
72
|
-
constructor({ now = () => Date.now(), log = () => {}, file = null } = {}) {
|
|
73
|
-
this.now = now;
|
|
74
|
-
this.log = log;
|
|
75
|
-
this.file = file; // 提供则设备注册表落盘;不提供保持纯内存(测试/临时实例)
|
|
76
|
-
this.code = null; // { value, expiresAt, attempts, deviceName }
|
|
77
|
-
this.lockedUntil = 0;
|
|
78
|
-
this.issued = []; // 时间戳数组,用于限速
|
|
79
|
-
this.devices = new Map(); // tokenHash -> device
|
|
80
|
-
this.byDeviceId = new Map();
|
|
81
|
-
if (this.file) this.#load();
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
#load() {
|
|
85
|
-
try {
|
|
86
|
-
let deduped = 0;
|
|
87
|
-
for (const device of loadDevices(this.file, this.log)) {
|
|
88
|
-
// 同一 installId 只认最新一条:历史上重配对会堆积重复记录(同机 6 条),
|
|
89
|
-
// 旧的直接标记撤销——audit 语义保留,verify() 对它们回 4009。
|
|
90
|
-
const existing = [...this.devices.values()].find((d) => !d.revoked && d.installId === device.installId);
|
|
91
|
-
if (existing && String(existing.createdAt) > String(device.createdAt)) {
|
|
92
|
-
device.revoked = true;
|
|
93
|
-
deduped += 1;
|
|
94
|
-
} else if (existing) {
|
|
95
|
-
existing.revoked = true;
|
|
96
|
-
deduped += 1;
|
|
97
|
-
}
|
|
98
|
-
this.devices.set(device.deviceTokenHash, device);
|
|
99
|
-
this.byDeviceId.set(device.deviceId, device);
|
|
100
|
-
}
|
|
101
|
-
// 历史积压一并压回上限:活跃设备只保留最新 5 台,更旧的标记撤销
|
|
102
|
-
// (手机下次请求收到 4009,重新扫码即可,不丢 audit 记录)。
|
|
103
|
-
const overflow = [...this.devices.values()].filter((d) => !d.revoked)
|
|
104
|
-
.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
|
|
105
|
-
.slice(MAX_ACTIVE_DEVICES);
|
|
106
|
-
for (const device of overflow) device.revoked = true;
|
|
107
|
-
if (overflow.length) deduped += overflow.length;
|
|
108
|
-
const n = this.devices.size;
|
|
109
|
-
if (n) this.log(`pair 从注册表恢复 ${n} 台设备(活跃 ${[...this.devices.values()].filter((d) => !d.revoked).length})${deduped ? `,按上限/去重回收 ${deduped} 条旧记录` : ''}`);
|
|
110
|
-
if (deduped) this.#persist();
|
|
111
|
-
} catch (err) {
|
|
112
|
-
// 读盘失败(权限等)不阻塞启动:R12——网关以降级形态活着,手机最多重新配对
|
|
113
|
-
this.log(`pair 设备注册表读取失败,本次以内存态运行:${err.message}`);
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
#persist() {
|
|
118
|
-
if (!this.file) return;
|
|
119
|
-
try {
|
|
120
|
-
saveDevices(this.file, [...this.devices.values()]);
|
|
121
|
-
} catch (err) {
|
|
122
|
-
this.log(`pair 设备注册表写入失败(内存态不受影响):${err.message}`);
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
#prune() {
|
|
127
|
-
const cutoff = this.now() - CODE_RATE_WINDOW_MS;
|
|
128
|
-
this.issued = this.issued.filter((t) => t > cutoff);
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
issueCode({ deviceName = 'iOS 设备' } = {}) {
|
|
132
|
-
this.#prune();
|
|
133
|
-
if (this.issued.length >= CODE_RATE_LIMIT) {
|
|
134
|
-
const retryAfterMs = Math.max(1000, this.issued[0] + CODE_RATE_WINDOW_MS - this.now());
|
|
135
|
-
throw fail(4029, undefined, { retryAfterMs });
|
|
136
|
-
}
|
|
137
|
-
const value = String(crypto.randomInt(0, 1_000_000)).padStart(6, '0');
|
|
138
|
-
const expiresAt = this.now() + CODE_TTL_SEC * 1000;
|
|
139
|
-
this.code = { value, expiresAt, attempts: CODE_MAX_ATTEMPTS, deviceName };
|
|
140
|
-
this.issued.push(this.now());
|
|
141
|
-
this.log(`pair code=${value} ttl=${CODE_TTL_SEC}s`);
|
|
142
|
-
return {
|
|
143
|
-
code: value,
|
|
144
|
-
expiresAt: new Date(expiresAt).toISOString(),
|
|
145
|
-
expiresInSec: CODE_TTL_SEC,
|
|
146
|
-
attemptsRemaining: CODE_MAX_ATTEMPTS,
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
redeem({ code, deviceName, installId, platform = 'ios', appVersion = '' }) {
|
|
151
|
-
if (!code || !/^\d{6}$/.test(String(code))) throw fail(4400, '配对码应为 6 位数字');
|
|
152
|
-
if (!installId) throw fail(4400, '缺少 installId');
|
|
153
|
-
|
|
154
|
-
if (this.lockedUntil > this.now()) {
|
|
155
|
-
throw fail(4008, undefined, { retryAfterMs: this.lockedUntil - this.now() });
|
|
156
|
-
}
|
|
157
|
-
if (!this.code || this.code.expiresAt <= this.now()) {
|
|
158
|
-
throw fail(4008, '配对码已过期,请重新生成');
|
|
159
|
-
}
|
|
160
|
-
if (code !== this.code.value) {
|
|
161
|
-
this.code.attempts -= 1;
|
|
162
|
-
if (this.code.attempts <= 0) {
|
|
163
|
-
this.code = null;
|
|
164
|
-
this.lockedUntil = this.now() + LOCK_MS;
|
|
165
|
-
this.log('pair 连错 5 次,锁定 60s');
|
|
166
|
-
}
|
|
167
|
-
throw fail(4008, undefined, { attemptsRemaining: Math.max(0, this.code?.attempts ?? 0) });
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
// 单次有效:兑换即作废,不留复用窗口
|
|
171
|
-
const matchedDeviceName = this.code.deviceName;
|
|
172
|
-
this.code = null;
|
|
173
|
-
|
|
174
|
-
// 同一 installId 重新配对 = 换凭证,不是新增设备:覆盖旧记录。
|
|
175
|
-
// 旧行为是无脑新增,同一台手机重装一次 App 就多一条(曾堆到 60 条)。
|
|
176
|
-
for (const [hash, d] of [...this.devices]) {
|
|
177
|
-
if (d.installId === installId && !d.revoked) {
|
|
178
|
-
this.devices.delete(hash);
|
|
179
|
-
this.byDeviceId.delete(d.deviceId);
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
// 活跃设备上限:满员时挤掉最旧的一台(标记撤销保留在表内做 audit,
|
|
184
|
-
// 那台手机下次请求会收到 4009 并清凭证重新配对)。
|
|
185
|
-
const active = [...this.devices.values()].filter((d) => !d.revoked)
|
|
186
|
-
.sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)));
|
|
187
|
-
while (active.length >= MAX_ACTIVE_DEVICES) {
|
|
188
|
-
const oldest = active.shift();
|
|
189
|
-
oldest.revoked = true;
|
|
190
|
-
this.log(`pair 活跃设备已达上限 ${MAX_ACTIVE_DEVICES},挤掉最旧的 ${oldest.deviceName || oldest.deviceId}`);
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
const token = `dt_${crypto.randomBytes(18).toString('hex')}`;
|
|
194
|
-
const device = {
|
|
195
|
-
deviceId: `dev_${crypto.randomBytes(4).toString('hex')}`,
|
|
196
|
-
deviceTokenHash: sha256(token),
|
|
197
|
-
installId,
|
|
198
|
-
deviceName: deviceName || matchedDeviceName,
|
|
199
|
-
platform,
|
|
200
|
-
appVersion,
|
|
201
|
-
scopes: [...SCOPES],
|
|
202
|
-
createdAt: new Date(this.now()).toISOString(),
|
|
203
|
-
expiresAt: new Date(this.now() + TOKEN_TTL_SEC * 1000).toISOString(),
|
|
204
|
-
revoked: false,
|
|
205
|
-
};
|
|
206
|
-
this.devices.set(device.deviceTokenHash, device);
|
|
207
|
-
this.byDeviceId.set(device.deviceId, device);
|
|
208
|
-
this.#persist();
|
|
209
|
-
this.log(`pair 兑换成功 device=${device.deviceId}`);
|
|
210
|
-
return {
|
|
211
|
-
deviceId: device.deviceId,
|
|
212
|
-
deviceToken: token,
|
|
213
|
-
tokenType: 'Bearer',
|
|
214
|
-
expiresAt: device.expiresAt,
|
|
215
|
-
scopes: device.scopes,
|
|
216
|
-
pairedAt: device.createdAt,
|
|
217
|
-
};
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
/** 校验 Bearer;失败抛 4001 / 4009(已撤销),均由客户端做不同处理 */
|
|
221
|
-
verify(token) {
|
|
222
|
-
if (!token) throw fail(4001);
|
|
223
|
-
const device = this.devices.get(sha256(token));
|
|
224
|
-
if (!device) throw fail(4001);
|
|
225
|
-
if (device.revoked) throw fail(4009);
|
|
226
|
-
if (Date.parse(device.expiresAt) <= this.now()) throw fail(4001);
|
|
227
|
-
return device;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
revokeAll() {
|
|
231
|
-
let n = 0;
|
|
232
|
-
for (const d of this.devices.values()) {
|
|
233
|
-
if (!d.revoked) {
|
|
234
|
-
d.revoked = true;
|
|
235
|
-
n += 1;
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
if (n) {
|
|
239
|
-
this.#persist();
|
|
240
|
-
this.log(`pair 撤销全部设备 n=${n}`);
|
|
241
|
-
}
|
|
242
|
-
return n;
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
/**
|
|
246
|
-
* 桌面面板的设备清单:只回显展示字段,绝不泄露 deviceTokenHash / installId。
|
|
247
|
-
* 撤销过的设备不入列——面板问的是「现在还能连上来的设备」,
|
|
248
|
-
* 历史审计记录留在注册表里供 verify() 回 4009,但不给用户看。
|
|
249
|
-
*/
|
|
250
|
-
listDevices() {
|
|
251
|
-
return [...this.devices.values()]
|
|
252
|
-
.filter((d) => !d.revoked && (!d.expiresAt || Date.parse(d.expiresAt) > this.now()))
|
|
253
|
-
.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
|
|
254
|
-
.map((d) => ({
|
|
255
|
-
deviceId: d.deviceId,
|
|
256
|
-
deviceName: d.deviceName || '未命名设备',
|
|
257
|
-
platform: d.platform,
|
|
258
|
-
appVersion: d.appVersion,
|
|
259
|
-
createdAt: d.createdAt,
|
|
260
|
-
expiresAt: d.expiresAt,
|
|
261
|
-
}));
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
/**
|
|
265
|
-
* 已认证设备在 WS hello 时回报「关于 → 设备名称」全称,立即覆盖配对时记下的名字。
|
|
266
|
-
* 名字来自设备自身,服务端不截短、不改写;空值忽略,撤销设备不接受改名。
|
|
267
|
-
*/
|
|
268
|
-
renameDevice(deviceId, name) {
|
|
269
|
-
if (typeof name !== 'string') return false;
|
|
270
|
-
const clean = name.trim();
|
|
271
|
-
if (!clean) return false;
|
|
272
|
-
const device = this.byDeviceId.get(String(deviceId || ''));
|
|
273
|
-
if (!device || device.revoked || device.deviceName === clean) return false;
|
|
274
|
-
device.deviceName = clean;
|
|
275
|
-
this.#persist();
|
|
276
|
-
this.log(`pair 更新设备名 device=${device.deviceId} name=${clean}`);
|
|
277
|
-
return true;
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
/** 单设备下线:设备下次带旧凭证请求会收到 4009 并清本地凭证。 */
|
|
281
|
-
revokeDevice(deviceId) {
|
|
282
|
-
const device = this.byDeviceId.get(String(deviceId || ''));
|
|
283
|
-
if (!device || device.revoked) return 0;
|
|
284
|
-
device.revoked = true;
|
|
285
|
-
this.#persist();
|
|
286
|
-
this.log(`pair 下线设备 device=${device.deviceId} name=${device.deviceName || '-'}`);
|
|
287
|
-
return 1;
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
get maxDevices() { return MAX_ACTIVE_DEVICES; }
|
|
291
|
-
|
|
292
|
-
stats() {
|
|
293
|
-
return {
|
|
294
|
-
devices: this.devices.size,
|
|
295
|
-
activeDevices: [...this.devices.values()].filter((d) => !d.revoked).length,
|
|
296
|
-
codeActive: Boolean(this.code && this.code.expiresAt > this.now()),
|
|
297
|
-
lockedUntil: this.lockedUntil > this.now() ? new Date(this.lockedUntil).toISOString() : null,
|
|
298
|
-
};
|
|
299
|
-
}
|
|
300
|
-
}
|
|
1
|
+
// pairing.mjs — 配对与设备凭证(GW-4 / GW-7)
|
|
2
|
+
// 安全约束(不可放松):
|
|
3
|
+
// · 配对码 6 位数字、TTL 120s、单次有效、生成 5 次/分钟;
|
|
4
|
+
// · 错 5 次锁定 60s,且锁定期间不泄露"码对不对";
|
|
5
|
+
// · 凭证只存哈希,内存里不保留明文副本;
|
|
6
|
+
// · 撤销是"整设备"语义,客户端收到 4009 必须清本地凭证并停止重连。
|
|
7
|
+
|
|
8
|
+
import crypto from 'node:crypto';
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { fail } from './protocol.mjs';
|
|
12
|
+
|
|
13
|
+
const CODE_TTL_SEC = 120;
|
|
14
|
+
const CODE_MAX_ATTEMPTS = 5;
|
|
15
|
+
const CODE_RATE_LIMIT = 5;
|
|
16
|
+
const CODE_RATE_WINDOW_MS = 60_000;
|
|
17
|
+
const LOCK_MS = 60_000;
|
|
18
|
+
const TOKEN_TTL_SEC = 30 * 24 * 3600;
|
|
19
|
+
// 活跃设备上限:一台电脑的可信手机就那么几台;不设上限的话,每次重装 App
|
|
20
|
+
// / 重新配对都会新增一条记录(历史上堆到过 60 条),面板数字失去意义。
|
|
21
|
+
const MAX_ACTIVE_DEVICES = 5;
|
|
22
|
+
|
|
23
|
+
const SCOPES = ['tasks.read', 'tasks.write', 'todos.answer', 'artifacts.read'];
|
|
24
|
+
const sha256 = (s) => crypto.createHash('sha256').update(s).digest('hex');
|
|
25
|
+
|
|
26
|
+
// 持久化(借鉴 dsh-plugin-mobile-gateway 的 gateway-state 原子写模式):
|
|
27
|
+
// · tmp 文件 + rename,写一半进程死掉不会留下半截 JSON;
|
|
28
|
+
// · 目录 0700 / 文件 0600,只存 token 哈希,不存明文;
|
|
29
|
+
// · 有意偏离第三方的「损坏即 fail-fast」:我们的插件跑在宿主进程内(R12),
|
|
30
|
+
// 状态文件损坏不该带崩宿主——改成备份损坏文件后空表启动。
|
|
31
|
+
function loadDevices(file, log) {
|
|
32
|
+
let raw;
|
|
33
|
+
try {
|
|
34
|
+
raw = fs.readFileSync(file, 'utf8');
|
|
35
|
+
} catch (err) {
|
|
36
|
+
if (err.code === 'ENOENT') return [];
|
|
37
|
+
throw err;
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
const parsed = JSON.parse(raw);
|
|
41
|
+
if (!parsed || parsed.version !== 1 || !Array.isArray(parsed.devices)) throw new Error('结构不符');
|
|
42
|
+
const now = Date.now();
|
|
43
|
+
// 过期设备加载时即丢弃(撤销的保留:audit 语义 + 4009 响应需要知道它存在过)
|
|
44
|
+
return parsed.devices.filter((d) => d && typeof d.deviceTokenHash === 'string'
|
|
45
|
+
&& (!d.expiresAt || Date.parse(d.expiresAt) > now));
|
|
46
|
+
} catch (err) {
|
|
47
|
+
const backup = `${file}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`;
|
|
48
|
+
try {
|
|
49
|
+
fs.renameSync(file, backup);
|
|
50
|
+
log(`pair 设备注册表损坏,已备份到 ${path.basename(backup)} 并空表启动(${err.message})`);
|
|
51
|
+
} catch {
|
|
52
|
+
log(`pair 设备注册表损坏且备份失败,空表启动(${err.message})`);
|
|
53
|
+
}
|
|
54
|
+
return [];
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function saveDevices(file, devices) {
|
|
59
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
60
|
+
const tmp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
|
|
61
|
+
const payload = JSON.stringify({ version: 1, savedAt: new Date().toISOString(), devices }, null, 2);
|
|
62
|
+
try {
|
|
63
|
+
fs.writeFileSync(tmp, payload, { mode: 0o600, flag: 'wx' });
|
|
64
|
+
fs.renameSync(tmp, file);
|
|
65
|
+
try { fs.chmodSync(file, 0o600); } catch { /* 刚写的文件权限已正确 */ }
|
|
66
|
+
} finally {
|
|
67
|
+
try { fs.unlinkSync(tmp); } catch { /* rename 成功时 tmp 已不存在 */ }
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export class PairingService {
|
|
72
|
+
constructor({ now = () => Date.now(), log = () => {}, file = null } = {}) {
|
|
73
|
+
this.now = now;
|
|
74
|
+
this.log = log;
|
|
75
|
+
this.file = file; // 提供则设备注册表落盘;不提供保持纯内存(测试/临时实例)
|
|
76
|
+
this.code = null; // { value, expiresAt, attempts, deviceName }
|
|
77
|
+
this.lockedUntil = 0;
|
|
78
|
+
this.issued = []; // 时间戳数组,用于限速
|
|
79
|
+
this.devices = new Map(); // tokenHash -> device
|
|
80
|
+
this.byDeviceId = new Map();
|
|
81
|
+
if (this.file) this.#load();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
#load() {
|
|
85
|
+
try {
|
|
86
|
+
let deduped = 0;
|
|
87
|
+
for (const device of loadDevices(this.file, this.log)) {
|
|
88
|
+
// 同一 installId 只认最新一条:历史上重配对会堆积重复记录(同机 6 条),
|
|
89
|
+
// 旧的直接标记撤销——audit 语义保留,verify() 对它们回 4009。
|
|
90
|
+
const existing = [...this.devices.values()].find((d) => !d.revoked && d.installId === device.installId);
|
|
91
|
+
if (existing && String(existing.createdAt) > String(device.createdAt)) {
|
|
92
|
+
device.revoked = true;
|
|
93
|
+
deduped += 1;
|
|
94
|
+
} else if (existing) {
|
|
95
|
+
existing.revoked = true;
|
|
96
|
+
deduped += 1;
|
|
97
|
+
}
|
|
98
|
+
this.devices.set(device.deviceTokenHash, device);
|
|
99
|
+
this.byDeviceId.set(device.deviceId, device);
|
|
100
|
+
}
|
|
101
|
+
// 历史积压一并压回上限:活跃设备只保留最新 5 台,更旧的标记撤销
|
|
102
|
+
// (手机下次请求收到 4009,重新扫码即可,不丢 audit 记录)。
|
|
103
|
+
const overflow = [...this.devices.values()].filter((d) => !d.revoked)
|
|
104
|
+
.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
|
|
105
|
+
.slice(MAX_ACTIVE_DEVICES);
|
|
106
|
+
for (const device of overflow) device.revoked = true;
|
|
107
|
+
if (overflow.length) deduped += overflow.length;
|
|
108
|
+
const n = this.devices.size;
|
|
109
|
+
if (n) this.log(`pair 从注册表恢复 ${n} 台设备(活跃 ${[...this.devices.values()].filter((d) => !d.revoked).length})${deduped ? `,按上限/去重回收 ${deduped} 条旧记录` : ''}`);
|
|
110
|
+
if (deduped) this.#persist();
|
|
111
|
+
} catch (err) {
|
|
112
|
+
// 读盘失败(权限等)不阻塞启动:R12——网关以降级形态活着,手机最多重新配对
|
|
113
|
+
this.log(`pair 设备注册表读取失败,本次以内存态运行:${err.message}`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
#persist() {
|
|
118
|
+
if (!this.file) return;
|
|
119
|
+
try {
|
|
120
|
+
saveDevices(this.file, [...this.devices.values()]);
|
|
121
|
+
} catch (err) {
|
|
122
|
+
this.log(`pair 设备注册表写入失败(内存态不受影响):${err.message}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
#prune() {
|
|
127
|
+
const cutoff = this.now() - CODE_RATE_WINDOW_MS;
|
|
128
|
+
this.issued = this.issued.filter((t) => t > cutoff);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
issueCode({ deviceName = 'iOS 设备' } = {}) {
|
|
132
|
+
this.#prune();
|
|
133
|
+
if (this.issued.length >= CODE_RATE_LIMIT) {
|
|
134
|
+
const retryAfterMs = Math.max(1000, this.issued[0] + CODE_RATE_WINDOW_MS - this.now());
|
|
135
|
+
throw fail(4029, undefined, { retryAfterMs });
|
|
136
|
+
}
|
|
137
|
+
const value = String(crypto.randomInt(0, 1_000_000)).padStart(6, '0');
|
|
138
|
+
const expiresAt = this.now() + CODE_TTL_SEC * 1000;
|
|
139
|
+
this.code = { value, expiresAt, attempts: CODE_MAX_ATTEMPTS, deviceName };
|
|
140
|
+
this.issued.push(this.now());
|
|
141
|
+
this.log(`pair code=${value} ttl=${CODE_TTL_SEC}s`);
|
|
142
|
+
return {
|
|
143
|
+
code: value,
|
|
144
|
+
expiresAt: new Date(expiresAt).toISOString(),
|
|
145
|
+
expiresInSec: CODE_TTL_SEC,
|
|
146
|
+
attemptsRemaining: CODE_MAX_ATTEMPTS,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
redeem({ code, deviceName, installId, platform = 'ios', appVersion = '' }) {
|
|
151
|
+
if (!code || !/^\d{6}$/.test(String(code))) throw fail(4400, '配对码应为 6 位数字');
|
|
152
|
+
if (!installId) throw fail(4400, '缺少 installId');
|
|
153
|
+
|
|
154
|
+
if (this.lockedUntil > this.now()) {
|
|
155
|
+
throw fail(4008, undefined, { retryAfterMs: this.lockedUntil - this.now() });
|
|
156
|
+
}
|
|
157
|
+
if (!this.code || this.code.expiresAt <= this.now()) {
|
|
158
|
+
throw fail(4008, '配对码已过期,请重新生成');
|
|
159
|
+
}
|
|
160
|
+
if (code !== this.code.value) {
|
|
161
|
+
this.code.attempts -= 1;
|
|
162
|
+
if (this.code.attempts <= 0) {
|
|
163
|
+
this.code = null;
|
|
164
|
+
this.lockedUntil = this.now() + LOCK_MS;
|
|
165
|
+
this.log('pair 连错 5 次,锁定 60s');
|
|
166
|
+
}
|
|
167
|
+
throw fail(4008, undefined, { attemptsRemaining: Math.max(0, this.code?.attempts ?? 0) });
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// 单次有效:兑换即作废,不留复用窗口
|
|
171
|
+
const matchedDeviceName = this.code.deviceName;
|
|
172
|
+
this.code = null;
|
|
173
|
+
|
|
174
|
+
// 同一 installId 重新配对 = 换凭证,不是新增设备:覆盖旧记录。
|
|
175
|
+
// 旧行为是无脑新增,同一台手机重装一次 App 就多一条(曾堆到 60 条)。
|
|
176
|
+
for (const [hash, d] of [...this.devices]) {
|
|
177
|
+
if (d.installId === installId && !d.revoked) {
|
|
178
|
+
this.devices.delete(hash);
|
|
179
|
+
this.byDeviceId.delete(d.deviceId);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// 活跃设备上限:满员时挤掉最旧的一台(标记撤销保留在表内做 audit,
|
|
184
|
+
// 那台手机下次请求会收到 4009 并清凭证重新配对)。
|
|
185
|
+
const active = [...this.devices.values()].filter((d) => !d.revoked)
|
|
186
|
+
.sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)));
|
|
187
|
+
while (active.length >= MAX_ACTIVE_DEVICES) {
|
|
188
|
+
const oldest = active.shift();
|
|
189
|
+
oldest.revoked = true;
|
|
190
|
+
this.log(`pair 活跃设备已达上限 ${MAX_ACTIVE_DEVICES},挤掉最旧的 ${oldest.deviceName || oldest.deviceId}`);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const token = `dt_${crypto.randomBytes(18).toString('hex')}`;
|
|
194
|
+
const device = {
|
|
195
|
+
deviceId: `dev_${crypto.randomBytes(4).toString('hex')}`,
|
|
196
|
+
deviceTokenHash: sha256(token),
|
|
197
|
+
installId,
|
|
198
|
+
deviceName: deviceName || matchedDeviceName,
|
|
199
|
+
platform,
|
|
200
|
+
appVersion,
|
|
201
|
+
scopes: [...SCOPES],
|
|
202
|
+
createdAt: new Date(this.now()).toISOString(),
|
|
203
|
+
expiresAt: new Date(this.now() + TOKEN_TTL_SEC * 1000).toISOString(),
|
|
204
|
+
revoked: false,
|
|
205
|
+
};
|
|
206
|
+
this.devices.set(device.deviceTokenHash, device);
|
|
207
|
+
this.byDeviceId.set(device.deviceId, device);
|
|
208
|
+
this.#persist();
|
|
209
|
+
this.log(`pair 兑换成功 device=${device.deviceId}`);
|
|
210
|
+
return {
|
|
211
|
+
deviceId: device.deviceId,
|
|
212
|
+
deviceToken: token,
|
|
213
|
+
tokenType: 'Bearer',
|
|
214
|
+
expiresAt: device.expiresAt,
|
|
215
|
+
scopes: device.scopes,
|
|
216
|
+
pairedAt: device.createdAt,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** 校验 Bearer;失败抛 4001 / 4009(已撤销),均由客户端做不同处理 */
|
|
221
|
+
verify(token) {
|
|
222
|
+
if (!token) throw fail(4001);
|
|
223
|
+
const device = this.devices.get(sha256(token));
|
|
224
|
+
if (!device) throw fail(4001);
|
|
225
|
+
if (device.revoked) throw fail(4009);
|
|
226
|
+
if (Date.parse(device.expiresAt) <= this.now()) throw fail(4001);
|
|
227
|
+
return device;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
revokeAll() {
|
|
231
|
+
let n = 0;
|
|
232
|
+
for (const d of this.devices.values()) {
|
|
233
|
+
if (!d.revoked) {
|
|
234
|
+
d.revoked = true;
|
|
235
|
+
n += 1;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
if (n) {
|
|
239
|
+
this.#persist();
|
|
240
|
+
this.log(`pair 撤销全部设备 n=${n}`);
|
|
241
|
+
}
|
|
242
|
+
return n;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* 桌面面板的设备清单:只回显展示字段,绝不泄露 deviceTokenHash / installId。
|
|
247
|
+
* 撤销过的设备不入列——面板问的是「现在还能连上来的设备」,
|
|
248
|
+
* 历史审计记录留在注册表里供 verify() 回 4009,但不给用户看。
|
|
249
|
+
*/
|
|
250
|
+
listDevices() {
|
|
251
|
+
return [...this.devices.values()]
|
|
252
|
+
.filter((d) => !d.revoked && (!d.expiresAt || Date.parse(d.expiresAt) > this.now()))
|
|
253
|
+
.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
|
|
254
|
+
.map((d) => ({
|
|
255
|
+
deviceId: d.deviceId,
|
|
256
|
+
deviceName: d.deviceName || '未命名设备',
|
|
257
|
+
platform: d.platform,
|
|
258
|
+
appVersion: d.appVersion,
|
|
259
|
+
createdAt: d.createdAt,
|
|
260
|
+
expiresAt: d.expiresAt,
|
|
261
|
+
}));
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* 已认证设备在 WS hello 时回报「关于 → 设备名称」全称,立即覆盖配对时记下的名字。
|
|
266
|
+
* 名字来自设备自身,服务端不截短、不改写;空值忽略,撤销设备不接受改名。
|
|
267
|
+
*/
|
|
268
|
+
renameDevice(deviceId, name) {
|
|
269
|
+
if (typeof name !== 'string') return false;
|
|
270
|
+
const clean = name.trim();
|
|
271
|
+
if (!clean) return false;
|
|
272
|
+
const device = this.byDeviceId.get(String(deviceId || ''));
|
|
273
|
+
if (!device || device.revoked || device.deviceName === clean) return false;
|
|
274
|
+
device.deviceName = clean;
|
|
275
|
+
this.#persist();
|
|
276
|
+
this.log(`pair 更新设备名 device=${device.deviceId} name=${clean}`);
|
|
277
|
+
return true;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** 单设备下线:设备下次带旧凭证请求会收到 4009 并清本地凭证。 */
|
|
281
|
+
revokeDevice(deviceId) {
|
|
282
|
+
const device = this.byDeviceId.get(String(deviceId || ''));
|
|
283
|
+
if (!device || device.revoked) return 0;
|
|
284
|
+
device.revoked = true;
|
|
285
|
+
this.#persist();
|
|
286
|
+
this.log(`pair 下线设备 device=${device.deviceId} name=${device.deviceName || '-'}`);
|
|
287
|
+
return 1;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
get maxDevices() { return MAX_ACTIVE_DEVICES; }
|
|
291
|
+
|
|
292
|
+
stats() {
|
|
293
|
+
return {
|
|
294
|
+
devices: this.devices.size,
|
|
295
|
+
activeDevices: [...this.devices.values()].filter((d) => !d.revoked).length,
|
|
296
|
+
codeActive: Boolean(this.code && this.code.expiresAt > this.now()),
|
|
297
|
+
lockedUntil: this.lockedUntil > this.now() ? new Date(this.lockedUntil).toISOString() : null,
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
}
|