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
package/lib/relay/relay-probe.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
|
+
// 中转健康响应与注册失败分账,延迟、冷却和衰减均按单调经过时间计算。
|
|
1
2
|
'use strict'
|
|
2
|
-
// 公用中转「电脑决定」的延迟探测:worker
|
|
3
|
-
//
|
|
3
|
+
// 公用中转「电脑决定」的延迟探测:worker 连中转前先量各候选的健康响应延迟,
|
|
4
|
+
// 把最快的那台排在前面再连。健康响应不代表隧道注册成功,注册失败证据由调用方单独保存。
|
|
4
5
|
//
|
|
5
6
|
// 两件事分开:`orderByLatency` 是纯函数(只排顺序、不碰网络),`probeRelayHealth` 是薄探测
|
|
6
|
-
// (发一次 GET
|
|
7
|
+
// (发一次 GET、校验完整响应,失败返回 null)。探测结果交给排序函数,两者互不依赖。
|
|
7
8
|
|
|
8
9
|
const http = require('node:http')
|
|
9
10
|
const https = require('node:https')
|
|
11
|
+
const { performance } = require('node:perf_hooks')
|
|
10
12
|
|
|
11
13
|
/**
|
|
12
14
|
* 按实测延迟给候选地址排序:量到延迟的按升序在前,不可达 / 没量到的排后面。
|
|
@@ -36,51 +38,140 @@ function orderByLatency(urls, latencyByUrl) {
|
|
|
36
38
|
return [...reachable.map((item) => item.url), ...unreachable]
|
|
37
39
|
}
|
|
38
40
|
|
|
41
|
+
const RELAY_HEALTH_SERVICE = 'dsh-mobile-relay'
|
|
42
|
+
const MAX_HEALTH_BODY_BYTES = 16 * 1024
|
|
43
|
+
|
|
39
44
|
/**
|
|
40
|
-
*
|
|
45
|
+
* 对现有 `/api/mobile/v1/health` 发一次 GET,只认 2xx、ok 与中转固定服务名。
|
|
41
46
|
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
47
|
+
* 校验完整的小响应体后才接受首字节延迟;不跟随重定向,避免把门户页当成健康中转。
|
|
48
|
+
* 一个总定时器覆盖 DNS、连接、响应头和响应体,滴流也不能延长探测预算。
|
|
44
49
|
*
|
|
45
50
|
* @param {string} url 中转地址
|
|
46
|
-
* @param {{ timeoutMs?: number }} [options]
|
|
47
|
-
* @returns {Promise<number|null>}
|
|
51
|
+
* @param {{ timeoutMs?: number }} [options] 总超时毫秒,默认 1500
|
|
52
|
+
* @returns {Promise<number|null>} 首字节延迟毫秒,或 null
|
|
48
53
|
*/
|
|
49
54
|
function probeRelayHealth(url, options = {}) {
|
|
50
|
-
const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 1500
|
|
55
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 1500
|
|
51
56
|
return new Promise((resolve) => {
|
|
52
57
|
let healthUrl
|
|
53
58
|
try {
|
|
54
|
-
healthUrl = new URL(`${String(url).replace(/\/+$/, '')}/
|
|
59
|
+
healthUrl = new URL(`${String(url).replace(/\/+$/, '')}/api/mobile/v1/health`)
|
|
60
|
+
if (healthUrl.protocol !== 'http:' && healthUrl.protocol !== 'https:') {
|
|
61
|
+
resolve(null)
|
|
62
|
+
return
|
|
63
|
+
}
|
|
55
64
|
} catch {
|
|
56
65
|
resolve(null)
|
|
57
66
|
return
|
|
58
67
|
}
|
|
59
68
|
const client = healthUrl.protocol === 'https:' ? https : http
|
|
60
|
-
const startedAt =
|
|
69
|
+
const startedAt = performance.now()
|
|
61
70
|
let settled = false
|
|
71
|
+
let req
|
|
72
|
+
let response
|
|
62
73
|
const finish = (value) => {
|
|
63
74
|
if (settled) return
|
|
64
75
|
settled = true
|
|
76
|
+
clearTimeout(timer)
|
|
77
|
+
if (value === null) {
|
|
78
|
+
if (response) response.destroy()
|
|
79
|
+
if (req) req.destroy()
|
|
80
|
+
}
|
|
65
81
|
resolve(value)
|
|
66
82
|
}
|
|
67
|
-
|
|
83
|
+
const timer = setTimeout(() => finish(null), timeoutMs)
|
|
68
84
|
try {
|
|
69
85
|
// agent:false:一次性连接,探完就关,别把 keep-alive 的 socket 留在进程里。
|
|
70
86
|
req = client.get(healthUrl, { agent: false }, (res) => {
|
|
71
|
-
res
|
|
72
|
-
|
|
87
|
+
response = res
|
|
88
|
+
const latency = performance.now() - startedAt
|
|
89
|
+
let size = 0
|
|
90
|
+
const chunks = []
|
|
91
|
+
res.on('error', () => finish(null))
|
|
92
|
+
res.on('aborted', () => finish(null))
|
|
93
|
+
res.on('close', () => { if (!res.complete) finish(null) })
|
|
94
|
+
if (!(res.statusCode >= 200 && res.statusCode < 300)) {
|
|
95
|
+
finish(null)
|
|
96
|
+
return
|
|
97
|
+
}
|
|
98
|
+
if (Number(res.headers['content-length']) > MAX_HEALTH_BODY_BYTES) {
|
|
99
|
+
finish(null)
|
|
100
|
+
return
|
|
101
|
+
}
|
|
102
|
+
res.on('data', (chunk) => {
|
|
103
|
+
if (settled) return
|
|
104
|
+
size += chunk.length
|
|
105
|
+
if (size > MAX_HEALTH_BODY_BYTES) {
|
|
106
|
+
finish(null)
|
|
107
|
+
return
|
|
108
|
+
}
|
|
109
|
+
chunks.push(chunk)
|
|
110
|
+
})
|
|
111
|
+
res.on('end', () => {
|
|
112
|
+
if (settled) return
|
|
113
|
+
try {
|
|
114
|
+
const body = JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
115
|
+
finish(body && body.ok === true && body.service === RELAY_HEALTH_SERVICE ? latency : null)
|
|
116
|
+
} catch {
|
|
117
|
+
finish(null)
|
|
118
|
+
}
|
|
119
|
+
})
|
|
73
120
|
})
|
|
121
|
+
req.on('error', () => finish(null))
|
|
74
122
|
} catch {
|
|
75
123
|
finish(null)
|
|
76
|
-
return
|
|
77
124
|
}
|
|
78
|
-
req.on('error', () => finish(null))
|
|
79
|
-
req.setTimeout(timeoutMs, () => {
|
|
80
|
-
finish(null)
|
|
81
|
-
req.destroy()
|
|
82
|
-
})
|
|
83
125
|
})
|
|
84
126
|
}
|
|
85
127
|
|
|
86
|
-
|
|
128
|
+
/** 注册失败与健康延迟分账:只有真实注册成功清账,失败成本随时间衰减。 */
|
|
129
|
+
function createRelayRegistrationLedger({ now = () => performance.now() } = {}) {
|
|
130
|
+
const failures = new Map()
|
|
131
|
+
const penaltyOf = (url) => {
|
|
132
|
+
const fact = failures.get(url)
|
|
133
|
+
if (!fact) return 0
|
|
134
|
+
const count = Math.max(0, fact.count - Math.floor(Math.max(0, now() - fact.at) / 300000))
|
|
135
|
+
if (!count) failures.delete(url)
|
|
136
|
+
return count * 8000
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
noteFailure(url) {
|
|
140
|
+
const count = penaltyOf(url) / 8000
|
|
141
|
+
failures.set(url, { count: Math.min(4, count + 1), at: now() })
|
|
142
|
+
},
|
|
143
|
+
noteSuccess(url) { failures.delete(url) },
|
|
144
|
+
order(urls, latencyByUrl) {
|
|
145
|
+
const latency = (url) => latencyByUrl instanceof Map ? latencyByUrl.get(url) : latencyByUrl?.[url]
|
|
146
|
+
const measured = urls.map(latency).filter((ms) => typeof ms === 'number' && Number.isFinite(ms) && ms >= 0)
|
|
147
|
+
const unknown = Math.max(1500, ...measured) + 1
|
|
148
|
+
const cost = (url) => {
|
|
149
|
+
const ms = latency(url)
|
|
150
|
+
return (typeof ms === 'number' && Number.isFinite(ms) && ms >= 0 ? ms : unknown) + penaltyOf(url)
|
|
151
|
+
}
|
|
152
|
+
const present = new Set(urls)
|
|
153
|
+
for (const url of failures.keys()) if (!present.has(url)) failures.delete(url)
|
|
154
|
+
const cooling = (url) => penaltyOf(url) > 0 && Math.max(0, now() - failures.get(url).at) < 30000
|
|
155
|
+
return [...urls].sort((a, b) => {
|
|
156
|
+
const aCooling = cooling(a), bCooling = cooling(b)
|
|
157
|
+
if (aCooling !== bCooling) return aCooling ? 1 : -1
|
|
158
|
+
// 全部都在短冷却时照样重试,先试最久没失败的,封顶后也不能粘在固定前几条。
|
|
159
|
+
if (aCooling && bCooling && failures.get(a).at !== failures.get(b).at) return failures.get(a).at - failures.get(b).at
|
|
160
|
+
return cost(a) - cost(b)
|
|
161
|
+
})
|
|
162
|
+
},
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 只报告真实环境配置或代理失败证据,不输出代理地址与认证材料。 */
|
|
167
|
+
function relayFailureMessage(error, env = process.env) {
|
|
168
|
+
const message = String(error && typeof error.message === 'string' ? error.message : error || '连接失败')
|
|
169
|
+
if (message.includes('宿主中转与总控目前只支持直连出网')) return message
|
|
170
|
+
const configured = ['HTTPS_PROXY', 'HTTP_PROXY', 'ALL_PROXY', 'https_proxy', 'http_proxy', 'all_proxy']
|
|
171
|
+
.filter((name) => typeof env[name] === 'string' && env[name].trim())
|
|
172
|
+
if (!configured.length && !/\b407\b|proxy authentication|proxy connect/i.test(message)) return message
|
|
173
|
+
const evidence = configured.length ? `检测到环境代理 ${configured.join('、')}` : '对端返回代理认证或连接错误'
|
|
174
|
+
return `${message};${evidence}。宿主中转与总控目前只支持直连出网,未使用环境代理;请允许目标地址直连或更换可直连网络。`
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
module.exports = { orderByLatency, probeRelayHealth, createRelayRegistrationLedger, relayFailureMessage }
|
package/lib/relay/status.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 固定入口和目录发布确认与手机实际恢复状态分别呈现。
|
|
1
2
|
'use strict';
|
|
2
3
|
// 区分端口已启用和已配对手机完成连接验证。
|
|
3
4
|
|
|
@@ -117,15 +118,11 @@ function createStatusView(deps) {
|
|
|
117
118
|
relayRoute: sidecarSnapshot?.tunnel?.route ?? null,
|
|
118
119
|
name: state.name,
|
|
119
120
|
pairingPolicy: state.pairingPolicy === 'deny' ? 'deny' : 'code',
|
|
120
|
-
// 新配对设备的权限档位(只读 / 可答审批 / 全权)。面板据此显示并让电脑侧改。
|
|
121
|
-
// 未知值收敛回 full,老状态文件没这一格时也回 full(与配对签发同一口径)。
|
|
122
|
-
pairingTier: ['readonly', 'approve', 'full'].includes(state.pairingTier) ? state.pairingTier : 'full',
|
|
123
|
-
// 审批自动审阅档(默认关,见 lib/mobile/auto-review.js)。面板与手机设置页都读这一格
|
|
124
|
-
// 显示开关状态;非 true 一律当关,与 `configOf(state)` 的读法同一口径。
|
|
125
|
-
approvalAutoReview: state.approvalAutoReview === true,
|
|
126
121
|
// 「自动上报网络地址」(总控上报)开关状态。面板据此显示开关;非 false 一律当开,
|
|
127
122
|
// 与 `configOf(state)` 的读法同一口径(老状态文件没这一格时默认开)。
|
|
128
123
|
controlReportEnabled: state.controlReportEnabled !== false,
|
|
124
|
+
lanPortFixed: state.lanPortFixed === true,
|
|
125
|
+
lanPortLockReason: typeof deps.getLanPortLock === 'function' ? deps.getLanPortLock() : '',
|
|
129
126
|
// 桌面设置页那两颗侧边栏图标的显示开关。**只给桌面客户端读**,手机端不画它们;
|
|
130
127
|
// 老机器没落过这两格时按开处理,与 configOf 的默认值同一口径。
|
|
131
128
|
desktopPhoneIcon: state.desktopPhoneIcon !== false,
|
|
@@ -149,7 +146,7 @@ function createStatusView(deps) {
|
|
|
149
146
|
...(sidecarSnapshot.lan || {}),
|
|
150
147
|
port: lanPortInUse(),
|
|
151
148
|
adjusted: lanPortAdjusted,
|
|
152
|
-
...(deps.getLanRecovery ? { recovery: deps.getLanRecovery() } : {}),
|
|
149
|
+
...(deps.getLanRecovery ? { recovery: { ...deps.getLanRecovery(), directoryPublished: getControl?.()?.published === true } } : {}),
|
|
153
150
|
requestedPort: state.lanPort,
|
|
154
151
|
},
|
|
155
152
|
sidecar: {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 在隧道落点覆盖可信来源标记,区分固定的直连与点对点入口。
|
|
1
2
|
'use strict';
|
|
2
3
|
// 落点代理转给宿主 web 服务时跟随宿主实际绑定地址(不再写死回环),回环绑定行为不变。
|
|
3
4
|
|
|
@@ -42,6 +43,7 @@ const HOP_BY_HOP = new Set([
|
|
|
42
43
|
*/
|
|
43
44
|
function createTunnelForwarder(options) {
|
|
44
45
|
const upstreamPort = options.upstreamPort;
|
|
46
|
+
const via = options.via === 'p2p' ? 'p2p' : VIA_TUNNEL;
|
|
45
47
|
const upstreamHost = typeof options.upstreamHost === 'function'
|
|
46
48
|
? options.upstreamHost
|
|
47
49
|
: () => options.upstreamHost || DEFAULT_UPSTREAM_HOST;
|
|
@@ -62,7 +64,7 @@ function createTunnelForwarder(options) {
|
|
|
62
64
|
function forwardedHeaders(incoming) {
|
|
63
65
|
return withViaHeader(
|
|
64
66
|
Object.fromEntries(Object.entries(incoming).filter(([key, value]) => !HOP_BY_HOP.has(key) && value !== undefined)),
|
|
65
|
-
|
|
67
|
+
via,
|
|
66
68
|
upstreamOf(),
|
|
67
69
|
);
|
|
68
70
|
}
|
|
@@ -112,7 +114,7 @@ function createTunnelForwarder(options) {
|
|
|
112
114
|
lines.push(`${req.rawHeaders[at]}: ${req.rawHeaders[at + 1]}`);
|
|
113
115
|
}
|
|
114
116
|
lines.push(`Host: ${upstreamOf()}`);
|
|
115
|
-
lines.push(`${VIA_HEADER}: ${
|
|
117
|
+
lines.push(`${VIA_HEADER}: ${via}`);
|
|
116
118
|
// 头是按字节传的,Node 的 rawHeaders 就是 latin1 解出来的,按同一个编码写回。
|
|
117
119
|
return Buffer.from(`${lines.join('\r\n')}\r\n\r\n`, 'latin1');
|
|
118
120
|
}
|
package/lib/relay/tunnel.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 注册取消与单调心跳保持原语义,blob逐片确认独立于HTTP/WS请求。
|
|
1
2
|
'use strict';
|
|
2
3
|
// 中转隧道把请求转给宿主 web 服务时,上游地址跟随宿主实际绑定地址(可能不是回环)。
|
|
3
4
|
|
|
@@ -18,6 +19,8 @@
|
|
|
18
19
|
*/
|
|
19
20
|
|
|
20
21
|
const http = require('node:http');
|
|
22
|
+
const { performance } = require('node:perf_hooks');
|
|
23
|
+
const { BlobUpload } = require('./blob-upload.cjs');
|
|
21
24
|
const { WebSocket } = require('ws');
|
|
22
25
|
const { T, jsonFrame, encodeFrame, createFrameDecoder, parseJson, encodeClosePayload, decodeClosePayload } = require('./protocol.js');
|
|
23
26
|
const { isFreshRequest } = require('../shared/fresh-request');
|
|
@@ -100,6 +103,7 @@ class RelayTunnel {
|
|
|
100
103
|
this.onPairRequest = opts.onPairRequest || (() => {});
|
|
101
104
|
this.onLog = opts.onLog || (() => {});
|
|
102
105
|
this.ws = null;
|
|
106
|
+
this.cancelRegistration = null;
|
|
103
107
|
this.wsClients = new Map(); // relay 侧 ws id -> 上游 ws client
|
|
104
108
|
this.reqClients = new Map(); // relay 侧 http id -> { req, res }
|
|
105
109
|
this.sseClients = new Set();
|
|
@@ -122,6 +126,7 @@ class RelayTunnel {
|
|
|
122
126
|
this.lastControlError = null;
|
|
123
127
|
// 清除所有授权的等待回调(一次一个);由 requestRevokeAll 注入,revokeAllAck 触发。
|
|
124
128
|
this._revokeAllAck = null;
|
|
129
|
+
this.blobUpload = new BlobUpload(this);
|
|
125
130
|
}
|
|
126
131
|
|
|
127
132
|
log(...args) {
|
|
@@ -167,6 +172,7 @@ class RelayTunnel {
|
|
|
167
172
|
trySendJson(type, id, obj) {
|
|
168
173
|
try { return this.trySendEncodedFrame(jsonFrame(type, id, obj)); } catch { return 'error'; }
|
|
169
174
|
}
|
|
175
|
+
pushBlob(frame) { return this.blobUpload.send(frame); }
|
|
170
176
|
sendFrame(type, id, payload) { return this.trySendFrame(type, id, payload) === 'sent'; }
|
|
171
177
|
sendJson(type, id, obj) { return this.trySendJson(type, id, obj) === 'sent'; }
|
|
172
178
|
createHttpResponseEntry(req = null, res = null, isSse = false) {
|
|
@@ -289,7 +295,9 @@ class RelayTunnel {
|
|
|
289
295
|
return false;
|
|
290
296
|
}
|
|
291
297
|
const size = isChunk ? body.length : frame.length;
|
|
292
|
-
const
|
|
298
|
+
const blobNeedsWindow = this.blobUpload.active?.waiting
|
|
299
|
+
&& Number(this.ws?.bufferedAmount || 0) + size > TUNNEL_BUFFER_LOW_WATER_BYTES - 128 * 1024;
|
|
300
|
+
const mustQueue = (isChunk && body.length > HTTP_RESPONSE_CHUNK_BYTES) || blobNeedsWindow;
|
|
293
301
|
if (!entry.pendingFrames.length && !mustQueue && !entry.relayPaused) {
|
|
294
302
|
const result = isChunk ? this.trySendFrame(type, id, body) : this.trySendEncodedFrame(frame);
|
|
295
303
|
if (result === 'sent') {
|
|
@@ -357,7 +365,9 @@ class RelayTunnel {
|
|
|
357
365
|
const index = (start + step) % count;
|
|
358
366
|
const [id, entry] = all[index];
|
|
359
367
|
if (entry.done || entry.relayPaused || !entry.pendingFrames?.length) continue;
|
|
360
|
-
|
|
368
|
+
// blob等发送时留一小片窗口;HTTP仍逐流轮转,blob一片发出后即恢复原预算。
|
|
369
|
+
const ceiling = this.blobUpload.active?.waiting ? TUNNEL_BUFFER_LOW_WATER_BYTES - 128 * 1024 : MAX_TUNNEL_BUFFERED_BYTES;
|
|
370
|
+
if (Number(this.ws.bufferedAmount || 0) + HTTP_RESPONSE_CHUNK_BYTES + 16 > ceiling) break;
|
|
361
371
|
const item = entry.pendingFrames[0];
|
|
362
372
|
let result;
|
|
363
373
|
if (item.type === T.httpChunk) {
|
|
@@ -506,6 +516,7 @@ class RelayTunnel {
|
|
|
506
516
|
const done = (fn, arg) => {
|
|
507
517
|
if (!settled) {
|
|
508
518
|
settled = true;
|
|
519
|
+
this.cancelRegistration = null;
|
|
509
520
|
fn(arg);
|
|
510
521
|
}
|
|
511
522
|
};
|
|
@@ -516,14 +527,24 @@ class RelayTunnel {
|
|
|
516
527
|
this.ws = ws;
|
|
517
528
|
const timer = setTimeout(() => {
|
|
518
529
|
done(reject, new Error('注册超时'));
|
|
519
|
-
try { ws.
|
|
530
|
+
try { ws.terminate(); } catch { /* ignore */ }
|
|
520
531
|
}, 8000);
|
|
532
|
+
this.cancelRegistration = () => {
|
|
533
|
+
clearTimeout(timer);
|
|
534
|
+
const error = new Error('隧道注册已取消');
|
|
535
|
+
error.code = 'relay_cancelled';
|
|
536
|
+
done(reject, error);
|
|
537
|
+
};
|
|
521
538
|
|
|
522
539
|
const push = createFrameDecoder((frame) => {
|
|
540
|
+
if (this.ws !== ws) return;
|
|
523
541
|
if (frame.type === T.registered) {
|
|
542
|
+
if (settled) return;
|
|
524
543
|
// 回执里带 `mirror`:对端说不存镜像,就只推摘要(凭据 + 两个 revision),正文不推。
|
|
525
544
|
// 老中转回的是空载荷,`parseJson` 给空对象,于是判定为「存」——与以前完全一样。
|
|
526
|
-
|
|
545
|
+
const registered = parseJson(frame.payload);
|
|
546
|
+
this.relayMirror = registered.mirror !== false;
|
|
547
|
+
this.blobUpload.configure(registered.blobUpload);
|
|
527
548
|
clearTimeout(timer);
|
|
528
549
|
done(resolve);
|
|
529
550
|
this.onRegistered();
|
|
@@ -533,12 +554,15 @@ class RelayTunnel {
|
|
|
533
554
|
});
|
|
534
555
|
|
|
535
556
|
ws.on('open', () => {
|
|
557
|
+
if (this.ws !== ws) return;
|
|
536
558
|
this.sendJson(T.register, 0, this.registrationPayload());
|
|
537
559
|
});
|
|
538
560
|
ws.on('message', (data, isBinary) => push(Buffer.isBuffer(data) ? data : Buffer.from(data)));
|
|
539
561
|
ws.on('close', (code, reason) => {
|
|
540
562
|
clearTimeout(timer);
|
|
563
|
+
if (this.ws !== ws) { done(reject, new Error(`隧道关闭: ${code} ${reason}`)); return; }
|
|
541
564
|
this.stopHeartbeat();
|
|
565
|
+
this.blobUpload.close();
|
|
542
566
|
this.log(`tunnel closed: ${code} ${reason}`);
|
|
543
567
|
this.ws = null;
|
|
544
568
|
this.clearHttpPumpTimer();
|
|
@@ -572,6 +596,8 @@ class RelayTunnel {
|
|
|
572
596
|
}
|
|
573
597
|
|
|
574
598
|
stop() {
|
|
599
|
+
this.blobUpload.close();
|
|
600
|
+
this.cancelRegistration?.();
|
|
575
601
|
this.stopHeartbeat();
|
|
576
602
|
this.clearHttpPumpTimer();
|
|
577
603
|
for (const [, client] of this.wsClients) {
|
|
@@ -584,18 +610,19 @@ class RelayTunnel {
|
|
|
584
610
|
this.cancelledHttp.clear();
|
|
585
611
|
this.cancelledWs.clear();
|
|
586
612
|
if (this.ws) {
|
|
587
|
-
|
|
613
|
+
const ws = this.ws;
|
|
588
614
|
this.ws = null;
|
|
615
|
+
try { ws.terminate(); } catch { /* ignore */ }
|
|
589
616
|
}
|
|
590
617
|
}
|
|
591
618
|
|
|
592
619
|
// ── 心跳 ──────────────────────────────────────────────────────────
|
|
593
620
|
startHeartbeat() {
|
|
594
621
|
this.stopHeartbeat();
|
|
595
|
-
this.lastPong =
|
|
622
|
+
this.lastPong = performance.now();
|
|
596
623
|
this.hbTimer = setInterval(() => {
|
|
597
624
|
if (!this.connected) return;
|
|
598
|
-
if (
|
|
625
|
+
if (performance.now() - this.lastPong > PONG_TIMEOUT_MS) {
|
|
599
626
|
this.log('心跳超时,断开隧道');
|
|
600
627
|
try { this.ws.terminate(); } catch { /* ignore */ }
|
|
601
628
|
return;
|
|
@@ -613,6 +640,10 @@ class RelayTunnel {
|
|
|
613
640
|
// ── 帧分发 ────────────────────────────────────────────────────────
|
|
614
641
|
handleFrame(frame) {
|
|
615
642
|
const { type, id, payload } = frame;
|
|
643
|
+
if (type === T.blobPut && id !== 0) {
|
|
644
|
+
this.blobUpload.onAck(id, parseJson(payload));
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
616
647
|
// id=0 的 wsError 是中转在断开之前给的一句话(现在还只用于「注册被拒」):先记下来,
|
|
617
648
|
// 等随后的 close 回调把它带进 start() 的 reject,调用方按 `code` 分流。
|
|
618
649
|
if (type === T.wsError && id === 0) {
|
|
@@ -797,7 +828,7 @@ class RelayTunnel {
|
|
|
797
828
|
this.sendFrame(T.pong, 0, Buffer.alloc(0));
|
|
798
829
|
break;
|
|
799
830
|
case T.pong:
|
|
800
|
-
this.lastPong =
|
|
831
|
+
this.lastPong = performance.now();
|
|
801
832
|
break;
|
|
802
833
|
case T.revokeAllAck: {
|
|
803
834
|
const msg = parseJson(payload);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// 远程电脑状态保留环境诊断,助手换代主动撤下隧道并恢复现有访问。
|
|
2
2
|
// 2026-11-19:桌面窗口改成多窗口集合(只有最后一个窗口退出才回到未打开),进程还在就显示正在打开 /
|
|
3
3
|
// 已打开;换网按 lost 与非 lost 分流,lost 只断开已打开设备的连接、不改状态也不探活,非 lost 让所有
|
|
4
4
|
// 绑定(含没打开过的)都重选线路;connect 回调记下 connection.route 作为「实际在用线路」供面板展示;
|
|
@@ -18,7 +18,11 @@ const REMOTE_ERROR_TEXT = {
|
|
|
18
18
|
REMOTE_REVOKED: '这台电脑的授权已被撤销,请重新绑定',
|
|
19
19
|
REMOTE_VERSION: '对方插件版本不兼容,请升级到支持远程电脑的版本',
|
|
20
20
|
REMOTE_EXPIRED: '授权已到期,请重新打开',
|
|
21
|
-
REMOTE_TIMEOUT: '
|
|
21
|
+
REMOTE_TIMEOUT: '连接远程电脑超时,请检查对方在线状态;受限网络也可能需要代理或先完成网络登录',
|
|
22
|
+
REMOTE_PROXY: '网络返回代理认证要求,请完成代理配置或更换网络后重试',
|
|
23
|
+
REMOTE_PROXY_CONFIGURED: '本机配置了出站代理,当前远程连接使用直连;请确认网络允许直连或更换网络',
|
|
24
|
+
REMOTE_INTERCEPTED: '连接收到了网页而非远程协议,请检查网络登录页或线路地址',
|
|
25
|
+
REMOTE_HELPER_RESTARTING: '本机隧道助手正在恢复,请稍后重试',
|
|
22
26
|
REMOTE_CONNECT: '暂时无法连接远程电脑,请检查网络和对方是否在线',
|
|
23
27
|
REMOTE_UNAVAILABLE: '对方电脑暂时不可用,请确认它已打开 DSH 后重试',
|
|
24
28
|
REMOTE_NOT_FOUND: '找不到这台远程电脑,它可能已被删除,请刷新后重试',
|
|
@@ -124,6 +128,32 @@ function createRemoteController({ store, transport, name, tunnels, onBindingsCha
|
|
|
124
128
|
item.router = routerFor(item);
|
|
125
129
|
}
|
|
126
130
|
|
|
131
|
+
const unsubscribeTunnels = tunnels?.onChange?.(state => {
|
|
132
|
+
if (closed) return;
|
|
133
|
+
for (const item of devices.values()) {
|
|
134
|
+
const hadTunnel = ['tunnel', 'p2p'].includes(item.activeRoute?.channel || item.router.snapshot().route?.channel);
|
|
135
|
+
if (!state.ready) {
|
|
136
|
+
item.helperRecovery = Boolean(item.helperRecovery || check(item)
|
|
137
|
+
&& item.router.snapshot().routes.some(route => ['tunnel', 'p2p'].includes(route.channel)));
|
|
138
|
+
item.router.invalidateTunnels();
|
|
139
|
+
if (hadTunnel) {
|
|
140
|
+
item.gateway?.disconnect?.(); item.activeRoute = null;
|
|
141
|
+
item.lastErrorCode = 'REMOTE_HELPER_RESTARTING';
|
|
142
|
+
item.lastError = REMOTE_ERROR_TEXT.REMOTE_HELPER_RESTARTING;
|
|
143
|
+
if (check(item)) item.state = 'connecting';
|
|
144
|
+
}
|
|
145
|
+
} else if (item.helperRecovery && check(item) && !['expired', 'revoked'].includes(item.state)) {
|
|
146
|
+
item.helperRecovery = false;
|
|
147
|
+
const router = item.router;
|
|
148
|
+
void router.refresh(true).then(() => router.probe()).then(() => {
|
|
149
|
+
if (!closed && item.router === router && check(item)) {
|
|
150
|
+
item.state = 'connected'; item.lastError = ''; item.lastErrorCode = '';
|
|
151
|
+
}
|
|
152
|
+
}).catch(error => { if (!closed && item.router === router && check(item)) fault(item, error); });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
|
|
127
157
|
const network = createNetworkMonitor({
|
|
128
158
|
async onTick(time) {
|
|
129
159
|
const active = [...devices.values()].filter((item) => check(item));
|
|
@@ -272,7 +302,7 @@ function createRemoteController({ store, transport, name, tunnels, onBindingsCha
|
|
|
272
302
|
},
|
|
273
303
|
async close() {
|
|
274
304
|
if (closed) return;
|
|
275
|
-
closed = true; network.close();
|
|
305
|
+
closed = true; network.close(); unsubscribeTunnels?.();
|
|
276
306
|
await Promise.all([...devices.values()].map(async (item) => {
|
|
277
307
|
item.gateway?.close(); item.gateway = null; item.router.close();
|
|
278
308
|
await tunnels?.close?.(item.binding.id);
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
// IPv6 候选按真实监听端口生成,独立于 IPv4 局域网候选开关。
|
|
1
2
|
'use strict';
|
|
2
3
|
// 电脑间已认证控制信令只提供隧道会合,目标固定为本机插件入口。
|
|
3
4
|
const { relayAddressesOf } = require('../relay/core.js');
|
|
4
|
-
const { advertisedCandidates, phoneCandidates, ipv6Candidates, withManualIpv6Candidate } = require('../relay/lan-network.cjs');
|
|
5
|
+
const { advertisedCandidates, phoneCandidates, ipv6Candidates, withManualIpv6Candidate, tcpDirectTarget } = require('../relay/lan-network.cjs');
|
|
5
6
|
|
|
6
7
|
function routesOf({ state, lanPortInUse, lanAvailable = () => state.lanEnabled, interfaces }) {
|
|
7
8
|
const routes = [];
|
|
@@ -11,12 +12,20 @@ function routesOf({ state, lanPortInUse, lanAvailable = () => state.lanEnabled,
|
|
|
11
12
|
if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password || parsed.search || parsed.hash) return;
|
|
12
13
|
routes.push({ url: parsed.href.replace(/\/$/, ''), channel });
|
|
13
14
|
};
|
|
15
|
+
const port = Number(lanPortInUse());
|
|
14
16
|
if (lanAvailable()) {
|
|
15
|
-
const port = lanPortInUse();
|
|
16
17
|
for (const item of phoneCandidates(advertisedCandidates(port, interfaces), { manual: state.manualLanUrl })) push(item.url, 'lan');
|
|
18
|
+
}
|
|
19
|
+
// lanPortInUse 为 0 表示没有监听,不能把配置端口或中转回环口发布成 v6 直连。
|
|
20
|
+
if (Number.isInteger(port) && port > 0) {
|
|
17
21
|
for (const item of withManualIpv6Candidate(ipv6Candidates(port, interfaces), state.manualIpv6Url)) push(item.url, 'ipv6');
|
|
18
22
|
}
|
|
19
23
|
for (const url of relayAddressesOf(state).relayUrls) push(url, 'relay');
|
|
24
|
+
// 「TCP 直连」目标:公网可达、手机靠裸 TCP 拨的那条,电脑对电脑同样能走(明文 http 转发到本机入口)。
|
|
25
|
+
// 与自建中转 / 直连同属「公网可达的自建」,配了之后公用中转会被停用(见 relay/core.publicRelayBlocked),
|
|
26
|
+
// 所以这里必须把它也当候选,否则远程电脑反而少一条可用的公网线路。
|
|
27
|
+
const tcp = tcpDirectTarget(state.manualTcpUrl);
|
|
28
|
+
if (tcp) push(`http://${tcp}`, 'tcp');
|
|
20
29
|
return routes;
|
|
21
30
|
}
|
|
22
31
|
function candidates(value) {
|