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.
@@ -1,698 +1,735 @@
1
- // cloudflare.mjs — Pro 固定地址:一个 tunnel + 一个子域 + 一份 token 的自动开通
2
- //
3
- // 三种凭证必须先分清,否则一定会把 zone 权限塞进客户端:
4
- // · Zone API Token:能建/删整个 matrixboard.cn 的 DNS。**只能待在运营方**,
5
- // 一旦随桌面端分发,任何用户都能把域名迁走。
6
- // · Tunnel Token:只对单个 tunnel 有效的 JWT,给 cloudflared 用,可在主机落盘。
7
- // · 子域名:由安装标识派生,稳定、不可猜、可回收。
8
- //
9
- // 因此这里提供两条同构路径,REST 层与 UI 不需要知道背后是谁:
10
- // CloudflareProvisioner —— 自托管 / 运营调试:主机侧直连 CF API(需 zone token)
11
- // HostedProvisioner —— 产品形态:主机拿 enroll 凭证向开通服务换三件套
12
- //
13
- // 共同语义(不可放松):
14
- // 1. 幂等:重复 ensure 不重建 tunnel、不重复写 DNS;
15
- // 2. token 只落盘 0600,永不出现在 status()/日志/诊断包里;
16
- // 3. 端口变了要重写 ingress(端口会因占用顺延,写死会指向空气);
17
- // 4. 失败要能定位:CF 的错误码原样带上,但不带 token。
18
-
19
- import crypto from 'node:crypto';
20
- import fs from 'node:fs';
21
- import path from 'node:path';
22
- import { fail } from './protocol.mjs';
23
- import { deriveSubdomain, isValidLabel } from './dns-label.mjs';
24
- import { DNS_PENDING_HINT, DNS_TAMPER_HINT, dnsWarningFor, evaluateDnsAnswer, probeDns } from './dns-probe.mjs';
25
- import { LocalProvisioner, sanitizeZone } from './provision-local.mjs';
26
- import { diagnoseZone, findDnsOwner, ZONE_STATUS_HINT } from './zone-health.mjs';
27
-
28
- // 兼容既有调用方与测试:子域规则从 dns-label.mjs 来,这里一并导出
29
- export { deriveSubdomain, isValidLabel };
30
-
31
- export const CF_API_BASE = 'https://api.cloudflare.com/client/v4';
32
- const STATE_VERSION = 1;
33
-
34
- function loadState(file, log) {
35
- if (!file) return null;
36
- let raw;
37
- try {
38
- raw = fs.readFileSync(file, 'utf8');
39
- } catch (err) {
40
- if (err.code === 'ENOENT') return null;
41
- throw err;
42
- }
43
- try {
44
- const parsed = JSON.parse(raw);
45
- if (!parsed || parsed.version !== STATE_VERSION) throw new Error('结构不符');
46
- if (!parsed.hostname || !parsed.tunnelId) throw new Error('缺少 hostname/tunnelId');
47
- return parsed;
48
- } catch (err) {
49
- // 与设备注册表同一取舍:插件跑在宿主进程内,坏文件不该带崩宿主。
50
- const backup = `${file}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`;
51
- try {
52
- fs.renameSync(file, backup);
53
- log?.(`tunnel 开通状态损坏,已备份到 ${path.basename(backup)}(${err.message})`);
54
- } catch {
55
- log?.(`tunnel 开通状态损坏且备份失败(${err.message})`);
56
- }
57
- return null;
58
- }
59
- }
60
-
61
- function saveState(file, state) {
62
- if (!file) return;
63
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
64
- const tmp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
65
- const payload = JSON.stringify({ version: STATE_VERSION, ...state }, null, 2);
66
- try {
67
- fs.writeFileSync(tmp, payload, { mode: 0o600, flag: 'wx' });
68
- fs.renameSync(tmp, file);
69
- try { fs.chmodSync(file, 0o600); } catch { /* 刚写即 0600 */ }
70
- } finally {
71
- try { fs.unlinkSync(tmp); } catch { /* rename 成功时已不存在 */ }
72
- }
73
- }
74
-
75
- class BaseProvisioner {
76
- constructor({ stateFile = null, log = () => {}, baseDomain = 'matrixboard.cn', probe = null, zoneDiagnose = null } = {}) {
77
- this.stateFile = stateFile;
78
- this.log = log;
79
- this.baseDomain = String(baseDomain).replace(/^\./, '').toLowerCase();
80
- this._state = undefined; // undefined=未读;null=没有
81
- // 可注入:测试里不该真发 DNS 查询(依赖外网且要等重试)
82
- this.probe = probe || probeDns;
83
- // 解析失败时进一步归因(moved / pending / ns-mismatch);不注入就只报「解析不到」
84
- this.zoneDiagnose = zoneDiagnose;
85
- this._zone = null;
86
- }
87
-
88
- /**
89
- * 复核固定域名的公网解析,结论写回状态。
90
- *
91
- * 只做一次就够:确认可解析后 `dnsOk=true` 会被持久化,后续启动不再查;
92
- * 没确认过(null,例如老状态文件)或上次失败(false)才复查——
93
- * 否则「域名不可用」会因为状态文件存在而被永久固化,NS 改好了也发现不了。
94
- */
95
- async verifyDns(hostname = this.state?.hostname) {
96
- if (!hostname) return { ok: false, kind: null, records: [] };
97
- const check = await this.probe(hostname);
98
- const current = this.state;
99
- // 防劫持:CNAME 必须仍指向**本机**隧道(评估逻辑在 dns-probe.evaluateDnsAnswer)。
100
- // 记录若被人改指到别的隧道/服务器,解析照样「成功」,流量却会落到对方 ingress——
101
- // 这时按「地址不可用」处理,绝不下发。
102
- const verdict = evaluateDnsAnswer(check, current?.tunnelId);
103
- // 解析不到时再问一句「这域名现在归谁」:moved(被别的账号接管)与 pending(NS 还没指过来)
104
- // 的修法完全不同,笼统一句「等 NS 生效」会让人白等。
105
- let zone = null;
106
- if (!verdict.ok && typeof this.zoneDiagnose === 'function') {
107
- try {
108
- zone = sanitizeZone(await this.zoneDiagnose({ baseDomain: this.baseDomain, dnsOk: false }));
109
- } catch {
110
- zone = null;
111
- }
112
- this._zone = zone;
113
- }
114
- if (current && current.hostname === hostname) {
115
- this.#persist({
116
- ...current,
117
- dnsOk: verdict.ok,
118
- dnsTampered: verdict.tampered,
119
- dnsCheckedAt: new Date().toISOString(),
120
- zone,
121
- });
122
- }
123
- if (verdict.tampered) {
124
- this.log(`tunnel 警告 固定地址解析被改指 ${hostname} → ${verdict.target}(期望 ${verdict.expected}),拒绝下发该地址`);
125
- } else if (verdict.ok) {
126
- this.log(`tunnel 固定地址已可解析 ${hostname}(${verdict.kind} ${verdict.records.join(',')})`);
127
- } else {
128
- this.log(`tunnel 警告 固定地址公网解析不到 ${hostname}`);
129
- }
130
- return verdict;
131
- }
132
-
133
- /**
134
- * 面板「重新检测解析」:强制重探一次并写回状态,不做缓存短路。
135
- * 与 LocalProvisioner.recheckDns 同一契约,面板对两种开通形态一视同仁。
136
- */
137
- async recheckDns() {
138
- const s = this.state;
139
- if (!s?.hostname) return { provisioned: false, ok: false, tampered: false, warning: null, zone: null };
140
- const verdict = await this.verifyDns(s.hostname);
141
- const now = this.state;
142
- return {
143
- provisioned: true,
144
- hostname: now.hostname,
145
- ok: Boolean(verdict.ok),
146
- tampered: Boolean(verdict.tampered),
147
- expected: verdict.expected ?? null,
148
- target: verdict.target ?? null,
149
- warning: dnsWarningFor(now),
150
- checkedAt: now.dnsCheckedAt ?? null,
151
- zone: now.zone ?? this._zone ?? null,
152
- };
153
- }
154
-
155
- /** 状态文件里的缓存(读一次后常驻;写穿时同步更新)。 */
156
- get state() {
157
- if (this._state === undefined) this._state = loadState(this.stateFile, this.log);
158
- return this._state;
159
- }
160
-
161
- #persist(next) {
162
- this._state = next;
163
- try {
164
- saveState(this.stateFile, next);
165
- } catch (err) {
166
- // 落盘失败不该阻断本次开通(重启后重开会再换一份 token,仍是幂等的)
167
- this.log(`tunnel 开通状态写入失败(本次仍可用):${err.message}`);
168
- }
169
- return next;
170
- }
171
-
172
- get url() {
173
- return this.state ? `https://${this.state.hostname}` : null;
174
- }
175
-
176
- /** 对外可播报的信息:绝不含 token。 */
177
- status() {
178
- const s = this.state;
179
- if (!s) return { kind: this.kind, provisioned: false, hostname: null, url: null, tunnelId: null };
180
- return {
181
- kind: this.kind,
182
- provisioned: true,
183
- hostname: s.hostname,
184
- url: `https://${s.hostname}`,
185
- tunnelId: s.tunnelId,
186
- port: s.port ?? null,
187
- // null = 还没验过;true/false = 验过且结论明确
188
- dnsOk: s.dnsOk ?? null,
189
- dnsCheckedAt: s.dnsCheckedAt ?? null,
190
- zone: s.zone ?? this._zone ?? null,
191
- warning: dnsWarningFor(s),
192
- createdAt: s.createdAt ?? null,
193
- updatedAt: s.updatedAt ?? null,
194
- };
195
- }
196
-
197
- /**
198
- * 开通/复用固定地址。返回 `{ hostname, url, tunnelId, created, changed }`。
199
- *
200
- * `port` 一定要传当前监听端口:端口被占用时网关会顺延,ingress 写死旧端口
201
- * 会让公网地址 502,而用户完全看不出原因。
202
- */
203
- async ensure({ port, force = false } = {}) {
204
- if (!this.configured) throw fail(4021, this.notConfiguredMessage, { detail: this.notConfiguredDetail });
205
- if (!Number.isInteger(port) || port <= 0) throw fail(4400, '开通隧道需要有效端口');
206
-
207
- const cached = this.state;
208
- if (!force && cached && cached.port === port) {
209
- // 已确认可解析就不再查;否则现场验一次,避免把「未生效」固化在状态里
210
- if (cached.dnsOk !== true) await this.verifyDns(cached.hostname);
211
- const s = this.state;
212
- return {
213
- hostname: s.hostname,
214
- url: `https://${s.hostname}`,
215
- tunnelId: s.tunnelId,
216
- created: false,
217
- changed: false,
218
- dnsOk: s.dnsOk ?? null,
219
- warning: dnsWarningFor(s),
220
- };
221
- }
222
-
223
- const fresh = await this.provision({ port, cached });
224
- const now = new Date().toISOString();
225
- const next = this.#persist({
226
- ...cached,
227
- ...fresh,
228
- port,
229
- createdAt: cached?.createdAt ?? now,
230
- updatedAt: now,
231
- });
232
- this.log(`tunnel 固定地址就绪 ${next.hostname}(${fresh.created ? '新建' : '复用'})`);
233
- // 开通即自检:写成功 ≠ 公网能解析
234
- if (next.dnsOk !== true) await this.verifyDns(next.hostname);
235
- const done = this.state;
236
- return {
237
- hostname: done.hostname,
238
- url: `https://${done.hostname}`,
239
- tunnelId: done.tunnelId,
240
- created: Boolean(fresh.created),
241
- changed: Boolean(cached && cached.hostname !== next.hostname),
242
- dnsOk: done.dnsOk ?? null,
243
- warning: dnsWarningFor(done),
244
- };
245
- }
246
-
247
- /**
248
- * 取 cloudflared 要用的 `{ hostname, token }`。**仅供网关进程内部调用**,
249
- * REST 层不得把它序列化出去。
250
- */
251
- async credential({ port }) {
252
- await this.ensure({ port });
253
- if (!this.state?.token) throw fail(4500, '隧道 token 缺失,请重新开通固定地址');
254
- return { hostname: this.state.hostname, token: this.state.token };
255
- }
256
-
257
- /** 主机侧要用的一次性凭证/配置是否齐备。 */
258
- get configured() {
259
- return false;
260
- }
261
-
262
- get notConfiguredMessage() {
263
- return '主机未配置隧道开通凭据';
264
- }
265
-
266
- get notConfiguredDetail() {
267
- return null;
268
- }
269
- }
270
-
271
- /**
272
- * 直连 Cloudflare API 的开通器(运营/自托管)。
273
- *
274
- * 需要的权限(最小集):
275
- * · Account → Cloudflare Tunnel: Edit
276
- * · Zone(matrixboard.cn) → DNS: Edit
277
- * · Zone(matrixboard.cn) → Zone: Read(用于把域名解析成 zoneId)
278
- */
279
- export class CloudflareProvisioner extends BaseProvisioner {
280
- constructor({
281
- apiToken = null,
282
- accountId = null,
283
- zoneId = null,
284
- baseDomain = 'matrixboard.cn',
285
- prefix = 'dsh',
286
- stateFile = null,
287
- seed = null,
288
- fetchImpl = globalThis.fetch,
289
- apiBase = CF_API_BASE,
290
- log = () => {},
291
- probe = null,
292
- zoneDiagnose = null,
293
- } = {}) {
294
- super({ stateFile, log, baseDomain, probe, zoneDiagnose });
295
- this.apiToken = apiToken;
296
- this.accountId = accountId;
297
- this.zoneId = zoneId;
298
- this.prefix = prefix;
299
- this.seed = seed;
300
- this.fetchImpl = fetchImpl;
301
- this.apiBase = String(apiBase).replace(/\/$/, '');
302
- // API 形态本身就有 zone 级凭据,不必借 cert.pem:解析失败时直接问清 zone 现状
303
- this.zoneDiagnose = zoneDiagnose || ((args = {}) => diagnoseZone({
304
- ...args,
305
- apiToken: this.apiToken,
306
- zoneId: this.zoneId,
307
- baseDomain: args.baseDomain || this.baseDomain,
308
- fetchImpl: this.fetchImpl,
309
- apiBase: this.apiBase,
310
- }));
311
- }
312
-
313
- get kind() {
314
- return 'cloudflare';
315
- }
316
-
317
- get configured() {
318
- // accountId 不强制:一个 Token 往往只属于一个账号,让 API 自己说到底是谁,
319
- // 比要求用户去面板抄一串 32 位十六进制更不容易出错。
320
- return Boolean(this.apiToken && this.baseDomain && typeof this.fetchImpl === 'function');
321
- }
322
-
323
- get notConfiguredMessage() {
324
- return '主机未配置 Cloudflare 凭据,无法开通固定地址';
325
- }
326
-
327
- get notConfiguredDetail() {
328
- return '需要一个带 Account → Cloudflare Tunnel: Edit、Zone → DNS: Edit/Zone: Read 的 API Token;'
329
- + '也可改用 hosted 开通服务(见 config.tunnel.provisioner)';
330
- }
331
-
332
- async #api(method, pathname, body) {
333
- let res;
334
- try {
335
- res = await this.fetchImpl(`${this.apiBase}${pathname}`, {
336
- method,
337
- headers: {
338
- Authorization: `Bearer ${this.apiToken}`,
339
- 'Content-Type': 'application/json',
340
- },
341
- body: body === undefined ? undefined : JSON.stringify(body),
342
- });
343
- } catch (err) {
344
- throw fail(4500, `无法连接 Cloudflare API:${err.message}`);
345
- }
346
- const text = await res.text();
347
- let payload = null;
348
- try {
349
- payload = text ? JSON.parse(text) : null;
350
- } catch {
351
- throw fail(4500, `Cloudflare API 返回了非 JSON 响应(HTTP ${res.status})`);
352
- }
353
- if (!payload || payload.success !== true) {
354
- const first = payload?.errors?.[0];
355
- // 只透出 CF 自己的话,不带 Authorization
356
- throw fail(4500, `Cloudflare 拒绝了请求:${first?.message || `HTTP ${res.status}`}`, {
357
- status: res.status,
358
- cfCode: first?.code ?? null,
359
- });
360
- }
361
- return payload.result;
362
- }
363
-
364
- /**
365
- * 确定 accountId。Token 能看见几个账号就用几个:
366
- * 恰好一个 → 直接用它(绝大多数情况);多个 → 必须显式指定,否则可能开到别人的账号里。
367
- */
368
- async #ensureAccount() {
369
- if (this.accountId) return this.accountId;
370
- const raw = await this.#api('GET', '/accounts');
371
- const list = (Array.isArray(raw) ? raw : []).filter((a) => a && a.id);
372
- if (list.length === 1) {
373
- this.accountId = list[0].id;
374
- this.log?.(`tunnel 账号自动识别为 ${list[0].name || list[0].id}`);
375
- return this.accountId;
376
- }
377
- if (!list.length) {
378
- throw fail(4021, 'API Token 看不到任何 Cloudflare 账号', {
379
- detail: 'Token 需要 Account → Cloudflare Tunnel: Edit 权限',
380
- });
381
- }
382
- throw fail(4021, 'API Token 可见多个 Cloudflare 账号,请显式指定 accountId', {
383
- detail: list.map((a) => a.name || a.id).join(' / '),
384
- });
385
- }
386
-
387
- async #ensureZone() {
388
- if (this.zoneId) return this.zoneId;
389
- const zones = await this.#api('GET', `/zones?name=${encodeURIComponent(this.baseDomain)}`);
390
- const zone = Array.isArray(zones) ? zones.find((z) => z.name === this.baseDomain) : null;
391
- if (!zone) {
392
- throw fail(4021, `Cloudflare 账号里找不到域名 ${this.baseDomain}`, {
393
- detail: '确认该域名已接入当前账号;若用子账号,API Token 需要能看到这个 zone',
394
- });
395
- }
396
- if (zone.status && zone.status !== 'active') {
397
- // 状态不同,修法完全不同:moved 说明域名已被另一个 Cloudflare 账号接管,
398
- // 在本账号重试一万次也不会生效;pending 只是 NS 还没指过来。
399
- const hint = ZONE_STATUS_HINT[zone.status] || `状态 ${zone.status}`;
400
- const ns = (zone.name_servers || []).join(' / ') || '(当前账号未分配)';
401
- throw fail(4021, `域名 ${this.baseDomain} 未生效:${hint}`, {
402
- detail: zone.status === 'moved'
403
- ? `本账号分配的公网 NS 是 ${ns}。域名现在被另一个 Cloudflare 账号接管,本账号写入的记录不会下发——`
404
- + '要么在注册商把 NS 改回这一对,要么统一只用同一个 Cloudflare 账号登录(两边互斥,只能二选一)。'
405
- : `本账号分配的公网 NS 是 ${ns};到域名注册商把 NS 改成这一对,生效后再开通。`,
406
- zoneStatus: zone.status,
407
- expectedNs: zone.name_servers || [],
408
- });
409
- }
410
- this.zoneId = zone.id;
411
- this._zone = zone; // 供 requiredNameservers() 复用,避免为了一句提示再查一次
412
- return zone.id;
413
- }
414
-
415
- /**
416
- * 这个 zone 要求域名指向的 NS。用于「名称服务器无效」时的可执行提示:
417
- * 用户拿到这两个名字去注册商改,比让他理解 pending zone 的概念有效得多。
418
- */
419
- async requiredNameservers() {
420
- if (this._zone?.name_servers?.length) return this._zone.name_servers;
421
- try {
422
- const zones = await this.#api('GET', `/zones?name=${encodeURIComponent(this.baseDomain)}`);
423
- const zone = (Array.isArray(zones) ? zones : []).find((z) => z.name === this.baseDomain);
424
- if (zone) {
425
- this._zone = zone;
426
- return zone.name_servers || [];
427
- }
428
- } catch {
429
- /* 权限不足时只是少一句提示,不该让开通失败 */
430
- }
431
- return [];
432
- }
433
-
434
- async #ensureTunnel(name) {
435
- const list = await this.#api(
436
- 'GET',
437
- `/accounts/${this.accountId}/cfd_tunnel?name=${encodeURIComponent(name)}&is_deleted=false`,
438
- );
439
- // REST 这边未删除给的是 null,与 CLI 的 "0001-01-01T00:00:00Z" 不同;
440
- // 两种都按「没删」处理,免得两条开通路径对同一条隧道得出相反结论。
441
- const hit = (Array.isArray(list) ? list : []).find((t) => t && t.name === name
442
- && (!t.deleted_at || String(t.deleted_at).startsWith('0001-01-01')));
443
- if (hit) {
444
- // 本地管理型 tunnel 不接受远端 ingress 下发,拿 token 跑起来会没有路由。
445
- if (hit.remote_config === false) {
446
- throw fail(4021, `已存在同名本地管理隧道 ${name}`, {
447
- detail: '在 Cloudflare 面板删掉它,或换一个开通前缀;本方案只用 remotely-managed tunnel',
448
- });
449
- }
450
- return { id: hit.id, created: false };
451
- }
452
- const created = await this.#api('POST', `/accounts/${this.accountId}/cfd_tunnel`, {
453
- name,
454
- config_src: 'cloudflare',
455
- });
456
- return { id: created.id, created: true };
457
- }
458
-
459
- async #putIngress(tunnelId, hostname, port) {
460
- await this.#api('PUT', `/accounts/${this.accountId}/cfd_tunnel/${tunnelId}/configurations`, {
461
- config: {
462
- ingress: [
463
- { hostname, service: `http://127.0.0.1:${port}` },
464
- // 兜底规则是 CF 的硬要求:最后一条必须无 hostname,否则保存被拒。
465
- { service: 'http_status:404' },
466
- ],
467
- },
468
- });
469
- }
470
-
471
- async #upsertDns(zoneId, fqdn, tunnelId) {
472
- const target = `${tunnelId}.cfdargotunnel.com`;
473
- const list = await this.#api(
474
- 'GET',
475
- `/zones/${zoneId}/dns_records?type=CNAME&name=${encodeURIComponent(fqdn)}`,
476
- );
477
- const existing = (Array.isArray(list) ? list : [])[0];
478
- const record = { type: 'CNAME', name: fqdn, content: target, proxied: true, ttl: 1 };
479
- if (existing) {
480
- if (String(existing.content || '').toLowerCase() === target) return { created: false };
481
- await this.#api('PUT', `/zones/${zoneId}/dns_records/${existing.id}`, record);
482
- return { created: false, updated: true };
483
- }
484
- await this.#api('POST', `/zones/${zoneId}/dns_records`, { ...record, comment: 'dsh-mobile pro tunnel' });
485
- return { created: true };
486
- }
487
-
488
- async provision({ port, cached }) {
489
- const installationId = cached?.installationId || crypto.randomBytes(16).toString('hex');
490
- await this.#ensureAccount();
491
- const zoneId = await this.#ensureZone();
492
- const label = cached?.subdomain || deriveSubdomain(this.seed || installationId, { prefix: this.prefix });
493
- const hostname = `${label}.${this.baseDomain}`;
494
- const tunnel = await this.#ensureTunnel(label);
495
- // token 只在第一次(或状态文件丢失)时取;CF 侧 token 不会因为重启而变。
496
- let token = cached?.token;
497
- if (!token || cached.tunnelId !== tunnel.id) {
498
- token = await this.#api('GET', `/accounts/${this.accountId}/cfd_tunnel/${tunnel.id}/token`);
499
- }
500
- await this.#putIngress(tunnel.id, hostname, port);
501
- await this.#upsertDns(zoneId, hostname, tunnel.id);
502
- return {
503
- installationId,
504
- subdomain: label,
505
- hostname,
506
- tunnelId: tunnel.id,
507
- token,
508
- created: tunnel.created,
509
- };
510
- }
511
- }
512
-
513
- /**
514
- * 通过开通服务换三件套(产品形态)。
515
- *
516
- * 合约(服务端实现同样语义即可):
517
- * POST {endpoint}/v1/tunnel
518
- * Authorization: Bearer <enroll token>
519
- * { "hostId": "...", "port": 3081, "subdomain": "dsh-xxxx"|null }
520
- * → { "hostname": "dsh-xxxx.matrixboard.cn", "tunnelId": "...", "token": "eyJ..." }
521
- *
522
- * 主机侧只保存 enroll 凭证与换回来的 tunnel token,永远看不到 zone 级权限。
523
- */
524
- export class HostedProvisioner extends BaseProvisioner {
525
- constructor({
526
- endpoint = null,
527
- enrollToken = null,
528
- hostId = null,
529
- baseDomain = 'matrixboard.cn',
530
- stateFile = null,
531
- fetchImpl = globalThis.fetch,
532
- log = () => {},
533
- probe = null,
534
- } = {}) {
535
- super({ stateFile, log, baseDomain, probe });
536
- this.endpoint = endpoint ? String(endpoint).replace(/\/$/, '') : null;
537
- this.enrollToken = enrollToken;
538
- this.hostId = hostId;
539
- this.fetchImpl = fetchImpl;
540
- }
541
-
542
- get kind() {
543
- return 'hosted';
544
- }
545
-
546
- get configured() {
547
- return Boolean(this.endpoint && this.enrollToken && typeof this.fetchImpl === 'function');
548
- }
549
-
550
- get notConfiguredMessage() {
551
- return '主机未加入固定地址开通服务';
552
- }
553
-
554
- get notConfiguredDetail() {
555
- return '需要 config.tunnel.endpoint 与 enrollToken(Pro 订阅后由账号体系下发)';
556
- }
557
-
558
- async provision({ port, cached }) {
559
- let res;
560
- try {
561
- res = await this.fetchImpl(`${this.endpoint}/v1/tunnel`, {
562
- method: 'POST',
563
- headers: {
564
- Authorization: `Bearer ${this.enrollToken}`,
565
- 'Content-Type': 'application/json',
566
- },
567
- body: JSON.stringify({
568
- hostId: this.hostId,
569
- port,
570
- subdomain: cached?.subdomain ?? null,
571
- }),
572
- });
573
- } catch (err) {
574
- throw fail(4500, `无法连接固定地址开通服务:${err.message}`);
575
- }
576
- const text = await res.text();
577
- let body = null;
578
- try {
579
- body = text ? JSON.parse(text) : null;
580
- } catch {
581
- throw fail(4500, `开通服务返回了非 JSON 响应(HTTP ${res.status})`);
582
- }
583
- if (!res.ok || !body) {
584
- throw fail(4500, `开通服务拒绝了请求:${body?.message || body?.error?.message || `HTTP ${res.status}`}`, {
585
- status: res.status,
586
- });
587
- }
588
- const hostname = String(body.hostname || '').toLowerCase();
589
- // 服务端被攻陷时也不能把用户手机引到别的域名去。
590
- if (!hostname.endsWith(`.${this.baseDomain}`)) {
591
- throw fail(4500, `开通服务返回的域名不在 ${this.baseDomain} 下,已拒绝`);
592
- }
593
- if (!body.tunnelId || !body.token) throw fail(4500, '开通服务返回内容不完整(缺 tunnelId/token)');
594
- return {
595
- installationId: cached?.installationId || crypto.randomBytes(16).toString('hex'),
596
- subdomain: hostname.slice(0, -(this.baseDomain.length + 1)),
597
- hostname,
598
- tunnelId: String(body.tunnelId),
599
- token: String(body.token),
600
- created: true,
601
- };
602
- }
603
- }
604
-
605
- /**
606
- * 只读现有开通状态(kind=state)。
607
- *
608
- * 用途:**已经开通过的机器日常启动**。此时主机不该再持有 zone 级凭据——
609
- * token 与固定域名在 0600 状态文件里就够了,cloudflared 也只认 token。
610
- * 这也正是产品形态:开通是一次性的服务端动作,之后本机离线也能起隧道。
611
- *
612
- * 唯一代价:端口顺延后无法自行改写 CF 侧 ingress(那需要 API 凭据)。
613
- * 这种情况必须**如实报错**,而不是让公网地址 502 给用户一个「连上了但没数据」。
614
- */
615
- export class StateProvisioner extends BaseProvisioner {
616
- constructor({ stateFile = null, baseDomain = 'matrixboard.cn', log = () => {}, probe = null } = {}) {
617
- super({ stateFile, log, baseDomain, probe });
618
- }
619
-
620
- get kind() {
621
- return 'state';
622
- }
623
-
624
- get configured() {
625
- return Boolean(this.state?.hostname && this.state?.token);
626
- }
627
-
628
- get notConfiguredMessage() {
629
- return '这台主机还没有开通固定地址';
630
- }
631
-
632
- get notConfiguredDetail() {
633
- return '先配置 Cloudflare 凭据或开通服务跑一次开通;之后日常启动只需状态文件';
634
- }
635
-
636
- async provision({ port, cached }) {
637
- if (!cached?.token || !cached?.hostname) throw fail(4021, this.notConfiguredMessage);
638
- if (cached.port && port && cached.port !== port) {
639
- throw fail(4021, `固定地址目前指向端口 ${cached.port},当前监听 ${port}`, {
640
- detail: '端口变化需要带上 Cloudflare 凭据重新开通一次(改写 ingress),否则公网地址会 502',
641
- });
642
- }
643
- return { ...cached, created: false };
644
- }
645
- }
646
-
647
- /** 按配置挑一个开通器;都不满足时返回 null(隧道退化成 Quick Tunnel)。 */
648
- export function createProvisioner(config = {}, { log = () => {}, stateFile = null, hostId = null } = {}) {
649
- // 没显式指定时按凭据推断:有开通服务地址就走 hosted,否则直连 CF。
650
- // 硬性默认 cloudflare 会让「只配了 endpoint」的主机静默退回 Quick Tunnel。
651
- const kind = String(config.provisioner || (config.endpoint ? 'hosted' : 'cloudflare')).toLowerCase();
652
- if (kind === 'cloudflare') {
653
- const provisioner = new CloudflareProvisioner({
654
- apiToken: config.apiToken || null,
655
- accountId: config.accountId || null,
656
- zoneId: config.zoneId || null,
657
- baseDomain: config.baseDomain || 'matrixboard.cn',
658
- prefix: config.prefix || 'dsh',
659
- seed: config.seed || null,
660
- stateFile,
661
- log,
662
- });
663
- return provisioner.configured ? provisioner : null;
664
- }
665
- if (kind === 'local') {
666
- return new LocalProvisioner({
667
- baseDomain: config.baseDomain || 'matrixboard.cn',
668
- prefix: config.prefix || 'dsh',
669
- executable: config.executable || 'cloudflared',
670
- stateFile,
671
- configFile: config.configFile || null,
672
- seed: config.seed || null,
673
- log,
674
- // 生产路径才接真实探测:测试直接 new LocalProvisioner 时保持零网络依赖
675
- zoneDiagnose: diagnoseZone,
676
- ownerLookup: findDnsOwner,
677
- });
678
- }
679
- if (kind === 'state') {
680
- return new StateProvisioner({
681
- stateFile,
682
- baseDomain: config.baseDomain || 'matrixboard.cn',
683
- log,
684
- });
685
- }
686
- if (kind === 'hosted') {
687
- const provisioner = new HostedProvisioner({
688
- endpoint: config.endpoint || null,
689
- enrollToken: config.enrollToken || null,
690
- hostId,
691
- baseDomain: config.baseDomain || 'matrixboard.cn',
692
- stateFile,
693
- log,
694
- });
695
- return provisioner.configured ? provisioner : null;
696
- }
697
- return null;
698
- }
1
+ // cloudflare.mjs — Pro 固定地址:一个 tunnel + 一个子域 + 一份 token 的自动开通
2
+ //
3
+ // 三种凭证必须先分清,否则一定会把 zone 权限塞进客户端:
4
+ // · Zone API Token:能建/删整个 matrixboard.cn 的 DNS。**只能待在运营方**,
5
+ // 一旦随桌面端分发,任何用户都能把域名迁走。
6
+ // · Tunnel Token:只对单个 tunnel 有效的 JWT,给 cloudflared 用,可在主机落盘。
7
+ // · 子域名:由安装标识派生,稳定、不可猜、可回收。
8
+ //
9
+ // 因此这里提供两条同构路径,REST 层与 UI 不需要知道背后是谁:
10
+ // CloudflareProvisioner —— 自托管 / 运营调试:主机侧直连 CF API(需 zone token)
11
+ // HostedProvisioner —— 产品形态:主机拿 enroll 凭证向开通服务换三件套
12
+ //
13
+ // 共同语义(不可放松):
14
+ // 1. 幂等:重复 ensure 不重建 tunnel、不重复写 DNS;
15
+ // 2. token 只落盘 0600,永不出现在 status()/日志/诊断包里;
16
+ // 3. 端口变了要重写 ingress(端口会因占用顺延,写死会指向空气);
17
+ // 4. 失败要能定位:CF 的错误码原样带上,但不带 token。
18
+
19
+ import crypto from 'node:crypto';
20
+ import fs from 'node:fs';
21
+ import os from 'node:os';
22
+ import path from 'node:path';
23
+ import { fail } from './protocol.mjs';
24
+ import { deriveSubdomain, isValidLabel } from './dns-label.mjs';
25
+ import { DNS_PENDING_HINT, DNS_TAMPER_HINT, dnsWarningFor, evaluateDnsAnswer, probeDns } from './dns-probe.mjs';
26
+ import { LocalProvisioner, LocalStateProvisioner, sanitizeZone } from './provision-local.mjs';
27
+ import { diagnoseZone, findDnsOwner, verifyCertAccess, ZONE_STATUS_HINT } from './zone-health.mjs';
28
+
29
+ // 兼容既有调用方与测试:子域规则从 dns-label.mjs 来,这里一并导出
30
+ export { deriveSubdomain, isValidLabel };
31
+
32
+ export const CF_API_BASE = 'https://api.cloudflare.com/client/v4';
33
+ const STATE_VERSION = 1;
34
+
35
+ function loadState(file, log) {
36
+ if (!file) return null;
37
+ let raw;
38
+ try {
39
+ raw = fs.readFileSync(file, 'utf8');
40
+ } catch (err) {
41
+ if (err.code === 'ENOENT') return null;
42
+ throw err;
43
+ }
44
+ try {
45
+ const parsed = JSON.parse(raw);
46
+ if (!parsed || parsed.version !== STATE_VERSION) throw new Error('结构不符');
47
+ if (!parsed.hostname || !parsed.tunnelId) throw new Error('缺少 hostname/tunnelId');
48
+ return parsed;
49
+ } catch (err) {
50
+ // 与设备注册表同一取舍:插件跑在宿主进程内,坏文件不该带崩宿主。
51
+ const backup = `${file}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`;
52
+ try {
53
+ fs.renameSync(file, backup);
54
+ log?.(`tunnel 开通状态损坏,已备份到 ${path.basename(backup)}(${err.message})`);
55
+ } catch {
56
+ log?.(`tunnel 开通状态损坏且备份失败(${err.message})`);
57
+ }
58
+ return null;
59
+ }
60
+ }
61
+
62
+ function saveState(file, state) {
63
+ if (!file) return;
64
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
65
+ const tmp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
66
+ const payload = JSON.stringify({ version: STATE_VERSION, ...state }, null, 2);
67
+ try {
68
+ fs.writeFileSync(tmp, payload, { mode: 0o600, flag: 'wx' });
69
+ fs.renameSync(tmp, file);
70
+ try { fs.chmodSync(file, 0o600); } catch { /* 刚写即 0600 */ }
71
+ } finally {
72
+ try { fs.unlinkSync(tmp); } catch { /* rename 成功时已不存在 */ }
73
+ }
74
+ }
75
+
76
+ class BaseProvisioner {
77
+ constructor({ stateFile = null, log = () => {}, baseDomain = 'matrixboard.cn', probe = null, zoneDiagnose = null } = {}) {
78
+ this.stateFile = stateFile;
79
+ this.log = log;
80
+ this.baseDomain = String(baseDomain).replace(/^\./, '').toLowerCase();
81
+ this._state = undefined; // undefined=未读;null=没有
82
+ // 可注入:测试里不该真发 DNS 查询(依赖外网且要等重试)
83
+ this.probe = probe || probeDns;
84
+ // 解析失败时进一步归因(moved / pending / ns-mismatch);不注入就只报「解析不到」
85
+ this.zoneDiagnose = zoneDiagnose;
86
+ this._zone = null;
87
+ }
88
+
89
+ /**
90
+ * 复核固定域名的公网解析,结论写回状态。
91
+ *
92
+ * 只做一次就够:确认可解析后 `dnsOk=true` 会被持久化,后续启动不再查;
93
+ * 没确认过(null,例如老状态文件)或上次失败(false)才复查——
94
+ * 否则「域名不可用」会因为状态文件存在而被永久固化,NS 改好了也发现不了。
95
+ */
96
+ async verifyDns(hostname = this.state?.hostname) {
97
+ if (!hostname) return { ok: false, kind: null, records: [] };
98
+ const check = await this.probe(hostname);
99
+ const current = this.state;
100
+ // 防劫持:CNAME 必须仍指向**本机**隧道(评估逻辑在 dns-probe.evaluateDnsAnswer)。
101
+ // 记录若被人改指到别的隧道/服务器,解析照样「成功」,流量却会落到对方 ingress——
102
+ // 这时按「地址不可用」处理,绝不下发。
103
+ const verdict = evaluateDnsAnswer(check, current?.tunnelId);
104
+ // 解析不到时再问一句「这域名现在归谁」:moved(被别的账号接管)与 pending(NS 还没指过来)
105
+ // 的修法完全不同,笼统一句「等 NS 生效」会让人白等。
106
+ let zone = null;
107
+ if (!verdict.ok && typeof this.zoneDiagnose === 'function') {
108
+ try {
109
+ zone = sanitizeZone(await this.zoneDiagnose({ baseDomain: this.baseDomain, dnsOk: false }));
110
+ } catch {
111
+ zone = null;
112
+ }
113
+ this._zone = zone;
114
+ }
115
+ if (current && current.hostname === hostname) {
116
+ this.#persist({
117
+ ...current,
118
+ dnsOk: verdict.ok,
119
+ dnsTampered: verdict.tampered,
120
+ dnsCheckedAt: new Date().toISOString(),
121
+ zone,
122
+ });
123
+ }
124
+ if (verdict.tampered) {
125
+ this.log(`tunnel 警告 固定地址解析被改指 ${hostname} → ${verdict.target}(期望 ${verdict.expected}),拒绝下发该地址`);
126
+ } else if (verdict.ok) {
127
+ this.log(`tunnel 固定地址已可解析 ${hostname}(${verdict.kind} ${verdict.records.join(',')})`);
128
+ } else {
129
+ this.log(`tunnel 警告 固定地址公网解析不到 ${hostname}`);
130
+ }
131
+ return verdict;
132
+ }
133
+
134
+ /**
135
+ * 面板「重新检测解析」:强制重探一次并写回状态,不做缓存短路。
136
+ * 与 LocalProvisioner.recheckDns 同一契约,面板对两种开通形态一视同仁。
137
+ */
138
+ async recheckDns() {
139
+ const s = this.state;
140
+ if (!s?.hostname) return { provisioned: false, ok: false, tampered: false, warning: null, zone: null };
141
+ const verdict = await this.verifyDns(s.hostname);
142
+ const now = this.state;
143
+ return {
144
+ provisioned: true,
145
+ hostname: now.hostname,
146
+ ok: Boolean(verdict.ok),
147
+ tampered: Boolean(verdict.tampered),
148
+ expected: verdict.expected ?? null,
149
+ target: verdict.target ?? null,
150
+ warning: dnsWarningFor(now),
151
+ checkedAt: now.dnsCheckedAt ?? null,
152
+ zone: now.zone ?? this._zone ?? null,
153
+ };
154
+ }
155
+
156
+ /** 状态文件里的缓存(读一次后常驻;写穿时同步更新)。 */
157
+ get state() {
158
+ if (this._state === undefined) this._state = loadState(this.stateFile, this.log);
159
+ return this._state;
160
+ }
161
+
162
+ #persist(next) {
163
+ this._state = next;
164
+ try {
165
+ saveState(this.stateFile, next);
166
+ } catch (err) {
167
+ // 落盘失败不该阻断本次开通(重启后重开会再换一份 token,仍是幂等的)
168
+ this.log(`tunnel 开通状态写入失败(本次仍可用):${err.message}`);
169
+ }
170
+ return next;
171
+ }
172
+
173
+ get url() {
174
+ return this.state ? `https://${this.state.hostname}` : null;
175
+ }
176
+
177
+ /** 对外可播报的信息:绝不含 token。 */
178
+ status() {
179
+ const s = this.state;
180
+ if (!s) return { kind: this.kind, provisioned: false, hostname: null, url: null, tunnelId: null };
181
+ return {
182
+ kind: this.kind,
183
+ provisioned: true,
184
+ hostname: s.hostname,
185
+ url: `https://${s.hostname}`,
186
+ tunnelId: s.tunnelId,
187
+ port: s.port ?? null,
188
+ // null = 还没验过;true/false = 验过且结论明确
189
+ dnsOk: s.dnsOk ?? null,
190
+ dnsCheckedAt: s.dnsCheckedAt ?? null,
191
+ zone: s.zone ?? this._zone ?? null,
192
+ warning: dnsWarningFor(s),
193
+ createdAt: s.createdAt ?? null,
194
+ updatedAt: s.updatedAt ?? null,
195
+ };
196
+ }
197
+
198
+ /**
199
+ * 开通/复用固定地址。返回 `{ hostname, url, tunnelId, created, changed }`。
200
+ *
201
+ * `port` 一定要传当前监听端口:端口被占用时网关会顺延,ingress 写死旧端口
202
+ * 会让公网地址 502,而用户完全看不出原因。
203
+ */
204
+ async ensure({ port, force = false } = {}) {
205
+ if (!this.configured) throw fail(4021, this.notConfiguredMessage, { detail: this.notConfiguredDetail });
206
+ if (!Number.isInteger(port) || port <= 0) throw fail(4400, '开通隧道需要有效端口');
207
+
208
+ const cached = this.state;
209
+ if (!force && cached && cached.port === port) {
210
+ // 已确认可解析就不再查;否则现场验一次,避免把「未生效」固化在状态里
211
+ if (cached.dnsOk !== true) await this.verifyDns(cached.hostname);
212
+ const s = this.state;
213
+ return {
214
+ hostname: s.hostname,
215
+ url: `https://${s.hostname}`,
216
+ tunnelId: s.tunnelId,
217
+ created: false,
218
+ changed: false,
219
+ dnsOk: s.dnsOk ?? null,
220
+ warning: dnsWarningFor(s),
221
+ };
222
+ }
223
+
224
+ const fresh = await this.provision({ port, cached });
225
+ const now = new Date().toISOString();
226
+ const next = this.#persist({
227
+ ...cached,
228
+ ...fresh,
229
+ port,
230
+ createdAt: cached?.createdAt ?? now,
231
+ updatedAt: now,
232
+ });
233
+ this.log(`tunnel 固定地址就绪 ${next.hostname}(${fresh.created ? '新建' : '复用'})`);
234
+ // 开通即自检:写成功 ≠ 公网能解析
235
+ if (next.dnsOk !== true) await this.verifyDns(next.hostname);
236
+ const done = this.state;
237
+ return {
238
+ hostname: done.hostname,
239
+ url: `https://${done.hostname}`,
240
+ tunnelId: done.tunnelId,
241
+ created: Boolean(fresh.created),
242
+ changed: Boolean(cached && cached.hostname !== next.hostname),
243
+ dnsOk: done.dnsOk ?? null,
244
+ warning: dnsWarningFor(done),
245
+ };
246
+ }
247
+
248
+ /**
249
+ * 取 cloudflared 要用的 `{ hostname, token }`。**仅供网关进程内部调用**,
250
+ * REST 层不得把它序列化出去。
251
+ */
252
+ async credential({ port }) {
253
+ await this.ensure({ port });
254
+ if (!this.state?.token) throw fail(4500, '隧道 token 缺失,请重新开通固定地址');
255
+ return { hostname: this.state.hostname, token: this.state.token };
256
+ }
257
+
258
+ /** 主机侧要用的一次性凭证/配置是否齐备。 */
259
+ get configured() {
260
+ return false;
261
+ }
262
+
263
+ get notConfiguredMessage() {
264
+ return '主机未配置隧道开通凭据';
265
+ }
266
+
267
+ get notConfiguredDetail() {
268
+ return null;
269
+ }
270
+
271
+ /** 非本地形态没有 cert.pem 可预检;面板统一按「无凭据信息」处理。 */
272
+ get credentials() {
273
+ return null;
274
+ }
275
+
276
+ /** 重置本机状态:token 形态由状态文件承载,删掉即「重新开通」。 */
277
+ async reset() {
278
+ let removed = [];
279
+ try {
280
+ if (this.stateFile && fs.statSync(this.stateFile).isFile()) {
281
+ fs.unlinkSync(this.stateFile);
282
+ removed = [path.basename(this.stateFile)];
283
+ }
284
+ } catch { /* 不存在即目标状态 */ }
285
+ const hadState = Boolean(this.state?.hostname);
286
+ this._state = null;
287
+ this._zone = null;
288
+ return { reset: true, hadState, removed, hostname: null, provisioned: false };
289
+ }
290
+ }
291
+
292
+ /**
293
+ * 直连 Cloudflare API 的开通器(运营/自托管)。
294
+ *
295
+ * 需要的权限(最小集):
296
+ * · Account → Cloudflare Tunnel: Edit
297
+ * · Zone(matrixboard.cn) → DNS: Edit
298
+ * · Zone(matrixboard.cn) → Zone: Read(用于把域名解析成 zoneId)
299
+ */
300
+ export class CloudflareProvisioner extends BaseProvisioner {
301
+ constructor({
302
+ apiToken = null,
303
+ accountId = null,
304
+ zoneId = null,
305
+ baseDomain = 'matrixboard.cn',
306
+ prefix = 'dsh',
307
+ stateFile = null,
308
+ seed = null,
309
+ fetchImpl = globalThis.fetch,
310
+ apiBase = CF_API_BASE,
311
+ log = () => {},
312
+ probe = null,
313
+ zoneDiagnose = null,
314
+ } = {}) {
315
+ super({ stateFile, log, baseDomain, probe, zoneDiagnose });
316
+ this.apiToken = apiToken;
317
+ this.accountId = accountId;
318
+ this.zoneId = zoneId;
319
+ this.prefix = prefix;
320
+ this.seed = seed;
321
+ this.fetchImpl = fetchImpl;
322
+ this.apiBase = String(apiBase).replace(/\/$/, '');
323
+ // API 形态本身就有 zone 级凭据,不必借 cert.pem:解析失败时直接问清 zone 现状
324
+ this.zoneDiagnose = zoneDiagnose || ((args = {}) => diagnoseZone({
325
+ ...args,
326
+ apiToken: this.apiToken,
327
+ zoneId: this.zoneId,
328
+ baseDomain: args.baseDomain || this.baseDomain,
329
+ fetchImpl: this.fetchImpl,
330
+ apiBase: this.apiBase,
331
+ }));
332
+ }
333
+
334
+ get kind() {
335
+ return 'cloudflare';
336
+ }
337
+
338
+ get configured() {
339
+ // accountId 不强制:一个 Token 往往只属于一个账号,让 API 自己说到底是谁,
340
+ // 比要求用户去面板抄一串 32 位十六进制更不容易出错。
341
+ return Boolean(this.apiToken && this.baseDomain && typeof this.fetchImpl === 'function');
342
+ }
343
+
344
+ get notConfiguredMessage() {
345
+ return '主机未配置 Cloudflare 凭据,无法开通固定地址';
346
+ }
347
+
348
+ get notConfiguredDetail() {
349
+ return '需要一个带 Account → Cloudflare Tunnel: Edit、Zone → DNS: Edit/Zone: Read 的 API Token;'
350
+ + '也可改用 hosted 开通服务(见 config.tunnel.provisioner)';
351
+ }
352
+
353
+ async #api(method, pathname, body) {
354
+ let res;
355
+ try {
356
+ res = await this.fetchImpl(`${this.apiBase}${pathname}`, {
357
+ method,
358
+ headers: {
359
+ Authorization: `Bearer ${this.apiToken}`,
360
+ 'Content-Type': 'application/json',
361
+ },
362
+ body: body === undefined ? undefined : JSON.stringify(body),
363
+ });
364
+ } catch (err) {
365
+ throw fail(4500, `无法连接 Cloudflare API:${err.message}`);
366
+ }
367
+ const text = await res.text();
368
+ let payload = null;
369
+ try {
370
+ payload = text ? JSON.parse(text) : null;
371
+ } catch {
372
+ throw fail(4500, `Cloudflare API 返回了非 JSON 响应(HTTP ${res.status})`);
373
+ }
374
+ if (!payload || payload.success !== true) {
375
+ const first = payload?.errors?.[0];
376
+ // 只透出 CF 自己的话,不带 Authorization
377
+ throw fail(4500, `Cloudflare 拒绝了请求:${first?.message || `HTTP ${res.status}`}`, {
378
+ status: res.status,
379
+ cfCode: first?.code ?? null,
380
+ });
381
+ }
382
+ return payload.result;
383
+ }
384
+
385
+ /**
386
+ * 确定 accountId。Token 能看见几个账号就用几个:
387
+ * 恰好一个 → 直接用它(绝大多数情况);多个 → 必须显式指定,否则可能开到别人的账号里。
388
+ */
389
+ async #ensureAccount() {
390
+ if (this.accountId) return this.accountId;
391
+ const raw = await this.#api('GET', '/accounts');
392
+ const list = (Array.isArray(raw) ? raw : []).filter((a) => a && a.id);
393
+ if (list.length === 1) {
394
+ this.accountId = list[0].id;
395
+ this.log?.(`tunnel 账号自动识别为 ${list[0].name || list[0].id}`);
396
+ return this.accountId;
397
+ }
398
+ if (!list.length) {
399
+ throw fail(4021, 'API Token 看不到任何 Cloudflare 账号', {
400
+ detail: 'Token 需要 Account → Cloudflare Tunnel: Edit 权限',
401
+ });
402
+ }
403
+ throw fail(4021, 'API Token 可见多个 Cloudflare 账号,请显式指定 accountId', {
404
+ detail: list.map((a) => a.name || a.id).join(' / '),
405
+ });
406
+ }
407
+
408
+ async #ensureZone() {
409
+ if (this.zoneId) return this.zoneId;
410
+ const zones = await this.#api('GET', `/zones?name=${encodeURIComponent(this.baseDomain)}`);
411
+ const zone = Array.isArray(zones) ? zones.find((z) => z.name === this.baseDomain) : null;
412
+ if (!zone) {
413
+ throw fail(4021, `Cloudflare 账号里找不到域名 ${this.baseDomain}`, {
414
+ detail: '确认该域名已接入当前账号;若用子账号,API Token 需要能看到这个 zone',
415
+ });
416
+ }
417
+ if (zone.status && zone.status !== 'active') {
418
+ // 状态不同,修法完全不同:moved 说明域名已被另一个 Cloudflare 账号接管,
419
+ // 在本账号重试一万次也不会生效;pending 只是 NS 还没指过来。
420
+ const hint = ZONE_STATUS_HINT[zone.status] || `状态 ${zone.status}`;
421
+ const ns = (zone.name_servers || []).join(' / ') || '(当前账号未分配)';
422
+ throw fail(4021, `域名 ${this.baseDomain} 未生效:${hint}`, {
423
+ detail: zone.status === 'moved'
424
+ ? `本账号分配的公网 NS 是 ${ns}。域名现在被另一个 Cloudflare 账号接管,本账号写入的记录不会下发——`
425
+ + '要么在注册商把 NS 改回这一对,要么统一只用同一个 Cloudflare 账号登录(两边互斥,只能二选一)。'
426
+ : `本账号分配的公网 NS 是 ${ns};到域名注册商把 NS 改成这一对,生效后再开通。`,
427
+ zoneStatus: zone.status,
428
+ expectedNs: zone.name_servers || [],
429
+ });
430
+ }
431
+ this.zoneId = zone.id;
432
+ this._zone = zone; // 供 requiredNameservers() 复用,避免为了一句提示再查一次
433
+ return zone.id;
434
+ }
435
+
436
+ /**
437
+ * 这个 zone 要求域名指向的 NS。用于「名称服务器无效」时的可执行提示:
438
+ * 用户拿到这两个名字去注册商改,比让他理解 pending zone 的概念有效得多。
439
+ */
440
+ async requiredNameservers() {
441
+ if (this._zone?.name_servers?.length) return this._zone.name_servers;
442
+ try {
443
+ const zones = await this.#api('GET', `/zones?name=${encodeURIComponent(this.baseDomain)}`);
444
+ const zone = (Array.isArray(zones) ? zones : []).find((z) => z.name === this.baseDomain);
445
+ if (zone) {
446
+ this._zone = zone;
447
+ return zone.name_servers || [];
448
+ }
449
+ } catch {
450
+ /* 权限不足时只是少一句提示,不该让开通失败 */
451
+ }
452
+ return [];
453
+ }
454
+
455
+ async #ensureTunnel(name) {
456
+ const list = await this.#api(
457
+ 'GET',
458
+ `/accounts/${this.accountId}/cfd_tunnel?name=${encodeURIComponent(name)}&is_deleted=false`,
459
+ );
460
+ // REST 这边未删除给的是 null,与 CLI 的 "0001-01-01T00:00:00Z" 不同;
461
+ // 两种都按「没删」处理,免得两条开通路径对同一条隧道得出相反结论。
462
+ const hit = (Array.isArray(list) ? list : []).find((t) => t && t.name === name
463
+ && (!t.deleted_at || String(t.deleted_at).startsWith('0001-01-01')));
464
+ if (hit) {
465
+ // 本地管理型 tunnel 不接受远端 ingress 下发,拿 token 跑起来会没有路由。
466
+ if (hit.remote_config === false) {
467
+ throw fail(4021, `已存在同名本地管理隧道 ${name}`, {
468
+ detail: '在 Cloudflare 面板删掉它,或换一个开通前缀;本方案只用 remotely-managed tunnel',
469
+ });
470
+ }
471
+ return { id: hit.id, created: false };
472
+ }
473
+ const created = await this.#api('POST', `/accounts/${this.accountId}/cfd_tunnel`, {
474
+ name,
475
+ config_src: 'cloudflare',
476
+ });
477
+ return { id: created.id, created: true };
478
+ }
479
+
480
+ async #putIngress(tunnelId, hostname, port) {
481
+ await this.#api('PUT', `/accounts/${this.accountId}/cfd_tunnel/${tunnelId}/configurations`, {
482
+ config: {
483
+ ingress: [
484
+ { hostname, service: `http://127.0.0.1:${port}` },
485
+ // 兜底规则是 CF 的硬要求:最后一条必须无 hostname,否则保存被拒。
486
+ { service: 'http_status:404' },
487
+ ],
488
+ },
489
+ });
490
+ }
491
+
492
+ async #upsertDns(zoneId, fqdn, tunnelId) {
493
+ const target = `${tunnelId}.cfdargotunnel.com`;
494
+ const list = await this.#api(
495
+ 'GET',
496
+ `/zones/${zoneId}/dns_records?type=CNAME&name=${encodeURIComponent(fqdn)}`,
497
+ );
498
+ const existing = (Array.isArray(list) ? list : [])[0];
499
+ const record = { type: 'CNAME', name: fqdn, content: target, proxied: true, ttl: 1 };
500
+ if (existing) {
501
+ if (String(existing.content || '').toLowerCase() === target) return { created: false };
502
+ await this.#api('PUT', `/zones/${zoneId}/dns_records/${existing.id}`, record);
503
+ return { created: false, updated: true };
504
+ }
505
+ await this.#api('POST', `/zones/${zoneId}/dns_records`, { ...record, comment: 'dsh-mobile pro tunnel' });
506
+ return { created: true };
507
+ }
508
+
509
+ async provision({ port, cached }) {
510
+ const installationId = cached?.installationId || crypto.randomBytes(16).toString('hex');
511
+ await this.#ensureAccount();
512
+ const zoneId = await this.#ensureZone();
513
+ const label = cached?.subdomain || deriveSubdomain(this.seed || installationId, { prefix: this.prefix });
514
+ const hostname = `${label}.${this.baseDomain}`;
515
+ const tunnel = await this.#ensureTunnel(label);
516
+ // token 只在第一次(或状态文件丢失)时取;CF 侧 token 不会因为重启而变。
517
+ let token = cached?.token;
518
+ if (!token || cached.tunnelId !== tunnel.id) {
519
+ token = await this.#api('GET', `/accounts/${this.accountId}/cfd_tunnel/${tunnel.id}/token`);
520
+ }
521
+ await this.#putIngress(tunnel.id, hostname, port);
522
+ await this.#upsertDns(zoneId, hostname, tunnel.id);
523
+ return {
524
+ installationId,
525
+ subdomain: label,
526
+ hostname,
527
+ tunnelId: tunnel.id,
528
+ token,
529
+ created: tunnel.created,
530
+ };
531
+ }
532
+ }
533
+
534
+ /**
535
+ * 通过开通服务换三件套(产品形态)。
536
+ *
537
+ * 合约(服务端实现同样语义即可):
538
+ * POST {endpoint}/v1/tunnel
539
+ * Authorization: Bearer <enroll token>
540
+ * { "hostId": "...", "port": 3081, "subdomain": "dsh-xxxx"|null }
541
+ * → { "hostname": "dsh-xxxx.matrixboard.cn", "tunnelId": "...", "token": "eyJ..." }
542
+ *
543
+ * 主机侧只保存 enroll 凭证与换回来的 tunnel token,永远看不到 zone 级权限。
544
+ */
545
+ export class HostedProvisioner extends BaseProvisioner {
546
+ constructor({
547
+ endpoint = null,
548
+ enrollToken = null,
549
+ hostId = null,
550
+ baseDomain = 'matrixboard.cn',
551
+ stateFile = null,
552
+ fetchImpl = globalThis.fetch,
553
+ log = () => {},
554
+ probe = null,
555
+ } = {}) {
556
+ super({ stateFile, log, baseDomain, probe });
557
+ this.endpoint = endpoint ? String(endpoint).replace(/\/$/, '') : null;
558
+ this.enrollToken = enrollToken;
559
+ this.hostId = hostId;
560
+ this.fetchImpl = fetchImpl;
561
+ }
562
+
563
+ get kind() {
564
+ return 'hosted';
565
+ }
566
+
567
+ get configured() {
568
+ return Boolean(this.endpoint && this.enrollToken && typeof this.fetchImpl === 'function');
569
+ }
570
+
571
+ get notConfiguredMessage() {
572
+ return '主机未加入固定地址开通服务';
573
+ }
574
+
575
+ get notConfiguredDetail() {
576
+ return '需要 config.tunnel.endpoint 与 enrollToken(Pro 订阅后由账号体系下发)';
577
+ }
578
+
579
+ async provision({ port, cached }) {
580
+ let res;
581
+ try {
582
+ res = await this.fetchImpl(`${this.endpoint}/v1/tunnel`, {
583
+ method: 'POST',
584
+ headers: {
585
+ Authorization: `Bearer ${this.enrollToken}`,
586
+ 'Content-Type': 'application/json',
587
+ },
588
+ body: JSON.stringify({
589
+ hostId: this.hostId,
590
+ port,
591
+ subdomain: cached?.subdomain ?? null,
592
+ }),
593
+ });
594
+ } catch (err) {
595
+ throw fail(4500, `无法连接固定地址开通服务:${err.message}`);
596
+ }
597
+ const text = await res.text();
598
+ let body = null;
599
+ try {
600
+ body = text ? JSON.parse(text) : null;
601
+ } catch {
602
+ throw fail(4500, `开通服务返回了非 JSON 响应(HTTP ${res.status})`);
603
+ }
604
+ if (!res.ok || !body) {
605
+ throw fail(4500, `开通服务拒绝了请求:${body?.message || body?.error?.message || `HTTP ${res.status}`}`, {
606
+ status: res.status,
607
+ });
608
+ }
609
+ const hostname = String(body.hostname || '').toLowerCase();
610
+ // 服务端被攻陷时也不能把用户手机引到别的域名去。
611
+ if (!hostname.endsWith(`.${this.baseDomain}`)) {
612
+ throw fail(4500, `开通服务返回的域名不在 ${this.baseDomain} 下,已拒绝`);
613
+ }
614
+ if (!body.tunnelId || !body.token) throw fail(4500, '开通服务返回内容不完整(缺 tunnelId/token)');
615
+ return {
616
+ installationId: cached?.installationId || crypto.randomBytes(16).toString('hex'),
617
+ subdomain: hostname.slice(0, -(this.baseDomain.length + 1)),
618
+ hostname,
619
+ tunnelId: String(body.tunnelId),
620
+ token: String(body.token),
621
+ created: true,
622
+ };
623
+ }
624
+ }
625
+
626
+ /**
627
+ * 只读现有开通状态(kind=state)。
628
+ *
629
+ * 用途:**已经开通过的机器日常启动**。此时主机不该再持有 zone 级凭据——
630
+ * token 与固定域名在 0600 状态文件里就够了,cloudflared 也只认 token。
631
+ * 这也正是产品形态:开通是一次性的服务端动作,之后本机离线也能起隧道。
632
+ *
633
+ * 唯一代价:端口顺延后无法自行改写 CF 侧 ingress(那需要 API 凭据)。
634
+ * 这种情况必须**如实报错**,而不是让公网地址 502 给用户一个「连上了但没数据」。
635
+ */
636
+ export class StateProvisioner extends BaseProvisioner {
637
+ constructor({ stateFile = null, baseDomain = 'matrixboard.cn', log = () => {}, probe = null } = {}) {
638
+ super({ stateFile, log, baseDomain, probe });
639
+ }
640
+
641
+ get kind() {
642
+ return 'state';
643
+ }
644
+
645
+ get configured() {
646
+ return Boolean(this.state?.hostname && this.state?.token);
647
+ }
648
+
649
+ get notConfiguredMessage() {
650
+ return '这台主机还没有开通固定地址';
651
+ }
652
+
653
+ get notConfiguredDetail() {
654
+ return '先配置 Cloudflare 凭据或开通服务跑一次开通;之后日常启动只需状态文件';
655
+ }
656
+
657
+ async provision({ port, cached }) {
658
+ if (!cached?.token || !cached?.hostname) throw fail(4021, this.notConfiguredMessage);
659
+ if (cached.port && port && cached.port !== port) {
660
+ throw fail(4021, `固定地址目前指向端口 ${cached.port},当前监听 ${port}`, {
661
+ detail: '端口变化需要带上 Cloudflare 凭据重新开通一次(改写 ingress),否则公网地址会 502',
662
+ });
663
+ }
664
+ return { ...cached, created: false };
665
+ }
666
+ }
667
+
668
+ /** 按配置挑一个开通器;都不满足时返回 null(隧道退化成 Quick Tunnel)。 */
669
+ export function createProvisioner(config = {}, { log = () => {}, stateFile = null, hostId = null } = {}) {
670
+ // 没显式指定时按凭据推断:有开通服务地址就走 hosted,否则直连 CF。
671
+ // 硬性默认 cloudflare 会让「只配了 endpoint」的主机静默退回 Quick Tunnel。
672
+ const kind = String(config.provisioner || (config.endpoint ? 'hosted' : 'cloudflare')).toLowerCase();
673
+ if (kind === 'cloudflare') {
674
+ const provisioner = new CloudflareProvisioner({
675
+ apiToken: config.apiToken || null,
676
+ accountId: config.accountId || null,
677
+ zoneId: config.zoneId || null,
678
+ baseDomain: config.baseDomain || 'matrixboard.cn',
679
+ prefix: config.prefix || 'dsh',
680
+ seed: config.seed || null,
681
+ stateFile,
682
+ log,
683
+ });
684
+ return provisioner.configured ? provisioner : null;
685
+ }
686
+ if (kind === 'local') {
687
+ return new LocalProvisioner({
688
+ baseDomain: config.baseDomain || 'matrixboard.cn',
689
+ prefix: config.prefix || 'dsh',
690
+ executable: config.executable || 'cloudflared',
691
+ stateFile,
692
+ configFile: config.configFile || null,
693
+ seed: config.seed || null,
694
+ // 默认当前用户;显式传入便于测试与「非标准 home」的宿主环境
695
+ homeDir: config.homeDir || os.homedir(),
696
+ log,
697
+ // 生产路径才接真实探测:测试直接 new LocalProvisioner 时保持零网络依赖
698
+ zoneDiagnose: diagnoseZone,
699
+ ownerLookup: findDnsOwner,
700
+ // 开通前凭据预检:跨账号的 cert.pem 必须在写 DNS **之前**被识别出来
701
+ verifyAccess: verifyCertAccess,
702
+ hostname: os.hostname(),
703
+ });
704
+ }
705
+ if (kind === 'state') {
706
+ // 先按 token 形态找;找不到再按**本地管理型**状态找(cert.pem 被删了也能继续用固定地址)。
707
+ // 返回 null 的语义是「这台机器确实没有可复用的固定地址」,而不是「凭据不全就降级成随机地址」。
708
+ const byToken = new StateProvisioner({
709
+ stateFile,
710
+ baseDomain: config.baseDomain || 'matrixboard.cn',
711
+ log,
712
+ });
713
+ if (byToken.configured) return byToken;
714
+ const byLocal = new LocalStateProvisioner({
715
+ stateFile,
716
+ configFile: config.configFile || null,
717
+ baseDomain: config.baseDomain || 'matrixboard.cn',
718
+ homeDir: config.homeDir || os.homedir(),
719
+ log,
720
+ });
721
+ return byLocal.configured ? byLocal : null;
722
+ }
723
+ if (kind === 'hosted') {
724
+ const provisioner = new HostedProvisioner({
725
+ endpoint: config.endpoint || null,
726
+ enrollToken: config.enrollToken || null,
727
+ hostId,
728
+ baseDomain: config.baseDomain || 'matrixboard.cn',
729
+ stateFile,
730
+ log,
731
+ });
732
+ return provisioner.configured ? provisioner : null;
733
+ }
734
+ return null;
735
+ }