@dsh-mobile/mobile-remote 3.2.4 → 3.2.5

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 (57) hide show
  1. package/CHANGELOG.md +204 -0
  2. package/FAQ.md +4 -0
  3. package/README.md +21 -14
  4. package/docs/01-PRD.md +4 -4
  5. package/docs/02-architecture.md +1 -1
  6. package/docs/03-api.md +49 -1
  7. package/docs/05-test-cases.md +7 -7
  8. package/docs/06-install-run.md +16 -3
  9. package/docs/07-user-manual.md +23 -1
  10. package/docs/08-/346/211/251/345/261/225/345/274/200/345/217/221/346/214/207/345/215/227.md +2 -2
  11. package/docs/09-compatibility.md +3 -3
  12. package/docs/10-remote-access-and-launch-plan.md +216 -0
  13. package/docs/11-remote-relay-guide.md +82 -0
  14. package/docs/APP-ENCRYPTION-DESCRIPTION.md +50 -0
  15. package/docs/APP-ENCRYPTION-DESCRIPTION.pdf +0 -0
  16. package/docs/AUDIT-2026-11-node.md +181 -0
  17. package/docs/AUDIT-2026-11.md +167 -0
  18. package/docs/BRAND-ASSETS.md +142 -0
  19. package/docs/BUILD-ENVIRONMENT.md +15 -4
  20. package/docs/FEATURE-PARITY.md +2 -2
  21. package/docs/PRIVACY-POLICY.en.md +143 -0
  22. package/docs/PRIVACY-POLICY.md +108 -30
  23. package/docs/STORE-LAUNCH.md +169 -21
  24. package/docs/STORE-LISTING.md +150 -0
  25. package/docs/SUPPORT.md +4 -3
  26. package/docs/TERMS-OF-SERVICE.en.md +70 -0
  27. package/docs/TERMS-OF-SERVICE.md +70 -0
  28. package/docs/screenshots/01-home.png +0 -0
  29. package/docs/screenshots/02-notifications.png +0 -0
  30. package/docs/screenshots/03-sessions.png +0 -0
  31. package/docs/screenshots/04-chat.png +0 -0
  32. package/docs/screenshots/05-settings.png +0 -0
  33. package/docs/screenshots/06-new-session.png +0 -0
  34. package/docs/screenshots/07-connect.png +0 -0
  35. package/lib/account-usage-query.js +278 -0
  36. package/lib/api-helpers.js +333 -0
  37. package/lib/client.js +284 -1
  38. package/lib/config.js +211 -0
  39. package/lib/host-compat.js +133 -0
  40. package/lib/http-util.js +69 -0
  41. package/lib/index.js +179 -2009
  42. package/lib/push.js +73 -0
  43. package/lib/rate-limit.js +46 -0
  44. package/lib/relay/connector.js +300 -0
  45. package/lib/relay/crypto.js +117 -0
  46. package/lib/relay/devices.js +138 -0
  47. package/lib/relay/identity.js +60 -0
  48. package/lib/relay/mux.js +411 -0
  49. package/lib/relay/noise.js +178 -0
  50. package/lib/relay/pairing.js +64 -0
  51. package/lib/relay/phone.js +114 -0
  52. package/lib/relay/serve.js +105 -0
  53. package/lib/rpc-adapter.js +88 -0
  54. package/lib/session-list.js +77 -0
  55. package/lib/timeline.js +476 -0
  56. package/lib/turn-outline.js +289 -0
  57. package/package.json +1 -1
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,278 @@
1
+ /**
2
+ * 账户用量与额度的上游查询(DeepSeek 余额 / Codex / OpenCode Go)。归一化纯函数在 account-usage.js。
3
+ * 从 lib/index.js 原样拆出(行为不变)。
4
+ */
5
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
6
+ import { createRequire } from "node:module";
7
+ import { homedir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { pathToFileURL } from "node:url";
10
+ import { normalizeCodexUsage, normalizeDeepSeekBalance, normalizeOpenCodeUsage } from "./account-usage.js";
11
+ import { safeFailureReason } from "./api-helpers.js";
12
+ import { readSettingsSection, readSettingsSectionStrict } from "./host-compat.js";
13
+
14
+ /** 与 PC 端设置页一致的凭据引用派生规则(v2.6):路由 id 大写 → `<ID>_API_KEY`。 */
15
+ export function deriveKeyRef(provider) {
16
+ return `${String(provider).toUpperCase().replace(/[^A-Z0-9]+/g, "_")}_API_KEY`;
17
+ }
18
+
19
+ async function resolveCredentialValue(ctx, ref) {
20
+ let value;
21
+ try {
22
+ const credentials = ctx.get("credentials");
23
+ if (credentials?.resolve) value = (await credentials.resolve(credentialRef(ref)))?.value;
24
+ } catch {
25
+ // 环境变量兜底;不把凭据服务异常暴露给手机端。
26
+ }
27
+ if ((!value || typeof value !== "string") && typeof process.env[ref] === "string") value = process.env[ref];
28
+ return typeof value === "string" && value.trim() !== "" ? value : undefined;
29
+ }
30
+
31
+ async function resolveOpenCodeCredential(ctx, profileRef) {
32
+ const validRef = (value) => typeof value === "string"
33
+ && value !== "DEEPSEEK_API_KEY"
34
+ && /^[A-Za-z_][A-Za-z0-9_]*$/.test(value);
35
+ if (validRef(profileRef)) {
36
+ const explicit = await resolveCredentialValue(ctx, profileRef);
37
+ if (explicit) return explicit;
38
+ }
39
+ try {
40
+ const credentials = ctx?.get?.("credentials");
41
+ const record = typeof credentials?.readRecord === "function"
42
+ ? await credentials.readRecord("llm-pi-ai/opencode-go")
43
+ : undefined;
44
+ if (record?.kind === "api-key" && typeof record.key === "string" && record.key.trim() !== "") return record.key;
45
+ } catch {
46
+ // 旧版 credentials 服务没有 readRecord 时继续走引用/环境变量回退。
47
+ }
48
+ for (const ref of ["OPENCODE_GO_API_KEY", "OPENCODE_API_KEY"]) {
49
+ const fallback = await resolveCredentialValue(ctx, ref);
50
+ if (fallback) return fallback;
51
+ }
52
+ return undefined;
53
+ }
54
+
55
+ async function loadCodexConnect() {
56
+ let bareError;
57
+ try {
58
+ return await import("dsh-codex-connect");
59
+ } catch (error) {
60
+ bareError = error;
61
+ }
62
+ const dshHome = typeof process.env.DSH_HOME === "string" && process.env.DSH_HOME.trim() !== ""
63
+ ? process.env.DSH_HOME
64
+ : join(homedir(), ".dsh");
65
+ for (const profile of ["web", "desktop", "cli"]) {
66
+ try {
67
+ const profileRequire = createRequire(join(dshHome, "profiles", profile, "package.json"));
68
+ const entry = profileRequire.resolve("dsh-codex-connect");
69
+ return await import(pathToFileURL(entry).href);
70
+ } catch {
71
+ // 继续尝试其他 DSH profile;缺失时最终按“未安装”处理。
72
+ }
73
+ }
74
+ throw bareError;
75
+ }
76
+
77
+ async function queryDeepSeekUsage(ctx) {
78
+ const key = await resolveCredentialValue(ctx, "DEEPSEEK_API_KEY");
79
+ if (!key) return { configured: false };
80
+ try {
81
+ const response = await fetch("https://api.deepseek.com/user/balance", {
82
+ headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
83
+ signal: AbortSignal.timeout(15_000),
84
+ });
85
+ if (!response.ok) {
86
+ await response.body?.cancel();
87
+ return { configured: true, failed: true, failedId: "deepseek", failedReason: `HTTP ${response.status}` };
88
+ }
89
+ const data = await response.json();
90
+ const balance = normalizeDeepSeekBalance(data);
91
+ return {
92
+ configured: true,
93
+ source: {
94
+ id: "deepseek",
95
+ title: "DeepSeek",
96
+ kind: "balance",
97
+ ...balance,
98
+ },
99
+ };
100
+ } catch (err) {
101
+ return { configured: true, failed: true, failedId: "deepseek", failedReason: safeFailureReason(err) };
102
+ }
103
+ }
104
+
105
+ /**
106
+ * 读取 Codex 代理配置(导出以便单测:issue #21 的回归点正在这里)。
107
+ *
108
+ * 返回值三态,**必须区分**:
109
+ * - `{ enabled: false }` —— 设置读得到,但用户没开代理(走直连是正确的);
110
+ * - `{ enabled: true, url }` —— 代理已启用且地址有效;
111
+ * - `{ enabled: true, url: undefined, unreadable: true }` —— **读不到宿主设置**。
112
+ * 这是插件与宿主的接口问题,不是用户的选择;原实现把它误判为"代理未启用",
113
+ * 于是静默改走直连、最终以"Codex 余额消失"的形式暴露,根因完全不可见。
114
+ */
115
+ export function codexProxyUrl(ctx, mod) {
116
+ const namespace = mod.OPENAI_CODEX_SETTINGS_NAMESPACE ?? "llm-openai-codex";
117
+ let settingsSvc;
118
+ try {
119
+ settingsSvc = ctx?.get?.("settings");
120
+ } catch {
121
+ settingsSvc = undefined;
122
+ }
123
+ // issue #21:原实现用 `settings.get()` 读该命名空间,而宿主 0.2.0 **移除了该方法**
124
+ // (同一处破坏在 issue #19 已修过另两个调用点,这一处因是可选链写法 `?.get?.(` 被漏掉)。
125
+ // 更要紧的是**语义**:读不到配置 ≠ 代理未启用。原实现把前者当作后者 → 返回 enabled:false
126
+ // → 插件静默改走直连 chatgpt.com → 连接超时 → 表现为"手机看不到 Codex 余额",
127
+ // 而配置本身(enableProxy:true + proxyUrl)一直好好的,用户完全看不出根因。
128
+ //
129
+ // 评审 WARNING 3 的补充:仅判断"读取方法存在"不够——`get()` 抛错、`describe()` 抛错、
130
+ // 或 describe 返回形状不合法时,宽松读取会把它们一律折叠成 undefined,再由 `?? {}`
131
+ // 伪装成"命名空间不存在"。故此处用**严格读取**,只有"读取成功且命名空间确实不存在"
132
+ // 才允许判定为"用户没开代理"。
133
+ const read = readSettingsSectionStrict(settingsSvc, namespace);
134
+ if (!read.ok) return { enabled: true, url: undefined, unreadable: true, reason: read.reason };
135
+ const settings = read.value ?? {};
136
+ try {
137
+ const resolved = typeof mod.resolveOpenAICodexSettings === "function"
138
+ ? mod.resolveOpenAICodexSettings(settings)
139
+ : settings;
140
+ const enabled = resolved?.enableProxy === true || settings?.enableProxy === true;
141
+ // 命名空间确实不存在 ⇒ 用户没开代理,走直连是正确行为(区别于上面的"读不了")
142
+ if (!enabled) return { enabled: false, url: undefined };
143
+ const url = typeof mod.resolveOpenAICodexProxyUrl === "function"
144
+ ? mod.resolveOpenAICodexProxyUrl(resolved)
145
+ : resolved?.proxyUrl;
146
+ return { enabled: true, url: typeof url === "string" && url.trim() !== "" ? url : undefined };
147
+ } catch {
148
+ return { enabled: true, url: undefined, unreadable: true, reason: "settings-resolve-threw" };
149
+ }
150
+ }
151
+
152
+ async function queryCodexUsage(ctx) {
153
+ let mod;
154
+ try {
155
+ mod = await loadCodexConnect();
156
+ } catch {
157
+ return { configured: false };
158
+ }
159
+ if (typeof mod?.OpenAICodexCredentialStore !== "function"
160
+ || typeof mod?.openAICodexAuthStatus !== "function"
161
+ || typeof mod?.readOpenAICodexRateLimits !== "function") return { configured: false };
162
+ let store;
163
+ let captured;
164
+ let proxyManager;
165
+ try {
166
+ store = new mod.OpenAICodexCredentialStore();
167
+ // 新版返回同一账户快照;旧版没有该方法时仍可读取额度,但账户标签降级为可选。
168
+ captured = typeof store.captureActiveAccount === "function" ? await store.captureActiveAccount() : store;
169
+ if (!captured) return { configured: false };
170
+ const status = await mod.openAICodexAuthStatus(captured);
171
+ if (status?.authenticated !== true) return { configured: false };
172
+ const proxy = codexProxyUrl(ctx, mod);
173
+ if (proxy.enabled && (!proxy.url || typeof mod.OpenAICodexProxyManager !== "function")) {
174
+ // v3.1.6(issue #21):**必须区分**「读不到宿主配置」与「用户没开代理」。
175
+ // 前者是插件与宿主的接口问题,后者是用户的选择;原实现把两者都归为 failed,
176
+ // 于是 Codex 余额整块消失而原因无法归因(见 failedReason 的两种措辞)。
177
+ return {
178
+ configured: true, failed: true, failedId: "codex",
179
+ failedReason: proxy.unreadable
180
+ ? "读不到宿主设置(settings 服务没有可用的读取方法),无法判断 Codex 代理配置"
181
+ : (proxy.url ? "宿主未提供代理管理器" : "代理已启用但未配置代理地址"),
182
+ };
183
+ }
184
+ proxyManager = proxy.enabled ? new mod.OpenAICodexProxyManager() : undefined;
185
+ const readUsage = () => mod.readOpenAICodexRateLimits(captured);
186
+ const usage = normalizeCodexUsage(proxyManager ? await proxyManager.run(proxy.url, readUsage) : await readUsage());
187
+ let active;
188
+ try {
189
+ const accounts = typeof captured.accounts === "function" ? await captured.accounts() : [];
190
+ active = Array.isArray(accounts) ? accounts.find((account) => account?.active === true) : undefined;
191
+ } catch {
192
+ // 账户标签是可选展示信息;额度投影成功时不因标签读取失败而隐藏来源。
193
+ }
194
+ return {
195
+ configured: true,
196
+ source: {
197
+ id: "codex",
198
+ title: "Codex",
199
+ kind: "quota",
200
+ ...usage,
201
+ ...(active && (active.displayName || active.maskedEmail) ? {
202
+ account: {
203
+ ...(typeof active.displayName === "string" && active.displayName !== "" ? { displayName: active.displayName } : {}),
204
+ ...(typeof active.maskedEmail === "string" && active.maskedEmail !== "" ? { maskedEmail: active.maskedEmail } : {}),
205
+ },
206
+ } : {}),
207
+ },
208
+ };
209
+ } catch (err) {
210
+ // v3.1.6(issue #21):失败原因要能对上号(此前只记 failed,用户无从判断是网络、
211
+ // 凭据还是插件读不到宿主配置)。detail 走脱敏。
212
+ return { configured: true, failed: true, failedId: "codex", failedReason: safeFailureReason(err) };
213
+ } finally {
214
+ try {
215
+ await proxyManager?.dispose?.();
216
+ } catch {
217
+ // 代理池释放失败不应掩盖已拿到的额度快照。
218
+ }
219
+ }
220
+ }
221
+
222
+ async function queryOpenCodeUsage(ctx) {
223
+ let profile;
224
+ try {
225
+ // issue #21:与 codexProxyUrl 同一种写法(可选链),同样受"0.2.0 移除 settings.get()"影响。
226
+ // 此处目前**碰巧仍有数据**(额度走的是凭据解析路径,profile 只用于取 apiKeyEnv),
227
+ // 但同一形式的读取必须一并改为跨代版本——否则换个宿主版本就会静默失效。
228
+ const settingsSvc = ctx?.get?.("settings");
229
+ const section = readSettingsSection(settingsSvc, "llm-pi-ai");
230
+ profile = section?.providers?.["opencode-go"];
231
+ } catch {
232
+ profile = undefined;
233
+ }
234
+ const key = await resolveOpenCodeCredential(ctx, profile?.apiKeyEnv);
235
+ if (!key) return { configured: false };
236
+ // 不接受设置页可配置的 baseURL,避免把套餐密钥发送到非官方/内网地址。
237
+ const url = "https://opencode.ai/zen/go/v1/usage";
238
+ try {
239
+ const response = await fetch(url, {
240
+ headers: { authorization: `Bearer ${key}`, accept: "application/json" },
241
+ signal: AbortSignal.timeout(15_000),
242
+ });
243
+ if (!response.ok) {
244
+ await response.body?.cancel();
245
+ return { configured: true, failed: true, failedId: "opencode-go", failedReason: `HTTP ${response.status}` };
246
+ }
247
+ const source = normalizeOpenCodeUsage(await response.json());
248
+ return { configured: true, source: { id: "opencode-go", title: "OpenCode Go", kind: "quota", ...source } };
249
+ } catch (err) {
250
+ return { configured: true, failed: true, failedId: "opencode-go", failedReason: safeFailureReason(err) };
251
+ }
252
+ }
253
+
254
+ export async function queryAccountUsage(ctx) {
255
+ const results = await Promise.all([
256
+ queryDeepSeekUsage(ctx),
257
+ queryCodexUsage(ctx),
258
+ queryOpenCodeUsage(ctx),
259
+ ]);
260
+ const sources = results.filter((result) => result?.source).map((result) => result.source);
261
+ const failures = results.filter((result) => result?.configured === true && result?.failed === true);
262
+ return {
263
+ ok: true,
264
+ fetchedAt: new Date().toISOString(),
265
+ sources,
266
+ availableCount: sources.length,
267
+ failedCount: failures.length,
268
+ // v3.1.6(issue #21):此前只给 failedCount。用户看到的是「Codex 整块消失」,
269
+ // 却无法判断是凭据没配、网络不通、还是插件读不到宿主配置——定位只能靠猜。
270
+ // 现在把**哪个来源失败、为什么失败**一并给出(无失败时省略该字段,保持响应稳定)。
271
+ ...(failures.length > 0 ? {
272
+ failures: failures.map((result) => ({
273
+ id: result.failedId ?? "unknown",
274
+ reason: result.failedReason ?? "未提供原因",
275
+ })),
276
+ } : {}),
277
+ };
278
+ }
@@ -0,0 +1,333 @@
1
+ /**
2
+ * HTTP/文本层的纯辅助:路径脱敏、请求头读取、截断、MIME、二维码地址排序、发送回执 TTL、服务端路径归一、问答校验、抓取失败归类。
3
+ * 从 lib/index.js 原样拆出(行为不变)。
4
+ */
5
+ import { extname } from "node:path";
6
+
7
+ /** 主机绝对路径脱敏(v3.1.5 S7):抹掉 POSIX 多段路径与 Windows 盘符路径。
8
+ * 宿主错误 message 常带工作区/会话/设置文件路径。此前只在服务端日志与推送里用过,
9
+ * 结果 `/files`、`/directories`、`rpcError` 等把主机绝对路径原样回给了客户端——
10
+ * 现在日志、HTTP 错误详情、推送正文统一走这里(原文只进服务端日志)。
11
+ * 刻意保留单段 `/foo`(如 URL 的路径段不会被整段吞掉)。 */
12
+ const REDACT_PATH_PATTERN = /(?:\/[A-Za-z0-9_.-]+){2,}|[A-Za-z]:\\[^\s"']*/g;
13
+
14
+ export function redactPathText(value) {
15
+ return String(value ?? "").replace(REDACT_PATH_PATTERN, "<redacted>");
16
+ }
17
+
18
+ /**
19
+ * 普通文件下载能力:Range / HEAD / ETag(v3.2.3)。
20
+ *
21
+ * App 用它决定能不能"只取前 256 KiB 预览"和"大文件断点续传";不存在该能力位时
22
+ * 自动退回整文件 GET(旧插件行为)。
23
+ */
24
+ export const FILE_RANGE_CAPABILITIES = {
25
+ version: 1,
26
+ supported: true,
27
+ };
28
+
29
+ /** 读请求头单值文本(防御数组/非字符串)。 */
30
+ export function requestHeaderText(req, name) {
31
+ const raw = req?.headers?.[name];
32
+ const value = Array.isArray(raw) ? raw[0] : raw;
33
+ return typeof value === "string" ? value : "";
34
+ }
35
+
36
+ /** 截断字符串到上限(超出加省略号),避免移动端流量/渲染膨胀。
37
+ * P2:截断提示本身计入上限——输出总长严格 ≤ max(对齐文档的"≤ N 字符"语义)。 */
38
+ export function clampText(text, max) {
39
+ text = text === undefined || text === null ? "" : String(text);
40
+ if (text.length <= max) return text;
41
+ const suffix = "\n…(已截断)";
42
+ const keep = max - suffix.length;
43
+ return keep > 0 ? `${text.slice(0, keep)}${suffix}` : text.slice(0, max);
44
+ }
45
+
46
+ /** v3.1.2:文件下载 MIME(扩展名映射,兜底 octet-stream)。 */
47
+ const FILE_MIME = {
48
+ ".txt": "text/plain; charset=utf-8", ".md": "text/markdown; charset=utf-8", ".json": "application/json",
49
+ ".pdf": "application/pdf", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
50
+ ".gif": "image/gif", ".webp": "image/webp", ".zip": "application/zip", ".gz": "application/gzip",
51
+ ".doc": "application/msword", ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
52
+ ".xls": "application/vnd.ms-excel", ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
53
+ ".csv": "text/csv; charset=utf-8", ".yaml": "text/yaml; charset=utf-8", ".yml": "text/yaml; charset=utf-8",
54
+ ".js": "text/javascript; charset=utf-8", ".ts": "text/plain; charset=utf-8", ".py": "text/plain; charset=utf-8",
55
+ ".html": "text/html; charset=utf-8", ".mp4": "video/mp4", ".apk": "application/vnd.android.package-archive",
56
+ };
57
+
58
+ export const fileMimeOf = (name) => FILE_MIME[extname(name).toLowerCase()] ?? "application/octet-stream";
59
+
60
+ /**
61
+ * 有界并发映射(保持入参顺序)。用于**不能**一次性扇出的上游读取:
62
+ * 逐个 `readTitleSnapshot` 在真实宿主上每次都会自带一轮全语料枚举,
63
+ * `Promise.all(ids)` 会让 N 个枚举同时开跑。
64
+ */
65
+ export const mapBounded = async (items, width, worker) => {
66
+ const list = [...items];
67
+ if (list.length === 0) return [];
68
+ const results = new Array(list.length);
69
+ let cursor = 0;
70
+ const run = async () => {
71
+ for (;;) {
72
+ const index = cursor;
73
+ cursor += 1;
74
+ if (index >= list.length) return;
75
+ results[index] = await worker(list[index], index);
76
+ }
77
+ };
78
+ // 评审 note 908:不能用 `Promise.all`——它**首拒即返回**,调用方(以及它背后的折叠串行门)
79
+ // 会在其余 worker 仍在清理时就被释放;重试随即再开一路,旧 3 路 + 新 4 路叠加实测
80
+ // maxActive=7,突破 ≤4 的读取宽度上限。改为等**全部** worker settle 之后再重抛原失败,
81
+ // 使"在途读取"真正受调用方生命周期约束。
82
+ const settled = await Promise.allSettled(Array.from({ length: Math.min(width, list.length) }, run));
83
+ const failed = settled.find((entry) => entry.status === "rejected");
84
+ if (failed) throw failed.reason;
85
+ return results;
86
+ };
87
+
88
+ // ── 宿主 API 代际探测(ADR 0017)────────────────────────────────────────────
89
+ // 宿主不为 API 声明契约版本,插件只能按**结构特征**探测当前是哪一代,而不是查版本号。
90
+ // 下列四处差异都在宿主 0.2.0 一并发生;各自用最贴近该处差异的结构特征判别,
91
+ // 是为了避免"用一个特征的版本号去推断另一个特征"这种脆弱做法。
92
+ // 判别必须是"服务存在但语义不同"也能识别的——这正是能力语义漂移的形态。
93
+
94
+ /**
95
+ * 二维码地址排序(issue #49)。
96
+ *
97
+ * 默认保持「局域网私有地址优先」:在家扫码必须给手机可达的局域网地址,组网地址
98
+ * (Tailscale CGNAT 100.64/10)排在其后,避免「桌面有 Tailscale、手机没登录 → 扫到黑洞」。
99
+ *
100
+ * 例外:**当前没有任何局域网私有地址**时,把 Tailscale 提到最前。这类机器(校园网 / 热点 /
101
+ * 只剩虚拟网卡)若不这样排,唯一可用的组网地址会被「其他」段压到后面,二维码首选变成不可达地址。
102
+ * 两种情形都按「手机能否直接到达」取最优,而不是按网卡枚举顺序。
103
+ *
104
+ * 排序:0 = 10./192.168.x;1 = 172.16-31;2 = 100.64/10;3 = 其他。
105
+ */
106
+ export const orderQrAddresses = (ips) => {
107
+ const rankOf = (ip) => {
108
+ const o = String(ip).split(".").map(Number);
109
+ if (o.length !== 4 || o.some((n) => !Number.isFinite(n))) return 3;
110
+ if (o[0] === 10 || (o[0] === 192 && o[1] === 168)) return 0;
111
+ if (o[0] === 172 && o[1] >= 16 && o[1] <= 31) return 1;
112
+ if (o[0] === 100 && o[1] >= 64 && o[1] <= 127) return 2;
113
+ return 3;
114
+ };
115
+ const hasLanPrivate = ips.some((ip) => {
116
+ const rank = rankOf(ip);
117
+ return rank === 0 || rank === 1;
118
+ });
119
+ // 没有局域网私有地址时,把 CGNAT 从 2 提到 0(其余保持原相对次序)
120
+ const adjusted = (ip) => (rankOf(ip) === 2 && !hasLanPrivate ? 0 : rankOf(ip));
121
+ return [...ips].sort((a, b) => adjusted(a) - adjusted(b));
122
+ };
123
+
124
+ /** v3.0.0(热修 07):回执过期判定(顶层纯函数,便于单测)——now 超过 at+ttl 即过期。 */
125
+ export function receiptExpired(at, now, ttl = 15 * 60 * 1000) {
126
+ return now - at > ttl;
127
+ }
128
+
129
+ /** v3.0.0(热修 08):回执**全量**过期/上限清理(顶层纯函数,可单测)——返回是否有删除。
130
+ * 语义对齐 receiptExpired:恰好 TTL 边界不算过期,仅超过才算;超上限按最旧淘汰。 */
131
+ export function pruneReceiptMap(receipts, now = Date.now(), ttl = 15 * 60 * 1000, max = 2000) {
132
+ let changed = false;
133
+ for (const [k, v] of receipts) {
134
+ if (now - v.at > ttl) { receipts.delete(k); changed = true; }
135
+ }
136
+ while (receipts.size > max) { receipts.delete(receipts.keys().next().value); changed = true; }
137
+ return changed;
138
+ }
139
+
140
+ /** v3.1.1(issue #5):把客户端传来的路径按目标平台归一化分隔符。
141
+ * 旧版移动端按 Windows 习惯用 `\` 拼路径(WSL/Linux 上把 `/home` 拼成 `/\home`,
142
+ * readdir 必然 ENOENT);服务端统一换成当前平台分隔符后浏览/建夹/建会话才能命中
143
+ * 真实目录。仅换分隔符:不展开 ..、不解析软链、不改其余字符。
144
+ * platform 参数仅用于单测固定平台;调用点一律用默认值。 */
145
+ export function normalizeServerPath(p, platform = process.platform) {
146
+ if (typeof p !== "string") return p;
147
+ return platform === "win32" ? p.replaceAll("/", "\\") : p.replaceAll("\\", "/");
148
+ }
149
+
150
+ /**
151
+ * v3.1.5(PR #11 P1):校验手机端提交的问询答案,不信任移动端 UI。
152
+ *
153
+ * 内核 `dsh-tool-ask-user` 直接展开答案字段(`selected: [...answer.selected]`,
154
+ * 见 @deepseek-ai/dsh-tool-ask-user/lib/index.js:107-111),`ctx.userQuestions.ask()`
155
+ * 本身不做任何形状校验(@deepseek-ai/dsh-user-questions/lib/index.js:69-78):
156
+ * `selected` 缺失/为 null 会在内核里抛 TypeError,选项未声明/一问多答则会把
157
+ * 模型收到伪造答案。故在插件边界逐条校验,非法一律 400 且保留 pending 可重试。
158
+ *
159
+ * @returns `{ ok: true }` 或 `{ ok: false, code, detail }`。
160
+ */
161
+ export function validateQuestionAnswers(questions, answers) {
162
+ if (!Array.isArray(questions) || questions.length === 0) {
163
+ return { ok: false, code: "question-answer-invalid", detail: "问询条目缺少 questions" };
164
+ }
165
+ if (!Array.isArray(answers) || answers.length !== questions.length) {
166
+ return { ok: false, code: "question-answer-invalid", detail: "每个问题必须恰好对应一个答案" };
167
+ }
168
+ const byId = new Map();
169
+ for (const answer of answers) {
170
+ // id 必须是自身属性且不重复(重复 id 会让"每问一答"变成一问多答)
171
+ if (!answer || typeof answer !== "object" || typeof answer.id !== "string" || byId.has(answer.id)) {
172
+ return { ok: false, code: "question-answer-invalid", detail: "答案 id 无效或重复" };
173
+ }
174
+ byId.set(answer.id, answer);
175
+ }
176
+ for (const question of questions) {
177
+ if (!question || typeof question.id !== "string") {
178
+ return { ok: false, code: "question-answer-invalid", detail: "问题 id 无效" };
179
+ }
180
+ const answer = byId.get(question.id);
181
+ if (!answer) return { ok: false, code: "question-answer-invalid", detail: `缺少问题 ${question.id} 的答案` };
182
+ // selected 必须是自身属性且为 string[]:不接受 null/undefined 兜底,
183
+ // 否则内核 `[...answer.selected]` 抛 TypeError(本函数的存在理由之一)
184
+ if (!Object.hasOwn(answer, "selected") || !Array.isArray(answer.selected)) {
185
+ return { ok: false, code: "question-answer-invalid", detail: `问题 ${question.id} 的 selected 无效` };
186
+ }
187
+ const selected = answer.selected;
188
+ let custom = "";
189
+ if (Object.hasOwn(answer, "custom")) {
190
+ if (typeof answer.custom !== "string") {
191
+ return { ok: false, code: "question-answer-invalid", detail: `问题 ${question.id} 的 custom 无效` };
192
+ }
193
+ custom = answer.custom;
194
+ }
195
+ if (selected.some((label) => typeof label !== "string")) {
196
+ return { ok: false, code: "question-answer-invalid", detail: `问题 ${question.id} 的 selected 无效` };
197
+ }
198
+ if (new Set(selected).size !== selected.length) {
199
+ return { ok: false, code: "question-answer-invalid", detail: `问题 ${question.id} 的选项重复` };
200
+ }
201
+ const labels = new Set((Array.isArray(question.options) ? question.options : [])
202
+ .filter((option) => option && typeof option.label === "string")
203
+ .map((option) => option.label));
204
+ if (selected.some((label) => !labels.has(label))) {
205
+ return { ok: false, code: "question-answer-invalid", detail: `问题 ${question.id} 含未声明选项` };
206
+ }
207
+ if (!question.multiSelect && selected.length > 1) {
208
+ return { ok: false, code: "question-answer-invalid", detail: `问题 ${question.id} 只能单选` };
209
+ }
210
+ if (!question.multiSelect && custom.trim() !== "" && selected.length > 0) {
211
+ return { ok: false, code: "question-answer-invalid", detail: `问题 ${question.id} 不能同时提交选项和自定义答案` };
212
+ }
213
+ if (selected.length === 0 && custom.trim() === "") {
214
+ return { ok: false, code: "question-answer-invalid", detail: `问题 ${question.id} 未回答` };
215
+ }
216
+ }
217
+ return { ok: true };
218
+ }
219
+
220
+ /**
221
+ * 把网络/请求失败归类为**稳定错误码**(issue #21 评审 BLOCKING 1)。
222
+ *
223
+ * 为什么不回传异常原文:凭据里若含内嵌 CR/LF,原生 fetch 的 Headers 校验会抛出
224
+ * `Headers.append: "Bearer sk-…\n…" is an invalid header value.` —— **消息里带完整密钥**,
225
+ * 而 `redactPathText` 只脱敏主机路径、不脱敏凭据,所以"脱敏后回传异常消息"并不安全。
226
+ * 移动端只需要知道失败**类别**;细节留在服务端日志(那里本就有权限边界)。
227
+ */
228
+ export const classifyFetchFailure = (err) => {
229
+ const name = typeof err?.name === "string" ? err.name : "";
230
+ const code = typeof err?.code === "string" ? err.code : (typeof err?.cause?.code === "string" ? err.cause.code : "");
231
+ if (name === "TimeoutError" || name === "AbortError") return "timeout";
232
+ if (code === "UND_ERR_CONNECT_TIMEOUT") return "connect-timeout";
233
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return "dns";
234
+ if (code === "ECONNREFUSED") return "connection-refused";
235
+ if (code === "ECONNRESET") return "connection-reset";
236
+ if (code === "UND_ERR_SOCKET") return "socket-error";
237
+ // issue #30 评审 WARNING 4:宿主模块已经给出**结构化**失败——拿到 HTTP 响应就**不是**网络不可达,
238
+ // 归到 unreachable 会让用户排查错方向(限流/登录失效去查网络)。只接受 allow-list 的稳定 code
239
+ // 与**校验过的数值** status,仍然不接收任何异常原文。
240
+ if (code === "OPENAI_CODEX_REAUTH_REQUIRED") return "reauth-required";
241
+ const status = Number.isInteger(err?.status)
242
+ ? err.status
243
+ : (Number.isInteger(err?.cause?.status) ? err.cause.status : undefined);
244
+ if (status !== undefined && status >= 400 && status <= 599) {
245
+ return status === 429 ? "rate-limited" : "http-error";
246
+ }
247
+ // TypeError 覆盖 Headers/URL 的本地校验失败——**凭据形态问题会落在这里**,
248
+ // 因此这一类绝不能附带原文。
249
+ if (name === "TypeError") return "invalid-request";
250
+ return "unreachable";
251
+ };
252
+
253
+ /** 错误码 → 固定摘要(allow-list,逐字写死,永不包含异常原文或凭据)。 */
254
+ const FAILURE_SUMMARY = {
255
+ timeout: "请求超时",
256
+ "connect-timeout": "连接超时",
257
+ dns: "域名解析失败",
258
+ "connection-refused": "连接被拒绝",
259
+ "connection-reset": "连接被重置",
260
+ "socket-error": "连接异常中断",
261
+ "invalid-request": "请求构造被拒(可能是凭据或地址形态问题)",
262
+ // 结构化失败(issue #30 评审 WARNING 4):已收到 HTTP 响应 / 宿主明确要求重新登录
263
+ "reauth-required": "需重新登录",
264
+ "rate-limited": "请求被限流",
265
+ "http-error": "服务端返回错误",
266
+ unreachable: "网络不可达",
267
+ };
268
+
269
+ /** 供移动端展示的安全失败摘要:稳定错误码 + 固定文案,不含任何异常原文。 */
270
+ export const safeFailureReason = (err) => {
271
+ const code = classifyFetchFailure(err);
272
+ return `${code}(${FAILURE_SUMMARY[code] ?? FAILURE_SUMMARY.unreachable})`;
273
+ };
274
+
275
+ /**
276
+ * 请求级取消:客户端断开(超时 / 关页面 / 切网络)时,停止服务端仍在进行的扫描。
277
+ *
278
+ * **为什么需要**(issue #20):`/sessions` 的代价与历史语料规模成正比——实测单次请求
279
+ * 72 秒、约 95 CPU-秒、读取 1.24 GB,而客户端通常三十秒就超时走人了。宿主**本来就支持
280
+ * 取消**(`listSessions(signal?)`、`readTitleSnapshots(ids, signal?)`,持久化层还会
281
+ * `signal.throwIfAborted()`),插件此前一处都没传,于是断开的请求照样跑完:
282
+ * 实测**约 86% 的算力与 I/O 花在已经离开的客户端上**,并发重试时还会互相叠加。
283
+ *
284
+ * **为什么在 `res` 的 close 上判 `writableEnded`**:正常完成的响应同样会触发 close,
285
+ * 不判就会把每一次成功响应都当成取消。
286
+ *
287
+ * 监听器刻意**不显式移除**:`res` 是每请求一个的对象,请求结束即随对象回收,不存在
288
+ * 跨请求累积;而在响应之后再触发 abort 也没有任何等待者,是无害的空操作。
289
+ */
290
+ export const requestAbort = (res) => {
291
+ const ac = new AbortController();
292
+ res.once("close", () => {
293
+ if (!res.writableEnded) ac.abort();
294
+ });
295
+ return ac.signal;
296
+ };
297
+
298
+ /** 插件主体。 */
299
+
300
+ /**
301
+ * 解析 `Range: bytes=...`(v3.2.3)。
302
+ *
303
+ * 只支持单区间(多区间用不上,还容易被拿来放大响应);越界/格式错返回
304
+ * `{ invalid: true }`,调用方回 416 并带 `Content-Range: bytes * /size`。
305
+ */
306
+ export const parseByteRange = (value, size) => {
307
+ const text = String(value ?? "").trim();
308
+ if (text === "") return null;
309
+ const match = /^bytes=(\d*)-(\d*)$/.exec(text);
310
+ if (!match) return { invalid: true };
311
+ const [, startText, endText] = match;
312
+ if (startText === "" && endText === "") return { invalid: true };
313
+ if (startText === "") {
314
+ const suffix = Number(endText);
315
+ if (!Number.isSafeInteger(suffix) || suffix <= 0) return { invalid: true };
316
+ return { start: Math.max(0, size - suffix), end: size - 1 };
317
+ }
318
+ const start = Number(startText);
319
+ if (!Number.isSafeInteger(start) || start >= size) return { invalid: true };
320
+ const end = endText === "" ? size - 1 : Number(endText);
321
+ if (!Number.isSafeInteger(end) || end < start) return { invalid: true };
322
+ return { start, end: Math.min(end, size - 1) };
323
+ };
324
+ /** `If-None-Match` 是否命中当前 ETag(支持 `*` 与逗号列表)。 */
325
+ export const ifNoneMatch = (req, etag) => {
326
+ if (!etag) return false;
327
+ const raw = requestHeaderText(req, "if-none-match");
328
+ if (raw === "") return false;
329
+ return raw
330
+ .split(",")
331
+ .map((part) => part.trim())
332
+ .some((part) => part === "*" || part === etag);
333
+ };