@dsh-mobile/mobile-remote 3.3.0 → 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.
@@ -20,7 +20,7 @@
20
20
  * 检索:没有 embedding 接口(DeepSeek 侧不提供),所以先用 BM25 关键词检索。
21
21
  * 语义检索等有了 embedding 再加一层,接口不变(`search()` 的返回形状)。
22
22
  */
23
- import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
23
+ import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
24
24
  import { createRequire } from "node:module";
25
25
  import { dirname, join } from "node:path";
26
26
 
@@ -206,16 +206,34 @@ export function queryTerms(query) {
206
206
  // 随 `wal_checkpoint(TRUNCATE)` 一起截掉,全量存档里这条的每一行都被重写剔除。
207
207
  // 之前的软删除把原文留在库、存档、导出、备份四个地方,用户点了删除却删不掉。
208
208
 
209
- /** 记忆相关的全部文件(库、WAL、共享内存索引、全量存档)。 */
209
+ /** 记忆相关的全部文件(库、WAL、共享内存索引、全量存档,和存档重写时的临时文件:A-42)。 */
210
210
  export function memoryFilesIn(dir) {
211
211
  return [
212
212
  join(dir, "memory.db"),
213
213
  join(dir, "memory.db-wal"),
214
214
  join(dir, "memory.db-shm"),
215
215
  join(dir, "memory-archive.jsonl"),
216
+ join(dir, "memory-archive.jsonl.tmp"),
216
217
  ];
217
218
  }
218
219
 
220
+ /** A-42: memories are only for this OS user: files 0600, the folder 0700 (best effort; no-op on Windows). */
221
+ function restrictModes(dir) {
222
+ if (process.platform === "win32") return;
223
+ try {
224
+ chmodSync(dir, 0o700);
225
+ } catch {
226
+ /* not ours to change */
227
+ }
228
+ for (const file of memoryFilesIn(dir)) {
229
+ try {
230
+ chmodSync(file, 0o600);
231
+ } catch {
232
+ /* not there */
233
+ }
234
+ }
235
+ }
236
+
219
237
  /**
220
238
  * 「删除全部记忆」在记忆功能关闭(库没打开)时的落点:直接删掉全部文件。
221
239
  * 记忆开着时请用 `store.removeAll()`,它在打开的连接上做同样的事。
@@ -264,7 +282,7 @@ function purgeArchive(archiveFile, ids) {
264
282
  * @param {string} [opts.dir] 状态目录(默认 `DSH_HOME/mobile-remote`,由调用方传入)
265
283
  * @param {() => number} [opts.now] 时间源(测试注入)
266
284
  */
267
- export function openMemoryStore({ dir, now = () => Date.now() } = {}) {
285
+ export function openMemoryStore({ dir, now = () => Date.now(), walRetryMs = 1000, walRetries = 60 } = {}) {
268
286
  if (!dir) throw new Error("openMemoryStore: dir is required");
269
287
  const DatabaseSync = loadDatabaseSync(); // 先确认有 sqlite,再动磁盘
270
288
  const file = join(dir, "memory.db");
@@ -277,6 +295,7 @@ export function openMemoryStore({ dir, now = () => Date.now() } = {}) {
277
295
  // T-63:删除与覆盖时把释放的内容清零,否则「删掉的原文」还躺在空闲页里。
278
296
  db.exec("PRAGMA secure_delete = ON;");
279
297
  db.exec(SCHEMA);
298
+ restrictModes(dir); // memory.db, -wal and -shm exist now (SQLite creates them with the umask's 0644)
280
299
  // 旧库升级:逐列探测后补,避免每次启动都对已存在的列执行 ALTER 报错。
281
300
  const existing = new Set(
282
301
  db.prepare(`PRAGMA table_info(memory)`).all().map((r) => r.name),
@@ -295,14 +314,37 @@ export function openMemoryStore({ dir, now = () => Date.now() } = {}) {
295
314
  * 会让"删掉这条记忆"与"永久存档"两件事互相矛盾。
296
315
  */
297
316
  const archiveFile = join(dir, "memory-archive.jsonl");
298
- /** 把 WAL 里的旧页写回并截断:被删行的旧副本不能留在 memory.db-wal 里。 */
299
- const truncateWal = () => {
317
+ /**
318
+ * 把 WAL 里的旧页写回并截断:被删行的旧副本不能留在 memory.db-wal 里。
319
+ * A-42: while another connection holds a read transaction (a second plugin instance on the same
320
+ * DSH_HOME, a DB browser left open) SQLite answers `busy` instead of truncating, and `db.exec` used
321
+ * to drop that answer. Now a busy checkpoint is retried in the background until it succeeds.
322
+ */
323
+ let walTimer = null;
324
+ let walAttempts = 0;
325
+ let closed = false;
326
+ const checkpointOnce = () => {
300
327
  try {
301
- db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
328
+ const row = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
329
+ return Number(row?.busy ?? 0) === 0;
302
330
  } catch {
303
- // 有读者占着时会失败:下次删除或关闭时再截。
331
+ return false;
304
332
  }
305
333
  };
334
+ const truncateWal = () => {
335
+ if (closed) return;
336
+ if (checkpointOnce()) return;
337
+ walAttempts = 0;
338
+ if (walTimer) return;
339
+ const retry = () => {
340
+ walTimer = null;
341
+ if (closed || checkpointOnce() || ++walAttempts >= walRetries) return;
342
+ walTimer = setTimeout(retry, walRetryMs);
343
+ walTimer.unref?.();
344
+ };
345
+ walTimer = setTimeout(retry, walRetryMs);
346
+ walTimer.unref?.();
347
+ };
306
348
  /** 真删一批行,并清掉它们在存档里的痕迹。 */
307
349
  const hardDelete = (ids) => {
308
350
  if (ids.length === 0) return 0;
@@ -488,6 +530,8 @@ export function openMemoryStore({ dir, now = () => Date.now() } = {}) {
488
530
  } catch {
489
531
  // 存档不存在或写不了:下面照常截 WAL。
490
532
  }
533
+ // A-42: a rewrite interrupted between write and rename leaves this copy of the archive behind.
534
+ rmSync(`${archiveFile}.tmp`, { force: true });
491
535
  truncateWal();
492
536
  return n;
493
537
  }
@@ -616,7 +660,10 @@ export function openMemoryStore({ dir, now = () => Date.now() } = {}) {
616
660
  }
617
661
 
618
662
  function close() {
619
- truncateWal();
663
+ checkpointOnce();
664
+ closed = true;
665
+ if (walTimer) clearTimeout(walTimer);
666
+ walTimer = null;
620
667
  try {
621
668
  db.close();
622
669
  } catch {
@@ -24,7 +24,11 @@ import { readBody, sendError, sendJson } from "./http-util.js";
24
24
  export const PERSONA_SCHEMA = "dsh-mobile.persona/1";
25
25
  export const DEFAULT_PERSONA_ID = "workaholic";
26
26
  export const MAX_IMPORTED_CARDS = 20;
27
- /** The card text that goes into the system prompt, in UTF-8 bytes (T-31 fix: ~2k tokens). */
27
+ /**
28
+ * The card text that goes to the model, in UTF-8 bytes (T-31 fix: ~2k tokens). A-34: it is not the
29
+ * system prompt: DSH renders prompt contexts into a user-role `<system-reminder>` message, and a DSH
30
+ * config with `includeRuntimeContext: false` drops non-required contexts, this card among them.
31
+ */
28
32
  export const MAX_PERSONA_PROMPT_BYTES = 8 * 1024;
29
33
  /** The only fields that reach the model. Unknown fields stay in the card, not in the prompt. */
30
34
  export const PERSONA_PROMPT_FIELDS = Object.freeze(["name", "summary", "identity", "speaking_style", "rhythm", "light_memory", "emotes", "forbidden_topics"]);
package/lib/proactive.js CHANGED
@@ -283,7 +283,10 @@ export function createProactiveScheduler({
283
283
  // returns is ignored.
284
284
  let dueOnly = false;
285
285
  if (!gate.ok) {
286
- const lighter = !["paused", "disabled", "quiet-hours"].includes(gate.reason) && !isChatting();
286
+ // A-35: decided from quiet hours, pause and "off" directly, not from the full gate's first
287
+ // reason: after 7 silent days that reason is "silence-stopped" (checked before quiet hours),
288
+ // and a due reminder went out at 03:00.
289
+ const lighter = !["paused", "disabled", "quiet-hours"].includes(gate.reason) && !state.paused && !isQuiet() && !isChatting();
287
290
  if (!lighter) {
288
291
  lastReason = gate.reason;
289
292
  // 闸门没过也要把"下一次该检查的时间"落盘:诊断页据此显示"它什么时候会再想说话"。
@@ -15,25 +15,40 @@
15
15
  * - `isProtectedFile(stat)`: after opening, the opened file's `(dev, ino)` compared with every
16
16
  * file inside the protected folders. That catches hard links and `/dev/fd/N`, and checks what
17
17
  * was actually opened, so there is no check-then-open race.
18
- * - `/dev` and `/proc` are refused outright (they name open files and processes).
18
+ * - `/dev` and `/proc` are refused outright (they name open files and processes), in any case
19
+ * spelling and through links (A-03: `/DEV/fd/N` is `/dev/fd/N` on a case-insensitive disk).
20
+ * - A path whose real path can't be worked out (a symlink chain longer than PATH_MAX, a loop) is
21
+ * treated as protected: fail closed (A-05).
22
+ * - A file with more than one name (`nlink > 1`) is compared with every file in the DSH home, not
23
+ * just the keys (A-04), and `isStillAt(target, st)` checks after opening that the name still
24
+ * leads to the opened file outside the protected folders, which closes the check-then-open race
25
+ * through a swapped symlink (A-08).
19
26
  */
20
- import { lstatSync, readdirSync, realpathSync, statSync } from "node:fs";
27
+ import { lstatSync, readdirSync, realpathSync, statSync, unlinkSync } from "node:fs";
21
28
  import { homedir } from "node:os";
22
- import { dirname, join, resolve, sep } from "node:path";
29
+ import { basename, dirname, join, resolve, sep } from "node:path";
23
30
  import { mobileRemoteStateDir } from "./auto-config.js";
24
31
 
25
32
  const caseInsensitive = process.platform === "darwin" || process.platform === "win32";
26
33
  const norm = (p) => (caseInsensitive ? p.normalize("NFC").toLowerCase() : p.normalize("NFC"));
27
34
  const idOf = (st) => `${st.dev}:${st.ino}`;
28
35
 
29
- /** Resolve symlinks; for a missing path, resolve the nearest existing parent and re-append. */
36
+ /**
37
+ * Resolve symlinks; for a missing path, resolve the nearest existing parent and re-append.
38
+ * Only "does not exist" (ENOENT, ENOTDIR) moves on to the parent. Any other error (ENAMETOOLONG
39
+ * from an over-long symlink chain, ELOOP, EACCES) throws a `path-unresolvable` error: guessing the
40
+ * real path from the spelling is exactly how the A-05 chain reached the DSH home.
41
+ */
30
42
  export function realPathOf(path) {
31
43
  let current = resolve(path);
32
44
  const rest = [];
33
45
  for (;;) {
34
46
  try {
35
47
  return join(realpathSync(current), ...rest.reverse());
36
- } catch {
48
+ } catch (err) {
49
+ if (err?.code !== "ENOENT" && err?.code !== "ENOTDIR") {
50
+ throw Object.assign(new Error("path-unresolvable"), { code: "path-unresolvable", cause: err?.code });
51
+ }
37
52
  const parent = dirname(current);
38
53
  if (parent === current) return resolve(path);
39
54
  rest.push(current.slice(parent.length).replace(/^[\\/]+/, ""));
@@ -61,17 +76,55 @@ function rootIds(roots) {
61
76
  return ids;
62
77
  }
63
78
 
64
- /** True for `/dev` and `/proc` and anything under them (open files, other processes). */
79
+ const DEVICE_ROOTS = ["/dev", "/proc"];
80
+ const underDevice = (p) => {
81
+ const f = norm(p);
82
+ return DEVICE_ROOTS.some((d) => f === d || f.startsWith(`${d}/`));
83
+ };
84
+ /**
85
+ * True for `/dev` and `/proc` and anything under them (open files, other processes), however it is
86
+ * spelled: case-folded where the disk is case-insensitive (A-03), after resolving links, and by the
87
+ * identity of the folders on the way. Unresolvable paths count as device paths (fail closed).
88
+ */
65
89
  export function isDeviceOrProcPath(path) {
66
90
  if (process.platform === "win32") return false;
67
- const p = resolve(path);
68
- return ["/dev", "/proc"].some((d) => p === d || p.startsWith(`${d}/`));
91
+ if (underDevice(resolve(path))) return true;
92
+ let real;
93
+ try {
94
+ real = realPathOf(path);
95
+ } catch {
96
+ return true;
97
+ }
98
+ if (underDevice(real)) return true;
99
+ const ids = new Set();
100
+ for (const d of DEVICE_ROOTS) {
101
+ try {
102
+ ids.add(idOf(statSync(d)));
103
+ } catch {
104
+ /* no /proc on macOS */
105
+ }
106
+ }
107
+ for (let current = real; ; ) {
108
+ try {
109
+ if (ids.has(idOf(statSync(current)))) return true;
110
+ } catch {
111
+ /* not there (yet) */
112
+ }
113
+ const parent = dirname(current);
114
+ if (parent === current) return false;
115
+ current = parent;
116
+ }
69
117
  }
70
118
 
71
119
  /** True when `target` is a protected folder or anywhere inside one, whatever it is called. */
72
120
  export function isProtectedPath(target, roots = protectedRoots()) {
73
121
  if (isDeviceOrProcPath(target)) return true;
74
- const real = realPathOf(target);
122
+ let real;
123
+ try {
124
+ real = realPathOf(target);
125
+ } catch {
126
+ return true; // A-05: can't tell where it leads, so it is not served
127
+ }
75
128
  // Fast path: the usual spelling.
76
129
  const r = norm(real);
77
130
  if (roots.some((root) => r === norm(root) || r.startsWith(norm(root).endsWith(sep) ? norm(root) : `${norm(root)}${sep}`))) return true;
@@ -124,7 +177,114 @@ export function protectedFileIds(roots = protectedRoots()) {
124
177
  return ids;
125
178
  }
126
179
 
127
- /** True when an opened file (its fstat) is one of the protected files. */
128
- export function isProtectedFile(st, ids = protectedFileIds()) {
129
- return Boolean(st) && ids.has(idOf(st));
180
+ /** Folders never walked by the full walk: package installs (pnpm hard-links them by the thousand), no keys. */
181
+ const SKIP_DIRS = new Set(["node_modules", ".pnpm-store", ".git"]);
182
+ /** Upper bound of the full walk; past it, a hard-linked file is refused rather than guessed about. */
183
+ export const FULL_WALK_LIMIT = 100_000;
184
+
185
+ /**
186
+ * `(dev, ino)` of every file and folder in the DSH home and the state folder (A-04: a hard link to
187
+ * `profiles/<name>/cordis.patch.yml`, a session log or a deep state file reached nothing before).
188
+ * Bounded: returns `null` when the walk hits `limit`, and the caller then fails closed.
189
+ */
190
+ export function allProtectedIds(roots = protectedRoots(), limit = FULL_WALK_LIMIT) {
191
+ const ids = rootIds(roots);
192
+ let seen = 0;
193
+ const stack = roots.filter(Boolean).map((r) => [r, 0]);
194
+ while (stack.length) {
195
+ const [dir, depth] = stack.pop();
196
+ let entries;
197
+ try {
198
+ entries = readdirSync(dir, { withFileTypes: true });
199
+ } catch {
200
+ continue;
201
+ }
202
+ for (const entry of entries) {
203
+ if (++seen > limit) return null;
204
+ const path = join(dir, entry.name);
205
+ try {
206
+ const st = lstatSync(path);
207
+ ids.add(idOf(st));
208
+ if (st.isDirectory() && depth < 32 && !SKIP_DIRS.has(entry.name)) stack.push([path, depth + 1]);
209
+ } catch {
210
+ /* vanished */
211
+ }
212
+ }
213
+ }
214
+ return ids;
215
+ }
216
+
217
+ /**
218
+ * True when an opened file (its fstat) is one of the protected files. A file with more than one
219
+ * name may have its other name anywhere in the DSH home, so it is compared with the full walk.
220
+ */
221
+ export function isProtectedFile(st, ids) {
222
+ if (!st) return false;
223
+ const id = idOf(st);
224
+ if ((ids ?? protectedFileIds()).has(id)) return true;
225
+ if (ids === undefined && st.nlink > 1 && !st.isDirectory()) {
226
+ const all = allProtectedIds();
227
+ return all === null || all.has(id);
228
+ }
229
+ return false;
230
+ }
231
+
232
+ /**
233
+ * After opening `target`: does that name still lead, through its real path, to the very file that
234
+ * was opened (`st` = fstat of the descriptor), outside the protected folders? A symlink swapped
235
+ * between the path check and the open (A-08) makes the answer no, whichever way it points by now.
236
+ */
237
+ export function isStillAt(target, st, roots = protectedRoots()) {
238
+ try {
239
+ const real = realPathOf(target);
240
+ if (isProtectedPath(real, roots)) return false;
241
+ return idOf(statSync(real)) === idOf(st);
242
+ } catch {
243
+ return false;
244
+ }
245
+ }
246
+
247
+ /**
248
+ * A refused upload that created its file (O_EXCL) removes it again (A-08, A-45): the entry named
249
+ * like `target` whose identity is `st`, wherever a swapped folder put it (the target's folder now,
250
+ * or any folder in the DSH home). Only that exact inode is removed; nothing else is touched.
251
+ */
252
+ export function removeCreatedEntry(target, st, roots = protectedRoots()) {
253
+ if (!st) return false;
254
+ const name = basename(target);
255
+ const id = idOf(st);
256
+ const dirs = [dirname(resolve(target))];
257
+ try {
258
+ dirs.push(dirname(realPathOf(target)));
259
+ } catch {
260
+ /* unresolvable: the walk below still looks in the DSH home */
261
+ }
262
+ const stack = roots.filter(Boolean).map((r) => [r, 0]);
263
+ let seen = 0;
264
+ while (stack.length && seen < FULL_WALK_LIMIT) {
265
+ const [dir, depth] = stack.pop();
266
+ dirs.push(dir);
267
+ let entries;
268
+ try {
269
+ entries = readdirSync(dir, { withFileTypes: true });
270
+ } catch {
271
+ continue;
272
+ }
273
+ for (const entry of entries) {
274
+ seen++;
275
+ if (entry.isDirectory() && depth < 32 && !SKIP_DIRS.has(entry.name)) stack.push([join(dir, entry.name), depth + 1]);
276
+ }
277
+ }
278
+ for (const dir of dirs) {
279
+ const candidate = join(dir, name);
280
+ try {
281
+ if (idOf(lstatSync(candidate)) === id) {
282
+ unlinkSync(candidate);
283
+ return true;
284
+ }
285
+ } catch {
286
+ /* not here */
287
+ }
288
+ }
289
+ return false;
130
290
  }
package/lib/protocol.js CHANGED
@@ -22,6 +22,10 @@ export const PROTOCOL = Object.freeze({ min: 1, max: 1 });
22
22
  export const FEATURES = Object.freeze([
23
23
  // Persona cards: GET/POST/DELETE /api/persona (T-31).
24
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",
25
29
  ]);
26
30
 
27
31
  /** Apps older than this can't work with this plugin (none so far). */
@@ -17,7 +17,14 @@
17
17
  * 不能让重放者把真正在用的会话顶掉。
18
18
  * · 中继没动静的检测:每次心跳之后 pongMs 内收不到任何消息就认定连接已死、立刻重连
19
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
+ * 访问口令从头到尾不出现在局域网上。
20
26
  */
27
+ import { randomBytes } from "node:crypto";
21
28
  import { b64u, concat, ed25519Sign, hex } from "./crypto.js";
22
29
  import { MuxError, MuxSession } from "./mux.js";
23
30
  import { NoiseResponder } from "./noise.js";
@@ -44,10 +51,12 @@ export class RelayConnector {
44
51
  this.log = log;
45
52
  this.timing = { ...RelayConnector.TIMING, ...timing };
46
53
  this.links = urls.map((url) => new RelayLink(this, url.replace(/\/+$/, "")));
54
+ /** 局域网直连的会话(每条一个 DirectLink)。与中继无关:中继停着也照常接。 */
55
+ this.direct = new Set();
47
56
  this.stopped = true;
48
57
  this.unsubscribe = devices.onRevoke((id) => this.dropDevice(id));
49
58
  }
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 });
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 });
51
60
 
52
61
  start() {
53
62
  if (!this.stopped) return;
@@ -62,6 +71,28 @@ export class RelayConnector {
62
71
  this.unsubscribe = null;
63
72
  for (const l of this.links) l.shutdown();
64
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
+ }
65
96
  status() {
66
97
  return this.links.map((l) => ({ url: l.url, state: l.state, since: l.since, lastError: l.lastError, phones: l.sessions.size }));
67
98
  }
@@ -80,9 +111,9 @@ export class RelayConnector {
80
111
  }
81
112
  return true;
82
113
  }
83
- /** 设备被撤销:立刻踢掉它所有在线的会话。 */
114
+ /** 设备被撤销:立刻踢掉它所有在线的会话(中继上的与局域网直连的)。 */
84
115
  dropDevice(deviceId) {
85
- for (const l of this.links) for (const s of [...l.sessions.values()]) if (s.device?.id === deviceId) s.kick("device revoked");
116
+ for (const l of this.allLinks()) for (const s of [...l.sessions.values()]) if (s.device?.id === deviceId) s.kick("device revoked");
86
117
  }
87
118
  }
88
119
 
@@ -358,7 +389,7 @@ class GuestSession {
358
389
  #replaceOlder() {
359
390
  const id = this.device?.id;
360
391
  if (!id) return;
361
- for (const link of this.link.o.links) {
392
+ for (const link of this.link.o.allLinks()) {
362
393
  for (const other of [...link.sessions.values()]) {
363
394
  if (other !== this && other.device?.id === id) other.kick("replaced by a newer connection from the same device", "replaced");
364
395
  }
@@ -383,3 +414,81 @@ class GuestSession {
383
414
  this.link.sessions.delete(this.connId);
384
415
  }
385
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
+ }
@@ -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;
@@ -95,28 +105,38 @@ export class DeviceStore {
95
105
  return () => this.revokeListeners.delete(fn);
96
106
  }
97
107
 
98
- /** 生成一次性配对码。返回明文码(只此一次)与过期时间。 */
99
- createPairing(name) {
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 } = {}) {
100
113
  this.#sweep();
101
114
  while (this.otps.size >= MAX_PENDING_OTPS) this.otps.delete(this.otps.keys().next().value); // 最旧的让位
102
115
  const otp = b64u.enc(randomBytesU8(16));
103
116
  const expiresAt = this.now() + this.otpTtlMs;
104
- 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 });
105
118
  return { otp, expiresAt };
106
119
  }
107
120
  #sweep() {
108
121
  const t = this.now();
109
122
  for (const [k, v] of this.otps) if (v.expiresAt <= t) this.otps.delete(k);
110
123
  }
111
- pendingPairings() {
124
+ /** Codes still valid. `{ relay: true }` counts only remote-access codes (T-71, C-04). */
125
+ pendingPairings({ relay } = {}) {
112
126
  this.#sweep();
113
- return this.otps.size;
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;
114
131
  }
115
132
  /** 最后一个还有效的配对码什么时候过期(毫秒时间戳);没有则 0。按需连接用它决定何时可以断开中继。 */
116
- pairingExpiry() {
133
+ pairingExpiry({ relay } = {}) {
117
134
  this.#sweep();
118
135
  let latest = 0;
119
- for (const v of this.otps.values()) if (v.expiresAt > latest) latest = v.expiresAt;
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
+ }
120
140
  return latest;
121
141
  }
122
142
 
@@ -127,6 +147,17 @@ export class DeviceStore {
127
147
  authorize(pub, info = {}) {
128
148
  const known = this.find(pub);
129
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
+ }
130
161
  this.touch(known);
131
162
  return { device: known, newlyPaired: false };
132
163
  }
@@ -144,6 +175,7 @@ export class DeviceStore {
144
175
  pub: pub.slice(),
145
176
  createdAt: this.now(),
146
177
  lastSeen: this.now(),
178
+ relay: entry.relay !== false,
147
179
  };
148
180
  this.devices.push(device);
149
181
  this.#persist();