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.
@@ -8,6 +8,8 @@ const fs = require('node:fs');
8
8
  const path = require('node:path');
9
9
  const { spawn } = require('node:child_process');
10
10
  const { dshHome } = require('../shared/paths.js');
11
+ const { nextRestartDelay } = require('../shared/restart-backoff.cjs');
12
+ const { cloudflaredEdgeIpVersion } = require('../relay/net-family.cjs');
11
13
 
12
14
  const RESTART_DELAYS_MS = [1000, 2000, 4000, 8000, 16000];
13
15
  // 起进程后这么久还没连上 Cloudflare 边缘,就认定「连不上」(国内被屏蔽/代理拦截很常见),
@@ -89,6 +91,9 @@ function createCloudflaredRunner(options = {}) {
89
91
  const fsImpl = options.fsImpl || fs;
90
92
  const setTimer = options.setTimerImpl || options.setTimeoutImpl || setTimeout;
91
93
  const clearTimer = options.clearTimerImpl || options.clearTimeoutImpl || clearTimeout;
94
+ const random = typeof options.random === 'function' ? options.random : Math.random;
95
+ // 出站协议族策略可能是「取值器」(跟随时随配置变),也可能直接是字符串。
96
+ const ipVersionPolicyOf = typeof options.ipVersionPolicy === 'function' ? options.ipVersionPolicy : () => options.ipVersionPolicy;
92
97
  const sleep = typeof options.sleepImpl === 'function' ? options.sleepImpl : null;
93
98
  // 连接超时单独一套定时器:默认走真实 setTimeout,和「崩溃重连」那套 setTimerImpl 互不影响。
94
99
  const connectTimeoutMs = Number(options.connectTimeoutMs) > 0 ? Number(options.connectTimeoutMs) : CONNECT_TIMEOUT_MS;
@@ -166,12 +171,15 @@ function createCloudflaredRunner(options = {}) {
166
171
  }
167
172
 
168
173
  function scheduleRestart() {
169
- if (!desired || exists(paths.disabled) || retryTimer !== null || retries >= RESTART_DELAYS_MS.length) return;
174
+ if (!desired || exists(paths.disabled) || retryTimer !== null) return;
170
175
  const token = generation;
176
+ // 退避表用尽后转固定长间隔继续重试:一次网络风暴耗光机会后兜底隧道不能就此静默死掉。
177
+ const { ms } = nextRestartDelay(retries, { delays: RESTART_DELAYS_MS, random });
178
+ retries += 1;
171
179
  retryTimer = setTimer(() => {
172
180
  retryTimer = null;
173
181
  if (desired && generation === token && !exists(paths.disabled)) launch().catch(() => {});
174
- }, RESTART_DELAYS_MS[retries++]);
182
+ }, ms);
175
183
  if (retryTimer && typeof retryTimer.unref === 'function') retryTimer.unref();
176
184
  }
177
185
 
@@ -201,8 +209,12 @@ function createCloudflaredRunner(options = {}) {
201
209
  if (waitingForPort) { error = ''; return; }
202
210
  binary = got.path;
203
211
  let proc;
212
+ // ipv4-first / ipv4-only 时让 cloudflared 只连 Cloudflare 边缘的 IPv4 地址,绕开 IPv6 黑洞。
213
+ const edge = cloudflaredEdgeIpVersion(ipVersionPolicyOf());
214
+ const args = ['tunnel', '--url', `http://127.0.0.1:${port}`, '--no-autoupdate'];
215
+ if (edge) args.push('--edge-ip-version', edge);
204
216
  try {
205
- proc = spawnImpl(binary, ['tunnel', '--url', `http://127.0.0.1:${port}`, '--no-autoupdate'], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
217
+ proc = spawnImpl(binary, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
206
218
  } catch (err) {
207
219
  error = describeSpawnFailure(err, binary);
208
220
  scheduleRestart();
@@ -359,6 +371,14 @@ function createCloudflaredRunner(options = {}) {
359
371
  return status();
360
372
  }
361
373
 
374
+ /** 协议族策略变了:正在跑就重启一次让新的 --edge-ip-version 生效;没在跑就不管。 */
375
+ async function restartForPolicy() {
376
+ if (!desired) return status();
377
+ stopProcess();
378
+ retries = 0;
379
+ return launch();
380
+ }
381
+
362
382
  /** 宿主卸载/退出:杀进程、清地址、解绑监听,不动关闭标记(用户此刻的开/关意图照旧保留)。 */
363
383
  function dispose() {
364
384
  desired = false;
@@ -370,7 +390,7 @@ function createCloudflaredRunner(options = {}) {
370
390
  }
371
391
 
372
392
  return {
373
- status, start, stop, syncLocalPort, dispose,
393
+ status, start, stop, syncLocalPort, dispose, restartForPolicy,
374
394
  get runId() { return generation; },
375
395
  setAddressListener(listener) {
376
396
  addressListener = typeof listener === 'function' ? listener : null;
@@ -49,7 +49,7 @@ function mountCloudflare(options) {
49
49
  // 运行器创建本身万一抛错,也不能让插件加载失败:给一个「不可用但可查询原因」的降级壳。
50
50
  let runner;
51
51
  try {
52
- runner = host && host.runner ? host.runner : createCloudflaredRunner({ portOf });
52
+ runner = host && host.runner ? host.runner : createCloudflaredRunner({ portOf, ipVersionPolicy: () => state.ipVersionPolicy });
53
53
  } catch (error) {
54
54
  warn('Cloudflare 隧道运行器创建失败:%s', error && error.message ? error.message : error);
55
55
  const degraded = () => ({ available: false, running: false, pid: null, url: '', error: `Cloudflare 隧道初始化失败:${error && error.message ? error.message : error}`, startedAt: 0, starting: false, retrying: false, waitingForPort: false, enabled: false });
@@ -120,7 +120,15 @@ function mountCloudflare(options) {
120
120
  * 起兜底前先备份手填地址,停止时一并还原;有别的线路时不重复起。
121
121
  */
122
122
  let fallbackOn = false;
123
+ // 上一次 reconcile 时的协议族策略:变了就重启正在跑的 cloudflared,让 --edge-ip-version 生效。
124
+ let lastIpVersionPolicy = null;
123
125
  const reconcile = async (initial = false) => {
126
+ const policy = state.ipVersionPolicy || 'auto';
127
+ if (lastIpVersionPolicy !== null && policy !== lastIpVersionPolicy && typeof runner.restartForPolicy === 'function') {
128
+ const now = status();
129
+ if (now.running || now.starting) await runner.restartForPolicy();
130
+ }
131
+ lastIpVersionPolicy = policy;
124
132
  if (!hasGate) return runner.status();
125
133
  if (shouldFallback()) {
126
134
  if (!fallbackOn) { await rememberManual(); fallbackOn = true; }
@@ -1,4 +1,4 @@
1
- // FRP 等待真实监听端口并跟随运行中变更,异常退出有限重试,主动停止取消待启动工作。
1
+ // FRP 等待真实监听端口并跟随运行中变更,异常退出退避重启且封顶后不放弃,主动停止取消待启动工作。
2
2
  'use strict';
3
3
 
4
4
  /** 本机 frpc 的配置准备、进程起停和服务端分配地址读取。 */
@@ -8,6 +8,7 @@ const crypto = require('node:crypto');
8
8
  const { spawn } = require('node:child_process');
9
9
  const { dshHome } = require('../shared/paths.js');
10
10
  const { ensureFrpc } = require('./provision.cjs');
11
+ const { nextRestartDelay } = require('../shared/restart-backoff.cjs');
11
12
  const DEFAULT_ADMIN_PORT = 17401;
12
13
  const RESTART_DELAYS_MS = [1000, 2000, 4000, 8000, 16000];
13
14
 
@@ -90,6 +91,7 @@ function createFrpcRunner(options = {}) {
90
91
  const adminPort = Number.isInteger(options.adminPort) ? options.adminPort : DEFAULT_ADMIN_PORT;
91
92
  const setTimer = options.setTimeoutImpl || setTimeout;
92
93
  const clearTimer = options.clearTimeoutImpl || clearTimeout;
94
+ const random = typeof options.random === 'function' ? options.random : Math.random;
93
95
  let child = null;
94
96
  let binary = '';
95
97
  let error = '';
@@ -188,12 +190,15 @@ function createFrpcRunner(options = {}) {
188
190
  }
189
191
 
190
192
  function scheduleRestart() {
191
- if (!desired || !exists(paths.enabled) || retryTimer !== null || retries >= RESTART_DELAYS_MS.length) return;
193
+ if (!desired || !exists(paths.enabled) || retryTimer !== null) return;
192
194
  const token = generation;
195
+ // 退避表用尽后转固定长间隔继续重试:一次网络风暴耗光机会后穿透不能就此静默死掉。
196
+ const { ms } = nextRestartDelay(retries, { delays: RESTART_DELAYS_MS, random });
197
+ retries += 1;
193
198
  retryTimer = setTimer(() => {
194
199
  retryTimer = null;
195
200
  if (desired && generation === token && exists(paths.enabled)) void launch();
196
- }, RESTART_DELAYS_MS[retries++]);
201
+ }, ms);
197
202
  if (retryTimer && typeof retryTimer.unref === 'function') retryTimer.unref();
198
203
  }
199
204
 
package/lib/impl.js CHANGED
@@ -44,7 +44,7 @@ const { deviceMetaFromHeaders } = require('./shared/device-headers.js')
44
44
  const { createSidecarLifecycle, createRouteAdopter, createTunnelReconnector, sidecarFingerprint } = require('./sidecar-lifecycle.cjs')
45
45
  const { createMirrorPusher } = require('./mirror/pusher.cjs')
46
46
  const { randomBytes } = require('node:crypto')
47
- const { lanUrls, advertisedCandidates, phoneCandidates, ipv6Candidates, withManualIpv6Candidate } = require('./relay/lan-network.cjs')
47
+ const { lanUrls, advertisedCandidates, phoneCandidates, ipv6Candidates, withManualIpv6Candidate, setIpVersionPolicy } = require('./relay/lan-network.cjs')
48
48
  // 配对二维码的载荷:面板与终端命令共用一份,拼装在 `./relay/pairing-payload.cjs`。
49
49
  const { pairingPayload, pairingText } = require('./relay/pairing-payload.cjs')
50
50
  // 总控上报客户端:把本机全部连接地址报给总控、拿回设备令牌(见 lib/relay/control.js)。
@@ -175,6 +175,7 @@ function createConfigStore(state) {
175
175
  }
176
176
  core.normalizeRelayAddresses(parsed)
177
177
  Object.assign(state, parsed)
178
+ setIpVersionPolicy(state.ipVersionPolicy)
178
179
  core.saveState(state)
179
180
  if (options.notify !== false) notify()
180
181
  return configOf(state)
@@ -275,6 +276,8 @@ function apply(ctx) {
275
276
  }
276
277
 
277
278
  const state = core.loadState()
279
+ // 先把出站协议族策略设进候选/上报那一层(本进程),httpOnly 时 IPv6 候选从这里起就不产出。
280
+ setIpVersionPolicy(state.ipVersionPolicy)
278
281
  // 这台机器上是否还绑着远程电脑:关掉手机「局域网直连」时,只要还有远程电脑,局域网监听口
279
282
  // 仍要开着给它们用。启动时从凭据库读一次,之后由 add/remove 回调更新。
280
283
  let hasRemoteBindings = false
@@ -366,7 +369,7 @@ function apply(ctx) {
366
369
  // (实现被单独挂载 / 测试)时退回本地创建,行为与从前一致。配置由这一代组装后交给它。
367
370
  // 下发配置的闭包同样会被外壳持有的 sidecar 跨代调用,沿用上面挂载时缓存的父端口 / 绑定地址,
368
371
  // 免得本代 ctx 已 inactive 时现读 ctx.webServer 抛错,把重启与配置下发全打挂(隧道、frpc、P2P)。
369
- const buildSidecarConfig = (lanPort) => ({ enabled: state.enabled, relayUrl: state.relayUrl, relayUrls: core.relayAddressesOf(state).relayUrls, instanceId: state.instanceId, previousInstanceId: state.previousInstanceId || '', pairingCode: state.pairingCode, pairingTicket: state.pairingTicket || '', pairingTier: permissions.isKnownTier(state.pairingTier) ? state.pairingTier : permissions.DEFAULT_TIER, name: state.name, upstreamPort: webPortForSidecar, upstreamHost: webHostForSidecar, lanPort, lanPortLockReason: portLock(), lanEnabled: effectiveLanEnabled(), lanSecret: state.lanSecret, registerSecret: state.registerSecret, tunnelIngressPort: state.tunnelIngressPort || 0 })
372
+ const buildSidecarConfig = (lanPort) => ({ enabled: state.enabled, relayUrl: state.relayUrl, relayUrls: core.relayAddressesOf(state).relayUrls, instanceId: state.instanceId, previousInstanceId: state.previousInstanceId || '', pairingCode: state.pairingCode, pairingTicket: state.pairingTicket || '', pairingTier: permissions.isKnownTier(state.pairingTier) ? state.pairingTier : permissions.DEFAULT_TIER, name: state.name, upstreamPort: webPortForSidecar, upstreamHost: webHostForSidecar, lanPort, lanPortLockReason: portLock(), lanEnabled: effectiveLanEnabled(), lanSecret: state.lanSecret, registerSecret: state.registerSecret, tunnelIngressPort: state.tunnelIngressPort || 0, ipVersionPolicy: state.ipVersionPolicy })
370
373
  let hostedSidecar = null
371
374
  try { hostedSidecar = typeof ctx.get === 'function' ? ctx.get('dshMobileSidecarHost') || null : null } catch { hostedSidecar = null }
372
375
  // pluginLibDir 显式传本代目录(re-fork 前清的是正在跑的这份缓存);buildConfig 字段集是 worker 启动契约
@@ -147,6 +147,9 @@ async function handleDeviceStream(ctx, req, res) {
147
147
  'x-dsh-heartbeat-ms': String(HEARTBEAT_MS),
148
148
  'cache-control': 'no-cache',
149
149
  connection: 'keep-alive',
150
+ // 与会话流同一口径:禁掉中间层缓冲与压缩,心跳帧才能按时到达,App 不会误杀健康流。
151
+ 'x-accel-buffering': 'no',
152
+ 'content-encoding': 'identity',
150
153
  ...(sealFrame ? { 'x-dsh-proto': '2' } : {}),
151
154
  });
152
155
  } catch { return; }
@@ -32,6 +32,7 @@ const { probeInstanceId, verifyRelayRegistration } = require('../relay/verify.js
32
32
  const { probeRelayHealth, relayFailureMessage } = require('../relay/relay-probe.js');
33
33
  const { canListen } = require('../relay/port-allocator.cjs');
34
34
  const { lanCandidates, publicCandidates, ipv6Candidates, withManualIpv6Candidate } = require('../relay/lan-network.cjs');
35
+ const { POLICIES: IP_VERSION_POLICIES, normalizeIpVersionPolicy, outboundAgentFor } = require('../relay/net-family.cjs');
35
36
  // 地址分栏校验与面板保存路径共用同一份实现和文案(面板那条路曾只挡类型 / 长度,Tailscale
36
37
  // 这类存了也不生效的地址能被默默存下)。
37
38
  const { addressSlotProblem } = require('../relay/address-slot.cjs');
@@ -49,7 +50,7 @@ const { openHistoryBlob } = require('../mirror/history-blob.cjs');
49
50
  *
50
51
  * 取不到(没开上报 / 没令牌 / 没 HK / 暂离线 / 解不开)一律回 null,由上层如实说「没比成」。
51
52
  */
52
- function queryControlDirectory(url, token, instanceId, historyKey, timeoutMs = 4000) {
53
+ function queryControlDirectory(url, token, instanceId, historyKey, timeoutMs = 4000, ipVersionPolicy) {
53
54
  return new Promise((resolve) => {
54
55
  if (!url || !token || !instanceId || !historyKey) return resolve(null);
55
56
  let settled = false;
@@ -65,7 +66,9 @@ function queryControlDirectory(url, token, instanceId, historyKey, timeoutMs = 4
65
66
  timer.unref?.();
66
67
  try {
67
68
  const base = controlWsUrl(url);
68
- ws = new WebSocket(`${base}/ws/app?instanceId=${encodeURIComponent(instanceId)}&token=${encodeURIComponent(token)}`);
69
+ const target = `${base}/ws/app?instanceId=${encodeURIComponent(instanceId)}&token=${encodeURIComponent(token)}`;
70
+ const agent = outboundAgentFor(ipVersionPolicy, /^wss:/i.test(target));
71
+ ws = agent ? new WebSocket(target, { agent }) : new WebSocket(target);
69
72
  ws.on('open', () => { try { ws.send(JSON.stringify({ type: 'watch' })); } catch { finish(null); } });
70
73
  ws.on('message', (raw) => {
71
74
  let msg;
@@ -129,6 +132,8 @@ function configView(state) {
129
132
  pairingPolicy: pairingApproval.normalize(state.pairingPolicy),
130
133
  // 「自动上报网络地址」(总控上报)开关。非 false 一律当开,与宿主 configOf 同一口径。
131
134
  controlReportEnabled: state.controlReportEnabled !== false,
135
+ // 出站协议族策略:auto / ipv4-first / ipv4-only(口径见 relay/net-family.cjs)。
136
+ ipVersionPolicy: normalizeIpVersionPolicy(state.ipVersionPolicy),
132
137
  preferredLanAddress: typeof state.preferredLanAddress === 'string' ? state.preferredLanAddress : '',
133
138
  manualLanUrl: typeof state.manualLanUrl === 'string' ? state.manualLanUrl : '',
134
139
  manualIpv6Url: typeof state.manualIpv6Url === 'string' ? state.manualIpv6Url : '',
@@ -192,6 +197,13 @@ function configPatch(body) {
192
197
  if (typeof body.controlReportEnabled !== 'boolean') return { ok: false, message: 'controlReportEnabled 必须是布尔值' };
193
198
  patch.controlReportEnabled = body.controlReportEnabled;
194
199
  }
200
+ // 出站协议族策略:只认三档枚举,别的值整次拒绝。
201
+ if (body.ipVersionPolicy !== undefined) {
202
+ if (!IP_VERSION_POLICIES.includes(body.ipVersionPolicy)) {
203
+ return { ok: false, message: `ipVersionPolicy 只能是 ${IP_VERSION_POLICIES.join(' / ')}` };
204
+ }
205
+ patch.ipVersionPolicy = body.ipVersionPolicy;
206
+ }
195
207
  if (body.registerSecret !== undefined) {
196
208
  if (typeof body.registerSecret !== 'string' || body.registerSecret.length > 512) {
197
209
  return { ok: false, message: '注册密钥必须是 512 字以内的字符串' };
@@ -329,6 +341,7 @@ function createRelayControlHandlers(deps) {
329
341
  upstreamPort,
330
342
  name: typeof state.name === 'string' ? state.name : '',
331
343
  registerSecret: patch.registerSecret === undefined ? state.registerSecret : patch.registerSecret,
344
+ ipVersionPolicy: state.ipVersionPolicy,
332
345
  });
333
346
  return { ok: true };
334
347
  } catch (error) {
@@ -673,7 +686,7 @@ function createRelayControlHandlers(deps) {
673
686
  if (snapshot.published === true && snapshot.connected === true && typeof getHistoryKey === 'function') {
674
687
  try {
675
688
  const historyKey = getHistoryKey() || '';
676
- const plain = await queryControlDirectory(snapshot.url, snapshot.token, state && state.instanceId, historyKey);
689
+ const plain = await queryControlDirectory(snapshot.url, snapshot.token, state && state.instanceId, historyKey, 4000, state && state.ipVersionPolicy);
677
690
  if (plain && Array.isArray(plain.addresses)) {
678
691
  stored = plain.addresses
679
692
  .map((item) => ({ kind: typeof item?.kind === 'string' ? item.kind : '', url: String(item?.url || '').trim() }))