dsh-mobile-plugin 0.5.130 → 0.5.131
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/cloudflared/runner.cjs +24 -4
- package/lib/cloudflared/wiring.cjs +9 -1
- package/lib/frpc/runner.cjs +8 -3
- package/lib/impl.js +5 -2
- package/lib/mobile/events.js +3 -0
- package/lib/mobile/relay-control.js +16 -3
- package/lib/panel/index.html +13 -13
- package/lib/relay/config-store.js +6 -0
- package/lib/relay/control.js +17 -2
- package/lib/relay/ipv6-liveness.cjs +102 -0
- package/lib/relay/lan-network.cjs +17 -1
- package/lib/relay/lan-proxy.js +7 -1
- package/lib/relay/net-family.cjs +36 -0
- package/lib/relay/tunnel.js +7 -1
- package/lib/relay/verify.js +3 -1
- package/lib/shared/restart-backoff.cjs +32 -0
- package/lib/shared/route-order.cjs +34 -0
- package/lib/sidecar-facade-worker.cjs +27 -4
- package/package.json +13 -13
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
const z = require('@deepseek-ai/schemastery');
|
|
10
10
|
const core = require('./core.js');
|
|
11
11
|
const pairingApproval = require('./pairing-policy.js');
|
|
12
|
+
const { normalizeIpVersionPolicy } = require('./net-family.cjs');
|
|
12
13
|
|
|
13
14
|
/** 通用线路清单最多几条:总控信封有上限,写多了只会拖慢每次同步。 */
|
|
14
15
|
const CUSTOM_ROUTES_LIMIT = 16;
|
|
@@ -65,6 +66,9 @@ const RemoteControlSettingsSchema = z.object({
|
|
|
65
66
|
// 是否把本机网络地址加密上报给「总控」(地址目录)。默认开 = 与历史行为一致;
|
|
66
67
|
// 关掉后宿主不再跑总控上报客户端,手机换网后拿不到这台电脑的新地址(见 relay/control.js)。
|
|
67
68
|
controlReportEnabled: z.boolean().default(true),
|
|
69
|
+
// 出站网络协议族策略:auto=跟随系统(默认,行为不变);ipv4-first=出站 WS / 穿透优先走 IPv4;
|
|
70
|
+
// ipv4-only=只用 IPv4,并且不再产出/上报 IPv6 直连候选。口径统一在 relay/net-family.cjs。
|
|
71
|
+
ipVersionPolicy: z.union([z.const('auto'), z.const('ipv4-first'), z.const('ipv4-only')]).default('auto'),
|
|
68
72
|
// 桌面设置页那两颗侧边栏图标(手机 / 电脑)的可见性。默认全开;老 relay.json 没这两格时
|
|
69
73
|
// 由 configOf 收成 true,界面不会在升级后突然少一颗。只给桌面控制面写,手机端配置口不收。
|
|
70
74
|
desktopPhoneIcon: z.boolean().default(true),
|
|
@@ -145,6 +149,8 @@ function configOf(state) {
|
|
|
145
149
|
pairingPolicy: pairingApproval.normalize(state.pairingPolicy),
|
|
146
150
|
// 只有明确写成 false 才算关;老状态文件没这一格时按开(与历史行为一致)。
|
|
147
151
|
controlReportEnabled: state.controlReportEnabled !== false,
|
|
152
|
+
// 非法值一律归 auto,老状态文件没有这一格也是 auto。
|
|
153
|
+
ipVersionPolicy: normalizeIpVersionPolicy(state.ipVersionPolicy),
|
|
148
154
|
// 没写过的老配置按显示处理:这两颗是入口,不因为升级就凭空消失。
|
|
149
155
|
desktopPhoneIcon: state.desktopPhoneIcon !== false,
|
|
150
156
|
desktopComputerIcon: state.desktopComputerIcon !== false,
|
package/lib/relay/control.js
CHANGED
|
@@ -34,6 +34,7 @@ const path = require('node:path');
|
|
|
34
34
|
const crypto = require('node:crypto');
|
|
35
35
|
const { performance } = require('node:perf_hooks');
|
|
36
36
|
const { sealHistoryBlob } = require('../mirror/history-blob.cjs');
|
|
37
|
+
const { outboundAgentFor, normalizeIpVersionPolicy } = require('./net-family.cjs');
|
|
37
38
|
// 网卡枚举 / 手填地址解析这些「候选计算」住在「代」里,由当前这一代经 `lanTools` 注入;外壳不认识它们。
|
|
38
39
|
// 服务商线路清单与配对二维码 / 手机心跳同源,但那件计算住在「代」里:由当前这一代经
|
|
39
40
|
// `getProviderLines` 注入进来。外壳不认识它 —— 改清单、加服务商都只换代,不动外壳。
|
|
@@ -189,6 +190,8 @@ function createControlClient(options = {}) {
|
|
|
189
190
|
? getAddresses
|
|
190
191
|
: (s) => controlAddresses(s, typeof getPort === 'function' ? getPort() : undefined, typeof getConnectedRelay === 'function' ? getConnectedRelay() : '', { getProviderLines, lanTools: lanToolsOf() });
|
|
191
192
|
const connectedOf = typeof getRelayConnected === 'function' ? getRelayConnected : () => false;
|
|
193
|
+
// 重连退避的抖动用它:默认真随机,测试可注入固定值保持确定性。
|
|
194
|
+
const random = typeof options.random === 'function' ? options.random : Math.random;
|
|
192
195
|
|
|
193
196
|
let sock = null;
|
|
194
197
|
let running = false;
|
|
@@ -206,6 +209,8 @@ function createControlClient(options = {}) {
|
|
|
206
209
|
let reconnectTimer = null;
|
|
207
210
|
let tickTimer = null;
|
|
208
211
|
let releaseSocket = null;
|
|
212
|
+
// 上一次真正拨号时用的协议族策略:变了就在 sync 里主动重拨,别让已连的连接继续按旧策略出站。
|
|
213
|
+
let lastDialPolicy = null;
|
|
209
214
|
// 「身份冲突」连续计数:同一台机器被别处占了令牌时会持续收到 identity_conflict。
|
|
210
215
|
// 累计到阈值(且都在一个窗口内)就触发一次换身份,把本机换成新号从冲突里出来;
|
|
211
216
|
// 换完若还冲突,靠冷却期避免反复触发放大(换身份本身会重连,别在里头死循环)。
|
|
@@ -336,7 +341,9 @@ function createControlClient(options = {}) {
|
|
|
336
341
|
function scheduleReconnect() {
|
|
337
342
|
if (!running) return;
|
|
338
343
|
attempt += 1;
|
|
339
|
-
|
|
344
|
+
// 基数仍按 1/2/4/…/30 秒封顶;加 ±20% 抖动,避免全网宿主在总控重连时齐步撞门。
|
|
345
|
+
const base = Math.min(30_000, 1_000 * 2 ** Math.min(attempt - 1, 5));
|
|
346
|
+
const delay = Math.max(0, Math.round(Math.min(30_000, base * (0.8 + random() * 0.4))));
|
|
340
347
|
clearTimeout(reconnectTimer);
|
|
341
348
|
const timer = setTimeout(() => {
|
|
342
349
|
if (reconnectTimer !== timer) return;
|
|
@@ -371,7 +378,8 @@ function createControlClient(options = {}) {
|
|
|
371
378
|
const url = `${controlWsUrl()}/ws/device?instanceId=${encodeURIComponent(getState().instanceId || '')}${tokenQuery}`;
|
|
372
379
|
let ws;
|
|
373
380
|
try {
|
|
374
|
-
|
|
381
|
+
const wsAgent = outboundAgentFor(getState().ipVersionPolicy, /^wss:/i.test(url));
|
|
382
|
+
ws = wsAgent ? new WebSocket(url, { agent: wsAgent }) : new WebSocket(url);
|
|
375
383
|
} catch (error) {
|
|
376
384
|
log('control: dial failed');
|
|
377
385
|
scheduleReconnect();
|
|
@@ -379,6 +387,7 @@ function createControlClient(options = {}) {
|
|
|
379
387
|
}
|
|
380
388
|
sock = ws;
|
|
381
389
|
connected = false;
|
|
390
|
+
lastDialPolicy = normalizeIpVersionPolicy(getState().ipVersionPolicy);
|
|
382
391
|
lastSent = '';
|
|
383
392
|
let handshakeTimer = null;
|
|
384
393
|
let heartbeatTimer = null;
|
|
@@ -522,6 +531,12 @@ function createControlClient(options = {}) {
|
|
|
522
531
|
start();
|
|
523
532
|
return;
|
|
524
533
|
}
|
|
534
|
+
// 协议族策略变了:已连的连接仍按旧策略出站,主动重拨一次把它换过来。
|
|
535
|
+
if (sock && lastDialPolicy !== null && normalizeIpVersionPolicy(getState().ipVersionPolicy) !== lastDialPolicy) {
|
|
536
|
+
stop();
|
|
537
|
+
start();
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
525
540
|
if (!sock && !reconnectTimer) connect();
|
|
526
541
|
else tick();
|
|
527
542
|
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// IPv6 直连候选的本机活性预筛。
|
|
3
|
+
//
|
|
4
|
+
// 为什么:手机配对/重连时拿到的 IPv6 候选是**静态快照**(二维码、总控上报、connection-info),
|
|
5
|
+
// 里面可能混着已经失效的地址(RFC 4941 临时地址轮换、前缀撤销)。手机逐条去拨,每条要吃满
|
|
6
|
+
// 自己那一侧的操作系统 TCP 超时。这里在本机对每条候选做一次**短超时 TCP 连**(连的是本机自己的
|
|
7
|
+
// 监听端口):连不上基本就等于这条地址已经不在网卡上/不可用,先从候选里过滤掉。
|
|
8
|
+
//
|
|
9
|
+
// 它只能证伪「本机这条地址此刻还通」,证明不了「手机在外面一定拨得进来」——所以它是旁路预筛,
|
|
10
|
+
// 不是保证。结果按 TTL 缓存,供同步的候选生成直接过滤;探测本身失败一律吞掉,不制造新失败点。
|
|
11
|
+
const net = require('node:net');
|
|
12
|
+
|
|
13
|
+
const DEFAULT_TIMEOUT_MS = 1000;
|
|
14
|
+
const DEFAULT_TTL_MS = 60_000;
|
|
15
|
+
/** 同一地址两次主动探测的最小间隔:避免每次取候选都打一发。 */
|
|
16
|
+
const DEFAULT_RETRY_MS = 30_000;
|
|
17
|
+
|
|
18
|
+
/** 对 host:port 做一次短超时 TCP 连接;连上为 true,超时/报错为 false。 */
|
|
19
|
+
function probeTcp(host, port, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
20
|
+
return new Promise((resolve) => {
|
|
21
|
+
let done = false;
|
|
22
|
+
const finish = (alive) => {
|
|
23
|
+
if (done) return;
|
|
24
|
+
done = true;
|
|
25
|
+
try { socket.destroy(); } catch { /* 已关闭 */ }
|
|
26
|
+
resolve(alive);
|
|
27
|
+
};
|
|
28
|
+
const socket = net.connect({ host, port });
|
|
29
|
+
socket.setTimeout(Math.max(1, timeoutMs));
|
|
30
|
+
socket.once('connect', () => finish(true));
|
|
31
|
+
socket.once('timeout', () => finish(false));
|
|
32
|
+
socket.once('error', () => finish(false));
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 从 URL 里取出 host:port(IPv6 会带方括号);取不到(端口 0 / 缺端口)返回 null。 */
|
|
37
|
+
function parseHostPort(url) {
|
|
38
|
+
const match = /^[a-z][a-z0-9+.-]*:\/\/(\[[^\]]+\]|[^/:]+)(?::(\d+))?/i.exec(String(url || ''));
|
|
39
|
+
if (!match) return null;
|
|
40
|
+
let host = match[1];
|
|
41
|
+
if (host.startsWith('[') && host.endsWith(']')) host = host.slice(1, -1);
|
|
42
|
+
const port = match[2] ? Number(match[2]) : 0;
|
|
43
|
+
if (!host || !Number.isInteger(port) || port <= 0 || port > 65535) return null;
|
|
44
|
+
return { host, port };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 一个按 TTL 记账的活性缓存。
|
|
49
|
+
* @param {{ probe?: (host:string, port:number)=>Promise<boolean>, timeoutMs?: number, ttlMs?: number, retryMs?: number, now?: ()=>number }} [options]
|
|
50
|
+
*/
|
|
51
|
+
function createLivenessCache(options = {}) {
|
|
52
|
+
const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : DEFAULT_TIMEOUT_MS;
|
|
53
|
+
const ttlMs = Number(options.ttlMs) > 0 ? Number(options.ttlMs) : DEFAULT_TTL_MS;
|
|
54
|
+
const retryMs = Number(options.retryMs) >= 0 ? Number(options.retryMs) : DEFAULT_RETRY_MS;
|
|
55
|
+
const now = typeof options.now === 'function' ? options.now : Date.now;
|
|
56
|
+
const probe = typeof options.probe === 'function' ? options.probe : (host, port) => probeTcp(host, port, timeoutMs);
|
|
57
|
+
/** url → 判定为「死」的截止时刻。 */
|
|
58
|
+
const deadUntil = new Map();
|
|
59
|
+
const probing = new Set();
|
|
60
|
+
const lastProbedAt = new Map();
|
|
61
|
+
|
|
62
|
+
function isDead(url) {
|
|
63
|
+
const until = deadUntil.get(url);
|
|
64
|
+
if (until === undefined) return false;
|
|
65
|
+
if (now() >= until) { deadUntil.delete(url); return false; }
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 起一轮旁路探测;同一地址在 retryMs 内不重复打。 */
|
|
70
|
+
function schedule(urls) {
|
|
71
|
+
const at = now();
|
|
72
|
+
for (const url of urls) {
|
|
73
|
+
if (probing.has(url)) continue;
|
|
74
|
+
const target = parseHostPort(url);
|
|
75
|
+
if (!target) continue;
|
|
76
|
+
const last = lastProbedAt.get(url);
|
|
77
|
+
if (last !== undefined && at - last < retryMs) continue;
|
|
78
|
+
lastProbedAt.set(url, at);
|
|
79
|
+
probing.add(url);
|
|
80
|
+
Promise.resolve()
|
|
81
|
+
.then(() => probe(target.host, target.port))
|
|
82
|
+
.then((alive) => { if (alive) deadUntil.delete(url); else deadUntil.set(url, now() + ttlMs); })
|
|
83
|
+
.catch(() => { /* 探测失败不改结论 */ })
|
|
84
|
+
.finally(() => { probing.delete(url); });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 过滤掉已知死地址,并顺手为整批起一轮探测。返回仍认为活的 urls。 */
|
|
89
|
+
function filter(urls) {
|
|
90
|
+
const list = Array.from(urls);
|
|
91
|
+
schedule(list);
|
|
92
|
+
return list.filter((url) => !isDead(url));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function reset() { deadUntil.clear(); probing.clear(); lastProbedAt.clear(); }
|
|
96
|
+
|
|
97
|
+
return { isDead, schedule, filter, reset, _deadUntil: deadUntil };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const defaultCache = createLivenessCache();
|
|
101
|
+
|
|
102
|
+
module.exports = { createLivenessCache, probeTcp, parseHostPort, defaultCache, DEFAULT_TIMEOUT_MS, DEFAULT_TTL_MS };
|
|
@@ -14,6 +14,13 @@
|
|
|
14
14
|
const os = require('node:os')
|
|
15
15
|
// 私有地址判断搬到 shared/private-address.js:内核也要用它,不能反过来让内核依赖这个会频繁变的文件。
|
|
16
16
|
const { isPrivateLanAddress } = require('../shared/private-address.js')
|
|
17
|
+
const { normalizeIpVersionPolicy, allowsIpv6Candidates } = require('./net-family.cjs')
|
|
18
|
+
const ipv6Liveness = require('./ipv6-liveness.cjs')
|
|
19
|
+
|
|
20
|
+
// 出站协议族策略与 IPv6 候选活性账都放在模块级:同一进程里所有取候选的入口共用一份。
|
|
21
|
+
// 每个进程(宿主 / worker)各自把自己那份配置口径设进来即可,见 `setIpVersionPolicy`。
|
|
22
|
+
let ipVersionPolicy = 'auto'
|
|
23
|
+
function setIpVersionPolicy(value) { ipVersionPolicy = normalizeIpVersionPolicy(value) }
|
|
17
24
|
|
|
18
25
|
// Only advertise RFC1918 addresses. This intentionally excludes VPN/CGNAT,
|
|
19
26
|
// link-local and benchmarking/test ranges (notably 198.18.0.0/15).
|
|
@@ -277,8 +284,14 @@ function isGlobalUnicastV6(address) {
|
|
|
277
284
|
*/
|
|
278
285
|
const IPV6_CANDIDATE_MAX = 4
|
|
279
286
|
function ipv6Interfaces(port, interfaces = os.networkInterfaces()) {
|
|
280
|
-
|
|
287
|
+
// ipv4-only:整条 IPv6 直连通道不产出,手机也就不会拿到会超时的 v6 候选。
|
|
288
|
+
if (!allowsIpv6Candidates(ipVersionPolicy)) return []
|
|
289
|
+
const all = toCandidates(collectEndpoints(interfaces, isGlobalUnicastV6, 'IPv6'), port, 'IPv6')
|
|
281
290
|
.slice(0, IPV6_CANDIDATE_MAX)
|
|
291
|
+
// 本机活性预筛:已知连不上的(临时地址轮换/前缀撤销后的死地址)先从候选里过滤掉,别再发给手机。
|
|
292
|
+
// 首轮没有结论时原样返回,探测在后台补齐(旁路,失败不影响候选生成)。
|
|
293
|
+
const alive = new Set(ipv6Liveness.defaultCache.filter(all.map((candidate) => candidate.url)))
|
|
294
|
+
return all.filter((candidate) => alive.has(candidate.url))
|
|
282
295
|
}
|
|
283
296
|
function ipv6Urls(port, interfaces = os.networkInterfaces()) {
|
|
284
297
|
return ipv6Interfaces(port, interfaces).map((candidate) => candidate.url)
|
|
@@ -411,6 +424,8 @@ function manualIpv6Candidate(value) {
|
|
|
411
424
|
* 一个数量级,排最前就会按「先回话的赢」永远选中手填那条。
|
|
412
425
|
*/
|
|
413
426
|
function withManualIpv6Candidate(list, value) {
|
|
427
|
+
// ipv4-only:手填的 IPv6 也不再上报,否则会绕过上面 ipv6Interfaces 的整族关闭。
|
|
428
|
+
if (!allowsIpv6Candidates(ipVersionPolicy)) return []
|
|
414
429
|
const manual = manualIpv6Candidate(value)
|
|
415
430
|
const rest = Array.isArray(list) ? list : []
|
|
416
431
|
if (!manual) return rest
|
|
@@ -488,6 +503,7 @@ module.exports = {
|
|
|
488
503
|
isLanCandidateAddress,
|
|
489
504
|
isPublicAddress,
|
|
490
505
|
isGlobalUnicastV6,
|
|
506
|
+
setIpVersionPolicy,
|
|
491
507
|
isVpnInterface,
|
|
492
508
|
isVirtualInterface,
|
|
493
509
|
interfaceRank,
|
package/lib/relay/lan-proxy.js
CHANGED
|
@@ -128,7 +128,13 @@ function createLanProxy(opts) {
|
|
|
128
128
|
};
|
|
129
129
|
|
|
130
130
|
const inboundSockets = new Set();
|
|
131
|
-
const trackSocket = socket => {
|
|
131
|
+
const trackSocket = socket => {
|
|
132
|
+
inboundSockets.add(socket);
|
|
133
|
+
// 手机切网/睡死时 TCP 可能半开无 FIN。开保活让内核在空闲后主动探测对端,
|
|
134
|
+
// 别让一条僵尸连接一直占着订阅与内存直到 OS 的分钟级重传超时。
|
|
135
|
+
try { socket.setKeepAlive(true, 30_000) } catch { /* 已关闭/老运行时忽略 */ }
|
|
136
|
+
socket.once('close', () => inboundSockets.delete(socket));
|
|
137
|
+
};
|
|
132
138
|
let server = null;
|
|
133
139
|
// IPv6 那条监听(`::`,ipv6Only)。它可能压根没建立(机器没有 IPv6),所以单独存一份。
|
|
134
140
|
let v6Server = null;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// 出站协议族策略的单一出口:把「auto / ipv4-first / ipv4-only」翻译成
|
|
3
|
+
// - 出站 WebSocket 的 agent(强制 IPv4 时 family:4),
|
|
4
|
+
// - cloudflared 的 --edge-ip-version,
|
|
5
|
+
// - 是否还产出/上报 IPv6 直连候选。
|
|
6
|
+
// 别处不要再各写一份,改口径只改这里。
|
|
7
|
+
const http = require('node:http');
|
|
8
|
+
const https = require('node:https');
|
|
9
|
+
|
|
10
|
+
const POLICIES = ['auto', 'ipv4-first', 'ipv4-only'];
|
|
11
|
+
|
|
12
|
+
/** 只有这三档是合法值,其余(含老配置缺失)一律按 auto。 */
|
|
13
|
+
function normalizeIpVersionPolicy(value) {
|
|
14
|
+
return POLICIES.includes(value) ? value : 'auto';
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** 还要不要产出 / 上报 IPv6 直连候选:只有 ipv4-only 一刀切掉。 */
|
|
18
|
+
function allowsIpv6Candidates(policy) {
|
|
19
|
+
return normalizeIpVersionPolicy(policy) !== 'ipv4-only';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* 出站 WS 用的 agent:auto 交给系统(返回 undefined,行为与历史完全一致);
|
|
24
|
+
* 其余强制 family:4,按目标 ws / wss 选 http / https agent。
|
|
25
|
+
*/
|
|
26
|
+
function outboundAgentFor(policy, secure) {
|
|
27
|
+
if (normalizeIpVersionPolicy(policy) === 'auto') return undefined;
|
|
28
|
+
return secure ? new https.Agent({ family: 4 }) : new http.Agent({ family: 4 });
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** cloudflared 的 --edge-ip-version 取值:auto 不传(undefined);其余传 '4'。 */
|
|
32
|
+
function cloudflaredEdgeIpVersion(policy) {
|
|
33
|
+
return normalizeIpVersionPolicy(policy) === 'auto' ? undefined : '4';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
module.exports = { POLICIES, normalizeIpVersionPolicy, allowsIpv6Candidates, outboundAgentFor, cloudflaredEdgeIpVersion };
|
package/lib/relay/tunnel.js
CHANGED
|
@@ -27,6 +27,7 @@ const { T, jsonFrame, encodeFrame, createFrameDecoder, parseJson, encodeClosePay
|
|
|
27
27
|
const { isFreshRequest } = require('../shared/fresh-request');
|
|
28
28
|
const { encodeJsonBody } = require('../shared/http-util');
|
|
29
29
|
const { withViaHeader } = require('../shared/via-header');
|
|
30
|
+
const { outboundAgentFor } = require('./net-family.cjs');
|
|
30
31
|
|
|
31
32
|
// 上报给中转的插件版本:只有包自己的 package.json 这一个来源(与 lib/relay/status.js 同口径)。
|
|
32
33
|
// 中转靠它判「这台宿主是不是太旧」,见 relay-core 的 PROTOCOL.md 的 register 那行。
|
|
@@ -88,6 +89,8 @@ class RelayTunnel {
|
|
|
88
89
|
constructor(opts) {
|
|
89
90
|
this.relayUrl = opts.relayUrl;
|
|
90
91
|
this.instanceId = opts.instanceId;
|
|
92
|
+
// 出站协议族策略:auto 时出站 WS 交给系统;ipv4-first / ipv4-only 时强制 IPv4 agent。
|
|
93
|
+
this.ipVersionPolicy = opts.ipVersionPolicy;
|
|
91
94
|
this.pairingCode = opts.pairingCode || '';
|
|
92
95
|
this.name = opts.name || '';
|
|
93
96
|
this.lanUrls = Array.isArray(opts.lanUrls) ? opts.lanUrls.slice() : [];
|
|
@@ -531,7 +534,8 @@ class RelayTunnel {
|
|
|
531
534
|
// 中转侧是 tokio-tungstenite 手写的 101,从不回 `sec-websocket-extensions`,
|
|
532
535
|
// 所以 permessage-deflate 一次都没协商成功过;开着只会让人以为隧道压过。
|
|
533
536
|
// 真省字节靠的是响应体的 gzip(见 lib/shared/http-util.js)。
|
|
534
|
-
const
|
|
537
|
+
const wsAgent = outboundAgentFor(this.ipVersionPolicy, /^wss:/i.test(this.relayUrl));
|
|
538
|
+
const ws = wsAgent ? new WebSocket(this.relayUrl, { agent: wsAgent }) : new WebSocket(this.relayUrl);
|
|
535
539
|
this.ws = ws;
|
|
536
540
|
const timer = setTimeout(() => {
|
|
537
541
|
done(reject, new Error('注册超时'));
|
|
@@ -639,6 +643,8 @@ class RelayTunnel {
|
|
|
639
643
|
}
|
|
640
644
|
this.sendFrame(T.ping, 0, Buffer.alloc(0));
|
|
641
645
|
}, HEARTBEAT_INTERVAL_MS);
|
|
646
|
+
// 与 mux 的心跳定时器同一口径:不因这条定时器把宿主进程吊着不退出。
|
|
647
|
+
if (this.hbTimer && typeof this.hbTimer.unref === 'function') this.hbTimer.unref();
|
|
642
648
|
}
|
|
643
649
|
stopHeartbeat() {
|
|
644
650
|
if (this.hbTimer) {
|
package/lib/relay/verify.js
CHANGED
|
@@ -34,7 +34,7 @@ function probeInstanceId(instanceId) {
|
|
|
34
34
|
* resolve = 这个地址登录得了;reject = 地址形状不对、连不上、注册被拒或超时(消息原样往上
|
|
35
35
|
* 回,手机上看的就是这句)。无论成败都断开:留一个实例在中转上,下次真连接会被它顶一下。
|
|
36
36
|
*/
|
|
37
|
-
async function verifyRelayRegistration({ relayUrl, instanceId, upstreamPort, name, registerSecret }) {
|
|
37
|
+
async function verifyRelayRegistration({ relayUrl, instanceId, upstreamPort, name, registerSecret, ipVersionPolicy }) {
|
|
38
38
|
// 地址形状不对在这里当场抛(与保存配置同一个判据),别等到 WebSocket 才炸。
|
|
39
39
|
const tunnel = new RelayTunnel({
|
|
40
40
|
relayUrl: core.tunnelWsUrl(relayUrl),
|
|
@@ -42,6 +42,8 @@ async function verifyRelayRegistration({ relayUrl, instanceId, upstreamPort, nam
|
|
|
42
42
|
name: name || '',
|
|
43
43
|
upstream: `http://127.0.0.1:${upstreamPort}`,
|
|
44
44
|
registerSecret: typeof registerSecret === 'string' ? registerSecret : '',
|
|
45
|
+
// 试连同样服从协议族策略,否则 ipv4-only 下这条探测仍可能走 IPv6 造成「假连不上」。
|
|
46
|
+
ipVersionPolicy,
|
|
45
47
|
});
|
|
46
48
|
try {
|
|
47
49
|
await tunnel.start();
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// 进程守护的重启节奏:先用一段指数退避扛过瞬时故障,退避表用尽后转固定长间隔无限重试,
|
|
2
|
+
// 不再像旧实现那样耗光几次机会就永久停机。固定档带抖动,避免一批宿主在同一刻齐步回来。
|
|
3
|
+
'use strict';
|
|
4
|
+
|
|
5
|
+
/** 退避表用尽后的固定重试间隔(毫秒)。对齐 tailcat 的「封顶但不放弃」。 */
|
|
6
|
+
const STEADY_INTERVAL_MS = 60_000;
|
|
7
|
+
/** 固定档的抖动幅度(正负比例)。 */
|
|
8
|
+
const STEADY_JITTER_RATIO = 0.2;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 第 `retries` 次(从 0 起)重试该等多久。
|
|
12
|
+
*
|
|
13
|
+
* 退避表里还有档位就用表里的值(无抖动,行为与旧实现一致);用尽后转固定长间隔,
|
|
14
|
+
* 并在 `steadyMs ± steadyMs * jitterRatio` 之间抖动一次,把一批同时掉线的宿主摊开。
|
|
15
|
+
*
|
|
16
|
+
* @returns {{ ms: number, steady: boolean }} `steady` 为真表示已进入固定重试档。
|
|
17
|
+
*/
|
|
18
|
+
function nextRestartDelay(retries, {
|
|
19
|
+
delays,
|
|
20
|
+
steadyMs = STEADY_INTERVAL_MS,
|
|
21
|
+
jitterRatio = STEADY_JITTER_RATIO,
|
|
22
|
+
random = Math.random,
|
|
23
|
+
} = {}) {
|
|
24
|
+
if (!Array.isArray(delays) || delays.length === 0) throw new Error('nextRestartDelay: delays 必须是非空数组');
|
|
25
|
+
const index = Math.max(0, Math.floor(Number(retries) || 0));
|
|
26
|
+
if (index < delays.length) return { ms: delays[index], steady: false };
|
|
27
|
+
const spread = steadyMs * jitterRatio;
|
|
28
|
+
const ms = Math.max(0, Math.round(steadyMs + (random() * 2 - 1) * spread));
|
|
29
|
+
return { ms, steady: true };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
module.exports = { nextRestartDelay, STEADY_INTERVAL_MS, STEADY_JITTER_RATIO };
|
|
@@ -24,6 +24,8 @@ function createRoutePolicy() {
|
|
|
24
24
|
const ROUTE_SWITCH_SHARE = 1 / 3;
|
|
25
25
|
const SWITCH_GAIN_FLOOR_MS = 10;
|
|
26
26
|
const SETTLE_ROUNDS = 4;
|
|
27
|
+
const FAMILY_FAILURE_TRIGGER = 2;
|
|
28
|
+
const FAMILY_COOL_ROUNDS = 4;
|
|
27
29
|
const factsByScope = new Map();
|
|
28
30
|
function factsOf(scope) {
|
|
29
31
|
let facts = factsByScope.get(scope);
|
|
@@ -31,6 +33,7 @@ function createRoutePolicy() {
|
|
|
31
33
|
facts = {
|
|
32
34
|
latency: new Map(), samples: new Map(), lossPenalty: new Map(), failurePenalty: new Map(),
|
|
33
35
|
foreign: new Set(), evidenceAtRound: new Map(), evidenceRound: 0, staleRounds: 2, lastSwitch: null,
|
|
36
|
+
familyFails: new Map(),
|
|
34
37
|
};
|
|
35
38
|
factsByScope.set(scope, facts);
|
|
36
39
|
}
|
|
@@ -39,6 +42,9 @@ function createRoutePolicy() {
|
|
|
39
42
|
function norm(url) {
|
|
40
43
|
return String(url || '').trim().replace(/\/+$/, '');
|
|
41
44
|
}
|
|
45
|
+
function familyOf(url) {
|
|
46
|
+
return /^[a-z][a-z0-9+.-]*:\/\/\[/i.test(norm(url)) ? 'ipv6' : null;
|
|
47
|
+
}
|
|
42
48
|
function penaltyOf(attempts) {
|
|
43
49
|
if (!attempts)
|
|
44
50
|
return null;
|
|
@@ -62,6 +68,10 @@ function createRoutePolicy() {
|
|
|
62
68
|
facts.evidenceAtRound.delete(key);
|
|
63
69
|
facts.samples.delete(key);
|
|
64
70
|
}
|
|
71
|
+
for (const [family, entry] of facts.familyFails) {
|
|
72
|
+
if (facts.evidenceRound - entry.atRound > FAMILY_COOL_ROUNDS)
|
|
73
|
+
facts.familyFails.delete(family);
|
|
74
|
+
}
|
|
65
75
|
if (facts.lastSwitch && facts.evidenceRound - facts.lastSwitch.round > SETTLE_ROUNDS)
|
|
66
76
|
facts.lastSwitch = null;
|
|
67
77
|
}
|
|
@@ -79,6 +89,9 @@ function createRoutePolicy() {
|
|
|
79
89
|
facts.samples.set(key, window.slice(-SAMPLE_WINDOW));
|
|
80
90
|
facts.latency.set(key, ms);
|
|
81
91
|
facts.evidenceAtRound.set(key, facts.evidenceRound);
|
|
92
|
+
const family = familyOf(key);
|
|
93
|
+
if (family)
|
|
94
|
+
facts.familyFails.delete(family);
|
|
82
95
|
const penalty = penaltyOf(attempts);
|
|
83
96
|
if (penalty !== null)
|
|
84
97
|
facts.lossPenalty.set(key, penalty);
|
|
@@ -90,6 +103,14 @@ function createRoutePolicy() {
|
|
|
90
103
|
const facts = factsOf(scope);
|
|
91
104
|
const prev = facts.failurePenalty.get(key) ?? 1;
|
|
92
105
|
facts.failurePenalty.set(key, Math.min(FAILURE_PENALTY_MAX, prev * FAILURE_PENALTY_STEP));
|
|
106
|
+
const family = familyOf(key);
|
|
107
|
+
if (family) {
|
|
108
|
+
const entry = facts.familyFails.get(family) ?? { urls: new Set(), atRound: facts.evidenceRound };
|
|
109
|
+
entry.urls.add(key);
|
|
110
|
+
if (entry.urls.size >= FAMILY_FAILURE_TRIGGER)
|
|
111
|
+
entry.atRound = facts.evidenceRound;
|
|
112
|
+
facts.familyFails.set(family, entry);
|
|
113
|
+
}
|
|
93
114
|
}
|
|
94
115
|
function noteRouteProven(url, scope = '') {
|
|
95
116
|
const key = norm(url);
|
|
@@ -98,6 +119,9 @@ function createRoutePolicy() {
|
|
|
98
119
|
const facts = factsByScope.get(scope);
|
|
99
120
|
facts?.failurePenalty.delete(key);
|
|
100
121
|
facts?.foreign.delete(key);
|
|
122
|
+
const family = familyOf(key);
|
|
123
|
+
if (family)
|
|
124
|
+
facts?.familyFails.delete(family);
|
|
101
125
|
}
|
|
102
126
|
function noteRouteVerified(url, scope = '') {
|
|
103
127
|
factsByScope.get(scope)?.foreign.delete(norm(url));
|
|
@@ -151,7 +175,17 @@ function createRoutePolicy() {
|
|
|
151
175
|
const facts = factsOf(scope);
|
|
152
176
|
const current = norm(currentUrl);
|
|
153
177
|
const foreignFree = routes.filter((route) => !facts.foreign.has(norm(route.url)));
|
|
178
|
+
const familyCooled = new Set();
|
|
179
|
+
for (const [family, entry] of facts.familyFails) {
|
|
180
|
+
if (entry.urls.size >= FAMILY_FAILURE_TRIGGER && facts.evidenceRound - entry.atRound <= FAMILY_COOL_ROUNDS)
|
|
181
|
+
familyCooled.add(family);
|
|
182
|
+
}
|
|
154
183
|
const cooling = new Set((suspended || []).map(norm).filter(Boolean));
|
|
184
|
+
for (const route of routes) {
|
|
185
|
+
const family = familyOf(route.url);
|
|
186
|
+
if (family && familyCooled.has(family))
|
|
187
|
+
cooling.add(norm(route.url));
|
|
188
|
+
}
|
|
155
189
|
const allCooling = foreignFree.length > 0 && foreignFree.every((route) => cooling.has(norm(route.url)));
|
|
156
190
|
const cool = allCooling ? new Set() : cooling;
|
|
157
191
|
const warm = foreignFree.filter((route) => !cool.has(norm(route.url)));
|
|
@@ -42,7 +42,7 @@ const { T } = require('./relay/protocol.js')
|
|
|
42
42
|
const { switchRelay } = require('./relay/migrate.js')
|
|
43
43
|
const { createLanProxy } = require('./relay/lan-proxy.js')
|
|
44
44
|
const { createLanDiscovery, bindLanEndpoint } = require('./relay/lan-discovery.cjs')
|
|
45
|
-
const { lanUrls, ipv6Urls } = require('./relay/lan-network.cjs')
|
|
45
|
+
const { lanUrls, ipv6Urls, setIpVersionPolicy } = require('./relay/lan-network.cjs')
|
|
46
46
|
const core = require('./relay/core.js')
|
|
47
47
|
const { probeRelayHealth, createRelayRegistrationLedger, relayFailureMessage } = require('./relay/relay-probe.js')
|
|
48
48
|
const { createReconnectScheduler } = require('./reconnect-scheduler.cjs')
|
|
@@ -384,7 +384,8 @@ function snapshotRead(info) {
|
|
|
384
384
|
* 的信号。这也意味着写回队首之后**不能**再触发一次配置下发 —— 见 adoptRoute 那一段。
|
|
385
385
|
*/
|
|
386
386
|
function tunnelSignature(c) {
|
|
387
|
-
|
|
387
|
+
// ipVersionPolicy 进签名:改了协议族策略要重建隧道,否则已连的那条仍按旧策略出站。
|
|
388
|
+
return JSON.stringify([Boolean(c.enabled), c.relayUrl || '', Array.isArray(c.relayUrls) ? c.relayUrls : [], c.instanceId || '', c.upstreamPort || 0, c.upstreamHost || '', c.registerSecret || '', c.ipVersionPolicy || 'auto'])
|
|
388
389
|
}
|
|
389
390
|
/** 「这份配置里哪几项决定局域网代理要重建」。 */
|
|
390
391
|
function lanSignature(c) {
|
|
@@ -434,12 +435,30 @@ function startNetworkMonitor() {
|
|
|
434
435
|
if (!config.enabled) return
|
|
435
436
|
const addresses = () => [...(config.lanEnabled ? lanUrls(lanUrlPort()) : []), ...ipv6Urls(lanUrlPort())]
|
|
436
437
|
let previous = addresses()
|
|
438
|
+
// 用墙钟(Date.now)不是单调时钟:休眠/挂起期间单调钟不走,套不出「这一拍被拉长」的判据,
|
|
439
|
+
// 只有墙钟能反映睡了多久。
|
|
440
|
+
let lastPollAt = Date.now()
|
|
437
441
|
networkTimer = setInterval(() => {
|
|
442
|
+
const now = Date.now()
|
|
443
|
+
const elapsed = now - lastPollAt
|
|
444
|
+
lastPollAt = now
|
|
438
445
|
const current = addresses()
|
|
439
|
-
|
|
446
|
+
const changed = JSON.stringify(current) !== JSON.stringify(previous)
|
|
447
|
+
// 休眠唤醒/系统挂起之后,隧道 WS 常常半开假死却收不到任何事件。轮询间隔被时间跳变
|
|
448
|
+
// 拉长就是这一下的信号:命中就主动重建隧道,别等 pong 判死 + 退避(最坏约 75 秒)。
|
|
449
|
+
const woke = elapsed > NETWORK_POLL_MS * 3
|
|
450
|
+
if (!changed && !woke) return
|
|
440
451
|
previous = current
|
|
441
452
|
const publisher = lanDiscovery
|
|
442
453
|
if (lanState === 'listening' && publisher) void publisher.publish(lanBoundPort)
|
|
454
|
+
if (woke) {
|
|
455
|
+
// 唤醒:地址可能没变,但底层连接已死。按当前候选重建隧道(只动隧道与它的在途请求,
|
|
456
|
+
// 局域网监听一根手指都不碰)。startTunnel 内部先 stopTunnel 再择路,幂等。
|
|
457
|
+
startTunnel()
|
|
458
|
+
publishState()
|
|
459
|
+
return
|
|
460
|
+
}
|
|
461
|
+
// 仅是地址变化(换 DHCP、端口变化):仍只重报名片,不打断可能在正常转发数据的隧道。
|
|
443
462
|
reannounceRegistration()
|
|
444
463
|
publishState()
|
|
445
464
|
}, NETWORK_POLL_MS)
|
|
@@ -472,6 +491,7 @@ function openTunnel(route, race = null) {
|
|
|
472
491
|
const current = new RelayTunnel({
|
|
473
492
|
relayUrl: core.tunnelWsUrl(targetUrl), instanceId: config.instanceId,
|
|
474
493
|
name: config.name, upstream: upstream(),
|
|
494
|
+
ipVersionPolicy: config.ipVersionPolicy,
|
|
475
495
|
registerSecret: config.registerSecret,
|
|
476
496
|
lanUrls: currentLanUrls(),
|
|
477
497
|
readSnapshot: snapshotRead,
|
|
@@ -830,8 +850,9 @@ async function configure(next) {
|
|
|
830
850
|
// `relayUrls` 在白名单里,而且从这一轮起**进签名**(见 tunnelSignature):地址组或它的
|
|
831
851
|
// 顺序变了就要重新择路。白名单缺了它,宿主下发这一格会直接抛 unknown configuration
|
|
832
852
|
// field,整次配置下发失败。
|
|
833
|
-
const allowed = ['enabled', 'relayUrl', 'relayUrls', 'instanceId', 'previousInstanceId', 'pairingCode', 'pairingTicket', 'pairingTier', 'name', 'upstreamPort', 'upstreamHost', 'lanPort', 'lanPortLockReason', 'lanEnabled', 'lanSecret', 'registerSecret', 'tunnelIngressPort']
|
|
853
|
+
const allowed = ['enabled', 'relayUrl', 'relayUrls', 'instanceId', 'previousInstanceId', 'pairingCode', 'pairingTicket', 'pairingTier', 'name', 'upstreamPort', 'upstreamHost', 'lanPort', 'lanPortLockReason', 'lanEnabled', 'lanSecret', 'registerSecret', 'tunnelIngressPort', 'ipVersionPolicy']
|
|
834
854
|
if (Object.keys(next).some(key => !allowed.includes(key))) throw new Error('unknown configuration field')
|
|
855
|
+
if (next.ipVersionPolicy !== undefined && !['auto', 'ipv4-first', 'ipv4-only'].includes(next.ipVersionPolicy)) throw new Error('invalid ipVersionPolicy')
|
|
835
856
|
if (typeof next.instanceId !== 'string' || next.instanceId.length > 128) throw new Error('invalid instanceId')
|
|
836
857
|
if (next.previousInstanceId !== undefined && (typeof next.previousInstanceId !== 'string' || next.previousInstanceId.length > 128)) throw new Error('invalid previousInstanceId')
|
|
837
858
|
if (typeof next.pairingCode !== 'string' || !/^\d{6}$/.test(next.pairingCode)) throw new Error('invalid pairingCode')
|
|
@@ -860,6 +881,8 @@ async function configure(next) {
|
|
|
860
881
|
const monitorNeedsRestart = monitorSignature(previous) !== monitorSignature(next)
|
|
861
882
|
config = { ...next }
|
|
862
883
|
if (config.tunnelIngressPort === undefined) config.tunnelIngressPort = previous.tunnelIngressPort || 0
|
|
884
|
+
// 出站协议族策略落到本进程的候选/上报层(ipv4-only 时 worker 这一侧也不再产出 IPv6 候选)。
|
|
885
|
+
setIpVersionPolicy(config.ipVersionPolicy)
|
|
863
886
|
if (tunnelNeedsRebuild) {
|
|
864
887
|
if (relayUrlChanged && config.enabled && config.relayUrl && config.upstreamPort) {
|
|
865
888
|
// 换地址这条路**等新隧道真的注册上**再返回:注册不上要把错误一路回给调用方,
|