dsh-mobile-plugin 0.5.93 → 0.5.95
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/config/agent-presets/standard/skills/dsh-mobile-kb/SKILL.md +10 -3
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/cloudflare.md +58 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/frp.md +50 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/ipv4.md +2 -2
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/load-error-after-action.md +27 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/network-guide.md +55 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/network.md +5 -1
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/plugin-not-loaded.md +22 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/relay-server.md +48 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/relay.md +9 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/selfhost-common.md +1 -1
- package/lib/client.js +53 -162
- package/lib/cloudflared/provision.cjs +392 -0
- package/lib/cloudflared/runner.cjs +305 -0
- package/lib/cloudflared/wiring.cjs +82 -0
- package/lib/frpc/runner.cjs +1 -1
- package/lib/impl.js +11 -1
- package/lib/mobile/history-derive.js +16 -0
- package/lib/mobile/pairing.js +4 -0
- package/lib/panel/index.html +47 -27
- package/lib/relay/config-store.js +9 -0
- package/lib/relay/control.js +8 -0
- package/lib/relay/core.js +6 -0
- package/lib/relay/lan-network.cjs +23 -0
- package/lib/relay/pairing-payload.cjs +2 -1
- package/lib/remote/routes.cjs +7 -5
- package/lib/remote/tunnel-helper.cjs +3 -3
- package/lib/routes/control-plane.js +116 -155
- package/lib/routes/mobile-api.js +10 -2
- package/lib/shared/route-channels.cjs +1 -0
- package/lib/shared/route-order.cjs +8 -1
- package/lib/tailcat/host-process.cjs +9 -3
- package/package.json +14 -13
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
// CLOUDFLARED 下载逐源分配预算,响应体同样受时限约束,坏校验不阻断后续镜像。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
// 2026-11-22:cloudflared 获取层,照 frpc 那套「自带 → PATH → 缓存 → 下载」写,钉版本并填全四平台校验和。
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 在用户电脑上「弄到一份能用的 cloudflared」:先看用户自己有没有,再看有没有缓存,都没有就按平台
|
|
8
|
+
* 从官方 release 拉一份、校验、解包、落到缓存目录。
|
|
9
|
+
*
|
|
10
|
+
* 为什么单独一层:cloudflared 是第三方二进制,我们既不想把它打进 npm 包(每个平台一个包,维护不动),
|
|
11
|
+
* 也不能指望用户自己会装。这里只做「拿到可执行文件」这一件事——真正怎么起隧道、连哪个地址、
|
|
12
|
+
* 传什么配置,留给调用方(这一步之后再说)。
|
|
13
|
+
*
|
|
14
|
+
* 三条来源,按优先级:
|
|
15
|
+
* ① 用户指定的路径(环境变量 `DSHM_CLOUDFLARED_BIN`)或系统 PATH 里已有的 cloudflared —— 直接用,不下载;
|
|
16
|
+
* ② 以前下载过的缓存(按「版本 + 平台」存)—— 直接用;
|
|
17
|
+
* ③ 都没有 —— 按当前系统与架构从官方 release 下载对应产物,sha256 校验通过后再落盘。
|
|
18
|
+
* 国内常连不上 GitHub,下载这一步会依次回退几条公开加速镜像;镜像只换传输路径,
|
|
19
|
+
* 仍是同一份资产、同一份钉死的 sha256,校验不符当场拒掉,不因为「换源」放松验证。
|
|
20
|
+
*
|
|
21
|
+
* 失败抛带 code 的错误(`download-failed` / `checksum` / `unsupported-platform`),由调用方决定
|
|
22
|
+
* 是当「这台机器没有 cloudflared」继续降级,还是提示用户。全源都不通时把每条源的底层原因
|
|
23
|
+
* (从 undici 的 `cause` 里挖出来的真话,而不是一句 `fetch failed`)一并列出来。
|
|
24
|
+
*
|
|
25
|
+
* 纯 Node 实现,不依赖系统 tar:下载的是官方 .tgz(macOS)或裸二进制(Linux/Windows),
|
|
26
|
+
* .tgz 解包在本文件里手写,只挑出里面那个 cloudflared 可执行文件,其余不落盘。
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
const crypto = require('node:crypto');
|
|
30
|
+
const fs = require('node:fs');
|
|
31
|
+
const path = require('node:path');
|
|
32
|
+
|
|
33
|
+
const { dshHome } = require('../shared/paths.js');
|
|
34
|
+
|
|
35
|
+
/** 钉死的 cloudflared 版本。换版本时改这一个常量,并把下面的文件名与 sha256 一起更新。 */
|
|
36
|
+
const CLOUDFLARED_VERSION = '2026.11.0';
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 官方 release 的下载根;国内常连不上,下面挂着几条公开加速镜像,按顺序回退。
|
|
40
|
+
* 只换「同一份字节的传输路径」,资产与 sha256 不变——镜像给错内容照样在校验那步被拒。
|
|
41
|
+
* 镜像是第三方服务,会失效也会变,所以做成一张可替换的表,且永远最后才动失败文案。
|
|
42
|
+
*/
|
|
43
|
+
const DEFAULT_BASE_URL = `https://github.com/cloudflare/cloudflared/releases/download/${CLOUDFLARED_VERSION}`;
|
|
44
|
+
|
|
45
|
+
const MIRROR_BASE_URLS = [
|
|
46
|
+
`https://gh-proxy.com/https://github.com/cloudflare/cloudflared/releases/download/${CLOUDFLARED_VERSION}`,
|
|
47
|
+
`https://ghfast.top/https://github.com/cloudflare/cloudflared/releases/download/${CLOUDFLARED_VERSION}`,
|
|
48
|
+
`https://ghproxy.net/https://github.com/cloudflare/cloudflared/releases/download/${CLOUDFLARED_VERSION}`,
|
|
49
|
+
];
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 这一轮下载要按顺序试的根地址。
|
|
53
|
+
*
|
|
54
|
+
* 优先级:`baseUrl`(部署方/测试显式钉死,只试这一条)> 官方 + 镜像。任何一环给出的
|
|
55
|
+
* 字节都要过同一份 sha256,镜像进不了「少校验」的捷径。
|
|
56
|
+
*/
|
|
57
|
+
function baseUrlsOf(options = {}) {
|
|
58
|
+
if (typeof options.baseUrl === 'string' && options.baseUrl) return [options.baseUrl];
|
|
59
|
+
return [DEFAULT_BASE_URL, ...MIRROR_BASE_URLS];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* undici 把真正的 syscall 错塞在 `cause` 里,表层只有一句没信息的 `fetch failed`。
|
|
64
|
+
* 沿 cause 链找第一句比 "fetch failed" 更具体的话;找不到就退回表层那句,不凭空编。
|
|
65
|
+
*/
|
|
66
|
+
function fetchErrorMessage(error) {
|
|
67
|
+
let cursor = error;
|
|
68
|
+
let generic = '';
|
|
69
|
+
for (let depth = 0; depth < 4 && cursor; depth += 1) {
|
|
70
|
+
const message = typeof cursor.message === 'string' ? cursor.message.trim() : '';
|
|
71
|
+
if (message && message.toLowerCase() !== 'fetch failed') return message;
|
|
72
|
+
if (message) generic = message;
|
|
73
|
+
cursor = cursor.cause;
|
|
74
|
+
}
|
|
75
|
+
return generic || (error && error.message ? error.message : String(error));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 支持的平台 → 资产描述。
|
|
80
|
+
*
|
|
81
|
+
* `file` 是官方 release 里那个产物的名字,`archive` 决定是不是要解包(macOS 是 .tgz,
|
|
82
|
+
* Linux/Windows 是裸二进制),`bin` 是落盘后的可执行名,`sha256` 是官方发布的校验值
|
|
83
|
+
* (写死在这里,防的是「下到的包被换掉」,而不是防文件坏)。只列我们真正支持的平台;
|
|
84
|
+
* 不在表里的(FreeBSD、32 位等)一律当「不支持」,不猜。
|
|
85
|
+
*/
|
|
86
|
+
const ASSETS = {
|
|
87
|
+
'darwin-x64': { file: 'cloudflared-darwin-amd64.tgz', archive: 'tar.gz', bin: 'cloudflared', sha256: '8a59d51120cebbe902f0a8d6e1b7a7fd4f9a5bb4dcb3e0f05872483e75e7db6b' },
|
|
88
|
+
'darwin-arm64': { file: 'cloudflared-darwin-arm64.tgz', archive: 'tar.gz', bin: 'cloudflared', sha256: '8c2f90277ef06a6080bb40b964d33f09f1188102f8798f2e344174b6cf41accf' },
|
|
89
|
+
'linux-x64': { file: 'cloudflared-linux-amd64', archive: 'binary', bin: 'cloudflared', sha256: '51f7c68b57ed7269164075d7e789efce5b59355982f06392deeb037d982a51fd' },
|
|
90
|
+
'linux-arm64': { file: 'cloudflared-linux-arm64', archive: 'binary', bin: 'cloudflared', sha256: 'abe54a006acf9faf2d19ee9d953cb0d0804e92f59c5382a162e57b84d086f56f' },
|
|
91
|
+
'win32-x64': { file: 'cloudflared-windows-amd64.exe', archive: 'binary', bin: 'cloudflared.exe', sha256: 'd5c1d82031da6253dcdcff64c944cd0fe063016edeb2e4fd088075fc9bd52d0a' },
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/** 下载超时:cloudflared 的产物二三十 MB,给足两分钟;卡住也不至于让调用方一直等。 */
|
|
95
|
+
const DOWNLOAD_TIMEOUT_MS = 120_000;
|
|
96
|
+
|
|
97
|
+
/** 同一平台同一时刻只拉一次:多个入口同时触发时共用同一个 Promise。 */
|
|
98
|
+
const inflight = new Map();
|
|
99
|
+
|
|
100
|
+
/** 这台机器对应哪个平台(与 frpc 的 `platformId` 同一套命名)。不支持就返回 undefined。 */
|
|
101
|
+
function platformId(platform = process.platform, arch = process.arch) {
|
|
102
|
+
const osName = platform === 'win32' ? 'win32' : platform;
|
|
103
|
+
// Windows on ARM 没有原生 cloudflared(官方只发 386 / amd64),但 Windows 能跑 x64 程序
|
|
104
|
+
// (Windows 11 ARM 带 x64 模拟),所以 arm64 归到 x64 那份资产,而不是判成不支持。
|
|
105
|
+
const cpu = arch === 'x64' ? 'x64' : arch === 'arm64' ? (osName === 'win32' ? 'x64' : 'arm64') : arch;
|
|
106
|
+
const id = `${osName}-${cpu}`;
|
|
107
|
+
return Object.prototype.hasOwnProperty.call(ASSETS, id) ? id : undefined;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 缓存根:`<DSH 数据目录>/cloudflared`(测试可注入)。 */
|
|
111
|
+
function cacheRoot(options = {}) {
|
|
112
|
+
return options.cacheRoot || path.join(dshHome(), 'cloudflared');
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 某一版本 + 平台的缓存目录。 */
|
|
116
|
+
function cacheDirOf(options = {}) {
|
|
117
|
+
const version = options.version || CLOUDFLARED_VERSION;
|
|
118
|
+
const platform = options.platformId || platformId(options.platform, options.arch);
|
|
119
|
+
if (!platform) return null;
|
|
120
|
+
return path.join(cacheRoot(options), version, platform);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function sha256Hex(buffer) {
|
|
124
|
+
return crypto.createHash('sha256').update(buffer).digest('hex');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function isFile(target) {
|
|
128
|
+
try { return fs.statSync(target).isFile(); } catch { return false; }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 在 PATH 里找一个可执行文件。
|
|
133
|
+
*
|
|
134
|
+
* `PATH` 分隔符跟随平台(Windows 是 `;`,其余是 `:`);只判「在、且是普通文件」,不判可执行位
|
|
135
|
+
* ——Windows 上没有可执行位那一说,而 POSIX 上用户既然把它放进 PATH,基本就是能跑的。
|
|
136
|
+
*/
|
|
137
|
+
function findOnPath(binName, options = {}) {
|
|
138
|
+
const env = options.env || process.env;
|
|
139
|
+
const platform = options.platform;
|
|
140
|
+
const raw = env.PATH || env.Path || '';
|
|
141
|
+
const sep = platform === 'win32' || path.delimiter === ';' ? ';' : path.delimiter;
|
|
142
|
+
for (const dir of raw.split(sep)) {
|
|
143
|
+
if (!dir) continue;
|
|
144
|
+
const candidate = path.join(dir, binName);
|
|
145
|
+
if (isFile(candidate)) return candidate;
|
|
146
|
+
}
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 用户已经有的 cloudflared(优先级最高)。
|
|
152
|
+
*
|
|
153
|
+
* ① 环境变量 `DSHM_CLOUDFLARED_BIN` 指的那一份;② 系统 PATH 里的 cloudflared。
|
|
154
|
+
* 都没有返回 null。这里不关心平台资产表——用户给了就直接用。
|
|
155
|
+
*/
|
|
156
|
+
function resolveInstalled(options = {}) {
|
|
157
|
+
const env = options.env || process.env;
|
|
158
|
+
const platform = options.platform || process.platform;
|
|
159
|
+
const override = env.DSHM_CLOUDFLARED_BIN;
|
|
160
|
+
if (typeof override === 'string' && override && isFile(override)) {
|
|
161
|
+
return { path: override, source: 'env' };
|
|
162
|
+
}
|
|
163
|
+
const binName = options.bin || (platform === 'win32' ? 'cloudflared.exe' : 'cloudflared');
|
|
164
|
+
const found = findOnPath(binName, { env, platform });
|
|
165
|
+
if (found) return { path: found, source: 'path' };
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** 从 tar.gz 里读出名为 `basename` 的那个文件(只挑这一个,别的不要)。 */
|
|
170
|
+
function extractTarGzEntry(input, basename) {
|
|
171
|
+
const zlib = require('node:zlib');
|
|
172
|
+
const tar = input.length >= 2 && input[0] === 0x1f && input[1] === 0x8b ? zlib.gunzipSync(input) : input;
|
|
173
|
+
const str = (buf, start, length) => {
|
|
174
|
+
const slice = buf.subarray(start, start + length);
|
|
175
|
+
const zero = slice.indexOf(0);
|
|
176
|
+
return (zero === -1 ? slice : slice.subarray(0, zero)).toString('utf8');
|
|
177
|
+
};
|
|
178
|
+
const BLOCK = 512;
|
|
179
|
+
let offset = 0;
|
|
180
|
+
while (offset + BLOCK <= tar.length) {
|
|
181
|
+
const header = tar.subarray(offset, offset + BLOCK);
|
|
182
|
+
if (header.every((byte) => byte === 0)) break;
|
|
183
|
+
const name = str(header, 0, 100);
|
|
184
|
+
const prefix = str(header, 345, 155);
|
|
185
|
+
const sizeText = str(header, 124, 12).trim();
|
|
186
|
+
const size = sizeText ? Number.parseInt(sizeText, 8) : 0;
|
|
187
|
+
const type = String.fromCharCode(header[156]) || '0';
|
|
188
|
+
const start = offset + BLOCK;
|
|
189
|
+
const end = start + (Number.isFinite(size) ? size : 0);
|
|
190
|
+
if (end > tar.length) throw new Error(`压缩包被截断:条目 ${name || '(无名)'} 声明的长度超出文件`);
|
|
191
|
+
const full = prefix ? `${prefix}/${name}` : name;
|
|
192
|
+
if ((type === '0' || type === '\u0000') && path.basename(full) === basename) {
|
|
193
|
+
return Buffer.from(tar.subarray(start, end));
|
|
194
|
+
}
|
|
195
|
+
offset = start + Math.ceil((Number.isFinite(size) ? size : 0) / BLOCK) * BLOCK;
|
|
196
|
+
}
|
|
197
|
+
throw new Error(`压缩包里没有找到 ${basename}`);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** 按 `archive` 类型从下载到的字节里挑出可执行文件;裸二进制直接用整份响应体。 */
|
|
201
|
+
function extractEntry(buffer, asset) {
|
|
202
|
+
return asset.archive === 'tar.gz' ? extractTarGzEntry(buffer, asset.bin) : buffer;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** macOS 上尽力摘掉 quarantine 标记;摘不掉(没有 xattr / 本来没有该属性)也不阻断。 */
|
|
206
|
+
function clearQuarantine(target, platform) {
|
|
207
|
+
if (platform !== 'darwin') return;
|
|
208
|
+
try {
|
|
209
|
+
require('node:child_process').execFileSync('xattr', ['-d', 'com.apple.quarantine', target], { stdio: 'ignore' });
|
|
210
|
+
} catch { /* 没有该属性或系统不带 xattr:留着也不影响执行 */ }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* 下载一份资产、校验、解包,把可执行文件写到 `dir/bin`。
|
|
215
|
+
*
|
|
216
|
+
* 只写这一个文件;先写进调用方给的暂存目录,最后由 `ensureCloudflared` 原子换上,所以半截文件
|
|
217
|
+
* 不会出现在正式缓存目录里。可执行位与去 quarantine 都在这里一并处理。
|
|
218
|
+
*/
|
|
219
|
+
async function downloadTo({ url, asset, dir, platform, fetchImpl, timeoutMs = DOWNLOAD_TIMEOUT_MS }) {
|
|
220
|
+
const doFetch = fetchImpl || globalThis.fetch;
|
|
221
|
+
if (typeof doFetch !== 'function') throw codedError('no-fetch', '当前环境没有可用的 fetch');
|
|
222
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
223
|
+
const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
|
|
224
|
+
let buffer;
|
|
225
|
+
try {
|
|
226
|
+
const response = await doFetch(url, controller ? { signal: controller.signal } : {});
|
|
227
|
+
if (!response || response.ok !== true) {
|
|
228
|
+
throw new Error(`HTTP ${response ? response.status : '无响应'}`);
|
|
229
|
+
}
|
|
230
|
+
buffer = Buffer.from(await response.arrayBuffer());
|
|
231
|
+
} catch (error) {
|
|
232
|
+
throw codedError('download-failed', `下载 cloudflared 失败:${fetchErrorMessage(error)}`);
|
|
233
|
+
} finally {
|
|
234
|
+
if (timer) clearTimeout(timer);
|
|
235
|
+
}
|
|
236
|
+
const got = sha256Hex(buffer);
|
|
237
|
+
if (asset.sha256 && got !== asset.sha256) {
|
|
238
|
+
throw codedError('checksum', `cloudflared 校验失败:下载内容的 sha256 与预期不一致(预期 ${asset.sha256},实际 ${got})`);
|
|
239
|
+
}
|
|
240
|
+
let binary;
|
|
241
|
+
try {
|
|
242
|
+
binary = extractEntry(buffer, asset);
|
|
243
|
+
} catch (error) {
|
|
244
|
+
throw codedError('extract-failed', `解包 cloudflared 失败:${error && error.message ? error.message : error}`);
|
|
245
|
+
}
|
|
246
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
247
|
+
const dest = path.join(dir, asset.bin);
|
|
248
|
+
fs.writeFileSync(dest, binary);
|
|
249
|
+
// 可执行位只在 POSIX 有意义;Windows 上 chmod 只改只读标记,别去碰。
|
|
250
|
+
if (platform !== 'win32') {
|
|
251
|
+
try { fs.chmodSync(dest, 0o755); } catch { /* 权限位没打上也不至于跑不了 */ }
|
|
252
|
+
}
|
|
253
|
+
clearQuarantine(dest, platform);
|
|
254
|
+
return dest;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function codedError(code, message) {
|
|
258
|
+
const error = new Error(message);
|
|
259
|
+
error.code = code;
|
|
260
|
+
return error;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** 把目录换成目标目录;同盘 rename,跨盘退回复制再删(与 OTA 那条同一套兜底)。 */
|
|
264
|
+
function moveDir(src, dst) {
|
|
265
|
+
try {
|
|
266
|
+
fs.renameSync(src, dst);
|
|
267
|
+
return;
|
|
268
|
+
} catch (error) {
|
|
269
|
+
const code = error && error.code;
|
|
270
|
+
if (!['EXDEV', 'EPERM', 'EACCES', 'ENOTEMPTY', 'EEXIST'].includes(code)) throw error;
|
|
271
|
+
}
|
|
272
|
+
fs.rmSync(dst, { recursive: true, force: true });
|
|
273
|
+
fs.cpSync(src, dst, { recursive: true });
|
|
274
|
+
fs.rmSync(src, { recursive: true, force: true });
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** 成功后清掉**其它版本目录**的缓存,失败不影响主流程。只清版本号样式的目录,别动同目录下的配置/标记。 */
|
|
278
|
+
function pruneOldVersions(root, currentVersion) {
|
|
279
|
+
let names;
|
|
280
|
+
try { names = fs.readdirSync(root); } catch { return; }
|
|
281
|
+
for (const name of names) {
|
|
282
|
+
if (name === currentVersion || !/^\d+\.\d+\.\d+/.test(name)) continue;
|
|
283
|
+
try { fs.rmSync(path.join(root, name), { recursive: true, force: true }); } catch { /* 占着就下次再清 */ }
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** 同一平台的并发触发合并成一次下载。 */
|
|
288
|
+
function withLock(key, task) {
|
|
289
|
+
const existing = inflight.get(key);
|
|
290
|
+
if (existing) return existing;
|
|
291
|
+
const promise = Promise.resolve().then(task).finally(() => inflight.delete(key));
|
|
292
|
+
inflight.set(key, promise);
|
|
293
|
+
return promise;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* 拿到一份可用的 cloudflared。
|
|
298
|
+
*
|
|
299
|
+
* @returns {Promise<{path:string, version:string|null, source:'env'|'path'|'cache'|'download'}>}
|
|
300
|
+
* 失败时抛带 `code` 的错误:`unsupported-platform` / `checksum` / `download-failed`。
|
|
301
|
+
*
|
|
302
|
+
* 选项中可注入(测试用):platform/platformId、arch、env、cacheRoot、version、asset、baseUrl、fetchImpl、
|
|
303
|
+
* offline(true = 不允许联网,只认已有/缓存)。
|
|
304
|
+
*/
|
|
305
|
+
async function ensureCloudflared(options = {}) {
|
|
306
|
+
const platform = options.platformId || platformId(options.platform, options.arch);
|
|
307
|
+
const version = options.version || CLOUDFLARED_VERSION;
|
|
308
|
+
|
|
309
|
+
// ① 用户自己有的(显式路径 / PATH):平台认不出也先认这一份。
|
|
310
|
+
const installed = resolveInstalled(options);
|
|
311
|
+
if (installed) {
|
|
312
|
+
return { path: installed.path, version: null, source: installed.source };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// ② 平台/资产:认不出就不猜。
|
|
316
|
+
const asset = options.asset || (platform ? ASSETS[platform] : null);
|
|
317
|
+
if (!platform || !asset) {
|
|
318
|
+
throw codedError('unsupported-platform', `这台机器(${options.platform || process.platform}/${options.arch || process.arch})不在支持的平台上,装不了 cloudflared`);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const dir = options.cacheRoot
|
|
322
|
+
? path.join(options.cacheRoot, version, platform)
|
|
323
|
+
: cacheDirOf({ ...options, platformId: platform, version });
|
|
324
|
+
const binaryPath = path.join(dir, asset.bin);
|
|
325
|
+
// ③ 缓存命中。
|
|
326
|
+
if (isFile(binaryPath)) {
|
|
327
|
+
return { path: binaryPath, version, source: 'cache' };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// ④ 要联网:不允许就直接回,别让调用方等超时。
|
|
331
|
+
if (options.offline) {
|
|
332
|
+
throw codedError('download-failed', '本机没有找到 cloudflared,且当前不允许联网下载');
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
return withLock(platform, async () => {
|
|
336
|
+
// 排队期间可能已经被别的调用拉好了,再确认一次。
|
|
337
|
+
if (isFile(binaryPath)) {
|
|
338
|
+
return { path: binaryPath, version, source: 'cache' };
|
|
339
|
+
}
|
|
340
|
+
const root = options.cacheRoot || cacheRoot(options);
|
|
341
|
+
const staging = path.join(root, `.staging-${process.pid}-${crypto.randomBytes(6).toString('hex')}`);
|
|
342
|
+
const bases = baseUrlsOf(options);
|
|
343
|
+
const attempts = [];
|
|
344
|
+
// 在总预算内给每个剩余源留一份,首源挂起也不能独占整轮。
|
|
345
|
+
const budgetMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : DOWNLOAD_TIMEOUT_MS;
|
|
346
|
+
const deadline = performance.now() + budgetMs;
|
|
347
|
+
let lastError = null;
|
|
348
|
+
try {
|
|
349
|
+
for (const [index, base] of bases.entries()) {
|
|
350
|
+
const remaining = deadline - performance.now();
|
|
351
|
+
if (remaining <= 0) break;
|
|
352
|
+
const timeoutMs = Math.max(1, remaining / (bases.length - index));
|
|
353
|
+
const url = `${String(base).replace(/\/+$/, '')}/${asset.file}`;
|
|
354
|
+
try {
|
|
355
|
+
await downloadTo({ url, asset, dir: staging, platform, fetchImpl: options.fetchImpl, timeoutMs });
|
|
356
|
+
// 先剔掉可能残留的旧目录,再把暂存目录原子换上。
|
|
357
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
358
|
+
fs.mkdirSync(path.dirname(dir), { recursive: true });
|
|
359
|
+
moveDir(staging, dir);
|
|
360
|
+
pruneOldVersions(root, version);
|
|
361
|
+
return { path: binaryPath, version, source: 'download' };
|
|
362
|
+
} catch (error) {
|
|
363
|
+
lastError = error;
|
|
364
|
+
const reason = error && error.message ? error.message : String(error);
|
|
365
|
+
attempts.push(reason.replace(/^下载 cloudflared 失败:/, ''));
|
|
366
|
+
// 本源响应可能是门户页或镜像错误页;后源仍必须通过同一份钉死校验。
|
|
367
|
+
fs.rmSync(staging, { recursive: true, force: true });
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
if (bases.length === 1 && lastError) throw codedError(lastError.code || 'download-failed', lastError.message || String(lastError));
|
|
371
|
+
throw codedError('download-failed', `下载 cloudflared 失败:${attempts.length} 个源均失败(${attempts.join(';')})`);
|
|
372
|
+
} finally {
|
|
373
|
+
fs.rmSync(staging, { recursive: true, force: true });
|
|
374
|
+
}
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
module.exports = {
|
|
379
|
+
CLOUDFLARED_VERSION,
|
|
380
|
+
ASSETS,
|
|
381
|
+
DEFAULT_BASE_URL,
|
|
382
|
+
MIRROR_BASE_URLS,
|
|
383
|
+
baseUrlsOf,
|
|
384
|
+
fetchErrorMessage,
|
|
385
|
+
platformId,
|
|
386
|
+
cacheRoot,
|
|
387
|
+
cacheDirOf,
|
|
388
|
+
resolveInstalled,
|
|
389
|
+
findOnPath,
|
|
390
|
+
extractTarGzEntry,
|
|
391
|
+
ensureCloudflared,
|
|
392
|
+
};
|