dsh-mobile-ios 0.2.17 → 0.2.19

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.
@@ -25,10 +25,13 @@ import { deriveSubdomain, isValidLabel } from './dns-label.mjs';
25
25
  import { dnsWarningFor, evaluateDnsAnswer, probeDns, resolveNs } from './dns-probe.mjs';
26
26
  import { cnameBelongsTo, readZoneCert } from './zone-health.mjs';
27
27
  import { findCloudflared } from './tunnel.mjs';
28
+ import { explainTunnelFailure } from './tunnel-error.mjs';
29
+ import { hasLocalCredentials, isForeignState, machineIdentity, readState, writeState } from './tunnel-state.mjs';
28
30
 
29
31
  const execFileAsync = promisify(nodeExecFile);
30
32
  const CLI_TIMEOUT_MS = 45_000;
31
- const STATE_VERSION = 1;
33
+ // 凭据预检的缓存时长:够短(重新 login 后一分钟内生效),够长(不会每次开隧道都打 API)。
34
+ const AUTH_TTL_MS = 120_000;
32
35
 
33
36
  const UUID_PATTERN = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i;
34
37
 
@@ -48,26 +51,8 @@ function isLiveTunnel(t) {
48
51
  return String(deleted).startsWith('0001-01-01');
49
52
  }
50
53
 
51
- function readState(file, log) {
52
- if (!file) return null;
53
- try {
54
- const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
55
- if (!parsed || parsed.version !== STATE_VERSION) throw new Error('结构不符');
56
- return parsed;
57
- } catch (err) {
58
- if (err.code !== 'ENOENT') log?.(`tunnel 本地开通状态不可用:${err.message}`);
59
- return null;
60
- }
61
- }
62
-
63
- function writeState(file, state) {
64
- if (!file) return;
65
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
66
- const tmp = `${file}.${process.pid}.tmp`;
67
- fs.writeFileSync(tmp, JSON.stringify({ version: STATE_VERSION, ...state }, null, 2), { mode: 0o600, flag: 'w' });
68
- fs.renameSync(tmp, file);
69
- try { fs.chmodSync(file, 0o600); } catch { /* 刚写即 0600 */ }
70
- }
54
+ // 状态读写统一走 tunnel-state.mjs:那里同时负责「这份状态是不是本机的」,
55
+ // 否则跨机拷贝的 tunnel-named.json 会让新机器对外宣称一个指向旧机器的地址。
71
56
 
72
57
  /** cloudflared 的 ingress 配置文件。ports/hostname 变一次就要重写一次。 */
73
58
  export function renderConfig({ tunnelId, credentialsFile, hostname, port }) {
@@ -124,6 +109,11 @@ export class LocalProvisioner {
124
109
  zoneDiagnose = null,
125
110
  // 可注入:开通前查这条 hostname 现在指向哪条隧道,避免多机互相覆盖。
126
111
  ownerLookup = null,
112
+ // 可注入:开通前预检「这本 cert.pem 能不能写这个域名的 DNS」。
113
+ // 不注入就不预检(测试/离线保持零网络依赖);生产由 createProvisioner 注入。
114
+ verifyAccess = null,
115
+ // 可注入:本机主机名(只用于状态里记录机器身份,便于排障时看出「拷来的状态」)
116
+ hostname = null,
127
117
  } = {}) {
128
118
  this.baseDomain = String(baseDomain).replace(/^\./, '').toLowerCase();
129
119
  this.prefix = prefix;
@@ -135,11 +125,15 @@ export class LocalProvisioner {
135
125
  this.env = env;
136
126
  this.log = log;
137
127
  this._state = undefined;
128
+ this._machine = undefined;
129
+ this._auth = null; // { at, fp, verdict } —— 凭据预检结果缓存(不含 token)
130
+ this.hostnameHint = hostname;
138
131
  // 可注入,测试里不必真起 cloudflared
139
132
  this.run = run || this.#exec;
140
133
  this.probe = probe || probeDns;
141
134
  this.zoneDiagnose = zoneDiagnose;
142
135
  this.ownerLookup = ownerLookup;
136
+ this.verifyAccess = verifyAccess;
143
137
  this._zone = null; // 最近一次 zone 诊断结论(不含凭据)
144
138
  }
145
139
 
@@ -152,12 +146,100 @@ export class LocalProvisioner {
152
146
  return this._state;
153
147
  }
154
148
 
149
+ /** 本机身份(首次调用会生成 machine-id);目录不可写时为 null。 */
150
+ get machine() {
151
+ if (this._machine === undefined) {
152
+ try {
153
+ this._machine = machineIdentity({ stateFile: this.stateFile, hostname: this.hostnameHint });
154
+ } catch {
155
+ this._machine = null;
156
+ }
157
+ }
158
+ return this._machine;
159
+ }
160
+
155
161
  get configured() {
156
162
  // 本地形态只要证书在就算可开通;已开通则要配置与凭据都在
157
163
  if (this.state?.configFile) return true;
158
164
  return fs.existsSync(path.join(this.homeDir, '.cloudflared', 'cert.pem'));
159
165
  }
160
166
 
167
+ /** 最近一次凭据预检结论(面板展示用;未预检过为 null)。不含 token。 */
168
+ get credentials() {
169
+ if (!this._auth?.verdict) return null;
170
+ return this.#authSnapshot(this._auth.verdict);
171
+ }
172
+
173
+ #authSnapshot(verdict) {
174
+ if (!verdict) return null;
175
+ return {
176
+ state: verdict.state || 'unknown',
177
+ blocking: Boolean(verdict.blocking),
178
+ hint: verdict.hint ?? null,
179
+ accountName: verdict.accountName ?? null,
180
+ // 「证书账号」与「域名所在账号」在跨账号场景下是两个名字,面板必须都能显示:
181
+ // 只给域名账号名时,用户看不出自己刚跑的 tunnel login 到底切没切成功。
182
+ certAccountName: verdict.certAccountName ?? null,
183
+ certAccountId: verdict.certAccountId ?? null,
184
+ certZoneName: verdict.certZoneName ?? null,
185
+ zoneName: verdict.zoneName ?? null,
186
+ zoneStatus: verdict.zoneStatus ?? null,
187
+ detail: verdict.detail ?? null,
188
+ checkedAt: this._auth?.at ? new Date(this._auth.at).toISOString() : null,
189
+ };
190
+ }
191
+
192
+ #certFingerprint() {
193
+ const file = path.join(this.homeDir, '.cloudflared', 'cert.pem');
194
+ try {
195
+ const st = fs.statSync(file);
196
+ return `${st.size}:${Math.round(st.mtimeMs)}`;
197
+ } catch {
198
+ return 'none';
199
+ }
200
+ }
201
+
202
+ /**
203
+ * 凭据预检:当前 cert.pem 能不能管理 baseDomain。
204
+ *
205
+ * 只在**要写 Cloudflare** 的路径上作为硬门槛;日常启动命中缓存时只用于提示,
206
+ * 绝不因为「账号对不上」去拦一个本来能跑的隧道(cloudflared 运行时只需要
207
+ * credentials 文件,不需要 cert.pem)。
208
+ */
209
+ async checkCredentials({ force = false } = {}) {
210
+ if (typeof this.verifyAccess !== 'function') {
211
+ return { state: 'unknown', blocking: false, hint: null, accountName: null, checkedAt: null };
212
+ }
213
+ const fp = this.#certFingerprint();
214
+ const now = Date.now();
215
+ if (!force && this._auth && this._auth.fp === fp && now - this._auth.at < AUTH_TTL_MS) {
216
+ return this.#authSnapshot(this._auth.verdict);
217
+ }
218
+ let verdict = null;
219
+ try {
220
+ verdict = await this.verifyAccess({ homeDir: this.homeDir, baseDomain: this.baseDomain });
221
+ } catch (err) {
222
+ verdict = { state: 'unknown', blocking: false, hint: null, detail: err?.message || String(err) };
223
+ }
224
+ if (!verdict || typeof verdict !== 'object') verdict = { state: 'unknown', blocking: false, hint: null };
225
+ this._auth = { at: now, fp, verdict };
226
+ if (verdict.blocking) this.log(`tunnel 凭据预检未通过(${verdict.state}):${verdict.hint || ''}`);
227
+ return this.#authSnapshot(verdict);
228
+ }
229
+
230
+ /** 凭据不可用时抛出的统一错误(带可执行修法)。 */
231
+ #credentialError(verdict) {
232
+ const hint = verdict?.hint || '当前登录的 Cloudflare 账号无法管理这个域名';
233
+ const exe = findCloudflared(this.executable, this.env) || findCloudflared('auto', this.env) || this.executable;
234
+ const account = verdict?.accountName ? `(当前证书属于 ${verdict.accountName})` : '';
235
+ return fail(4021, `${hint}${account}`, {
236
+ detail: `在这台电脑的终端执行:${exe} tunnel login,`
237
+ + `在浏览器里选择持有 ${this.baseDomain} 的账号完成授权(会覆盖 ~/.cloudflared/cert.pem),`
238
+ + '然后回到面板重新点「开启远程」。重装插件、重启宿主、改 NS 都不能替代这一步。',
239
+ reason: 'credentials',
240
+ });
241
+ }
242
+
161
243
  get notConfiguredMessage() {
162
244
  return '主机还没有登录 Cloudflare';
163
245
  }
@@ -235,7 +317,10 @@ export class LocalProvisioner {
235
317
 
236
318
  status() {
237
319
  const s = this.state;
238
- if (!s) return { kind: 'local', provisioned: false, hostname: null, url: null, tunnelId: null };
320
+ // credentials 是「预检结论」,未预检过就是 null——面板据此决定要不要提示
321
+ // 「账号对不上」。它不是开通状态的替代品:隧道能跑 ≠ 能改写 DNS。
322
+ const credentials = this.credentials;
323
+ if (!s) return { kind: 'local', provisioned: false, hostname: null, url: null, tunnelId: null, credentials };
239
324
  return {
240
325
  kind: 'local',
241
326
  provisioned: true,
@@ -250,6 +335,7 @@ export class LocalProvisioner {
250
335
  // 面板据此给出**不同**的修法,而不是一律「等 NS 生效」。
251
336
  zone: s.zone ?? this._zone ?? null,
252
337
  warning: dnsWarningFor(s),
338
+ credentials,
253
339
  createdAt: s.createdAt ?? null,
254
340
  updatedAt: s.updatedAt ?? null,
255
341
  };
@@ -263,8 +349,11 @@ export class LocalProvisioner {
263
349
  * 于是 NS 改好了也永远停在「解析异常」,只能删状态文件才恢复(自锁死)。
264
350
  */
265
351
  async recheckDns() {
352
+ // 顺手强制刷一次凭据预检:用户改完账号跑 login 后,面板点「重新检测」就应
353
+ // 立刻看到结论变化(cert.pem 指纹变了会自动失效缓存,这里再加一层强制)。
354
+ const credentials = await this.checkCredentials({ force: true });
266
355
  const s = this.state;
267
- if (!s?.hostname) return { provisioned: false, ok: false, tampered: false, warning: null, publicNs: [], zone: null };
356
+ if (!s?.hostname) return { provisioned: false, ok: false, tampered: false, warning: null, publicNs: [], zone: null, credentials };
268
357
  const { verdict, zone } = await this.#evaluate(s.hostname, s.tunnelId);
269
358
  const next = {
270
359
  ...s,
@@ -285,9 +374,43 @@ export class LocalProvisioner {
285
374
  warning: dnsWarningFor(next),
286
375
  checkedAt: next.dnsCheckedAt,
287
376
  zone,
377
+ credentials,
288
378
  };
289
379
  }
290
380
 
381
+ /**
382
+ * 清空本机的固定地址状态(面板「重置本机隧道状态」)。
383
+ *
384
+ * 用途:状态文件被跨机拷贝、或结构损坏到无法自愈时,给用户一条不用手改文件系统的出路。
385
+ * 边界(刻意保守):
386
+ * · 只删**本模块自己写的**两个文件(状态 + ingress 配置),不碰 cert.pem;
387
+ * · 不删 Cloudflare 上的隧道与 DNS 记录——那是用户账号资产,删了不可恢复;
388
+ * · 幂等:反复调用都返回成功,不会因为文件已不在而报错。
389
+ */
390
+ async reset() {
391
+ const removed = [];
392
+ const targets = [this.stateFile, this.state?.configFile || this.configFile];
393
+ for (const file of targets) {
394
+ if (!file) continue;
395
+ try {
396
+ if (fs.statSync(file).isFile()) {
397
+ fs.unlinkSync(file);
398
+ removed.push(path.basename(file));
399
+ }
400
+ } catch {
401
+ /* 不存在即目标状态 */
402
+ }
403
+ }
404
+ const hadState = Boolean(this.state?.hostname);
405
+ if (hadState) {
406
+ this.log(`tunnel 已重置本机固定地址状态(原地址 ${this.state.hostname},Cloudflare 侧的隧道与记录未删除)`);
407
+ }
408
+ this._state = null;
409
+ this._auth = null;
410
+ this._zone = null;
411
+ return { reset: true, hadState, removed, hostname: null, provisioned: false };
412
+ }
413
+
291
414
  async #exec(args) {
292
415
  const { stdout, stderr } = await execFileAsync(this.#resolveExecutable(), args, {
293
416
  timeout: CLI_TIMEOUT_MS,
@@ -339,9 +462,54 @@ export class LocalProvisioner {
339
462
  return list.some((t) => isLiveTunnel(t) && t.id === tunnelId);
340
463
  }
341
464
 
465
+ /** 状态里记的地址是否仍属当前域名(运营换 baseDomain 后旧地址要重写)。 */
466
+ #hostnameBelongs(hostname) {
467
+ const h = String(hostname || '').toLowerCase();
468
+ return h.endsWith(`.${this.baseDomain}`) && h.length > this.baseDomain.length + 1;
469
+ }
470
+
471
+ /** 写状态时顺带记下本机身份:下次从别处拷来的状态就能被识别出来。 */
472
+ #withMachine(state) {
473
+ const m = this.machine;
474
+ if (!m) return state;
475
+ const prev = state?.machine;
476
+ if (prev?.id === m.id && prev?.hostname === m.hostname) return state;
477
+ return { ...state, machine: { id: m.id, hostname: m.hostname } };
478
+ }
479
+
342
480
  async ensure({ port, force = false } = {}) {
343
481
  if (!Number.isInteger(port) || port <= 0) throw fail(4400, '开通隧道需要有效端口');
344
- // 授权账号可能变过(域名迁到另一个 Cloudflare 账号后重新 login 就是这种情况):
482
+ const account = readZoneCert({ homeDir: this.homeDir })?.accountId || null;
483
+ // 记下进入本次调用前的地址:跨机状态/凭据缺失会把 cached 清空,
484
+ // 用这个变量才能如实回答「地址有没有变」(changed 供调用方记日志/判断漂移)。
485
+ const previousHostname = this.state?.hostname || null;
486
+ let cached = this.state;
487
+ let rebuild = false;
488
+
489
+ // ── 0) 状态归属校验(跨机拷贝是「分发后分配不出地址」的第二大来源)──
490
+ // · machine.id 不是本机 → 整份作废,重新分配地址(不能对外宣称别人的地址);
491
+ // · tunnel 凭据文件不在了 → 状态在本机跑不起来,同样重新分配。
492
+ if (cached && isForeignState(cached, this.machine)) {
493
+ this.log(`tunnel 状态来自另一台电脑(${String(cached.machine?.id || '').slice(0, 8)}… ≠ ${String(this.machine?.id || '').slice(0, 8)}…),重新分配固定地址`);
494
+ cached = null;
495
+ } else if (cached?.tunnelId && !hasLocalCredentials(cached)) {
496
+ this.log('tunnel 状态里的 tunnel 凭据文件已不存在,重新分配固定地址');
497
+ cached = null;
498
+ }
499
+
500
+ // 域名变更(运营换 baseDomain):子域可沿用,但要按新域名重写地址与记录
501
+ if (cached?.hostname && !this.#hostnameBelongs(cached.hostname)) {
502
+ if (cached.subdomain && isValidLabel(cached.subdomain)) {
503
+ this.log(`tunnel 记录的地址 ${cached.hostname} 不属于当前域名 ${this.baseDomain},按原前缀重写`);
504
+ cached = { ...cached, hostname: `${cached.subdomain}.${this.baseDomain}`, dnsOk: null, zone: null };
505
+ rebuild = true;
506
+ } else {
507
+ this.log('tunnel 记录的地址与当前域名不符且前缀不可用,重新分配');
508
+ cached = null;
509
+ }
510
+ }
511
+
512
+ // ── 1) 账号可能变过(域名迁到另一个 Cloudflare 账号后重新 login 就是这种情况)──
345
513
  // 旧 tunnel 属于上一个账号,继续拿它的 id 去 route dns 只会得到 "tunnel not found",
346
514
  // 或者更糟——静默写不进去却以为自己开通成功。真判定有两条线:
347
515
  // 1) 状态文件记了 account 且与当前 cert 不一致 → 确知换了账号;
@@ -350,9 +518,6 @@ export class LocalProvisioner {
350
518
  // 注意线 2) 只在「不知道归属」时才走:两种情况都清楚了还去拉子进程,会让面板每次
351
519
  // 点开通都多几百毫秒(tunnel-named 里「重复开通不再调 CLI」这条契约就是拦这个的)。
352
520
  // 账号变了就当新装:重建隧道、保留同一个子域(地址不变,用户不用重新记/重新扫码)。
353
- const account = readZoneCert({ homeDir: this.homeDir })?.accountId || null;
354
- let cached = this.state;
355
- let rebuild = false;
356
521
  if (cached?.tunnelId) {
357
522
  const knownMismatch = Boolean(cached.account && account && cached.account !== account);
358
523
  // 只有「当前证书能读出账号,但状态文件没记」才算归属未知。反过来若连证书都解析
@@ -381,23 +546,29 @@ export class LocalProvisioner {
381
546
  // 校验通过:把归属记下来。否则每次开通都因为「不知道归谁」再问一遍 Cloudflare,
382
547
  // 白白多一个子进程的延迟(这条路径就是给老状态文件补账的)。
383
548
  cached = { ...cached, account };
384
- this._state = cached;
385
- writeState(this.stateFile, cached);
549
+ this._state = this.#withMachine(cached);
550
+ writeState(this.stateFile, this._state);
386
551
  }
387
552
  }
388
553
  // 走完整开通:缓存里的 port/hostname 看着都可用,但它们描述的是上一个账号的隧道,
389
554
  // 跳过缓存才不会「解析通了就以为没事」。
390
555
  if (!force && !rebuild && cached?.hostname && cached.port === port) {
556
+ // 老状态文件没有 machine 字段:命中缓存时顺手认领(一次性,之后就是本机状态)
557
+ if (!cached.machine && this.machine) {
558
+ cached = this.#withMachine(cached);
559
+ this._state = cached;
560
+ writeState(this.stateFile, cached);
561
+ }
391
562
  // 与 BaseProvisioner 同策略:没确认过就现场验一次(含防篡改评估)
392
563
  if (cached.dnsOk !== true) {
393
564
  const { verdict, zone } = await this.#evaluate(cached.hostname, cached.tunnelId);
394
- const next = {
565
+ const next = this.#withMachine({
395
566
  ...cached,
396
567
  dnsOk: verdict.ok,
397
568
  dnsTampered: verdict.tampered,
398
569
  dnsCheckedAt: new Date().toISOString(),
399
570
  zone,
400
- };
571
+ });
401
572
  this._state = next;
402
573
  writeState(this.stateFile, next);
403
574
  return {
@@ -433,7 +604,7 @@ export class LocalProvisioner {
433
604
  hostname: cached.hostname,
434
605
  port,
435
606
  }), { mode: 0o600 });
436
- const next = { ...cached, port, updatedAt: new Date().toISOString() };
607
+ const next = this.#withMachine({ ...cached, port, updatedAt: new Date().toISOString() });
437
608
  this._state = next;
438
609
  writeState(this.stateFile, next);
439
610
  return {
@@ -447,6 +618,13 @@ export class LocalProvisioner {
447
618
  };
448
619
  }
449
620
 
621
+ // ── 以下每一步都要写 Cloudflare:先在本地把凭据问清楚 ──
622
+ // 这一步就是 2026-11-21 事故的正解:跨账号的 cert.pem 能列/建隧道,只有写 DNS 才失败,
623
+ // 等 CLI 报错时用户已经拿到「隧道正常」的假象。预检把失败提前到**任何写入之前**,
624
+ // 并直接说清「用哪个账号重跑 login」。网络不可达时结论是 unknown,不拦(降级原则)。
625
+ const auth = await this.checkCredentials();
626
+ if (auth.blocking) throw this.#credentialError(auth);
627
+
450
628
  const installationId = cached?.installationId || crypto.randomBytes(16).toString('hex');
451
629
  const label = cached?.subdomain || deriveSubdomain(this.seed || installationId, { prefix: this.prefix });
452
630
  if (!isValidLabel(label)) throw fail(4400, `派生出的子域不合法:${label}`);
@@ -459,7 +637,23 @@ export class LocalProvisioner {
459
637
  if (found) {
460
638
  tunnelId = found.id;
461
639
  } else {
462
- const out = await this.run(['tunnel', 'create', label]);
640
+ let out;
641
+ try {
642
+ out = await this.run(['tunnel', 'create', label]);
643
+ } catch (err) {
644
+ // 建隧道也会因为凭据/账号问题失败:同样把真实原因透传出来,不要只留一行命令回显
645
+ const explained = explainTunnelFailure(err, {
646
+ baseDomain: this.baseDomain,
647
+ operation: 'create-tunnel',
648
+ accountName: auth.accountName || null,
649
+ exe: this.#exeLabel(),
650
+ });
651
+ this.log(`tunnel 创建隧道失败 ${explained.reason} ${explained.message}`);
652
+ throw fail(4500, explained.message, {
653
+ detail: explained.detail,
654
+ reason: explained.reason,
655
+ });
656
+ }
463
657
  const m = UUID_PATTERN.exec(out);
464
658
  if (!m) throw fail(4500, 'cloudflared 没有返回 tunnel id', { detail: String(out).slice(-300) });
465
659
  tunnelId = m[1];
@@ -497,8 +691,19 @@ export class LocalProvisioner {
497
691
  try {
498
692
  await this.run(['tunnel', 'route', 'dns', '--overwrite-dns', label, hostname]);
499
693
  } catch (err) {
500
- throw fail(4500, `写入 DNS 失败:${String(err.message).split('\n')[0]}`, {
501
- detail: '确认 matrixboard.cn 在当前 Cloudflare 账号下,且登录时授权的就是它',
694
+ // 关键修复:不再 `split('\n')[0]`。真实原因在第二行
695
+ // (`Failed to add route: code: 10000, reason: Authentication error`),
696
+ // 旧代码把它丢掉,只留下 `Command failed: …` 的命令回显,患者无从下手。
697
+ const explained = explainTunnelFailure(err, {
698
+ baseDomain: this.baseDomain,
699
+ operation: 'route-dns',
700
+ accountName: auth.accountName || null,
701
+ exe: this.#exeLabel(),
702
+ });
703
+ this.log(`tunnel 写 DNS 失败 ${explained.reason}${explained.code ? ` code=${explained.code}` : ''} ${explained.message}`);
704
+ throw fail(4500, explained.message, {
705
+ detail: explained.detail,
706
+ reason: explained.reason,
502
707
  });
503
708
  }
504
709
 
@@ -519,7 +724,7 @@ export class LocalProvisioner {
519
724
  this.log(`tunnel 警告 固定地址写入成功但公网解析不到 ${hostname}`);
520
725
  }
521
726
 
522
- const next = {
727
+ const next = this.#withMachine({
523
728
  ...cached,
524
729
  installationId,
525
730
  // 记下这本证书属于哪个 Cloudflare 账号:下次若换了账号,能识别出「旧隧道不再可用」
@@ -536,7 +741,7 @@ export class LocalProvisioner {
536
741
  zone,
537
742
  createdAt: cached?.createdAt ?? now,
538
743
  updatedAt: now,
539
- };
744
+ });
540
745
  this._state = next;
541
746
  writeState(this.stateFile, next);
542
747
  this.log(`tunnel 固定地址就绪 ${hostname}(${created ? '新建' : '复用'},本地管理型)`);
@@ -545,16 +750,140 @@ export class LocalProvisioner {
545
750
  url: `https://${hostname}`,
546
751
  tunnelId,
547
752
  created,
548
- changed: Boolean(cached && cached.hostname !== hostname),
753
+ changed: Boolean(previousHostname && previousHostname !== hostname),
549
754
  dnsOk: verdict.ok,
550
755
  zone,
551
756
  warning,
552
757
  };
553
758
  }
554
759
 
760
+ /** 面板/报错里展示用的 cloudflared 名字(找不到时退回配置值,不发明路径)。 */
761
+ #exeLabel() {
762
+ return findCloudflared(this.executable, this.env) || findCloudflared('auto', this.env) || this.executable;
763
+ }
764
+
555
765
  async credential({ port }) {
556
766
  await this.ensure({ port });
557
767
  if (!this.state?.configFile) throw fail(4500, '隧道配置缺失,请重新开通固定地址');
558
768
  return { hostname: this.state.hostname, configFile: this.state.configFile };
559
769
  }
560
770
  }
771
+
772
+ /**
773
+ * 只读本地状态的开通器(cert.pem 不在了 / 被删了也能继续用固定地址)。
774
+ *
775
+ * 为什么需要:本地管理型的 ingress 与 tunnel 凭据(<uuid>.json)都在本机,
776
+ * 日常启动**不需要** zone 凭据——cert.pem 只在开通时用来写 DNS。
777
+ * 早先这种情况会掉回 Quick Tunnel(随机地址),用户会以为「固定地址丢了」。
778
+ *
779
+ * 边界:
780
+ * · 绝不写 DNS、绝不建隧道(没有 zone 凭据,做不到也不该假装做到);
781
+ * · 端口变了只重写本地 ingress(纯本地操作,安全);
782
+ * · 状态必须属于本机、凭据文件必须存在,否则 configured=false(不冒充别人的地址)。
783
+ */
784
+ export class LocalStateProvisioner {
785
+ constructor({ stateFile = null, configFile = null, baseDomain = 'matrixboard.cn', log = () => {}, homeDir = os.homedir() } = {}) {
786
+ this.stateFile = stateFile;
787
+ this.configFile = configFile || (stateFile ? path.join(path.dirname(stateFile), 'tunnel-config.yml') : null);
788
+ this.baseDomain = String(baseDomain || '').replace(/^\./, '').toLowerCase();
789
+ this.log = log;
790
+ this.homeDir = homeDir;
791
+ this._state = undefined;
792
+ }
793
+
794
+ get kind() {
795
+ return 'state';
796
+ }
797
+
798
+ get state() {
799
+ if (this._state === undefined) this._state = readState(this.stateFile, this.log);
800
+ return this._state;
801
+ }
802
+
803
+ get configured() {
804
+ const s = this.state;
805
+ if (!s?.hostname || !s.configFile || !s.credentialsFile) return false;
806
+ if (isForeignState(s, machineIdentity({ stateFile: this.stateFile }))) return false;
807
+ if (!fs.existsSync(s.configFile)) return false;
808
+ return hasLocalCredentials(s);
809
+ }
810
+
811
+ get credentials() {
812
+ return null;
813
+ }
814
+
815
+ /** 没有 cert.pem 也就没有写入能力:这里只保证「能起隧道」。 */
816
+ async ensure({ port } = {}) {
817
+ const s = this.state;
818
+ if (!s?.hostname || !s.configFile) throw fail(4021, '这台主机还没有可复用的固定地址');
819
+ if (Number.isInteger(port) && port > 0 && port !== s.port) {
820
+ try {
821
+ fs.mkdirSync(path.dirname(s.configFile), { recursive: true, mode: 0o700 });
822
+ fs.writeFileSync(s.configFile, renderConfig({
823
+ tunnelId: s.tunnelId,
824
+ credentialsFile: s.credentialsFile,
825
+ hostname: s.hostname,
826
+ port,
827
+ }), { mode: 0o600 });
828
+ const next = { ...s, port, updatedAt: new Date().toISOString() };
829
+ this._state = next;
830
+ writeState(this.stateFile, next);
831
+ this.log(`tunnel 端口顺延 ${s.port} → ${port}(本地 ingress 已重写,DNS 未改动)`);
832
+ } catch (err) {
833
+ this.log(`tunnel 重写 ingress 失败:${err.message}`);
834
+ }
835
+ }
836
+ return {
837
+ hostname: s.hostname,
838
+ url: `https://${s.hostname}`,
839
+ tunnelId: s.tunnelId,
840
+ created: false,
841
+ changed: false,
842
+ dnsOk: s.dnsOk ?? null,
843
+ warning: dnsWarningFor(s),
844
+ };
845
+ }
846
+
847
+ async credential({ port } = {}) {
848
+ const r = await this.ensure({ port });
849
+ return { hostname: r.hostname, configFile: this.state?.configFile };
850
+ }
851
+
852
+ /** 与 LocalProvisioner.reset 同语义:只清本机状态与 ingress,不碰 Cloudflare 侧。 */
853
+ async reset() {
854
+ const removed = [];
855
+ const hadState = Boolean(this.state?.hostname);
856
+ for (const file of [this.stateFile, this.state?.configFile || this.configFile]) {
857
+ if (!file) continue;
858
+ try {
859
+ if (fs.statSync(file).isFile()) {
860
+ fs.unlinkSync(file);
861
+ removed.push(path.basename(file));
862
+ }
863
+ } catch { /* 不存在即目标状态 */ }
864
+ }
865
+ if (hadState) this.log('tunnel 已重置本机固定地址状态(Cloudflare 侧的隧道与记录未删除)');
866
+ this._state = null;
867
+ return { reset: true, hadState, removed, hostname: null, provisioned: false };
868
+ }
869
+
870
+ status() {
871
+ const s = this.state;
872
+ if (!s) return { kind: 'state', provisioned: false, hostname: null, url: null, tunnelId: null };
873
+ return {
874
+ kind: 'state',
875
+ provisioned: true,
876
+ hostname: s.hostname,
877
+ url: `https://${s.hostname}`,
878
+ tunnelId: s.tunnelId,
879
+ port: s.port ?? null,
880
+ dnsOk: s.dnsOk ?? null,
881
+ dnsCheckedAt: s.dnsCheckedAt ?? null,
882
+ zone: s.zone ?? null,
883
+ warning: dnsWarningFor(s),
884
+ credentials: null,
885
+ createdAt: s.createdAt ?? null,
886
+ updatedAt: s.updatedAt ?? null,
887
+ };
888
+ }
889
+ }
@@ -0,0 +1,105 @@
1
+ // provision-select.mjs — 「这台机器该用哪种固定地址开通器」的唯一判定入口
2
+ //
3
+ // 背景:同一套判定原来在两个入口各写了一份(entries/plugin.mjs 与 entries/sidecar.mjs),
4
+ // 判据还不一样——sidecar 只看 `fs.existsSync(cert.pem)` 就选 local,plugin 还要看
5
+ // `configured`。分发到不同电脑后,「同一版本、同样的凭据,两个入口给出不同结论」,
6
+ // 这正是「换台电脑就分配不出固定地址 / 地址忽然没了」的一部分来源。
7
+ //
8
+ // 统一后的顺序(谁先齐备用谁):
9
+ // 1. 显式 provisioner:尊重运营决定,但配置的形态不可用时**明确降级并记录原因**;
10
+ // 2. hosted:有开通服务地址(endpoint + enrollToken)——产品形态;
11
+ // 3. cloudflare:本机有 accountId + apiToken——运营/自托管;
12
+ // 4. local:跑过 `cloudflared tunnel login`(cert.pem 存在)——零 API Token 的默认路径;
13
+ // 5. state:以前开通过的机器,没有证书也能按本机状态起隧道(token 或本地 ingress 两种形态);
14
+ // 6. 都没有 → null,隧道退回 Quick Tunnel(行为与旧版一致)。
15
+ //
16
+ // 判定只做**本地**检查(文件/配置存在性),不发网络请求。凭据是否真能写这个域名,
17
+ // 由 LocalProvisioner.checkCredentials 在真正开通前问 Cloudflare——两件事分开,
18
+ // 启动不能被网络拖住,写入不能带着错凭据。
19
+
20
+ import fs from 'node:fs';
21
+ import os from 'node:os';
22
+ import path from 'node:path';
23
+ import { createProvisioner } from './cloudflare.mjs';
24
+
25
+ /**
26
+ * @param {object} opts
27
+ * @param {object} opts.tunnelCfg 已归一化的 tunnel 配置(plugin config 或 sidecar args 映射后)
28
+ * @param {string|null} [opts.stateFile]
29
+ * @param {string|null} [opts.hostId]
30
+ * @param {string} [opts.homeDir] cert.pem 所在 home(测试必须能隔离;默认当前用户)
31
+ * @param {Function} [opts.log]
32
+ * @returns {object|null} 可用的开通器;null 表示保持 Quick Tunnel
33
+ */
34
+ export function resolveProvisioner({
35
+ tunnelCfg = {}, stateFile = null, hostId = null, log = () => {}, homeDir = os.homedir(),
36
+ } = {}) {
37
+ const baseDomain = tunnelCfg.baseDomain || process.env.DSH_TUNNEL_BASE_DOMAIN || 'matrixboard.cn';
38
+ const common = {
39
+ baseDomain,
40
+ homeDir,
41
+ prefix: tunnelCfg.prefix || 'dsh',
42
+ // 没找到就留 'auto':让发现链在真正要用的那一刻再解析一次(自动安装发生在启动之后)
43
+ executable: tunnelCfg.executable || 'auto',
44
+ };
45
+ const make = (kind, extra = {}) => createProvisioner(
46
+ { ...common, ...extra, provisioner: kind },
47
+ { log, stateFile, hostId },
48
+ );
49
+ const usable = (p) => (p && p.configured ? p : null);
50
+ const pick = (p, why) => {
51
+ if (p) log(`tunnel 固定地址开通器=${p.kind}(${why})域名=${baseDomain}`);
52
+ return p || null;
53
+ };
54
+ /** 启动时顺手预检一次凭据(不阻塞启动):面板因此能在用户点按钮之前就提示账号不对。 */
55
+ const warm = (p) => {
56
+ if (p && typeof p.checkCredentials === 'function') p.checkCredentials().catch(() => {});
57
+ return p;
58
+ };
59
+
60
+ const explicit = tunnelCfg.provisioner ? String(tunnelCfg.provisioner) : null;
61
+ // 「有没有登录过 Cloudflare」只由 cert.pem 决定:它是唯一能做特权写入(建隧道/写 DNS)的凭据。
62
+ // 状态文件只能复用已有地址,不能代替它——两者混在 configured 里会让判定随状态漂移。
63
+ const hasCert = (() => {
64
+ try {
65
+ return fs.statSync(path.join(homeDir, '.cloudflared', 'cert.pem')).isFile();
66
+ } catch {
67
+ return false;
68
+ }
69
+ })();
70
+ /** 没有证书时只能复用本机状态(token 形态或本地 ingress 形态)。 */
71
+ const stateOnly = () => usable(make('state'));
72
+
73
+ if (explicit === 'state') return warm(pick(stateOnly(), '显式 state'));
74
+ if (explicit === 'local') {
75
+ if (hasCert) {
76
+ const local = usable(make('local'));
77
+ if (local) return warm(pick(local, '显式 local'));
78
+ }
79
+ return warm(pick(stateOnly(), 'cert.pem 缺失,复用本机已开通状态'));
80
+ }
81
+ if (explicit === 'hosted' || (!explicit && tunnelCfg.endpoint)) {
82
+ return warm(pick(make('hosted', { endpoint: tunnelCfg.endpoint, enrollToken: tunnelCfg.enrollToken }), '开通服务'));
83
+ }
84
+ if (explicit === 'cloudflare') {
85
+ const cf = make('cloudflare', { apiToken: tunnelCfg.apiToken, accountId: tunnelCfg.accountId, zoneId: tunnelCfg.zoneId });
86
+ if (cf) return warm(pick(cf, '显式 cloudflare'));
87
+ return warm(pick(hasCert ? usable(make('local')) : null, 'cloudflare 凭据不全,改用 cloudflared 证书'));
88
+ }
89
+ // 自动:API 凭据 → 证书(可开通/可复用) → 本机状态(只复用)
90
+ const cf = make('cloudflare', { apiToken: tunnelCfg.apiToken, accountId: tunnelCfg.accountId, zoneId: tunnelCfg.zoneId });
91
+ if (cf) return warm(pick(cf, 'API 凭据'));
92
+ if (hasCert) {
93
+ const local = usable(make('local'));
94
+ if (local) return warm(pick(local, 'cloudflared 证书'));
95
+ }
96
+ const fromState = stateOnly();
97
+ if (fromState) return warm(pick(fromState, '本机已开通状态(无需证书)'));
98
+ log('tunnel 没有可用的固定地址凭据,保持 Quick Tunnel');
99
+ return null;
100
+ }
101
+
102
+ /** 供入口读取的默认状态文件位置(两个入口必须一致,否则状态会分裂成两份)。 */
103
+ export function defaultTunnelStateFile() {
104
+ return process.env.DSH_TUNNEL_STATE_FILE || path.join(os.homedir(), '.dsh', 'mobile-access', 'tunnel-named.json');
105
+ }