@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.
package/lib/index.js CHANGED
@@ -25,7 +25,7 @@ import { createSessionTitleRefresher, DEFAULT_TITLE_REFRESH_BUDGET_MS, DEFAULT_T
25
25
  export { normalizeCodexUsage, normalizeDeepSeekBalance, normalizeOpenCodeUsage, usageWindowLabel } from "./account-usage.js";
26
26
  import { createMemoryRoutes } from "./memory/routes.js";
27
27
  import { openMemoryStore, wipeMemoryFiles } from "./memory/store.js";
28
- import { isProtectedFile, isProtectedPath, realPathOf } from "./protected-paths.js";
28
+ import { isProtectedFile, isProtectedPath, isStillAt, realPathOf, removeCreatedEntry } from "./protected-paths.js";
29
29
  import { extractMemories, recordMemories } from "./memory/extract.js";
30
30
  import { createMemoryContextProvider, installMemoryContext, MEMORY_CONTEXT_NAME } from "./memory/context.js";
31
31
  import { createAssistantPrefs, modeBrief } from "./assistant-prefs.js";
@@ -41,6 +41,7 @@ import { RelayConnector } from "./relay/connector.js";
41
41
  import { createRelayDemand } from "./relay/on-demand.js";
42
42
  import { createHttpReplayer } from "./relay/serve.js";
43
43
  import { buildPairingUri, isAllowedRelayUrl } from "./relay/pairing.js";
44
+ import { acceptWebSocket, rejectUpgrade } from "./relay/ws-server.js";
44
45
  import { pairingFingerprint as pairingFingerprintOf } from "./relay/fingerprint.js";
45
46
  import { b64u as relayB64u } from "./relay/crypto.js";
46
47
 
@@ -54,9 +55,9 @@ import { createProactiveScheduler } from "./proactive.js";
54
55
  import { CHATTING_MS, DEFAULT_IDLE_MS, isUserIdle, pickMaterial } from "./proactive-material.js";
55
56
  import { createReminderRoutes, createReminderStore } from "./reminders.js";
56
57
  import { createBreakReminder, isUserActivityEvent } from "./break-reminder.js";
57
- import { MAX_RESTORE_BODY_BYTES, MIN_BACKUP_PASSPHRASE, applyRestore, buildBackup, decryptBackup, encryptBackup, isEncryptedBackup, planRestore } from "./backup.js";
58
+ import { MAX_RESTORE_BODY_BYTES, applyRestore, buildBackup, decryptBackup, encryptBackup, isEncryptedBackup, passphraseProblem, planRestore } from "./backup.js";
58
59
  import { buildRotation } from "./session-rotation.js";
59
- import { inQuietHours, kindLabelOf, notifyBody, notifyHeadline, quietHoursSuppress, shouldSuppressForQuietHours } from "./notify-copy.js";
60
+ import { inQuietHours, kindLabelOf, notifyBody, notifyHeadline, parseHm, quietHoursSuppress, shouldSuppressForQuietHours } from "./notify-copy.js";
60
61
  import { compareSessionsForList, latestMessageTimeOf, planMessageTimePrune } from "./session-list.js";
61
62
  import { EVENT_TIMELINE_CAPABILITIES, blocksToText, detailEventFor, isDetailVisibleType, isLiveTimelineRecord, isTimelineRecord, isVisibleConversationMessage, sniffImageType, summarizeEvent } from "./timeline.js";
62
63
  import { EVENT_DETAIL_MAX_BYTES, SEEDED_PREFIX_ERROR_MESSAGE, TURN_OUTLINE_TIMEOUT_MS, classifyEventDetailReadError, classifyTurnOutlineReadError, createTurnOutlineQueue, raceWithDeadline, turnOutlineCapabilityOf, turnOutlineStateOf } from "./turn-outline.js";
@@ -121,6 +122,24 @@ function installAssistantContext(ctx, getPrefs, getCard) {
121
122
  return true;
122
123
  }
123
124
 
125
+ /**
126
+ * A-11: is this request path one of the desktop-only API endpoints (no phone token; DSH's own
127
+ * login on hosts with route auth)? Same rule as handleApi's `desktopOnlyRest`, plus anything that
128
+ * merely looks like one after case folding or percent-decoding, so a spelling can't slip past.
129
+ */
130
+ export function isDesktopOnlyApiPath(pathname, apiPrefix) {
131
+ const rest = String(pathname).slice(String(apiPrefix).length);
132
+ if (rest === "/qr-config" || rest.startsWith("/relay/")) return true;
133
+ let decoded = rest;
134
+ try {
135
+ decoded = decodeURIComponent(rest);
136
+ } catch {
137
+ /* keep the raw form */
138
+ }
139
+ const folded = decoded.toLowerCase().replace(/\/+/g, "/");
140
+ return folded.includes("qr-config") || folded.startsWith("/relay/") || folded === "/relay";
141
+ }
142
+
124
143
  export function apply(ctx, configInput) {
125
144
  // 零配置(v3.2.4):把 "@auto" 口令与 "auto" 开桥在这里**一次性**解析成真实值,
126
145
  // 之后整个函数(认证、qr-config、LAN 桥、诊断)看到的都是确定的 authToken / lanBridge.enabled。
@@ -206,6 +225,12 @@ export function apply(ctx, configInput) {
206
225
  // after network blips while the user is away. `newsCursor`: results up to here were reported.
207
226
  let returned = null; // { at, since }
208
227
  let newsCursor = 0;
228
+ // A-14: the main app says when it goes to the background (POST /presence {state:"background"}).
229
+ // iOS keeps a suspended app's socket open and the Android pet keeps its own stream, so an open
230
+ // stream is not "the user can see it". Apps that never send "background" keep the old rule.
231
+ let presenceState = "foreground";
232
+ /** Someone can see the app now: a stream is open and the app did not say it went to the background. */
233
+ const appInForeground = () => connections.size > 0 && presenceState !== "background";
209
234
  const proactiveIdleMs = () => config.proactive?.activeWindowMs ?? DEFAULT_IDLE_MS;
210
235
  /** Sessions whose agent is running (a reminder tied to one of them waits). */
211
236
  const runningSessions = () => {
@@ -277,11 +302,14 @@ export function apply(ctx, configInput) {
277
302
  // shows. Without: the same push channels and wording layer as every other push
278
303
  // (quiet hours, cooldown, redaction). Throw when nothing went out, so the scheduler
279
304
  // does not count it (see pushSend).
280
- if (connections.size > 0) {
305
+ // A-14: "connected" means in the foreground; a backgrounded app gets the push. When nothing
306
+ // went out, throw: the item is not marked sent and goes out on a later tick (the app coming
307
+ // back to the foreground is one).
308
+ if (appInForeground()) {
281
309
  await pushNotification(item.sessionId ?? "", "reminder", item.text, item.sessionId ? {} : { fixedTitle: item.title });
282
310
  } else {
283
311
  const ok = await pushSend("reminder", item.sessionId ?? "", item.title ?? "", item.text);
284
- if (!ok) throw new Error("no-push-channel");
312
+ if (!ok) throw new Error(connections.size > 0 ? "app-in-background-no-push-channel" : "no-push-channel");
285
313
  }
286
314
  // T-32 fix: results reported once are not news again on the next return.
287
315
  if (item.kind === "news" && Number.isFinite(item.until)) {
@@ -311,6 +339,15 @@ export function apply(ctx, configInput) {
311
339
  // Without it here, prefs always answered the hard default and a configured window was ignored.
312
340
  defaults: () => ({ mode: config.mode ?? "work", persona: config.persona ?? "colleague", quietHours: config.quietHours }),
313
341
  });
342
+ // A-37: a quiet-hours window in the config that can't be read ("22:00:00", "10pm", "24:00") used
343
+ // to mean "never quiet" without a word. Say so at start and in /diagnostics.
344
+ const quietHoursConfigProblem = (() => {
345
+ const q = config.quietHours;
346
+ if (q === undefined || q === null) return null;
347
+ if (parseHm(q.start) !== null && parseHm(q.end) !== null) return null;
348
+ return `quietHours in the config is not "HH:MM"–"HH:MM" (start ${JSON.stringify(q.start)}, end ${JSON.stringify(q.end)}): this PC has no quiet hours from the config (only the app's own setting applies) / 配置里的安静时段格式不对(要 HH:MM),这台电脑没有按配置静音`;
349
+ })();
350
+ if (quietHoursConfigProblem) ctx.logger.warn(`mobile-remote: ${quietHoursConfigProblem}`);
314
351
  // 记忆 → agent 上下文(T7 的「能召回」)。只登记一次,provider 每次装配时才读库:
315
352
  // 这样记忆在对话中途被改/删,下一轮就生效,不需要重载插件。
316
353
  // 宿主没有 systemPrompt 服务时静默降级(记忆只能存、读不到),不影响其它功能。
@@ -708,7 +745,7 @@ export function apply(ctx, configInput) {
708
745
  const heldOf = (sessionId) => heldQueue.get(sessionId) ?? [];
709
746
  const persistHeld = () => {
710
747
  try {
711
- mkdirSync(STATE_DIR, { recursive: true });
748
+ mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 });
712
749
  const tmp = HELD_FILE + ".tmp";
713
750
  writeFileSync(tmp, JSON.stringify({ held: Object.fromEntries(heldQueue) }), "utf8");
714
751
  renameSync(tmp, HELD_FILE);
@@ -754,7 +791,7 @@ export function apply(ctx, configInput) {
754
791
  const receiptKeyOf = (sessionId, targetId, requestId) => `${sessionId ?? `root:${targetId}`}:${requestId}`;
755
792
  const persistReceipts = () => {
756
793
  try {
757
- mkdirSync(STATE_DIR, { recursive: true });
794
+ mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 });
758
795
  const tmp = RECEIPT_FILE + ".tmp";
759
796
  writeFileSync(tmp, JSON.stringify({ receipts: Object.fromEntries(sendReceipts) }), "utf8");
760
797
  renameSync(tmp, RECEIPT_FILE);
@@ -937,7 +974,7 @@ export function apply(ctx, configInput) {
937
974
  };
938
975
  const persistReadIds = () => {
939
976
  try {
940
- mkdirSync(STATE_DIR, { recursive: true });
977
+ mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 });
941
978
  const tmp = READ_FILE + ".tmp";
942
979
  writeFileSync(tmp, JSON.stringify({ readNotifs: [...readIds] }), "utf8");
943
980
  renameSync(tmp, READ_FILE);
@@ -1007,7 +1044,7 @@ export function apply(ctx, configInput) {
1007
1044
  };
1008
1045
  const persistMessageTimesNow = () => {
1009
1046
  try {
1010
- mkdirSync(STATE_DIR, { recursive: true });
1047
+ mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 });
1011
1048
  const tmp = MESSAGE_TIME_FILE + ".tmp";
1012
1049
  writeFileSync(tmp, JSON.stringify(Object.fromEntries(messageTimeMap)), "utf8");
1013
1050
  renameSync(tmp, MESSAGE_TIME_FILE);
@@ -1047,7 +1084,7 @@ export function apply(ctx, configInput) {
1047
1084
  };
1048
1085
  const persistActivityNow = () => {
1049
1086
  try {
1050
- mkdirSync(STATE_DIR, { recursive: true });
1087
+ mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 });
1051
1088
  const tmp = ACTIVITY_FILE + ".tmp";
1052
1089
  writeFileSync(tmp, JSON.stringify(Object.fromEntries(activityMap)), "utf8");
1053
1090
  renameSync(tmp, ACTIVITY_FILE);
@@ -1491,6 +1528,17 @@ export function apply(ctx, configInput) {
1491
1528
  * 默认局域网私有地址优先;只有当机器上没有任何局域网私有地址时,才把
1492
1529
  * Tailscale CGNAT 提到最前,避免二维码首选到不可达地址。 */
1493
1530
  const privateFirst = (ips) => orderQrAddresses(ips);
1531
+ /**
1532
+ * 局域网加密通道(T-25)的地址:LAN 桥在监听、且这台电脑有中继身份(配对与设备名单都在那里)时,
1533
+ * 手机可以在桥端口上直接走 Noise(`ws://<局域网地址>:<桥端口>/v1/guest/<房间号>`)。
1534
+ * 只报 IPv4 局域网地址,顺序与二维码一致;最多 4 个(配对链接的上限)。
1535
+ */
1536
+ const lanNoiseUrls = () => {
1537
+ if (!lanBridgeListening || !relay) return [];
1538
+ // 桥绑在某一个地址上(不是 0.0.0.0):只有那个地址连得上
1539
+ const hosts = lanHost === "0.0.0.0" || lanHost === "::" ? privateFirst(ipv4Addresses()) : [lanHost];
1540
+ return hosts.slice(0, 4).map((ip) => `ws://${ip}:${lanPort}`);
1541
+ };
1494
1542
  /** Host 校验白名单(与 dsh /api 信任围栏同思路,阻断 DNS 重绑定)。
1495
1543
  * = 回环(含 IPv6 ::1)+ 本机全部 internal IPv4(含 Tailscale/ZeroTier/WireGuard 虚拟网段)+ 显式配置的 `trustedHosts`(内网穿透中转)。 */
1496
1544
  /** 审计 S9:`os.networkInterfaces()` 是按请求调用里最贵的一步(每个请求一次系统枚举,
@@ -1690,10 +1738,16 @@ export function apply(ctx, configInput) {
1690
1738
  // ── Break reminder (T-15, §5.7, D10) ──────────────────────────────
1691
1739
  // Counts activity from clients only: user messages from any DSH client (onSessionEvent) and
1692
1740
  // write requests from the phone (handleApi). The agent's own output does not count, so an
1693
- // unattended run never triggers it. Two off switches: `breakReminder.enabled` in the config
1694
- // (this PC) and `breakReminder` in the assistant prefs (the app's setting).
1741
+ // unattended run never triggers it. Switches: `breakReminder.enabled` in the config (this PC:
1742
+ // false = off, true = on even without the app's switch) and `breakReminder` in the assistant
1743
+ // prefs (the app's setting). A-13: with neither set, it stays off, because the store apps up
1744
+ // to 3.2.7 have no switch and the reminder's text tells the user to use it.
1695
1745
  const breakReminder = createBreakReminder({
1696
- isEnabled: () => config.breakReminder?.enabled !== false && assistantPrefs.get().breakReminder !== false,
1746
+ isEnabled: () => {
1747
+ const pc = config.breakReminder?.enabled;
1748
+ if (pc === false || assistantPrefs.get().breakReminder === false) return false;
1749
+ return pc === true || assistantPrefs.breakReminderSetByApp();
1750
+ },
1697
1751
  isQuiet: (at) =>
1698
1752
  shouldSuppressForQuietHours({
1699
1753
  kind: "break",
@@ -1702,7 +1756,7 @@ export function apply(ctx, configInput) {
1702
1756
  fallback: config.quietHours,
1703
1757
  }),
1704
1758
  remind: ({ at, workedMs }) => {
1705
- const phoneOnline = connections.size > 0;
1759
+ const phoneOnline = appInForeground(); // A-14: a backgrounded app gets the push too
1706
1760
  // Three ways out, so it is never lost:
1707
1761
  // - `break/reminder` frame: the pet stretches on it (T-29/T-40);
1708
1762
  // - a sessionless entry in the notification center (`mobile/notify`), which the app
@@ -2425,7 +2479,7 @@ export function apply(ctx, configInput) {
2425
2479
  }
2426
2480
  const method = req.method;
2427
2481
  // 只给电脑桌面 GUI 的端点(qr-config、relay 管理):豁免口令(桌面没有口令),改由 localDesktopGate 把关。
2428
- const desktopOnlyRest = rest === "/qr-config" || rest.startsWith("/relay/");
2482
+ const desktopOnlyRest = rest === "/qr-config" || rest.startsWith("/relay/"); // keep in step with isDesktopOnlyApiPath
2429
2483
  if (desktopOnlyRest && rest !== "/qr-config" && method !== "GET" && method !== "HEAD" && crossSiteBlocked(req)) {
2430
2484
  error(res, 403, "cross-site-blocked", "跨站请求被拒绝:请从 App 或桌面端发起");
2431
2485
  return;
@@ -2472,7 +2526,9 @@ export function apply(ctx, configInput) {
2472
2526
  }
2473
2527
  // T-15: an authenticated write from the phone is client activity for the break reminder.
2474
2528
  // Reads are left out: the app polls and reconnects in the background on its own.
2475
- if ((method !== "GET" && method !== "HEAD") && rest !== "/presence") noteUserActivity();
2529
+ // A-20: /assistant counts only when it changed something (the app re-syncs it on every
2530
+ // reconnect); /presence decides for itself (see there).
2531
+ if ((method !== "GET" && method !== "HEAD") && rest !== "/presence" && rest !== "/assistant") noteUserActivity();
2476
2532
  }
2477
2533
 
2478
2534
  if (rest === "/bootstrap") {
@@ -2518,6 +2574,9 @@ export function apply(ctx, configInput) {
2518
2574
  turnOutline: turnOutlineCapabilityOf(ctx),
2519
2575
  // v3.2.3:普通文件下载支持 Range/HEAD/ETag(大文件续传 + 前缀预览)。
2520
2576
  fileRange: FILE_RANGE_CAPABILITIES,
2577
+ // T-25:局域网加密通道。有这一项 = 手机可以在这些地址上走 Noise,不再在局域网上发口令。
2578
+ // (T-61 的特性列表里对应 "lan-noise"。)
2579
+ ...(lanNoiseUrls().length > 0 ? { lanNoise: { version: 1, urls: lanNoiseUrls() } } : {}),
2521
2580
  // v3.2.4(issue #55):手机端待办等待上限(仅供显示剩余时间,结算仍以服务端为准)。
2522
2581
  hold: {
2523
2582
  version: 1,
@@ -2545,7 +2604,15 @@ export function apply(ctx, configInput) {
2545
2604
  if (requirePost(method, res)) return;
2546
2605
  const body = await readJson(req, res);
2547
2606
  if (body === undefined) return;
2548
- if (body?.state !== "foreground") return error(res, 400, "bad-request", "state must be \"foreground\"");
2607
+ if (body?.state === "background") {
2608
+ // A-14: pushes go out again while the app is in the background. Not a reaction, not activity.
2609
+ presenceState = "background";
2610
+ sendJson(res, 200, { ok: true });
2611
+ return;
2612
+ }
2613
+ if (body?.state !== "foreground") return error(res, 400, "bad-request", "state must be \"foreground\" or \"background\"");
2614
+ const wasBackground = presenceState === "background";
2615
+ presenceState = "foreground";
2549
2616
  const t = Date.now();
2550
2617
  const idleMs = proactiveIdleMs();
2551
2618
  const awayMs = Number.isFinite(body.awayMs) && body.awayMs >= 0 ? body.awayMs : null;
@@ -2553,6 +2620,8 @@ export function apply(ctx, configInput) {
2553
2620
  if (wasAway) {
2554
2621
  returned = { at: t, since: Math.max(lastTypedAt, awayMs === null ? 0 : t - awayMs, newsCursor) };
2555
2622
  if (config.proactive?.enabled) setImmediate(() => void proactive.tick());
2623
+ } else if (wasBackground && config.proactive?.enabled) {
2624
+ setImmediate(() => void proactive.tick()); // anything held while it was in the background
2556
2625
  }
2557
2626
  noteUserActivity(); // opening the app is a reaction (silence decay)
2558
2627
  sendJson(res, 200, { ok: true, returned: wasAway });
@@ -2593,7 +2662,7 @@ export function apply(ctx, configInput) {
2593
2662
  return error(res, 400, "bad-request", "请求体必须是对象");
2594
2663
  }
2595
2664
  try {
2596
- const next = assistantPrefs.set({
2665
+ const { changed, ...next } = assistantPrefs.set({
2597
2666
  mode: body.mode,
2598
2667
  persona: body.persona,
2599
2668
  // 只有请求里带了 quietHours 才改它——App 切换模式时不该顺手
@@ -2604,6 +2673,7 @@ export function apply(ctx, configInput) {
2604
2673
  // T-31: the active persona card; absent = unchanged.
2605
2674
  personaCard: body.personaCard,
2606
2675
  });
2676
+ if (changed) noteUserActivity(); // A-20: an automatic re-sync is not someone working
2607
2677
  sendJson(res, 200, { ok: true, ...next });
2608
2678
  } catch (err) {
2609
2679
  // 非法值要明说,不能静默保留旧值——用户会以为切换成功了。
@@ -2630,9 +2700,8 @@ export function apply(ctx, configInput) {
2630
2700
  const body = await readJson(req, res);
2631
2701
  if (body === undefined) return;
2632
2702
  passphrase = body?.passphrase;
2633
- if (typeof passphrase !== "string" || passphrase.length < MIN_BACKUP_PASSPHRASE) {
2634
- return error(res, 400, "weak-passphrase", `口令至少 ${MIN_BACKUP_PASSPHRASE} 个字符 / the passphrase needs at least ${MIN_BACKUP_PASSPHRASE} characters`);
2635
- }
2703
+ const problem = passphraseProblem(passphrase); // A-16: 15+ characters, not an obvious one
2704
+ if (problem) return error(res, 400, "weak-passphrase", problem);
2636
2705
  } else if (method !== "GET" && method !== "HEAD") {
2637
2706
  sendError(res, 405, "method-not-allowed");
2638
2707
  return;
@@ -2656,7 +2725,7 @@ export function apply(ctx, configInput) {
2656
2725
  store,
2657
2726
  prefs: assistantPrefs,
2658
2727
  });
2659
- sendJson(res, 200, passphrase === undefined ? backup : encryptBackup(backup, passphrase));
2728
+ sendJson(res, 200, passphrase === undefined ? backup : await encryptBackup(backup, passphrase));
2660
2729
  return;
2661
2730
  }
2662
2731
  if (rest === "/backup/restore") {
@@ -2701,10 +2770,13 @@ export function apply(ctx, configInput) {
2701
2770
  }
2702
2771
  if (isEncryptedBackup(payload)) {
2703
2772
  try {
2704
- payload = decryptBackup(payload, typeof passphrase === "string" ? passphrase : undefined);
2773
+ payload = await decryptBackup(payload, typeof passphrase === "string" ? passphrase : undefined);
2705
2774
  } catch (err) {
2706
2775
  return error(res, 400, err?.code ?? "bad-backup", err?.message ?? "备份解不开");
2707
2776
  }
2777
+ } else if (typeof passphrase === "string" && passphrase !== "") {
2778
+ // A-41: a passphrase was given but the file is plain: not the file the user meant to restore.
2779
+ return error(res, 400, "not-encrypted", "这份备份没有设口令,和输入的口令对不上 / this backup is not protected by a passphrase; check that it is the right file");
2708
2780
  }
2709
2781
  const dryRun = url.searchParams.get("dryRun") === "1";
2710
2782
  // 恢复要写记忆与人格,两者都可能没开:分别取值,别让一个缺失把整次恢复否掉。
@@ -2806,7 +2878,10 @@ export function apply(ctx, configInput) {
2806
2878
  if (!gate.ok) return error(res, 403, gate.code, gate.detail);
2807
2879
  sendJson(res, 200, {
2808
2880
  ok: true,
2809
- enabled: relay !== null,
2881
+ // Remote access (the relay) is allowed. The encrypted LAN path is `lanNoise` (T-71):
2882
+ // it can be on with the relay off.
2883
+ enabled: relay?.remote === true,
2884
+ lanNoise: lanNoiseUrls().length > 0,
2810
2885
  ...(relay
2811
2886
  ? {
2812
2887
  // 待命 = 允许使用中继,但现在没有连着:没有已配对的手机,也没有有效的配对码
@@ -2825,14 +2900,23 @@ export function apply(ctx, configInput) {
2825
2900
  if (requirePost(method, res)) return;
2826
2901
  const gate = localDesktopGate(req);
2827
2902
  if (!gate.ok) return error(res, 403, gate.code, gate.detail);
2828
- if (!relay) return error(res, 409, "relay-disabled", "未启用中继:在 cordis.patch.yml 的 mobile-remote 配置里设置 relay.enabled 与 relay.urls");
2829
- // T-62 fix: a code made now would carry the key that is about to be replaced.
2830
- if (relay.rotating) return error(res, 409, "relay-rotating", "正在更换中继密钥,请稍后再试 / the relay key is being replaced; try again in a moment");
2831
2903
  const body = await readJson(req, res, 4096);
2832
2904
  if (body === undefined) return;
2833
- const { otp, expiresAt } = relay.devices.createPairing(typeof body?.deviceName === "string" ? body.deviceName : undefined);
2834
- relay.demand.sync(); // 有了配对码:现在才连中继,等手机来(码过期没人用就再断开)
2835
- const uri = buildPairingUri({ relays: relay.urls, roomId: relay.identity.roomId, pcPub: relay.identity.x.pub, otp, name: relay.name });
2905
+ // T-71 (D-01, C-15): `mode: "lan"` is the desktop's default QR, an encrypted pairing on the
2906
+ // local network: no relay URL, no relay connection, no account. Anything else is the
2907
+ // remote-access QR (relay + LAN), as before.
2908
+ const lanOnly = body?.mode === "lan";
2909
+ if (lanOnly) {
2910
+ if (!relay || lanNoiseUrls().length === 0) return error(res, 409, "lan-noise-unavailable", "局域网加密通道不可用(LAN 桥没有在监听)/ the encrypted LAN path is not available (the LAN bridge is not listening)");
2911
+ } else if (!relay?.remote) {
2912
+ return error(res, 409, "relay-disabled", "未启用中继:在 cordis.patch.yml 的 mobile-remote 配置里设置 relay.enabled 与 relay.urls");
2913
+ }
2914
+ // T-62 fix: a code made now would carry the key that is about to be replaced.
2915
+ if (relay.rotating) return error(res, 409, "relay-rotating", "正在更换中继密钥,请稍后再试 / the relay key is being replaced; try again in a moment");
2916
+ const { otp, expiresAt } = relay.devices.createPairing(typeof body?.deviceName === "string" ? body.deviceName : undefined, { relay: !lanOnly });
2917
+ relay.demand.sync(); // 有了配对码:现在才连中继,等手机来(码过期没人用就再断开)。LAN 码不算(C-04)
2918
+ // lan=(B8):手机在家时直接在局域网上走同一套加密,不必绕中继
2919
+ const uri = buildPairingUri({ relays: lanOnly ? [] : relay.urls, roomId: relay.identity.roomId, pcPub: relay.identity.x.pub, otp, name: relay.name, lan: lanNoiseUrls() });
2836
2920
  const qr = await QRCode.toDataURL(uri, { width: 512, margin: 1, errorCorrectionLevel: "M" });
2837
2921
  // 本机公钥指纹:手机配对时会显示同一串数字(算法见 App 的
2838
2922
  // lib/relay/fingerprint.dart,两边都是 sha256 前 8 字节的十六进制)。
@@ -4957,6 +5041,7 @@ export function apply(ctx, configInput) {
4957
5041
  "skill-catalog: 移动端新建会话已随预设装配注入技能目录(v3.1.0 起);若目录缺失请重启插件并查看本诊断",
4958
5042
  // v3.1.6(issue #19):能力非全绿时才出现(常态不产生噪音)
4959
5043
  ...(capabilityNote ? [capabilityNote] : []),
5044
+ ...(quietHoursConfigProblem ? [quietHoursConfigProblem] : []),
4960
5045
  ],
4961
5046
  });
4962
5047
  return;
@@ -4990,7 +5075,13 @@ export function apply(ctx, configInput) {
4990
5075
  if (name === "" || name === "." || name === ".." || /[\\/:*?"<>|]/.test(name)) return error(res, 400, "invalid-name", "文件夹名不合法");
4991
5076
  // T-62 fix: create under the same resolved parent that was checked (no "r/.." games).
4992
5077
  const shown = parent ? join(parent, name) : name;
4993
- const target = join(realPathOf(parent ?? "."), name);
5078
+ // A-05: a parent whose real path can't be worked out is refused, not guessed.
5079
+ let target;
5080
+ try {
5081
+ target = join(realPathOf(parent ?? "."), name);
5082
+ } catch {
5083
+ return protectedPathError(res);
5084
+ }
4994
5085
  if (isProtectedPath(target)) return protectedPathError(res);
4995
5086
  try {
4996
5087
  mkdirSync(target, { recursive: false });
@@ -5020,7 +5111,12 @@ export function apply(ctx, configInput) {
5020
5111
  // v3.1.1(issue #5):兜底兼容旧版 App 的 `\` 拼接(WSL 上 `/\home` 归一为 `/home`)
5021
5112
  const base = normalizeServerPath(path);
5022
5113
  // T-62 fix: check and list the same resolved folder (a link plus ".." cannot change it in between).
5023
- const listed = realPathOf(base);
5114
+ let listed;
5115
+ try {
5116
+ listed = realPathOf(base);
5117
+ } catch {
5118
+ return protectedPathError(res); // A-05: unresolvable (over-long link chain, loop): fail closed
5119
+ }
5024
5120
  if (isProtectedPath(listed)) return protectedPathError(res);
5025
5121
  try {
5026
5122
  const entries = await readdir(listed, { withFileTypes: true });
@@ -5069,9 +5165,11 @@ export function apply(ctx, configInput) {
5069
5165
  // T-62 fix: open first, then check what was opened (fstat of the descriptor), then serve
5070
5166
  // from that descriptor. A hard link or /dev/fd/N to a protected file is refused, and the
5071
5167
  // file cannot be swapped between the check and the read.
5168
+ // A-07: O_NONBLOCK, so a FIFO with no writer can't block the host's only JS thread (it is then
5169
+ // refused as not-a-file below); regular files ignore the flag.
5072
5170
  let fd;
5073
5171
  try {
5074
- fd = openSync(target, fsConstants.O_RDONLY);
5172
+ fd = openSync(target, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0));
5075
5173
  } catch (err) {
5076
5174
  return error(res, 404, "file-not-found", failureDetail(err));
5077
5175
  }
@@ -5095,6 +5193,11 @@ export function apply(ctx, configInput) {
5095
5193
  closeFd();
5096
5194
  return error(res, 400, "not-a-file", "path is not a file");
5097
5195
  }
5196
+ // A-08: the name must still lead to this same file, outside the DSH home (a swapped symlink fails this).
5197
+ if (!isStillAt(target, st)) {
5198
+ closeFd();
5199
+ return isProtectedPath(target) ? protectedPathError(res) : error(res, 409, "file-changed", "the file changed while it was being opened; try again");
5200
+ }
5098
5201
  const name = basename(target);
5099
5202
  // ETag 由「大小 + mtime」组成:文件被改写就变,够用且不用读内容。
5100
5203
  const etag = `"${st.size.toString(16)}-${Math.floor(st.mtimeMs).toString(16)}"`;
@@ -5199,25 +5302,48 @@ export function apply(ctx, configInput) {
5199
5302
  // DSH home), and check what was opened before writing (a hard link to a protected file).
5200
5303
  // Opened without O_TRUNC: nothing is overwritten until the check has passed.
5201
5304
  try {
5202
- if (lstatSync(target).isSymbolicLink()) return error(res, 400, "link-not-allowed", "目标是一个链接 / the target is a link");
5305
+ const existing = lstatSync(target);
5306
+ if (existing.isSymbolicLink()) return error(res, 400, "link-not-allowed", "目标是一个链接 / the target is a link");
5307
+ if (!existing.isFile()) return error(res, 400, "not-a-file", "path is not a file"); // A-07: FIFO, socket, device
5203
5308
  } catch {
5204
5309
  /* does not exist yet: fine */
5205
5310
  }
5311
+ // O_NONBLOCK (A-07): a FIFO swapped in with no reader fails at once (ENXIO) instead of blocking.
5312
+ // O_EXCL first (A-08, A-45): when this call created the file, a refused upload removes it again.
5313
+ const base = fsConstants.O_WRONLY | (fsConstants.O_NOFOLLOW ?? 0) | (fsConstants.O_NONBLOCK ?? 0);
5206
5314
  let fd;
5315
+ let created = false;
5207
5316
  try {
5208
- fd = openSync(target, fsConstants.O_WRONLY | fsConstants.O_CREAT | (fsConstants.O_NOFOLLOW ?? 0), 0o644);
5317
+ try {
5318
+ fd = openSync(target, base | fsConstants.O_CREAT | fsConstants.O_EXCL, 0o644);
5319
+ created = true;
5320
+ } catch (err) {
5321
+ if (err?.code !== "EEXIST") throw err;
5322
+ fd = openSync(target, base);
5323
+ }
5209
5324
  } catch (err) {
5210
5325
  if (err?.code === "ELOOP" || err?.code === "EMLINK") return error(res, 400, "link-not-allowed", "目标是一个链接 / the target is a link");
5326
+ if (err?.code === "ENXIO") return error(res, 400, "not-a-file", "path is not a file");
5211
5327
  throw err;
5212
5328
  }
5329
+ let refusal;
5330
+ let st;
5213
5331
  try {
5214
- const st = fstatSync(fd);
5215
- if (isProtectedFile(st) || (st.nlink > 1 && isProtectedPath(realPathOf(target)))) return protectedPathError(res);
5216
- if (!st.isFile()) return error(res, 400, "not-a-file", "path is not a file");
5217
- writeFdFully(fd, buf);
5332
+ st = fstatSync(fd);
5333
+ if (isProtectedFile(st)) refusal = "protected";
5334
+ else if (!st.isFile()) refusal = "not-a-file";
5335
+ // A-08: the folder may have been a symlink swapped in and out; the name must still lead here.
5336
+ else if (!isStillAt(target, st)) refusal = isProtectedPath(target) ? "protected" : "changed";
5337
+ if (!refusal) writeFdFully(fd, buf);
5218
5338
  } finally {
5219
5339
  closeSync(fd);
5220
5340
  }
5341
+ if (refusal) {
5342
+ if (created) removeCreatedEntry(target, st);
5343
+ if (refusal === "not-a-file") return error(res, 400, "not-a-file", "path is not a file");
5344
+ if (refusal === "changed") return error(res, 409, "file-changed", "the folder changed while the file was being written; try again");
5345
+ return protectedPathError(res);
5346
+ }
5221
5347
  sendJson(res, 200, { ok: true, path: target, bytes: buf.length });
5222
5348
  } catch (err) {
5223
5349
  ctx.logger.warn(`mobile-remote: /files/upload 写入失败:${err?.message ?? err}`);
@@ -6172,9 +6298,16 @@ export function apply(ctx, configInput) {
6172
6298
  try { return ctx[name]; } catch { return undefined; }
6173
6299
  };
6174
6300
  let relay = null;
6301
+ // T-71 (D-01, C-15): the encrypted LAN path uses the same identity, device list and Noise
6302
+ // sessions as the relay, but it is free and must work with the relay switched off (D5, D20).
6303
+ // So the identity exists whenever the relay is allowed **or** the LAN bridge is on; only the
6304
+ // relay links themselves depend on relay.enabled. `relay.remote` says whether remote access
6305
+ // (the relay) is available; without it the connector has no links and never dials out.
6306
+ const relayRemote = Boolean(config.relay?.enabled) && relayUrls.length > 0;
6175
6307
  if (config.relay?.enabled && relayUrls.length === 0) {
6176
6308
  ctx.logger.warn?.("mobile-remote: relay.enabled 为 true 但没有合法的 relay.urls,中继未启用");
6177
- } else if (config.relay?.enabled) {
6309
+ }
6310
+ if (relayRemote || lanEnabled) {
6178
6311
  try {
6179
6312
  const dir = join(mobileRemoteStateDir(), "relay");
6180
6313
  const identity = loadOrCreateIdentity(dir, { log: (m) => ctx.logger.warn?.(`mobile-remote: ${m}`) });
@@ -6182,7 +6315,7 @@ export function apply(ctx, configInput) {
6182
6315
  const connector = new RelayConnector({
6183
6316
  identity,
6184
6317
  devices,
6185
- urls: relayUrls,
6318
+ urls: relayRemote ? relayUrls : [],
6186
6319
  serve: createHttpReplayer({
6187
6320
  port: () => ctx.webServer.port,
6188
6321
  basePath,
@@ -6196,8 +6329,10 @@ export function apply(ctx, configInput) {
6196
6329
  timing: testHook("relayTiming"), // 仅测试注入(缩短超时);生产不设
6197
6330
  log: (m) => ctx.logger.warn?.(`mobile-remote: ${m}`),
6198
6331
  });
6199
- const demand = createRelayDemand({ connector, devices, log: (m) => ctx.logger.warn?.(`mobile-remote: ${m}`) });
6200
- relay = { identity, devices, connector, demand, urls: relayUrls, name: config.relay.name || hostname() };
6332
+ const demand = relayRemote
6333
+ ? createRelayDemand({ connector, devices, log: (m) => ctx.logger.warn?.(`mobile-remote: ${m}`) })
6334
+ : { active: false, start() { return false; }, stop() {}, sync() { return false; }, dispose() {} };
6335
+ relay = { identity, devices, connector, demand, remote: relayRemote, urls: relayRemote ? relayUrls : [], name: config.relay?.name || hostname() };
6201
6336
  } catch (err) {
6202
6337
  ctx.logger.warn?.(`mobile-remote: 中继初始化失败,已关闭:${err?.message ?? err}`);
6203
6338
  }
@@ -6209,7 +6344,7 @@ export function apply(ctx, configInput) {
6209
6344
  // end of the window, and on the next start an expired entry is not reopened.
6210
6345
  const retiredRooms = new Set();
6211
6346
  const openRetiredRoom = ({ identity, until }) => {
6212
- if (!relay || until <= Date.now()) return;
6347
+ if (!relay?.remote || until <= Date.now()) return;
6213
6348
  const room = new RelayConnector({
6214
6349
  identity,
6215
6350
  devices: { authorize: () => null, onRevoke: () => () => {}, list: () => [] },
@@ -6431,6 +6566,24 @@ export function apply(ctx, configInput) {
6431
6566
  lanServer.maxConnections = 128;
6432
6567
  lanServer.headersTimeout = 15_000;
6433
6568
  lanServer.requestTimeout = 180_000;
6569
+ // T-25:局域网加密通道。手机在桥端口上升级到 WebSocket,走与中继相同的 Noise IK + 多路复用
6570
+ // (relay.connector.acceptDirect)。身份靠握手里的设备密钥,不带、也不需要访问口令。
6571
+ // 路径是 /v1/lan,不带房间号:局域网上是明文 WebSocket,房间号是这台电脑的长期标识。
6572
+ // 别的路径一律 404,不升级。
6573
+ lanServer.on("upgrade", (req, socket, head) => {
6574
+ let pathname = "";
6575
+ try {
6576
+ pathname = new URL(req.url ?? "/", "http://lan").pathname;
6577
+ } catch {
6578
+ return rejectUpgrade(socket, 400, "Bad Request");
6579
+ }
6580
+ if (!relay || pathname !== "/v1/lan") return rejectUpgrade(socket, 404, "Not Found");
6581
+ lanBridgeSockets.add(socket);
6582
+ socket.once("close", () => lanBridgeSockets.delete(socket));
6583
+ // 一条 Noise 消息最大 65535 字节(与中继的帧上限一致)
6584
+ const ws = acceptWebSocket(req, socket, head, { maxPayload: 65_535 + 64 });
6585
+ if (ws) relay.connector.acceptDirect(ws, { ip: String(req.socket.remoteAddress ?? "") });
6586
+ });
6434
6587
  lanServer.on("error", (err) => {
6435
6588
  lanBridgeListening = false;
6436
6589
  ctx.logger.warn(`mobile-remote: lanBridge 监听错误:${err?.message ?? err}`);
@@ -6458,11 +6611,17 @@ export function apply(ctx, configInput) {
6458
6611
  // "required": 503/401 without a Peer). The phone has no DSH login; it proves itself with our
6459
6612
  // token, so the routes opt out with "anonymous", but only while our own auth is on. With our
6460
6613
  // auth off (loopback-only), DSH's login stays in front. rc.5 ignores the extra field.
6461
- const routeAuth = authEnabled ? { auth: "anonymous" } : {};
6614
+ // A-11: the desktop-only endpoints (`/qr-config` hands out the token, `/relay/*` pairs a phone)
6615
+ // answer without our token to anything that looks local, which a raw TCP tunnel or another OS
6616
+ // user can fake. On hosts with route auth they keep DSH's login in front ("required"; DSH's own
6617
+ // page has it), and localDesktopGate stays as a second layer. `/qr.png` is desktop-only too, so
6618
+ // it keeps the host's default. A function rule is master's WebAuthenticationRule.
6619
+ const apiPrefix = `${basePath}/api`;
6620
+ const routeAuth = authEnabled ? { auth: (request) => (isDesktopOnlyApiPath(request?.url?.pathname ?? "", apiPrefix) ? "required" : "anonymous") } : {};
6462
6621
  const disposers = web ? [
6463
6622
  web.register({
6464
6623
  kind: "prefix",
6465
- path: `${basePath}/api`,
6624
+ path: apiPrefix,
6466
6625
  ...routeAuth,
6467
6626
  handler: (req, res) => {
6468
6627
  let url;
@@ -6488,7 +6647,7 @@ export function apply(ctx, configInput) {
6488
6647
  web.register({
6489
6648
  kind: "exact",
6490
6649
  path: `${basePath}/qr.png`,
6491
- ...routeAuth,
6650
+ // A-11: desktop-only (the QR carries the token): no "anonymous", the host's default applies.
6492
6651
  handler: (req, res) => {
6493
6652
  let url;
6494
6653
  try {
@@ -70,6 +70,11 @@ export function installMemoryContext(ctx, provider) {
70
70
  name: MEMORY_CONTEXT_NAME,
71
71
  // 放在常规运行时上下文之后、工具指引之前:它是背景,不该压过仓库与系统信息。
72
72
  order: 60,
73
+ // A-01: memory text is the user's own words (e.g. GitHub Actions `${{ secrets.X }}`, Vue/Helm/Jinja
74
+ // templates). DSH interpolates every context unless this is false, and any `{{…}}` that is not a
75
+ // registered variable makes the host's prompt render throw before every turn: one such memory used to
76
+ // stop every conversation. The provider's try/catch can't help; the throw happens later, in the host.
77
+ interpolate: false,
73
78
  text: provider,
74
79
  });
75
80
  return true;