dsh-mobile-ios 0.2.6 → 0.2.8
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 +284 -284
- package/cordis.patch.yml +20 -20
- package/entries/plugin.mjs +246 -246
- package/entries/sidecar.mjs +111 -111
- package/lib/client.js +1294 -1193
- package/lib/vendor/qrcode-generator.cjs +2297 -2297
- package/lib/vendor/qrcode-utf8.cjs +26 -26
- package/package.json +53 -53
- package/src/adapter/artifacts.mjs +235 -235
- package/src/adapter/cordis-host.mjs +1225 -1225
- package/src/adapter/mock-host.mjs +437 -437
- package/src/adapter/mux-host.mjs +99 -99
- package/src/adapter/session-history.mjs +241 -241
- package/src/cloudflare.mjs +628 -628
- package/src/cloudflared-install.mjs +139 -0
- package/src/dns-label.mjs +32 -32
- package/src/dns-probe.mjs +90 -90
- package/src/file-log.mjs +68 -68
- package/src/gateway.mjs +285 -285
- package/src/pairing.mjs +300 -300
- package/src/protocol.mjs +59 -59
- package/src/provision-local.mjs +309 -309
- package/src/rest.mjs +812 -786
- package/src/ring.mjs +148 -148
- package/src/server.mjs +219 -219
- package/src/tunnel.mjs +523 -504
- package/src/version.mjs +24 -24
- package/src/ws.mjs +332 -332
package/src/provision-local.mjs
CHANGED
|
@@ -1,309 +1,309 @@
|
|
|
1
|
-
// provision-local.mjs — 用 cloudflared 自己的证书开通固定地址(本地管理型隧道)
|
|
2
|
-
//
|
|
3
|
-
// 为什么要有这条路:zone 级 API Token 不是谁手边都有,也不该为了一次开通就建一个。
|
|
4
|
-
// `cloudflared tunnel login` 会在本机写一份 zone 范围的 cert.pem;之后 create / route dns
|
|
5
|
-
// 都用它完成,全程不需要我们接触 API Token。
|
|
6
|
-
//
|
|
7
|
-
// 与 token 形态(cloudflare.mjs)的差别只有一个:cloudflared 用 `--config` 指向本地
|
|
8
|
-
// ingress 配置 + credentials 文件,而不是 `TUNNEL_TOKEN` 环境变量。对外接口保持一致:
|
|
9
|
-
// ensure({ port }) → { hostname, url, tunnelId, created }
|
|
10
|
-
// credential({ port }) → { hostname, configFile }
|
|
11
|
-
//
|
|
12
|
-
// 安全边界:
|
|
13
|
-
// · cert.pem 属于 zone 级凭据,绝不复制、绝不外发;这里只检查它存在;
|
|
14
|
-
// · credentials 文件同理,只把**路径**写进配置,不读内容、不进日志;
|
|
15
|
-
// · 配置与状态文件都 0600。
|
|
16
|
-
|
|
17
|
-
import crypto from 'node:crypto';
|
|
18
|
-
import fs from 'node:fs';
|
|
19
|
-
import os from 'node:os';
|
|
20
|
-
import path from 'node:path';
|
|
21
|
-
import { execFile as nodeExecFile } from 'node:child_process';
|
|
22
|
-
import { promisify } from 'node:util';
|
|
23
|
-
import { fail } from './protocol.mjs';
|
|
24
|
-
import { deriveSubdomain, isValidLabel } from './dns-label.mjs';
|
|
25
|
-
import { dnsWarningFor, evaluateDnsAnswer, probeDns } from './dns-probe.mjs';
|
|
26
|
-
|
|
27
|
-
const execFileAsync = promisify(nodeExecFile);
|
|
28
|
-
const CLI_TIMEOUT_MS = 45_000;
|
|
29
|
-
const STATE_VERSION = 1;
|
|
30
|
-
|
|
31
|
-
const UUID_PATTERN = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i;
|
|
32
|
-
|
|
33
|
-
function readState(file, log) {
|
|
34
|
-
if (!file) return null;
|
|
35
|
-
try {
|
|
36
|
-
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
37
|
-
if (!parsed || parsed.version !== STATE_VERSION) throw new Error('结构不符');
|
|
38
|
-
return parsed;
|
|
39
|
-
} catch (err) {
|
|
40
|
-
if (err.code !== 'ENOENT') log?.(`tunnel 本地开通状态不可用:${err.message}`);
|
|
41
|
-
return null;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function writeState(file, state) {
|
|
46
|
-
if (!file) return;
|
|
47
|
-
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
48
|
-
const tmp = `${file}.${process.pid}.tmp`;
|
|
49
|
-
fs.writeFileSync(tmp, JSON.stringify({ version: STATE_VERSION, ...state }, null, 2), { mode: 0o600, flag: 'w' });
|
|
50
|
-
fs.renameSync(tmp, file);
|
|
51
|
-
try { fs.chmodSync(file, 0o600); } catch { /* 刚写即 0600 */ }
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/** cloudflared 的 ingress 配置文件。ports/hostname 变一次就要重写一次。 */
|
|
55
|
-
export function renderConfig({ tunnelId, credentialsFile, hostname, port }) {
|
|
56
|
-
return [
|
|
57
|
-
`# generated by dsh-mobile — 端口变化会重写本文件;不要手改`,
|
|
58
|
-
`tunnel: ${tunnelId}`,
|
|
59
|
-
`credentials-file: ${credentialsFile}`,
|
|
60
|
-
'',
|
|
61
|
-
'ingress:',
|
|
62
|
-
` - hostname: ${hostname}`,
|
|
63
|
-
` service: http://127.0.0.1:${port}`,
|
|
64
|
-
' - service: http_status:404',
|
|
65
|
-
'',
|
|
66
|
-
].join('\n');
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
export class LocalProvisioner {
|
|
70
|
-
constructor({
|
|
71
|
-
baseDomain = 'matrixboard.cn',
|
|
72
|
-
prefix = 'dsh',
|
|
73
|
-
executable = 'cloudflared',
|
|
74
|
-
stateFile = null,
|
|
75
|
-
configFile = null,
|
|
76
|
-
seed = null,
|
|
77
|
-
homeDir = os.homedir(),
|
|
78
|
-
log = () => {},
|
|
79
|
-
run = null,
|
|
80
|
-
// 可注入:测试里不该真发 DNS 查询(会等 NXDOMAIN 重试,还依赖外网)
|
|
81
|
-
probe = null,
|
|
82
|
-
} = {}) {
|
|
83
|
-
this.baseDomain = String(baseDomain).replace(/^\./, '').toLowerCase();
|
|
84
|
-
this.prefix = prefix;
|
|
85
|
-
this.executable = executable;
|
|
86
|
-
this.stateFile = stateFile;
|
|
87
|
-
this.configFile = configFile || path.join(path.dirname(stateFile || path.join(homeDir, 'x')), 'tunnel-config.yml');
|
|
88
|
-
this.seed = seed;
|
|
89
|
-
this.homeDir = homeDir;
|
|
90
|
-
this.log = log;
|
|
91
|
-
this._state = undefined;
|
|
92
|
-
// 可注入,测试里不必真起 cloudflared
|
|
93
|
-
this.run = run || this.#exec;
|
|
94
|
-
this.probe = probe || probeDns;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
get kind() {
|
|
98
|
-
return 'local';
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
get state() {
|
|
102
|
-
if (this._state === undefined) this._state = readState(this.stateFile, this.log);
|
|
103
|
-
return this._state;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
get configured() {
|
|
107
|
-
// 本地形态只要证书在就算可开通;已开通则要配置与凭据都在
|
|
108
|
-
if (this.state?.configFile) return true;
|
|
109
|
-
return fs.existsSync(path.join(this.homeDir, '.cloudflared', 'cert.pem'));
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
get notConfiguredMessage() {
|
|
113
|
-
return '主机还没有登录 Cloudflare';
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
get notConfiguredDetail() {
|
|
117
|
-
return `在这台电脑的终端执行:${this.executable} tunnel login(浏览器里选 matrixboard.cn 授权)`;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
status() {
|
|
121
|
-
const s = this.state;
|
|
122
|
-
if (!s) return { kind: 'local', provisioned: false, hostname: null, url: null, tunnelId: null };
|
|
123
|
-
return {
|
|
124
|
-
kind: 'local',
|
|
125
|
-
provisioned: true,
|
|
126
|
-
hostname: s.hostname,
|
|
127
|
-
url: `https://${s.hostname}`,
|
|
128
|
-
tunnelId: s.tunnelId,
|
|
129
|
-
port: s.port ?? null,
|
|
130
|
-
// null = 还没验过(老状态文件);false = 验过但公网没有——面板必须提示,别让人扫码扫到空气
|
|
131
|
-
dnsOk: s.dnsOk ?? null,
|
|
132
|
-
warning: dnsWarningFor(s),
|
|
133
|
-
createdAt: s.createdAt ?? null,
|
|
134
|
-
updatedAt: s.updatedAt ?? null,
|
|
135
|
-
};
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
async #exec(args) {
|
|
139
|
-
const { stdout, stderr } = await execFileAsync(this.executable, args, {
|
|
140
|
-
timeout: CLI_TIMEOUT_MS,
|
|
141
|
-
maxBuffer: 4 * 1024 * 1024,
|
|
142
|
-
env: process.env,
|
|
143
|
-
});
|
|
144
|
-
return `${stdout || ''}${stderr || ''}`;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
async #assertLogin() {
|
|
148
|
-
const cert = path.join(this.homeDir, '.cloudflared', 'cert.pem');
|
|
149
|
-
if (!fs.existsSync(cert)) throw fail(4021, this.notConfiguredMessage, { detail: this.notConfiguredDetail });
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
async #findTunnelByName(label) {
|
|
153
|
-
let raw;
|
|
154
|
-
try {
|
|
155
|
-
raw = await this.run(['tunnel', 'list', '--output', 'json']);
|
|
156
|
-
} catch {
|
|
157
|
-
return null; // 老版本不支持 --output;交给 create 的报错去说明
|
|
158
|
-
}
|
|
159
|
-
const start = raw.indexOf('[');
|
|
160
|
-
if (start < 0) return null;
|
|
161
|
-
const list = JSON.parse(raw.slice(start));
|
|
162
|
-
const hit = Array.isArray(list) ? list.find((t) => t && t.name === label && !t.deleted_at) : null;
|
|
163
|
-
return hit?.id ? { id: hit.id } : null;
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
async ensure({ port, force = false } = {}) {
|
|
167
|
-
if (!Number.isInteger(port) || port <= 0) throw fail(4400, '开通隧道需要有效端口');
|
|
168
|
-
const cached = this.state;
|
|
169
|
-
if (!force && cached?.hostname && cached.port === port) {
|
|
170
|
-
// 与 BaseProvisioner 同策略:没确认过就现场验一次(含防篡改评估)
|
|
171
|
-
if (cached.dnsOk !== true) {
|
|
172
|
-
const verdict = evaluateDnsAnswer(await this.probe(cached.hostname), cached.tunnelId);
|
|
173
|
-
const next = { ...cached, dnsOk: verdict.ok, dnsTampered: verdict.tampered, dnsCheckedAt: new Date().toISOString() };
|
|
174
|
-
this._state = next;
|
|
175
|
-
writeState(this.stateFile, next);
|
|
176
|
-
return {
|
|
177
|
-
hostname: next.hostname,
|
|
178
|
-
url: `https://${next.hostname}`,
|
|
179
|
-
tunnelId: next.tunnelId,
|
|
180
|
-
created: false,
|
|
181
|
-
changed: false,
|
|
182
|
-
dnsOk: next.dnsOk,
|
|
183
|
-
warning: dnsWarningFor(next),
|
|
184
|
-
};
|
|
185
|
-
}
|
|
186
|
-
return {
|
|
187
|
-
hostname: cached.hostname,
|
|
188
|
-
url: `https://${cached.hostname}`,
|
|
189
|
-
tunnelId: cached.tunnelId,
|
|
190
|
-
created: false,
|
|
191
|
-
changed: false,
|
|
192
|
-
dnsOk: cached.dnsOk ?? null,
|
|
193
|
-
warning: dnsWarningFor(cached),
|
|
194
|
-
};
|
|
195
|
-
}
|
|
196
|
-
await this.#assertLogin();
|
|
197
|
-
|
|
198
|
-
// 端口顺延:tunnel 与 DNS 都不用动,只重写本地 ingress 配置。
|
|
199
|
-
// 不走这一步就会为了换个端口重新 route dns(多余的一次 CF 写入)。
|
|
200
|
-
if (!force && cached?.tunnelId && cached.hostname && cached.credentialsFile) {
|
|
201
|
-
fs.mkdirSync(path.dirname(this.configFile), { recursive: true, mode: 0o700 });
|
|
202
|
-
fs.writeFileSync(this.configFile, renderConfig({
|
|
203
|
-
tunnelId: cached.tunnelId,
|
|
204
|
-
credentialsFile: cached.credentialsFile,
|
|
205
|
-
hostname: cached.hostname,
|
|
206
|
-
port,
|
|
207
|
-
}), { mode: 0o600 });
|
|
208
|
-
const next = { ...cached, port, updatedAt: new Date().toISOString() };
|
|
209
|
-
this._state = next;
|
|
210
|
-
writeState(this.stateFile, next);
|
|
211
|
-
return {
|
|
212
|
-
hostname: next.hostname,
|
|
213
|
-
url: `https://${next.hostname}`,
|
|
214
|
-
tunnelId: next.tunnelId,
|
|
215
|
-
created: false,
|
|
216
|
-
changed: false,
|
|
217
|
-
dnsOk: next.dnsOk ?? null,
|
|
218
|
-
warning: dnsWarningFor(next),
|
|
219
|
-
};
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
const installationId = cached?.installationId || crypto.randomBytes(16).toString('hex');
|
|
223
|
-
const label = cached?.subdomain || deriveSubdomain(this.seed || installationId, { prefix: this.prefix });
|
|
224
|
-
if (!isValidLabel(label)) throw fail(4400, `派生出的子域不合法:${label}`);
|
|
225
|
-
const hostname = `${label}.${this.baseDomain}`;
|
|
226
|
-
|
|
227
|
-
let tunnelId = cached?.tunnelId || null;
|
|
228
|
-
let created = false;
|
|
229
|
-
if (!tunnelId) {
|
|
230
|
-
const found = await this.#findTunnelByName(label);
|
|
231
|
-
if (found) {
|
|
232
|
-
tunnelId = found.id;
|
|
233
|
-
} else {
|
|
234
|
-
const out = await this.run(['tunnel', 'create', label]);
|
|
235
|
-
const m = UUID_PATTERN.exec(out);
|
|
236
|
-
if (!m) throw fail(4500, 'cloudflared 没有返回 tunnel id', { detail: String(out).slice(-300) });
|
|
237
|
-
tunnelId = m[1];
|
|
238
|
-
created = true;
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
const credentialsFile = path.join(this.homeDir, '.cloudflared', `${tunnelId}.json`);
|
|
243
|
-
if (!fs.existsSync(credentialsFile)) {
|
|
244
|
-
throw fail(4500, '找不到 tunnel 凭据文件', {
|
|
245
|
-
detail: `期望在 ${path.basename(credentialsFile)};重新执行 cloudflared tunnel create ${label}`,
|
|
246
|
-
});
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
// --overwrite-dns:重复开通时把记录改到当前 tunnel,而不是报「已存在」
|
|
250
|
-
try {
|
|
251
|
-
await this.run(['tunnel', 'route', 'dns', '--overwrite-dns', label, hostname]);
|
|
252
|
-
} catch (err) {
|
|
253
|
-
throw fail(4500, `写入 DNS 失败:${String(err.message).split('\n')[0]}`, {
|
|
254
|
-
detail: '确认 matrixboard.cn 在当前 Cloudflare 账号下,且登录时授权的就是它',
|
|
255
|
-
});
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
fs.mkdirSync(path.dirname(this.configFile), { recursive: true, mode: 0o700 });
|
|
259
|
-
fs.writeFileSync(this.configFile, renderConfig({ tunnelId, credentialsFile, hostname, port }), { mode: 0o600 });
|
|
260
|
-
try { fs.chmodSync(this.configFile, 0o600); } catch { /* 已 0600 */ }
|
|
261
|
-
|
|
262
|
-
const now = new Date().toISOString();
|
|
263
|
-
// 开通即自检:DNS 写成功 ≠ 公网能解析(pending zone 就是这么骗人的);
|
|
264
|
-
// CNAME 被改指到别的隧道同样不放行(防劫持评估见 dns-probe.evaluateDnsAnswer)
|
|
265
|
-
const verdict = evaluateDnsAnswer(await this.probe(hostname), tunnelId);
|
|
266
|
-
const warning = dnsWarningFor({ dnsOk: verdict.ok, dnsTampered: verdict.tampered });
|
|
267
|
-
if (verdict.tampered) {
|
|
268
|
-
this.log(`tunnel 警告 固定地址解析被改指 ${hostname} → ${verdict.target}(期望 ${verdict.expected}),拒绝下发该地址`);
|
|
269
|
-
} else if (verdict.ok) {
|
|
270
|
-
this.log(`tunnel 固定地址已可解析 ${hostname}(${verdict.kind} ${verdict.records.join(',')})`);
|
|
271
|
-
} else {
|
|
272
|
-
this.log(`tunnel 警告 固定地址写入成功但公网解析不到 ${hostname}`);
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
const next = {
|
|
276
|
-
...cached,
|
|
277
|
-
installationId,
|
|
278
|
-
subdomain: label,
|
|
279
|
-
hostname,
|
|
280
|
-
tunnelId,
|
|
281
|
-
credentialsFile,
|
|
282
|
-
configFile: this.configFile,
|
|
283
|
-
port,
|
|
284
|
-
dnsOk: verdict.ok,
|
|
285
|
-
dnsTampered: verdict.tampered,
|
|
286
|
-
dnsCheckedAt: now,
|
|
287
|
-
createdAt: cached?.createdAt ?? now,
|
|
288
|
-
updatedAt: now,
|
|
289
|
-
};
|
|
290
|
-
this._state = next;
|
|
291
|
-
writeState(this.stateFile, next);
|
|
292
|
-
this.log(`tunnel 固定地址就绪 ${hostname}(${created ? '新建' : '复用'},本地管理型)`);
|
|
293
|
-
return {
|
|
294
|
-
hostname,
|
|
295
|
-
url: `https://${hostname}`,
|
|
296
|
-
tunnelId,
|
|
297
|
-
created,
|
|
298
|
-
changed: Boolean(cached && cached.hostname !== hostname),
|
|
299
|
-
dnsOk: verdict.ok,
|
|
300
|
-
warning,
|
|
301
|
-
};
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
async credential({ port }) {
|
|
305
|
-
await this.ensure({ port });
|
|
306
|
-
if (!this.state?.configFile) throw fail(4500, '隧道配置缺失,请重新开通固定地址');
|
|
307
|
-
return { hostname: this.state.hostname, configFile: this.state.configFile };
|
|
308
|
-
}
|
|
309
|
-
}
|
|
1
|
+
// provision-local.mjs — 用 cloudflared 自己的证书开通固定地址(本地管理型隧道)
|
|
2
|
+
//
|
|
3
|
+
// 为什么要有这条路:zone 级 API Token 不是谁手边都有,也不该为了一次开通就建一个。
|
|
4
|
+
// `cloudflared tunnel login` 会在本机写一份 zone 范围的 cert.pem;之后 create / route dns
|
|
5
|
+
// 都用它完成,全程不需要我们接触 API Token。
|
|
6
|
+
//
|
|
7
|
+
// 与 token 形态(cloudflare.mjs)的差别只有一个:cloudflared 用 `--config` 指向本地
|
|
8
|
+
// ingress 配置 + credentials 文件,而不是 `TUNNEL_TOKEN` 环境变量。对外接口保持一致:
|
|
9
|
+
// ensure({ port }) → { hostname, url, tunnelId, created }
|
|
10
|
+
// credential({ port }) → { hostname, configFile }
|
|
11
|
+
//
|
|
12
|
+
// 安全边界:
|
|
13
|
+
// · cert.pem 属于 zone 级凭据,绝不复制、绝不外发;这里只检查它存在;
|
|
14
|
+
// · credentials 文件同理,只把**路径**写进配置,不读内容、不进日志;
|
|
15
|
+
// · 配置与状态文件都 0600。
|
|
16
|
+
|
|
17
|
+
import crypto from 'node:crypto';
|
|
18
|
+
import fs from 'node:fs';
|
|
19
|
+
import os from 'node:os';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { execFile as nodeExecFile } from 'node:child_process';
|
|
22
|
+
import { promisify } from 'node:util';
|
|
23
|
+
import { fail } from './protocol.mjs';
|
|
24
|
+
import { deriveSubdomain, isValidLabel } from './dns-label.mjs';
|
|
25
|
+
import { dnsWarningFor, evaluateDnsAnswer, probeDns } from './dns-probe.mjs';
|
|
26
|
+
|
|
27
|
+
const execFileAsync = promisify(nodeExecFile);
|
|
28
|
+
const CLI_TIMEOUT_MS = 45_000;
|
|
29
|
+
const STATE_VERSION = 1;
|
|
30
|
+
|
|
31
|
+
const UUID_PATTERN = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i;
|
|
32
|
+
|
|
33
|
+
function readState(file, log) {
|
|
34
|
+
if (!file) return null;
|
|
35
|
+
try {
|
|
36
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
37
|
+
if (!parsed || parsed.version !== STATE_VERSION) throw new Error('结构不符');
|
|
38
|
+
return parsed;
|
|
39
|
+
} catch (err) {
|
|
40
|
+
if (err.code !== 'ENOENT') log?.(`tunnel 本地开通状态不可用:${err.message}`);
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function writeState(file, state) {
|
|
46
|
+
if (!file) return;
|
|
47
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
48
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
49
|
+
fs.writeFileSync(tmp, JSON.stringify({ version: STATE_VERSION, ...state }, null, 2), { mode: 0o600, flag: 'w' });
|
|
50
|
+
fs.renameSync(tmp, file);
|
|
51
|
+
try { fs.chmodSync(file, 0o600); } catch { /* 刚写即 0600 */ }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** cloudflared 的 ingress 配置文件。ports/hostname 变一次就要重写一次。 */
|
|
55
|
+
export function renderConfig({ tunnelId, credentialsFile, hostname, port }) {
|
|
56
|
+
return [
|
|
57
|
+
`# generated by dsh-mobile — 端口变化会重写本文件;不要手改`,
|
|
58
|
+
`tunnel: ${tunnelId}`,
|
|
59
|
+
`credentials-file: ${credentialsFile}`,
|
|
60
|
+
'',
|
|
61
|
+
'ingress:',
|
|
62
|
+
` - hostname: ${hostname}`,
|
|
63
|
+
` service: http://127.0.0.1:${port}`,
|
|
64
|
+
' - service: http_status:404',
|
|
65
|
+
'',
|
|
66
|
+
].join('\n');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export class LocalProvisioner {
|
|
70
|
+
constructor({
|
|
71
|
+
baseDomain = 'matrixboard.cn',
|
|
72
|
+
prefix = 'dsh',
|
|
73
|
+
executable = 'cloudflared',
|
|
74
|
+
stateFile = null,
|
|
75
|
+
configFile = null,
|
|
76
|
+
seed = null,
|
|
77
|
+
homeDir = os.homedir(),
|
|
78
|
+
log = () => {},
|
|
79
|
+
run = null,
|
|
80
|
+
// 可注入:测试里不该真发 DNS 查询(会等 NXDOMAIN 重试,还依赖外网)
|
|
81
|
+
probe = null,
|
|
82
|
+
} = {}) {
|
|
83
|
+
this.baseDomain = String(baseDomain).replace(/^\./, '').toLowerCase();
|
|
84
|
+
this.prefix = prefix;
|
|
85
|
+
this.executable = executable;
|
|
86
|
+
this.stateFile = stateFile;
|
|
87
|
+
this.configFile = configFile || path.join(path.dirname(stateFile || path.join(homeDir, 'x')), 'tunnel-config.yml');
|
|
88
|
+
this.seed = seed;
|
|
89
|
+
this.homeDir = homeDir;
|
|
90
|
+
this.log = log;
|
|
91
|
+
this._state = undefined;
|
|
92
|
+
// 可注入,测试里不必真起 cloudflared
|
|
93
|
+
this.run = run || this.#exec;
|
|
94
|
+
this.probe = probe || probeDns;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
get kind() {
|
|
98
|
+
return 'local';
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
get state() {
|
|
102
|
+
if (this._state === undefined) this._state = readState(this.stateFile, this.log);
|
|
103
|
+
return this._state;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
get configured() {
|
|
107
|
+
// 本地形态只要证书在就算可开通;已开通则要配置与凭据都在
|
|
108
|
+
if (this.state?.configFile) return true;
|
|
109
|
+
return fs.existsSync(path.join(this.homeDir, '.cloudflared', 'cert.pem'));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
get notConfiguredMessage() {
|
|
113
|
+
return '主机还没有登录 Cloudflare';
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
get notConfiguredDetail() {
|
|
117
|
+
return `在这台电脑的终端执行:${this.executable} tunnel login(浏览器里选 matrixboard.cn 授权)`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
status() {
|
|
121
|
+
const s = this.state;
|
|
122
|
+
if (!s) return { kind: 'local', provisioned: false, hostname: null, url: null, tunnelId: null };
|
|
123
|
+
return {
|
|
124
|
+
kind: 'local',
|
|
125
|
+
provisioned: true,
|
|
126
|
+
hostname: s.hostname,
|
|
127
|
+
url: `https://${s.hostname}`,
|
|
128
|
+
tunnelId: s.tunnelId,
|
|
129
|
+
port: s.port ?? null,
|
|
130
|
+
// null = 还没验过(老状态文件);false = 验过但公网没有——面板必须提示,别让人扫码扫到空气
|
|
131
|
+
dnsOk: s.dnsOk ?? null,
|
|
132
|
+
warning: dnsWarningFor(s),
|
|
133
|
+
createdAt: s.createdAt ?? null,
|
|
134
|
+
updatedAt: s.updatedAt ?? null,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async #exec(args) {
|
|
139
|
+
const { stdout, stderr } = await execFileAsync(this.executable, args, {
|
|
140
|
+
timeout: CLI_TIMEOUT_MS,
|
|
141
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
142
|
+
env: process.env,
|
|
143
|
+
});
|
|
144
|
+
return `${stdout || ''}${stderr || ''}`;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async #assertLogin() {
|
|
148
|
+
const cert = path.join(this.homeDir, '.cloudflared', 'cert.pem');
|
|
149
|
+
if (!fs.existsSync(cert)) throw fail(4021, this.notConfiguredMessage, { detail: this.notConfiguredDetail });
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async #findTunnelByName(label) {
|
|
153
|
+
let raw;
|
|
154
|
+
try {
|
|
155
|
+
raw = await this.run(['tunnel', 'list', '--output', 'json']);
|
|
156
|
+
} catch {
|
|
157
|
+
return null; // 老版本不支持 --output;交给 create 的报错去说明
|
|
158
|
+
}
|
|
159
|
+
const start = raw.indexOf('[');
|
|
160
|
+
if (start < 0) return null;
|
|
161
|
+
const list = JSON.parse(raw.slice(start));
|
|
162
|
+
const hit = Array.isArray(list) ? list.find((t) => t && t.name === label && !t.deleted_at) : null;
|
|
163
|
+
return hit?.id ? { id: hit.id } : null;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async ensure({ port, force = false } = {}) {
|
|
167
|
+
if (!Number.isInteger(port) || port <= 0) throw fail(4400, '开通隧道需要有效端口');
|
|
168
|
+
const cached = this.state;
|
|
169
|
+
if (!force && cached?.hostname && cached.port === port) {
|
|
170
|
+
// 与 BaseProvisioner 同策略:没确认过就现场验一次(含防篡改评估)
|
|
171
|
+
if (cached.dnsOk !== true) {
|
|
172
|
+
const verdict = evaluateDnsAnswer(await this.probe(cached.hostname), cached.tunnelId);
|
|
173
|
+
const next = { ...cached, dnsOk: verdict.ok, dnsTampered: verdict.tampered, dnsCheckedAt: new Date().toISOString() };
|
|
174
|
+
this._state = next;
|
|
175
|
+
writeState(this.stateFile, next);
|
|
176
|
+
return {
|
|
177
|
+
hostname: next.hostname,
|
|
178
|
+
url: `https://${next.hostname}`,
|
|
179
|
+
tunnelId: next.tunnelId,
|
|
180
|
+
created: false,
|
|
181
|
+
changed: false,
|
|
182
|
+
dnsOk: next.dnsOk,
|
|
183
|
+
warning: dnsWarningFor(next),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
hostname: cached.hostname,
|
|
188
|
+
url: `https://${cached.hostname}`,
|
|
189
|
+
tunnelId: cached.tunnelId,
|
|
190
|
+
created: false,
|
|
191
|
+
changed: false,
|
|
192
|
+
dnsOk: cached.dnsOk ?? null,
|
|
193
|
+
warning: dnsWarningFor(cached),
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
await this.#assertLogin();
|
|
197
|
+
|
|
198
|
+
// 端口顺延:tunnel 与 DNS 都不用动,只重写本地 ingress 配置。
|
|
199
|
+
// 不走这一步就会为了换个端口重新 route dns(多余的一次 CF 写入)。
|
|
200
|
+
if (!force && cached?.tunnelId && cached.hostname && cached.credentialsFile) {
|
|
201
|
+
fs.mkdirSync(path.dirname(this.configFile), { recursive: true, mode: 0o700 });
|
|
202
|
+
fs.writeFileSync(this.configFile, renderConfig({
|
|
203
|
+
tunnelId: cached.tunnelId,
|
|
204
|
+
credentialsFile: cached.credentialsFile,
|
|
205
|
+
hostname: cached.hostname,
|
|
206
|
+
port,
|
|
207
|
+
}), { mode: 0o600 });
|
|
208
|
+
const next = { ...cached, port, updatedAt: new Date().toISOString() };
|
|
209
|
+
this._state = next;
|
|
210
|
+
writeState(this.stateFile, next);
|
|
211
|
+
return {
|
|
212
|
+
hostname: next.hostname,
|
|
213
|
+
url: `https://${next.hostname}`,
|
|
214
|
+
tunnelId: next.tunnelId,
|
|
215
|
+
created: false,
|
|
216
|
+
changed: false,
|
|
217
|
+
dnsOk: next.dnsOk ?? null,
|
|
218
|
+
warning: dnsWarningFor(next),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const installationId = cached?.installationId || crypto.randomBytes(16).toString('hex');
|
|
223
|
+
const label = cached?.subdomain || deriveSubdomain(this.seed || installationId, { prefix: this.prefix });
|
|
224
|
+
if (!isValidLabel(label)) throw fail(4400, `派生出的子域不合法:${label}`);
|
|
225
|
+
const hostname = `${label}.${this.baseDomain}`;
|
|
226
|
+
|
|
227
|
+
let tunnelId = cached?.tunnelId || null;
|
|
228
|
+
let created = false;
|
|
229
|
+
if (!tunnelId) {
|
|
230
|
+
const found = await this.#findTunnelByName(label);
|
|
231
|
+
if (found) {
|
|
232
|
+
tunnelId = found.id;
|
|
233
|
+
} else {
|
|
234
|
+
const out = await this.run(['tunnel', 'create', label]);
|
|
235
|
+
const m = UUID_PATTERN.exec(out);
|
|
236
|
+
if (!m) throw fail(4500, 'cloudflared 没有返回 tunnel id', { detail: String(out).slice(-300) });
|
|
237
|
+
tunnelId = m[1];
|
|
238
|
+
created = true;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const credentialsFile = path.join(this.homeDir, '.cloudflared', `${tunnelId}.json`);
|
|
243
|
+
if (!fs.existsSync(credentialsFile)) {
|
|
244
|
+
throw fail(4500, '找不到 tunnel 凭据文件', {
|
|
245
|
+
detail: `期望在 ${path.basename(credentialsFile)};重新执行 cloudflared tunnel create ${label}`,
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// --overwrite-dns:重复开通时把记录改到当前 tunnel,而不是报「已存在」
|
|
250
|
+
try {
|
|
251
|
+
await this.run(['tunnel', 'route', 'dns', '--overwrite-dns', label, hostname]);
|
|
252
|
+
} catch (err) {
|
|
253
|
+
throw fail(4500, `写入 DNS 失败:${String(err.message).split('\n')[0]}`, {
|
|
254
|
+
detail: '确认 matrixboard.cn 在当前 Cloudflare 账号下,且登录时授权的就是它',
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
fs.mkdirSync(path.dirname(this.configFile), { recursive: true, mode: 0o700 });
|
|
259
|
+
fs.writeFileSync(this.configFile, renderConfig({ tunnelId, credentialsFile, hostname, port }), { mode: 0o600 });
|
|
260
|
+
try { fs.chmodSync(this.configFile, 0o600); } catch { /* 已 0600 */ }
|
|
261
|
+
|
|
262
|
+
const now = new Date().toISOString();
|
|
263
|
+
// 开通即自检:DNS 写成功 ≠ 公网能解析(pending zone 就是这么骗人的);
|
|
264
|
+
// CNAME 被改指到别的隧道同样不放行(防劫持评估见 dns-probe.evaluateDnsAnswer)
|
|
265
|
+
const verdict = evaluateDnsAnswer(await this.probe(hostname), tunnelId);
|
|
266
|
+
const warning = dnsWarningFor({ dnsOk: verdict.ok, dnsTampered: verdict.tampered });
|
|
267
|
+
if (verdict.tampered) {
|
|
268
|
+
this.log(`tunnel 警告 固定地址解析被改指 ${hostname} → ${verdict.target}(期望 ${verdict.expected}),拒绝下发该地址`);
|
|
269
|
+
} else if (verdict.ok) {
|
|
270
|
+
this.log(`tunnel 固定地址已可解析 ${hostname}(${verdict.kind} ${verdict.records.join(',')})`);
|
|
271
|
+
} else {
|
|
272
|
+
this.log(`tunnel 警告 固定地址写入成功但公网解析不到 ${hostname}`);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const next = {
|
|
276
|
+
...cached,
|
|
277
|
+
installationId,
|
|
278
|
+
subdomain: label,
|
|
279
|
+
hostname,
|
|
280
|
+
tunnelId,
|
|
281
|
+
credentialsFile,
|
|
282
|
+
configFile: this.configFile,
|
|
283
|
+
port,
|
|
284
|
+
dnsOk: verdict.ok,
|
|
285
|
+
dnsTampered: verdict.tampered,
|
|
286
|
+
dnsCheckedAt: now,
|
|
287
|
+
createdAt: cached?.createdAt ?? now,
|
|
288
|
+
updatedAt: now,
|
|
289
|
+
};
|
|
290
|
+
this._state = next;
|
|
291
|
+
writeState(this.stateFile, next);
|
|
292
|
+
this.log(`tunnel 固定地址就绪 ${hostname}(${created ? '新建' : '复用'},本地管理型)`);
|
|
293
|
+
return {
|
|
294
|
+
hostname,
|
|
295
|
+
url: `https://${hostname}`,
|
|
296
|
+
tunnelId,
|
|
297
|
+
created,
|
|
298
|
+
changed: Boolean(cached && cached.hostname !== hostname),
|
|
299
|
+
dnsOk: verdict.ok,
|
|
300
|
+
warning,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async credential({ port }) {
|
|
305
|
+
await this.ensure({ port });
|
|
306
|
+
if (!this.state?.configFile) throw fail(4500, '隧道配置缺失,请重新开通固定地址');
|
|
307
|
+
return { hostname: this.state.hostname, configFile: this.state.configFile };
|
|
308
|
+
}
|
|
309
|
+
}
|