@dsh-mobile/mobile-remote 3.2.7 → 3.3.1
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/FAQ.md +19 -12
- package/LICENSE +0 -0
- package/README.md +40 -40
- package/cordis.patch.yml +8 -4
- package/docs/PRIVACY-POLICY.en.md +89 -47
- package/docs/PRIVACY-POLICY.md +89 -47
- package/docs/SUPPORT.md +5 -5
- package/docs/TERMS-OF-SERVICE.en.md +5 -3
- package/docs/TERMS-OF-SERVICE.md +5 -3
- package/docs/USER-GUIDE.zh-CN.md +562 -0
- package/lib/account-usage.js +0 -0
- package/lib/api-helpers.js +6 -2
- package/lib/assistant-prefs.js +167 -0
- package/lib/auto-config.js +55 -3
- package/lib/backup.js +441 -0
- package/lib/break-reminder.js +133 -0
- package/lib/client.js +321 -77
- package/lib/config.js +96 -5
- package/lib/git-read-bundled-provider.js +32 -3
- package/lib/git-read-service.js +4 -0
- package/lib/host-compat.js +25 -0
- package/lib/http-util.js +6 -2
- package/lib/index.js +1121 -83
- package/lib/memory/context.js +81 -0
- package/lib/memory/decay.js +144 -0
- package/lib/memory/extract.js +146 -0
- package/lib/memory/routes.js +198 -0
- package/lib/memory/store.js +714 -0
- package/lib/notify-copy.js +245 -0
- package/lib/permission-guide.js +184 -0
- package/lib/persona-cards.js +366 -0
- package/lib/proactive-material.js +162 -0
- package/lib/proactive.js +372 -0
- package/lib/protected-paths.js +290 -0
- package/lib/protocol.js +39 -0
- package/lib/rate-limit.js +1 -1
- package/lib/relay/connector.js +208 -14
- package/lib/relay/devices.js +54 -8
- package/lib/relay/fingerprint.js +55 -0
- package/lib/relay/identity.js +69 -0
- package/lib/relay/on-demand.js +89 -0
- package/lib/relay/pairing.js +45 -6
- package/lib/relay/phone.js +89 -12
- package/lib/relay/ws-server.js +245 -0
- package/lib/reminders.js +140 -0
- package/lib/rpc-adapter.js +21 -2
- package/lib/session-rotation.js +198 -0
- package/lib/session-title-cache.js +0 -0
- package/lib/session-title-refresh.js +0 -0
- package/lib/timeline.js +1 -1
- package/package.json +30 -14
- package/CHANGELOG.md +0 -1383
- package/CONTRIBUTING.md +0 -61
- package/docs/00-/345/274/200/345/217/221/346/200/273/347/272/262.md +0 -432
- package/docs/01-PRD.md +0 -148
- package/docs/02-architecture.md +0 -249
- package/docs/03-api.md +0 -882
- package/docs/04-security.md +0 -110
- package/docs/05-test-cases.md +0 -376
- package/docs/06-install-run.md +0 -335
- package/docs/07-user-manual.md +0 -92
- package/docs/08-/346/211/251/345/261/225/345/274/200/345/217/221/346/214/207/345/215/227.md +0 -86
- package/docs/09-compatibility.md +0 -201
- package/docs/11-remote-relay-guide.md +0 -86
- package/docs/APP-ENCRYPTION-DESCRIPTION.md +0 -50
- package/docs/APP-ENCRYPTION-DESCRIPTION.pdf +0 -0
- package/docs/APP-REVIEW-NOTES.md +0 -105
- package/docs/BRAND-ASSETS.md +0 -142
- package/docs/COMPANION-PLAN.md +0 -199
- package/docs/STORE-LAUNCH.md +0 -341
- package/docs/STORE-LISTING.md +0 -190
package/lib/protocol.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* App ↔ plugin protocol and feature negotiation (plan §5.12, T-61).
|
|
3
|
+
*
|
|
4
|
+
* Every computer may run a different plugin version, so the plugin says what it speaks
|
|
5
|
+
* and offers, in `/bootstrap` and in the SSE `hello` frame:
|
|
6
|
+
*
|
|
7
|
+
* - `protocol: { min, max }`: the protocol versions it speaks. Version 1 is the API as it
|
|
8
|
+
* stood when negotiation was added (every older plugin speaks exactly that, without
|
|
9
|
+
* saying so). Raise `max` when the plugin learns a new version; raise `min` only when it
|
|
10
|
+
* drops an old one.
|
|
11
|
+
* - `features`: optional features this build has. The app gates each one per computer
|
|
12
|
+
* and shows "update the plugin on {PC}" instead of calling an endpoint that 404s.
|
|
13
|
+
* - `minAppVersion`: the oldest app that works with this plugin.
|
|
14
|
+
*
|
|
15
|
+
* Feature names are shared with the app (`dsh-mobile-app/lib/plugin_protocol.dart`).
|
|
16
|
+
* Not built yet, and so not listed (the app reserves them): `p2p`, `multi-pc`,
|
|
17
|
+
* `phone-tools`, `toolbox-install`. Add a name here in the same change that ships it.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export const PROTOCOL = Object.freeze({ min: 1, max: 1 });
|
|
21
|
+
|
|
22
|
+
export const FEATURES = Object.freeze([
|
|
23
|
+
// Persona cards: GET/POST/DELETE /api/persona (T-31).
|
|
24
|
+
"persona-cards",
|
|
25
|
+
// Encrypted LAN path: Noise on the LAN bridge port at /v1/lan (T-25). Whether it is on right
|
|
26
|
+
// now (bridge listening, relay identity present) and at which addresses is in
|
|
27
|
+
// `capabilities.lanNoise`; this name says the build has it.
|
|
28
|
+
"lan-noise",
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
/** Apps older than this can't work with this plugin (none so far). */
|
|
32
|
+
export const MIN_APP_VERSION = "3.0.0";
|
|
33
|
+
|
|
34
|
+
/** The fields `/bootstrap` and the `hello` frame carry. */
|
|
35
|
+
export const protocolInfo = () => ({
|
|
36
|
+
protocol: { min: PROTOCOL.min, max: PROTOCOL.max },
|
|
37
|
+
features: [...FEATURES],
|
|
38
|
+
minAppVersion: MIN_APP_VERSION,
|
|
39
|
+
});
|
package/lib/rate-limit.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
export function createLoginRateLimiter(overrides) {
|
|
10
10
|
// 正常用户一次成功即重置计数;frp 等中继场景所有外部请求同源(中继 IP),
|
|
11
|
-
// 阈值 10 次/60s 对单用户足够宽裕(见 docs/
|
|
11
|
+
// 阈值 10 次/60s 对单用户足够宽裕(见 docs/CONSOLIDATED-DOCUMENTATION.en.md Part 04 §2)。
|
|
12
12
|
const rateLimitCfg = { maxFailures: 10, windowMs: 60_000, blockMs: 60_000, ...(overrides ?? {}) };
|
|
13
13
|
const rateBuckets = new Map(); // ip -> { count, windowStart, blockedUntil? }
|
|
14
14
|
// 封锁用显式的 blockedUntil 计时:到阈值那一刻起算 blockMs,与 windowMs 无关。
|
package/lib/relay/connector.js
CHANGED
|
@@ -8,7 +8,23 @@
|
|
|
8
8
|
* 4. 通过后告诉中继 `verified`(解除未确认限额),之后的传输消息解密后交给 MuxSession → serve() 回放给本机 HTTP。
|
|
9
9
|
*
|
|
10
10
|
* 防重放:握手之后 15 秒内必须收到一条能解密的传输数据,否则踢掉——重放者拿不到会话密钥,发不出来。
|
|
11
|
+
*
|
|
12
|
+
* 协议卫生(T-12)
|
|
13
|
+
* · 接满了(会话数到上限)告诉中继 `kick{why:"busy"}`:手机收到的是 4430「电脑忙,稍后重试」,
|
|
14
|
+
* 而不是 4401「这台手机没配对」。
|
|
15
|
+
* · 同一台设备的新会话**收到第一条能解密的数据之后**,踢掉它的旧会话(why:"replaced" → 4409):
|
|
16
|
+
* 手机切网络 / 切后台再回来时,旧连接往往还挂在中继上。必须等能解密的数据——握手消息 1 可以被重放,
|
|
17
|
+
* 不能让重放者把真正在用的会话顶掉。
|
|
18
|
+
* · 中继没动静的检测:每次心跳之后 pongMs 内收不到任何消息就认定连接已死、立刻重连
|
|
19
|
+
* (以前要等 50 秒)。配合中继侧的宽限期,电脑闪断后手机不必重新连接中继。
|
|
20
|
+
*
|
|
21
|
+
* 局域网加密通道(T-25):手机也可以不经中继,直接连电脑 LAN 桥端口上的 `/v1/lan`
|
|
22
|
+
* (见 lib/index.js 的 upgrade 处理与 ./ws-server.js)。路径里不带房间号:局域网上是明文 WebSocket,
|
|
23
|
+
* 房间号是这台电脑的长期标识,不该在咖啡馆的 Wi-Fi 里被同一个 IP 上的陌生主机看到。那条 WebSocket 由 [acceptDirect] 接过来,
|
|
24
|
+
* 跑的是同一个 GuestSession:同样的 Noise IK、同样的设备核对、同样的多路复用与回放——
|
|
25
|
+
* 访问口令从头到尾不出现在局域网上。
|
|
11
26
|
*/
|
|
27
|
+
import { randomBytes } from "node:crypto";
|
|
12
28
|
import { b64u, concat, ed25519Sign, hex } from "./crypto.js";
|
|
13
29
|
import { MuxError, MuxSession } from "./mux.js";
|
|
14
30
|
import { NoiseResponder } from "./noise.js";
|
|
@@ -35,10 +51,12 @@ export class RelayConnector {
|
|
|
35
51
|
this.log = log;
|
|
36
52
|
this.timing = { ...RelayConnector.TIMING, ...timing };
|
|
37
53
|
this.links = urls.map((url) => new RelayLink(this, url.replace(/\/+$/, "")));
|
|
54
|
+
/** 局域网直连的会话(每条一个 DirectLink)。与中继无关:中继停着也照常接。 */
|
|
55
|
+
this.direct = new Set();
|
|
38
56
|
this.stopped = true;
|
|
39
57
|
this.unsubscribe = devices.onRevoke((id) => this.dropDevice(id));
|
|
40
58
|
}
|
|
41
|
-
static TIMING = Object.freeze({ handshakeMs: 15_000, pingMs: 20_000,
|
|
59
|
+
static TIMING = Object.freeze({ handshakeMs: 15_000, pingMs: 20_000, pongMs: 10_000, firstFrameMs: 15_000, backoffMinMs: 1_000, backoffMaxMs: 30_000, maxSessionsPerLink: 16, kickAckMs: 2_000, maxDirect: 16, maxDirectPerIp: 4, directHelloMs: 3_000, directOpenMs: 5_000 });
|
|
42
60
|
|
|
43
61
|
start() {
|
|
44
62
|
if (!this.stopped) return;
|
|
@@ -53,12 +71,49 @@ export class RelayConnector {
|
|
|
53
71
|
this.unsubscribe = null;
|
|
54
72
|
for (const l of this.links) l.shutdown();
|
|
55
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* 接过一条局域网直连的 WebSocket(已完成 HTTP 升级,见 ./ws-server.js)。
|
|
76
|
+
* 接满了(总数 maxDirect,或同一个来源地址 maxDirectPerIp)回 4430,和中继上「电脑忙」一样,手机会稍后重试。
|
|
77
|
+
* 每个来源地址的上限是为了让局域网里的别的设备占不满全部名额,把真正的手机挤到收费的中继上去。
|
|
78
|
+
*/
|
|
79
|
+
acceptDirect(ws, { ip = "" } = {}) {
|
|
80
|
+
let fromIp = 0;
|
|
81
|
+
for (const l of this.direct) if (l.ip === ip) fromIp++;
|
|
82
|
+
if (this.direct.size >= this.timing.maxDirect || fromIp >= this.timing.maxDirectPerIp) {
|
|
83
|
+
ws.close(4430, "host busy");
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
// 撤销设备要能踢掉直连会话:中继停着(stop 取消了订阅)时也一样
|
|
87
|
+
this.unsubscribe ??= this.devices.onRevoke((id) => this.dropDevice(id));
|
|
88
|
+
const link = new DirectLink(this, ws, ip);
|
|
89
|
+
this.direct.add(link);
|
|
90
|
+
return link;
|
|
91
|
+
}
|
|
92
|
+
/** 所有在线会话所在的连接:各条中继 + 各条局域网直连。 */
|
|
93
|
+
allLinks() {
|
|
94
|
+
return [...this.links, ...this.direct];
|
|
95
|
+
}
|
|
56
96
|
status() {
|
|
57
97
|
return this.links.map((l) => ({ url: l.url, state: l.state, since: l.since, lastError: l.lastError, phones: l.sessions.size }));
|
|
58
98
|
}
|
|
59
|
-
/**
|
|
99
|
+
/**
|
|
100
|
+
* Resolves once every kick sent to the relay has been acknowledged (`guest-close`) and every
|
|
101
|
+
* link that was stopping has closed, or after `timeoutMs`. Returns whether it settled in time.
|
|
102
|
+
* (T-62 fix: a revoke must not close the room before the relay has closed the phones with
|
|
103
|
+
* 4401, or they see 4503 "PC offline" and keep retrying.)
|
|
104
|
+
*/
|
|
105
|
+
async settled(timeoutMs = this.timing.kickAckMs + 500) {
|
|
106
|
+
const deadline = Date.now() + timeoutMs;
|
|
107
|
+
const busy = () => this.links.some((l) => l.pendingKicks.size > 0 || l.closing !== null);
|
|
108
|
+
while (busy()) {
|
|
109
|
+
if (Date.now() >= deadline) return false;
|
|
110
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
111
|
+
}
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
/** 设备被撤销:立刻踢掉它所有在线的会话(中继上的与局域网直连的)。 */
|
|
60
115
|
dropDevice(deviceId) {
|
|
61
|
-
for (const l of this.
|
|
116
|
+
for (const l of this.allLinks()) for (const s of [...l.sessions.values()]) if (s.device?.id === deviceId) s.kick("device revoked");
|
|
62
117
|
}
|
|
63
118
|
}
|
|
64
119
|
|
|
@@ -74,6 +129,11 @@ class RelayLink {
|
|
|
74
129
|
this.attempt = 0;
|
|
75
130
|
this.timers = new Set();
|
|
76
131
|
this.lastHeard = 0;
|
|
132
|
+
this.heardSincePing = true;
|
|
133
|
+
/** Guests we kicked whose close the relay has not confirmed yet (`guest-close`). */
|
|
134
|
+
this.pendingKicks = new Set();
|
|
135
|
+
/** While stopping: the timer that closes the link if the relay does not confirm the kicks. */
|
|
136
|
+
this.closing = null;
|
|
77
137
|
}
|
|
78
138
|
#set(state) {
|
|
79
139
|
this.state = state;
|
|
@@ -90,6 +150,7 @@ class RelayLink {
|
|
|
90
150
|
}
|
|
91
151
|
|
|
92
152
|
connect() {
|
|
153
|
+
if (this.closing !== null) this.#finishShutdown(); // a restart while still stopping: finish first
|
|
93
154
|
if (this.o.stopped) return;
|
|
94
155
|
this.#set("connecting");
|
|
95
156
|
let ws;
|
|
@@ -120,6 +181,7 @@ class RelayLink {
|
|
|
120
181
|
#onMessage(ws, data) {
|
|
121
182
|
if (ws !== this.ws) return;
|
|
122
183
|
this.lastHeard = Date.now();
|
|
184
|
+
this.heardSincePing = true;
|
|
123
185
|
try {
|
|
124
186
|
if (typeof data === "string") return this.#onControl(JSON.parse(data));
|
|
125
187
|
const bytes = new Uint8Array(data);
|
|
@@ -147,11 +209,17 @@ class RelayLink {
|
|
|
147
209
|
return this.o.log(`relay: 已连上 ${this.url}`);
|
|
148
210
|
case "guest":
|
|
149
211
|
if (typeof msg.c !== "string" || !/^[0-9a-f]{16}$/.test(msg.c)) return;
|
|
150
|
-
|
|
212
|
+
// Stopping (waiting only for kick acknowledgements): take no new phones.
|
|
213
|
+
if (this.closing !== null || this.o.stopped) return this.control({ t: "kick", c: msg.c, why: "busy" });
|
|
214
|
+
// 接满了:不是「不认识这台手机」,让中继用 4430 关它,手机会稍后重试
|
|
215
|
+
if (this.sessions.size >= this.o.timing.maxSessionsPerLink) return this.control({ t: "kick", c: msg.c, why: "busy" });
|
|
151
216
|
this.sessions.set(msg.c, new GuestSession(this, msg.c));
|
|
152
217
|
return;
|
|
153
218
|
case "guest-close":
|
|
154
|
-
|
|
219
|
+
this.sessions.get(msg.c)?.dispose();
|
|
220
|
+
this.pendingKicks.delete(msg.c);
|
|
221
|
+
if (this.closing !== null && this.pendingKicks.size === 0) this.#finishShutdown();
|
|
222
|
+
return;
|
|
155
223
|
case "pong":
|
|
156
224
|
case "error":
|
|
157
225
|
return;
|
|
@@ -159,14 +227,25 @@ class RelayLink {
|
|
|
159
227
|
}
|
|
160
228
|
}
|
|
161
229
|
#startPing() {
|
|
162
|
-
const { pingMs,
|
|
230
|
+
const { pingMs, pongMs } = this.o.timing;
|
|
163
231
|
const tick = () => {
|
|
164
|
-
|
|
165
|
-
if (
|
|
166
|
-
|
|
167
|
-
return void this.ws?.close();
|
|
168
|
-
}
|
|
232
|
+
const ws = this.ws;
|
|
233
|
+
if (this.o.stopped || this.state !== "online" || !ws) return;
|
|
234
|
+
this.heardSincePing = false;
|
|
169
235
|
this.send(JSON.stringify({ t: "ping" }));
|
|
236
|
+
// 中继对心跳必有回应(pong)。pongMs 内什么都没收到 = 这条连接已经死了(半开的 TCP、
|
|
237
|
+
// 电脑刚从睡眠醒来……):不等系统自己发现,立刻断开重连。
|
|
238
|
+
this.after(Math.min(pongMs, pingMs), () => {
|
|
239
|
+
if (ws !== this.ws || this.state !== "online" || this.heardSincePing) return;
|
|
240
|
+
this.lastError = "relay went silent";
|
|
241
|
+
try {
|
|
242
|
+
ws.close();
|
|
243
|
+
} catch {
|
|
244
|
+
/* 已断开 */
|
|
245
|
+
}
|
|
246
|
+
// 不等对端确认关闭:失联的中继可能连 close 也不回。
|
|
247
|
+
this.#onClose(ws, {});
|
|
248
|
+
});
|
|
170
249
|
this.after(pingMs, tick);
|
|
171
250
|
};
|
|
172
251
|
this.after(pingMs, tick);
|
|
@@ -174,6 +253,9 @@ class RelayLink {
|
|
|
174
253
|
#onClose(ws, event) {
|
|
175
254
|
if (ws !== this.ws) return;
|
|
176
255
|
this.ws = null;
|
|
256
|
+
this.pendingKicks.clear();
|
|
257
|
+
if (this.closing !== null) clearTimeout(this.closing);
|
|
258
|
+
this.closing = null;
|
|
177
259
|
for (const t of this.timers) clearTimeout(t);
|
|
178
260
|
this.timers.clear();
|
|
179
261
|
for (const s of [...this.sessions.values()]) s.dispose();
|
|
@@ -194,6 +276,23 @@ class RelayLink {
|
|
|
194
276
|
for (const t of this.timers) clearTimeout(t);
|
|
195
277
|
this.timers.clear();
|
|
196
278
|
for (const s of [...this.sessions.values()]) s.dispose();
|
|
279
|
+
// T-62 fix: kicks still in flight (a revoked phone) must reach the relay before the room
|
|
280
|
+
// closes, or the phone sees 4503 "PC offline" instead of 4401 "revoked". Keep the socket
|
|
281
|
+
// until the relay confirms them (guest-close), for at most kickAckMs.
|
|
282
|
+
if (this.pendingKicks.size > 0 && this.ws && this.ws.readyState === 1) {
|
|
283
|
+
if (this.closing === null) {
|
|
284
|
+
this.closing = setTimeout(() => this.#finishShutdown(), this.o.timing.kickAckMs);
|
|
285
|
+
this.closing.unref?.();
|
|
286
|
+
}
|
|
287
|
+
this.#set("idle"); // no longer serving; the socket only waits for the acknowledgements
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
this.#finishShutdown();
|
|
291
|
+
}
|
|
292
|
+
#finishShutdown() {
|
|
293
|
+
if (this.closing !== null) clearTimeout(this.closing);
|
|
294
|
+
this.closing = null;
|
|
295
|
+
this.pendingKicks.clear();
|
|
197
296
|
const ws = this.ws;
|
|
198
297
|
this.ws = null;
|
|
199
298
|
try {
|
|
@@ -245,6 +344,7 @@ class GuestSession {
|
|
|
245
344
|
if (this.state === "await-first") {
|
|
246
345
|
this.state = "open";
|
|
247
346
|
clearTimeout(this.timer);
|
|
347
|
+
this.#replaceOlder();
|
|
248
348
|
}
|
|
249
349
|
this.mux.receive(plain);
|
|
250
350
|
} catch (err) {
|
|
@@ -282,12 +382,28 @@ class GuestSession {
|
|
|
282
382
|
if (this.state === "closed") return;
|
|
283
383
|
this.link.send(concat(this.idBytes, this.cipherOut.encrypt(frame)));
|
|
284
384
|
}
|
|
385
|
+
/**
|
|
386
|
+
* 这台设备已经用新连接证明了自己(发来了能解密的数据):它的旧会话让位。
|
|
387
|
+
* 一台手机同一时间只该有一条会话;旧的那条多半是切网络 / 切后台留下的死连接。
|
|
388
|
+
*/
|
|
389
|
+
#replaceOlder() {
|
|
390
|
+
const id = this.device?.id;
|
|
391
|
+
if (!id) return;
|
|
392
|
+
for (const link of this.link.o.allLinks()) {
|
|
393
|
+
for (const other of [...link.sessions.values()]) {
|
|
394
|
+
if (other !== this && other.device?.id === id) other.kick("replaced by a newer connection from the same device", "replaced");
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
285
398
|
|
|
286
|
-
/**
|
|
287
|
-
|
|
399
|
+
/**
|
|
400
|
+
* 拒绝并断开这个访客(同时让中继关掉它)。
|
|
401
|
+
* `why` 告诉中继用哪个关闭码:缺省 4401(不认识 / 不合规);"replaced" → 4409;"busy" → 4430。
|
|
402
|
+
*/
|
|
403
|
+
kick(reason = "kicked", why = "") {
|
|
288
404
|
if (this.state === "closed") return;
|
|
289
405
|
this.link.o.log(`relay: 断开访客 ${this.connId.slice(0, 6)}…(${reason})`);
|
|
290
|
-
this.link.control({ t: "kick", c: this.connId });
|
|
406
|
+
if (this.link.control(why ? { t: "kick", c: this.connId, why } : { t: "kick", c: this.connId })) this.link.pendingKicks.add(this.connId);
|
|
291
407
|
this.dispose();
|
|
292
408
|
}
|
|
293
409
|
dispose() {
|
|
@@ -298,3 +414,81 @@ class GuestSession {
|
|
|
298
414
|
this.link.sessions.delete(this.connId);
|
|
299
415
|
}
|
|
300
416
|
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* 一条局域网直连(T-25)。对 GuestSession 来说它就是一条「只有一位访客的中继连接」:
|
|
420
|
+
* · 中继会先发 `hello{host:true}`、回答心跳:这里照做,手机端不用区分走的是哪条路;
|
|
421
|
+
* · GuestSession 发出的 `connId‖消息` → 去掉 8 字节 connId 直接发给手机;
|
|
422
|
+
* · `verified` 只是告诉中继解除限额,这里没有中继,无事可做;
|
|
423
|
+
* · `kick` → 按 why 用和中继相同的关闭码断开(4401 不认识 / 4409 被顶替 / 4430 忙)。
|
|
424
|
+
* 握手时限、设备核对、防重放都在 GuestSession 里,与中继上完全相同。
|
|
425
|
+
*/
|
|
426
|
+
class DirectLink {
|
|
427
|
+
constructor(owner, ws, ip = "") {
|
|
428
|
+
this.o = owner;
|
|
429
|
+
this.ws = ws;
|
|
430
|
+
this.ip = ip;
|
|
431
|
+
this.url = "lan";
|
|
432
|
+
this.sessions = new Map();
|
|
433
|
+
this.timers = new Set();
|
|
434
|
+
this.closed = false;
|
|
435
|
+
const connId = hex(randomBytes(8));
|
|
436
|
+
this.session = new GuestSession(this, connId);
|
|
437
|
+
this.sessions.set(connId, this.session);
|
|
438
|
+
ws.on("message", (data) => this.#onMessage(data));
|
|
439
|
+
ws.on("close", () => this.dispose());
|
|
440
|
+
this.control({ t: "hello", host: true });
|
|
441
|
+
// 握手前的时限比中继上短:真手机在局域网上几十毫秒就发出消息 1、完成握手;占着不动的连接早点放掉
|
|
442
|
+
const { directHelloMs, directOpenMs } = owner.timing;
|
|
443
|
+
this.after(directHelloMs, () => {
|
|
444
|
+
if (this.session.state === "handshake") this.ws.close(4408, "hello timeout");
|
|
445
|
+
});
|
|
446
|
+
this.after(directOpenMs, () => {
|
|
447
|
+
if (this.session.state !== "open" && this.session.state !== "closed") this.ws.close(4408, "handshake timeout");
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
after(ms, fn) {
|
|
451
|
+
const t = setTimeout(() => {
|
|
452
|
+
this.timers.delete(t);
|
|
453
|
+
fn();
|
|
454
|
+
}, ms);
|
|
455
|
+
t.unref?.();
|
|
456
|
+
this.timers.add(t);
|
|
457
|
+
return t;
|
|
458
|
+
}
|
|
459
|
+
#onMessage(data) {
|
|
460
|
+
if (this.closed) return;
|
|
461
|
+
if (typeof data !== "string") return void this.session.onFrame(data);
|
|
462
|
+
let msg = null;
|
|
463
|
+
try {
|
|
464
|
+
msg = data.length <= 256 ? JSON.parse(data) : null;
|
|
465
|
+
} catch {
|
|
466
|
+
/* 下面统一处理 */
|
|
467
|
+
}
|
|
468
|
+
if (msg?.t === "ping") return void this.ws.send(JSON.stringify({ t: "pong" }));
|
|
469
|
+
this.ws.close(4400, "unknown control");
|
|
470
|
+
}
|
|
471
|
+
send(bytes) {
|
|
472
|
+
if (this.closed || typeof bytes === "string" || bytes.length < 8) return false;
|
|
473
|
+
return this.ws.send(bytes.subarray(8));
|
|
474
|
+
}
|
|
475
|
+
control(obj) {
|
|
476
|
+
if (this.closed) return false;
|
|
477
|
+
if (obj?.t === "kick") {
|
|
478
|
+
const code = obj.why === "busy" ? 4430 : obj.why === "replaced" ? 4409 : 4401;
|
|
479
|
+
this.ws.close(code, obj.why || "kicked");
|
|
480
|
+
return true;
|
|
481
|
+
}
|
|
482
|
+
if (obj?.t === "verified") return true;
|
|
483
|
+
return this.ws.send(JSON.stringify(obj));
|
|
484
|
+
}
|
|
485
|
+
dispose() {
|
|
486
|
+
if (this.closed) return;
|
|
487
|
+
this.closed = true;
|
|
488
|
+
for (const t of this.timers) clearTimeout(t);
|
|
489
|
+
this.timers.clear();
|
|
490
|
+
this.session.dispose();
|
|
491
|
+
this.o.direct.delete(this);
|
|
492
|
+
if (this.ws.readyState === 1) this.ws.close(1001, "going away");
|
|
493
|
+
}
|
|
494
|
+
}
|
package/lib/relay/devices.js
CHANGED
|
@@ -6,6 +6,12 @@
|
|
|
6
6
|
*
|
|
7
7
|
* 配对:桌面生成一次性配对码(5 分钟内有效、只能用一次、最多同时 5 个),放进二维码。手机第一次握手时
|
|
8
8
|
* 在加密负载里带上它;电脑核对通过就把这台手机的公钥登记进名单。以后重连只认公钥。
|
|
9
|
+
*
|
|
10
|
+
* T-71: every code and every device remembers what it was made for. `relay: false` = the desktop's
|
|
11
|
+
* default QR, an encrypted pairing on the local network only (no relay URL in the link); `relay:
|
|
12
|
+
* true` = the remote-access QR. The on-demand relay logic (./on-demand.js) only counts the second
|
|
13
|
+
* kind, so pairing a phone for the LAN never keeps this PC on our relay (C-04). Devices saved before
|
|
14
|
+
* T-71 were all paired through the remote-access QR and load as `relay: true`.
|
|
9
15
|
*/
|
|
10
16
|
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
11
17
|
import { join } from "node:path";
|
|
@@ -42,7 +48,7 @@ export class DeviceStore {
|
|
|
42
48
|
const raw = JSON.parse(readFileSync(this.file, "utf8"));
|
|
43
49
|
if (raw?.v !== 1 || !Array.isArray(raw.devices)) return;
|
|
44
50
|
this.devices = raw.devices
|
|
45
|
-
.map((d) => ({ id: String(d.id), name: cleanName(d.name), pub: b64u.dec(d.pub), createdAt: Number(d.createdAt) || 0, lastSeen: Number(d.lastSeen) || 0 }))
|
|
51
|
+
.map((d) => ({ id: String(d.id), name: cleanName(d.name), pub: b64u.dec(d.pub), createdAt: Number(d.createdAt) || 0, lastSeen: Number(d.lastSeen) || 0, relay: d.relay !== false }))
|
|
46
52
|
.filter((d) => d.pub.length === 32 && d.id === fingerprint(d.pub));
|
|
47
53
|
} catch {
|
|
48
54
|
/* 损坏的名单 = 没有已配对设备(宁可让人重新配对,也不放行不认识的东西) */
|
|
@@ -51,7 +57,7 @@ export class DeviceStore {
|
|
|
51
57
|
#persist() {
|
|
52
58
|
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
53
59
|
const tmp = `${this.file}.${process.pid}.tmp`;
|
|
54
|
-
const body = { v: 1, devices: this.devices.map((d) => ({ id: d.id, name: d.name, pub: b64u.enc(d.pub), createdAt: d.createdAt, lastSeen: d.lastSeen })) };
|
|
60
|
+
const body = { v: 1, devices: this.devices.map((d) => ({ id: d.id, name: d.name, pub: b64u.enc(d.pub), createdAt: d.createdAt, lastSeen: d.lastSeen, relay: d.relay !== false })) };
|
|
55
61
|
writeFileSync(tmp, `${JSON.stringify(body)}\n`, { mode: 0o600 });
|
|
56
62
|
renameSync(tmp, this.file);
|
|
57
63
|
try {
|
|
@@ -64,7 +70,11 @@ export class DeviceStore {
|
|
|
64
70
|
|
|
65
71
|
/** 给 UI 看的列表:不含公钥全文,只有稳定的 id(公钥指纹)。 */
|
|
66
72
|
list() {
|
|
67
|
-
return this.devices.map(({ id, name, createdAt, lastSeen }) => ({ id, name, createdAt, lastSeen }));
|
|
73
|
+
return this.devices.map(({ id, name, createdAt, lastSeen, relay }) => ({ id, name, createdAt, lastSeen, via: relay === false ? "lan" : "relay" }));
|
|
74
|
+
}
|
|
75
|
+
/** How many devices were paired for remote access (the relay), not only for the LAN (T-71, C-04). */
|
|
76
|
+
relayPaired() {
|
|
77
|
+
return this.devices.filter((d) => d.relay !== false).length;
|
|
68
78
|
}
|
|
69
79
|
find(pub) {
|
|
70
80
|
return this.devices.find((d) => equalBytes(d.pub, pub)) ?? null;
|
|
@@ -74,6 +84,13 @@ export class DeviceStore {
|
|
|
74
84
|
if (this.now() - this.lastPersist > 60_000) this.#persist();
|
|
75
85
|
}
|
|
76
86
|
|
|
87
|
+
/** Void every pairing code not yet used (T-62: codes shown with a key that is being replaced). */
|
|
88
|
+
cancelPairings() {
|
|
89
|
+
const n = this.otps.size;
|
|
90
|
+
this.otps.clear();
|
|
91
|
+
return n;
|
|
92
|
+
}
|
|
93
|
+
|
|
77
94
|
/** 撤销设备;返回是否真的删掉了。监听者(连接器)据此踢掉它正在用的连接。 */
|
|
78
95
|
revoke(id) {
|
|
79
96
|
const i = this.devices.findIndex((d) => d.id === id);
|
|
@@ -88,22 +105,39 @@ export class DeviceStore {
|
|
|
88
105
|
return () => this.revokeListeners.delete(fn);
|
|
89
106
|
}
|
|
90
107
|
|
|
91
|
-
/**
|
|
92
|
-
|
|
108
|
+
/**
|
|
109
|
+
* 生成一次性配对码。返回明文码(只此一次)与过期时间。
|
|
110
|
+
* `relay: false` = a code for the LAN-only QR (T-71): the phone it pairs is a LAN device.
|
|
111
|
+
*/
|
|
112
|
+
createPairing(name, { relay = true } = {}) {
|
|
93
113
|
this.#sweep();
|
|
94
114
|
while (this.otps.size >= MAX_PENDING_OTPS) this.otps.delete(this.otps.keys().next().value); // 最旧的让位
|
|
95
115
|
const otp = b64u.enc(randomBytesU8(16));
|
|
96
116
|
const expiresAt = this.now() + this.otpTtlMs;
|
|
97
|
-
this.otps.set(hex(sha256(otp)), { expiresAt, name: name ? cleanName(name) : undefined });
|
|
117
|
+
this.otps.set(hex(sha256(otp)), { expiresAt, name: name ? cleanName(name) : undefined, relay: relay !== false });
|
|
98
118
|
return { otp, expiresAt };
|
|
99
119
|
}
|
|
100
120
|
#sweep() {
|
|
101
121
|
const t = this.now();
|
|
102
122
|
for (const [k, v] of this.otps) if (v.expiresAt <= t) this.otps.delete(k);
|
|
103
123
|
}
|
|
104
|
-
|
|
124
|
+
/** Codes still valid. `{ relay: true }` counts only remote-access codes (T-71, C-04). */
|
|
125
|
+
pendingPairings({ relay } = {}) {
|
|
126
|
+
this.#sweep();
|
|
127
|
+
if (relay === undefined) return this.otps.size;
|
|
128
|
+
let n = 0;
|
|
129
|
+
for (const v of this.otps.values()) if ((v.relay !== false) === relay) n++;
|
|
130
|
+
return n;
|
|
131
|
+
}
|
|
132
|
+
/** 最后一个还有效的配对码什么时候过期(毫秒时间戳);没有则 0。按需连接用它决定何时可以断开中继。 */
|
|
133
|
+
pairingExpiry({ relay } = {}) {
|
|
105
134
|
this.#sweep();
|
|
106
|
-
|
|
135
|
+
let latest = 0;
|
|
136
|
+
for (const v of this.otps.values()) {
|
|
137
|
+
if (relay !== undefined && (v.relay !== false) !== relay) continue;
|
|
138
|
+
if (v.expiresAt > latest) latest = v.expiresAt;
|
|
139
|
+
}
|
|
140
|
+
return latest;
|
|
107
141
|
}
|
|
108
142
|
|
|
109
143
|
/**
|
|
@@ -113,6 +147,17 @@ export class DeviceStore {
|
|
|
113
147
|
authorize(pub, info = {}) {
|
|
114
148
|
const known = this.find(pub);
|
|
115
149
|
if (known) {
|
|
150
|
+
// A LAN-only phone that scans the remote-access QR with the same key: it is a relay
|
|
151
|
+
// device from now on (T-71). The code is used up, as for a new pairing.
|
|
152
|
+
if (known.relay === false && typeof info.otp === "string" && info.otp !== "" && info.otp.length <= 64) {
|
|
153
|
+
this.#sweep();
|
|
154
|
+
const key = hex(sha256(info.otp));
|
|
155
|
+
if (this.otps.get(key)?.relay) {
|
|
156
|
+
this.otps.delete(key);
|
|
157
|
+
known.relay = true;
|
|
158
|
+
this.#persist();
|
|
159
|
+
}
|
|
160
|
+
}
|
|
116
161
|
this.touch(known);
|
|
117
162
|
return { device: known, newlyPaired: false };
|
|
118
163
|
}
|
|
@@ -130,6 +175,7 @@ export class DeviceStore {
|
|
|
130
175
|
pub: pub.slice(),
|
|
131
176
|
createdAt: this.now(),
|
|
132
177
|
lastSeen: this.now(),
|
|
178
|
+
relay: entry.relay !== false,
|
|
133
179
|
};
|
|
134
180
|
this.devices.push(device);
|
|
135
181
|
this.#persist();
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 配对指纹的算法与显示格式——**电脑端与手机端共用这一份定义**。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独抽一个文件:手机(Dart)和电脑(JS)各自算一次指纹,只要算法或分组
|
|
5
|
+
* 差一点,用户就会看到两个不同的字符串,然后合理地拒绝连接——一个安全功能
|
|
6
|
+
* 变成「连不上」的元凶。把电脑侧的算法收在这里,测试可以直接对着它跑,
|
|
7
|
+
* 而不是去 `lib/client.js` 那个需要完整 React/浏览器沙箱才能加载的模块里取。
|
|
8
|
+
*
|
|
9
|
+
* 手机侧的对应实现:`dsh-mobile-app/lib/relay/fingerprint.dart`。
|
|
10
|
+
* 两边的测试(`test/pairing-fingerprint.test.mjs` 与
|
|
11
|
+
* `dsh-mobile-app/test/relay_fingerprint_test.dart`)都用同一组向量对拍,
|
|
12
|
+
* 改任何一边都必须同时改另一边。
|
|
13
|
+
*
|
|
14
|
+
* 算法与服务端设备列表 `lib/relay/devices.js` 的 `fingerprint()` 一致:
|
|
15
|
+
* sha256(公钥) 的十六进制前 16 个字符。
|
|
16
|
+
*/
|
|
17
|
+
import { createHash } from "node:crypto";
|
|
18
|
+
|
|
19
|
+
/** 指纹的十六进制长度。 */
|
|
20
|
+
export const FINGERPRINT_HEX_LEN = 16;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* 算一把 X25519 公钥的指纹。
|
|
24
|
+
*
|
|
25
|
+
* @param {Buffer|Uint8Array} publicKey 32 字节公钥
|
|
26
|
+
* @returns {string} 16 位小写十六进制
|
|
27
|
+
*/
|
|
28
|
+
export function pairingFingerprint(publicKey) {
|
|
29
|
+
if (!publicKey || publicKey.length !== 32) {
|
|
30
|
+
throw new Error(`公钥必须是 32 字节(X25519),实际 ${publicKey?.length ?? 0}`);
|
|
31
|
+
}
|
|
32
|
+
return createHash("sha256").update(publicKey).digest("hex").slice(0, FINGERPRINT_HEX_LEN);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 把 16 位十六进制拆成 4 组 4 位,供界面显示。
|
|
37
|
+
*
|
|
38
|
+
* 分组是为了能一眼念出来、也方便和另一块屏幕逐段比。一整串 16 位连着写,
|
|
39
|
+
* 眼睛会串行——而这一串的意义正是让人认真核对。
|
|
40
|
+
*
|
|
41
|
+
* 非法输入原样返回(不抛):这是展示层,不该因为一个坏字符串把面板弄崩。
|
|
42
|
+
*
|
|
43
|
+
* @param {string} hex
|
|
44
|
+
* @returns {string}
|
|
45
|
+
*/
|
|
46
|
+
export function formatPairingFingerprint(hex) {
|
|
47
|
+
const clean = String(hex ?? "").toLowerCase().replace(/[^0-9a-f]/g, "");
|
|
48
|
+
if (clean.length !== FINGERPRINT_HEX_LEN) return String(hex ?? "");
|
|
49
|
+
return [
|
|
50
|
+
clean.slice(0, 4),
|
|
51
|
+
clean.slice(4, 8),
|
|
52
|
+
clean.slice(8, 12),
|
|
53
|
+
clean.slice(12, 16),
|
|
54
|
+
].join(" ");
|
|
55
|
+
}
|
package/lib/relay/identity.js
CHANGED
|
@@ -27,6 +27,75 @@ const valid = (raw) => {
|
|
|
27
27
|
* 读取身份;没有就生成并落盘。文件存在但损坏时**不覆盖**:改名留档后再生成(旧文件已不可用,
|
|
28
28
|
* 但留着方便排查,也不会因为一次读失败就悄悄销毁一个有效身份)。
|
|
29
29
|
*/
|
|
30
|
+
/**
|
|
31
|
+
* Replace the PC's identity with a fresh one (T-62: after a device is revoked). The old private
|
|
32
|
+
* keys are overwritten, not kept: a revoked phone must not be able to talk to this PC again.
|
|
33
|
+
* Every phone pinned the old public key and room, so all of them have to pair again.
|
|
34
|
+
*/
|
|
35
|
+
export function rotateIdentity(dir) {
|
|
36
|
+
const file = join(dir, "identity.json");
|
|
37
|
+
const ed = ed25519Generate();
|
|
38
|
+
const x = x25519Generate();
|
|
39
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
40
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
41
|
+
writeFileSync(
|
|
42
|
+
tmp,
|
|
43
|
+
`${JSON.stringify({ v: 1, ed25519: { pub: b64u.enc(ed.pub), priv: b64u.enc(ed.priv) }, x25519: { pub: b64u.enc(x.pub), priv: b64u.enc(x.priv) } })}\n`,
|
|
44
|
+
{ mode: 0o600 },
|
|
45
|
+
);
|
|
46
|
+
renameSync(tmp, file);
|
|
47
|
+
try {
|
|
48
|
+
chmodSync(file, 0o600);
|
|
49
|
+
} catch {
|
|
50
|
+
/* Windows 上无意义 */
|
|
51
|
+
}
|
|
52
|
+
return { ed, x, roomId: roomIdOf(ed.pub), file, created: true };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** How long an old room keeps answering after a rotation (T-62 fix). */
|
|
56
|
+
export const RETIRED_ROOM_MS = 7 * 24 * 60 * 60_000;
|
|
57
|
+
const MAX_RETIRED = 4;
|
|
58
|
+
const encodeIdentity = (id) => ({ v: 1, ed25519: { pub: b64u.enc(id.ed.pub), priv: b64u.enc(id.ed.priv) }, x25519: { pub: b64u.enc(id.x.pub), priv: b64u.enc(id.x.priv) } });
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Identities replaced by a rotation, still used for a while to answer their old room
|
|
62
|
+
* (`<dir>/retired.json`, 0600): phones that dial it get 4401 "revoked, pair again" instead of
|
|
63
|
+
* waiting for a computer that never comes. Expired entries are dropped on every read.
|
|
64
|
+
* @returns {{ identity: object, until: number }[]}
|
|
65
|
+
*/
|
|
66
|
+
export function loadRetiredIdentities(dir, now = Date.now()) {
|
|
67
|
+
const file = join(dir, "retired.json");
|
|
68
|
+
if (!existsSync(file)) return [];
|
|
69
|
+
let raw;
|
|
70
|
+
try {
|
|
71
|
+
raw = JSON.parse(readFileSync(file, "utf8"));
|
|
72
|
+
} catch {
|
|
73
|
+
return [];
|
|
74
|
+
}
|
|
75
|
+
const live = (Array.isArray(raw?.items) ? raw.items : [])
|
|
76
|
+
.filter((item) => Number.isFinite(item?.until) && item.until > now)
|
|
77
|
+
.map((item) => ({ until: item.until, parsed: valid(item.identity) }))
|
|
78
|
+
.filter((item) => item.parsed)
|
|
79
|
+
.map(({ until, parsed }) => ({ until, identity: { ...parsed, roomId: roomIdOf(parsed.ed.pub) } }));
|
|
80
|
+
if (live.length !== (raw?.items?.length ?? 0)) saveRetired(dir, live);
|
|
81
|
+
return live;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function saveRetired(dir, items) {
|
|
85
|
+
const file = join(dir, "retired.json");
|
|
86
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
87
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
88
|
+
writeFileSync(tmp, `${JSON.stringify({ items: items.map((i) => ({ until: i.until, identity: encodeIdentity(i.identity) })) })}\n`, { mode: 0o600 });
|
|
89
|
+
renameSync(tmp, file);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Keep `identity` answering its old room until `until`. Returns the live list. */
|
|
93
|
+
export function retireIdentity(dir, identity, until) {
|
|
94
|
+
const items = [...loadRetiredIdentities(dir), { identity, until }].slice(-MAX_RETIRED);
|
|
95
|
+
saveRetired(dir, items);
|
|
96
|
+
return items;
|
|
97
|
+
}
|
|
98
|
+
|
|
30
99
|
export function loadOrCreateIdentity(dir, { log = () => {} } = {}) {
|
|
31
100
|
const file = join(dir, "identity.json");
|
|
32
101
|
if (existsSync(file)) {
|