dsh-mobile-plugin 0.5.129 → 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 +17 -17
- package/lib/relay/config-store.js +13 -0
- package/lib/relay/control.js +17 -2
- package/lib/relay/core.js +5 -0
- package/lib/relay/ingress-guard.cjs +2 -1
- 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/routes/control-plane.js +7 -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/lib/update-install.cjs +124 -4
- package/lib/zeronews/runner.cjs +44 -1
- package/lib/zeronews/wiring.cjs +16 -1
- package/package.json +14 -13
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 2026-11-27:零讯客户端身份两格进 schema(连上时落盘,复用本机客户端前比对,手机配置口不开放)。
|
|
1
2
|
// 2026-11-25:专属回环入口端口进 schema(worker 绑定后落盘、手机配置口不开放),兜底期间的手填地址备份同属运行时字段。
|
|
2
3
|
// 固定端口设置随远程连接配置一并保存和投影。
|
|
3
4
|
// 远程控制配置的 schema 与投影:装配层从这里取,不把实现搬回去(状态仓外壳仍在 impl.js)。
|
|
@@ -8,6 +9,7 @@
|
|
|
8
9
|
const z = require('@deepseek-ai/schemastery');
|
|
9
10
|
const core = require('./core.js');
|
|
10
11
|
const pairingApproval = require('./pairing-policy.js');
|
|
12
|
+
const { normalizeIpVersionPolicy } = require('./net-family.cjs');
|
|
11
13
|
|
|
12
14
|
/** 通用线路清单最多几条:总控信封有上限,写多了只会拖慢每次同步。 */
|
|
13
15
|
const CUSTOM_ROUTES_LIMIT = 16;
|
|
@@ -64,6 +66,9 @@ const RemoteControlSettingsSchema = z.object({
|
|
|
64
66
|
// 是否把本机网络地址加密上报给「总控」(地址目录)。默认开 = 与历史行为一致;
|
|
65
67
|
// 关掉后宿主不再跑总控上报客户端,手机换网后拿不到这台电脑的新地址(见 relay/control.js)。
|
|
66
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'),
|
|
67
72
|
// 桌面设置页那两颗侧边栏图标(手机 / 电脑)的可见性。默认全开;老 relay.json 没这两格时
|
|
68
73
|
// 由 configOf 收成 true,界面不会在升级后突然少一颗。只给桌面控制面写,手机端配置口不收。
|
|
69
74
|
desktopPhoneIcon: z.boolean().default(true),
|
|
@@ -106,6 +111,10 @@ const RemoteControlSettingsSchema = z.object({
|
|
|
106
111
|
// ZeroNews 的账户 AuthToken 是否已经写进本机客户端配置(面板据此决定还要不要显示粘贴框)。
|
|
107
112
|
// 存的是「做过没有」,不是 token 本身:token 只经一次请求交给官方 CLI,插件不保存凭据。
|
|
108
113
|
zeroNewsBound: z.boolean().default(false),
|
|
114
|
+
// 上次连上的零讯客户端身份(client_id / 接入节点):运行时由 zeronews/wiring.cjs 写入,
|
|
115
|
+
// 手机配置口不开放。本机已有客户端在跑时用它比对,避免 attach 到另一个身份的客户端。
|
|
116
|
+
zeroNewsClientId: z.string().max(200).default(''),
|
|
117
|
+
zeroNewsNode: z.string().max(300).default(''),
|
|
109
118
|
// 节点小宝那条 TCP 线路的外网地址(`域名:端口`,空 = 没接)。用户在面板填一次,之后随通用线路
|
|
110
119
|
// 清单上报。手机配置口同样不开放:设备端和线路都在节点小宝那边,手机端只该看到一条线路。
|
|
111
120
|
jdxbUrl: z.string().max(300).default(''),
|
|
@@ -140,6 +149,8 @@ function configOf(state) {
|
|
|
140
149
|
pairingPolicy: pairingApproval.normalize(state.pairingPolicy),
|
|
141
150
|
// 只有明确写成 false 才算关;老状态文件没这一格时按开(与历史行为一致)。
|
|
142
151
|
controlReportEnabled: state.controlReportEnabled !== false,
|
|
152
|
+
// 非法值一律归 auto,老状态文件没有这一格也是 auto。
|
|
153
|
+
ipVersionPolicy: normalizeIpVersionPolicy(state.ipVersionPolicy),
|
|
143
154
|
// 没写过的老配置按显示处理:这两颗是入口,不因为升级就凭空消失。
|
|
144
155
|
desktopPhoneIcon: state.desktopPhoneIcon !== false,
|
|
145
156
|
desktopComputerIcon: state.desktopComputerIcon !== false,
|
|
@@ -160,6 +171,8 @@ function configOf(state) {
|
|
|
160
171
|
zeroNewsEnabled: state.zeroNewsEnabled === true,
|
|
161
172
|
// 账户 token 写过没有:决定面板还显不显示粘贴框;不涉及凭据本身。
|
|
162
173
|
zeroNewsBound: state.zeroNewsBound === true,
|
|
174
|
+
zeroNewsClientId: typeof state.zeroNewsClientId === 'string' ? state.zeroNewsClientId : '',
|
|
175
|
+
zeroNewsNode: typeof state.zeroNewsNode === 'string' ? state.zeroNewsNode : '',
|
|
163
176
|
// FRP 隧道地址:运行时写入的独立线路,空 = 没在跑 / 没分到地址。
|
|
164
177
|
frpUrl: typeof state.frpUrl === 'string' ? state.frpUrl : '',
|
|
165
178
|
// 用户手填的节点小宝线路地址;同样按空串兜底(没接这条线路)。
|
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
|
}
|
package/lib/relay/core.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 2026-11-27:零讯客户端身份两格进默认状态(连上时落盘,复用本机客户端前比对)。
|
|
1
2
|
// 2026-11-25:专属回环入口端口与兜底期手填地址备份进默认状态(运行时字段,手机配置口不开放)。
|
|
2
3
|
// 中转地址的废弃内置项在读盘与落盘时统一清理;配置收敛保持两格自洽。
|
|
3
4
|
// 通用线路引擎的运行时线路清单(customRoutes)随状态落盘,默认空:没接第三方线路时上报清单逐字不变。
|
|
@@ -102,6 +103,10 @@ function defaultState() {
|
|
|
102
103
|
zeroNewsEnabled: false,
|
|
103
104
|
// 账户 AuthToken 是否已经写进本机客户端配置:只记「做过没有」,不存 token。
|
|
104
105
|
zeroNewsBound: false,
|
|
106
|
+
// 上次连上的零讯客户端身份(client_id / 接入节点):运行时由 zeronews/wiring.cjs 落盘,
|
|
107
|
+
// 复用本机客户端时据此认人;不进 sidecar,手机配置口也不开放。
|
|
108
|
+
zeroNewsClientId: '',
|
|
109
|
+
zeroNewsNode: '',
|
|
105
110
|
// FRP 隧道此刻分到的公网地址(运行时由 frpc 发现后写入)。它是**独立一条线路**,
|
|
106
111
|
// 与用户手填的「TCP 直连」分开:那条归用户,这条归本机跑着的 frpc。
|
|
107
112
|
frpUrl: '',
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 2026-11-27:外部目标提示只在真绕开时给;配了 frp / 手填目标不等于端口被占。
|
|
1
2
|
// 2026-11-27:线路级问题码也搬进来(原先在装配层里占 9 行,把装配层顶过了行数守卫)。
|
|
2
3
|
// 2026-11-25:新增回环入口判据:端口有效性、漂移/遮蔽信号、三条线路落点与兜底原因码,只判据不碰进程。
|
|
3
4
|
'use strict';
|
|
@@ -97,7 +98,7 @@ function routeIssueOf(input = {}) {
|
|
|
97
98
|
let routeIssue = '';
|
|
98
99
|
if (signals.needsBypass === true && ingressPort > 0 && input.hasLegacyTunnel === true
|
|
99
100
|
&& validPort(input.legacyTunnelPort) !== ingressPort) routeIssue = 'zeronews-stale';
|
|
100
|
-
else if (input.externalTarget === true) routeIssue = 'external-target';
|
|
101
|
+
else if (signals.needsBypass === true && input.externalTarget === true) routeIssue = 'external-target';
|
|
101
102
|
else if (signals.conflict === 'shadowed' && ingressPort === 0) routeIssue = 'port-conflict';
|
|
102
103
|
return { fallbackReason, routeIssue };
|
|
103
104
|
}
|
|
@@ -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();
|
|
@@ -70,7 +70,7 @@ const { createSelfCheck } = require('../mobile/self-check.cjs');
|
|
|
70
70
|
// 「查有没有新版」与「装新版」这两格都归插件自己:查直接问 npm 注册表,装在 profile 里跑
|
|
71
71
|
// 它自己的包管理器(见 `../update-registry.cjs` / `../update-install.cjs`)。不再借道市场。
|
|
72
72
|
const { checkForUpdate } = require('../update-registry.cjs');
|
|
73
|
-
const { declaredSource, profileRegistry } = require('../update-install.cjs');
|
|
73
|
+
const { declaredSource, profileRegistry, readUpdateLog, UPDATE_LOG_KEEP_DAYS } = require('../update-install.cjs');
|
|
74
74
|
const { clearCompletionForAllDevices, invalidateSessionList } = require('../mobile/session-cache.js');
|
|
75
75
|
const { recordSessionRead } = require('../mobile/session-last-turn.js');
|
|
76
76
|
// 收件目录的占用与清理:和移动端那条路由是同一份实现(`lib/mobile/inbox-clean.js`)。
|
|
@@ -1619,6 +1619,11 @@ function registerControlPlaneRoutes(deps) {
|
|
|
1619
1619
|
}
|
|
1620
1620
|
return sendJson(res, 200, { ok: outcome.installed || outcome.skipped, data: outcome })
|
|
1621
1621
|
}) })
|
|
1622
|
+
// 更新日志:把装包模块落在 <DSH_HOME>/logs 的那几行原样读回给面板查看/复制。只读本机文件,
|
|
1623
|
+
// 内容已由写入端限长、只记事实;老版本没有这个模块时回空串,面板照常显示「暂无日志」。
|
|
1624
|
+
registerRoute({ kind: 'exact', path: '/api/relay/update/log', handler: localOnly('GET', async (_req, res) => {
|
|
1625
|
+
return sendJson(res, 200, { ok: true, data: { text: readUpdateLog(), keepDays: UPDATE_LOG_KEEP_DAYS } });
|
|
1626
|
+
}) })
|
|
1622
1627
|
// 自动更新开关(默认关)。开=外壳每 2 分钟问一次有没有新版,有就自己装并就地切换
|
|
1623
1628
|
// (轮询住在外壳里,因为「没人看着也要发生」;装与换代用的就是上面这两条同一套实现)。
|
|
1624
1629
|
registerRoute({ kind: 'exact', path: '/api/relay/update/auto', handler: localOnly('POST', async (req, res) => {
|
|
@@ -1797,6 +1802,7 @@ const WEB_ACCESS_ROUTES = new Set([
|
|
|
1797
1802
|
'/api/relay/update/check',
|
|
1798
1803
|
'/api/relay/update/apply',
|
|
1799
1804
|
'/api/relay/update/auto',
|
|
1805
|
+
'/api/relay/update/log',
|
|
1800
1806
|
'/api/relay/update/ota/status',
|
|
1801
1807
|
'/api/relay/update/ota/check',
|
|
1802
1808
|
'/api/relay/update/ota/apply',
|
|
@@ -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
|
// 换地址这条路**等新隧道真的注册上**再返回:注册不上要把错误一路回给调用方,
|