@dsh-mobile/mobile-remote 3.3.1 → 3.4.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 (58) hide show
  1. package/README.md +9 -5
  2. package/docs/PRIVACY-POLICY.en.md +10 -3
  3. package/docs/PRIVACY-POLICY.md +10 -3
  4. package/docs/USER-GUIDE.zh-CN.md +1 -0
  5. package/lib/account-usage-query.js +60 -60
  6. package/lib/account-usage.js +10 -10
  7. package/lib/api-helpers.js +109 -109
  8. package/lib/assistant-prefs.js +82 -59
  9. package/lib/auto-config.js +65 -65
  10. package/lib/backup.js +117 -117
  11. package/lib/break-reminder.js +45 -45
  12. package/lib/client.js +93 -93
  13. package/lib/config.js +232 -218
  14. package/lib/git-read-bundled-provider.js +12 -12
  15. package/lib/git-read-service.js +5 -5
  16. package/lib/host-compat.js +84 -84
  17. package/lib/http-util.js +17 -17
  18. package/lib/index.js +1534 -1534
  19. package/lib/memory/context.js +44 -44
  20. package/lib/memory/decay.js +93 -93
  21. package/lib/memory/extract.js +77 -77
  22. package/lib/memory/routes.js +33 -33
  23. package/lib/memory/store.js +196 -196
  24. package/lib/notify-copy.js +93 -93
  25. package/lib/permission-guide.js +86 -86
  26. package/lib/persona-cards.js +73 -65
  27. package/lib/phone-action-args.js +175 -0
  28. package/lib/phone-actions.js +227 -0
  29. package/lib/phone-announce.js +58 -0
  30. package/lib/proactive-material.js +42 -42
  31. package/lib/proactive.js +121 -121
  32. package/lib/protected-paths.js +79 -79
  33. package/lib/protocol.js +61 -26
  34. package/lib/push.js +29 -29
  35. package/lib/rate-limit.js +16 -16
  36. package/lib/relay/connector.js +246 -102
  37. package/lib/relay/crypto.js +15 -15
  38. package/lib/relay/devices.js +36 -36
  39. package/lib/relay/fingerprint.js +34 -34
  40. package/lib/relay/identity.js +26 -26
  41. package/lib/relay/mux.js +60 -46
  42. package/lib/relay/noise.js +40 -40
  43. package/lib/relay/on-demand.js +33 -33
  44. package/lib/relay/p2p.js +239 -0
  45. package/lib/relay/pairing.js +24 -24
  46. package/lib/relay/phone.js +62 -40
  47. package/lib/relay/serve.js +21 -21
  48. package/lib/relay/signal.js +69 -0
  49. package/lib/relay/ws-server.js +32 -32
  50. package/lib/reminders.js +15 -15
  51. package/lib/rpc-adapter.js +43 -43
  52. package/lib/session-list.js +31 -31
  53. package/lib/session-rotation.js +95 -95
  54. package/lib/session-title-cache.js +35 -35
  55. package/lib/session-title-refresh.js +51 -51
  56. package/lib/timeline.js +140 -140
  57. package/lib/turn-outline.js +104 -104
  58. package/package.json +6 -13
@@ -1,43 +1,43 @@
1
- /**
2
- * 零配置接入(装上插件就能用)。
3
- *
4
- * 以前要让手机连上,用户得:手写 `cordis.patch.yml` 启用插件 → 自己生成口令 → 桌面版还要手写 lanBridge →
5
- * 自己去查 IP。这里把「必须由人决定」之外的部分全部自动化,且都是**纯函数 + 显式输入**,便于单测:
6
- *
7
- * - `authToken: "@auto"` 首次启动随机生成强口令并持久化,之后复用(手机只需配对一次)。
8
- * - `lanBridge.enabled: "auto"` 仅在需要时开桥(桌面版 webserver 只听回环)。
9
- * - `formatConnectionBanner` 启动时把手机 App 需要填的两项(地址 + 口令)打印出来。
10
- *
11
- * 向后兼容:`authToken` 为空仅在服务只有本机可达时表示「关闭认证」,否则按 `@auto` 处理(T-03,见
12
- * `effectiveAuthSetting`);`lanBridge.enabled` 仍可写 true/false;
13
- * 这些「自动」值只会出现在插件自带的 `cordis.patch.yml` 里,已有手写配置的用户行为不变。
14
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
15
  import { randomBytes } from "node:crypto";
16
16
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
17
17
  import { homedir } from "node:os";
18
18
  import { join } from "node:path";
19
19
 
20
- /** 配置里写这个值 = 「请自动生成并持久化口令」。刻意带 `@`:不会和人手写的口令撞车。 */
20
+
21
21
  export const AUTO = "@auto";
22
22
 
23
- /** 自动口令的合法形态:24 字节 base64url = 32 字符;读回时按此校验,损坏的文件视为不存在。 */
23
+
24
24
  const SAVED_TOKEN_RE = /^[A-Za-z0-9_-]{24,128}$/;
25
25
 
26
26
  const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1"]);
27
27
 
28
- /** 插件的状态目录。与宿主同一个 `DSH_HOME` 约定(隔离测试/多实例时口令不串)。 */
28
+
29
29
  export function mobileRemoteStateDir(env = process.env, home = homedir()) {
30
30
  const base = typeof env.DSH_HOME === "string" && env.DSH_HOME.trim() !== "" ? env.DSH_HOME : join(home, ".dsh");
31
31
  return join(base, "mobile-remote");
32
32
  }
33
33
 
34
- /**
35
- * 解析 `authToken`。
36
- * - 不是 `@auto`:原样返回(空串 = 关闭认证;调用方只在服务仅本机可达时才会传空串,见 effectiveAuthSetting)。
37
- * - `@auto`:读 `<stateDir>/auth-token`;没有或损坏就生成新的并原子写入(0600)。
38
- * 写盘失败不阻断启动:本次进程内用内存口令,但会返回 `persistError`,调用方应提示
39
- * 「重启后口令会变,手机需要重新配对」。
40
- */
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
41
  export function resolveAuthToken(configured, { dir = mobileRemoteStateDir(), generate = () => randomBytes(24).toString("base64url") } = {}) {
42
42
  if (configured !== AUTO) return { token: configured ?? "", auto: false };
43
43
  const file = join(dir, "auth-token");
@@ -47,7 +47,7 @@ export function resolveAuthToken(configured, { dir = mobileRemoteStateDir(), gen
47
47
  if (SAVED_TOKEN_RE.test(saved)) return { token: saved, auto: true, generated: false, file };
48
48
  }
49
49
  } catch {
50
- // 读失败 → 当作没有,走下面的重新生成
50
+
51
51
  }
52
52
  const token = generate();
53
53
  try {
@@ -61,39 +61,39 @@ export function resolveAuthToken(configured, { dir = mobileRemoteStateDir(), gen
61
61
  }
62
62
  }
63
63
 
64
- /**
65
- * T-03 (finding E6): whether nothing but this computer can reach the mobile API.
66
- *
67
- * True only when the DSH webserver listens on a loopback address and none of the ways out
68
- * is on: no LAN bridge, no `trustedHosts` (a tunnel or reverse proxy), no relay (it replays
69
- * phone requests into this server). An unknown webserver host counts as reachable, so the
70
- * answer fails closed.
71
- */
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
72
  export function isLoopbackOnly({ webHost, lanBridgeEnabled = false, trustedHosts = [], relayEnabled = false } = {}) {
73
73
  if (typeof webHost !== "string" || !LOOPBACK_HOSTS.has(webHost.trim().toLowerCase())) return false;
74
74
  if (lanBridgeEnabled || relayEnabled) return false;
75
75
  return !(Array.isArray(trustedHosts) && trustedHosts.length > 0);
76
76
  }
77
77
 
78
- /**
79
- * T-03 (finding E6): the `authToken` setting to resolve.
80
- *
81
- * An empty token used to switch authentication off wherever the server was reachable, so a
82
- * user config that replaced the shipped `"@auto"` and left the token out opened an agent with
83
- * shell access to the whole LAN. Now an empty (or missing) token means "off" only when the
84
- * server is loopback-only (`isLoopbackOnly`); everywhere else it is treated as `"@auto"`.
85
- * A non-empty value is returned unchanged.
86
- */
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
87
  export function effectiveAuthSetting(configured, reach = {}) {
88
88
  if (typeof configured === "string" && configured !== "") return configured;
89
89
  return isLoopbackOnly(reach) ? "" : AUTO;
90
90
  }
91
91
 
92
- /**
93
- * Replace an auto-managed token with a fresh one (T-62: after a device is revoked). Written
94
- * atomically over `<dir>/auth-token` (0600). Only for `@auto` tokens: a token the owner wrote
95
- * into their config is theirs to change. Throws when the file cannot be written.
96
- */
92
+
93
+
94
+
95
+
96
+
97
97
  export function rotateAuthToken({ dir = mobileRemoteStateDir(), generate = () => randomBytes(24).toString("base64url") } = {}) {
98
98
  const file = join(dir, "auth-token");
99
99
  const token = generate();
@@ -104,35 +104,35 @@ export function rotateAuthToken({ dir = mobileRemoteStateDir(), generate = () =>
104
104
  return { token, file };
105
105
  }
106
106
 
107
- /**
108
- * 解析 `lanBridge.enabled`:true/false 原样;`"auto"` = 需要才开。
109
- * 「需要」= webserver 只听回环(桌面版强制如此,手机直连不了)。web 版 webserver 已经听 0.0.0.0,
110
- * 再开桥反而会和它抢同一个端口。宿主地址拿不到时按桌面版处理,但桥端口与 webserver 端口相同则不开。
111
- */
107
+
108
+
109
+
110
+
111
+
112
112
  export function resolveLanBridgeEnabled(setting, { webHost, webPort, bridgePort } = {}) {
113
113
  if (setting !== "auto") return Boolean(setting);
114
114
  if (typeof webHost === "string" && webHost !== "") return LOOPBACK_HOSTS.has(webHost.toLowerCase());
115
115
  return !(webPort !== undefined && bridgePort === webPort);
116
116
  }
117
117
 
118
- /**
119
- * 自动开桥时选桥端口。桥默认端口 3080 与 `dsh web` 自己的 webserver 端口(回环 3080)相同:
120
- * macOS/BSD 允许「回环 3080」与「通配 3080」并存,Linux 却会 EADDRINUSE(Windows 行为也不可依赖)。
121
- * 所以 `auto` 模式下撞端口就让到下一个;用户**显式**写 true/false 时一律尊重其端口,不替人改。
122
- */
118
+
119
+
120
+
121
+
122
+
123
123
  export function resolveLanBridgePort(setting, port, webPort) {
124
124
  if (setting === "auto" && webPort !== undefined && port === webPort) return port < 65535 ? port + 1 : port - 1;
125
125
  return port;
126
126
  }
127
127
 
128
- /**
129
- * 启动时打印给人看的「手机 App 要填的两项」。
130
- * 口令只在**自动生成**时打印——那是用户唯一能第一时间拿到它的地方;用户自己写进配置的口令不进日志。
131
- */
132
- /**
133
- * T-62 (E11): an auto token is printed only on the start that generated it (`tokenNew`). Later
134
- * starts say where it is saved instead: stderr often ends up in log files.
135
- */
128
+
129
+
130
+
131
+
132
+
133
+
134
+
135
+
136
136
  export function formatConnectionBanner({ addresses, token, tokenIsAuto, tokenNew = true, tokenFile, persistError, authEnabled = true }) {
137
137
  const [first, ...rest] = addresses;
138
138
  const lines = ["mobile-remote ▶ 手机 App 连接信息 / Phone app connection"];
package/lib/backup.js CHANGED
@@ -1,52 +1,52 @@
1
- /**
2
- * 备份、恢复与「预演恢复」(P1-16)。
3
- *
4
- * 为什么需要预演:恢复是一次**不可撤销的写入**,而用户手里的备份文件可能来自
5
- * 另一台电脑、另一个版本、甚至是手改过的。让他在真写之前先看清「会写进去多少条、
6
- * 跳过多少条、为什么跳过」,比事后提供一个「撤销」便宜得多。
7
- *
8
- * 为什么预演和真恢复必须是同一份计划:如果预演走一套判断、真恢复走另一套,
9
- * 预演就变成了一句安慰话——它会说「将恢复 42 条」,而实际写进去 40 条。
10
- * 所以两者都调 `planRestore()`,真恢复只是把计划执行一遍。
11
- *
12
- * **备份里没有凭据,这是刻意的**:
13
- * - `auth-token`(连接口令)与 `relay/`(中继身份私钥)能让别人冒充这台电脑
14
- * 或这个账号。备份文件通常被放进网盘、聊天记录、U 盘,一旦带上它们,
15
- * 泄露面就从"一台机器"变成"所有存过备份的地方"。
16
- * - `held-queue`(暂存待发消息)与 `send-receipts`(幂等回执)具有强时效性,
17
- * 恢复到另一台设备只会产生重复投递与陈旧状态。
18
- * 所以恢复之后需要在**新设备上重新扫码配对**——这是设计,不是缺陷,要说出来。
19
- *
20
- * 恢复是**只增不删**的:已有条目按 (scope, text) 判重后跳过,绝不因为备份里
21
- * 没有某条就删掉本机现有的。这样即使用户拿错了备份文件,也不会丢东西。
22
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
23
  import { createCipheriv, createDecipheriv, randomBytes, scrypt } from "node:crypto";
24
24
  import { SCOPES } from "./memory/store.js";
25
25
  import { parseHm } from "./notify-copy.js";
26
26
 
27
- /** 文件里的格式标记。读到别的值说明这不是我们的备份,不要试着"尽力解析"。 */
27
+
28
28
  export const BACKUP_FORMAT = "dsh-mobile-backup";
29
29
 
30
- /** 版本号。将来改结构时递增,旧版本仍需可读。 */
30
+
31
31
  export const BACKUP_VERSION = 1;
32
32
 
33
- /** 单条记忆的长度上限,与 `/api/memory` 的写入校验保持一致。 */
33
+
34
34
  const MAX_TEXT = 4000;
35
35
 
36
- /** 一次恢复的条数上限:防止一个巨型/畸形文件把库灌满。 */
36
+
37
37
  export const MAX_RESTORE_ITEMS = 5000;
38
38
 
39
- /**
40
- * Largest restore request body, in bytes (T-55, finding E5). The generic 64 KiB body limit made
41
- * every real backup fail as "not valid JSON". 32 MiB holds MAX_RESTORE_ITEMS full-length items of
42
- * ASCII text with room to spare; anything larger is refused with a 413 that says so.
43
- */
39
+
40
+
41
+
42
+
43
+
44
44
  export const MAX_RESTORE_BODY_BYTES = 32 * 1024 * 1024;
45
45
 
46
- /**
47
- * 备份内容里**明确不包含**的东西。写进文件本身,让拿到备份的人一眼看到
48
- * "这里面没有口令",而不是去猜。
49
- */
46
+
47
+
48
+
49
+
50
50
  export const BACKUP_EXCLUDES = [
51
51
  "auth-token(连接口令)",
52
52
  "relay/(中继身份私钥与设备名单)",
@@ -55,22 +55,22 @@ export const BACKUP_EXCLUDES = [
55
55
  "session-titles / session-activity / session-message-time(与本机会话 id 绑定)",
56
56
  ];
57
57
 
58
- /**
59
- * 生成备份对象。
60
- *
61
- * @param {object} e
62
- * @param {object|null} e.store 记忆库(null = 记忆功能没开,仍可备份人格)
63
- * @param {{get: () => object}} e.prefs 助手偏好
64
- * @param {() => number} [e.now]
65
- */
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
66
  export function buildBackup({ store, prefs, now = () => Date.now() }) {
67
67
  const memories = store ? store.exportAll() : [];
68
68
  return {
69
69
  format: BACKUP_FORMAT,
70
70
  version: BACKUP_VERSION,
71
71
  createdAt: new Date(now()).toISOString(),
72
- // 只备份"关于这个人"的数据:记忆 + 模式/人格/安静时段。
73
- // 会话、任务、审批都是电脑上那一刻的状态,不属于可搬运的用户数据。
72
+
73
+
74
74
  excludes: BACKUP_EXCLUDES,
75
75
  assistant: prefs?.get?.() ?? null,
76
76
  memories: memories.map((m) => ({
@@ -79,38 +79,38 @@ export function buildBackup({ store, prefs, now = () => Date.now() }) {
79
79
  source: m.source === "manual" ? "manual" : "conversation",
80
80
  origin: m.origin ?? null,
81
81
  pinned: Boolean(m.pinned),
82
- // 衰减参数一并带走:否则恢复后所有旧记忆都会被当成"刚记住",
83
- // 到第 60 天集体消失一次——那不是恢复,是重置。
82
+
83
+
84
84
  stability: typeof m.stability === "number" ? m.stability : undefined,
85
85
  difficulty: typeof m.difficulty === "number" ? m.difficulty : undefined,
86
86
  lastRecalledAt:
87
87
  typeof m.lastRecalledAt === "number" ? m.lastRecalledAt : undefined,
88
- // T-63:删掉的记忆不进备份(exportAll 只给现存的)。旧备份里带 `deleted: true`
89
- // 的条目在恢复时仍会被跳过(见 validateMemory)。
88
+
89
+
90
90
  })),
91
91
  };
92
92
  }
93
93
 
94
- // ── 备份口令(T-63,可选)────────────────────────────────────────────────
95
- //
96
- // 不设口令时备份是明文 JSON(原样可读,便于用户自己检查)。设了口令时整份备份用
97
- // scrypt 派生的密钥做 AES-256-GCM 加密,文件里只剩格式标记与密文:拿到文件但不知道
98
- // 口令的人读不到任何一条记忆。口令只在请求里出现一次,插件不保存它。
99
-
100
- /**
101
- * 口令最短长度,按字符(code point)数,不按 UTF-16 单元(A-16)。A backup file can be attacked
102
- * offline at full speed, so this follows NIST SP 800-63B-4 for single-factor passwords: at least
103
- * 15 characters, plus a check against obviously guessable ones (`passphraseProblem`).
104
- */
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
105
  export const MIN_BACKUP_PASSPHRASE = 15;
106
106
 
107
- /** A few long passphrases that are on every list; the shape checks below catch most of the rest. */
107
+
108
108
  const COMMON_PASSPHRASES = new Set([
109
109
  "passwordpassword", "password1234567", "123456789012345", "1234567890123456", "qwertyuiopasdfg",
110
110
  "qwertyuiopasdfgh", "1q2w3e4r5t6y7u8i", "iloveyouiloveyou", "abcdefghijklmno", "abcdefghijklmnop",
111
111
  ]);
112
112
 
113
- /** Why `passphrase` is too weak for an offline-attackable backup, or null if it is acceptable. */
113
+
114
114
  export function passphraseProblem(passphrase) {
115
115
  if (typeof passphrase !== "string") return `口令至少 ${MIN_BACKUP_PASSPHRASE} 个字符 / the passphrase needs at least ${MIN_BACKUP_PASSPHRASE} characters`;
116
116
  const chars = [...passphrase.normalize("NFC")];
@@ -122,16 +122,16 @@ export function passphraseProblem(passphrase) {
122
122
  return null;
123
123
  }
124
124
 
125
- /**
126
- * Written now: scrypt N=2^17, r=8, p=1 (OWASP's minimum for scrypt, A-16). 3.3.0 wrote N=2^15;
127
- * those backups still open. No other parameter set is accepted from a file (T-63: a file must not
128
- * be able to make the plugin spend unbounded time or memory).
129
- */
125
+
126
+
127
+
128
+
129
+
130
130
  const KDF = { name: "scrypt", N: 1 << 17, r: 8, p: 1, keyLen: 32 };
131
131
  const ACCEPTED_KDF = [KDF, { name: "scrypt", N: 1 << 15, r: 8, p: 1, keyLen: 32 }];
132
132
  export const BACKUP_KDF = Object.freeze({ ...KDF });
133
133
 
134
- /** One scrypt at a time (each takes ~128 MiB and a few hundred ms), off the event loop. */
134
+
135
135
  let kdfQueue = Promise.resolve();
136
136
  const deriveKey = (passphrase, salt, kdf = KDF) => {
137
137
  const run = () =>
@@ -145,17 +145,17 @@ const deriveKey = (passphrase, salt, kdf = KDF) => {
145
145
  return next;
146
146
  };
147
147
 
148
- /** 备份文件是不是加了口令的。 */
148
+
149
149
  export function isEncryptedBackup(payload) {
150
150
  return Boolean(payload && typeof payload === "object" && payload.encrypted && typeof payload.encrypted === "object");
151
151
  }
152
152
 
153
- /**
154
- * 给备份加口令。返回 `{ format, version, encrypted: {...} }`,可直接存成文件。
155
- * @param {object} backup buildBackup 的结果
156
- * @param {string} passphrase 至少 MIN_BACKUP_PASSPHRASE 个字符,且不是 passphraseProblem 认为好猜的
157
- * @returns {Promise<object>}
158
- */
153
+
154
+
155
+
156
+
157
+
158
+
159
159
  export async function encryptBackup(backup, passphrase) {
160
160
  const problem = passphraseProblem(passphrase);
161
161
  if (problem) throw Object.assign(new Error(problem), { code: "weak-passphrase" });
@@ -163,7 +163,7 @@ export async function encryptBackup(backup, passphrase) {
163
163
  const iv = randomBytes(12);
164
164
  const key = await deriveKey(passphrase, salt);
165
165
  const cipher = createCipheriv("aes-256-gcm", key, iv);
166
- // 格式标记作为附加认证数据:密文被挪到别的格式里会解不开。
166
+
167
167
  cipher.setAAD(Buffer.from(`${BACKUP_FORMAT}/${BACKUP_VERSION}`));
168
168
  const data = Buffer.concat([cipher.update(JSON.stringify(backup), "utf8"), cipher.final()]);
169
169
  return {
@@ -179,10 +179,10 @@ export async function encryptBackup(backup, passphrase) {
179
179
  };
180
180
  }
181
181
 
182
- /**
183
- * 解开加了口令的备份。口令不对、文件被改过、参数不认识都抛错(`code` 区分)。
184
- * @returns {object} 原始备份对象(再交给 planRestore / applyRestore)
185
- */
182
+
183
+
184
+
185
+
186
186
  export async function decryptBackup(envelope, passphrase) {
187
187
  const e = envelope?.encrypted;
188
188
  if (!e || e.cipher !== "aes-256-gcm" || e.kdf?.name !== "scrypt") {
@@ -191,8 +191,8 @@ export async function decryptBackup(envelope, passphrase) {
191
191
  if (typeof passphrase !== "string" || passphrase === "") {
192
192
  throw Object.assign(new Error("这份备份设了口令 / this backup needs its passphrase"), { code: "passphrase-required" });
193
193
  }
194
- // 参数来自文件:只接受我们自己写的那一组。scryptSync 在事件循环上跑,放宽就等于让一个
195
- // 恶意文件把插件卡住或吃光内存(T-63 fix)。
194
+
195
+
196
196
  const N = Number(e.kdf.N);
197
197
  const r = Number(e.kdf.r);
198
198
  const p = Number(e.kdf.p);
@@ -205,7 +205,7 @@ export async function decryptBackup(envelope, passphrase) {
205
205
  }
206
206
  try {
207
207
  const key = await deriveKey(passphrase, Buffer.from(String(e.kdf.salt), "base64"), { N, r, p, keyLen: 32 });
208
- // authTagLength: a truncated tag is refused instead of checked on fewer bits (DEP0182).
208
+
209
209
  const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(String(e.iv), "base64"), { authTagLength: 16 });
210
210
  decipher.setAAD(Buffer.from(`${envelope.format}/${envelope.version}`));
211
211
  decipher.setAuthTag(tag);
@@ -216,11 +216,11 @@ export async function decryptBackup(envelope, passphrase) {
216
216
  }
217
217
  }
218
218
 
219
- /**
220
- * 校验一条待恢复的记忆。返回 `{ ok: true, item }` 或 `{ ok: false, reason }`。
221
- *
222
- * 备份文件是外部输入,一律当作不可信:不信任任何字段的类型,也不信任长度。
223
- */
219
+
220
+
221
+
222
+
223
+
224
224
  function validateMemory(raw, index) {
225
225
  if (!raw || typeof raw !== "object") {
226
226
  return { ok: false, reason: "不是对象", index };
@@ -238,7 +238,7 @@ function validateMemory(raw, index) {
238
238
  return { ok: false, reason: `text 超过 ${MAX_TEXT} 字符`, index };
239
239
  }
240
240
  if (raw.deleted === true) {
241
- // 旧版本的备份会带上软删除的条目:删掉的就是删掉了,不恢复。
241
+
242
242
  return { ok: false, reason: "备份里这条已删除", index };
243
243
  }
244
244
  return {
@@ -254,15 +254,15 @@ function validateMemory(raw, index) {
254
254
  };
255
255
  }
256
256
 
257
- /**
258
- * 算出「这次恢复会做什么」。纯函数:不写库、不改任何状态。
259
- *
260
- * @param {unknown} payload 备份文件解析后的对象
261
- * @param {object} e
262
- * @param {object|null} e.store
263
- * @param {{get: () => object}} e.prefs
264
- * @returns {{ok: boolean, error?: string, counts: object, items: object[], skipped: object[], assistant: object|null}}
265
- */
257
+
258
+
259
+
260
+
261
+
262
+
263
+
264
+
265
+
266
266
  export function planRestore(payload, { store, prefs }) {
267
267
  const empty = {
268
268
  ok: false,
@@ -285,8 +285,8 @@ export function planRestore(payload, { store, prefs }) {
285
285
  return { ...empty, error: "备份版本号缺失或非法" };
286
286
  }
287
287
  if (payload.version > BACKUP_VERSION) {
288
- // 新版本备份可能带旧代码看不懂的字段。与其"尽力恢复"出一个半截状态,
289
- // 不如明确拒绝并告诉用户升级插件。
288
+
289
+
290
290
  return {
291
291
  ...empty,
292
292
  error: `备份来自更新的版本(v${payload.version}),请先升级插件`,
@@ -304,8 +304,8 @@ export function planRestore(payload, { store, prefs }) {
304
304
  };
305
305
  }
306
306
 
307
- // 本机已有条目:按 (scope, text) 判重。用归一化后的文本比较——
308
- // 否则「末尾多一个空格」会让同一条记忆被恢复成两条。
307
+
308
+
309
309
  const existing = new Set();
310
310
  if (store) {
311
311
  for (const mode of ["work", "life"]) {
@@ -341,8 +341,8 @@ export function planRestore(payload, { store, prefs }) {
341
341
  items.push(v.item);
342
342
  });
343
343
 
344
- // 人格/模式:只在字段合法时恢复。非法就整块跳过,不"猜一个最近的"——
345
- // 猜错会让用户以为恢复成功,实际还在原来的模式里。
344
+
345
+
346
346
  let assistant = null;
347
347
  const a = payload.assistant;
348
348
  if (a && typeof a === "object") {
@@ -352,9 +352,9 @@ export function planRestore(payload, { store, prefs }) {
352
352
  next.persona = a.persona;
353
353
  }
354
354
  const q = a.quietHours;
355
- // 用 `parseHm` 而不是手写正则:`/^\d{1,2}:\d{2}$/` 会放过 `25:00`,
356
- // 而一个非法窗口恢复进去之后,安静时段会整段失效(或整段生效)——
357
- // 用户会发现夜里突然被吵醒,却不知道是恢复带进来的。
355
+
356
+
357
+
358
358
  if (
359
359
  q &&
360
360
  typeof q === "object" &&
@@ -384,13 +384,13 @@ export function planRestore(payload, { store, prefs }) {
384
384
  };
385
385
  }
386
386
 
387
- /**
388
- * 执行恢复:跑同一份计划,然后按计划写入。
389
- *
390
- * 只增不删——本机现有条目一条都不会因为这次恢复而消失。
391
- *
392
- * @returns {{ok: boolean, error?: string, added: number, skipped: number, invalid: number, assistant: boolean}}
393
- */
387
+
388
+
389
+
390
+
391
+
392
+
393
+
394
394
  export function applyRestore(payload, { store, prefs }) {
395
395
  const plan = planRestore(payload, { store, prefs });
396
396
  if (!plan.ok) {
@@ -416,7 +416,7 @@ export function applyRestore(payload, { store, prefs }) {
416
416
  });
417
417
  added += 1;
418
418
  } catch (err) {
419
- // 单条失败不该中断整次恢复:脱敏后为空、库写满都会走到这里。
419
+
420
420
  plan.skipped.push({ index: -1, reason: err?.message ?? "写入失败" });
421
421
  }
422
422
  }
@@ -427,13 +427,13 @@ export function applyRestore(payload, { store, prefs }) {
427
427
  prefs.set(plan.assistant);
428
428
  assistant = true;
429
429
  } catch {
430
- // 人格恢复失败不影响记忆:两块分别报告,不混成一个"失败"。
430
+
431
431
  }
432
432
  }
433
433
  return {
434
434
  ok: true,
435
435
  added,
436
- // 计划里的跳过 + 写入时失败的
436
+
437
437
  skipped: plan.skipped.length,
438
438
  invalid: plan.counts.invalid,
439
439
  assistant,