dsh-mobile-plugin 0.5.63 → 0.5.65
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/frpc/provision.cjs +384 -0
- package/lib/frpc/runner.cjs +229 -0
- package/lib/impl.js +36 -0
- package/lib/mobile/pairing.js +7 -0
- package/lib/mobile/relay-control.js +11 -0
- package/lib/mobile/session-send.js +4 -2
- package/lib/panel/index.html +9 -9
- package/lib/relay/control.js +260 -0
- package/lib/relay/core.js +13 -1
- package/lib/relay/lan-network.cjs +26 -0
- package/lib/relay/pairing-payload.cjs +8 -0
- package/lib/relay/status.js +3 -0
- package/lib/routes/control-plane.js +54 -1
- package/lib/routes/mobile-api.js +11 -2
- package/lib/shell/updater.js +13 -8
- package/lib/update-install.cjs +43 -12
- package/package.json +1 -1
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 在用户电脑上「弄到一份能用的 frpc」:先看用户自己有没有,再看有没有缓存,都没有就按平台
|
|
5
|
+
* 从官方 release 拉一份、校验、解包、落到缓存目录。
|
|
6
|
+
*
|
|
7
|
+
* 为什么单独一层:frpc 是第三方二进制,我们既不想把它打进 npm 包(每个平台一个包,维护不动),
|
|
8
|
+
* 也不能指望用户自己会装。所以这里只做「拿到可执行文件」这一件事——真正怎么起、连哪台服务器、
|
|
9
|
+
* 传什么配置,留给调用方(这一步之后再说)。
|
|
10
|
+
*
|
|
11
|
+
* 三条来源,按优先级:
|
|
12
|
+
* ① 用户指定的路径(环境变量 `DSHM_FRPC_BIN`)或系统 PATH 里已有的 frpc —— 直接用,不下载;
|
|
13
|
+
* ② 以前下载过的缓存(按「版本 + 平台」存)—— 直接用;
|
|
14
|
+
* ③ 都没有 —— 按当前系统与架构从官方 release 下载对应包,sha256 校验通过后再解包落盘。
|
|
15
|
+
*
|
|
16
|
+
* 失败一律走返回值(`{ ok: false, reason, message }`),从不抛给调用方:这条只是可选能力,
|
|
17
|
+
* 弄不到就等于「这台机器没有 frpc」,插件其它功能一点不受影响。
|
|
18
|
+
*
|
|
19
|
+
* 纯 Node 实现,不依赖系统 tar/unzip:下载的是官方 .tar.gz(Linux/macOS)或 .zip(Windows),
|
|
20
|
+
* 两种解包都在本文件里手写,只挑出里面那个 frpc 可执行文件,其余(frps、LICENSE…)不落盘。
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const crypto = require('node:crypto');
|
|
24
|
+
const fs = require('node:fs');
|
|
25
|
+
const path = require('node:path');
|
|
26
|
+
|
|
27
|
+
const { dshHome } = require('../shared/paths.js');
|
|
28
|
+
|
|
29
|
+
/** 钉死的 frp 版本。换版本时改这一个常量,并把下面的文件名与 sha256 一起更新。 */
|
|
30
|
+
const FRP_VERSION = '0.72.0';
|
|
31
|
+
|
|
32
|
+
/** 官方 release 的下载根;可被环境变量覆盖(以后换成自家分发服务器只改这里)。 */
|
|
33
|
+
const DEFAULT_BASE_URL = `https://github.com/fatedier/frp/releases/download/v${FRP_VERSION}`;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 支持的平台 → 资产描述。
|
|
37
|
+
*
|
|
38
|
+
* `file` 是官方 release 里那个压缩包的名字,`archive` 决定用哪种解包,`bin` 是包内可执行名,
|
|
39
|
+
* `sha256` 是官方发布的校验值(写死在这里,防的是「下到的包被换掉」,而不是防文件坏)。
|
|
40
|
+
* 只列我们真正支持的平台;不在表里的(FreeBSD、32 位等)一律当「不支持」,不猜。
|
|
41
|
+
*/
|
|
42
|
+
const ASSETS = {
|
|
43
|
+
'darwin-x64': { file: `frp_${FRP_VERSION}_darwin_amd64.tar.gz`, archive: 'tar.gz', bin: 'frpc', sha256: '60439dc6bf794c4182a1a4cac147d642f839d55201607208979eb23aecd09be9' },
|
|
44
|
+
'darwin-arm64': { file: `frp_${FRP_VERSION}_darwin_arm64.tar.gz`, archive: 'tar.gz', bin: 'frpc', sha256: '6e8576c5b6b9914a86850f6ff4fb81c5a09e706f91f70f64d5f398558bdc9db8' },
|
|
45
|
+
'linux-x64': { file: `frp_${FRP_VERSION}_linux_amd64.tar.gz`, archive: 'tar.gz', bin: 'frpc', sha256: 'daf719b32ca2778770bb92955e231a07414d754378b9af328aa2642862479804' },
|
|
46
|
+
'linux-arm64': { file: `frp_${FRP_VERSION}_linux_arm64.tar.gz`, archive: 'tar.gz', bin: 'frpc', sha256: '02180b857480302fd934e9ddbd50fe2f73229f99062f88756abc6de9df5e95cf' },
|
|
47
|
+
'win32-x64': { file: `frp_${FRP_VERSION}_windows_amd64.zip`, archive: 'zip', bin: 'frpc.exe', sha256: '5197c1b69564089cdc229fc1260a0e25db1e722b1b7db45fe1542c3c43edf9ae' },
|
|
48
|
+
'win32-arm64': { file: `frp_${FRP_VERSION}_windows_arm64.zip`, archive: 'zip', bin: 'frpc.exe', sha256: 'e4b83b66c4045971dd9a47cdef16dd02af471aaa6667dd303e63b1a669162927' },
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/** 下载超时:frp 的包十来 MB,给足两分钟;卡住也不至于让调用方一直等。 */
|
|
52
|
+
const DOWNLOAD_TIMEOUT_MS = 120_000;
|
|
53
|
+
|
|
54
|
+
/** 同一平台同一时刻只拉一次:多个入口同时触发时共用同一个 Promise。 */
|
|
55
|
+
const inflight = new Map();
|
|
56
|
+
|
|
57
|
+
/** 这台机器对应哪个平台(与 tailcat 的 `platformId` 同一套命名)。不支持就返回 undefined。 */
|
|
58
|
+
function platformId(platform = process.platform, arch = process.arch) {
|
|
59
|
+
const os = platform === 'win32' ? 'win32' : platform;
|
|
60
|
+
const cpu = arch === 'x64' ? 'x64' : arch === 'arm64' ? 'arm64' : arch;
|
|
61
|
+
const id = `${os}-${cpu}`;
|
|
62
|
+
return Object.prototype.hasOwnProperty.call(ASSETS, id) ? id : undefined;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 缓存根:`<DSH 数据目录>/frpc`(测试可注入)。 */
|
|
66
|
+
function cacheRoot(options = {}) {
|
|
67
|
+
return options.cacheRoot || path.join(dshHome(), 'frpc');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 某一版本 + 平台的缓存目录。 */
|
|
71
|
+
function cacheDirOf(options = {}) {
|
|
72
|
+
const version = options.version || FRP_VERSION;
|
|
73
|
+
const platform = options.platformId || platformId(options.platform, options.arch);
|
|
74
|
+
if (!platform) return null;
|
|
75
|
+
return path.join(cacheRoot(options), version, platform);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function sha256Hex(buffer) {
|
|
79
|
+
return crypto.createHash('sha256').update(buffer).digest('hex');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function fail(reason, message) {
|
|
83
|
+
return { ok: false, reason, message };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function isFile(target) {
|
|
87
|
+
try { return fs.statSync(target).isFile(); } catch { return false; }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 在 PATH 里找一个可执行文件。
|
|
92
|
+
*
|
|
93
|
+
* `PATH` 分隔符跟随平台(Windows 是 `;`,其余是 `:`);只判「在、且是普通文件」,不判可执行位
|
|
94
|
+
* ——Windows 上没有可执行位那一说,而 POSIX 上用户既然把它放进 PATH,基本就是能跑的。
|
|
95
|
+
*/
|
|
96
|
+
function findOnPath(binName, options = {}) {
|
|
97
|
+
const env = options.env || process.env;
|
|
98
|
+
const platform = options.platform;
|
|
99
|
+
const raw = env.PATH || env.Path || '';
|
|
100
|
+
const sep = platform === 'win32' || path.delimiter === ';' ? ';' : path.delimiter;
|
|
101
|
+
for (const dir of raw.split(sep)) {
|
|
102
|
+
if (!dir) continue;
|
|
103
|
+
const candidate = path.join(dir, binName);
|
|
104
|
+
if (isFile(candidate)) return candidate;
|
|
105
|
+
}
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 用户已经有的 frpc(优先级最高)。
|
|
111
|
+
*
|
|
112
|
+
* ① 环境变量 `DSHM_FRPC_BIN` 指的那一份(用户/部署方自己放好的路径);
|
|
113
|
+
* ② 系统 PATH 里的 frpc。
|
|
114
|
+
* 都没有返回 null。这里不关心平台资产表——用户给了就直接用。
|
|
115
|
+
*/
|
|
116
|
+
function resolveInstalled(options = {}) {
|
|
117
|
+
const env = options.env || process.env;
|
|
118
|
+
const platform = options.platform || process.platform;
|
|
119
|
+
const override = env.DSHM_FRPC_BIN;
|
|
120
|
+
if (typeof override === 'string' && override && isFile(override)) {
|
|
121
|
+
return { path: override, source: 'configured' };
|
|
122
|
+
}
|
|
123
|
+
const binName = options.bin || (platform === 'win32' ? 'frpc.exe' : 'frpc');
|
|
124
|
+
const found = findOnPath(binName, { env, platform });
|
|
125
|
+
if (found) return { path: found, source: 'system' };
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** 从 tar.gz 里读出名为 `basename` 的那个文件(只挑这一个,别的不要)。 */
|
|
130
|
+
function extractTarGzEntry(input, basename) {
|
|
131
|
+
const zlib = require('node:zlib');
|
|
132
|
+
const tar = input.length >= 2 && input[0] === 0x1f && input[1] === 0x8b ? zlib.gunzipSync(input) : input;
|
|
133
|
+
const str = (buf, start, length) => {
|
|
134
|
+
const slice = buf.subarray(start, start + length);
|
|
135
|
+
const zero = slice.indexOf(0);
|
|
136
|
+
return (zero === -1 ? slice : slice.subarray(0, zero)).toString('utf8');
|
|
137
|
+
};
|
|
138
|
+
const BLOCK = 512;
|
|
139
|
+
let offset = 0;
|
|
140
|
+
while (offset + BLOCK <= tar.length) {
|
|
141
|
+
const header = tar.subarray(offset, offset + BLOCK);
|
|
142
|
+
if (header.every((byte) => byte === 0)) break;
|
|
143
|
+
const name = str(header, 0, 100);
|
|
144
|
+
const prefix = str(header, 345, 155);
|
|
145
|
+
const sizeText = str(header, 124, 12).trim();
|
|
146
|
+
const size = sizeText ? Number.parseInt(sizeText, 8) : 0;
|
|
147
|
+
const type = String.fromCharCode(header[156]) || '0';
|
|
148
|
+
const start = offset + BLOCK;
|
|
149
|
+
const end = start + (Number.isFinite(size) ? size : 0);
|
|
150
|
+
if (end > tar.length) throw new Error(`压缩包被截断:条目 ${name || '(无名)'} 声明的长度超出文件`);
|
|
151
|
+
const full = prefix ? `${prefix}/${name}` : name;
|
|
152
|
+
if ((type === '0' || type === '\u0000') && path.basename(full) === basename) {
|
|
153
|
+
return Buffer.from(tar.subarray(start, end));
|
|
154
|
+
}
|
|
155
|
+
offset = start + Math.ceil((Number.isFinite(size) ? size : 0) / BLOCK) * BLOCK;
|
|
156
|
+
}
|
|
157
|
+
throw new Error(`压缩包里没有找到 ${basename}`);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 从 zip 里读出名为 `basename` 的那个文件(只挑这一个)。支持 store(0) 与 deflate(8)。 */
|
|
161
|
+
function extractZipEntry(input, basename) {
|
|
162
|
+
const zlib = require('node:zlib');
|
|
163
|
+
const u16 = (buf, at) => buf.readUInt16LE(at);
|
|
164
|
+
const u32 = (buf, at) => buf.readUInt32LE(at);
|
|
165
|
+
// 从尾部找中央目录结束记录(EOCD),签名 0x06054b50,后面最多跟 65535 字节注释。
|
|
166
|
+
let eocd = -1;
|
|
167
|
+
const floor = Math.max(0, input.length - 22 - 0xffff);
|
|
168
|
+
for (let at = input.length - 22; at >= floor; at -= 1) {
|
|
169
|
+
if (u32(input, at) === 0x06054b50) { eocd = at; break; }
|
|
170
|
+
}
|
|
171
|
+
if (eocd < 0) throw new Error('不是有效的 zip:找不到中央目录');
|
|
172
|
+
const total = u16(input, eocd + 10);
|
|
173
|
+
let cursor = eocd;
|
|
174
|
+
// 中央目录在 EOCD 前面;从「中央目录偏移」开始逐条扫更稳。
|
|
175
|
+
const centralOffset = u32(input, eocd + 16);
|
|
176
|
+
let at = centralOffset;
|
|
177
|
+
for (let index = 0; index < total; index += 1) {
|
|
178
|
+
if (u32(input, at) !== 0x02014b50) throw new Error('zip 中央目录损坏');
|
|
179
|
+
const method = u16(input, at + 10);
|
|
180
|
+
const compressedSize = u32(input, at + 20);
|
|
181
|
+
const nameLen = u16(input, at + 28);
|
|
182
|
+
const extraLen = u16(input, at + 30);
|
|
183
|
+
const commentLen = u16(input, at + 32);
|
|
184
|
+
const localOffset = u32(input, at + 42);
|
|
185
|
+
const name = input.subarray(at + 46, at + 46 + nameLen).toString('utf8');
|
|
186
|
+
if (path.basename(name.replace(/\\/g, '/')) === basename) {
|
|
187
|
+
if (u32(input, localOffset) !== 0x04034b50) throw new Error('zip 本地头损坏');
|
|
188
|
+
const localNameLen = u16(input, localOffset + 26);
|
|
189
|
+
const localExtraLen = u16(input, localOffset + 28);
|
|
190
|
+
const dataStart = localOffset + 30 + localNameLen + localExtraLen;
|
|
191
|
+
const raw = input.subarray(dataStart, dataStart + compressedSize);
|
|
192
|
+
if (method === 0) return Buffer.from(raw);
|
|
193
|
+
if (method === 8) return zlib.inflateRawSync(raw);
|
|
194
|
+
throw new Error(`zip 用了不支持的压缩方式:${method}`);
|
|
195
|
+
}
|
|
196
|
+
at += 46 + nameLen + extraLen + commentLen;
|
|
197
|
+
cursor = at;
|
|
198
|
+
}
|
|
199
|
+
throw new Error(`压缩包里没有找到 ${basename}`);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** 按 `archive` 类型从解出的字节里挑出可执行文件。 */
|
|
203
|
+
function extractEntry(buffer, asset) {
|
|
204
|
+
return asset.archive === 'zip'
|
|
205
|
+
? extractZipEntry(buffer, asset.bin)
|
|
206
|
+
: extractTarGzEntry(buffer, asset.bin);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* 下载一个资产包、校验、解包,把可执行文件写到 `dir/bin`。
|
|
211
|
+
*
|
|
212
|
+
* 只写这一个文件;先写进调用方给的暂存目录,最后由 `ensureFrpc` 原子换上,所以半截文件
|
|
213
|
+
* 不会出现在正式缓存目录里。
|
|
214
|
+
*/
|
|
215
|
+
async function downloadTo({ url, asset, dir, fetchImpl, timeoutMs = DOWNLOAD_TIMEOUT_MS }) {
|
|
216
|
+
const doFetch = fetchImpl || globalThis.fetch;
|
|
217
|
+
if (typeof doFetch !== 'function') throw codedError('no-fetch', '当前环境没有可用的 fetch');
|
|
218
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
219
|
+
const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
|
|
220
|
+
let response;
|
|
221
|
+
try {
|
|
222
|
+
response = await doFetch(url, controller ? { signal: controller.signal } : {});
|
|
223
|
+
} catch (error) {
|
|
224
|
+
throw codedError('download-failed', `下载 frpc 失败:${error && error.message ? error.message : error}`);
|
|
225
|
+
} finally {
|
|
226
|
+
if (timer) clearTimeout(timer);
|
|
227
|
+
}
|
|
228
|
+
if (!response || response.ok !== true) {
|
|
229
|
+
throw codedError('download-failed', `下载 frpc 失败:HTTP ${response ? response.status : '无响应'}`);
|
|
230
|
+
}
|
|
231
|
+
const buffer = Buffer.from(await response.arrayBuffer());
|
|
232
|
+
const got = sha256Hex(buffer);
|
|
233
|
+
if (asset.sha256 && got !== asset.sha256) {
|
|
234
|
+
throw codedError('checksum', `frpc 校验失败:下载内容的 sha256 与预期不一致(预期 ${asset.sha256},实际 ${got})`);
|
|
235
|
+
}
|
|
236
|
+
let binary;
|
|
237
|
+
try {
|
|
238
|
+
binary = extractEntry(buffer, asset);
|
|
239
|
+
} catch (error) {
|
|
240
|
+
throw codedError('extract-failed', `解包 frpc 失败:${error && error.message ? error.message : error}`);
|
|
241
|
+
}
|
|
242
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
243
|
+
const dest = path.join(dir, asset.bin);
|
|
244
|
+
fs.writeFileSync(dest, binary);
|
|
245
|
+
// 可执行位只在 POSIX 有意义;Windows 上 chmod 只改只读标记,别去碰。
|
|
246
|
+
if (process.platform !== 'win32') {
|
|
247
|
+
try { fs.chmodSync(dest, 0o755); } catch { /* 权限位没打上也不至于跑不了 */ }
|
|
248
|
+
}
|
|
249
|
+
return dest;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function codedError(code, message) {
|
|
253
|
+
const error = new Error(message);
|
|
254
|
+
error.code = code;
|
|
255
|
+
return error;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** 把目录换成目标目录;同盘 rename,跨盘退回复制再删(与 OTA 那条同一套兜底)。 */
|
|
259
|
+
function moveDir(src, dst) {
|
|
260
|
+
try {
|
|
261
|
+
fs.renameSync(src, dst);
|
|
262
|
+
return;
|
|
263
|
+
} catch (error) {
|
|
264
|
+
const code = error && error.code;
|
|
265
|
+
if (!['EXDEV', 'EPERM', 'EACCES', 'ENOTEMPTY', 'EEXIST'].includes(code)) throw error;
|
|
266
|
+
}
|
|
267
|
+
fs.rmSync(dst, { recursive: true, force: true });
|
|
268
|
+
fs.cpSync(src, dst, { recursive: true });
|
|
269
|
+
fs.rmSync(src, { recursive: true, force: true });
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** 成功后清掉**其它版本目录**的缓存,失败不影响主流程。只清版本号样式的目录,别动同目录下的配置/标记。 */
|
|
273
|
+
function pruneOldVersions(root, currentVersion) {
|
|
274
|
+
let names;
|
|
275
|
+
try { names = fs.readdirSync(root); } catch { return; }
|
|
276
|
+
for (const name of names) {
|
|
277
|
+
if (name === currentVersion || !/^\d+\.\d+\.\d+/.test(name)) continue;
|
|
278
|
+
try { fs.rmSync(path.join(root, name), { recursive: true, force: true }); } catch { /* 占着就下次再清 */ }
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** 同一平台的并发触发合并成一次下载。 */
|
|
283
|
+
function withLock(key, task) {
|
|
284
|
+
const existing = inflight.get(key);
|
|
285
|
+
if (existing) return existing;
|
|
286
|
+
const promise = Promise.resolve().then(task).finally(() => inflight.delete(key));
|
|
287
|
+
inflight.set(key, promise);
|
|
288
|
+
return promise;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* 拿到一份可用的 frpc。
|
|
293
|
+
*
|
|
294
|
+
* @returns {Promise<{ok:true, path:string, source:'configured'|'system'|'cache'|'downloaded', version:string|null, platform:string}
|
|
295
|
+
* | {ok:false, reason:string, message:string}>}
|
|
296
|
+
*
|
|
297
|
+
* 选项中可注入(测试用):platform/platformId、arch、env、cacheRoot、version、asset、baseUrl、fetchImpl、
|
|
298
|
+
* offline(true = 不允许联网,只认已有/缓存)。
|
|
299
|
+
*/
|
|
300
|
+
async function ensureFrpc(options = {}) {
|
|
301
|
+
const platform = options.platformId || platformId(options.platform, options.arch);
|
|
302
|
+
const version = options.version || FRP_VERSION;
|
|
303
|
+
|
|
304
|
+
// ① 用户自己有的(显式路径 / PATH):平台认不出也先认这一份。
|
|
305
|
+
const installed = resolveInstalled(options);
|
|
306
|
+
if (installed) {
|
|
307
|
+
return { ok: true, path: installed.path, source: installed.source, version: null, platform: platform || null };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// ② 平台/资产:认不出就不猜。
|
|
311
|
+
const asset = options.asset || (platform ? ASSETS[platform] : null);
|
|
312
|
+
if (!platform || !asset) {
|
|
313
|
+
return fail('unsupported-platform', `这台机器(${options.platform || process.platform}/${options.arch || process.arch})不在支持的平台上,装不了 frpc`);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const dir = options.cacheRoot
|
|
317
|
+
? path.join(options.cacheRoot, version, platform)
|
|
318
|
+
: cacheDirOf({ ...options, platformId: platform, version });
|
|
319
|
+
const binaryPath = path.join(dir, asset.bin);
|
|
320
|
+
// ③ 缓存命中。
|
|
321
|
+
if (isFile(binaryPath)) {
|
|
322
|
+
return { ok: true, path: binaryPath, source: 'cache', version, platform };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// ④ 要联网:不允许就直接回,别让调用方等超时。
|
|
326
|
+
if (options.offline) {
|
|
327
|
+
return fail('offline', '本机没有找到 frpc,且当前不允许联网下载');
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
return withLock(platform, async () => {
|
|
331
|
+
// 排队期间可能已经被别的调用拉好了,再确认一次。
|
|
332
|
+
if (isFile(binaryPath)) {
|
|
333
|
+
return { ok: true, path: binaryPath, source: 'cache', version, platform };
|
|
334
|
+
}
|
|
335
|
+
const root = options.cacheRoot || cacheRoot(options);
|
|
336
|
+
const staging = path.join(root, `.staging-${process.pid}-${crypto.randomBytes(6).toString('hex')}`);
|
|
337
|
+
const baseUrl = options.baseUrl || DEFAULT_BASE_URL;
|
|
338
|
+
const url = `${baseUrl.replace(/\/+$/, '')}/${asset.file}`;
|
|
339
|
+
try {
|
|
340
|
+
await downloadTo({ url, asset, dir: staging, fetchImpl: options.fetchImpl, timeoutMs: options.timeoutMs });
|
|
341
|
+
// 先剔掉可能残留的旧目录,再把暂存目录原子换上。
|
|
342
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
343
|
+
fs.mkdirSync(path.dirname(dir), { recursive: true });
|
|
344
|
+
moveDir(staging, dir);
|
|
345
|
+
pruneOldVersions(root, version);
|
|
346
|
+
return { ok: true, path: binaryPath, source: 'downloaded', version, platform };
|
|
347
|
+
} catch (error) {
|
|
348
|
+
fs.rmSync(staging, { recursive: true, force: true });
|
|
349
|
+
return fail(error && error.code ? error.code : 'download-failed', error && error.message ? error.message : String(error));
|
|
350
|
+
}
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* 不联网地看一下现状:当前平台、能不能用、用的是哪一份。给界面/日志用,触发不到下载。
|
|
356
|
+
*/
|
|
357
|
+
function inspectFrpc(options = {}) {
|
|
358
|
+
const platform = options.platformId || platformId(options.platform, options.arch) || null;
|
|
359
|
+
const asset = (platform && ASSETS[platform]) || null;
|
|
360
|
+
const installed = resolveInstalled(options);
|
|
361
|
+
if (installed) {
|
|
362
|
+
return { ok: true, available: true, source: installed.source, path: installed.path, platform, version: null };
|
|
363
|
+
}
|
|
364
|
+
const version = options.version || FRP_VERSION;
|
|
365
|
+
if (!asset) return { ok: false, available: false, reason: 'unsupported-platform', platform, version };
|
|
366
|
+
const dir = options.cacheRoot ? path.join(options.cacheRoot, version, platform) : cacheDirOf({ ...options, platformId: platform, version });
|
|
367
|
+
const cached = path.join(dir, asset.bin);
|
|
368
|
+
return { ok: true, available: isFile(cached), source: isFile(cached) ? 'cache' : null, path: isFile(cached) ? cached : null, platform, version };
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
module.exports = {
|
|
372
|
+
FRP_VERSION,
|
|
373
|
+
ASSETS,
|
|
374
|
+
DEFAULT_BASE_URL,
|
|
375
|
+
platformId,
|
|
376
|
+
cacheRoot,
|
|
377
|
+
cacheDirOf,
|
|
378
|
+
resolveInstalled,
|
|
379
|
+
findOnPath,
|
|
380
|
+
extractTarGzEntry,
|
|
381
|
+
extractZipEntry,
|
|
382
|
+
ensureFrpc,
|
|
383
|
+
inspectFrpc,
|
|
384
|
+
};
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 在本机跑一个 frpc 进程,让面板导入的 FRP 配置真正生效。
|
|
5
|
+
*
|
|
6
|
+
* 为什么单独一层:`provision.cjs` 只负责「弄到可执行文件」,这里负责「用一份配置把它跑起来
|
|
7
|
+
* 并管住进程」。两件事分开,测试也能各测各的(这里注入假 spawn / 假 ensure,不真起进程)。
|
|
8
|
+
*
|
|
9
|
+
* 关键一步是**本地端口对齐**:面板导入的是服务商生成的配置,里面的 `localPort` 未必等于插件
|
|
10
|
+
* 此刻真正监听的端口(端口被占用会退让、用户改过也另说)。照抄会让公网请求转到一个没人的端口。
|
|
11
|
+
* 所以每次启动前都把配置里的 `localPort` 改成当前实际端口,再写盘、再起 frpc。
|
|
12
|
+
*
|
|
13
|
+
* 进程退出/起不来一律记进 `error`,不抛给调用方;`status()` 回一份可渲染的事实。frpc 自己会
|
|
14
|
+
* 对 frps 重试,进程不会因为连不上服务器就退出,所以这里不做进程级自动重启。
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const fs = require('node:fs');
|
|
18
|
+
const path = require('node:path');
|
|
19
|
+
const { spawn } = require('node:child_process');
|
|
20
|
+
|
|
21
|
+
const { dshHome } = require('../shared/paths.js');
|
|
22
|
+
const { ensureFrpc } = require('./provision.cjs');
|
|
23
|
+
|
|
24
|
+
/** 本机 frpc 管理接口的默认端口:只监听回环,用来读它实际分到的公网地址(remote_addr)。 */
|
|
25
|
+
const DEFAULT_ADMIN_PORT = 17401;
|
|
26
|
+
|
|
27
|
+
/** 把配置里每一处 `localPort / local_port` 改成实际端口,其余原样。 */
|
|
28
|
+
function alignLocalPort(text, port) {
|
|
29
|
+
const value = Number(port);
|
|
30
|
+
if (!Number.isInteger(value) || value <= 0) return String(text || '');
|
|
31
|
+
return String(text || '').replace(/^(\s*local(?:Port|_port)\s*[=:]\s*)["']?\d+["']?/gim, `$1${value}`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 给配置补一个本机管理接口(`webServer`),好让插件能读到 frpc 实际分到的公网地址。
|
|
36
|
+
*
|
|
37
|
+
* 服务商配置常常不写 `remotePort`(由服务端分配),地址只能从 frpc 的管理接口读。用户配置里
|
|
38
|
+
* 已经有 `webServer` 就不动它,免得把人家自己的设置覆盖掉。只对带 `[[proxies]]` 的 TOML 生效
|
|
39
|
+
* (INI 没这类顶层写法,跳过)。
|
|
40
|
+
*/
|
|
41
|
+
function withAdminPort(text, port) {
|
|
42
|
+
const source = String(text || '');
|
|
43
|
+
if (/(?:^|\n)\s*webServer\s*[.=]/i.test(source)) return source;
|
|
44
|
+
if (!/\[\[\s*proxies\s*\]\]/i.test(source)) return source;
|
|
45
|
+
const block = `webServer.addr = "127.0.0.1"\nwebServer.port = ${port}\n\n`;
|
|
46
|
+
return source.replace(/(\[\[\s*proxies\s*\]\])/i, `${block}$1`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function frpcPaths(root) {
|
|
50
|
+
// 配置与「启用」标记放在**单独目录**:`provision` 的缓存根是 `<DSH 数据目录>/frpc`,它在
|
|
51
|
+
// 装好新二进制后会清掉那里除版本号外的条目——放一起会把正在用的 frpc.toml 一起删掉。
|
|
52
|
+
const dir = root || path.join(dshHome(), 'frpc-run');
|
|
53
|
+
return { dir, config: path.join(dir, 'frpc.toml'), enabled: path.join(dir, 'frpc.enabled') };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 造一个 frpc 运行器。
|
|
58
|
+
*
|
|
59
|
+
* options(都可注入,测试用):
|
|
60
|
+
* root 缓存/配置目录(缺省 `<DSH 数据目录>/frpc`)
|
|
61
|
+
* portOf `() => number`:当前插件实际监听端口(启动前用它改 localPort)
|
|
62
|
+
* ensure `(opts) => Promise<{ok,path,message}>`:拿 frpc 可执行文件(缺省 provision.ensureFrpc)
|
|
63
|
+
* spawnImpl 子进程工厂(缺省 node:child_process.spawn)
|
|
64
|
+
* fsImpl 文件系统(缺省 node:fs,测试可造假)
|
|
65
|
+
*/
|
|
66
|
+
function createFrpcRunner(options = {}) {
|
|
67
|
+
const paths = frpcPaths(options.root);
|
|
68
|
+
const ensure = typeof options.ensure === 'function' ? options.ensure : ensureFrpc;
|
|
69
|
+
const spawnImpl = typeof options.spawnImpl === 'function' ? options.spawnImpl : spawn;
|
|
70
|
+
const portOf = typeof options.portOf === 'function' ? options.portOf : () => null;
|
|
71
|
+
const fsImpl = options.fsImpl || fs;
|
|
72
|
+
const fetchImpl = options.fetchImpl || (typeof globalThis.fetch === 'function' ? globalThis.fetch : null);
|
|
73
|
+
const adminPort = Number.isInteger(options.adminPort) ? options.adminPort : DEFAULT_ADMIN_PORT;
|
|
74
|
+
|
|
75
|
+
let child = null;
|
|
76
|
+
let binary = '';
|
|
77
|
+
let error = '';
|
|
78
|
+
let startedAt = 0;
|
|
79
|
+
/** frpc 连上后服务端分给这条隧道的公网地址(`remote_addr`);没读到就是空串。 */
|
|
80
|
+
let remoteAddress = '';
|
|
81
|
+
|
|
82
|
+
const exists = (p) => { try { return fsImpl.existsSync(p); } catch { return false; } };
|
|
83
|
+
const readConfig = () => { try { return fsImpl.readFileSync(paths.config, 'utf8'); } catch { return null; } };
|
|
84
|
+
|
|
85
|
+
function status() {
|
|
86
|
+
const running = Boolean(child);
|
|
87
|
+
return {
|
|
88
|
+
available: Boolean(binary),
|
|
89
|
+
running,
|
|
90
|
+
pid: running && child.pid ? child.pid : null,
|
|
91
|
+
error,
|
|
92
|
+
startedAt,
|
|
93
|
+
configPresent: exists(paths.config),
|
|
94
|
+
remoteAddress: running ? remoteAddress : '',
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 把配置按「实际端口 + 本机管理接口」写好(localPort 对齐、补 webServer 好读公网地址)。 */
|
|
99
|
+
function writeRunConfig(text) {
|
|
100
|
+
const prepared = withAdminPort(alignLocalPort(text, Number(portOf())), adminPort);
|
|
101
|
+
fsImpl.mkdirSync(paths.dir, { recursive: true });
|
|
102
|
+
fsImpl.writeFileSync(paths.config, prepared);
|
|
103
|
+
return prepared;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 保存导入的配置(localPort 对齐、补管理接口)并记下「启用」,重启宿主后自动再拉起。 */
|
|
107
|
+
function saveConfig(text) {
|
|
108
|
+
writeRunConfig(text);
|
|
109
|
+
try { fsImpl.writeFileSync(paths.enabled, '1'); } catch { /* 标记落不下去下次手动起 */ }
|
|
110
|
+
return paths.config;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** 从管理接口的 `/api/status` 里挑出第一条代理的 `remote_addr`。 */
|
|
114
|
+
function pickRemote(payload) {
|
|
115
|
+
if (!payload || typeof payload !== 'object') return '';
|
|
116
|
+
for (const group of Object.values(payload)) {
|
|
117
|
+
if (!Array.isArray(group)) continue;
|
|
118
|
+
for (const entry of group) {
|
|
119
|
+
const addr = entry && typeof entry.remote_addr === 'string' ? entry.remote_addr.trim() : '';
|
|
120
|
+
if (addr && addr.includes(':')) return addr;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return '';
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* 轮询 frpc 管理接口,拿到服务端实际分配的公网地址(`host:port`)。服务商配置不写 remotePort
|
|
128
|
+
* 时,这是唯一能知道「手机该连哪」的地方。读不到返回空串,不抛。
|
|
129
|
+
*/
|
|
130
|
+
async function discoverRemoteAddress(timeoutMs = 8000) {
|
|
131
|
+
if (!fetchImpl) return '';
|
|
132
|
+
const deadline = Date.now() + Math.max(500, Number(timeoutMs) || 8000);
|
|
133
|
+
const url = `http://127.0.0.1:${adminPort}/api/status`;
|
|
134
|
+
while (Date.now() < deadline) {
|
|
135
|
+
if (!child) return ''; // 进程都退了,别等了
|
|
136
|
+
try {
|
|
137
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
138
|
+
const timer = controller ? setTimeout(() => controller.abort(), 1500) : null;
|
|
139
|
+
let response;
|
|
140
|
+
try {
|
|
141
|
+
response = await fetchImpl(url, controller ? { signal: controller.signal } : {});
|
|
142
|
+
} finally {
|
|
143
|
+
if (timer) clearTimeout(timer);
|
|
144
|
+
}
|
|
145
|
+
if (response && response.ok) {
|
|
146
|
+
const addr = pickRemote(await response.json());
|
|
147
|
+
if (addr) { remoteAddress = addr; return addr; }
|
|
148
|
+
}
|
|
149
|
+
} catch { /* 还没起来,接着轮 */ }
|
|
150
|
+
await new Promise((resolve) => setTimeout(resolve, 350));
|
|
151
|
+
}
|
|
152
|
+
return '';
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async function start() {
|
|
156
|
+
if (child) return status();
|
|
157
|
+
const raw = readConfig();
|
|
158
|
+
if (!raw) { error = '还没有导入 frpc 配置'; return status(); }
|
|
159
|
+
try {
|
|
160
|
+
writeRunConfig(raw);
|
|
161
|
+
} catch (err) {
|
|
162
|
+
error = `写 frpc 配置失败:${err && err.message ? err.message : err}`;
|
|
163
|
+
return status();
|
|
164
|
+
}
|
|
165
|
+
const got = await ensure({});
|
|
166
|
+
if (!got || got.ok !== true) {
|
|
167
|
+
error = got && got.message ? got.message : '没拿到 frpc 可执行文件';
|
|
168
|
+
return status();
|
|
169
|
+
}
|
|
170
|
+
binary = got.path;
|
|
171
|
+
let proc;
|
|
172
|
+
try {
|
|
173
|
+
proc = spawnImpl(binary, ['-c', paths.config], { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true });
|
|
174
|
+
} catch (err) {
|
|
175
|
+
error = `启动 frpc 失败:${err && err.message ? err.message : err}`;
|
|
176
|
+
child = null;
|
|
177
|
+
return status();
|
|
178
|
+
}
|
|
179
|
+
child = proc;
|
|
180
|
+
error = '';
|
|
181
|
+
remoteAddress = '';
|
|
182
|
+
startedAt = Date.now();
|
|
183
|
+
let tail = '';
|
|
184
|
+
if (proc.stderr && typeof proc.stderr.on === 'function') {
|
|
185
|
+
if (typeof proc.stderr.setEncoding === 'function') proc.stderr.setEncoding('utf8');
|
|
186
|
+
proc.stderr.on('data', (chunk) => { tail = (tail + String(chunk)).slice(-1500); });
|
|
187
|
+
}
|
|
188
|
+
if (typeof proc.on === 'function') {
|
|
189
|
+
proc.on('error', (err) => { error = `frpc 进程出错:${err && err.message ? err.message : err}`; });
|
|
190
|
+
proc.on('exit', (code, signal) => {
|
|
191
|
+
if (!child) return;
|
|
192
|
+
child = null;
|
|
193
|
+
remoteAddress = '';
|
|
194
|
+
const lastLine = tail.trim() ? tail.trim().split('\n').pop() : '';
|
|
195
|
+
error = `frpc 已退出(code=${code}${signal ? `, ${signal}` : ''})${lastLine ? `:${lastLine}` : ''}`;
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
return status();
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function stop() {
|
|
202
|
+
if (!child) return status();
|
|
203
|
+
const proc = child;
|
|
204
|
+
child = null;
|
|
205
|
+
try { proc.kill('SIGTERM'); } catch { /* 已经没了 */ }
|
|
206
|
+
error = '';
|
|
207
|
+
return status();
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return {
|
|
211
|
+
status,
|
|
212
|
+
start,
|
|
213
|
+
stop,
|
|
214
|
+
async restart() { await stop(); return start(); },
|
|
215
|
+
saveConfig,
|
|
216
|
+
discoverRemoteAddress,
|
|
217
|
+
/** 停掉进程并清掉「启用」标记(用户主动断开时用)。 */
|
|
218
|
+
async clear() {
|
|
219
|
+
try { fsImpl.rmSync(paths.enabled, { force: true }); } catch { /* 没有就算了 */ }
|
|
220
|
+
return stop();
|
|
221
|
+
},
|
|
222
|
+
/** 宿主重启后要不要自动再拉起:上次是启用状态且配置还在。 */
|
|
223
|
+
shouldAutoStart() { return exists(paths.enabled) && exists(paths.config); },
|
|
224
|
+
dispose() { return stop(); },
|
|
225
|
+
_paths: paths,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
module.exports = { createFrpcRunner, alignLocalPort, withAdminPort, frpcPaths };
|