@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
@@ -0,0 +1,369 @@
1
+ /**
2
+ * 主动消息调度器(P0-5 / P0-6 的剩余部分)。
3
+ *
4
+ * 解决的问题只有三个,全部来自"用户被吵醒"与"提醒丢了"这两种真实抱怨:
5
+ *
6
+ * 1. **`nextFireAt` 落盘**。用 `setTimeout(N)` 排一次性提醒,进程重启、笔记本合盖、
7
+ * 系统时间跳变之后那个定时器就永远不触发了——用户等不到本该到来的汇报。
8
+ * 这里把"下一次该在什么时候发"写进磁盘,每次 tick 重新算"现在该不该发"。
9
+ * 定时器只负责把我叫醒,不负责决定发什么。
10
+ * 2. **每日上限**。没有上限的主动消息会很快变成骚扰,用户第一件事就是关掉它,
11
+ * 于是这个功能永久失效。上限按电脑本地日历日算,跨零点归零。
12
+ * 3. **主人在聊时不插嘴**。用户正在跟助手对话时插一条"我想到一件事"是最烦的;
13
+ * 这条判据必须能观测到"最近有没有人在说话",所以由调用方在装配时传入一个
14
+ * 读当前活动的回调,而不是让调度器自己去猜。
15
+ *
16
+ * 刻意不做的事:
17
+ * - **不生成内容**。调度器只决定"什么时候可以开口",说什么由调用方给的 `pick`
18
+ * 决定;`pick` 返回 null 就这次不发,且不消耗每日配额。这样"没有值得说的"与
19
+ * "说漏了"是两件不同的事,前者不该记账。
20
+ * - **不用长定时器**。tick 间隔固定(默认 60s),每次重算,时钟跳变最多晚一个 tick。
21
+ * - **不重发同一条**。候选带 `key`,发过的 key 落盘,进程重启也不会重复。
22
+ *
23
+ * 状态文件 `<状态目录>/proactive.json`:与口令、记忆库同在状态目录下,只在本机。
24
+ */
25
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
26
+ import { dirname, join } from "node:path";
27
+
28
+ /** 默认 tick 间隔。60s 够用:主动消息的精度本来就是分钟级。 */
29
+ export const DEFAULT_TICK_MS = 60_000;
30
+
31
+ /** 默认每日上限。3 条是"它记得我"与"它在烦我"之间比较稳的一条线。 */
32
+ export const DEFAULT_DAILY_LIMIT = 3;
33
+
34
+ /** 默认最小间隔:两条主动消息之间至少隔这么久,避免一次 tick 连发。 */
35
+ export const DEFAULT_MIN_GAP_MS = 90 * 60_000;
36
+
37
+ /**
38
+ * 沉默衰减(T-32,§5.7):从「第一条没得到回应的主动消息」算起,
39
+ * 3 天没回应就少说(每天至多 1 条,只说到期提醒与在等你的事),7 天没回应就停。
40
+ * 用户任何一次操作都算回应,计时清零。这样它永远不会因为你不在而越说越多。
41
+ */
42
+ export const SILENCE_SAY_LESS_MS = 3 * 24 * 60 * 60_000;
43
+ export const SILENCE_STOP_MS = 7 * 24 * 60 * 60_000;
44
+
45
+ /**
46
+ * 沉默等级:`normal` 照常;`less` 少说;`stopped` 不说。
47
+ * @param {{unansweredSince: number|null, now: Date}} e
48
+ */
49
+ export function silenceLevel({ unansweredSince, now }) {
50
+ if (unansweredSince == null) return "normal";
51
+ const silent = now.getTime() - unansweredSince;
52
+ if (silent >= SILENCE_STOP_MS) return "stopped";
53
+ if (silent >= SILENCE_SAY_LESS_MS) return "less";
54
+ return "normal";
55
+ }
56
+
57
+ /**
58
+ * 本地日历日的键(`YYYY-MM-DD`)。
59
+ *
60
+ * 必须用本地时间:用户在 UTC+8 的晚上 11 点与 UTC-8 的早上 7 点是同一天的不同感受,
61
+ * 用 UTC 会让"每日"在用户的夜里归零。
62
+ */
63
+ export function localDayKey(at) {
64
+ const y = at.getFullYear();
65
+ const m = String(at.getMonth() + 1).padStart(2, "0");
66
+ const d = String(at.getDate()).padStart(2, "0");
67
+ return `${y}-${m}-${d}`;
68
+ }
69
+
70
+ /**
71
+ * 判断现在能不能发一条主动消息。纯函数,所有输入显式传入——这样每条规则都能单测。
72
+ *
73
+ * 返回 `{ ok, reason }`:`reason` 只用于日志与诊断,不参与业务。
74
+ *
75
+ * @param {object} e
76
+ * @param {Date} e.now 当前时刻(本地时间)
77
+ * @param {number} [e.dailyLimit] 每日上限;0 表示关闭主动消息
78
+ * @param {{day: string, count: number}|null} [e.todaySent] 今天已发计数
79
+ * @param {number|null} [e.lastSentAt] 上一条主动消息的时间戳(毫秒)
80
+ * @param {number} [e.minGapMs] 两条之间最小间隔
81
+ * @param {boolean} [e.quiet] 是否处于安静时段(由 shouldSuppressForQuietHours 算出)
82
+ * @param {boolean} [e.userActive] 用户最近是否在对话("主人在聊时不插嘴")
83
+ * @param {boolean} [e.busy] 有会话正在干活(T-32:不打断正在跑的任务)
84
+ * @param {"normal"|"less"|"stopped"} [e.silence] 沉默等级(silenceLevel)
85
+ * @param {boolean} [e.paused] 用户手动暂停
86
+ */
87
+ export function canFire({
88
+ now,
89
+ dailyLimit = DEFAULT_DAILY_LIMIT,
90
+ todaySent = null,
91
+ lastSentAt = null,
92
+ minGapMs = DEFAULT_MIN_GAP_MS,
93
+ quiet = false,
94
+ userActive = false,
95
+ busy = false,
96
+ silence = "normal",
97
+ paused = false,
98
+ }) {
99
+ if (paused) return { ok: false, reason: "paused" };
100
+ if (!Number.isFinite(dailyLimit) || dailyLimit <= 0) {
101
+ return { ok: false, reason: "disabled" };
102
+ }
103
+ if (silence === "stopped") return { ok: false, reason: "silence-stopped" };
104
+ if (quiet) return { ok: false, reason: "quiet-hours" };
105
+ if (userActive) return { ok: false, reason: "user-active" };
106
+ if (busy) return { ok: false, reason: "session-busy" };
107
+ const day = localDayKey(now);
108
+ const used = todaySent && todaySent.day === day ? todaySent.count : 0;
109
+ // 少说:每天至多 1 条。
110
+ const limit = silence === "less" ? Math.min(dailyLimit, 1) : dailyLimit;
111
+ if (used >= limit) return { ok: false, reason: silence === "less" ? "silence-less" : "daily-limit" };
112
+ if (lastSentAt != null) {
113
+ const gap = now.getTime() - lastSentAt;
114
+ // 时钟往回跳会得到负值——此时不阻塞(否则用户改了系统时间就永久收不到消息了),
115
+ // 但把上一条的时间更新掉,见 markSent。
116
+ if (gap >= 0 && gap < minGapMs) return { ok: false, reason: "min-gap" };
117
+ }
118
+ return { ok: true, reason: "ok" };
119
+ }
120
+
121
+ /**
122
+ * 读状态文件。任何损坏都回落到空状态,绝不因为 JSON 坏了而不启动。
123
+ *
124
+ * @param {string} file
125
+ */
126
+ export function readState(file) {
127
+ try {
128
+ const raw = readFileSync(file, "utf8");
129
+ const parsed = JSON.parse(raw);
130
+ if (!parsed || typeof parsed !== "object") return emptyState();
131
+ return {
132
+ todaySent:
133
+ parsed.todaySent && typeof parsed.todaySent.day === "string"
134
+ ? { day: parsed.todaySent.day, count: Number(parsed.todaySent.count) || 0 }
135
+ : null,
136
+ lastSentAt: Number.isFinite(parsed.lastSentAt) ? parsed.lastSentAt : null,
137
+ nextFireAt: Number.isFinite(parsed.nextFireAt) ? parsed.nextFireAt : null,
138
+ sentKeys: Array.isArray(parsed.sentKeys)
139
+ ? parsed.sentKeys.filter((k) => typeof k === "string").slice(-200)
140
+ : [],
141
+ unansweredSince: Number.isFinite(parsed.unansweredSince) ? parsed.unansweredSince : null,
142
+ lastReactionAt: Number.isFinite(parsed.lastReactionAt) ? parsed.lastReactionAt : null,
143
+ ...(parsed.paused === true ? { paused: true } : {}),
144
+ };
145
+ } catch {
146
+ return emptyState();
147
+ }
148
+ }
149
+
150
+ export function emptyState() {
151
+ return { todaySent: null, lastSentAt: null, nextFireAt: null, sentKeys: [], unansweredSince: null, lastReactionAt: null };
152
+ }
153
+
154
+ /**
155
+ * 原子写状态文件:先写 `.tmp` 再 rename。
156
+ *
157
+ * 直接覆盖写会在断电/进程被杀时留下半截 JSON,下次启动就丢掉"今天已经发了 3 条"
158
+ * 这个事实,于是用户当天被多发几条。rename 在同一文件系统上是原子的。
159
+ */
160
+ export function writeState(file, state) {
161
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
162
+ const tmp = `${file}.tmp`;
163
+ writeFileSync(tmp, JSON.stringify(state, null, 2), { mode: 0o600 });
164
+ renameSync(tmp, file);
165
+ }
166
+
167
+ /**
168
+ * 创建调度器。
169
+ *
170
+ * @param {object} e
171
+ * @param {string} e.dir 状态目录(与口令、memory.db 同层)
172
+ * @param {() => Date} [e.now] 时间源(测试注入)
173
+ * @param {() => boolean} [e.isQuiet] 当前是否安静时段
174
+ * @param {() => boolean} [e.isUserActive] 用户最近是否在对话
175
+ * @param {() => boolean} [e.isBusy] 有会话正在干活(T-32)
176
+ * @param {() => boolean} [e.isChatting] 用户此刻正在打字对话(T-32 fix:用户自己设的提醒只看这一条与安静时段)
177
+ * @param {(ctx: {level: string, now: Date, sentKeys: string[]}) => Promise<{key: string, text: string}|null>} [e.pick]
178
+ * 选一条要发的候选;返回 null 表示这次没有值得说的(不记账)。`level` 是沉默等级,
179
+ * `sentKeys` 是已经发过的 key,候选来源据此跳过发过的、换下一条。
180
+ * @param {(item: {key: string, text: string}) => Promise<void>} [e.deliver]
181
+ * 真正发出去的动作(推送/气泡/IM)。
182
+ * @param {(e: {reason: string, at: string}) => void} [e.log]
183
+ * @param {object} [e.config] `{enabled, dailyLimit, minGapMs, tickMs}`
184
+ */
185
+ export function createProactiveScheduler({
186
+ dir,
187
+ now = () => new Date(),
188
+ isQuiet = () => false,
189
+ isUserActive = () => false,
190
+ isBusy = () => false,
191
+ isChatting = () => false,
192
+ pick = async () => null,
193
+ deliver = async () => {},
194
+ log = () => {},
195
+ config = {},
196
+ }) {
197
+ if (!dir) throw new Error("createProactiveScheduler: dir is required");
198
+ const file = join(dir, "proactive.json");
199
+ // 配置层只保证是数字(项目用的是 schemastery,没有 `.int()`),
200
+ // 所以在这里统一取整:`dailyLimit: 2.7` 的含义不该是"发 2.7 条"这种需要猜的东西。
201
+ const dailyLimit = Number.isFinite(config.dailyLimit)
202
+ ? Math.max(0, Math.floor(config.dailyLimit))
203
+ : DEFAULT_DAILY_LIMIT;
204
+ const minGapMs = Number.isFinite(config.minGapMs)
205
+ ? Math.max(0, config.minGapMs)
206
+ : DEFAULT_MIN_GAP_MS;
207
+ const tickMs = Number.isFinite(config.tickMs) && config.tickMs > 0
208
+ ? config.tickMs
209
+ : DEFAULT_TICK_MS;
210
+ const enabled = config.enabled !== false;
211
+
212
+ let state = readState(file);
213
+ let timer = null;
214
+ let stopped = true;
215
+ /** 上一次 tick 记下的判据,供诊断读("它现在为什么不说")。 */
216
+ let lastReason = "idle";
217
+
218
+ function save() {
219
+ try {
220
+ writeState(file, state);
221
+ } catch (err) {
222
+ // 落盘失败不能让调度器停摆:内存里的计数照旧生效,重启后最多多发一条。
223
+ log({ reason: `save-failed:${err?.message ?? err}`, at: now().toISOString() });
224
+ }
225
+ }
226
+
227
+ /**
228
+ * 记一次已发:更新当日计数、最后发送时间、已发 key。
229
+ * 用户自己设的提醒(kind "due")不算主动开口,不进沉默计时。
230
+ */
231
+ function markSent(item, at) {
232
+ const day = localDayKey(at);
233
+ const used = state.todaySent && state.todaySent.day === day
234
+ ? state.todaySent.count
235
+ : 0;
236
+ state = {
237
+ ...state,
238
+ todaySent: { day, count: used + 1 },
239
+ lastSentAt: at.getTime(),
240
+ sentKeys: [...state.sentKeys, item.key].slice(-200),
241
+ // 沉默计时从「回应之后的第一条」开始;后面再发不重置起点。
242
+ unansweredSince: item.kind === "due" ? state.unansweredSince : (state.unansweredSince ?? at.getTime()),
243
+ };
244
+ save();
245
+ }
246
+
247
+ /** 用户有任何操作 = 回应了:沉默计时清零(T-32)。 */
248
+ function noteReaction(at = now()) {
249
+ if (state.unansweredSince == null && state.lastReactionAt != null && at.getTime() - state.lastReactionAt < 60_000) return;
250
+ state = { ...state, unansweredSince: null, lastReactionAt: at.getTime() };
251
+ save();
252
+ }
253
+
254
+ /**
255
+ * 一次 tick:重算"现在该不该发",该发就选一条并投递。
256
+ *
257
+ * 这个函数是**可重入安全**的:并发调用时后到的那个会看到 `inFlight`,直接返回。
258
+ */
259
+ let inFlight = false;
260
+ async function tick() {
261
+ if (inFlight) return { fired: false, reason: "in-flight" };
262
+ if (!enabled) return { fired: false, reason: "disabled" };
263
+ inFlight = true;
264
+ try {
265
+ const at = now();
266
+ const level = silenceLevel({ unansweredSince: state.unansweredSince, now: at });
267
+ const gate = canFire({
268
+ now: at,
269
+ dailyLimit,
270
+ todaySent: state.todaySent,
271
+ lastSentAt: state.lastSentAt,
272
+ minGapMs,
273
+ quiet: isQuiet(),
274
+ userActive: isUserActive(),
275
+ busy: isBusy(),
276
+ silence: level,
277
+ paused: Boolean(state.paused),
278
+ });
279
+ // T-32 fix: a reminder the user set is not proactive chatter. When the full gate says no
280
+ // only because of idleness, a busy session, the daily allowance, the gap or silence decay,
281
+ // it may still go out, as long as the user is not chatting right now (quiet hours, pause
282
+ // and "off" always hold). pick() is asked for due reminders only, and anything else it
283
+ // returns is ignored.
284
+ let dueOnly = false;
285
+ if (!gate.ok) {
286
+ const lighter = !["paused", "disabled", "quiet-hours"].includes(gate.reason) && !isChatting();
287
+ if (!lighter) {
288
+ lastReason = gate.reason;
289
+ // 闸门没过也要把"下一次该检查的时间"落盘:诊断页据此显示"它什么时候会再想说话"。
290
+ state = { ...state, nextFireAt: at.getTime() + tickMs };
291
+ save();
292
+ return { fired: false, reason: gate.reason };
293
+ }
294
+ dueOnly = true;
295
+ }
296
+
297
+ const picked = await pick({ level, now: at, sentKeys: [...state.sentKeys], ...(dueOnly ? { dueOnly: true } : {}) });
298
+ const item = dueOnly && picked?.kind !== "due" ? null : picked;
299
+ if (dueOnly && !item) {
300
+ lastReason = gate.reason;
301
+ state = { ...state, nextFireAt: at.getTime() + tickMs };
302
+ save();
303
+ return { fired: false, reason: gate.reason };
304
+ }
305
+ if (!item || typeof item.key !== "string" || typeof item.text !== "string") {
306
+ lastReason = "nothing-to-say";
307
+ state = { ...state, nextFireAt: at.getTime() + tickMs };
308
+ save();
309
+ return { fired: false, reason: "nothing-to-say" };
310
+ }
311
+ if (state.sentKeys.includes(item.key)) {
312
+ // 同一条候选发过:不要重复。"没有新的"不等于"可以重复"。
313
+ lastReason = "already-sent";
314
+ state = { ...state, nextFireAt: at.getTime() + tickMs };
315
+ save();
316
+ return { fired: false, reason: "already-sent" };
317
+ }
318
+
319
+ await deliver(item);
320
+ markSent(item, at);
321
+ lastReason = "sent";
322
+ // 下一条最早也要等到最小间隔之后。
323
+ state = { ...state, nextFireAt: at.getTime() + minGapMs };
324
+ save();
325
+ log({ reason: `sent:${item.key}`, at: at.toISOString() });
326
+ return { fired: true, key: item.key };
327
+ } catch (err) {
328
+ lastReason = `error:${err?.message ?? err}`;
329
+ log({ reason: lastReason, at: now().toISOString() });
330
+ return { fired: false, reason: lastReason };
331
+ } finally {
332
+ inFlight = false;
333
+ }
334
+ }
335
+
336
+ function start() {
337
+ if (!stopped) return;
338
+ stopped = false;
339
+ timer = setInterval(() => {
340
+ void tick();
341
+ }, tickMs);
342
+ // 不要让调度器把宿主进程的退出拖住。
343
+ timer.unref?.();
344
+ // 启动时立刻跑一次:合盖一整晚之后不该再等一个完整 tick。
345
+ void tick();
346
+ }
347
+
348
+ function stop() {
349
+ stopped = true;
350
+ if (timer) clearInterval(timer);
351
+ timer = null;
352
+ }
353
+
354
+ return {
355
+ file,
356
+ start,
357
+ stop,
358
+ tick,
359
+ /** 只读快照:诊断页/测试用。 */
360
+ snapshot: () => ({ ...state, lastReason, enabled, silence: silenceLevel({ unansweredSince: state.unansweredSince, now: now() }) }),
361
+ noteReaction,
362
+ /** 手动暂停/继续(App 或设置页可调)。 */
363
+ setPaused: (v) => {
364
+ state = { ...state, paused: Boolean(v) };
365
+ save();
366
+ },
367
+ isPaused: () => Boolean(state.paused),
368
+ };
369
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Folders the phone's file routes must never read, list or write (T-62, finding E11).
3
+ *
4
+ * `/files`, `/directories` and the git preview let a paired phone look at the PC; that is the
5
+ * feature. But the DSH home (default `~/.dsh`, or `$DSH_HOME`) holds DSH's own keys
6
+ * (`.credentials.yaml`, `.env`) and this plugin's state (`mobile-remote/`: the access token, the
7
+ * relay private key, the memory database and archive, reminders, persona cards, prefs).
8
+ *
9
+ * T-62 fix: names are not identities. One folder has many spellings (`/System/Volumes/Data/Users/…`
10
+ * on macOS, an NFD-decomposed "José", a Windows 8.3 short name, a symlink, `..`), so the check is
11
+ * done on file identity, `(dev, ino)`:
12
+ * - `isProtectedPath(path)`: the real path of the target, or of its nearest existing parent,
13
+ * and every folder above it, compared by `(dev, ino)` with the protected folders. A string
14
+ * prefix check runs first as a fast path.
15
+ * - `isProtectedFile(stat)`: after opening, the opened file's `(dev, ino)` compared with every
16
+ * file inside the protected folders. That catches hard links and `/dev/fd/N`, and checks what
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).
19
+ */
20
+ import { lstatSync, readdirSync, realpathSync, statSync } from "node:fs";
21
+ import { homedir } from "node:os";
22
+ import { dirname, join, resolve, sep } from "node:path";
23
+ import { mobileRemoteStateDir } from "./auto-config.js";
24
+
25
+ const caseInsensitive = process.platform === "darwin" || process.platform === "win32";
26
+ const norm = (p) => (caseInsensitive ? p.normalize("NFC").toLowerCase() : p.normalize("NFC"));
27
+ const idOf = (st) => `${st.dev}:${st.ino}`;
28
+
29
+ /** Resolve symlinks; for a missing path, resolve the nearest existing parent and re-append. */
30
+ export function realPathOf(path) {
31
+ let current = resolve(path);
32
+ const rest = [];
33
+ for (;;) {
34
+ try {
35
+ return join(realpathSync(current), ...rest.reverse());
36
+ } catch {
37
+ const parent = dirname(current);
38
+ if (parent === current) return resolve(path);
39
+ rest.push(current.slice(parent.length).replace(/^[\\/]+/, ""));
40
+ current = parent;
41
+ }
42
+ }
43
+ }
44
+
45
+ /** The protected folders: the DSH home and this plugin's state directory (inside it by default). */
46
+ export function protectedRoots(env = process.env, home = homedir()) {
47
+ const dshHome = typeof env.DSH_HOME === "string" && env.DSH_HOME.trim() !== "" ? env.DSH_HOME : join(home, ".dsh");
48
+ return [dshHome, mobileRemoteStateDir(env, home)].map((root) => realPathOf(root));
49
+ }
50
+
51
+ /** `(dev, ino)` of the protected folders that exist. */
52
+ function rootIds(roots) {
53
+ const ids = new Set();
54
+ for (const root of roots) {
55
+ try {
56
+ ids.add(idOf(statSync(root)));
57
+ } catch {
58
+ /* not created yet: nothing to protect there */
59
+ }
60
+ }
61
+ return ids;
62
+ }
63
+
64
+ /** True for `/dev` and `/proc` and anything under them (open files, other processes). */
65
+ export function isDeviceOrProcPath(path) {
66
+ if (process.platform === "win32") return false;
67
+ const p = resolve(path);
68
+ return ["/dev", "/proc"].some((d) => p === d || p.startsWith(`${d}/`));
69
+ }
70
+
71
+ /** True when `target` is a protected folder or anywhere inside one, whatever it is called. */
72
+ export function isProtectedPath(target, roots = protectedRoots()) {
73
+ if (isDeviceOrProcPath(target)) return true;
74
+ const real = realPathOf(target);
75
+ // Fast path: the usual spelling.
76
+ const r = norm(real);
77
+ if (roots.some((root) => r === norm(root) || r.startsWith(norm(root).endsWith(sep) ? norm(root) : `${norm(root)}${sep}`))) return true;
78
+ // Identity: the nearest existing folder on the way, and every folder above it.
79
+ const ids = rootIds(roots);
80
+ if (ids.size === 0) return false;
81
+ let current = real;
82
+ for (;;) {
83
+ try {
84
+ if (ids.has(idOf(statSync(current)))) return true;
85
+ } catch {
86
+ /* not there (yet): look at its parent */
87
+ }
88
+ const parent = dirname(current);
89
+ if (parent === current) return false;
90
+ current = parent;
91
+ }
92
+ }
93
+
94
+ /**
95
+ * `(dev, ino)` of the protected files: everything in the plugin's state folder (a handful of
96
+ * files, walked a few levels deep) and the top level of the DSH home, where DSH keeps its keys
97
+ * (`.credentials.yaml`, `.env`). Session logs deeper in the DSH home are not keys and are not
98
+ * walked, so this stays cheap enough to run per request. Unlisted subfolders of the DSH home
99
+ * are still refused by path (`isProtectedPath`).
100
+ */
101
+ export function protectedFileIds(roots = protectedRoots()) {
102
+ const [dshHome, stateDir] = roots;
103
+ const ids = rootIds(roots);
104
+ const walk = (dir, depth) => {
105
+ let entries;
106
+ try {
107
+ entries = readdirSync(dir, { withFileTypes: true });
108
+ } catch {
109
+ return;
110
+ }
111
+ for (const entry of entries.slice(0, 2_000)) {
112
+ const path = join(dir, entry.name);
113
+ try {
114
+ const st = lstatSync(path);
115
+ ids.add(idOf(st));
116
+ if (st.isDirectory() && depth > 0) walk(path, depth - 1);
117
+ } catch {
118
+ /* vanished */
119
+ }
120
+ }
121
+ };
122
+ if (stateDir) walk(stateDir, 3);
123
+ if (dshHome) walk(dshHome, 0);
124
+ return ids;
125
+ }
126
+
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));
130
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * App ↔ plugin protocol and feature negotiation (plan §5.12, T-61).
3
+ *
4
+ * Every computer may run a different plugin version, so the plugin says what it speaks
5
+ * and offers, in `/bootstrap` and in the SSE `hello` frame:
6
+ *
7
+ * - `protocol: { min, max }`: the protocol versions it speaks. Version 1 is the API as it
8
+ * stood when negotiation was added (every older plugin speaks exactly that, without
9
+ * saying so). Raise `max` when the plugin learns a new version; raise `min` only when it
10
+ * drops an old one.
11
+ * - `features`: optional features this build has. The app gates each one per computer
12
+ * and shows "update the plugin on {PC}" instead of calling an endpoint that 404s.
13
+ * - `minAppVersion`: the oldest app that works with this plugin.
14
+ *
15
+ * Feature names are shared with the app (`dsh-mobile-app/lib/plugin_protocol.dart`).
16
+ * Not built yet, and so not listed (the app reserves them): `p2p`, `multi-pc`,
17
+ * `phone-tools`, `toolbox-install`. Add a name here in the same change that ships it.
18
+ */
19
+
20
+ export const PROTOCOL = Object.freeze({ min: 1, max: 1 });
21
+
22
+ export const FEATURES = Object.freeze([
23
+ // Persona cards: GET/POST/DELETE /api/persona (T-31).
24
+ "persona-cards",
25
+ ]);
26
+
27
+ /** Apps older than this can't work with this plugin (none so far). */
28
+ export const MIN_APP_VERSION = "3.0.0";
29
+
30
+ /** The fields `/bootstrap` and the `hello` frame carry. */
31
+ export const protocolInfo = () => ({
32
+ protocol: { min: PROTOCOL.min, max: PROTOCOL.max },
33
+ features: [...FEATURES],
34
+ minAppVersion: MIN_APP_VERSION,
35
+ });
package/lib/rate-limit.js CHANGED
@@ -8,7 +8,7 @@
8
8
  */
9
9
  export function createLoginRateLimiter(overrides) {
10
10
  // 正常用户一次成功即重置计数;frp 等中继场景所有外部请求同源(中继 IP),
11
- // 阈值 10 次/60s 对单用户足够宽裕(见 docs/04-security.md §2)。
11
+ // 阈值 10 次/60s 对单用户足够宽裕(见 docs/CONSOLIDATED-DOCUMENTATION.en.md Part 04 §2)。
12
12
  const rateLimitCfg = { maxFailures: 10, windowMs: 60_000, blockMs: 60_000, ...(overrides ?? {}) };
13
13
  const rateBuckets = new Map(); // ip -> { count, windowStart, blockedUntil? }
14
14
  // 封锁用显式的 blockedUntil 计时:到阈值那一刻起算 blockMs,与 windowMs 无关。