dsh-mobile-plugin 0.5.79 → 0.5.81

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.
@@ -74,6 +74,167 @@ export function createRuntime() {
74
74
  let swapping = null
75
75
  /** 在飞请求计数(`beginRequest` / `endRequest` 维护)。 */
76
76
  let inFlight = 0
77
+
78
+ // ── 蓝绿路由分发表 ───────────────────────────────────────────────────
79
+ // 六条传输都归外壳之后,新旧两代可以短暂并存:新一代把它注册的路由登记到 stage 表,并给每个
80
+ // 路径挂一个**稳定分派器**(每个路径只挂一次,分派器读 live 表)。提交时原子把 live 指向
81
+ // 新代、旧代继续服务在飞请求,排空后再卸。这样换代码那一刻没有「路由暂缺 / 404」的空窗,
82
+ // 也不会因为新旧两代注册同一路径撞「duplicate route」。
83
+ let applying = false
84
+ let liveHttp = new Map()
85
+ let liveUp = new Map()
86
+ let stageHttp = null
87
+ let stageUp = null
88
+ const httpDispatchers = new Map() // path -> unregister
89
+ const upDispatchers = new Map()
90
+ let dispatchServer = null
91
+ let dispatchOuter = null
92
+ let dispatchOuterUpgrade = null
93
+
94
+ /** 外壳把真实服务器的原始 register/registerUpgrade 交给运行时(只调一次)。 */
95
+ function installDispatch(server, outer, outerUpgrade) {
96
+ dispatchServer = server
97
+ dispatchOuter = typeof outer === 'function' ? outer : null
98
+ dispatchOuterUpgrade = typeof outerUpgrade === 'function' ? outerUpgrade : null
99
+ }
100
+
101
+ /** 给 route.handler 外面套「进 +1 / 出 -1」;拿不到 handler 原样返回。 */
102
+ function wrapInFlight(route) {
103
+ if (!route || typeof route.handler !== 'function') return route
104
+ const handler = route.handler
105
+ route.handler = async (req, res) => {
106
+ inFlight += 1
107
+ try { return await handler(req, res) } finally { inFlight = Math.max(0, inFlight - 1) }
108
+ }
109
+ return route
110
+ }
111
+
112
+ function ensureHttpDispatcher(path, sample) {
113
+ if (httpDispatchers.has(path) || !dispatchServer || !dispatchOuter) return
114
+ const dispatcher = {
115
+ kind: sample && sample.kind,
116
+ path,
117
+ handler: async (req, res) => {
118
+ const live = liveHttp.get(path)
119
+ if (!live || typeof live.handler !== 'function') {
120
+ try { res.statusCode = 404 } catch { /* ignore */ }
121
+ try { res.end && res.end('') } catch { /* ignore */ }
122
+ return
123
+ }
124
+ return live.handler(req, res)
125
+ },
126
+ }
127
+ const unregister = dispatchOuter.call(dispatchServer, wrapInFlight(dispatcher))
128
+ httpDispatchers.set(path, typeof unregister === 'function' ? unregister : () => {})
129
+ }
130
+
131
+ function ensureUpDispatcher(path, sample) {
132
+ if (upDispatchers.has(path) || !dispatchServer || !dispatchOuterUpgrade) return
133
+ const dispatcher = {
134
+ ...(sample || {}),
135
+ handler: (req, socket, head) => {
136
+ const live = liveUp.get(path)
137
+ if (!live || typeof live.handler !== 'function') {
138
+ try { if (socket) socket.destroy() } catch { /* ignore */ }
139
+ return
140
+ }
141
+ return live.handler(req, socket, head)
142
+ },
143
+ }
144
+ const unregister = dispatchOuterUpgrade.call(dispatchServer, dispatcher)
145
+ upDispatchers.set(path, typeof unregister === 'function' ? unregister : () => {})
146
+ }
147
+
148
+ /** 代注册一条 HTTP 路由。装在分发表里;只有「外壳自己的路由」(非装载期)才直挂真服务器。 */
149
+ function registerRoute(route, outer, thisArg) {
150
+ if (!applying) return outer.call(thisArg, wrapInFlight(route))
151
+ if (!route || typeof route.path !== 'string') return () => {}
152
+ stageHttp.set(route.path, route)
153
+ ensureHttpDispatcher(route.path, route)
154
+ return () => {}
155
+ }
156
+
157
+ /** 代注册一条升级(WebSocket)路由,同上。 */
158
+ function registerUpgradeRoute(route, outer, thisArg) {
159
+ if (!applying) return outer.call(thisArg, route)
160
+ if (!route || typeof route.path !== 'string') return () => {}
161
+ stageUp.set(route.path, route)
162
+ ensureUpDispatcher(route.path, route)
163
+ return () => {}
164
+ }
165
+
166
+ function beginActivation() {
167
+ applying = true
168
+ stageHttp = new Map()
169
+ stageUp = new Map()
170
+ }
171
+
172
+ /** 原子提交:live 指向新代;旧代有、新代没有的分派器撤掉。返回提交前的 live 快照供回退。 */
173
+ function commitActivation() {
174
+ const prev = { http: liveHttp, up: liveUp }
175
+ for (const path of liveHttp.keys()) {
176
+ if (!stageHttp.has(path) && httpDispatchers.has(path)) {
177
+ try { httpDispatchers.get(path)() } catch { /* ignore */ }
178
+ httpDispatchers.delete(path)
179
+ }
180
+ }
181
+ for (const path of liveUp.keys()) {
182
+ if (!stageUp.has(path) && upDispatchers.has(path)) {
183
+ try { upDispatchers.get(path)() } catch { /* ignore */ }
184
+ upDispatchers.delete(path)
185
+ }
186
+ }
187
+ liveHttp = stageHttp
188
+ liveUp = stageUp
189
+ stageHttp = null
190
+ stageUp = null
191
+ applying = false
192
+ return prev
193
+ }
194
+
195
+ /** 装载失败:丢弃 staging,撤掉只为新代挂上的分派器;live 不动。 */
196
+ function rollbackActivation() {
197
+ if (stageHttp) {
198
+ for (const path of stageHttp.keys()) {
199
+ if (!liveHttp.has(path) && httpDispatchers.has(path)) {
200
+ try { httpDispatchers.get(path)() } catch { /* ignore */ }
201
+ httpDispatchers.delete(path)
202
+ }
203
+ }
204
+ }
205
+ if (stageUp) {
206
+ for (const path of stageUp.keys()) {
207
+ if (!liveUp.has(path) && upDispatchers.has(path)) {
208
+ try { upDispatchers.get(path)() } catch { /* ignore */ }
209
+ upDispatchers.delete(path)
210
+ }
211
+ }
212
+ }
213
+ stageHttp = null
214
+ stageUp = null
215
+ applying = false
216
+ }
217
+
218
+ /** 自检失败:把 live 换回旧代;新代独有分派器撤掉,旧代独有的补回(旧 fiber 一直活着)。 */
219
+ function restoreLive(prev) {
220
+ for (const path of liveHttp.keys()) {
221
+ if (!prev.http.has(path) && httpDispatchers.has(path)) {
222
+ try { httpDispatchers.get(path)() } catch { /* ignore */ }
223
+ httpDispatchers.delete(path)
224
+ }
225
+ }
226
+ for (const path of prev.http.keys()) if (!liveHttp.has(path)) ensureHttpDispatcher(path, prev.http.get(path))
227
+ for (const path of liveUp.keys()) {
228
+ if (!prev.up.has(path) && upDispatchers.has(path)) {
229
+ try { upDispatchers.get(path)() } catch { /* ignore */ }
230
+ upDispatchers.delete(path)
231
+ }
232
+ }
233
+ for (const path of prev.up.keys()) if (!liveUp.has(path)) ensureUpDispatcher(path, prev.up.get(path))
234
+ liveHttp = prev.http
235
+ liveUp = prev.up
236
+ }
237
+
77
238
  let lastError = null
78
239
  let activatedAt = null
79
240
  let detached = false
@@ -123,7 +284,8 @@ export function createRuntime() {
123
284
  * 回滚**不重新 import**:新代装失败时旧代的目录可能已经被市场删掉了,重新读盘会
124
285
  * MODULE_NOT_FOUND;而旧代的模块本体一直在内存里,重新 apply 一次就够了。
125
286
  */
126
- async function activateLoaded(loaded) {
287
+ async function activateLoaded(loaded, options = {}) {
288
+ const commit = options.commit !== false
127
289
  let timer = null
128
290
  // 用 `{ inject, apply }` 而不是裸函数:cordis 只有在**声明过** inject 的 fiber 上
129
291
  // 才允许 `ctx.webServer` 这种取值(裸函数会以 "cannot get property without inject"
@@ -135,14 +297,24 @@ export function createRuntime() {
135
297
  // 旧运行时上读 `ctx.apiProxy` 抛 "cannot get property apiProxy without inject"。
136
298
  // 测试里的假代没声明 inject 时退回外壳默认值。
137
299
  const inject = Array.isArray(loaded.inject) && loaded.inject.length > 0 ? loaded.inject : DEFAULT_INJECT
138
- const result = await Promise.race([
139
- Promise.resolve().then(() => ctx.plugin({ inject, apply: loaded.apply })),
140
- new Promise((_, reject) => {
141
- timer = setTimeout(() => reject(new Error(`装载 ${loaded.version} 超时(${ACTIVATE_TIMEOUT_MS}ms):它可能卡在等一个永远不来的依赖服务上`)), ACTIVATE_TIMEOUT_MS)
142
- }),
143
- ]).finally(() => {
300
+ beginActivation()
301
+ let result
302
+ try {
303
+ result = await Promise.race([
304
+ Promise.resolve().then(() => ctx.plugin({ inject, apply: loaded.apply })),
305
+ new Promise((_, reject) => {
306
+ timer = setTimeout(() => reject(new Error(`装载 ${loaded.version} 超时(${ACTIVATE_TIMEOUT_MS}ms):它可能卡在等一个永远不来的依赖服务上`)), ACTIVATE_TIMEOUT_MS)
307
+ }),
308
+ ])
309
+ } catch (error) {
310
+ // 装载失败:丢掉 staging、撤掉只为新代挂的分派器,live 保持旧代不动。
311
+ rollbackActivation()
312
+ throw error
313
+ } finally {
144
314
  if (timer) clearTimeout(timer)
145
- })
315
+ }
316
+ // 默认直接提交(start / attemptAll / 回滚装载);reload 要自检,先不提交,由它自己 commit。
317
+ if (commit) commitActivation()
146
318
  return { loaded, fiber: result }
147
319
  }
148
320
 
@@ -243,62 +415,61 @@ export function createRuntime() {
243
415
  // 同一份目录里改了文件:不清缓存的话,重新 import 拿回来的还是内存里那份旧实现。
244
416
  if (options.reread === true) invalidateGeneration(target.version)
245
417
 
418
+ // 先把新代模块整份读进内存(解析、依赖树、磁盘这一大段是本该慢的部分),**在动旧代之前**。
419
+ // 好处有两条:a) 新代连 import 就失败(缺文件 / 语法错 / 依赖解析不到)时,旧代毫发无损、
420
+ // 根本不进换代;b) 真正切换那一刻只剩 apply,旧路由摘掉到新路由挂上的空窗被压到最小。
421
+ const prepared = await importGeneration(target)
422
+
246
423
  await drain()
247
424
  const oldFiber = fiber
248
425
  const oldCurrent = current
249
426
  // 旧的**模块本体**要在激活新代之前抓住:`loadedCurrent` 一旦被新代覆盖,回滚就只能
250
- // 拿到刚装坏的那一份(真机上表现为「自检没过、退回去的还是坏的那个」)。
427
+ // 拿到刚装坏的那一份。
251
428
  const oldLoaded = loadedCurrent
252
- fiber = null
253
- current = null
254
- if (oldFiber) {
255
- try {
256
- await oldFiber.dispose()
257
- } catch (error) {
258
- // dispose 里的清理动作自己炸了:记下来,但不能因此不装新代。
259
- lastError = `卸载 ${oldCurrent?.version ?? '旧代'} 时出错:${error?.message || error}`
260
- }
261
- }
429
+ const oldActivatedAt = activatedAt
430
+ // 蓝绿:不再先卸旧代。新代先登记到分发表(staging),旧代继续服务在飞请求;提交后才卸
431
+ // 旧代。这样换代码那一刻没有路由空窗,也不会因为新旧两代注册同一路径撞 duplicate route。
262
432
  try {
263
- const { loaded, fiber: nextFiber } = await activate(target)
264
- fiber = nextFiber
265
- loadedCurrent = loaded
266
- current = describe(loaded, target.dir)
267
- if (oldCurrent) previous = oldCurrent
433
+ const next = await activateLoaded(prepared, { commit: false })
434
+ // 原子提交:分发表切到新代
435
+ const prevLive = commitActivation()
436
+ fiber = next.fiber
437
+ loadedCurrent = next.loaded
438
+ current = describe(next.loaded, target.dir)
268
439
  activatedAt = new Date().toISOString()
269
440
  lastError = null
270
- // 装起来了不等于**手机要打的那批接口**可用:端口没绑上、守卫没挂上、某个 handler
271
- // 永远不回包,这些都要真打一发才看得见。所以换完之后问一次自己的 `/health`。
272
- //
273
- // 不过就自己退回去 —— 这一步刻意放在宿主里,不交给手机:装坏的后果正是 App
274
- // 连不上这台设备,那时候手机上一颗按钮都发不出去。
441
+ // 自检:此刻 live 已是新代,真打一发确认手机要的那批接口能应答。
275
442
  if (options.selfCheck !== false && oldCurrent) {
276
443
  const alive = await checkSelfCheck()
277
444
  if (alive.ok === false) {
278
445
  const failure = `新版 ${target.version} 换上来之后没通过自检:${alive.reason}`
279
- // **先把刚装起来的新代卸掉**:它占着同一批路由路径,不卸就装不回旧代
280
- // (webserver: duplicate exact route)。这条是自检回滚与「装载直接抛错」两条路
281
- // 唯一的区别 —— 后者根本没有新 fiber 可卸。
282
- const brokenFiber = fiber
283
- fiber = null
284
- if (brokenFiber) {
285
- try { await brokenFiber.dispose() } catch { /* 新代自己卸不干净时,回滚仍然照试 */ }
286
- }
287
- await rollbackTo(oldCurrent, oldLoaded, failure)
446
+ // 退回旧代:分发表切回、卸新代;旧 fiber 一直活着,没有空窗。
447
+ restoreLive(prevLive)
448
+ fiber = oldFiber
449
+ loadedCurrent = oldLoaded
450
+ current = oldCurrent
451
+ activatedAt = oldActivatedAt
452
+ const brokenFiber = next.fiber
453
+ if (brokenFiber) { try { await brokenFiber.dispose() } catch { /* 卸不干净也照退 */ } }
454
+ lastRollback = { at: new Date().toISOString(), ok: true, toVersion: oldCurrent?.version ?? null, fromVersion: target.version, reason: failure }
455
+ lastError = failure
288
456
  const error = new Error(failure)
289
457
  error.code = 'self_check_failed'
290
458
  throw error
291
459
  }
292
460
  }
461
+ if (oldCurrent) previous = oldCurrent
462
+ // 成功:旧代排空后卸掉(在飞请求仍跑旧 handler 闭包)。
463
+ await drain()
464
+ if (oldFiber) {
465
+ try { await oldFiber.dispose() } catch (error) { lastError = `卸载 ${oldCurrent?.version ?? '旧代'} 时出错:${error?.message || error}` }
466
+ }
293
467
  clearBacklogRetry()
294
468
  return status()
295
469
  } catch (error) {
296
- // 自检那条已经在上面退回过一次了,别退第二遍(第二遍会把刚装回去的旧代再卸一次)。
297
- // 但它记下的「退回也失败」那句话不能在这里被覆盖掉 —— 那才是真机上最要紧的一条。
298
- if (error?.code !== 'self_check_failed') {
299
- lastError = `装载 ${target.version} 失败:${error?.message || error}`
300
- if (oldCurrent) await rollbackTo(oldCurrent, oldLoaded, lastError)
301
- }
470
+ // 装载直接抛错:activateLoaded 已 rollbackActivation,旧代毫发无损(fiber/current 没动)。
471
+ if (error?.code === 'self_check_failed') throw error
472
+ lastError = `装载 ${target.version} 失败:${error?.message || error}`
302
473
  throw error
303
474
  }
304
475
  })().finally(() => {
@@ -439,6 +610,9 @@ export function createRuntime() {
439
610
  reload,
440
611
  detach,
441
612
  status,
613
+ installDispatch,
614
+ registerRoute,
615
+ registerUpgradeRoute,
442
616
  beginRequest: () => {
443
617
  inFlight += 1
444
618
  },
@@ -0,0 +1,158 @@
1
+ /**
2
+ * 稳定外壳持有的传输进程:sidecar(中转隧道 + 局域网监听)、FRP 直连、总控上报。
3
+ *
4
+ * 它们都是长期活着的连接/进程,**不能挂在一代实现下**——否则换代(dispose 旧代)会把它们
5
+ * 连同隧道一起停掉再重建,手机就在那几秒断线。这里由外壳创建并持有,跨代存活;换代只把
6
+ * 配置/端口/状态来源重新注入(`setProviders` / `setPortProvider`),进程本身照跑。
7
+ *
8
+ * 惰性启动:只有「认识对应服务」的一代注入来源时才真正 start,避免回滚到不认识该服务的旧版
9
+ * 时外壳与旧代各起一份(重复 frpc / 重复上报连接)。
10
+ *
11
+ * 外壳(`lib/index.js`)只调一次 `installTransportHosts(ctx)`,业务逻辑全在这个文件里,
12
+ * 免得把外壳那个「只装代码」的入口撑大(`test/assembly-layer.test.cjs` 钉着)。
13
+ */
14
+ import sidecarLifecycleCjs from '../sidecar-lifecycle.cjs'
15
+ import frpcRunnerCjs from '../frpc/runner.cjs'
16
+ import controlCjs from '../relay/control.js'
17
+ import tailcatWiringCjs from '../tailcat/wiring.cjs'
18
+ import p2pWiringCjs from '../p2p/wiring.cjs'
19
+ import muxCjs from '../mobile/mux.js'
20
+
21
+ const { createSidecarLifecycle } = sidecarLifecycleCjs
22
+ const { createFrpcRunner } = frpcRunnerCjs
23
+ const { createControlClient } = controlCjs
24
+ const { mountTailcat } = tailcatWiringCjs
25
+ const { mountP2P } = p2pWiringCjs
26
+ const { createMuxService } = muxCjs
27
+
28
+ export function installTransportHosts(ctx) {
29
+ // ── sidecar:中转隧道 + 局域网监听 ──────────────────────────────────
30
+ // 由代首次 sync 时惰性 start(幂等);换代只换配置来源,隧道跨代存活。外壳卸载才 stop。
31
+ const sidecarHost = createSidecarLifecycle({ ctx })
32
+ ctx.reflect.provide('dshMobileSidecarHost', sidecarHost)
33
+ ctx.effect(() => () => sidecarHost.stop(), 'dsh-mobile-plugin: sidecar transport host')
34
+
35
+ // ── FRP 直连:frpc 子进程 ──────────────────────────────────────────
36
+ let frpPortProvider = () => 0
37
+ const frpRunner = createFrpcRunner({ portOf: () => frpPortProvider() })
38
+ ctx.reflect.provide('dshMobileTransportFrp', {
39
+ runner: frpRunner,
40
+ setPortProvider: fn => {
41
+ if (typeof fn !== 'function') return
42
+ frpPortProvider = fn
43
+ if (frpRunner.shouldAutoStart()) void frpRunner.start()
44
+ },
45
+ })
46
+ ctx.effect(() => () => { void frpRunner.dispose() }, 'dsh-mobile-plugin: frpc transport host')
47
+
48
+ // ── 总控上报:常连的出站客户端 ─────────────────────────────────────
49
+ let controlProviders = {
50
+ getState: () => ({}),
51
+ persist: () => {},
52
+ getPort: () => 0,
53
+ getHistoryKey: () => '',
54
+ getRelayConnected: () => sidecarHost.tunnelConnected(),
55
+ // 身份冲突时触发换身份的动作,由当前这一代注入(换代换它即可)。缺省不启用。
56
+ onIdentityConflict: null,
57
+ }
58
+ const controlClient = createControlClient({
59
+ getState: () => controlProviders.getState(),
60
+ persist: () => controlProviders.persist(),
61
+ getPort: () => controlProviders.getPort(),
62
+ getHistoryKey: () => controlProviders.getHistoryKey(),
63
+ getRelayConnected: () => controlProviders.getRelayConnected(),
64
+ onIdentityConflict: (...args) => {
65
+ const fn = controlProviders.onIdentityConflict
66
+ return typeof fn === 'function' ? fn(...args) : undefined
67
+ },
68
+ })
69
+ ctx.reflect.provide('dshMobileTransportControl', {
70
+ client: controlClient,
71
+ setProviders: p => {
72
+ controlProviders = { ...controlProviders, ...(p && typeof p === 'object' ? p : {}) }
73
+ controlClient.start()
74
+ controlClient.sync()
75
+ },
76
+ })
77
+ ctx.effect(() => () => controlClient.stop(), 'dsh-mobile-plugin: control transport host')
78
+
79
+ // ── 对话页长连接(mux) ─────────────────────────────────────────────
80
+ // mux 只是一条把逻辑流转成本地回环 HTTP 打到移动 API 的搬运工。把它和它的升级路由提到外壳,
81
+ // 已建立的手机 WS 就能跨过换代不断(底层订阅续传由 App 的序号机制兜)。鉴权在服务里做,
82
+ // `authorize` 由当前这一代注入(换代换它即可)。
83
+ let muxProviders = { authorize: () => false }
84
+ const muxService = createMuxService({
85
+ upstream: { port: ctx.webServer.port },
86
+ authorize: req => (typeof muxProviders.authorize === 'function' ? muxProviders.authorize(req) : false),
87
+ onLog: message => { try { ctx.logger?.info?.(`dsh-mobile-plugin: ${message}`) } catch { /* ignore */ } },
88
+ })
89
+ ctx.reflect.provide('dshMobileTransportMux', {
90
+ service: muxService,
91
+ setProviders: p => { if (p && typeof p === 'object') muxProviders = { ...muxProviders, ...p } },
92
+ })
93
+ try {
94
+ if (typeof ctx.webServer.registerUpgrade === 'function') {
95
+ ctx.effect(() => ctx.webServer.registerUpgrade({ path: '/api/mobile/v1/mux', handler: muxService.handleUpgrade }), 'dsh-mobile-plugin: mux upgrade route')
96
+ }
97
+ } catch { /* 宿主没有升级路由能力时这条不挂,App 走 HTTP/SSE 兜底 */ }
98
+
99
+ // ── 隧道助手(直连隧道) ────────────────────────────────────────────
100
+ // 惰性 ensure:只有认识这个服务的一代第一次用到时才真正创建入口/落点/助手会话并起监听,
101
+ // 测试里的假代不碰它就完全不起端口/进程。创建用外壳的 ctx,effect 挂在外壳上,跨代存活;
102
+ // 换代只更新状态/端口来源(`ensure` 传进来的 providers),助手会话本身照跑。
103
+ const warn = message => { try { ctx.logger?.warn?.(`dsh-mobile-plugin: ${message}`) } catch { /* 日志不许反噬 */ } }
104
+ const looseMount = (label, fn) => { try { return fn() } catch (error) { warn(`${label} 没挂上:${error && error.message ? error.message : error}`); return undefined } }
105
+ let tailcatDoor = null
106
+ let tailcatProviders = {}
107
+ ctx.reflect.provide('dshMobileTransportTailcat', {
108
+ ensure: providers => {
109
+ if (providers && typeof providers === 'object') tailcatProviders = { ...tailcatProviders, ...providers }
110
+ const pick = name => (typeof tailcatProviders[name] === 'function' ? tailcatProviders[name] : null)
111
+ if (!tailcatDoor) {
112
+ tailcatDoor = mountTailcat({
113
+ mount: looseMount,
114
+ warn,
115
+ getState: () => (pick('getState') ? pick('getState')() : {}),
116
+ saveState: state => { const fn = pick('saveState'); if (fn) fn(state) },
117
+ lanEnabled: () => (pick('lanEnabled') ? pick('lanEnabled')() : false),
118
+ lanPort: () => (pick('lanPort') ? pick('lanPort')() : 0),
119
+ webPort: () => (pick('webPort') ? pick('webPort')() : 0),
120
+ webHost: () => (pick('webHost') ? pick('webHost')() : '127.0.0.1'),
121
+ hostName: () => (pick('hostName') ? pick('hostName')() : ''),
122
+ ctx,
123
+ name: 'dsh-mobile-plugin',
124
+ })
125
+ }
126
+ return tailcatDoor
127
+ },
128
+ })
129
+
130
+ // ── 点对点隧道 ──────────────────────────────────────────────────────
131
+ // 与隧道助手同一套惰性 ensure:不碰它就不起端口/会话;换代只更新来源。
132
+ let p2pDoor = null
133
+ let p2pProviders = {}
134
+ ctx.reflect.provide('dshMobileTransportP2P', {
135
+ ensure: providers => {
136
+ if (providers && typeof providers === 'object') p2pProviders = { ...p2pProviders, ...providers }
137
+ const pick = name => (typeof p2pProviders[name] === 'function' ? p2pProviders[name] : null)
138
+ if (!p2pDoor) {
139
+ p2pDoor = mountP2P({
140
+ mount: looseMount,
141
+ warn,
142
+ getState: () => (pick('getState') ? pick('getState')() : {}),
143
+ saveState: state => { const fn = pick('saveState'); if (fn) fn(state) },
144
+ localPort: () => (pick('localPort') ? pick('localPort')() : 0),
145
+ lanEnabled: () => (pick('lanEnabled') ? pick('lanEnabled')() : false),
146
+ lanPort: () => (pick('lanPort') ? pick('lanPort')() : 0),
147
+ webPort: () => (pick('webPort') ? pick('webPort')() : 0),
148
+ webHost: () => (pick('webHost') ? pick('webHost')() : '127.0.0.1'),
149
+ ctx,
150
+ name: 'dsh-mobile-plugin',
151
+ })
152
+ }
153
+ return p2pDoor
154
+ },
155
+ })
156
+
157
+ return { sidecarHost, frpRunner, controlClient, tailcatDoor: () => tailcatDoor, p2pDoor: () => p2pDoor }
158
+ }
@@ -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/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']
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', 'lib/shell/transport-host.js']
77
77
  const hash = createHash('sha256')
78
78
  let seen = 0
79
79
  for (const rel of files) {
@@ -44,6 +44,19 @@ const parentPort = Number(process.env.DSH_SIDECAR_PARENT_PORT)
44
44
  const token = process.env.DSH_SIDECAR_TOKEN
45
45
  const authorization = `Bearer ${token}`
46
46
  let config = {}
47
+ /**
48
+ * 按凭据查记录:先查当前号,过渡期再兜底旧号(见 core.rotateIdentity)。
49
+ * 只用于「认不认这枚凭据」,配对签发仍只用当前号。
50
+ */
51
+ function lookupAccepted(presented) {
52
+ return credentials.lookup(presented, config.instanceId)
53
+ || (config.previousInstanceId ? credentials.lookup(presented, config.previousInstanceId) : null)
54
+ }
55
+ /** 旧的无状态令牌验签:同样当前号优先、旧号兜底。 */
56
+ function verifyLanAccepted(presented) {
57
+ return core.verifyLanToken(config.lanSecret, presented, config.instanceId)
58
+ || (config.previousInstanceId ? core.verifyLanToken(config.lanSecret, presented, config.previousInstanceId) : false)
59
+ }
47
60
  const sockets = new Set()
48
61
  let tunnel = null
49
62
  let lan = null
@@ -302,15 +315,15 @@ function snapshotRead(info) {
302
315
  // (印在配对二维码上),不带任何凭据也能经中转读到会话 / 工作区列表。验不过回 null 回源,
303
316
  // 交给主进程守卫如实驳回(401);被吊销 / 已过期的凭据同样回落,吊销才不会在这条路上失效。
304
317
  if (!snapshotAuthorized(info && info.headers, {
305
- lookup: (presented) => credentials.lookup(presented, config.instanceId),
306
- verifyLanToken: (presented) => core.verifyLanToken(config.lanSecret, presented, config.instanceId),
318
+ lookup: lookupAccepted,
319
+ verifyLanToken: verifyLanAccepted,
307
320
  })) return null
308
321
  // **v2 绑定设备不能因中转删掉协议版本头就回明文快照**:这条捷径不封信封,一旦把一条
309
322
  // 绑了 `deviceKey` 的凭据当成老客户端,它要的列表 / 工作区就会以明文经中转送出去——
310
323
  // 主进程那条 `e2ee-required` 拦不到捷径这一层。认得出是设备密钥凭据就回源,交给主进程
311
324
  // 按「加密会话没带信封」如实驳回(见 lib/http/routing.js)。
312
325
  const boundRecord = snapshotAuthRecord(info && info.headers, {
313
- lookup: (presented) => credentials.lookup(presented, config.instanceId),
326
+ lookup: lookupAccepted,
314
327
  })
315
328
  if (boundRecord && boundRecord.deviceKey) return null
316
329
  let url
@@ -369,7 +382,7 @@ function tunnelSignature(c) {
369
382
  function lanSignature(c) {
370
383
  // **配对码与票据不在其中**:它们由 `currentPairing` 现读,改它们不该重建监听 ——
371
384
  // 配对成功就要换一次(§5.1),跟着重建会把刚握上的连接掐掉。
372
- return JSON.stringify([Boolean(c.enabled), Boolean(c.lanEnabled), c.lanPort || 0, c.upstreamPort || 0, c.upstreamHost || '', c.instanceId || '', c.lanSecret || '', c.pairingTier || 'full'])
385
+ return JSON.stringify([Boolean(c.enabled), Boolean(c.lanEnabled), c.lanPort || 0, c.upstreamPort || 0, c.upstreamHost || '', c.instanceId || '', c.previousInstanceId || '', c.lanSecret || '', c.pairingTier || 'full'])
373
386
  }
374
387
  /** 「这份配置里哪几项决定网络监视器要不要重排」。 */
375
388
  function monitorSignature(c) {
@@ -681,7 +694,7 @@ async function startLan() {
681
694
  requestedPort: config.lanPort, discovery, store: credentials, instanceId: config.instanceId,
682
695
  isCurrent: () => own === lanGeneration,
683
696
  createProxy: port => createLanProxy({
684
- lanPort: port, instanceId: config.instanceId, lanSecret: config.lanSecret,
697
+ lanPort: port, instanceId: config.instanceId, previousInstanceId: config.previousInstanceId || '', lanSecret: config.lanSecret,
685
698
  // 配对码与票据走取值器:配对成功之后宿主会换掉它们(§5.1),而重建局域网代理会把
686
699
  // 刚握上的连接全掐掉 —— 换值不该动监听。
687
700
  currentPairing: () => ({ code: config.pairingCode, ticket: config.pairingTicket || '' }),
@@ -732,9 +745,10 @@ async function configure(next) {
732
745
  // `relayUrls` 在白名单里,而且从这一轮起**进签名**(见 tunnelSignature):地址组或它的
733
746
  // 顺序变了就要重新择路。白名单缺了它,宿主下发这一格会直接抛 unknown configuration
734
747
  // field,整次配置下发失败。
735
- const allowed = ['enabled', 'relayUrl', 'relayUrls', 'instanceId', 'pairingCode', 'pairingTicket', 'pairingTier', 'name', 'upstreamPort', 'upstreamHost', 'lanPort', 'lanEnabled', 'lanSecret', 'registerSecret']
748
+ const allowed = ['enabled', 'relayUrl', 'relayUrls', 'instanceId', 'previousInstanceId', 'pairingCode', 'pairingTicket', 'pairingTier', 'name', 'upstreamPort', 'upstreamHost', 'lanPort', 'lanEnabled', 'lanSecret', 'registerSecret']
736
749
  if (Object.keys(next).some(key => !allowed.includes(key))) throw new Error('unknown configuration field')
737
750
  if (typeof next.instanceId !== 'string' || next.instanceId.length > 128) throw new Error('invalid instanceId')
751
+ if (next.previousInstanceId !== undefined && (typeof next.previousInstanceId !== 'string' || next.previousInstanceId.length > 128)) throw new Error('invalid previousInstanceId')
738
752
  if (typeof next.pairingCode !== 'string' || !/^\d{6}$/.test(next.pairingCode)) throw new Error('invalid pairingCode')
739
753
  if (next.pairingTicket !== undefined && (typeof next.pairingTicket !== 'string' || !/^[A-Za-z0-9_-]{0,64}$/.test(next.pairingTicket))) throw new Error('invalid pairingTicket')
740
754
  if (next.pairingTier !== undefined && !['readonly', 'approve', 'full'].includes(next.pairingTier)) throw new Error('invalid pairingTier')