dsh-mobile-plugin 0.5.81 → 0.5.83
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/README.md +4 -0
- package/dsh-mobile-credentials/lib/credentials.js +5 -0
- package/lib/client.js +171 -5
- package/lib/frpc/provision.cjs +21 -17
- package/lib/frpc/runner.cjs +231 -168
- package/lib/impl.js +77 -107
- package/lib/index.js +1 -1
- package/lib/mirror/pusher.cjs +60 -10
- package/lib/mobile/approval-memory.js +2 -55
- package/lib/mobile/approvals.js +6 -82
- package/lib/mobile/events.js +2 -1
- package/lib/mobile/feedback.js +6 -5
- package/lib/mobile/file-read.js +4 -2
- package/lib/mobile/host-bridge.js +12 -1
- package/lib/mobile/mux.js +148 -21
- package/lib/mobile/paired-devices.js +2 -1
- package/lib/mobile/pairing.js +8 -7
- package/lib/mobile/relay-control.js +33 -38
- package/lib/mobile/session-changes.js +8 -2
- package/lib/mobile/session-delivery.js +5 -1
- package/lib/mobile/session-file.js +46 -25
- package/lib/mobile/session-head.js +7 -3
- package/lib/mobile/session-snapshot.js +5 -1
- package/lib/mobile/session-step.js +13 -7
- package/lib/mobile/session-stop-summary.js +6 -1
- package/lib/mobile/stream-registry.js +48 -53
- package/lib/mobile/stream.js +17 -2
- package/lib/mobile/uploads.js +190 -163
- package/lib/p2p/session.cjs +169 -70
- package/lib/p2p/wiring.cjs +4 -2
- package/lib/panel/index.html +44 -24
- package/lib/relay/blob-upload.cjs +103 -0
- package/lib/relay/config-store.js +79 -0
- package/lib/relay/control.js +131 -52
- package/lib/relay/core.js +55 -17
- package/lib/relay/lan-discovery.cjs +22 -14
- package/lib/relay/lan-port-policy.cjs +8 -2
- package/lib/relay/lan-proxy.js +47 -12
- package/lib/relay/pairing-payload.cjs +14 -5
- package/lib/relay/preview-webapp.cjs +150 -0
- package/lib/relay/preview.js +35 -8
- package/lib/relay/protocol.js +6 -4
- package/lib/relay/relay-probe.js +112 -21
- package/lib/relay/status.js +4 -7
- package/lib/relay/tunnel-forwarder.cjs +4 -2
- package/lib/relay/tunnel.js +39 -8
- package/lib/remote/controller.cjs +33 -3
- package/lib/remote/host-control.cjs +11 -2
- package/lib/remote/router.cjs +83 -33
- package/lib/remote/transport.cjs +32 -5
- package/lib/remote/tunnel-helper.cjs +51 -25
- package/lib/remote/tunnels.cjs +27 -3
- package/lib/routes/control-plane.js +41 -53
- package/lib/routes/mobile-api.js +21 -31
- package/lib/shared/fresh-request.js +32 -1
- package/lib/shared/route-order.cjs +118 -132
- package/lib/shared/sse-write.js +29 -10
- package/lib/shared/via-header.js +5 -12
- package/lib/shell/transport-host.js +9 -1
- package/lib/shell/updater.js +18 -6
- package/lib/sidecar-facade-worker.cjs +165 -118
- package/lib/sidecar-facade.cjs +6 -1
- package/lib/sidecar-lifecycle.cjs +6 -2
- package/lib/tailcat/host-process.cjs +32 -8
- package/lib/tailcat/session.cjs +27 -10
- package/package.json +6 -6
- package/lib/mobile/auto-review.js +0 -178
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
// 绑定遵守固定入口策略,网卡变化及时通知宿主上报目录。
|
|
2
|
+
// blob分片等中转持久化确认,发送失败沿本机RPC返回生产者。
|
|
3
|
+
// 管理中转注册真值,以单调经过时间约束失败账和首连竞速,保留独立 IPv6 监听。
|
|
1
4
|
'use strict'
|
|
2
5
|
// LAN 生命周期等待旧监听释放,并由同一处绑定与发布入口。
|
|
3
6
|
// 转发给宿主 web 服务的上游地址跟随宿主实际绑定地址(不再写死回环)。
|
|
@@ -17,20 +20,21 @@
|
|
|
17
20
|
* 3. 请求体一律先量后读:`/configure` 与镜像帧都有字节上限,超限立刻 413。
|
|
18
21
|
* 4. 换中转地址不是「拆了重建」:先在旧隧道上登记迁移,再建新隧道,注册不上要撤销
|
|
19
22
|
* (见 lib/relay/migrate.js)。这条顺序是「填错地址就把自己锁在外面」的唯一解。
|
|
20
|
-
* 5.
|
|
21
|
-
*
|
|
23
|
+
* 5. 无当前连接时按健康延迟与注册失败账排序,最多三条并行,第一条注册成功的当主用,
|
|
24
|
+
* 全不通再退避;换成功只把它提到队首、报给宿主写回,**不发 migrate 帧**(自动换发生在旧地址已经
|
|
22
25
|
* 连不上的时刻,旧中转上那台机器的隧道早就断了,没人需要被指路)。
|
|
23
26
|
*/
|
|
24
27
|
|
|
25
28
|
const http = require('node:http')
|
|
29
|
+
const { performance } = require('node:perf_hooks')
|
|
26
30
|
const { RelayTunnel } = require('./relay/tunnel.js')
|
|
27
31
|
const { T } = require('./relay/protocol.js')
|
|
28
32
|
const { switchRelay } = require('./relay/migrate.js')
|
|
29
33
|
const { createLanProxy } = require('./relay/lan-proxy.js')
|
|
30
34
|
const { createLanDiscovery, bindLanEndpoint } = require('./relay/lan-discovery.cjs')
|
|
31
|
-
const { lanUrls } = require('./relay/lan-network.cjs')
|
|
35
|
+
const { lanUrls, ipv6Urls } = require('./relay/lan-network.cjs')
|
|
32
36
|
const core = require('./relay/core.js')
|
|
33
|
-
const {
|
|
37
|
+
const { probeRelayHealth, createRelayRegistrationLedger, relayFailureMessage } = require('./relay/relay-probe.js')
|
|
34
38
|
const { createReconnectScheduler } = require('./reconnect-scheduler.cjs')
|
|
35
39
|
const { isMirrorSnapshotFresh } = require('./mirror-snapshot.cjs')
|
|
36
40
|
const { snapshotAuthorized, snapshotAuthRecord } = require('./relay/snapshot-auth.js')
|
|
@@ -76,17 +80,14 @@ let relayMirror = true
|
|
|
76
80
|
* @type {null | { url: string, index: number, tried: number, total: number, urls: string[], adopted: boolean }}
|
|
77
81
|
*/
|
|
78
82
|
let tunnelRoute = null
|
|
83
|
+
let connectedRelayUrl = null
|
|
84
|
+
/** 在飞注册由竞速独占;未 registered 的 close 不写业务状态,统一由注册 Promise 结账。 */
|
|
85
|
+
let relayRace = null
|
|
86
|
+
const relayRegistrations = createRelayRegistrationLedger()
|
|
87
|
+
const RELAY_RACE_CONCURRENCY = 3
|
|
88
|
+
const RELAY_RACE_TIMEOUT_MS = 10_000
|
|
79
89
|
/**
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
* 择路的每一条都会先握手再失败:隧道实例的 `onClose` 与 `start()` 的 reject 会**同时**到达。
|
|
83
|
-
* 两条都记账的话,试第 2 条时状态会先被写成 error 再写成 connecting,宿主那边「隧道刚连上
|
|
84
|
-
* 补推一次全量」的边沿账跟着乱跳。所以等结果的这一段里 `onClose` 闭嘴,收尾统一由
|
|
85
|
-
* `raceTunnels` 与 `openTunnel` 的 catch 负责(**只有全部都不通才报 error**)。
|
|
86
|
-
*/
|
|
87
|
-
let pendingAttempt = null
|
|
88
|
-
/**
|
|
89
|
-
* 每个候选地址最近一次实测的 /healthz 延迟(URL→毫秒;null = 不可达)。
|
|
90
|
+
* 每个候选地址最近一次实测的身份健康延迟(URL→毫秒;null = 不可达)。
|
|
90
91
|
*
|
|
91
92
|
* 电脑侧按实测延迟排序候选,最快的那台排前面先试。`relayLatencyAt` 是那次探测的时间戳,
|
|
92
93
|
* 5 分钟保鲜期内沿用这份结果;过期了 `relayRoutePlan` 就退回配置原序,等下一次
|
|
@@ -97,13 +98,8 @@ let relayLatencyAt = 0
|
|
|
97
98
|
/** 一轮探活里最多几条同时在探(地址池变大时的并发上限,见 refreshRelayLatency)。 */
|
|
98
99
|
const PROBE_CONCURRENCY = 6
|
|
99
100
|
/**
|
|
100
|
-
*
|
|
101
|
-
*
|
|
102
|
-
* `startTunnel` 现在要先 await 一次延迟探测再进 `raceTunnels`,这中间隔了几百毫秒 ——
|
|
103
|
-
* 原先没有这个窗口。若这期间又来一次配置下发 / 重连又调了 `startTunnel`,两条异步链会各自
|
|
104
|
-
* 跑一遍 `raceTunnels`,各自 open 一条**同 instanceId** 的隧道;中转上同实例的后连会顶掉前一条,
|
|
105
|
-
* 结果把刚连好的那条挤断。世代号让已经过期的链在进 `raceTunnels` 前、以及循环每一轮都自检,
|
|
106
|
-
* 一旦发现自己是旧的立刻收手。
|
|
101
|
+
* 隧道世代号:停止或手动换线时前进,旧代竞速与健康探测都不能再接管当前状态。
|
|
102
|
+
* 同实例的迟到注册会顶掉新连接,所以旧代候选必须同时主动停止,不能只忽略回调。
|
|
107
103
|
*/
|
|
108
104
|
let tunnelGeneration = 0
|
|
109
105
|
let lanState = 'off'
|
|
@@ -130,7 +126,7 @@ function publishState() {
|
|
|
130
126
|
type: 'state',
|
|
131
127
|
// `route` 是这一轮择路的账:当前连的是哪条、是列表里第几条、试过几条。
|
|
132
128
|
// 宿主拿它决定「该把中选的那条写回队首了」,手机拿它诊断「为什么不是我配的那条」。
|
|
133
|
-
tunnel: { state: tunnelState, error: tunnelError, mirror: relayMirror, ...(tunnelRoute ? { route: tunnelRoute } : {}) },
|
|
129
|
+
tunnel: { state: tunnelState, error: tunnelError, mirror: relayMirror, relayUrl: tunnelState === 'connected' ? connectedRelayUrl : null, ...(tunnelRoute ? { route: tunnelRoute } : {}) },
|
|
134
130
|
lan: { enabled: Boolean(config.lanEnabled), port: lanUrlPort(), requestedPort: lanRequestedPort || config.lanPort, state: lanState, error: lanError, discovery: lanDiscovery?.snapshot() || { state: 'off', error: null } },
|
|
135
131
|
})
|
|
136
132
|
}
|
|
@@ -409,8 +405,12 @@ function stopTunnel() {
|
|
|
409
405
|
// 换代:任何还在探测 / 正在排队的旧 startTunnel 异步链据此作废,别再开新隧道(见 tunnelGeneration)。
|
|
410
406
|
tunnelGeneration += 1
|
|
411
407
|
reconnect.cancel()
|
|
412
|
-
|
|
413
|
-
|
|
408
|
+
relayRace?.cancel()
|
|
409
|
+
const previous = tunnel
|
|
410
|
+
tunnel = null
|
|
411
|
+
if (previous) previous.stop()
|
|
412
|
+
connectedRelayUrl = null
|
|
413
|
+
tunnelState = 'off'; tunnelError = null
|
|
414
414
|
// 断开即忘掉上一台中转的口径:下次连的可能是另一台,别拿旧的判断去决定推不推正文。
|
|
415
415
|
relayMirror = true
|
|
416
416
|
// 这一轮择路的账一并作废:下次 startTunnel 会从头重新走一遍列表。
|
|
@@ -419,15 +419,17 @@ function stopTunnel() {
|
|
|
419
419
|
}
|
|
420
420
|
function startNetworkMonitor() {
|
|
421
421
|
stopNetworkMonitor()
|
|
422
|
-
if (!config.enabled
|
|
423
|
-
|
|
422
|
+
if (!config.enabled) return
|
|
423
|
+
const addresses = () => [...(config.lanEnabled ? lanUrls(lanUrlPort()) : []), ...ipv6Urls(lanUrlPort())]
|
|
424
|
+
let previous = addresses()
|
|
424
425
|
networkTimer = setInterval(() => {
|
|
425
|
-
const current =
|
|
426
|
+
const current = addresses()
|
|
426
427
|
if (JSON.stringify(current) === JSON.stringify(previous)) return
|
|
427
428
|
previous = current
|
|
428
429
|
const publisher = lanDiscovery
|
|
429
430
|
if (lanState === 'listening' && publisher) void publisher.publish(lanBoundPort)
|
|
430
431
|
reannounceRegistration()
|
|
432
|
+
publishState()
|
|
431
433
|
}, NETWORK_POLL_MS)
|
|
432
434
|
}
|
|
433
435
|
async function stopLan() {
|
|
@@ -448,11 +450,13 @@ async function stopServices() { stopNetworkMonitor(); stopTunnel(); await stopLa
|
|
|
448
450
|
* (`configure` 的 503 会一路回到手机)。普通重建由 `startTunnel` 那一侧兜底 —— 状态置错 +
|
|
449
451
|
* 排重连,与旧实现一字不差。
|
|
450
452
|
*/
|
|
451
|
-
function openTunnel(route) {
|
|
453
|
+
function openTunnel(route, race = null) {
|
|
454
|
+
if (!race) { tunnelGeneration += 1; relayRace?.cancel() }
|
|
452
455
|
// 这一次尝试连的是哪一条。`configure()` 换地址那条路不走择路:它调的 openTunnel() 不带
|
|
453
456
|
// route,连的仍是 config.relayUrl 那一条,且**不许**把队首提上来——那是人手填的地址,
|
|
454
457
|
// 顺序归人管(见文件头第 4 条)。
|
|
455
458
|
const targetUrl = route ? route.url : config.relayUrl
|
|
459
|
+
let registered = false
|
|
456
460
|
const current = new RelayTunnel({
|
|
457
461
|
relayUrl: core.tunnelWsUrl(targetUrl), instanceId: config.instanceId,
|
|
458
462
|
name: config.name, upstream: upstream(),
|
|
@@ -474,17 +478,17 @@ function openTunnel(route) {
|
|
|
474
478
|
// 回执里的镜像口径(`relayMirror`)跟着状态一起改、一起播,同样只在这道身份闸之内:
|
|
475
479
|
// 旧实例迟到的回执不许改新连接的口径。
|
|
476
480
|
//
|
|
477
|
-
//
|
|
478
|
-
|
|
479
|
-
if (tunnel !== current) return; reconnect.
|
|
480
|
-
|
|
481
|
+
// 只有本代竞速接纳的唯一赢家可成为当前实例,并把真实 targetUrl 与注册状态一起发布。
|
|
482
|
+
if (race && !race.accept(current)) return
|
|
483
|
+
if (tunnel !== current) return; registered = true; reconnect.cancel(); reconnect.reset(); adoptRoute(route); connectedRelayUrl = targetUrl
|
|
484
|
+
relayRegistrations.noteSuccess(targetUrl)
|
|
485
|
+
if (tunnel !== current) return; tunnelState = 'connected'; tunnelError = null; relayMirror = current.relayMirror !== false; publishState()
|
|
481
486
|
},
|
|
482
487
|
onClose: () => {
|
|
483
|
-
if (tunnel !== current || !config.enabled) return
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
if (
|
|
487
|
-
tunnelState = 'error'; tunnelError = '连接断开'; publishState(); scheduleReconnect()
|
|
488
|
+
if (tunnel !== current || !config.enabled || !registered) return
|
|
489
|
+
if (markOutdated(current)) return
|
|
490
|
+
relayRegistrations.noteFailure(targetUrl)
|
|
491
|
+
if (tunnel !== current) return; tunnelState = 'error'; tunnelError = relayFailureMessage('连接断开'); publishState(); scheduleReconnect()
|
|
488
492
|
// 中转在关掉之前说过「插件太旧」的话,这一档要改口径:状态另立成 outdated、复位成
|
|
489
493
|
// 三十分钟一次。markOutdated 自带实例身份闸,改完直接盖掉上面那句「连接断开」。
|
|
490
494
|
markOutdated(current)
|
|
@@ -499,7 +503,8 @@ function openTunnel(route) {
|
|
|
499
503
|
},
|
|
500
504
|
onLog: (...args) => process.stderr.write(`[dsh-ai-hub sidecar] ${args.join(' ')}\n`),
|
|
501
505
|
})
|
|
502
|
-
|
|
506
|
+
if (race) race.track(current, route)
|
|
507
|
+
else tunnel = current
|
|
503
508
|
const ready = current.start()
|
|
504
509
|
// 挂了就如实报,并按 5s 起退避重连(旧实现在 startTunnel 的 catch 里做同一件事)。
|
|
505
510
|
// 换地址失败时这里也会排一次:配置里已经是新地址,值得继续试它,而不是悄悄退回旧地址。
|
|
@@ -507,11 +512,11 @@ function openTunnel(route) {
|
|
|
507
512
|
// 择路的**中间**那几条失败不吭声:状态只在「全部都不通」时才报 error。逐个报会让
|
|
508
513
|
// /status 在 error / connecting 之间来回跳,宿主那边「隧道刚连上就补推一次全量」的
|
|
509
514
|
// 边沿账会被这条假跳变带乱。它不改状态,所以排在实例身份闸前面无妨。
|
|
510
|
-
if (
|
|
515
|
+
if (race) return
|
|
511
516
|
if (tunnel !== current) return
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
517
|
+
if (markOutdated(current)) return
|
|
518
|
+
relayRegistrations.noteFailure(targetUrl)
|
|
519
|
+
if (tunnel !== current) return; tunnelState = 'error'; tunnelError = relayFailureMessage(error); publishState(); scheduleReconnect()
|
|
515
520
|
})
|
|
516
521
|
return ready
|
|
517
522
|
}
|
|
@@ -523,22 +528,16 @@ function startTunnel() {
|
|
|
523
528
|
if (!relayRoutePlan().length) { stopTunnel(); return }
|
|
524
529
|
stopTunnel(); tunnelState = 'connecting'
|
|
525
530
|
publishState()
|
|
526
|
-
//
|
|
527
|
-
// 探测本身失败不回滚这次连接(catch 吞掉),别忘了探完还要判一次 enabled。
|
|
528
|
-
// 记下这一代:探测期间若又发生重建(世代号前进),这条链就作废,别去开同实例的第二条隧道。
|
|
531
|
+
// 健康探测只作旁路证据,不再先扫完整个池才开始注册;旧代探测不能覆盖新代缓存。
|
|
529
532
|
const generation = tunnelGeneration
|
|
530
|
-
void (
|
|
531
|
-
|
|
532
|
-
if (generation !== tunnelGeneration || !config.enabled) return
|
|
533
|
-
await raceTunnels(generation)
|
|
534
|
-
})()
|
|
533
|
+
void refreshRelayLatency(generation).catch(() => {})
|
|
534
|
+
void raceTunnels(generation)
|
|
535
535
|
}
|
|
536
536
|
/**
|
|
537
537
|
* 一次配置里可以按优先级试的中转地址。
|
|
538
538
|
*
|
|
539
|
-
*
|
|
540
|
-
*
|
|
541
|
-
* 下一次 `startTunnel` 会先重新探测再进来。
|
|
539
|
+
* 候选同时考虑最近健康延迟与独立注册失败证据;健康证据过期后保留失败账与配置原序。
|
|
540
|
+
* 探测与注册并行,健康成功不能冲掉隧道注册失败,失败候选仍保留以供后续重试。
|
|
542
541
|
*
|
|
543
542
|
* `relayUrls` 缺席或为空(老宿主只下发 `relayUrl`)时退回单元素 —— 契约里那条兼容口径。
|
|
544
543
|
* 已按 `core.normalizeRelayUrl` 规范化并用它拼 `tunnelWsUrl`,脏地址在这里就被丢掉而不是
|
|
@@ -561,28 +560,29 @@ function relayRoutePlan() {
|
|
|
561
560
|
}
|
|
562
561
|
// 延迟结果还在保鲜期就按最快优先给出候选顺序;过期就按原序,等下次 startTunnel 重探。
|
|
563
562
|
// 只影响尝试顺序,不改地址本身,也不改去重 / 过滤的结果。
|
|
564
|
-
|
|
565
|
-
return urls
|
|
563
|
+
return relayRegistrations.order(urls, performance.now() - relayLatencyAt < 300000 ? relayLatencyCache : new Map())
|
|
566
564
|
}
|
|
567
565
|
/**
|
|
568
|
-
*
|
|
566
|
+
* 并发探当前候选中转的身份健康响应,把实测延迟写进缓存;不改变注册失败账。
|
|
569
567
|
*
|
|
570
568
|
* 每条独立超时(1500ms);某条探测失败只是这条记成 null(不可达、排后面),不影响其它条,
|
|
571
569
|
* 也不阻止这次连接(排序函数会把它们稳定地排在后面,失败仍由 raceTunnels 顺延到下一台)。
|
|
572
570
|
*/
|
|
573
|
-
async function refreshRelayLatency() {
|
|
571
|
+
async function refreshRelayLatency(generation) {
|
|
574
572
|
const urls = relayRoutePlan()
|
|
575
573
|
// 并发**分段**探,不一次性全打出去:地址池将来可能按地区变多,全并发会在同一瞬间打出一堆
|
|
576
574
|
// 连接(对自己的中转也等于一次小 DDoS),把 worker 的连接/内存压垮。每段最多 6 条同时探,
|
|
577
575
|
// 段内并发、段间顺序;每条的 1.5s 超时照旧只约束单条。
|
|
578
576
|
const results = new Map()
|
|
579
577
|
for (let index = 0; index < urls.length; index += PROBE_CONCURRENCY) {
|
|
578
|
+
if (generation !== tunnelGeneration || !config.enabled) return
|
|
580
579
|
const batch = urls.slice(index, index + PROBE_CONCURRENCY)
|
|
581
580
|
const probed = await Promise.all(batch.map(async (url) => [url, await probeRelayHealth(url, { timeoutMs: 1500 })]))
|
|
582
581
|
for (const [url, ms] of probed) results.set(url, ms)
|
|
583
582
|
}
|
|
583
|
+
if (generation !== tunnelGeneration || !config.enabled) return
|
|
584
584
|
relayLatencyCache = results
|
|
585
|
-
relayLatencyAt =
|
|
585
|
+
relayLatencyAt = performance.now()
|
|
586
586
|
}
|
|
587
587
|
/**
|
|
588
588
|
* 这一轮选中的中转写成当前主用,并把它**提到队首**,其余条目相对顺序不动。
|
|
@@ -622,78 +622,117 @@ function adoptRoute(route) {
|
|
|
622
622
|
adopted,
|
|
623
623
|
}
|
|
624
624
|
}
|
|
625
|
-
/**
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
* 回调全被 `tunnel !== current` 挡掉(那道闸是 `/status` 不撒谎的唯一保障)。这里只在真的
|
|
630
|
-
* 试下一条之前把上一个实例停掉,避免它还在握手时又开一条。
|
|
631
|
-
*
|
|
632
|
-
* 全部不通:状态由最后一次失败的 catch 置成 `error` 并排好退避重连;`startTunnel` 下一次
|
|
633
|
-
* 会**从列表第一条重新开始**(`tunnelRoute` 在 `stopTunnel` 里作废),不许记住「上次卡在
|
|
634
|
-
* 第几条」。
|
|
635
|
-
*/
|
|
636
|
-
async function raceTunnels(generation) {
|
|
625
|
+
/** 无已连线路时最多三条并行注册;唯一赢家接管,输家与旧代立即停止。 */
|
|
626
|
+
async function raceTunnels(generation = tunnelGeneration) {
|
|
627
|
+
if (!config.enabled) return false
|
|
628
|
+
if (generation !== tunnelGeneration) return false
|
|
637
629
|
const urls = relayRoutePlan()
|
|
638
630
|
if (!urls.length) { stopTunnel(); return false }
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
const
|
|
648
|
-
|
|
649
|
-
const
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
if (
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
631
|
+
return new Promise((resolve) => {
|
|
632
|
+
const active = new Map()
|
|
633
|
+
const waiting = urls.map((url, index) => ({ url, index }))
|
|
634
|
+
const authorityOf = (url) => { try { return new URL(url).host.toLowerCase() } catch { return url } }
|
|
635
|
+
let next = 0
|
|
636
|
+
let finished = false
|
|
637
|
+
let lastError = new Error('中转注册失败')
|
|
638
|
+
const latestStart = performance.now() + RELAY_RACE_TIMEOUT_MS - 8000
|
|
639
|
+
const valid = () => generation === tunnelGeneration && config.enabled
|
|
640
|
+
const stopOthers = (winner) => {
|
|
641
|
+
for (const current of active.values()) if (current !== winner) { try { current.stop() } catch {} }
|
|
642
|
+
active.clear()
|
|
643
|
+
}
|
|
644
|
+
const finish = (success, winner) => {
|
|
645
|
+
if (finished) return
|
|
646
|
+
finished = true
|
|
647
|
+
clearTimeout(timer)
|
|
648
|
+
if (relayRace === race) relayRace = null
|
|
649
|
+
stopOthers(winner)
|
|
650
|
+
resolve(success)
|
|
651
|
+
}
|
|
652
|
+
const failRound = () => {
|
|
653
|
+
if (!valid()) { finish(false); return }
|
|
654
|
+
finish(false)
|
|
655
|
+
tunnelState = 'error'; tunnelError = relayFailureMessage(lastError)
|
|
656
|
+
publishState(); scheduleReconnect()
|
|
657
|
+
}
|
|
658
|
+
const race = {
|
|
659
|
+
track(current, route) { active.set(route, current) },
|
|
660
|
+
accept(current) {
|
|
661
|
+
if (finished || !valid() || ![...active.values()].includes(current)) { current.stop(); return false }
|
|
662
|
+
tunnel = current
|
|
663
|
+
finish(true, current)
|
|
664
|
+
return true
|
|
665
|
+
},
|
|
666
|
+
cancel() { finish(false) },
|
|
667
|
+
}
|
|
668
|
+
relayRace = race
|
|
669
|
+
const timer = setTimeout(() => {
|
|
670
|
+
if (!valid()) { finish(false); return }
|
|
671
|
+
// 只有仍在真实等待的注册才记超时;未启动候选与主动取消的输家不记失败。
|
|
672
|
+
for (const [route] of active) relayRegistrations.noteFailure(route.url)
|
|
673
|
+
lastError = new Error('中转择路超时')
|
|
674
|
+
failRound()
|
|
675
|
+
}, RELAY_RACE_TIMEOUT_MS)
|
|
676
|
+
const launch = () => {
|
|
677
|
+
if (finished) return
|
|
678
|
+
if (!valid()) { finish(false); return }
|
|
679
|
+
// 不在整轮将结束时新开一条只剩碎片预算的注册;未试到的候选留在下轮,失败账会轮换优先级。
|
|
680
|
+
while (!finished && active.size < RELAY_RACE_CONCURRENCY && waiting.length && performance.now() <= latestStart) {
|
|
681
|
+
const busy = new Set([...active.keys()].map(route => authorityOf(route.url)))
|
|
682
|
+
const at = waiting.findIndex(candidate => !busy.has(authorityOf(candidate.url)))
|
|
683
|
+
if (at < 0) break // 同一中转的多个入口串行,避免同实例注册互相顶替。
|
|
684
|
+
const { url, index } = waiting.splice(at, 1)[0]
|
|
685
|
+
const route = { url, index, tried: ++next, urls }
|
|
686
|
+
let attempt
|
|
687
|
+
try { attempt = openTunnel(route, race) } catch (error) {
|
|
688
|
+
lastError = error
|
|
689
|
+
relayRegistrations.noteFailure(route.url)
|
|
690
|
+
const current = active.get(route)
|
|
691
|
+
active.delete(route)
|
|
692
|
+
try { current?.stop() } catch {}
|
|
693
|
+
continue
|
|
694
|
+
}
|
|
695
|
+
const current = active.get(route)
|
|
696
|
+
Promise.resolve(attempt).catch((error) => {
|
|
697
|
+
if (finished) return
|
|
698
|
+
if (!valid()) { finish(false); return }
|
|
699
|
+
active.delete(route)
|
|
700
|
+
lastError = error
|
|
701
|
+
if (current?.lastControlError?.code === 'plugin_too_old') {
|
|
702
|
+
// 版本门槛保持原有停轮与专用重试节奏,不把它当网络失败。
|
|
703
|
+
finish(false)
|
|
704
|
+
tunnel = current
|
|
705
|
+
markOutdated(current)
|
|
706
|
+
current.stop()
|
|
707
|
+
return
|
|
708
|
+
}
|
|
709
|
+
relayRegistrations.noteFailure(route.url)
|
|
710
|
+
try { current?.stop() } catch {}
|
|
711
|
+
launch()
|
|
712
|
+
})
|
|
678
713
|
}
|
|
714
|
+
if (!finished && !active.size) failRound()
|
|
679
715
|
}
|
|
680
|
-
|
|
681
|
-
|
|
716
|
+
launch()
|
|
717
|
+
})
|
|
682
718
|
}
|
|
683
719
|
async function startLan() {
|
|
684
720
|
await stopLan()
|
|
685
|
-
if (!config.enabled || !config.
|
|
721
|
+
if (!config.enabled || !config.upstreamPort) return
|
|
686
722
|
const own = lanGeneration
|
|
687
723
|
lanRequestedPort = config.lanPort
|
|
688
724
|
lanState = 'connecting'
|
|
689
|
-
const discovery =
|
|
725
|
+
const discovery = config.lanEnabled
|
|
726
|
+
? createLanDiscovery({ instanceId: config.instanceId, onChange: publishState })
|
|
727
|
+
: { publish: async () => false, stop: async () => {}, snapshot: () => ({ state: 'off', error: null }) }
|
|
690
728
|
lanDiscovery = discovery
|
|
691
729
|
publishState()
|
|
692
730
|
try {
|
|
693
731
|
const result = await bindLanEndpoint({
|
|
694
|
-
requestedPort: config.lanPort, discovery, store: credentials, instanceId: config.instanceId,
|
|
732
|
+
requestedPort: config.lanPort, lockReason: config.lanPortLockReason || '', discovery, store: credentials, instanceId: config.instanceId,
|
|
695
733
|
isCurrent: () => own === lanGeneration,
|
|
696
734
|
createProxy: port => createLanProxy({
|
|
735
|
+
ipv4Enabled: Boolean(config.lanEnabled),
|
|
697
736
|
lanPort: port, instanceId: config.instanceId, previousInstanceId: config.previousInstanceId || '', lanSecret: config.lanSecret,
|
|
698
737
|
// 配对码与票据走取值器:配对成功之后宿主会换掉它们(§5.1),而重建局域网代理会把
|
|
699
738
|
// 刚握上的连接全掐掉 —— 换值不该动监听。
|
|
@@ -745,7 +784,7 @@ async function configure(next) {
|
|
|
745
784
|
// `relayUrls` 在白名单里,而且从这一轮起**进签名**(见 tunnelSignature):地址组或它的
|
|
746
785
|
// 顺序变了就要重新择路。白名单缺了它,宿主下发这一格会直接抛 unknown configuration
|
|
747
786
|
// field,整次配置下发失败。
|
|
748
|
-
const allowed = ['enabled', 'relayUrl', 'relayUrls', 'instanceId', 'previousInstanceId', 'pairingCode', 'pairingTicket', 'pairingTier', 'name', 'upstreamPort', 'upstreamHost', 'lanPort', 'lanEnabled', 'lanSecret', 'registerSecret']
|
|
787
|
+
const allowed = ['enabled', 'relayUrl', 'relayUrls', 'instanceId', 'previousInstanceId', 'pairingCode', 'pairingTicket', 'pairingTier', 'name', 'upstreamPort', 'upstreamHost', 'lanPort', 'lanPortLockReason', 'lanEnabled', 'lanSecret', 'registerSecret']
|
|
749
788
|
if (Object.keys(next).some(key => !allowed.includes(key))) throw new Error('unknown configuration field')
|
|
750
789
|
if (typeof next.instanceId !== 'string' || next.instanceId.length > 128) throw new Error('invalid instanceId')
|
|
751
790
|
if (next.previousInstanceId !== undefined && (typeof next.previousInstanceId !== 'string' || next.previousInstanceId.length > 128)) throw new Error('invalid previousInstanceId')
|
|
@@ -792,7 +831,7 @@ async function configure(next) {
|
|
|
792
831
|
startTunnel()
|
|
793
832
|
}
|
|
794
833
|
}
|
|
795
|
-
if (lanNeedsRebuild || (config.enabled &&
|
|
834
|
+
if (lanNeedsRebuild || (config.enabled && lanState === 'error')) {
|
|
796
835
|
await startLan()
|
|
797
836
|
}
|
|
798
837
|
if (!tunnelNeedsRebuild && tunnel) {
|
|
@@ -821,7 +860,7 @@ function status() {
|
|
|
821
860
|
// 而宿主侧靠它判「当前连的不是队首 → 该写回了」。没试过(隧道没起来)时留空,
|
|
822
861
|
// 别让一份上上轮的账一直挂在那儿。
|
|
823
862
|
const route = tunnelRoute ? tunnelRoute : undefined
|
|
824
|
-
return { ok: true, sidecar: true, enabled: Boolean(config.enabled), relayUrl: config.relayUrl || '', relayUrls: Array.isArray(config.relayUrls) ? config.relayUrls : [], instanceId: config.instanceId, name: config.name, localPort: config.upstreamPort, tunnel: { state: tunnelState, error: tunnelError, mirror: relayMirror, ...(route ? { route } : {}) }, lan: { enabled: Boolean(config.lanEnabled), port: lanUrlPort(), requestedPort: lanRequestedPort || config.lanPort, state: lanState, error: lanError, discovery: lanDiscovery?.snapshot() || { state: 'off', error: null } }, process: { memoryUsage: process.memoryUsage() }, streams: { lan: lanStreams, relaySseOpen } }
|
|
863
|
+
return { ok: true, sidecar: true, enabled: Boolean(config.enabled), relayUrl: config.relayUrl || '', relayUrls: Array.isArray(config.relayUrls) ? config.relayUrls : [], instanceId: config.instanceId, name: config.name, localPort: config.upstreamPort, tunnel: { state: tunnelState, error: tunnelError, mirror: relayMirror, relayUrl: tunnelState === 'connected' ? connectedRelayUrl : null, ...(route ? { route } : {}) }, lan: { enabled: Boolean(config.lanEnabled), port: lanUrlPort(), requestedPort: lanRequestedPort || config.lanPort, state: lanState, error: lanError, discovery: lanDiscovery?.snapshot() || { state: 'off', error: null } }, process: { memoryUsage: process.memoryUsage() }, streams: { lan: lanStreams, relaySseOpen } }
|
|
825
864
|
}
|
|
826
865
|
const server = http.createServer(async (req, res) => {
|
|
827
866
|
try {
|
|
@@ -844,12 +883,20 @@ const server = http.createServer(async (req, res) => {
|
|
|
844
883
|
if (tunnel && tunnel.connected) {
|
|
845
884
|
// 历史 blob(HK 加密):单独一条 `blobPut` 帧,中转只存密文、不解析内容。
|
|
846
885
|
if (body && typeof body === 'object' && body.kind === 'blob') {
|
|
847
|
-
|
|
886
|
+
const current = tunnel;
|
|
887
|
+
const result = await current.pushBlob({
|
|
848
888
|
scope: body.scope,
|
|
849
889
|
key: body.key,
|
|
850
890
|
creds: Array.isArray(body.creds) ? body.creds : [],
|
|
851
891
|
cipher: body.cipher,
|
|
852
892
|
});
|
|
893
|
+
if (tunnel !== current || !current.connected) throw new Error('blob tunnel changed');
|
|
894
|
+
return send(res, 200, result);
|
|
895
|
+
}
|
|
896
|
+
if (body && typeof body === 'object' && body.kind === 'blob-delete') {
|
|
897
|
+
if (!tunnel.sendJson(T.blobDelete, 0, { scope: body.scope, key: body.key, keys: body.keys })) {
|
|
898
|
+
throw new Error('blob delete backpressure or closed');
|
|
899
|
+
}
|
|
853
900
|
return send(res, 202, { ok: true });
|
|
854
901
|
}
|
|
855
902
|
// kind === 'push' 是 iOS 推送帧(pushRegister / pushSend),帧类型由 pushFrame
|
package/lib/sidecar-facade.cjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// blob RPC等待最终确认;本机请求超时不伪报成功。
|
|
1
2
|
'use strict'
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -152,7 +153,11 @@ class SidecarFacade {
|
|
|
152
153
|
|
|
153
154
|
/** 推一条 HK 加密的历史 blob:worker 在同一条隧道上发 `blobPut`(payload 只有密文)。 */
|
|
154
155
|
pushBlob(frame) {
|
|
155
|
-
return this.request('/tunnel/send', 'POST', { kind: 'blob', ...frame })
|
|
156
|
+
return this.request('/tunnel/send', 'POST', { kind: 'blob', ...frame }, 30 * 60_000)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
deleteBlobs(frame) {
|
|
160
|
+
return this.request('/tunnel/send', 'POST', { kind: 'blob-delete', ...frame })
|
|
156
161
|
}
|
|
157
162
|
|
|
158
163
|
async configure(config) {
|
|
@@ -36,6 +36,10 @@ const HEALTH_POLL_INTERVAL_MS = 10000;
|
|
|
36
36
|
*/
|
|
37
37
|
function createSidecarLifecycle(deps = {}) {
|
|
38
38
|
const { ctx } = deps;
|
|
39
|
+
// 父进程端口在构造时取一次就缓存。自重启常发生在换代之后,那时旧 context 已 inactive,
|
|
40
|
+
// 再读 ctx.webServer 会抛 "cannot get required service webServer in inactive context",
|
|
41
|
+
// 让整个重启失败——隧道、frpc(TCP 直连)和 P2P 助手都跟着起不来。同一进程里端口不会变。
|
|
42
|
+
const parentPort = ctx.webServer.port;
|
|
39
43
|
// 传输进程归**稳定外壳**持有时,配置来源会在每一次换代后由新的一代重新注入:所以这里
|
|
40
44
|
// 做成可变对象,构造期给的值只是初值(外壳起的那一次用)。换代只 `setProviders`+`sync`,
|
|
41
45
|
// 配置签名不变 → worker 的 configure 不重建隧道、不重建局域网,连接跨代存活。
|
|
@@ -127,7 +131,7 @@ function createSidecarLifecycle(deps = {}) {
|
|
|
127
131
|
// 同一份历史里「择路选中了非队首」这件事也在这条路上报上来,写回由装配层订阅。
|
|
128
132
|
noteRouteAdopted(message.tunnel.route)
|
|
129
133
|
}
|
|
130
|
-
let sidecar = new SidecarFacade({ parentPort
|
|
134
|
+
let sidecar = new SidecarFacade({ parentPort, token: sidecarToken, onDown: markSidecarDown, onState: applyTunnelState })
|
|
131
135
|
// sidecar 自重启的账:几次、什么时候、上次成没成。自重启是运维动作(改完代码不想
|
|
132
136
|
// 逼用户重启整个 DSH),出问题时「刚才那次重启到底把哪一段换掉了」必须查得到。
|
|
133
137
|
let sidecarRestarts = 0
|
|
@@ -221,7 +225,7 @@ function createSidecarLifecycle(deps = {}) {
|
|
|
221
225
|
// 重新 require 的是 facade 及其依赖(relay/tunnel 等)——缓存已清,拿到的
|
|
222
226
|
// 是磁盘上的新代码。worker 更是直接 re-fork,天然是新的。
|
|
223
227
|
const Fresh = require('./sidecar-facade.cjs').SidecarFacade
|
|
224
|
-
sidecar = new Fresh({ parentPort
|
|
228
|
+
sidecar = new Fresh({ parentPort, token: sidecarToken, onDown: markSidecarDown, onState: applyTunnelState })
|
|
225
229
|
sidecarState = 'starting'
|
|
226
230
|
await sidecar.start()
|
|
227
231
|
await syncSidecar()
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 助手重启读取当前已持久身份与白名单,按 peer 保留 IPC 生命周期。
|
|
1
2
|
'use strict';
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -60,6 +61,7 @@ const EVENT_KEYS = {
|
|
|
60
61
|
const OPTIONAL_EVENT_KEYS = {
|
|
61
62
|
p2pReady: ['peerKey'],
|
|
62
63
|
p2pStatus: ['peerKey'],
|
|
64
|
+
p2pStopped: ['peerKey'],
|
|
63
65
|
};
|
|
64
66
|
|
|
65
67
|
const ADDRESS = /^tc[\x21-\x7e]{0,4095}$/;
|
|
@@ -130,6 +132,10 @@ function createTailcatHost(options) {
|
|
|
130
132
|
let restartTimer;
|
|
131
133
|
let ready = false;
|
|
132
134
|
let address = '';
|
|
135
|
+
let currentState = options.state === undefined ? null : options.state;
|
|
136
|
+
let currentAllowed = Array.isArray(options.allowedClients) ? [...options.allowedClients] : [];
|
|
137
|
+
const pendingPersists = new Map();
|
|
138
|
+
const launchProcess = options.spawn || spawn;
|
|
133
139
|
|
|
134
140
|
const status = () => ({ available: Boolean(binary), running: Boolean(child), ready, address, restarts });
|
|
135
141
|
|
|
@@ -150,7 +156,10 @@ function createTailcatHost(options) {
|
|
|
150
156
|
if (typeof kind !== 'string' || !EVENT_KEYS[kind]) return;
|
|
151
157
|
const keys = Object.keys(value);
|
|
152
158
|
const fields = EVENT_KEYS[kind];
|
|
153
|
-
//
|
|
159
|
+
// 已发布的旧助手只回 running:false;仅这一个空形态补齐,运行态仍须完整。
|
|
160
|
+
if (kind === 'p2pStatus' && value.running === false) {
|
|
161
|
+
value = { url: '', path: 'unknown', active: false, detail: '', candidates: [], ...value };
|
|
162
|
+
}
|
|
154
163
|
if (fields.some(field => !(field in value))) return;
|
|
155
164
|
const optional = OPTIONAL_EVENT_KEYS[kind] || [];
|
|
156
165
|
const extra = keys.filter(key => key !== 'event' && !fields.includes(key) && !optional.includes(key));
|
|
@@ -170,6 +179,7 @@ function createTailcatHost(options) {
|
|
|
170
179
|
} else if (kind === 'persist') {
|
|
171
180
|
if (typeof value.id !== 'string' || value.id.length > 32) return;
|
|
172
181
|
if (!Array.isArray(value.allowedClients)) return;
|
|
182
|
+
pendingPersists.set(value.id, { state: value.state, allowed: [...value.allowedClients] });
|
|
173
183
|
} else if (kind === 'error') {
|
|
174
184
|
if (typeof value.code !== 'string') return;
|
|
175
185
|
// 助手的失败原因可能是底层网络 / 证书报错这类长串(例如取 DERP 地图时 x509 证书校验失败,
|
|
@@ -197,7 +207,7 @@ function createTailcatHost(options) {
|
|
|
197
207
|
if (closed || !binary) return;
|
|
198
208
|
let proc;
|
|
199
209
|
try {
|
|
200
|
-
proc =
|
|
210
|
+
proc = launchProcess(binary, [], { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
|
|
201
211
|
} catch {
|
|
202
212
|
scheduleRestart();
|
|
203
213
|
return;
|
|
@@ -225,12 +235,19 @@ function createTailcatHost(options) {
|
|
|
225
235
|
address = '';
|
|
226
236
|
if (!closed) scheduleRestart();
|
|
227
237
|
});
|
|
238
|
+
pendingPersists.clear();
|
|
239
|
+
// 外壳跨实现代存活:每次拉起都以插件当前存储为准。
|
|
240
|
+
const latest = typeof options.readState === 'function' ? options.readState() : null;
|
|
241
|
+
if (latest) {
|
|
242
|
+
currentState = latest.identity === undefined ? currentState : latest.identity;
|
|
243
|
+
if (Array.isArray(latest.allowed)) currentAllowed = [...latest.allowed];
|
|
244
|
+
}
|
|
228
245
|
write({
|
|
229
246
|
version: IPC_VERSION,
|
|
230
247
|
localPort: options.localPort,
|
|
231
248
|
name: String(options.name || os.hostname()).slice(0, 64),
|
|
232
|
-
state:
|
|
233
|
-
allowedClients:
|
|
249
|
+
state: currentState,
|
|
250
|
+
allowedClients: currentAllowed,
|
|
234
251
|
});
|
|
235
252
|
}
|
|
236
253
|
|
|
@@ -249,10 +266,17 @@ function createTailcatHost(options) {
|
|
|
249
266
|
},
|
|
250
267
|
/** 换白名单(吊销手机就走这条)。 */
|
|
251
268
|
setAllowed(allowedClients) {
|
|
252
|
-
|
|
269
|
+
currentAllowed = Array.isArray(allowedClients) ? [...allowedClients] : [];
|
|
270
|
+
write({ command: 'setAllowed', allowedClients: currentAllowed });
|
|
253
271
|
},
|
|
254
|
-
/**
|
|
272
|
+
/** 只有存储确认成功的身份可用于下一次拉起。 */
|
|
255
273
|
ack(id, ok) {
|
|
274
|
+
const pending = pendingPersists.get(id);
|
|
275
|
+
pendingPersists.delete(id);
|
|
276
|
+
if (ok && pending) {
|
|
277
|
+
if (typeof pending.state === 'string' && pending.state) currentState = pending.state;
|
|
278
|
+
currentAllowed = pending.allowed;
|
|
279
|
+
}
|
|
256
280
|
write({ command: 'ack', id, ok: Boolean(ok) });
|
|
257
281
|
},
|
|
258
282
|
/**
|
|
@@ -274,8 +298,8 @@ function createTailcatHost(options) {
|
|
|
274
298
|
p2pTargetPort: Number(options.targetPort) || 0,
|
|
275
299
|
});
|
|
276
300
|
},
|
|
277
|
-
stopP2P() {
|
|
278
|
-
write({ command: 'p2pStop' });
|
|
301
|
+
stopP2P(peerKey) {
|
|
302
|
+
write({ command: 'p2pStop', ...(peerKey ? { p2pPeerKey: String(peerKey) } : {}) });
|
|
279
303
|
},
|
|
280
304
|
statusP2P() {
|
|
281
305
|
write({ command: 'p2pStatus' });
|