dsh-mobile-plugin 0.5.75 → 0.5.77

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/relay/core.js CHANGED
@@ -93,7 +93,10 @@ function loadState() {
93
93
  // **老文件里没有这一格**:默认值那个空数组会顶上来,把「只有 relayUrl 一条」判成
94
94
  // 「明确没有中转」,地址当场被清空。所以先把这一格撤掉,交给收敛函数从 relayUrl 生出来。
95
95
  if (!Object.prototype.hasOwnProperty.call(raw, 'relayUrls')) delete merged.relayUrls;
96
- return normalizeRelayAddresses(merged);
96
+ const state = normalizeRelayAddresses(merged);
97
+ // 老设备补齐:早先只写了第一台内置公用中转的,读盘时就补成整份(见 expandDefaultPublicRelays)。
98
+ expandDefaultPublicRelays(state);
99
+ return state;
97
100
  } catch {
98
101
  const state = defaultState();
99
102
  saveState(state);
@@ -147,12 +150,21 @@ function ensureHistoryKey(state) {
147
150
  function normalizeRelayUrl(relayUrl) {
148
151
  return String(relayUrl || '').trim().replace(/\/+$/, '');
149
152
  }
153
+ /**
154
+ * 一台电脑最多认多少条中转地址。**这是安全上限,不是功能上限**:正常场景(内置公用 3 条、
155
+ * 按地区下发的就近短清单 5~8 条、自建几条)远低于它。挡的是「有人往配置/落盘里塞进成千上万条」
156
+ * ——那会让探活、心跳、隧道签名、总控上报全部随条目数线性膨胀,把电脑压垮(见 2026-11-19 讨论)。
157
+ * 超出部分按原顺序截断,不报错(与「脏值就地丢弃」同一条契约口径)。
158
+ */
159
+ const MAX_RELAY_ADDRESSES = 64;
150
160
  /**
151
161
  * 一组中转地址的清洗:丢空串、去重、丢弃不以 http(s) 开头的,其余按原顺序留着。
152
162
  *
153
163
  * 这三条就是契约里的「读到的列表不满足就地丢弃、不报错」(docs/relay-multi-address.md)。
154
164
  * 每一条都过 `normalizeRelayUrl` 的规范形态,否则列表首项与 `relayUrl` 会差一个尾斜杠,
155
165
  * 那条「`relayUrls[0]` 恒等于 `relayUrl`」的不变式就不成立了。
166
+ *
167
+ * 末尾按 `MAX_RELAY_ADDRESSES` 封顶:这台电脑只留前 64 条有效地址。
156
168
  */
157
169
  function normalizeRelayUrlList(list) {
158
170
  if (!Array.isArray(list)) return [];
@@ -163,6 +175,7 @@ function normalizeRelayUrlList(list) {
163
175
  if (!/^https?:\/\/[^\s/]+/i.test(url)) continue;
164
176
  if (out.includes(url)) continue;
165
177
  out.push(url);
178
+ if (out.length >= MAX_RELAY_ADDRESSES) break;
166
179
  }
167
180
  return out;
168
181
  }
@@ -248,12 +261,18 @@ function signLanToken(secret, instanceId, ttlSec = MOBILE_TOKEN_TTL_SEC) { retur
248
261
  function verifyLanToken(secret, token, instanceId) { return sharedToken.verifyLanToken(secret, token, instanceId); }
249
262
 
250
263
  /**
251
- * 公用中转的入口 host。**必须与面板 `React/src/lib/links.ts` 的 `PUBLIC_RELAYS`、
264
+ * 内置公用中转的完整入口清单。**必须与面板 `React/src/lib/links.ts` 的 `PUBLIC_RELAYS`、
252
265
  * App `services/viewmodels/public-relay.ts` 的 `PUBLIC_RELAY_URLS` 保持一致** —— 三处各有一份,
253
- * 加一台公用中转要三处一起补,少补一处那台上的设备就会被漏判。按 host 比:协议、默认端口、
254
- * 尾斜杠的差异都不影响它是不是公用。
266
+ * 加一台公用中转要三处一起补,少补一处那台上的设备就会被漏判。
267
+ *
268
+ * 这里除了拿来判「是不是公用」,还是「老设备只配了第一台时补齐成整份」的地址来源(见
269
+ * `expandDefaultPublicRelays`):宿主必须自己握着这几条 URL,否则补不出另外两台。
255
270
  */
256
- const PUBLIC_RELAY_HOSTS = new Set(['ai-hub-de-1.wnluo.com', 'dsh.iouf.cn', 'dsh.yfyidc.cn']);
271
+ const PUBLIC_RELAY_URLS = ['https://ai-hub-de-1.wnluo.com', 'https://dsh.iouf.cn', 'https://dsh.yfyidc.cn'];
272
+ /** 按 host 比:协议、默认端口、尾斜杠的差异都不影响它是不是公用。 */
273
+ const PUBLIC_RELAY_HOSTS = new Set(PUBLIC_RELAY_URLS.map((url) => {
274
+ try { return new URL(url).host.toLowerCase(); } catch { return ''; }
275
+ }).filter(Boolean));
257
276
  function isPublicRelayUrl(url) {
258
277
  try {
259
278
  return PUBLIC_RELAY_HOSTS.has(new URL(String(url).trim()).host.toLowerCase());
@@ -297,8 +316,41 @@ function stripPublicRelay(next) {
297
316
  return true;
298
317
  }
299
318
 
319
+ /**
320
+ * 老设备补齐:这台如果**只用公用中转、且只配了第一台**(早先引导只写 `PUBLIC_RELAY_URL` 那一台),
321
+ * 读盘时就补成整份内置清单,让电脑能选/失败切换到另外两台(2026-11-19 用户口径:要把流量自动
322
+ * 分到别人维护的那两台上)。
323
+ *
324
+ * 只在三个条件同时成立时动(就地改 state,返回有没有改):
325
+ * - `relayUrls` 非空、且**每一条都是内置公用中转**(有自建中转就不归这管,自建是我们的还是别人的由用户定);
326
+ * - 不是「配了公网自建而强制停用」的状态(`publicRelayBlocked`:有手填直连 / TCP 就不补);
327
+ * - 确实缺着内置清单里的某几台(缺才补,已经齐了就一字不动)。
328
+ * 补齐时保留原有顺序在前(现有的主用不被挤下去),缺的按内置清单顺序追加在后面;`relayUrl` 恒为首项。
329
+ * **不碰任何非公用地址**。
330
+ */
331
+ function expandDefaultPublicRelays(state) {
332
+ if (!state || typeof state !== 'object') return false;
333
+ const urls = relayAddressesOf(state).relayUrls;
334
+ if (!urls.length) return false;
335
+ if (!urls.every((url) => isPublicRelayUrl(url))) return false;
336
+ if (publicRelayBlocked(state)) return false;
337
+ const hostOf = (url) => { try { return new URL(url).host.toLowerCase(); } catch { return ''; } };
338
+ const presentHosts = new Set(urls.map(hostOf).filter(Boolean));
339
+ const next = [...urls];
340
+ for (const url of PUBLIC_RELAY_URLS) {
341
+ const host = hostOf(url);
342
+ if (!host || presentHosts.has(host)) continue;
343
+ presentHosts.add(host);
344
+ next.push(url);
345
+ }
346
+ if (next.length === urls.length) return false;
347
+ state.relayUrls = next;
348
+ state.relayUrl = next[0];
349
+ return true;
350
+ }
351
+
300
352
  module.exports = {
301
353
  STATE_FILE, MOBILE_TOKEN_TTL_SEC, MOBILE_BEARER_TTL_SEC, defaultState, loadState, saveState, rotatePairing, genInstanceId, genPairingCode, genPairingTicket, genHistoryKey, ensureHistoryKey,
302
354
  tunnelWsUrl, normalizeRelayUrl, normalizeRelayUrlList, normalizeRelayAddresses, relayAddressesOf, applyRelayAddressPatch, signLanToken, verifyLanToken,
303
- isPublicRelayUrl, publicRelayBlocked, stripPublicRelay,
355
+ isPublicRelayUrl, publicRelayBlocked, stripPublicRelay, expandDefaultPublicRelays, PUBLIC_RELAY_URLS, MAX_RELAY_ADDRESSES,
304
356
  };
@@ -0,0 +1,86 @@
1
+ 'use strict'
2
+ // 公用中转「电脑决定」的延迟探测:worker 连中转前先量一遍各候选的 /healthz 延迟,
3
+ // 把最快的那台排在前面再按序连(失败仍按现有逻辑顺延到下一台)。
4
+ //
5
+ // 两件事分开:`orderByLatency` 是纯函数(只排顺序、不碰网络),`probeRelayHealth` 是薄探测
6
+ // (发一次 GET、量到响应为止、超时或报错返回 null)。探测结果交给排序函数,两者互不依赖。
7
+
8
+ const http = require('node:http')
9
+ const https = require('node:https')
10
+
11
+ /**
12
+ * 按实测延迟给候选地址排序:量到延迟的按升序在前,不可达 / 没量到的排后面。
13
+ *
14
+ * 不可达那一段保持它们原来在 `urls` 里的相对顺序(稳定),所以探测全挂时这里退化成原序。
15
+ * 只读入参、返回新数组,不改 `urls`。
16
+ *
17
+ * @param {string[]} urls 候选地址,原序
18
+ * @param {Map<string, number|null>|Object<string, number|null>} latencyByUrl URL→延迟毫秒,
19
+ * null / 缺失 = 不可达或未测到
20
+ * @returns {string[]} 新数组
21
+ */
22
+ function orderByLatency(urls, latencyByUrl) {
23
+ const readLatency = (url) => {
24
+ if (latencyByUrl instanceof Map) return latencyByUrl.get(url)
25
+ return latencyByUrl ? latencyByUrl[url] : undefined
26
+ }
27
+ const reachable = []
28
+ const unreachable = []
29
+ for (const url of urls) {
30
+ const latency = readLatency(url)
31
+ if (typeof latency === 'number' && Number.isFinite(latency)) reachable.push({ url, latency })
32
+ else unreachable.push(url)
33
+ }
34
+ // 数组的 sort 是稳定排序:延迟相同的几条保持原相对顺序。
35
+ reachable.sort((a, b) => a.latency - b.latency)
36
+ return [...reachable.map((item) => item.url), ...unreachable]
37
+ }
38
+
39
+ /**
40
+ * 对 `url + '/healthz'` 发一次 GET,量出从发起到拿到响应(任意状态码都算)的毫秒数。
41
+ *
42
+ * 超时或报错返回 null(= 这条当期不可达)。按 URL 协议选 http / https,用 `req.setTimeout`
43
+ * 起超时后 `destroy`,不走全局 fetch。
44
+ *
45
+ * @param {string} url 中转地址
46
+ * @param {{ timeoutMs?: number }} [options] 超时毫秒,默认 1500
47
+ * @returns {Promise<number|null>} 延迟毫秒,或 null
48
+ */
49
+ function probeRelayHealth(url, options = {}) {
50
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 1500
51
+ return new Promise((resolve) => {
52
+ let healthUrl
53
+ try {
54
+ healthUrl = new URL(`${String(url).replace(/\/+$/, '')}/healthz`)
55
+ } catch {
56
+ resolve(null)
57
+ return
58
+ }
59
+ const client = healthUrl.protocol === 'https:' ? https : http
60
+ const startedAt = Date.now()
61
+ let settled = false
62
+ const finish = (value) => {
63
+ if (settled) return
64
+ settled = true
65
+ resolve(value)
66
+ }
67
+ let req
68
+ try {
69
+ // agent:false:一次性连接,探完就关,别把 keep-alive 的 socket 留在进程里。
70
+ req = client.get(healthUrl, { agent: false }, (res) => {
71
+ res.resume()
72
+ finish(Date.now() - startedAt)
73
+ })
74
+ } catch {
75
+ finish(null)
76
+ return
77
+ }
78
+ req.on('error', () => finish(null))
79
+ req.setTimeout(timeoutMs, () => {
80
+ finish(null)
81
+ req.destroy()
82
+ })
83
+ })
84
+ }
85
+
86
+ module.exports = { orderByLatency, probeRelayHealth }
@@ -79,4 +79,34 @@ function credentialCandidates(headers) {
79
79
  return out;
80
80
  }
81
81
 
82
- module.exports = { snapshotAuthorized, credentialCandidates };
82
+ /**
83
+ * 与 `snapshotAuthorized` 同口径,但把**命中的那条记录**一并取出来。
84
+ *
85
+ * 存在只为一件事:判「这枚凭据是不是按协议 v2 配的」。绑了 `deviceKey` 的凭据说明设备
86
+ * 当初走的是逐请求信封,它的高频读一旦被中转删掉 `x-dsh-proto` 头就会被当成老客户端,
87
+ * 而快照捷径**不封信封**——那样列表 / 工作区就会以明文经中转送出去(主进程那条
88
+ * `e2ee-required` 守不到捷径)。调用方拿到 `deviceKey` 就回源,交给主进程如实驳回。
89
+ *
90
+ * 只回本机记录;走旧无状态令牌兜底的(升级前老 App / 中转签发)没有记录,返回 null——
91
+ * 那种凭据本来就不是 v2 绑定,不触发降级拦截。
92
+ *
93
+ * @param {object} headers 请求头(原始大小写都行)
94
+ * @param {{ lookup?: (presented: string) => object|null }} deps
95
+ * @returns {object|null} 命中且有效(未吊销 / 未过期)的本机凭据记录,否则 null
96
+ */
97
+ function snapshotAuthRecord(headers, deps = {}) {
98
+ const { lookup } = deps;
99
+ const candidates = credentialCandidates(headers);
100
+ if (!candidates.length) return null;
101
+ const now = Date.now();
102
+ for (const presented of candidates) {
103
+ const known = typeof lookup === 'function' ? lookup(presented) : null;
104
+ if (!known) continue;
105
+ if (known.revokedAt) return null;
106
+ if (known.expiresAt && known.expiresAt <= now) return null;
107
+ return known;
108
+ }
109
+ return null;
110
+ }
111
+
112
+ module.exports = { snapshotAuthorized, snapshotAuthRecord, credentialCandidates };
@@ -328,6 +328,8 @@ function registerMobileRoutes(deps) {
328
328
  rotatePairing,
329
329
  // 协议 v2 的配对封包里要下发实例历史密钥(HK)。取值器惰性生成并落盘。
330
330
  getHistoryKey,
331
+ // 配对回包顺手带上总控地址与令牌:补「配过但没连过一次」的盲区(见 mobile/pairing.js)。
332
+ getControl,
331
333
  log: (...args) => console.warn('[dsh-mobile-plugin] [pair]', ...args),
332
334
  }),
333
335
  })
@@ -4,6 +4,7 @@ import path from 'node:path'
4
4
  import { dshHome } from '../shared/paths.js'
5
5
  import { compareVersion, generationModulesError } from './manager.js'
6
6
  import { movePath, readManifest, sha256Hex, unpackTarGz, verifyManifest } from './ota-package.js'
7
+ import { verifyOtaSignature, otaPublicKeyPem } from './ota-signing.js'
7
8
  /**
8
9
  * OTA 包落在哪。
9
10
  *
@@ -118,7 +119,7 @@ export function snapshotGeneration(sourceDir, version) {
118
119
  return { created: false, error: String((error && error.message) || error) }
119
120
  }
120
121
  }
121
- export function createDeviceOta({ fetchImpl = fetch, installed = () => null, platform = PLATFORM, channel = CHANNEL, runtime = null } = {}) {
122
+ export function createDeviceOta({ fetchImpl = fetch, installed = () => null, platform = PLATFORM, channel = CHANNEL, runtime = null, publicKeyPem = otaPublicKeyPem() } = {}) {
122
123
  async function reconcileOfficial() {
123
124
  const active = runtime?.status()
124
125
  const officialVersion = installed()
@@ -162,7 +163,7 @@ export function createDeviceOta({ fetchImpl = fetch, installed = () => null, pla
162
163
  const absorbed = Boolean(validVersion(officialVersion) && newest && compareVersion(officialVersion, newest) >= 0 && runtime?.status()?.source !== 'ota')
163
164
  // 中转没给出合法 sha256 时这里归一成 null,apply 会据此**拒绝安装**(见那里的判据),
164
165
  // 绝不能让「没有哈希」被当成「不必校验」。
165
- return { available: Boolean(newest && !absorbed && compareVersion(newest, installedVersion || '0.0.0') > 0), version: newest, platform: release.platform || platform, channel: release.channel || channel, installedVersion, otaVersion: ota?.version ?? null, officialVersion, absorbed, packageUrl: release.packageUrl, sha256: typeof release.sha256 === 'string' && /^[0-9a-f]{64}$/i.test(release.sha256) ? release.sha256.toLowerCase() : null }
166
+ return { available: Boolean(newest && !absorbed && compareVersion(newest, installedVersion || '0.0.0') > 0), version: newest, platform: release.platform || platform, channel: release.channel || channel, installedVersion, otaVersion: ota?.version ?? null, officialVersion, absorbed, packageUrl: release.packageUrl, sha256: typeof release.sha256 === 'string' && /^[0-9a-f]{64}$/i.test(release.sha256) ? release.sha256.toLowerCase() : null, signature: typeof release.signature === 'string' ? release.signature : null }
166
167
  }
167
168
  async function apply() {
168
169
  const info = await check()
@@ -171,6 +172,16 @@ export function createDeviceOta({ fetchImpl = fetch, installed = () => null, pla
171
172
  // 没有合法 sha256 就等于完整性校验整段被跳过:从旧库升级上来的记录天然是空 sha,
172
173
  // 这种包一律不装 —— 宁可装不上,也不装一份验不了的包。
173
174
  if (!info.sha256) throw new Error('OTA 包缺少有效的 sha256,拒绝安装')
175
+ // 先验签:中转只转发、没有离线私钥就伪造不出签名。字段真实之后,再靠 sha256 校验下载
176
+ // 内容没被换过。两步任一不过都不装——「没签名」绝不等于「不必校验」。
177
+ verifyOtaSignature({
178
+ version: info.version,
179
+ platform: info.platform,
180
+ channel: info.channel,
181
+ sha256: info.sha256,
182
+ packageUrl: info.packageUrl,
183
+ signature: info.signature,
184
+ }, publicKeyPem)
174
185
  // 暂存目录**建在目标根里面**,不是系统临时目录:最后一步要 rename 到 `<root>/<version>`,
175
186
  // 跨盘的 rename 在 Windows 上直接 EXDEV(系统临时目录常在 C:,而 profile 可能在别的盘)。
176
187
  fs.mkdirSync(ROOT(), { recursive: true })
@@ -0,0 +1,7 @@
1
+ /**
2
+ * 桌面完整包 OTA 的内置签名公钥(Ed25519,SPKI PEM)。
3
+ *
4
+ * 私钥离线保管、不在这里;换发布方就换这一份,或用环境变量 DSH_OTA_PUBLIC_KEY_PEM 覆盖。
5
+ * 公开公钥不涉及泄密,随包分发是正常的。
6
+ */
7
+ export const OTA_PUBLIC_KEY_PEM = "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAKyPrnI61/wQkqWMfLAZCbPMdiYs7zQ5nhCg/RMltE/w=\n-----END PUBLIC KEY-----"
@@ -0,0 +1,76 @@
1
+ /**
2
+ * 桌面完整包 OTA 的签名校验。
3
+ *
4
+ * 现状(被审阅点名的那个洞):中转下发的 sha256 与包内清单都来自**同一台发布服务器**,
5
+ * 攻击者拿住那台机器就能把包和「用来证明包没被改」的哈希一起换掉——等于没有校验。这里
6
+ * 用 Ed25519 离线签名补上「来源真实」那一半:发布方在**离线**环境用私钥对「版本 / 平台 /
7
+ * 通道 / sha256 / 下载地址」这组字段签名,客户端内置**公钥**验签。中转只能转发,没有私钥
8
+ * 就伪造不出签名,也就推不了带毒的包。
9
+ *
10
+ * 边界:签名只证明「这组字段由私钥持有者发布」,不加密内容;内容完整性仍由 sha256 钉住。
11
+ * 两者一道:先验签(字段真实)→ 再按 sha256 校验下载内容(内容未改)。
12
+ *
13
+ * 私钥绝不进仓库、绝不与发布服务器同机(否则服务器被黑连签名一起伪造)。
14
+ */
15
+
16
+ import crypto from 'node:crypto'
17
+ import { OTA_PUBLIC_KEY_PEM } from './ota-public-key.js'
18
+
19
+ /** 签名字段集合的版本前缀,改字段就改它,免得新旧签法互相误认。 */
20
+ const SIGNING_DOMAIN = 'dsh-ota-v1'
21
+
22
+ /**
23
+ * 把要签的字段规范成一个稳定字符串。发布脚本与客户端**必须**用同一份,签出来才对得上。
24
+ *
25
+ * @param {{version:string, platform:string, channel:string, sha256:string, packageUrl:string}} release
26
+ * @returns {string}
27
+ */
28
+ export function otaSignaturePayload(release) {
29
+ return [
30
+ SIGNING_DOMAIN,
31
+ String(release.version ?? ''),
32
+ String(release.platform ?? ''),
33
+ String(release.channel ?? ''),
34
+ String(release.sha256 ?? ''),
35
+ String(release.packageUrl ?? ''),
36
+ ].join('\n')
37
+ }
38
+
39
+ /**
40
+ * 内置的 OTA 签名公钥。可用 `DSH_OTA_PUBLIC_KEY_PEM` 覆盖(自建发布方换自己的公钥)。
41
+ * 读不到就返回空串——调用方据此拒绝安装(没有公钥等于验不了签)。
42
+ *
43
+ * @returns {string}
44
+ */
45
+ export function otaPublicKeyPem() {
46
+ const override = process.env.DSH_OTA_PUBLIC_KEY_PEM
47
+ if (typeof override === 'string' && override.trim()) return override
48
+ return OTA_PUBLIC_KEY_PEM
49
+ }
50
+
51
+ /**
52
+ * 校验一条 OTA 发布记录的签名。任何一项不满足都抛错——绝不「没签名就当不校验」。
53
+ *
54
+ * @param {object} release 含 version / platform / channel / sha256 / packageUrl / signature
55
+ * @param {string} [publicKeyPem] 公钥 PEM;缺省用内置 / 环境变量
56
+ * @returns {true}
57
+ */
58
+ export function verifyOtaSignature(release, publicKeyPem = otaPublicKeyPem()) {
59
+ const signature = release && typeof release.signature === 'string' ? release.signature.trim() : ''
60
+ if (!signature) throw new Error('OTA 包缺少签名,拒绝安装')
61
+ if (!publicKeyPem) throw new Error('未配置 OTA 签名公钥,拒绝安装')
62
+ let key
63
+ try {
64
+ key = crypto.createPublicKey(publicKeyPem)
65
+ } catch {
66
+ throw new Error('OTA 签名公钥无法解析,拒绝安装')
67
+ }
68
+ let ok = false
69
+ try {
70
+ ok = crypto.verify(null, Buffer.from(otaSignaturePayload(release), 'utf8'), key, Buffer.from(signature, 'base64'))
71
+ } catch {
72
+ ok = false
73
+ }
74
+ if (!ok) throw new Error('OTA 包签名校验失败,拒绝安装')
75
+ return true
76
+ }
@@ -73,7 +73,7 @@ function installedPackageDirSafe() {
73
73
  */
74
74
  export function shellFingerprint(pkgDir) {
75
75
  if (!pkgDir) return null
76
- const files = ['lib/index.js', 'lib/shell/runtime.js', 'lib/shell/manager.js', 'lib/shell/updater.js', 'lib/shell/device-ota.js', 'lib/shell/ota-package.js', 'lib/shell/half-route.js', 'lib/shell/half-view.js', 'lib/shell/self-check-after-swap.js']
76
+ const files = ['lib/index.js', 'lib/shell/runtime.js', 'lib/shell/manager.js', 'lib/shell/updater.js', 'lib/shell/device-ota.js', 'lib/shell/ota-package.js', 'lib/shell/ota-signing.js', 'lib/shell/ota-public-key.js', 'lib/shell/half-route.js', 'lib/shell/half-view.js', 'lib/shell/self-check-after-swap.js']
77
77
  const hash = createHash('sha256')
78
78
  let seen = 0
79
79
  for (const rel of files) {
@@ -16,8 +16,8 @@
16
16
  * 3. 请求体一律先量后读:`/configure` 与镜像帧都有字节上限,超限立刻 413。
17
17
  * 4. 换中转地址不是「拆了重建」:先在旧隧道上登记迁移,再建新隧道,注册不上要撤销
18
18
  * (见 lib/relay/migrate.js)。这条顺序是「填错地址就把自己锁在外面」的唯一解。
19
- * 5. 启动与重连按 `relayUrls` 的顺序**依次试**,第一条注册成功的当主用,全不通再从第一条
20
- * 重来;换成功只把它提到队首、报给宿主写回,**不发 migrate 帧**(自动换发生在旧地址已经
19
+ * 5. 启动与重连先按最近实测延迟把候选排成「最快优先」,再**依次试**,第一条注册成功的当主用,
20
+ * 全不通再从第一条重来;换成功只把它提到队首、报给宿主写回,**不发 migrate 帧**(自动换发生在旧地址已经
21
21
  * 连不上的时刻,旧中转上那台机器的隧道早就断了,没人需要被指路)。
22
22
  */
23
23
 
@@ -29,9 +29,10 @@ const { createLanProxy } = require('./relay/lan-proxy.js')
29
29
  const { createLanDiscovery, bindLanEndpoint } = require('./relay/lan-discovery.cjs')
30
30
  const { lanUrls } = require('./relay/lan-network.cjs')
31
31
  const core = require('./relay/core.js')
32
+ const { orderByLatency, probeRelayHealth } = require('./relay/relay-probe.js')
32
33
  const { createReconnectScheduler } = require('./reconnect-scheduler.cjs')
33
34
  const { isMirrorSnapshotFresh } = require('./mirror-snapshot.cjs')
34
- const { snapshotAuthorized } = require('./relay/snapshot-auth.js')
35
+ const { snapshotAuthorized, snapshotAuthRecord } = require('./relay/snapshot-auth.js')
35
36
  // 凭据库在这个进程里**只读**(§3.7):写盘只有宿主主进程一家。签发与吊销都经 IPC 交给它,
36
37
  // 本地这份按文件指纹重载 —— 两个进程各持一份内存副本、各自整份覆写,后写的赢,于是
37
38
  // 「经中转配上的手机回局域网 401」「吊销被回滚」这两条必然出现。
@@ -70,6 +71,27 @@ let tunnelRoute = null
70
71
  * `raceTunnels` 与 `openTunnel` 的 catch 负责(**只有全部都不通才报 error**)。
71
72
  */
72
73
  let pendingAttempt = null
74
+ /**
75
+ * 每个候选地址最近一次实测的 /healthz 延迟(URL→毫秒;null = 不可达)。
76
+ *
77
+ * 电脑侧按实测延迟排序候选,最快的那台排前面先试。`relayLatencyAt` 是那次探测的时间戳,
78
+ * 5 分钟保鲜期内沿用这份结果;过期了 `relayRoutePlan` 就退回配置原序,等下一次
79
+ * `startTunnel` 重新探测再进来。
80
+ */
81
+ let relayLatencyCache = new Map()
82
+ let relayLatencyAt = 0
83
+ /** 一轮探活里最多几条同时在探(地址池变大时的并发上限,见 refreshRelayLatency)。 */
84
+ const PROBE_CONCURRENCY = 6
85
+ /**
86
+ * 隧道世代号:`stopTunnel` 每执行一次 +1。
87
+ *
88
+ * `startTunnel` 现在要先 await 一次延迟探测再进 `raceTunnels`,这中间隔了几百毫秒 ——
89
+ * 原先没有这个窗口。若这期间又来一次配置下发 / 重连又调了 `startTunnel`,两条异步链会各自
90
+ * 跑一遍 `raceTunnels`,各自 open 一条**同 instanceId** 的隧道;中转上同实例的后连会顶掉前一条,
91
+ * 结果把刚连好的那条挤断。世代号让已经过期的链在进 `raceTunnels` 前、以及循环每一轮都自检,
92
+ * 一旦发现自己是旧的立刻收手。
93
+ */
94
+ let tunnelGeneration = 0
73
95
  let lanState = 'off'
74
96
  let lanError = null
75
97
  let lanDiscovery = null
@@ -278,6 +300,14 @@ function snapshotRead(info) {
278
300
  lookup: (presented) => credentials.lookup(presented, config.instanceId),
279
301
  verifyLanToken: (presented) => core.verifyLanToken(config.lanSecret, presented, config.instanceId),
280
302
  })) return null
303
+ // **v2 绑定设备不能因中转删掉协议版本头就回明文快照**:这条捷径不封信封,一旦把一条
304
+ // 绑了 `deviceKey` 的凭据当成老客户端,它要的列表 / 工作区就会以明文经中转送出去——
305
+ // 主进程那条 `e2ee-required` 拦不到捷径这一层。认得出是设备密钥凭据就回源,交给主进程
306
+ // 按「加密会话没带信封」如实驳回(见 lib/http/routing.js)。
307
+ const boundRecord = snapshotAuthRecord(info && info.headers, {
308
+ lookup: (presented) => credentials.lookup(presented, config.instanceId),
309
+ })
310
+ if (boundRecord && boundRecord.deviceKey) return null
281
311
  let url
282
312
  try { url = new URL(String((info && info.path) || ''), 'http://127.0.0.1') } catch { return null }
283
313
  const pathname = url.pathname
@@ -358,6 +388,8 @@ function stopNetworkMonitor() {
358
388
  }
359
389
  function scheduleReconnect() { reconnect.schedule() }
360
390
  function stopTunnel() {
391
+ // 换代:任何还在探测 / 正在排队的旧 startTunnel 异步链据此作废,别再开新隧道(见 tunnelGeneration)。
392
+ tunnelGeneration += 1
361
393
  reconnect.cancel()
362
394
  if (tunnel) tunnel.stop()
363
395
  tunnel = null; tunnelState = 'off'; tunnelError = null
@@ -473,13 +505,22 @@ function startTunnel() {
473
505
  if (!relayRoutePlan().length) { stopTunnel(); return }
474
506
  stopTunnel(); tunnelState = 'connecting'
475
507
  publishState()
476
- void raceTunnels()
508
+ // 连之前先把各候选实测一遍延迟,让 relayRoutePlan 给出「最快优先」的顺序;探完再按序连。
509
+ // 探测本身失败不回滚这次连接(catch 吞掉),别忘了探完还要判一次 enabled。
510
+ // 记下这一代:探测期间若又发生重建(世代号前进),这条链就作废,别去开同实例的第二条隧道。
511
+ const generation = tunnelGeneration
512
+ void (async () => {
513
+ try { await refreshRelayLatency() } catch {}
514
+ if (generation !== tunnelGeneration || !config.enabled) return
515
+ await raceTunnels(generation)
516
+ })()
477
517
  }
478
518
  /**
479
- * 一次配置里可以按优先级试的中转地址,按 `relayUrls` 的原序。
519
+ * 一次配置里可以按优先级试的中转地址。
480
520
  *
481
- * 顺序就是优先级,这里**不做任何测量**:宿主只有一条出站 WSS,挑哪条对它的成本差异远小于
482
- * 手机那一头,而它每换一次就是全部在途请求断一次(契约 §择路-1)。延迟排序是手机侧的事。
521
+ * 公用中转改成「电脑决定」后,候选顺序取**最近一次实测延迟的快慢**(快的最先试);
522
+ * 探测结果超过 5 分钟保鲜期就退回 `relayUrls` 的原序 —— 那份原序是上一次写回收敛的结果,
523
+ * 下一次 `startTunnel` 会先重新探测再进来。
483
524
  *
484
525
  * `relayUrls` 缺席或为空(老宿主只下发 `relayUrl`)时退回单元素 —— 契约里那条兼容口径。
485
526
  * 已按 `core.normalizeRelayUrl` 规范化并用它拼 `tunnelWsUrl`,脏地址在这里就被丢掉而不是
@@ -500,14 +541,38 @@ function relayRoutePlan() {
500
541
  seen.add(url)
501
542
  urls.push(url)
502
543
  }
544
+ // 延迟结果还在保鲜期就按最快优先给出候选顺序;过期就按原序,等下次 startTunnel 重探。
545
+ // 只影响尝试顺序,不改地址本身,也不改去重 / 过滤的结果。
546
+ if (Date.now() - relayLatencyAt < 300000) return orderByLatency(urls, relayLatencyCache)
503
547
  return urls
504
548
  }
505
549
  /**
506
- * 这一轮选中了第几条:把它**提到队首**,其余条目相对顺序不动。
550
+ * 并发探一遍当前所有候选中转的 /healthz,把实测延迟写进模块级缓存并记时间戳。
551
+ *
552
+ * 每条独立超时(1500ms);某条探测失败只是这条记成 null(不可达、排后面),不影响其它条,
553
+ * 也不阻止这次连接(排序函数会把它们稳定地排在后面,失败仍由 raceTunnels 顺延到下一台)。
554
+ */
555
+ async function refreshRelayLatency() {
556
+ const urls = relayRoutePlan()
557
+ // 并发**分段**探,不一次性全打出去:地址池将来可能按地区变多,全并发会在同一瞬间打出一堆
558
+ // 连接(对自己的中转也等于一次小 DDoS),把 worker 的连接/内存压垮。每段最多 6 条同时探,
559
+ // 段内并发、段间顺序;每条的 1.5s 超时照旧只约束单条。
560
+ const results = new Map()
561
+ for (let index = 0; index < urls.length; index += PROBE_CONCURRENCY) {
562
+ const batch = urls.slice(index, index + PROBE_CONCURRENCY)
563
+ const probed = await Promise.all(batch.map(async (url) => [url, await probeRelayHealth(url, { timeoutMs: 1500 })]))
564
+ for (const [url, ms] of probed) results.set(url, ms)
565
+ }
566
+ relayLatencyCache = results
567
+ relayLatencyAt = Date.now()
568
+ }
569
+ /**
570
+ * 这一轮选中的中转写成当前主用,并把它**提到队首**,其余条目相对顺序不动。
507
571
  *
508
572
  * 为什么非提不可:`relayUrls[0]` 恒等于 `relayUrl`(core 的 normalize 每次落盘都会这么收敛)。
509
- * 只把中选的地址写成 `relayUrl` 而列表原样不动,下一次读盘就被旧首项顶回去,写回等于没写,
510
- * 重启又从死掉的那条开始试。**这不是延迟重排**:只把队首换人,不做任何按快慢的排序。
573
+ * 只把中选的地址写成 `relayUrl` 而列表原样不动,下一次读盘就被旧首项顶回去,写回等于没写。
574
+ * 启用延迟排序之后,中选那条**未必**是配置里的首项(`index 0` 只表示它是排序队列里最快的),
575
+ * 所以「要不要写回」改成看「写回后的顺序与当前 config 是否一致」,不是看「有没有从 0 挪到队首」。
511
576
  *
512
577
  * 两次账要一起结,漏一次就是「刚连上的隧道被自己拆掉」:
513
578
  * - 本进程的 `config` 就地换成新顺序 —— 宿主随后会下发同一份(它从这份状态里读),
@@ -520,11 +585,14 @@ function adoptRoute(route) {
520
585
  if (!route) return
521
586
  const remaining = route.urls.filter(url => url !== route.url)
522
587
  const next = [route.url, ...remaining]
523
- const adopted = route.index !== 0
524
- if (adopted) {
525
- config.relayUrl = next[0]
526
- config.relayUrls = next
527
- }
588
+ // 中选那条必须成为当前主用:它是此刻真的连上的那台。延迟排序后 `index 0` 不等于
589
+ // `config.relayUrl`,若沿旧判据(index !== 0)就会漏写回,让 `/status` 与总控继续报那条
590
+ // 可能已经死掉的旧主用 —— 手机连不上时查到的地址就是错的。
591
+ const current = Array.isArray(config.relayUrls) ? config.relayUrls : []
592
+ const sameOrder = next.length === current.length && next.every((url, index) => url === current[index])
593
+ const adopted = !sameOrder
594
+ config.relayUrl = next[0]
595
+ if (adopted) config.relayUrls = next
528
596
  tunnelRoute = {
529
597
  url: route.url,
530
598
  index: route.index,
@@ -532,7 +600,7 @@ function adoptRoute(route) {
532
600
  total: route.urls.length,
533
601
  // 报出去的是**写回之后**的顺序:宿主拿它落盘,与本进程那份一字不差。
534
602
  urls: next,
535
- // 只有真的挪了队首才需要宿主写回。已经在队首时落盘是多余的一次磁盘写。
603
+ // 顺序与当前 config 不同才需要宿主写回;一致时落盘是多余的一次磁盘写。
536
604
  adopted,
537
605
  }
538
606
  }
@@ -547,10 +615,13 @@ function adoptRoute(route) {
547
615
  * 会**从列表第一条重新开始**(`tunnelRoute` 在 `stopTunnel` 里作废),不许记住「上次卡在
548
616
  * 第几条」。
549
617
  */
550
- async function raceTunnels() {
618
+ async function raceTunnels(generation) {
551
619
  const urls = relayRoutePlan()
552
620
  if (!urls.length) { stopTunnel(); return false }
553
621
  for (let index = 0; index < urls.length; index += 1) {
622
+ // 这一代已经被新的 startTunnel 取代(配置又变了 / 又重连了一次):立刻收手,
623
+ // 别继续开同实例的隧道去顶掉新的那条(见 tunnelGeneration)。
624
+ if (generation !== undefined && generation !== tunnelGeneration) return false
554
625
  // 中途被关掉(用户点了关闭 / 配置改成 enabled:false):不试了,**顺手把这笔账清掉**。
555
626
  // 留着它的话,那条隧道的 close 会被 `onClose` 当成「还在等注册结果」吞掉 —— 下一次
556
627
  // 真正的掉线就报不出来,状态永远停在 connecting。
@@ -70,12 +70,12 @@ function createTailcatSession(options) {
70
70
  try {
71
71
  const state = options.readState() || {};
72
72
  return {
73
- enabled: state[STATE.enabled] !== false,
73
+ enabled: state[STATE.enabled] === true,
74
74
  identity: typeof state[STATE.identity] === 'string' ? state[STATE.identity] : null,
75
75
  allowed: Array.isArray(state[STATE.allowed]) ? state[STATE.allowed] : [],
76
76
  };
77
77
  } catch {
78
- return { enabled: true, identity: null, allowed: [] };
78
+ return { enabled: false, identity: null, allowed: [] };
79
79
  }
80
80
  }
81
81
 
@@ -66,7 +66,7 @@ function mountTailcat(options) {
66
66
  status: () => {
67
67
  const base = session
68
68
  ? session.status()
69
- : { available: Boolean(ingress), enabled: true, ready: false, address: '', paired: 0, error: 'starting' };
69
+ : { available: Boolean(ingress), enabled: false, ready: false, address: '', paired: 0, error: 'starting' };
70
70
  return { ...base, targetPort: resolvedTargetPort() };
71
71
  },
72
72
  openPairingWindow: ttl => (session ? session.openPairingWindow(ttl) : Promise.resolve(null)),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-plugin",
3
- "version": "0.5.75",
3
+ "version": "0.5.77",
4
4
  "description": "Mobile API (/api/mobile/v1) and relay client for the DSH mobile app — desktop profile build (dsh 0.2.x, peers resolved by the host)",
5
5
  "license": "MIT",
6
6
  "icon": "./icon.png",