dsh-mobile-ios 0.2.16 → 0.2.18
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/LICENSE +21 -21
- package/README.md +311 -284
- package/cordis.patch.yml +20 -20
- package/entries/plugin.mjs +197 -223
- package/entries/sidecar.mjs +92 -111
- package/lib/client.js +1754 -1621
- package/lib/vendor/qrcode-generator.cjs +2297 -2297
- package/lib/vendor/qrcode-utf8.cjs +26 -26
- package/package.json +3 -2
- package/src/adapter/artifacts.mjs +235 -235
- package/src/adapter/cordis-host.mjs +1444 -1225
- package/src/adapter/mock-host.mjs +498 -430
- package/src/adapter/mux-host.mjs +99 -99
- package/src/adapter/session-history.mjs +241 -241
- package/src/cloudflare.mjs +735 -698
- package/src/dns-label.mjs +32 -32
- package/src/dns-probe.mjs +110 -110
- package/src/file-log.mjs +68 -68
- package/src/gateway.mjs +285 -285
- package/src/host-name.mjs +42 -0
- package/src/pairing.mjs +300 -300
- package/src/protocol.mjs +59 -59
- package/src/provision-local.mjs +883 -560
- package/src/provision-select.mjs +105 -0
- package/src/rest.mjs +958 -894
- package/src/ring.mjs +148 -148
- package/src/server.mjs +246 -246
- package/src/tunnel-error.mjs +91 -0
- package/src/tunnel-state.mjs +122 -0
- package/src/tunnel.mjs +544 -544
- package/src/version.mjs +24 -24
- package/src/ws.mjs +332 -332
- package/src/zone-health.mjs +430 -251
package/src/tunnel.mjs
CHANGED
|
@@ -1,544 +1,544 @@
|
|
|
1
|
-
// tunnel.mjs — cloudflared Quick Tunnel 生命周期(GW-8)
|
|
2
|
-
//
|
|
3
|
-
// 设计原则:
|
|
4
|
-
// 1. **绝不伪装可用**。cloudflared 未安装时返回 4021(能力缺失),
|
|
5
|
-
// 而不是返回 500 或假地址——客户端据此隐藏入口。
|
|
6
|
-
// 2. **地址漂移必须广播**。Quick Tunnel 重启后域名会变,不通知客户端就会一直连旧地址。
|
|
7
|
-
// 3. **进程必须能被收干净**。网关退出时子进程不能变成孤儿,否则下次启动端口冲突。
|
|
8
|
-
|
|
9
|
-
import { execFileSync, spawn as nodeSpawn } from 'node:child_process';
|
|
10
|
-
import { accessSync, constants, readFileSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
11
|
-
import os from 'node:os';
|
|
12
|
-
import path from 'node:path';
|
|
13
|
-
import { fail } from './protocol.mjs';
|
|
14
|
-
|
|
15
|
-
// cloudflared 把日志写到 stderr,地址形如:
|
|
16
|
-
// 2026-11-15T11:00:01Z INF | https://random-words-1234.trycloudflare.com |
|
|
17
|
-
const URL_PATTERN = /https:\/\/([a-z0-9][a-z0-9-]*)\.trycloudflare\.com/i;
|
|
18
|
-
// named tunnel(带 token 运行)不会打印公网地址——地址是提前在 Cloudflare 侧
|
|
19
|
-
// 绑好的固定域名。它只在连接真正注册成功时打这一行,正好当作「可用」的判据。
|
|
20
|
-
const NAMED_REGISTERED = /Registered tunnel connection|Connection [0-9a-f-]{8,} registered/i;
|
|
21
|
-
const DEFAULT_START_TIMEOUT_MS = 20_000;
|
|
22
|
-
const DEFAULT_RESTART_DELAY_MS = 10_000;
|
|
23
|
-
const LOG_TAIL = 40;
|
|
24
|
-
|
|
25
|
-
// 诊断脱敏(借鉴 dsh-plugin-mobile-gateway 0.12.1):logTail 会进 status() 与诊断包,
|
|
26
|
-
// 可能被粘贴到聊天/issue 里,密钥类字符串必须在记录时就抹掉。
|
|
27
|
-
// · eyJ 开头的 JWT(cloudflared named tunnel token 等)
|
|
28
|
-
// · dt_ 设备令牌(配对凭证,40 位十六进制)
|
|
29
|
-
// · Bearer / Ticket 凭证值
|
|
30
|
-
export function redactSecrets(line) {
|
|
31
|
-
return String(line)
|
|
32
|
-
.replace(/eyJ[A-Za-z0-9._=-]+/g, '[redacted-jwt]')
|
|
33
|
-
.replace(/dt_[0-9a-fA-F]{8,}/g, '[redacted-device-token]')
|
|
34
|
-
.replace(/(Bearer|Ticket)\s+\S+/gi, '$1 [redacted-credential]');
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/** 版本目录按数字分段比较:字符串排序会把 2026.9.1 排到 2026.11.1 前面。 */
|
|
38
|
-
function compareVersionDesc(a, b) {
|
|
39
|
-
const pa = String(a).split(/\D+/).filter(Boolean).map(Number);
|
|
40
|
-
const pb = String(b).split(/\D+/).filter(Boolean).map(Number);
|
|
41
|
-
for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
|
|
42
|
-
const diff = (pb[i] ?? 0) - (pa[i] ?? 0);
|
|
43
|
-
if (diff !== 0) return diff;
|
|
44
|
-
}
|
|
45
|
-
return 0;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/** 在 PATH 里找可执行文件。找不到返回 null(调用方转成 4021)。 */
|
|
49
|
-
export function findCloudflared(explicit, env = process.env) {
|
|
50
|
-
// explicit 的三种形态:
|
|
51
|
-
// · 'auto' —— 走完整发现链
|
|
52
|
-
// · 含分隔符的绝对/相对路径 —— 只认它(显式指定却不存在 = 缺失,不偷偷换别处的二进制)
|
|
53
|
-
// · 裸文件名 —— 当作 PATH 里的名字继续找(历史行为是直接判缺失,
|
|
54
|
-
// 于是 sidecar 的 `--tunnel-bin cloudflared` 永远起不来)
|
|
55
|
-
let name = process.platform === 'win32' ? 'cloudflared.exe' : 'cloudflared';
|
|
56
|
-
if (explicit && explicit !== 'auto') {
|
|
57
|
-
if (explicit.includes('/') || explicit.includes('\\')) {
|
|
58
|
-
try {
|
|
59
|
-
accessSync(explicit, constants.X_OK);
|
|
60
|
-
return explicit;
|
|
61
|
-
} catch {
|
|
62
|
-
return null;
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
name = explicit;
|
|
66
|
-
} else if (env.CLOUDFLARED_BIN) {
|
|
67
|
-
try {
|
|
68
|
-
accessSync(env.CLOUDFLARED_BIN, constants.X_OK);
|
|
69
|
-
return env.CLOUDFLARED_BIN;
|
|
70
|
-
} catch {
|
|
71
|
-
/* 落到组件目录/ PATH 搜索 */
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
// 自举安装落点优先于 PATH:面板「自动安装 cloudflared」把二进制写进组件目录后,
|
|
76
|
-
// 下次 status()/start() 调 findCloudflared 就能立即发现,无需重启插件/宿主。
|
|
77
|
-
// 路径约定与 entries/plugin.mjs 的 resolveCloudflared、cloudflared-install.mjs 一致。
|
|
78
|
-
// home 来源与安装侧相同:USERPROFILE/HOME 优先,便于测试隔离与多用户环境。
|
|
79
|
-
const home = env.USERPROFILE || env.HOME || os.homedir();
|
|
80
|
-
const componentRoot = path.join(home, '.dsh', 'mobile-access', 'components', 'cloudflared');
|
|
81
|
-
try {
|
|
82
|
-
const versions = readdirSync(componentRoot).filter((v) => !v.startsWith('.')).sort(compareVersionDesc);
|
|
83
|
-
for (const v of versions) {
|
|
84
|
-
const candidate = path.join(componentRoot, v, name);
|
|
85
|
-
try {
|
|
86
|
-
accessSync(candidate, constants.X_OK);
|
|
87
|
-
return candidate;
|
|
88
|
-
} catch { /* 该版本目录里没有可执行文件,继续 */ }
|
|
89
|
-
}
|
|
90
|
-
} catch { /* 组件目录不存在,落到 PATH */ }
|
|
91
|
-
|
|
92
|
-
const dirs = (env.PATH || env.Path || '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin').split(path.delimiter);
|
|
93
|
-
for (const dir of dirs) {
|
|
94
|
-
if (!dir) continue;
|
|
95
|
-
const candidate = path.join(dir, name);
|
|
96
|
-
try {
|
|
97
|
-
accessSync(candidate, constants.X_OK);
|
|
98
|
-
return candidate;
|
|
99
|
-
} catch {
|
|
100
|
-
/* 继续找 */
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
return null;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
export class TunnelManager {
|
|
107
|
-
constructor({
|
|
108
|
-
port,
|
|
109
|
-
log = () => {},
|
|
110
|
-
executable = 'auto',
|
|
111
|
-
spawnImpl = nodeSpawn,
|
|
112
|
-
onAddrChanged = () => {},
|
|
113
|
-
env = process.env,
|
|
114
|
-
startTimeoutMs = DEFAULT_START_TIMEOUT_MS,
|
|
115
|
-
// 借鉴 dsh-plugin-mobile-gateway:运行中意外退出后自动重拉(退避 restartDelayMs)。
|
|
116
|
-
// 语义边界:
|
|
117
|
-
// · 只有「已经 running 过然后意外退出」才重拉——启动失败(超时/缺二进制)不重试,
|
|
118
|
-
// 能力缺失属于用户要修的环境问题,无限重试只会空转刷日志;
|
|
119
|
-
// · 显式 stop() 取消重拉(desired=off);
|
|
120
|
-
// · 重拉成功后地址必然漂移,onAddrChanged 会再次广播。
|
|
121
|
-
autoRestart = false,
|
|
122
|
-
restartDelayMs = DEFAULT_RESTART_DELAY_MS,
|
|
123
|
-
// 两种模式:
|
|
124
|
-
// quick —— 匿名隧道,地址随机且重启即变(现状,免费/临时用)
|
|
125
|
-
// named —— Pro 固定地址:token 认证 + 子域在 CF 侧绑好,地址永不漂移
|
|
126
|
-
// named 模式下 token 只能经 resolveNamedTarget 注入,**不进 argv**:
|
|
127
|
-
// argv 在 ps 里对所有本地进程可见,等于把隧道凭据贴在屏幕上。
|
|
128
|
-
mode = 'quick',
|
|
129
|
-
hostname = null,
|
|
130
|
-
resolveNamedTarget = null,
|
|
131
|
-
// 记录 cloudflared 的 pid。宿主被 kill -9 时子进程不会随父进程退出,
|
|
132
|
-
// 会变成孤儿继续占着隧道连接(端口顺延后还会把公网请求打到旧端口)。
|
|
133
|
-
// 下次启动据 pidfile 回收,比从头 pkill cloudflared 安全。
|
|
134
|
-
pidFile = null,
|
|
135
|
-
} = {}) {
|
|
136
|
-
this.port = port;
|
|
137
|
-
this.log = log;
|
|
138
|
-
this.executable = executable;
|
|
139
|
-
this.spawnImpl = spawnImpl;
|
|
140
|
-
this.onAddrChanged = onAddrChanged;
|
|
141
|
-
this.env = env;
|
|
142
|
-
this.startTimeoutMs = startTimeoutMs;
|
|
143
|
-
this.autoRestart = autoRestart;
|
|
144
|
-
this.restartDelayMs = restartDelayMs;
|
|
145
|
-
this.pidFile = pidFile;
|
|
146
|
-
this.mode = mode === 'named' ? 'named' : 'quick';
|
|
147
|
-
this.hostname = hostname;
|
|
148
|
-
this.resolveNamedTarget = resolveNamedTarget;
|
|
149
|
-
|
|
150
|
-
this.state = 'stopped'; // stopped | starting | running | failed | restarting
|
|
151
|
-
this.url = null;
|
|
152
|
-
// lastUrl 跨 stop/start 保留:Quick Tunnel 重启后域名必然变,
|
|
153
|
-
// 若 stop 时把基线一起清掉,就永远检测不到「地址漂移」这个真实场景。
|
|
154
|
-
this.lastUrl = null;
|
|
155
|
-
this.prevUrl = null;
|
|
156
|
-
this.startedAt = null;
|
|
157
|
-
this.error = null;
|
|
158
|
-
this.exitCode = null;
|
|
159
|
-
this.child = null;
|
|
160
|
-
this.pending = null;
|
|
161
|
-
this.logTail = [];
|
|
162
|
-
this.restartTimer = null;
|
|
163
|
-
// desired=on 表示「用户开过隧道且没手动关」——意外退出后据此决定是否重拉
|
|
164
|
-
this.desired = 'off';
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
status() {
|
|
168
|
-
return {
|
|
169
|
-
state: this.state,
|
|
170
|
-
url: this.url,
|
|
171
|
-
mode: this.mode,
|
|
172
|
-
// named 模式即使没启动也能报出固定域名:UI 据此显示「开通后就是这个地址」
|
|
173
|
-
hostname: this.mode === 'named' ? this.hostname : null,
|
|
174
|
-
startedAt: this.startedAt,
|
|
175
|
-
executable: findCloudflared(this.executable, this.env) ? 'found' : 'missing',
|
|
176
|
-
error: this.error,
|
|
177
|
-
// 不返回绝对路径:诊断包会外发,路径属于主机侧信息
|
|
178
|
-
logTail: [...this.logTail],
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* 回收上一轮遗留的 cloudflared。
|
|
184
|
-
*
|
|
185
|
-
* 只杀「确定是自己那条隧道」的进程:pidfile 里的 pid 可能已被系统复用,
|
|
186
|
-
* 所以必须核对命令行同时含 cloudflared 与我们的配置文件,否则宁可放过。
|
|
187
|
-
* 这一步不能省——孤儿进程会一直维持隧道连接,公网请求被分到旧端口时表现为 502。
|
|
188
|
-
*/
|
|
189
|
-
#reapStale() {
|
|
190
|
-
if (!this.pidFile || process.platform === 'win32') return;
|
|
191
|
-
let pid;
|
|
192
|
-
try {
|
|
193
|
-
pid = Number(readFileSync(this.pidFile, 'utf8').trim());
|
|
194
|
-
} catch {
|
|
195
|
-
return; // 没有 pidfile 是最常见的情况
|
|
196
|
-
}
|
|
197
|
-
if (!Number.isInteger(pid) || pid <= 1 || pid === process.pid) {
|
|
198
|
-
this.#dropPid();
|
|
199
|
-
return;
|
|
200
|
-
}
|
|
201
|
-
let cmd = '';
|
|
202
|
-
try {
|
|
203
|
-
cmd = String(execFileSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8' })).trim();
|
|
204
|
-
} catch {
|
|
205
|
-
this.#dropPid();
|
|
206
|
-
return; // 进程已不在
|
|
207
|
-
}
|
|
208
|
-
const ours = cmd.includes('cloudflared') && cmd.includes('tunnel-config');
|
|
209
|
-
if (!ours) {
|
|
210
|
-
this.#dropPid();
|
|
211
|
-
return;
|
|
212
|
-
}
|
|
213
|
-
try {
|
|
214
|
-
process.kill(pid, 'SIGTERM');
|
|
215
|
-
this.log(`tunnel 回收上一轮遗留进程 pid=${pid}`);
|
|
216
|
-
} catch {
|
|
217
|
-
/* 已退出或没权限,交给后续启动判断 */
|
|
218
|
-
}
|
|
219
|
-
this.#dropPid();
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
#writePid(pid) {
|
|
223
|
-
if (!this.pidFile || !pid) return;
|
|
224
|
-
try {
|
|
225
|
-
writeFileSync(this.pidFile, String(pid), { mode: 0o600 });
|
|
226
|
-
} catch {
|
|
227
|
-
/* pidfile 只是优化,写不进去不该影响隧道 */
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
#dropPid() {
|
|
232
|
-
if (!this.pidFile) return;
|
|
233
|
-
try {
|
|
234
|
-
unlinkSync(this.pidFile);
|
|
235
|
-
} catch {
|
|
236
|
-
/* 本来就没有 */
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
#record(line) {
|
|
241
|
-
const text = redactSecrets(String(line).trimEnd());
|
|
242
|
-
if (!text) return;
|
|
243
|
-
this.logTail.push(text);
|
|
244
|
-
if (this.logTail.length > LOG_TAIL) this.logTail.shift();
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
#scheduleRestart() {
|
|
248
|
-
if (!this.autoRestart || this.desired !== 'on') return;
|
|
249
|
-
this.state = 'restarting';
|
|
250
|
-
this.log(`tunnel 意外退出,${Math.round(this.restartDelayMs / 1000)}s 后自动重拉`);
|
|
251
|
-
this.restartTimer = setTimeout(() => {
|
|
252
|
-
this.restartTimer = null;
|
|
253
|
-
if (this.desired !== 'on' || this.state === 'running' || this.pending) return;
|
|
254
|
-
this.start().catch((err) => this.log(`tunnel 重拉失败:${err.message}`));
|
|
255
|
-
}, this.restartDelayMs);
|
|
256
|
-
this.restartTimer.unref?.();
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
async start() {
|
|
260
|
-
if (this.state === 'running') return this.status();
|
|
261
|
-
if (this.pending) return this.pending;
|
|
262
|
-
if (this.restartTimer) {
|
|
263
|
-
clearTimeout(this.restartTimer);
|
|
264
|
-
this.restartTimer = null;
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
const exe = findCloudflared(this.executable, this.env);
|
|
268
|
-
if (!exe) {
|
|
269
|
-
this.state = 'failed';
|
|
270
|
-
this.error = '主机未安装 cloudflared';
|
|
271
|
-
const installHint = process.platform === 'win32'
|
|
272
|
-
? '下载 cloudflared.exe 加入 PATH(或设置 CLOUDFLARED_BIN 指向它)'
|
|
273
|
-
: '在主机执行 `brew install cloudflared`,或设置 CLOUDFLARED_BIN 指向可执行文件';
|
|
274
|
-
const err = fail(4021, '主机未安装 cloudflared,无法开启隧道', {
|
|
275
|
-
detail: installHint,
|
|
276
|
-
});
|
|
277
|
-
throw err;
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
this.state = 'starting';
|
|
281
|
-
this.error = null;
|
|
282
|
-
this.exitCode = null;
|
|
283
|
-
|
|
284
|
-
// 起新进程前先收掉上一轮的遗留(宿主被强杀时会留下孤儿)
|
|
285
|
-
this.#reapStale();
|
|
286
|
-
|
|
287
|
-
this.pending = new Promise((resolve, reject) => {
|
|
288
|
-
let settled = false;
|
|
289
|
-
let timer = null;
|
|
290
|
-
const finish = (fn, value) => {
|
|
291
|
-
if (settled) return;
|
|
292
|
-
settled = true;
|
|
293
|
-
if (timer) clearTimeout(timer);
|
|
294
|
-
this.pending = null;
|
|
295
|
-
fn(value);
|
|
296
|
-
};
|
|
297
|
-
|
|
298
|
-
const spawnTunnel = (target) => {
|
|
299
|
-
const named = this.mode === 'named';
|
|
300
|
-
// named 有两种落地形态,对外都是「固定地址」:
|
|
301
|
-
// · token 形态(remotely-managed)→ TUNNEL_TOKEN 环境变量 + 远端 ingress
|
|
302
|
-
// · 本地管理型(cloudflared 自己的证书)→ --config 指向本地 ingress
|
|
303
|
-
// 两种都不用 --url:路由由 ingress 决定,本地再给 --url 会把它覆盖掉。
|
|
304
|
-
// 参数顺序有讲究:`run` 是 cloudflared 的子命令,`--config` / `--no-autoupdate`
|
|
305
|
-
// 都属于 `tunnel` 这一层,必须放在 `run` **之前**。
|
|
306
|
-
// 放到 `run` 之后会被当成 run 自己的选项,直接
|
|
307
|
-
// "flag provided but not defined: -no-autoupdate" 退出(真机才会踩到)。
|
|
308
|
-
// named 保持默认 QUIC:本机实测(深圳 → 洛杉矶边缘)QUIC 稳定 3.1–3.4s,
|
|
309
|
-
// 强制 http2 反而出现 12s 与直接超时。瓶颈是国际链路,不是协议。
|
|
310
|
-
// quick 仍用 http2——那是短命地址,优先保证在受限网络下能建起来。
|
|
311
|
-
const args = named
|
|
312
|
-
? (target?.configFile
|
|
313
|
-
? ['tunnel', '--config', target.configFile, '--no-autoupdate', 'run']
|
|
314
|
-
: ['tunnel', '--no-autoupdate', 'run'])
|
|
315
|
-
: ['tunnel', '--url', `http://127.0.0.1:${this.port}`, '--no-autoupdate', '--protocol', 'http2'];
|
|
316
|
-
const childEnv = target?.token ? { ...this.env, TUNNEL_TOKEN: target.token } : this.env;
|
|
317
|
-
|
|
318
|
-
let child;
|
|
319
|
-
try {
|
|
320
|
-
child = this.spawnImpl(exe, args, { stdio: ['ignore', 'pipe', 'pipe'], env: childEnv });
|
|
321
|
-
} catch (err) {
|
|
322
|
-
this.state = 'failed';
|
|
323
|
-
this.error = `无法启动 cloudflared:${err.message}`;
|
|
324
|
-
finish(reject, fail(4021, this.error));
|
|
325
|
-
return;
|
|
326
|
-
}
|
|
327
|
-
this.child = child;
|
|
328
|
-
this.#writePid(child.pid);
|
|
329
|
-
|
|
330
|
-
timer = setTimeout(() => {
|
|
331
|
-
this.state = 'failed';
|
|
332
|
-
this.error = named
|
|
333
|
-
? `隧道启动超时(${Math.round(this.startTimeoutMs / 1000)}s 内未连上 Cloudflare)`
|
|
334
|
-
: '隧道启动超时(20s 内未拿到地址)';
|
|
335
|
-
try {
|
|
336
|
-
child.kill('SIGTERM');
|
|
337
|
-
} catch {
|
|
338
|
-
/* 忽略 */
|
|
339
|
-
}
|
|
340
|
-
finish(reject, fail(4500, this.error, { detail: this.logTail.slice(-3).join(' | ') }));
|
|
341
|
-
}, this.startTimeoutMs);
|
|
342
|
-
timer.unref?.();
|
|
343
|
-
|
|
344
|
-
const onChunk = (chunk) => {
|
|
345
|
-
const text = chunk.toString('utf8');
|
|
346
|
-
for (const line of text.split('\n')) {
|
|
347
|
-
this.#record(line);
|
|
348
|
-
if (settled) continue;
|
|
349
|
-
if (named) {
|
|
350
|
-
if (!NAMED_REGISTERED.test(line)) continue;
|
|
351
|
-
// 地址是既定的固定域名,不存在漂移;running 的判据是「连接真的注册成功」,
|
|
352
|
-
// 而不是「进程起来了」——后者会在出口被墙时给用户一个连不上的假绿灯。
|
|
353
|
-
const url = `https://${this.hostname}`;
|
|
354
|
-
this.url = url;
|
|
355
|
-
this.lastUrl = url;
|
|
356
|
-
this.state = 'running';
|
|
357
|
-
this.startedAt = new Date().toISOString();
|
|
358
|
-
this.desired = 'on';
|
|
359
|
-
this.log(`tunnel up url=${url} (named)`);
|
|
360
|
-
finish(resolve, this.status());
|
|
361
|
-
continue;
|
|
362
|
-
}
|
|
363
|
-
const match = URL_PATTERN.exec(line);
|
|
364
|
-
if (!match) continue;
|
|
365
|
-
const url = `https://${match[1]}.trycloudflare.com`;
|
|
366
|
-
const previous = this.lastUrl;
|
|
367
|
-
this.url = url;
|
|
368
|
-
this.lastUrl = url;
|
|
369
|
-
this.state = 'running';
|
|
370
|
-
this.startedAt = new Date().toISOString();
|
|
371
|
-
this.desired = 'on';
|
|
372
|
-
this.log(`tunnel up url=${url}`);
|
|
373
|
-
if (previous && previous !== url) {
|
|
374
|
-
this.prevUrl = previous;
|
|
375
|
-
this.log(`tunnel addr changed ${previous} → ${url}`);
|
|
376
|
-
// 地址漂移:必须广播,否则客户端一直连旧域名
|
|
377
|
-
this.onAddrChanged(url, previous);
|
|
378
|
-
}
|
|
379
|
-
finish(resolve, this.status());
|
|
380
|
-
}
|
|
381
|
-
};
|
|
382
|
-
|
|
383
|
-
child.stdout?.on('data', onChunk);
|
|
384
|
-
child.stderr?.on('data', onChunk);
|
|
385
|
-
|
|
386
|
-
child.on('error', (err) => {
|
|
387
|
-
this.state = 'failed';
|
|
388
|
-
this.error = `cloudflared 进程错误:${err.message}`;
|
|
389
|
-
this.child = null;
|
|
390
|
-
finish(reject, fail(4021, this.error));
|
|
391
|
-
});
|
|
392
|
-
|
|
393
|
-
child.on('exit', (code, signal) => {
|
|
394
|
-
this.exitCode = code;
|
|
395
|
-
const wasRunning = this.state === 'running';
|
|
396
|
-
if (this.state !== 'stopped') {
|
|
397
|
-
this.state = wasRunning ? 'failed' : this.state;
|
|
398
|
-
if (wasRunning) this.error = `cloudflared 退出(code=${code}, signal=${signal ?? 'none'})`;
|
|
399
|
-
}
|
|
400
|
-
this.child = null;
|
|
401
|
-
this.url = null;
|
|
402
|
-
this.#dropPid();
|
|
403
|
-
this.log(`tunnel exit code=${code} signal=${signal ?? 'none'}`);
|
|
404
|
-
finish(reject, fail(4500, this.error || 'cloudflared 提前退出'));
|
|
405
|
-
// 运行中意外退出(而非启动阶段失败)→ 按退避自动重拉。
|
|
406
|
-
// start() 已 resolved 后的退出 pending 为空、finish 是 no-op,同样走到这里;
|
|
407
|
-
// 显式 stop() 已先把 state 置 stopped 且 desired=off,#scheduleRestart 会拒绝。
|
|
408
|
-
if (wasRunning) this.#scheduleRestart();
|
|
409
|
-
});
|
|
410
|
-
};
|
|
411
|
-
|
|
412
|
-
if (this.mode !== 'named') {
|
|
413
|
-
spawnTunnel(null);
|
|
414
|
-
return;
|
|
415
|
-
}
|
|
416
|
-
if (!this.resolveNamedTarget) {
|
|
417
|
-
this.state = 'failed';
|
|
418
|
-
this.error = '固定地址模式缺少 token 解析器';
|
|
419
|
-
finish(reject, fail(4021, this.error));
|
|
420
|
-
return;
|
|
421
|
-
}
|
|
422
|
-
// token 解析可能要走一次开通服务(网络),放在 pending 里做,
|
|
423
|
-
// 既保证 start() 的单飞语义,也不会让调用方以为隧道已经起来了。
|
|
424
|
-
Promise.resolve()
|
|
425
|
-
.then(() => this.resolveNamedTarget())
|
|
426
|
-
.then((target) => {
|
|
427
|
-
if (settled) return;
|
|
428
|
-
if (!target?.hostname || (!target.token && !target.configFile)) {
|
|
429
|
-
this.state = 'failed';
|
|
430
|
-
this.error = '固定地址未开通(缺少凭据或域名)';
|
|
431
|
-
finish(reject, fail(4021, this.error));
|
|
432
|
-
return;
|
|
433
|
-
}
|
|
434
|
-
this.hostname = target.hostname;
|
|
435
|
-
spawnTunnel(target);
|
|
436
|
-
})
|
|
437
|
-
.catch((err) => {
|
|
438
|
-
this.state = 'failed';
|
|
439
|
-
this.error = err?.message || '开通固定地址失败';
|
|
440
|
-
finish(reject, err?.code ? err : fail(4500, this.error));
|
|
441
|
-
});
|
|
442
|
-
});
|
|
443
|
-
|
|
444
|
-
return this.pending;
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
async stop() {
|
|
448
|
-
// 显式停止即「用户不再要隧道」:取消计划中的重拉,否则 stop 后又悄悄起来。
|
|
449
|
-
this.desired = 'off';
|
|
450
|
-
if (this.restartTimer) {
|
|
451
|
-
clearTimeout(this.restartTimer);
|
|
452
|
-
this.restartTimer = null;
|
|
453
|
-
}
|
|
454
|
-
const child = this.child;
|
|
455
|
-
this.state = 'stopped';
|
|
456
|
-
this.url = null;
|
|
457
|
-
this.child = null;
|
|
458
|
-
this.pending = null;
|
|
459
|
-
if (!child) return { stopped: false, alreadyStopped: true };
|
|
460
|
-
await new Promise((resolve) => {
|
|
461
|
-
const done = () => resolve();
|
|
462
|
-
const timer = setTimeout(done, 3000);
|
|
463
|
-
timer.unref?.();
|
|
464
|
-
child.once('exit', () => {
|
|
465
|
-
clearTimeout(timer);
|
|
466
|
-
resolve();
|
|
467
|
-
});
|
|
468
|
-
try {
|
|
469
|
-
child.kill('SIGTERM');
|
|
470
|
-
} catch {
|
|
471
|
-
clearTimeout(timer);
|
|
472
|
-
resolve();
|
|
473
|
-
}
|
|
474
|
-
});
|
|
475
|
-
// 显式停止也清一次:exit 回调是异步的,用户点停止后 pidfile 不该还指着一个死进程
|
|
476
|
-
this.#dropPid();
|
|
477
|
-
this.log('tunnel stopped');
|
|
478
|
-
return { stopped: true };
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
/**
|
|
483
|
-
* 孤儿隧道清扫(2026-11-16 真机排查发现):DSH 桌面自身的 `dsh web` 每次重启
|
|
484
|
-
* 都会从同一个组件目录(~/.dsh/mobile-access/components/cloudflared/)新拉一个
|
|
485
|
-
* Quick Tunnel,旧的从不回收——指向已死端口的 cloudflared 进程空转堆积
|
|
486
|
-
* (实测一次清理出 13 个)。本函数在插件启动时按「目标端口已死 → 进程是孤儿」
|
|
487
|
-
* 清理该组件目录拉起的隧道:
|
|
488
|
-
* · 只认组件目录二进制(不碰用户自己 PATH 里的 cloudflared);
|
|
489
|
-
* · 只杀目标端口已无人监听的(活端口——包括 DSH 当前 GUI 伴生口和我们自己的
|
|
490
|
-
* 隧道——一律保留);
|
|
491
|
-
* · SIGTERM 优雅退出,1.5s 不退再 SIGKILL。
|
|
492
|
-
*/
|
|
493
|
-
export async function sweepOrphanTunnels({ componentDir, log = () => {} } = {}) {
|
|
494
|
-
if (!componentDir) return { killed: 0 };
|
|
495
|
-
// Windows 没有 pgrep,也不存在「按命令行找进程」的廉价等价物;
|
|
496
|
-
// 孤儿回收在那里靠 pidFile(#reapStale)兜底,这里直接返回,别每次启动都白 throw 一次。
|
|
497
|
-
if (process.platform === 'win32') return { killed: 0 };
|
|
498
|
-
const { execFile } = await import('node:child_process');
|
|
499
|
-
const net = await import('node:net');
|
|
500
|
-
|
|
501
|
-
const portAlive = (port) => new Promise((resolve) => {
|
|
502
|
-
const sock = net.connect({ host: '127.0.0.1', port });
|
|
503
|
-
sock.setTimeout(600);
|
|
504
|
-
sock.once('connect', () => { sock.destroy(); resolve(true); });
|
|
505
|
-
sock.once('error', () => resolve(false));
|
|
506
|
-
sock.once('timeout', () => { sock.destroy(); resolve(false); });
|
|
507
|
-
});
|
|
508
|
-
|
|
509
|
-
const listPids = () => new Promise((resolve) => {
|
|
510
|
-
execFile('/usr/bin/pgrep', ['-fl', 'cloudflared'], (err, stdout) => {
|
|
511
|
-
resolve(err ? [] : String(stdout).split('\n').filter(Boolean));
|
|
512
|
-
});
|
|
513
|
-
});
|
|
514
|
-
|
|
515
|
-
const lines = await listPids();
|
|
516
|
-
const orphans = [];
|
|
517
|
-
for (const line of lines) {
|
|
518
|
-
const pid = Number(line.split(' ')[0]);
|
|
519
|
-
if (!Number.isFinite(pid)) continue;
|
|
520
|
-
// 只认组件目录二进制 + Quick Tunnel 形态(--url http://127.0.0.1:<port>)
|
|
521
|
-
if (!line.includes(componentDir)) continue;
|
|
522
|
-
const m = line.match(/--url\s+https?:\/\/127\.0\.0\.1:(\d+)/);
|
|
523
|
-
if (!m) continue;
|
|
524
|
-
const port = Number(m[1]);
|
|
525
|
-
if (!(await portAlive(port))) orphans.push({ pid, port });
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
let killed = 0;
|
|
529
|
-
for (const { pid, port } of orphans) {
|
|
530
|
-
try {
|
|
531
|
-
process.kill(pid, 'SIGTERM');
|
|
532
|
-
killed += 1;
|
|
533
|
-
log(`tunnel sweep: SIGTERM orphan pid=${pid} (target 127.0.0.1:${port} 已死)`);
|
|
534
|
-
} catch { /* 进程已退出/权限不足,忽略 */ }
|
|
535
|
-
}
|
|
536
|
-
// 宽限后强杀残留
|
|
537
|
-
if (killed > 0) {
|
|
538
|
-
await new Promise((r) => setTimeout(r, 1500));
|
|
539
|
-
for (const { pid } of orphans) {
|
|
540
|
-
try { process.kill(pid, 0); process.kill(pid, 'SIGKILL'); } catch { /* 已退 */ }
|
|
541
|
-
}
|
|
542
|
-
}
|
|
543
|
-
return { killed };
|
|
544
|
-
}
|
|
1
|
+
// tunnel.mjs — cloudflared Quick Tunnel 生命周期(GW-8)
|
|
2
|
+
//
|
|
3
|
+
// 设计原则:
|
|
4
|
+
// 1. **绝不伪装可用**。cloudflared 未安装时返回 4021(能力缺失),
|
|
5
|
+
// 而不是返回 500 或假地址——客户端据此隐藏入口。
|
|
6
|
+
// 2. **地址漂移必须广播**。Quick Tunnel 重启后域名会变,不通知客户端就会一直连旧地址。
|
|
7
|
+
// 3. **进程必须能被收干净**。网关退出时子进程不能变成孤儿,否则下次启动端口冲突。
|
|
8
|
+
|
|
9
|
+
import { execFileSync, spawn as nodeSpawn } from 'node:child_process';
|
|
10
|
+
import { accessSync, constants, readFileSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { fail } from './protocol.mjs';
|
|
14
|
+
|
|
15
|
+
// cloudflared 把日志写到 stderr,地址形如:
|
|
16
|
+
// 2026-11-15T11:00:01Z INF | https://random-words-1234.trycloudflare.com |
|
|
17
|
+
const URL_PATTERN = /https:\/\/([a-z0-9][a-z0-9-]*)\.trycloudflare\.com/i;
|
|
18
|
+
// named tunnel(带 token 运行)不会打印公网地址——地址是提前在 Cloudflare 侧
|
|
19
|
+
// 绑好的固定域名。它只在连接真正注册成功时打这一行,正好当作「可用」的判据。
|
|
20
|
+
const NAMED_REGISTERED = /Registered tunnel connection|Connection [0-9a-f-]{8,} registered/i;
|
|
21
|
+
const DEFAULT_START_TIMEOUT_MS = 20_000;
|
|
22
|
+
const DEFAULT_RESTART_DELAY_MS = 10_000;
|
|
23
|
+
const LOG_TAIL = 40;
|
|
24
|
+
|
|
25
|
+
// 诊断脱敏(借鉴 dsh-plugin-mobile-gateway 0.12.1):logTail 会进 status() 与诊断包,
|
|
26
|
+
// 可能被粘贴到聊天/issue 里,密钥类字符串必须在记录时就抹掉。
|
|
27
|
+
// · eyJ 开头的 JWT(cloudflared named tunnel token 等)
|
|
28
|
+
// · dt_ 设备令牌(配对凭证,40 位十六进制)
|
|
29
|
+
// · Bearer / Ticket 凭证值
|
|
30
|
+
export function redactSecrets(line) {
|
|
31
|
+
return String(line)
|
|
32
|
+
.replace(/eyJ[A-Za-z0-9._=-]+/g, '[redacted-jwt]')
|
|
33
|
+
.replace(/dt_[0-9a-fA-F]{8,}/g, '[redacted-device-token]')
|
|
34
|
+
.replace(/(Bearer|Ticket)\s+\S+/gi, '$1 [redacted-credential]');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 版本目录按数字分段比较:字符串排序会把 2026.9.1 排到 2026.11.1 前面。 */
|
|
38
|
+
function compareVersionDesc(a, b) {
|
|
39
|
+
const pa = String(a).split(/\D+/).filter(Boolean).map(Number);
|
|
40
|
+
const pb = String(b).split(/\D+/).filter(Boolean).map(Number);
|
|
41
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
|
|
42
|
+
const diff = (pb[i] ?? 0) - (pa[i] ?? 0);
|
|
43
|
+
if (diff !== 0) return diff;
|
|
44
|
+
}
|
|
45
|
+
return 0;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 在 PATH 里找可执行文件。找不到返回 null(调用方转成 4021)。 */
|
|
49
|
+
export function findCloudflared(explicit, env = process.env) {
|
|
50
|
+
// explicit 的三种形态:
|
|
51
|
+
// · 'auto' —— 走完整发现链
|
|
52
|
+
// · 含分隔符的绝对/相对路径 —— 只认它(显式指定却不存在 = 缺失,不偷偷换别处的二进制)
|
|
53
|
+
// · 裸文件名 —— 当作 PATH 里的名字继续找(历史行为是直接判缺失,
|
|
54
|
+
// 于是 sidecar 的 `--tunnel-bin cloudflared` 永远起不来)
|
|
55
|
+
let name = process.platform === 'win32' ? 'cloudflared.exe' : 'cloudflared';
|
|
56
|
+
if (explicit && explicit !== 'auto') {
|
|
57
|
+
if (explicit.includes('/') || explicit.includes('\\')) {
|
|
58
|
+
try {
|
|
59
|
+
accessSync(explicit, constants.X_OK);
|
|
60
|
+
return explicit;
|
|
61
|
+
} catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
name = explicit;
|
|
66
|
+
} else if (env.CLOUDFLARED_BIN) {
|
|
67
|
+
try {
|
|
68
|
+
accessSync(env.CLOUDFLARED_BIN, constants.X_OK);
|
|
69
|
+
return env.CLOUDFLARED_BIN;
|
|
70
|
+
} catch {
|
|
71
|
+
/* 落到组件目录/ PATH 搜索 */
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 自举安装落点优先于 PATH:面板「自动安装 cloudflared」把二进制写进组件目录后,
|
|
76
|
+
// 下次 status()/start() 调 findCloudflared 就能立即发现,无需重启插件/宿主。
|
|
77
|
+
// 路径约定与 entries/plugin.mjs 的 resolveCloudflared、cloudflared-install.mjs 一致。
|
|
78
|
+
// home 来源与安装侧相同:USERPROFILE/HOME 优先,便于测试隔离与多用户环境。
|
|
79
|
+
const home = env.USERPROFILE || env.HOME || os.homedir();
|
|
80
|
+
const componentRoot = path.join(home, '.dsh', 'mobile-access', 'components', 'cloudflared');
|
|
81
|
+
try {
|
|
82
|
+
const versions = readdirSync(componentRoot).filter((v) => !v.startsWith('.')).sort(compareVersionDesc);
|
|
83
|
+
for (const v of versions) {
|
|
84
|
+
const candidate = path.join(componentRoot, v, name);
|
|
85
|
+
try {
|
|
86
|
+
accessSync(candidate, constants.X_OK);
|
|
87
|
+
return candidate;
|
|
88
|
+
} catch { /* 该版本目录里没有可执行文件,继续 */ }
|
|
89
|
+
}
|
|
90
|
+
} catch { /* 组件目录不存在,落到 PATH */ }
|
|
91
|
+
|
|
92
|
+
const dirs = (env.PATH || env.Path || '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin').split(path.delimiter);
|
|
93
|
+
for (const dir of dirs) {
|
|
94
|
+
if (!dir) continue;
|
|
95
|
+
const candidate = path.join(dir, name);
|
|
96
|
+
try {
|
|
97
|
+
accessSync(candidate, constants.X_OK);
|
|
98
|
+
return candidate;
|
|
99
|
+
} catch {
|
|
100
|
+
/* 继续找 */
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export class TunnelManager {
|
|
107
|
+
constructor({
|
|
108
|
+
port,
|
|
109
|
+
log = () => {},
|
|
110
|
+
executable = 'auto',
|
|
111
|
+
spawnImpl = nodeSpawn,
|
|
112
|
+
onAddrChanged = () => {},
|
|
113
|
+
env = process.env,
|
|
114
|
+
startTimeoutMs = DEFAULT_START_TIMEOUT_MS,
|
|
115
|
+
// 借鉴 dsh-plugin-mobile-gateway:运行中意外退出后自动重拉(退避 restartDelayMs)。
|
|
116
|
+
// 语义边界:
|
|
117
|
+
// · 只有「已经 running 过然后意外退出」才重拉——启动失败(超时/缺二进制)不重试,
|
|
118
|
+
// 能力缺失属于用户要修的环境问题,无限重试只会空转刷日志;
|
|
119
|
+
// · 显式 stop() 取消重拉(desired=off);
|
|
120
|
+
// · 重拉成功后地址必然漂移,onAddrChanged 会再次广播。
|
|
121
|
+
autoRestart = false,
|
|
122
|
+
restartDelayMs = DEFAULT_RESTART_DELAY_MS,
|
|
123
|
+
// 两种模式:
|
|
124
|
+
// quick —— 匿名隧道,地址随机且重启即变(现状,免费/临时用)
|
|
125
|
+
// named —— Pro 固定地址:token 认证 + 子域在 CF 侧绑好,地址永不漂移
|
|
126
|
+
// named 模式下 token 只能经 resolveNamedTarget 注入,**不进 argv**:
|
|
127
|
+
// argv 在 ps 里对所有本地进程可见,等于把隧道凭据贴在屏幕上。
|
|
128
|
+
mode = 'quick',
|
|
129
|
+
hostname = null,
|
|
130
|
+
resolveNamedTarget = null,
|
|
131
|
+
// 记录 cloudflared 的 pid。宿主被 kill -9 时子进程不会随父进程退出,
|
|
132
|
+
// 会变成孤儿继续占着隧道连接(端口顺延后还会把公网请求打到旧端口)。
|
|
133
|
+
// 下次启动据 pidfile 回收,比从头 pkill cloudflared 安全。
|
|
134
|
+
pidFile = null,
|
|
135
|
+
} = {}) {
|
|
136
|
+
this.port = port;
|
|
137
|
+
this.log = log;
|
|
138
|
+
this.executable = executable;
|
|
139
|
+
this.spawnImpl = spawnImpl;
|
|
140
|
+
this.onAddrChanged = onAddrChanged;
|
|
141
|
+
this.env = env;
|
|
142
|
+
this.startTimeoutMs = startTimeoutMs;
|
|
143
|
+
this.autoRestart = autoRestart;
|
|
144
|
+
this.restartDelayMs = restartDelayMs;
|
|
145
|
+
this.pidFile = pidFile;
|
|
146
|
+
this.mode = mode === 'named' ? 'named' : 'quick';
|
|
147
|
+
this.hostname = hostname;
|
|
148
|
+
this.resolveNamedTarget = resolveNamedTarget;
|
|
149
|
+
|
|
150
|
+
this.state = 'stopped'; // stopped | starting | running | failed | restarting
|
|
151
|
+
this.url = null;
|
|
152
|
+
// lastUrl 跨 stop/start 保留:Quick Tunnel 重启后域名必然变,
|
|
153
|
+
// 若 stop 时把基线一起清掉,就永远检测不到「地址漂移」这个真实场景。
|
|
154
|
+
this.lastUrl = null;
|
|
155
|
+
this.prevUrl = null;
|
|
156
|
+
this.startedAt = null;
|
|
157
|
+
this.error = null;
|
|
158
|
+
this.exitCode = null;
|
|
159
|
+
this.child = null;
|
|
160
|
+
this.pending = null;
|
|
161
|
+
this.logTail = [];
|
|
162
|
+
this.restartTimer = null;
|
|
163
|
+
// desired=on 表示「用户开过隧道且没手动关」——意外退出后据此决定是否重拉
|
|
164
|
+
this.desired = 'off';
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
status() {
|
|
168
|
+
return {
|
|
169
|
+
state: this.state,
|
|
170
|
+
url: this.url,
|
|
171
|
+
mode: this.mode,
|
|
172
|
+
// named 模式即使没启动也能报出固定域名:UI 据此显示「开通后就是这个地址」
|
|
173
|
+
hostname: this.mode === 'named' ? this.hostname : null,
|
|
174
|
+
startedAt: this.startedAt,
|
|
175
|
+
executable: findCloudflared(this.executable, this.env) ? 'found' : 'missing',
|
|
176
|
+
error: this.error,
|
|
177
|
+
// 不返回绝对路径:诊断包会外发,路径属于主机侧信息
|
|
178
|
+
logTail: [...this.logTail],
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 回收上一轮遗留的 cloudflared。
|
|
184
|
+
*
|
|
185
|
+
* 只杀「确定是自己那条隧道」的进程:pidfile 里的 pid 可能已被系统复用,
|
|
186
|
+
* 所以必须核对命令行同时含 cloudflared 与我们的配置文件,否则宁可放过。
|
|
187
|
+
* 这一步不能省——孤儿进程会一直维持隧道连接,公网请求被分到旧端口时表现为 502。
|
|
188
|
+
*/
|
|
189
|
+
#reapStale() {
|
|
190
|
+
if (!this.pidFile || process.platform === 'win32') return;
|
|
191
|
+
let pid;
|
|
192
|
+
try {
|
|
193
|
+
pid = Number(readFileSync(this.pidFile, 'utf8').trim());
|
|
194
|
+
} catch {
|
|
195
|
+
return; // 没有 pidfile 是最常见的情况
|
|
196
|
+
}
|
|
197
|
+
if (!Number.isInteger(pid) || pid <= 1 || pid === process.pid) {
|
|
198
|
+
this.#dropPid();
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
let cmd = '';
|
|
202
|
+
try {
|
|
203
|
+
cmd = String(execFileSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8' })).trim();
|
|
204
|
+
} catch {
|
|
205
|
+
this.#dropPid();
|
|
206
|
+
return; // 进程已不在
|
|
207
|
+
}
|
|
208
|
+
const ours = cmd.includes('cloudflared') && cmd.includes('tunnel-config');
|
|
209
|
+
if (!ours) {
|
|
210
|
+
this.#dropPid();
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
try {
|
|
214
|
+
process.kill(pid, 'SIGTERM');
|
|
215
|
+
this.log(`tunnel 回收上一轮遗留进程 pid=${pid}`);
|
|
216
|
+
} catch {
|
|
217
|
+
/* 已退出或没权限,交给后续启动判断 */
|
|
218
|
+
}
|
|
219
|
+
this.#dropPid();
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
#writePid(pid) {
|
|
223
|
+
if (!this.pidFile || !pid) return;
|
|
224
|
+
try {
|
|
225
|
+
writeFileSync(this.pidFile, String(pid), { mode: 0o600 });
|
|
226
|
+
} catch {
|
|
227
|
+
/* pidfile 只是优化,写不进去不该影响隧道 */
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
#dropPid() {
|
|
232
|
+
if (!this.pidFile) return;
|
|
233
|
+
try {
|
|
234
|
+
unlinkSync(this.pidFile);
|
|
235
|
+
} catch {
|
|
236
|
+
/* 本来就没有 */
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
#record(line) {
|
|
241
|
+
const text = redactSecrets(String(line).trimEnd());
|
|
242
|
+
if (!text) return;
|
|
243
|
+
this.logTail.push(text);
|
|
244
|
+
if (this.logTail.length > LOG_TAIL) this.logTail.shift();
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
#scheduleRestart() {
|
|
248
|
+
if (!this.autoRestart || this.desired !== 'on') return;
|
|
249
|
+
this.state = 'restarting';
|
|
250
|
+
this.log(`tunnel 意外退出,${Math.round(this.restartDelayMs / 1000)}s 后自动重拉`);
|
|
251
|
+
this.restartTimer = setTimeout(() => {
|
|
252
|
+
this.restartTimer = null;
|
|
253
|
+
if (this.desired !== 'on' || this.state === 'running' || this.pending) return;
|
|
254
|
+
this.start().catch((err) => this.log(`tunnel 重拉失败:${err.message}`));
|
|
255
|
+
}, this.restartDelayMs);
|
|
256
|
+
this.restartTimer.unref?.();
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async start() {
|
|
260
|
+
if (this.state === 'running') return this.status();
|
|
261
|
+
if (this.pending) return this.pending;
|
|
262
|
+
if (this.restartTimer) {
|
|
263
|
+
clearTimeout(this.restartTimer);
|
|
264
|
+
this.restartTimer = null;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const exe = findCloudflared(this.executable, this.env);
|
|
268
|
+
if (!exe) {
|
|
269
|
+
this.state = 'failed';
|
|
270
|
+
this.error = '主机未安装 cloudflared';
|
|
271
|
+
const installHint = process.platform === 'win32'
|
|
272
|
+
? '下载 cloudflared.exe 加入 PATH(或设置 CLOUDFLARED_BIN 指向它)'
|
|
273
|
+
: '在主机执行 `brew install cloudflared`,或设置 CLOUDFLARED_BIN 指向可执行文件';
|
|
274
|
+
const err = fail(4021, '主机未安装 cloudflared,无法开启隧道', {
|
|
275
|
+
detail: installHint,
|
|
276
|
+
});
|
|
277
|
+
throw err;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
this.state = 'starting';
|
|
281
|
+
this.error = null;
|
|
282
|
+
this.exitCode = null;
|
|
283
|
+
|
|
284
|
+
// 起新进程前先收掉上一轮的遗留(宿主被强杀时会留下孤儿)
|
|
285
|
+
this.#reapStale();
|
|
286
|
+
|
|
287
|
+
this.pending = new Promise((resolve, reject) => {
|
|
288
|
+
let settled = false;
|
|
289
|
+
let timer = null;
|
|
290
|
+
const finish = (fn, value) => {
|
|
291
|
+
if (settled) return;
|
|
292
|
+
settled = true;
|
|
293
|
+
if (timer) clearTimeout(timer);
|
|
294
|
+
this.pending = null;
|
|
295
|
+
fn(value);
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
const spawnTunnel = (target) => {
|
|
299
|
+
const named = this.mode === 'named';
|
|
300
|
+
// named 有两种落地形态,对外都是「固定地址」:
|
|
301
|
+
// · token 形态(remotely-managed)→ TUNNEL_TOKEN 环境变量 + 远端 ingress
|
|
302
|
+
// · 本地管理型(cloudflared 自己的证书)→ --config 指向本地 ingress
|
|
303
|
+
// 两种都不用 --url:路由由 ingress 决定,本地再给 --url 会把它覆盖掉。
|
|
304
|
+
// 参数顺序有讲究:`run` 是 cloudflared 的子命令,`--config` / `--no-autoupdate`
|
|
305
|
+
// 都属于 `tunnel` 这一层,必须放在 `run` **之前**。
|
|
306
|
+
// 放到 `run` 之后会被当成 run 自己的选项,直接
|
|
307
|
+
// "flag provided but not defined: -no-autoupdate" 退出(真机才会踩到)。
|
|
308
|
+
// named 保持默认 QUIC:本机实测(深圳 → 洛杉矶边缘)QUIC 稳定 3.1–3.4s,
|
|
309
|
+
// 强制 http2 反而出现 12s 与直接超时。瓶颈是国际链路,不是协议。
|
|
310
|
+
// quick 仍用 http2——那是短命地址,优先保证在受限网络下能建起来。
|
|
311
|
+
const args = named
|
|
312
|
+
? (target?.configFile
|
|
313
|
+
? ['tunnel', '--config', target.configFile, '--no-autoupdate', 'run']
|
|
314
|
+
: ['tunnel', '--no-autoupdate', 'run'])
|
|
315
|
+
: ['tunnel', '--url', `http://127.0.0.1:${this.port}`, '--no-autoupdate', '--protocol', 'http2'];
|
|
316
|
+
const childEnv = target?.token ? { ...this.env, TUNNEL_TOKEN: target.token } : this.env;
|
|
317
|
+
|
|
318
|
+
let child;
|
|
319
|
+
try {
|
|
320
|
+
child = this.spawnImpl(exe, args, { stdio: ['ignore', 'pipe', 'pipe'], env: childEnv });
|
|
321
|
+
} catch (err) {
|
|
322
|
+
this.state = 'failed';
|
|
323
|
+
this.error = `无法启动 cloudflared:${err.message}`;
|
|
324
|
+
finish(reject, fail(4021, this.error));
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
this.child = child;
|
|
328
|
+
this.#writePid(child.pid);
|
|
329
|
+
|
|
330
|
+
timer = setTimeout(() => {
|
|
331
|
+
this.state = 'failed';
|
|
332
|
+
this.error = named
|
|
333
|
+
? `隧道启动超时(${Math.round(this.startTimeoutMs / 1000)}s 内未连上 Cloudflare)`
|
|
334
|
+
: '隧道启动超时(20s 内未拿到地址)';
|
|
335
|
+
try {
|
|
336
|
+
child.kill('SIGTERM');
|
|
337
|
+
} catch {
|
|
338
|
+
/* 忽略 */
|
|
339
|
+
}
|
|
340
|
+
finish(reject, fail(4500, this.error, { detail: this.logTail.slice(-3).join(' | ') }));
|
|
341
|
+
}, this.startTimeoutMs);
|
|
342
|
+
timer.unref?.();
|
|
343
|
+
|
|
344
|
+
const onChunk = (chunk) => {
|
|
345
|
+
const text = chunk.toString('utf8');
|
|
346
|
+
for (const line of text.split('\n')) {
|
|
347
|
+
this.#record(line);
|
|
348
|
+
if (settled) continue;
|
|
349
|
+
if (named) {
|
|
350
|
+
if (!NAMED_REGISTERED.test(line)) continue;
|
|
351
|
+
// 地址是既定的固定域名,不存在漂移;running 的判据是「连接真的注册成功」,
|
|
352
|
+
// 而不是「进程起来了」——后者会在出口被墙时给用户一个连不上的假绿灯。
|
|
353
|
+
const url = `https://${this.hostname}`;
|
|
354
|
+
this.url = url;
|
|
355
|
+
this.lastUrl = url;
|
|
356
|
+
this.state = 'running';
|
|
357
|
+
this.startedAt = new Date().toISOString();
|
|
358
|
+
this.desired = 'on';
|
|
359
|
+
this.log(`tunnel up url=${url} (named)`);
|
|
360
|
+
finish(resolve, this.status());
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
const match = URL_PATTERN.exec(line);
|
|
364
|
+
if (!match) continue;
|
|
365
|
+
const url = `https://${match[1]}.trycloudflare.com`;
|
|
366
|
+
const previous = this.lastUrl;
|
|
367
|
+
this.url = url;
|
|
368
|
+
this.lastUrl = url;
|
|
369
|
+
this.state = 'running';
|
|
370
|
+
this.startedAt = new Date().toISOString();
|
|
371
|
+
this.desired = 'on';
|
|
372
|
+
this.log(`tunnel up url=${url}`);
|
|
373
|
+
if (previous && previous !== url) {
|
|
374
|
+
this.prevUrl = previous;
|
|
375
|
+
this.log(`tunnel addr changed ${previous} → ${url}`);
|
|
376
|
+
// 地址漂移:必须广播,否则客户端一直连旧域名
|
|
377
|
+
this.onAddrChanged(url, previous);
|
|
378
|
+
}
|
|
379
|
+
finish(resolve, this.status());
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
child.stdout?.on('data', onChunk);
|
|
384
|
+
child.stderr?.on('data', onChunk);
|
|
385
|
+
|
|
386
|
+
child.on('error', (err) => {
|
|
387
|
+
this.state = 'failed';
|
|
388
|
+
this.error = `cloudflared 进程错误:${err.message}`;
|
|
389
|
+
this.child = null;
|
|
390
|
+
finish(reject, fail(4021, this.error));
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
child.on('exit', (code, signal) => {
|
|
394
|
+
this.exitCode = code;
|
|
395
|
+
const wasRunning = this.state === 'running';
|
|
396
|
+
if (this.state !== 'stopped') {
|
|
397
|
+
this.state = wasRunning ? 'failed' : this.state;
|
|
398
|
+
if (wasRunning) this.error = `cloudflared 退出(code=${code}, signal=${signal ?? 'none'})`;
|
|
399
|
+
}
|
|
400
|
+
this.child = null;
|
|
401
|
+
this.url = null;
|
|
402
|
+
this.#dropPid();
|
|
403
|
+
this.log(`tunnel exit code=${code} signal=${signal ?? 'none'}`);
|
|
404
|
+
finish(reject, fail(4500, this.error || 'cloudflared 提前退出'));
|
|
405
|
+
// 运行中意外退出(而非启动阶段失败)→ 按退避自动重拉。
|
|
406
|
+
// start() 已 resolved 后的退出 pending 为空、finish 是 no-op,同样走到这里;
|
|
407
|
+
// 显式 stop() 已先把 state 置 stopped 且 desired=off,#scheduleRestart 会拒绝。
|
|
408
|
+
if (wasRunning) this.#scheduleRestart();
|
|
409
|
+
});
|
|
410
|
+
};
|
|
411
|
+
|
|
412
|
+
if (this.mode !== 'named') {
|
|
413
|
+
spawnTunnel(null);
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
if (!this.resolveNamedTarget) {
|
|
417
|
+
this.state = 'failed';
|
|
418
|
+
this.error = '固定地址模式缺少 token 解析器';
|
|
419
|
+
finish(reject, fail(4021, this.error));
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
// token 解析可能要走一次开通服务(网络),放在 pending 里做,
|
|
423
|
+
// 既保证 start() 的单飞语义,也不会让调用方以为隧道已经起来了。
|
|
424
|
+
Promise.resolve()
|
|
425
|
+
.then(() => this.resolveNamedTarget())
|
|
426
|
+
.then((target) => {
|
|
427
|
+
if (settled) return;
|
|
428
|
+
if (!target?.hostname || (!target.token && !target.configFile)) {
|
|
429
|
+
this.state = 'failed';
|
|
430
|
+
this.error = '固定地址未开通(缺少凭据或域名)';
|
|
431
|
+
finish(reject, fail(4021, this.error));
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
this.hostname = target.hostname;
|
|
435
|
+
spawnTunnel(target);
|
|
436
|
+
})
|
|
437
|
+
.catch((err) => {
|
|
438
|
+
this.state = 'failed';
|
|
439
|
+
this.error = err?.message || '开通固定地址失败';
|
|
440
|
+
finish(reject, err?.code ? err : fail(4500, this.error));
|
|
441
|
+
});
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
return this.pending;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
async stop() {
|
|
448
|
+
// 显式停止即「用户不再要隧道」:取消计划中的重拉,否则 stop 后又悄悄起来。
|
|
449
|
+
this.desired = 'off';
|
|
450
|
+
if (this.restartTimer) {
|
|
451
|
+
clearTimeout(this.restartTimer);
|
|
452
|
+
this.restartTimer = null;
|
|
453
|
+
}
|
|
454
|
+
const child = this.child;
|
|
455
|
+
this.state = 'stopped';
|
|
456
|
+
this.url = null;
|
|
457
|
+
this.child = null;
|
|
458
|
+
this.pending = null;
|
|
459
|
+
if (!child) return { stopped: false, alreadyStopped: true };
|
|
460
|
+
await new Promise((resolve) => {
|
|
461
|
+
const done = () => resolve();
|
|
462
|
+
const timer = setTimeout(done, 3000);
|
|
463
|
+
timer.unref?.();
|
|
464
|
+
child.once('exit', () => {
|
|
465
|
+
clearTimeout(timer);
|
|
466
|
+
resolve();
|
|
467
|
+
});
|
|
468
|
+
try {
|
|
469
|
+
child.kill('SIGTERM');
|
|
470
|
+
} catch {
|
|
471
|
+
clearTimeout(timer);
|
|
472
|
+
resolve();
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
// 显式停止也清一次:exit 回调是异步的,用户点停止后 pidfile 不该还指着一个死进程
|
|
476
|
+
this.#dropPid();
|
|
477
|
+
this.log('tunnel stopped');
|
|
478
|
+
return { stopped: true };
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* 孤儿隧道清扫(2026-11-16 真机排查发现):DSH 桌面自身的 `dsh web` 每次重启
|
|
484
|
+
* 都会从同一个组件目录(~/.dsh/mobile-access/components/cloudflared/)新拉一个
|
|
485
|
+
* Quick Tunnel,旧的从不回收——指向已死端口的 cloudflared 进程空转堆积
|
|
486
|
+
* (实测一次清理出 13 个)。本函数在插件启动时按「目标端口已死 → 进程是孤儿」
|
|
487
|
+
* 清理该组件目录拉起的隧道:
|
|
488
|
+
* · 只认组件目录二进制(不碰用户自己 PATH 里的 cloudflared);
|
|
489
|
+
* · 只杀目标端口已无人监听的(活端口——包括 DSH 当前 GUI 伴生口和我们自己的
|
|
490
|
+
* 隧道——一律保留);
|
|
491
|
+
* · SIGTERM 优雅退出,1.5s 不退再 SIGKILL。
|
|
492
|
+
*/
|
|
493
|
+
export async function sweepOrphanTunnels({ componentDir, log = () => {} } = {}) {
|
|
494
|
+
if (!componentDir) return { killed: 0 };
|
|
495
|
+
// Windows 没有 pgrep,也不存在「按命令行找进程」的廉价等价物;
|
|
496
|
+
// 孤儿回收在那里靠 pidFile(#reapStale)兜底,这里直接返回,别每次启动都白 throw 一次。
|
|
497
|
+
if (process.platform === 'win32') return { killed: 0 };
|
|
498
|
+
const { execFile } = await import('node:child_process');
|
|
499
|
+
const net = await import('node:net');
|
|
500
|
+
|
|
501
|
+
const portAlive = (port) => new Promise((resolve) => {
|
|
502
|
+
const sock = net.connect({ host: '127.0.0.1', port });
|
|
503
|
+
sock.setTimeout(600);
|
|
504
|
+
sock.once('connect', () => { sock.destroy(); resolve(true); });
|
|
505
|
+
sock.once('error', () => resolve(false));
|
|
506
|
+
sock.once('timeout', () => { sock.destroy(); resolve(false); });
|
|
507
|
+
});
|
|
508
|
+
|
|
509
|
+
const listPids = () => new Promise((resolve) => {
|
|
510
|
+
execFile('/usr/bin/pgrep', ['-fl', 'cloudflared'], (err, stdout) => {
|
|
511
|
+
resolve(err ? [] : String(stdout).split('\n').filter(Boolean));
|
|
512
|
+
});
|
|
513
|
+
});
|
|
514
|
+
|
|
515
|
+
const lines = await listPids();
|
|
516
|
+
const orphans = [];
|
|
517
|
+
for (const line of lines) {
|
|
518
|
+
const pid = Number(line.split(' ')[0]);
|
|
519
|
+
if (!Number.isFinite(pid)) continue;
|
|
520
|
+
// 只认组件目录二进制 + Quick Tunnel 形态(--url http://127.0.0.1:<port>)
|
|
521
|
+
if (!line.includes(componentDir)) continue;
|
|
522
|
+
const m = line.match(/--url\s+https?:\/\/127\.0\.0\.1:(\d+)/);
|
|
523
|
+
if (!m) continue;
|
|
524
|
+
const port = Number(m[1]);
|
|
525
|
+
if (!(await portAlive(port))) orphans.push({ pid, port });
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
let killed = 0;
|
|
529
|
+
for (const { pid, port } of orphans) {
|
|
530
|
+
try {
|
|
531
|
+
process.kill(pid, 'SIGTERM');
|
|
532
|
+
killed += 1;
|
|
533
|
+
log(`tunnel sweep: SIGTERM orphan pid=${pid} (target 127.0.0.1:${port} 已死)`);
|
|
534
|
+
} catch { /* 进程已退出/权限不足,忽略 */ }
|
|
535
|
+
}
|
|
536
|
+
// 宽限后强杀残留
|
|
537
|
+
if (killed > 0) {
|
|
538
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
539
|
+
for (const { pid } of orphans) {
|
|
540
|
+
try { process.kill(pid, 0); process.kill(pid, 'SIGKILL'); } catch { /* 已退 */ }
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
return { killed };
|
|
544
|
+
}
|