@dsh-mobile/mobile-remote 3.2.7 → 3.3.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.
Files changed (62) hide show
  1. package/FAQ.md +19 -12
  2. package/README.md +38 -39
  3. package/cordis.patch.yml +8 -4
  4. package/docs/PRIVACY-POLICY.en.md +87 -46
  5. package/docs/PRIVACY-POLICY.md +87 -46
  6. package/docs/SUPPORT.md +5 -5
  7. package/docs/USER-GUIDE.zh-CN.md +562 -0
  8. package/lib/assistant-prefs.js +147 -0
  9. package/lib/auto-config.js +55 -3
  10. package/lib/backup.js +405 -0
  11. package/lib/break-reminder.js +133 -0
  12. package/lib/client.js +56 -10
  13. package/lib/config.js +94 -5
  14. package/lib/git-read-bundled-provider.js +12 -3
  15. package/lib/git-read-service.js +4 -0
  16. package/lib/host-compat.js +25 -0
  17. package/lib/http-util.js +6 -2
  18. package/lib/index.js +949 -70
  19. package/lib/memory/context.js +76 -0
  20. package/lib/memory/decay.js +144 -0
  21. package/lib/memory/extract.js +146 -0
  22. package/lib/memory/routes.js +198 -0
  23. package/lib/memory/store.js +667 -0
  24. package/lib/notify-copy.js +245 -0
  25. package/lib/permission-guide.js +184 -0
  26. package/lib/persona-cards.js +362 -0
  27. package/lib/proactive-material.js +162 -0
  28. package/lib/proactive.js +369 -0
  29. package/lib/protected-paths.js +130 -0
  30. package/lib/protocol.js +35 -0
  31. package/lib/rate-limit.js +1 -1
  32. package/lib/relay/connector.js +97 -12
  33. package/lib/relay/devices.js +14 -0
  34. package/lib/relay/fingerprint.js +55 -0
  35. package/lib/relay/identity.js +69 -0
  36. package/lib/relay/on-demand.js +84 -0
  37. package/lib/relay/phone.js +87 -12
  38. package/lib/reminders.js +140 -0
  39. package/lib/rpc-adapter.js +21 -2
  40. package/lib/session-rotation.js +198 -0
  41. package/lib/timeline.js +1 -1
  42. package/package.json +30 -14
  43. package/CHANGELOG.md +0 -1383
  44. package/CONTRIBUTING.md +0 -61
  45. package/docs/00-/345/274/200/345/217/221/346/200/273/347/272/262.md +0 -432
  46. package/docs/01-PRD.md +0 -148
  47. package/docs/02-architecture.md +0 -249
  48. package/docs/03-api.md +0 -882
  49. package/docs/04-security.md +0 -110
  50. package/docs/05-test-cases.md +0 -376
  51. package/docs/06-install-run.md +0 -335
  52. package/docs/07-user-manual.md +0 -92
  53. package/docs/08-/346/211/251/345/261/225/345/274/200/345/217/221/346/214/207/345/215/227.md +0 -86
  54. package/docs/09-compatibility.md +0 -201
  55. package/docs/11-remote-relay-guide.md +0 -86
  56. package/docs/APP-ENCRYPTION-DESCRIPTION.md +0 -50
  57. package/docs/APP-ENCRYPTION-DESCRIPTION.pdf +0 -0
  58. package/docs/APP-REVIEW-NOTES.md +0 -105
  59. package/docs/BRAND-ASSETS.md +0 -142
  60. package/docs/COMPANION-PLAN.md +0 -199
  61. package/docs/STORE-LAUNCH.md +0 -341
  62. package/docs/STORE-LISTING.md +0 -190
@@ -8,6 +8,15 @@
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 秒)。配合中继侧的宽限期,电脑闪断后手机不必重新连接中继。
11
20
  */
12
21
  import { b64u, concat, ed25519Sign, hex } from "./crypto.js";
13
22
  import { MuxError, MuxSession } from "./mux.js";
@@ -38,7 +47,7 @@ export class RelayConnector {
38
47
  this.stopped = true;
39
48
  this.unsubscribe = devices.onRevoke((id) => this.dropDevice(id));
40
49
  }
41
- static TIMING = Object.freeze({ handshakeMs: 15_000, pingMs: 20_000, deadMs: 50_000, firstFrameMs: 15_000, backoffMinMs: 1_000, backoffMaxMs: 30_000, maxSessionsPerLink: 16 });
50
+ 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 });
42
51
 
43
52
  start() {
44
53
  if (!this.stopped) return;
@@ -56,6 +65,21 @@ export class RelayConnector {
56
65
  status() {
57
66
  return this.links.map((l) => ({ url: l.url, state: l.state, since: l.since, lastError: l.lastError, phones: l.sessions.size }));
58
67
  }
68
+ /**
69
+ * Resolves once every kick sent to the relay has been acknowledged (`guest-close`) and every
70
+ * link that was stopping has closed, or after `timeoutMs`. Returns whether it settled in time.
71
+ * (T-62 fix: a revoke must not close the room before the relay has closed the phones with
72
+ * 4401, or they see 4503 "PC offline" and keep retrying.)
73
+ */
74
+ async settled(timeoutMs = this.timing.kickAckMs + 500) {
75
+ const deadline = Date.now() + timeoutMs;
76
+ const busy = () => this.links.some((l) => l.pendingKicks.size > 0 || l.closing !== null);
77
+ while (busy()) {
78
+ if (Date.now() >= deadline) return false;
79
+ await new Promise((resolve) => setTimeout(resolve, 10));
80
+ }
81
+ return true;
82
+ }
59
83
  /** 设备被撤销:立刻踢掉它所有在线的会话。 */
60
84
  dropDevice(deviceId) {
61
85
  for (const l of this.links) for (const s of [...l.sessions.values()]) if (s.device?.id === deviceId) s.kick("device revoked");
@@ -74,6 +98,11 @@ class RelayLink {
74
98
  this.attempt = 0;
75
99
  this.timers = new Set();
76
100
  this.lastHeard = 0;
101
+ this.heardSincePing = true;
102
+ /** Guests we kicked whose close the relay has not confirmed yet (`guest-close`). */
103
+ this.pendingKicks = new Set();
104
+ /** While stopping: the timer that closes the link if the relay does not confirm the kicks. */
105
+ this.closing = null;
77
106
  }
78
107
  #set(state) {
79
108
  this.state = state;
@@ -90,6 +119,7 @@ class RelayLink {
90
119
  }
91
120
 
92
121
  connect() {
122
+ if (this.closing !== null) this.#finishShutdown(); // a restart while still stopping: finish first
93
123
  if (this.o.stopped) return;
94
124
  this.#set("connecting");
95
125
  let ws;
@@ -120,6 +150,7 @@ class RelayLink {
120
150
  #onMessage(ws, data) {
121
151
  if (ws !== this.ws) return;
122
152
  this.lastHeard = Date.now();
153
+ this.heardSincePing = true;
123
154
  try {
124
155
  if (typeof data === "string") return this.#onControl(JSON.parse(data));
125
156
  const bytes = new Uint8Array(data);
@@ -147,11 +178,17 @@ class RelayLink {
147
178
  return this.o.log(`relay: 已连上 ${this.url}`);
148
179
  case "guest":
149
180
  if (typeof msg.c !== "string" || !/^[0-9a-f]{16}$/.test(msg.c)) return;
150
- if (this.sessions.size >= this.o.timing.maxSessionsPerLink) return this.control({ t: "kick", c: msg.c });
181
+ // Stopping (waiting only for kick acknowledgements): take no new phones.
182
+ if (this.closing !== null || this.o.stopped) return this.control({ t: "kick", c: msg.c, why: "busy" });
183
+ // 接满了:不是「不认识这台手机」,让中继用 4430 关它,手机会稍后重试
184
+ if (this.sessions.size >= this.o.timing.maxSessionsPerLink) return this.control({ t: "kick", c: msg.c, why: "busy" });
151
185
  this.sessions.set(msg.c, new GuestSession(this, msg.c));
152
186
  return;
153
187
  case "guest-close":
154
- return void this.sessions.get(msg.c)?.dispose();
188
+ this.sessions.get(msg.c)?.dispose();
189
+ this.pendingKicks.delete(msg.c);
190
+ if (this.closing !== null && this.pendingKicks.size === 0) this.#finishShutdown();
191
+ return;
155
192
  case "pong":
156
193
  case "error":
157
194
  return;
@@ -159,14 +196,25 @@ class RelayLink {
159
196
  }
160
197
  }
161
198
  #startPing() {
162
- const { pingMs, deadMs } = this.o.timing;
199
+ const { pingMs, pongMs } = this.o.timing;
163
200
  const tick = () => {
164
- if (this.o.stopped || this.state !== "online") return;
165
- if (Date.now() - this.lastHeard > deadMs) {
166
- this.lastError = "relay went silent";
167
- return void this.ws?.close();
168
- }
201
+ const ws = this.ws;
202
+ if (this.o.stopped || this.state !== "online" || !ws) return;
203
+ this.heardSincePing = false;
169
204
  this.send(JSON.stringify({ t: "ping" }));
205
+ // 中继对心跳必有回应(pong)。pongMs 内什么都没收到 = 这条连接已经死了(半开的 TCP、
206
+ // 电脑刚从睡眠醒来……):不等系统自己发现,立刻断开重连。
207
+ this.after(Math.min(pongMs, pingMs), () => {
208
+ if (ws !== this.ws || this.state !== "online" || this.heardSincePing) return;
209
+ this.lastError = "relay went silent";
210
+ try {
211
+ ws.close();
212
+ } catch {
213
+ /* 已断开 */
214
+ }
215
+ // 不等对端确认关闭:失联的中继可能连 close 也不回。
216
+ this.#onClose(ws, {});
217
+ });
170
218
  this.after(pingMs, tick);
171
219
  };
172
220
  this.after(pingMs, tick);
@@ -174,6 +222,9 @@ class RelayLink {
174
222
  #onClose(ws, event) {
175
223
  if (ws !== this.ws) return;
176
224
  this.ws = null;
225
+ this.pendingKicks.clear();
226
+ if (this.closing !== null) clearTimeout(this.closing);
227
+ this.closing = null;
177
228
  for (const t of this.timers) clearTimeout(t);
178
229
  this.timers.clear();
179
230
  for (const s of [...this.sessions.values()]) s.dispose();
@@ -194,6 +245,23 @@ class RelayLink {
194
245
  for (const t of this.timers) clearTimeout(t);
195
246
  this.timers.clear();
196
247
  for (const s of [...this.sessions.values()]) s.dispose();
248
+ // T-62 fix: kicks still in flight (a revoked phone) must reach the relay before the room
249
+ // closes, or the phone sees 4503 "PC offline" instead of 4401 "revoked". Keep the socket
250
+ // until the relay confirms them (guest-close), for at most kickAckMs.
251
+ if (this.pendingKicks.size > 0 && this.ws && this.ws.readyState === 1) {
252
+ if (this.closing === null) {
253
+ this.closing = setTimeout(() => this.#finishShutdown(), this.o.timing.kickAckMs);
254
+ this.closing.unref?.();
255
+ }
256
+ this.#set("idle"); // no longer serving; the socket only waits for the acknowledgements
257
+ return;
258
+ }
259
+ this.#finishShutdown();
260
+ }
261
+ #finishShutdown() {
262
+ if (this.closing !== null) clearTimeout(this.closing);
263
+ this.closing = null;
264
+ this.pendingKicks.clear();
197
265
  const ws = this.ws;
198
266
  this.ws = null;
199
267
  try {
@@ -245,6 +313,7 @@ class GuestSession {
245
313
  if (this.state === "await-first") {
246
314
  this.state = "open";
247
315
  clearTimeout(this.timer);
316
+ this.#replaceOlder();
248
317
  }
249
318
  this.mux.receive(plain);
250
319
  } catch (err) {
@@ -282,12 +351,28 @@ class GuestSession {
282
351
  if (this.state === "closed") return;
283
352
  this.link.send(concat(this.idBytes, this.cipherOut.encrypt(frame)));
284
353
  }
354
+ /**
355
+ * 这台设备已经用新连接证明了自己(发来了能解密的数据):它的旧会话让位。
356
+ * 一台手机同一时间只该有一条会话;旧的那条多半是切网络 / 切后台留下的死连接。
357
+ */
358
+ #replaceOlder() {
359
+ const id = this.device?.id;
360
+ if (!id) return;
361
+ for (const link of this.link.o.links) {
362
+ for (const other of [...link.sessions.values()]) {
363
+ if (other !== this && other.device?.id === id) other.kick("replaced by a newer connection from the same device", "replaced");
364
+ }
365
+ }
366
+ }
285
367
 
286
- /** 拒绝并断开这个访客(同时让中继关掉它)。 */
287
- kick(reason = "kicked") {
368
+ /**
369
+ * 拒绝并断开这个访客(同时让中继关掉它)。
370
+ * `why` 告诉中继用哪个关闭码:缺省 4401(不认识 / 不合规);"replaced" → 4409;"busy" → 4430。
371
+ */
372
+ kick(reason = "kicked", why = "") {
288
373
  if (this.state === "closed") return;
289
374
  this.link.o.log(`relay: 断开访客 ${this.connId.slice(0, 6)}…(${reason})`);
290
- this.link.control({ t: "kick", c: this.connId });
375
+ if (this.link.control(why ? { t: "kick", c: this.connId, why } : { t: "kick", c: this.connId })) this.link.pendingKicks.add(this.connId);
291
376
  this.dispose();
292
377
  }
293
378
  dispose() {
@@ -74,6 +74,13 @@ export class DeviceStore {
74
74
  if (this.now() - this.lastPersist > 60_000) this.#persist();
75
75
  }
76
76
 
77
+ /** Void every pairing code not yet used (T-62: codes shown with a key that is being replaced). */
78
+ cancelPairings() {
79
+ const n = this.otps.size;
80
+ this.otps.clear();
81
+ return n;
82
+ }
83
+
77
84
  /** 撤销设备;返回是否真的删掉了。监听者(连接器)据此踢掉它正在用的连接。 */
78
85
  revoke(id) {
79
86
  const i = this.devices.findIndex((d) => d.id === id);
@@ -105,6 +112,13 @@ export class DeviceStore {
105
112
  this.#sweep();
106
113
  return this.otps.size;
107
114
  }
115
+ /** 最后一个还有效的配对码什么时候过期(毫秒时间戳);没有则 0。按需连接用它决定何时可以断开中继。 */
116
+ pairingExpiry() {
117
+ this.#sweep();
118
+ let latest = 0;
119
+ for (const v of this.otps.values()) if (v.expiresAt > latest) latest = v.expiresAt;
120
+ return latest;
121
+ }
108
122
 
109
123
  /**
110
124
  * 握手成功之后、放行之前的最后一道关:这把公钥是不是我们认的?
@@ -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
+ }
@@ -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)) {
@@ -0,0 +1,84 @@
1
+ /**
2
+ * 按需连接中继(T-11)。
3
+ *
4
+ * 以前只要 relay.enabled 为 true(默认),插件一启动就连上公共中继——哪怕这台电脑从来没配对过手机。
5
+ * 那条连接没有任何用处(没有已配对设备、也没有有效的配对码时,谁都进不来),却让每一台装了插件的
6
+ * 电脑都常驻一条到我们服务器的连接:成本随安装量增长,隐私文本也没法说「不配对就不联网」。
7
+ *
8
+ * 现在的规则:**只有在「有人可能进得来」的时候才连**——
9
+ * · 已经有至少一台经中继配对的手机;或
10
+ * · 用户刚在桌面上要了一个配对码(5 分钟内有效)。
11
+ * 两个条件都不成立就断开:全新安装不产生任何中继连接;撤销最后一台设备、配对码过期没人用,也会断开。
12
+ *
13
+ * 这个模块只做「该不该连」的判断,连接本身仍由 RelayConnector 负责(重连、心跳、会话)。
14
+ */
15
+
16
+ /**
17
+ * @param {{ connector: { start():void, stop():void },
18
+ * devices: { list():unknown[], pendingPairings():number, pairingExpiry():number, onRevoke(fn:()=>void):()=>void },
19
+ * log?: (m:string)=>void, now?: ()=>number,
20
+ * setTimer?: typeof setTimeout, clearTimer?: typeof clearTimeout }} o
21
+ */
22
+ export function createRelayDemand({ connector, devices, log = () => {}, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout }) {
23
+ let enabled = false; // 插件是否在运行(effect 生效期间)
24
+ let active = false; // 连接器是否被我们启动了
25
+ let timer = null;
26
+
27
+ const paired = () => devices.list().length > 0;
28
+ const wanted = () => paired() || devices.pendingPairings() > 0;
29
+ const disarm = () => {
30
+ if (timer) clearTimer(timer);
31
+ timer = null;
32
+ };
33
+
34
+ /** 对一下表:该连就连,不该连就断。可以随便多调。返回当前是否在连。 */
35
+ const sync = () => {
36
+ disarm();
37
+ if (!enabled) return active;
38
+ const want = wanted();
39
+ if (want && !active) {
40
+ active = true;
41
+ connector.start();
42
+ log(paired() ? "relay: 有已配对的手机,连接中继" : "relay: 已生成配对码,连接中继等待手机");
43
+ } else if (!want && active) {
44
+ active = false;
45
+ connector.stop();
46
+ log("relay: 没有已配对的手机,也没有有效的配对码,已断开中继");
47
+ }
48
+ // 只靠配对码撑着的连接:最后一个码过期后再对一次表(码被用掉 → 有设备了 → 继续连着)
49
+ if (active && !paired()) {
50
+ timer = setTimer(sync, Math.max(1_000, devices.pairingExpiry() - now() + 1_000));
51
+ timer.unref?.();
52
+ }
53
+ return active;
54
+ };
55
+
56
+ // 撤销设备:连接器先踢掉它的会话(它的监听器注册在前),这里再看还需不需要连着
57
+ const unsubscribe = devices.onRevoke(() => sync());
58
+
59
+ return {
60
+ sync,
61
+ wanted,
62
+ get active() {
63
+ return active;
64
+ },
65
+ /** 插件启动:开始按需连接。 */
66
+ start() {
67
+ enabled = true;
68
+ return sync();
69
+ },
70
+ /** 插件停止 / 重载:断开,并且在下一次 start() 之前不再连接。 */
71
+ stop() {
72
+ enabled = false;
73
+ disarm();
74
+ if (active) {
75
+ active = false;
76
+ connector.stop();
77
+ }
78
+ },
79
+ dispose() {
80
+ this.stop();
81
+ unsubscribe();
82
+ },
83
+ };
84
+ }
@@ -6,6 +6,14 @@
6
6
  *
7
7
  * 流程:连中继(访客身份)→ 等房主在线 → Noise 发起方握手(消息 1 里带上设备名与一次性配对码)→
8
8
  * 读消息 2 → 之后所有流量都是 Noise 传输消息,里面跑多路复用的 HTTP。
9
+ *
10
+ * 电脑闪断后在原连接上续用(`resume: true`,访客协议 v2,见 relay/hub.js「访客协议版本」)
11
+ * 连接地址带 `?v=2`,告诉中继「我认得 host-down,也会在原连接上重新握手」。之后:
12
+ * host-down → 这条 Noise 会话作废:在途请求立刻失败,停止发送,等中继的下一句话;
13
+ * host-up → 用同一把设备密钥在**同一条连接**上重新握手(不带配对码——它已经用掉了),
14
+ * 握手完成后换上新的密钥与新的多路复用会话,`phone.resumes` 加一;
15
+ * 4503 → 电脑没在宽限期内回来,连接关闭,和以前一样重新连接。
16
+ * 不带 `resume`(缺省)就是所有已发布旧版 App 的行为:收到 host-up 只把会话作废,由上层另开连接。
9
17
  */
10
18
  import { MuxSession } from "./mux.js";
11
19
  import { NoiseInitiator } from "./noise.js";
@@ -19,10 +27,36 @@ export class PhoneSession {
19
27
  this.closeCode = null;
20
28
  this.closeReason = "";
21
29
  this.closed = new Promise((resolve) => (this._resolveClosed = resolve));
30
+ /** open = 会话可用;down = 电脑闪断、等它回来;handshake = 正在(重新)握手。 */
31
+ this.state = "handshake";
32
+ /** 在原连接上重新握手成功的次数。 */
33
+ this.resumes = 0;
34
+ this._waiters = [];
22
35
  }
23
36
  request(req) {
37
+ if (!this.mux) return Promise.reject(new Error(this.state === "open" ? "session closed" : "computer is reconnecting"));
24
38
  return this.mux.request(req);
25
39
  }
40
+ /** 等会话(重新)可用。连接已关闭、或 `timeoutMs` 内没等到,则拒绝。 */
41
+ whenOpen(timeoutMs = 10_000) {
42
+ if (this.closeCode !== null) return Promise.reject(new Error(`closed (${this.closeCode})`));
43
+ if (this.state === "open") return Promise.resolve(this);
44
+ return new Promise((resolve, reject) => {
45
+ const waiter = { resolve, reject, timer: setTimeout(() => {
46
+ this._waiters = this._waiters.filter((w) => w !== waiter);
47
+ reject(new Error("timed out waiting for the computer"));
48
+ }, timeoutMs) };
49
+ this._waiters.push(waiter);
50
+ });
51
+ }
52
+ _setState(state) {
53
+ this.state = state;
54
+ if (state !== "open") return;
55
+ for (const w of this._waiters.splice(0)) {
56
+ clearTimeout(w.timer);
57
+ w.resolve(this);
58
+ }
59
+ }
26
60
  close(code = 1000, reason = "bye") {
27
61
  this._shutdown(code, reason);
28
62
  try {
@@ -36,23 +70,29 @@ export class PhoneSession {
36
70
  this.closeCode = code;
37
71
  this.closeReason = reason;
38
72
  clearInterval(this.pinger);
73
+ clearTimeout(this._rehandshakeTimer);
39
74
  this.mux?.close(`closed ${code}`);
75
+ for (const w of this._waiters.splice(0)) {
76
+ clearTimeout(w.timer);
77
+ w.reject(new Error(`closed (${code})`));
78
+ }
40
79
  this._resolveClosed({ code, reason });
41
80
  }
42
81
  }
43
82
 
44
83
  /**
45
84
  * @param {{ relayUrl:string, room:string, pcPub:Uint8Array, device:{priv:Uint8Array,pub:Uint8Array},
46
- * name?:string, otp?:string, WebSocketImpl?:Function, timeoutMs?:number }} o
85
+ * name?:string, otp?:string, WebSocketImpl?:Function, timeoutMs?:number, resume?:boolean }} o
47
86
  */
48
- export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", otp, WebSocketImpl = globalThis.WebSocket, timeoutMs = 10_000 }) {
87
+ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", otp, WebSocketImpl = globalThis.WebSocket, timeoutMs = 10_000, resume = false }) {
49
88
  return new Promise((resolve, reject) => {
50
89
  const phone = new PhoneSession();
51
- const ws = new WebSocketImpl(`${relayUrl.replace(/\/+$/, "")}/v1/guest/${room}`);
90
+ const ws = new WebSocketImpl(`${relayUrl.replace(/\/+$/, "")}/v1/guest/${room}${resume ? "?v=2" : ""}`);
52
91
  ws.binaryType = "arraybuffer";
53
92
  phone.ws = ws;
54
- const noise = new NoiseInitiator({ s: device, rs: pcPub, prologue: enc.encode(`DSH-RELAY/1|${room}`) });
55
- let stage = "relay"; // relay → handshake → open
93
+ let noise = null;
94
+ let stage = "relay"; // relay → handshake → open(resume 时还有:→ down → handshake → open …)
95
+ let opened = false; // 第一次握手完成过了吗(connectPhone 的 Promise 只在那时兑现)
56
96
  let cipherOut = null;
57
97
  let cipherIn = null;
58
98
  const fail = (err) => {
@@ -67,19 +107,43 @@ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", ot
67
107
  };
68
108
  const timer = setTimeout(() => fail(new Error(`connect timeout in stage ${stage}`)), timeoutMs);
69
109
 
110
+ /** 握手总是全新的一次:新的临时密钥、新的握手哈希。重握时不带配对码(它是一次性的,已经用掉)。 */
70
111
  const startHandshake = () => {
112
+ noise = new NoiseInitiator({ s: device, rs: pcPub, prologue: enc.encode(`DSH-RELAY/1|${room}`) });
71
113
  stage = "handshake";
72
- ws.send(noise.writeMessage1(enc.encode(JSON.stringify({ v: 1, name, ...(otp ? { otp } : {}) }))));
114
+ phone._setState("handshake");
115
+ ws.send(noise.writeMessage1(enc.encode(JSON.stringify({ v: 1, name, ...(otp && !opened ? { otp } : {}) }))));
116
+ if (opened) {
117
+ clearTimeout(phone._rehandshakeTimer);
118
+ phone._rehandshakeTimer = setTimeout(() => phone.close(4408, "re-handshake timeout"), timeoutMs);
119
+ phone._rehandshakeTimer.unref?.();
120
+ }
121
+ };
122
+ /** 这条 Noise 会话作废:在途请求立刻失败,之后不再往这条会话里发任何东西。 */
123
+ const suspend = () => {
124
+ stage = "down";
125
+ cipherOut = null;
126
+ cipherIn = null;
127
+ const mux = phone.mux;
128
+ phone.mux = null;
129
+ mux?.close("computer is reconnecting");
130
+ phone._setState("down");
73
131
  };
74
132
  ws.addEventListener("message", (e) => {
75
133
  try {
76
134
  if (typeof e.data === "string") {
77
135
  const msg = JSON.parse(e.data);
78
136
  if (stage === "relay" && msg.t === "hello" && msg.host === true) return startHandshake();
137
+ if (msg.t === "host-down") {
138
+ if (resume && stage !== "relay") suspend();
139
+ return;
140
+ }
79
141
  if (msg.t === "host-up") {
80
142
  if (stage === "relay") return startHandshake();
81
- // 电脑重新上线(重启 / 换连接):我们的 Noise 会话已经无处可去,上层应重新连接
82
- return phone._shutdown(4503, "host restarted");
143
+ // 电脑重新上线(重启 / 换连接):我们的 Noise 会话已经无处可去
144
+ if (!resume) return phone._shutdown(4503, "host restarted"); // 旧版:上层重新连接
145
+ suspend();
146
+ return startHandshake();
83
147
  }
84
148
  return;
85
149
  }
@@ -89,22 +153,33 @@ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", ot
89
153
  cipherOut = done.send;
90
154
  cipherIn = done.recv;
91
155
  phone.info = JSON.parse(dec.decode(done.payload));
92
- phone.mux = new MuxSession({ role: "client", send: (frame) => ws.send(cipherOut.encrypt(frame)) });
156
+ const out = cipherOut;
157
+ phone.mux = new MuxSession({ role: "client", send: (frame) => ws.send(out.encrypt(frame)) });
158
+ stage = "open";
159
+ if (opened) {
160
+ clearTimeout(phone._rehandshakeTimer);
161
+ phone.resumes++;
162
+ // 电脑要求握手后限时内收到一条能解密的数据(防重放);不能指望上层恰好马上发请求
163
+ phone.mux.ping().catch(() => {});
164
+ return phone._setState("open");
165
+ }
166
+ opened = true;
93
167
  phone.pinger = setInterval(() => { try { ws.send(JSON.stringify({ t: "ping" })); } catch { /* 连接正在断开 */ } }, 20_000);
94
168
  phone.pinger.unref?.();
95
- stage = "open";
96
169
  clearTimeout(timer);
170
+ phone._setState("open");
97
171
  return resolve(phone);
98
172
  }
99
173
  if (stage === "open") phone.mux.receive(cipherIn.decrypt(bytes));
174
+ // stage === "down":作废会话的迟到帧,丢弃
100
175
  } catch (err) {
101
- if (stage !== "open") return fail(err);
176
+ if (!opened) return fail(err);
102
177
  phone.close(4000, "protocol error");
103
178
  }
104
179
  });
105
180
  ws.addEventListener("close", (e) => {
106
181
  phone._shutdown(e.code ?? 1006, e.reason ?? "");
107
- if (stage !== "open") {
182
+ if (!opened) {
108
183
  clearTimeout(timer);
109
184
  reject(Object.assign(new Error(`relay closed during ${stage} (${e.code})`), { code: e.code }));
110
185
  }