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.
package/src/rest.mjs CHANGED
@@ -4,10 +4,13 @@
4
4
  import { fail, ERRORS, newId } from './protocol.mjs';
5
5
  import { translateRecords } from './adapter/session-history.mjs';
6
6
  import { createRequire } from 'node:module';
7
+ import os from 'node:os';
7
8
  import { PLUGIN_VERSION } from './version.mjs';
8
9
  import { ensureCloudflared, resolveAsset } from './cloudflared-install.mjs';
9
10
  import { selfUpdatePlugin } from './plugin-update.mjs';
10
11
  import { resolveNs } from './dns-probe.mjs';
12
+ import { createLoginManager } from './cloudflared-login.mjs';
13
+ import { findCloudflared } from './tunnel.mjs';
11
14
 
12
15
  // QR 编码(vendor:qrcode-generator 1.4.4,MIT,零依赖;见 lib/vendor/,
13
16
  // .cjs 后缀:包为 type:module,require 需显式 CommonJS)
@@ -101,6 +104,9 @@ const DESKTOP_CORS_PATHS = [
101
104
  /^\/mobile\/v1\/tunnel\/provision$/,
102
105
  /^\/mobile\/v1\/tunnel\/install-cloudflared$/,
103
106
  /^\/mobile\/v1\/tunnel\/recheck-dns$/,
107
+ /^\/mobile\/v1\/tunnel\/reset$/,
108
+ /^\/mobile\/v1\/tunnel\/login$/,
109
+ /^\/mobile\/v1\/tunnel\/login\/cancel$/,
104
110
  /^\/mobile\/v1\/plugin\/self-update$/,
105
111
  ];
106
112
 
@@ -150,6 +156,22 @@ export function createRestRouter({ core, pairing, host, tickets, config = {}, lo
150
156
  const routes = [];
151
157
  const route = (method, pattern, handler) => routes.push({ method, pattern, handler });
152
158
 
159
+ /**
160
+ * 浏览器授权会话(`cloudflared tunnel login`)。
161
+ *
162
+ * 放在网关而不是面板:起子进程、读 HOME、等回调都只能在主机侧做;面板只负责
163
+ * 把链接摆出来并在结果出来后继续开通。会话是**进程级单例**——重复点不会开第二个
164
+ * 浏览器授权页(现场最容易踩的坑:点两次,两个 cloudflared 抢同一个 cert.pem)。
165
+ */
166
+ const loginManager = config.loginManager || createLoginManager({ log });
167
+
168
+ /** 授权用的 cloudflared 与开通用同一套发现链:能开通却找不到 login 的二进制没意义。 */
169
+ const loginExecutable = () => {
170
+ if (typeof config.loginExecutable === 'function') return config.loginExecutable();
171
+ const hint = config.tunnelProvisioner?.executable || 'auto';
172
+ return findCloudflared(hint, process.env) || findCloudflared('auto', process.env) || null;
173
+ };
174
+
153
175
  /**
154
176
  * 诊断包(GW-9)。
155
177
  *
@@ -263,6 +285,12 @@ export function createRestRouter({ core, pairing, host, tickets, config = {}, lo
263
285
  // 面板据此给**不同**的修法,而不是一律「等 NS 生效」。
264
286
  zone: prov?.zone ?? null,
265
287
  warning: prov?.warning ?? null,
288
+ // 凭据预检结论(local 形态才有):state=障碍类型,blocking=是否**确定**不可写。
289
+ // 面板因此能在用户点「开启远程」之前就提示「登录的账号不对」,而不是等写 DNS 才崩。
290
+ credentials: prov?.credentials ?? null,
291
+ // 浏览器授权的进度(idle/waiting/ok/error/canceled)。面板刷新/重载后能凭它
292
+ // 恢复「正在等授权」的界面,不会让用户以为按钮点了没反应。
293
+ login: loginManager.status(),
266
294
  // 面板据此决定是否显示「自动安装 cloudflared」入口:仅在缺失且有官方构建时为 true。
267
295
  canAutoInstall: base.executable === 'missing' && !!resolveAsset({}),
268
296
  };
@@ -572,6 +600,74 @@ export function createRestRouter({ core, pairing, host, tickets, config = {}, lo
572
600
  }, DESKTOP_CORS);
573
601
  });
574
602
 
603
+ /**
604
+ * 重置本机的固定地址状态(面板兜底动作)。
605
+ *
606
+ * 存在的理由:状态文件被跨机拷贝、或损坏到无法自愈时,用户原来只能手删
607
+ * ~/.dsh/mobile-access/tunnel-named.json——那是「只有开发者才会的操作」。
608
+ * 这里把「清本地状态」变成一次点击,并明确边界:
609
+ * · 只清本机状态与 ingress 配置,**不删** cert.pem;
610
+ * · **不删** Cloudflare 上的隧道与 DNS 记录(用户账号资产,删了不可恢复);
611
+ * · 幂等:重复点不会报错。
612
+ * 回环-only:管理面动作,与开通/启停同一道门。
613
+ */
614
+ route('POST', /^\/mobile\/v1\/tunnel\/reset$/, async (ctx) => {
615
+ loopbackOnly(ctx, '重置固定地址只允许在主机本机操作');
616
+ const prov = config.tunnelProvisioner;
617
+ if (typeof prov?.reset !== 'function') {
618
+ throw fail(4021, '当前主机没有可重置的固定地址状态', { method: 'tunnel.reset' });
619
+ }
620
+ // 先停隧道:进程还挂着旧配置时删配置,下一轮重拉会读到一个不存在的 ingress
621
+ try {
622
+ await config.tunnel?.stop?.();
623
+ } catch (err) {
624
+ log(`rest tunnel reset 前停止隧道失败(继续重置)${err?.message || err}`);
625
+ }
626
+ const result = await prov.reset();
627
+ log(`rest tunnel reset 完成 hadState=${result.hadState} removed=${(result.removed || []).join(',') || '(无文件)'}`);
628
+ return send(ctx.res, 200, { ...result, status: tunnelSnapshot() }, DESKTOP_CORS);
629
+ });
630
+
631
+ /**
632
+ * 发起 Cloudflare 浏览器授权(面板「重新授权」按钮)。
633
+ *
634
+ * 边界与开通同一道门(回环-only):这一步会起子进程并让浏览器拿到一次账号授权,
635
+ * 公网上的任何人都不能触发。返回里带 `url`——面板即使拿不到系统浏览器,也能把
636
+ * 链接复制出去在任意设备上完成授权(回调仍是本机 localhost,所以必须同机浏览器)。
637
+ */
638
+ route('POST', /^\/mobile\/v1\/tunnel\/login$/, async (ctx) => {
639
+ loopbackOnly(ctx, 'Cloudflare 授权只允许在主机本机操作');
640
+ const executable = loginExecutable();
641
+ if (!executable) {
642
+ throw fail(4021, '这台主机还没有 cloudflared,先安装再授权', {
643
+ method: 'tunnel.login',
644
+ detail: '面板「安装 cloudflared」或在这台电脑终端执行 brew install cloudflared',
645
+ });
646
+ }
647
+ let status;
648
+ try {
649
+ status = loginManager.start({ executable, homeDir: os.homedir() });
650
+ } catch (err) {
651
+ throw fail(4500, err?.message || '无法发起 Cloudflare 授权', { method: 'tunnel.login' });
652
+ }
653
+ log(`rest tunnel login ${status.state}${status.url ? '(已给出链接)' : '(等待输出链接)'}`);
654
+ return send(ctx.res, 200, status, DESKTOP_CORS);
655
+ });
656
+
657
+ /** 查询授权进度(面板每 1.5 秒轮询一次;状态机在 cloudflared-login.mjs)。 */
658
+ route('GET', /^\/mobile\/v1\/tunnel\/login$/, async (ctx) => {
659
+ loopbackOnly(ctx, 'Cloudflare 授权状态只允许在主机本机读取');
660
+ return send(ctx.res, 200, loginManager.status(), DESKTOP_CORS);
661
+ });
662
+
663
+ /** 取消授权:kill 掉等待中的 cloudflared,避免用户关了弹窗它还在后台等。 */
664
+ route('POST', /^\/mobile\/v1\/tunnel\/login\/cancel$/, async (ctx) => {
665
+ loopbackOnly(ctx, 'Cloudflare 授权只允许在主机本机操作');
666
+ const status = loginManager.cancel();
667
+ log(`rest tunnel login cancel → ${status.state}`);
668
+ return send(ctx.res, 200, status, DESKTOP_CORS);
669
+ });
670
+
575
671
  /**
576
672
  * 插件自更新(不依赖宿主 pluginManager)。
577
673
  *
@@ -909,6 +1005,9 @@ export function createRestRouter({ core, pairing, host, tickets, config = {}, lo
909
1005
  code,
910
1006
  message: err.message || meta.message,
911
1007
  ...(err.extra?.detail ? { detail: err.extra.detail } : {}),
1008
+ // 机器可读的失败原因(credentials / zone / conflict …):面板据此决定
1009
+ // 「给登录指引」还是「给 NS 修法」,不靠中文字符串匹配。
1010
+ ...(err.extra?.reason ? { reason: err.extra.reason } : {}),
912
1011
  traceId,
913
1012
  ...(err.extra?.retryAfterMs ? { retryAfterMs: err.extra.retryAfterMs } : {}),
914
1013
  ...(err.extra?.attemptsRemaining !== undefined ? { retryAfterMs: err.extra.retryAfterMs, attemptsRemaining: err.extra.attemptsRemaining } : {}),
package/src/server.mjs CHANGED
@@ -85,6 +85,9 @@ export async function createGateway({
85
85
  // 隧道子进程的 spawn 实现。默认用 node:child_process;测试注入假进程,
86
86
  // 嵌入式场景也可替换(TunnelManager 本身已支持,这里只是让网关能透传)。
87
87
  tunnelSpawn = null,
88
+ // 面板「重新授权」用的 cloudflared 与会话(测试注入;生产走发现链 + 真子进程)
89
+ loginExecutable = null,
90
+ loginManager = null,
88
91
  } = {}) {
89
92
  if (!host) throw new Error('createGateway 需要 host 适配器');
90
93
 
@@ -151,6 +154,8 @@ export async function createGateway({
151
154
  tunnel,
152
155
  tunnelProvisioner,
153
156
  hostView,
157
+ ...(loginExecutable ? { loginExecutable } : {}),
158
+ ...(loginManager ? { loginManager } : {}),
154
159
  // 手机端要填的「电脑地址」(LAN IP:port);未起或无私网地址时为 null
155
160
  lanAddr: () => (listening?.lan ?? null),
156
161
  };
@@ -0,0 +1,91 @@
1
+ // tunnel-error.mjs — 把 cloudflared 的失败翻译成「用户能照做」的一句话 + 一条命令
2
+ //
3
+ // 事故现场(2026-11-21):`cloudflared tunnel route dns` 失败时,
4
+ // provision-local 只取 stderr 第一行(`Command failed: /opt/homebrew/bin/cloudflared …`),
5
+ // 真正的原因在第二行 `Failed to add route: code: 10000, reason: Authentication error`,
6
+ // 被 `split('\n')[0]` 直接丢掉;detail 又固定写「确认域名在当前账号下」。
7
+ // 用户在面板上看到的是一句命令回显 —— 既不知道是账号问题,也不知道接下来做什么。
8
+ //
9
+ // 这里做两件事:
10
+ // 1. **如实保留** cloudflared 的错误码与原因(code / reason),不截断;
11
+ // 2. 按错误语义给出**对应的**修法。特别是「账号/域名不匹配」这一类,
12
+ // 唯一正确的动作是用持有该域名的账号重跑 `cloudflared tunnel login`,
13
+ // 重装插件、改 NS、重启宿主都无效——这一点必须写在提示里。
14
+
15
+ /** codeflared 的错误码含义(只收录会被我们误判成「网络问题」的几种)。 */
16
+ const CREDENTIAL_CODES = new Set([10000, 1001, 1003, 1004, 9109]);
17
+
18
+ /**
19
+ * 解析 cloudflared 的失败文本。
20
+ * @returns {{ code: number|null, reason: string|null, first: string, stderr: string }}
21
+ */
22
+ export function parseCloudflaredFailure(input) {
23
+ const text = String(input ?? '');
24
+ // 形如:Failed to add route: code: 10000, reason: Authentication error
25
+ const m = /code:\s*(\d{3,6})\s*,\s*reason:\s*([^\n\r]+)/i.exec(text);
26
+ const lines = text.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
27
+ const first = lines[0] || '';
28
+ return {
29
+ code: m ? Number(m[1]) : null,
30
+ reason: m ? m[2].trim() : null,
31
+ first,
32
+ // 保留完整文本供 detail 使用(面板/日志需要原始证据,不做二次截断)
33
+ stderr: text.trim(),
34
+ };
35
+ }
36
+
37
+ /** cloudflared 的失败文本里有没有「凭据/权限」语义。 */
38
+ function looksLikeCredentialIssue(text) {
39
+ return /authentication error|invalid zone identifier|unauthorized|forbidden|permission|not authorized|403/i.test(text);
40
+ }
41
+
42
+ function looksLikeZoneIssue(text) {
43
+ return /zone not found|invalid zone|no zone|zone does not exist|1001/i.test(text);
44
+ }
45
+
46
+ /**
47
+ * 生成可直接展示的错误。
48
+ *
49
+ * @param {unknown} err route/create 抛出的异常
50
+ * @param {object} opts
51
+ * @param {string} opts.baseDomain 固定地址所用域名(提示里要指名道姓)
52
+ * @param {'route-dns'|'create-tunnel'} [opts.operation] 失败发生在哪一步
53
+ * @param {string|null} [opts.accountName] 当前证书所属账号(已知时写进提示)
54
+ * @param {string|null} [opts.exe] 实际使用的 cloudflared 路径/名字
55
+ * @returns {{ message: string, detail: string, reason: string, code: number|null }}
56
+ */
57
+ export function explainTunnelFailure(err, { baseDomain = 'matrixboard.cn', operation = 'route-dns', accountName = null, exe = 'cloudflared' } = {}) {
58
+ const parsed = parseCloudflaredFailure(err?.message || err);
59
+ const raw = parsed.stderr || parsed.first;
60
+ const codeText = parsed.code !== null ? `code: ${parsed.code}${parsed.reason ? `, reason: ${parsed.reason}` : ''}` : null;
61
+ const accountText = accountName ? `(当前证书属于 ${accountName})` : '';
62
+ const loginHint = `请在这台电脑的终端执行:${exe} tunnel login`
63
+ + `,在浏览器里选择持有 ${baseDomain} 的账号完成授权(会覆盖 ~/.cloudflared/cert.pem),`
64
+ + '然后回到面板点「开启远程」重试。重装插件或重启宿主都不能替代这一步。';
65
+
66
+ if ((parsed.code !== null && CREDENTIAL_CODES.has(parsed.code)) || looksLikeCredentialIssue(raw)) {
67
+ return {
68
+ message: `Cloudflare 拒绝了写入:当前账号没有 ${baseDomain} 的权限`,
69
+ detail: `${loginHint}${codeText ? ` cloudflared 返回 ${codeText}。` : ''}${accountText}`,
70
+ reason: 'credentials',
71
+ code: parsed.code,
72
+ };
73
+ }
74
+ if (looksLikeZoneIssue(raw)) {
75
+ return {
76
+ // 保留 cloudflared 的原文(排障要用),同时把结论写在前面(用户要能一眼看懂)
77
+ message: `域名 ${baseDomain} 不在当前登录的 Cloudflare 账号下(${parsed.reason || parsed.first})`,
78
+ detail: `cloudflared 返回:${raw || 'zone not found'}。${loginHint}`,
79
+ reason: 'zone',
80
+ code: parsed.code,
81
+ };
82
+ }
83
+ const action = operation === 'create-tunnel' ? '创建隧道' : '写入 DNS';
84
+ return {
85
+ message: `${action}失败:${parsed.first || 'cloudflared 未给出原因'}`,
86
+ detail: `cloudflared 返回:${raw || '(空)'}`
87
+ + `。若反复失败,请执行 ${exe} tunnel login 重新授权 ${baseDomain} 后再试。`,
88
+ reason: 'unknown',
89
+ code: parsed.code,
90
+ };
91
+ }
@@ -0,0 +1,122 @@
1
+ // tunnel-state.mjs — 固定地址本地状态的**读写与归属校验**(唯一入口)
2
+ //
3
+ // 事故背景(2026-11-21,新 Mac 装插件后分配不出固定地址):
4
+ // 本机 `~/.cloudflared/cert.pem` 是另一个 Cloudflare 账号签发的旧证书,
5
+ // 插件却只检查「文件存在」就当已登录,于是隧道能建、写 DNS 才失败,
6
+ // 面板只留一句「写入 DNS 失败」,用户无从下手。
7
+ //
8
+ // 同一类问题还有第二个形态:**状态文件被跨机复用**。
9
+ // · 用户把 ~/.dsh 连同 tunnel-named.json 一起拷到新机器;
10
+ // · 或者网盘/迁移工具把整个 home 同步过去;
11
+ // · 状态里记着上一台机器的 tunnelId / credentialsFile / hostname。
12
+ // 若直接信这份状态,新机器会对外宣称一个指向**旧机器**的固定地址,
13
+ // 面板显示「已开通」,扫码却连到别人那里——比报错更糟。
14
+ //
15
+ // 因此状态文件的读必须带「这台机器是不是它的主人」这一条:
16
+ // · machine.id 与当前机器不同 → 外来状态,整份作废并重新派生地址;
17
+ // · credentialsFile 不存在 → 状态在本机不可用(缺 tunnel 凭据跑不起来);
18
+ // · 都没有(0.2.18 之前的旧状态)→ 认领,补写 machine 字段。
19
+ //
20
+ // 注:状态结构保持 version: 1,新字段全部可选——老插件读到新文件也只是忽略,
21
+ // 不需要迁移逻辑,升级与回滚都不会丢地址。
22
+
23
+ import crypto from 'node:crypto';
24
+ import fs from 'node:fs';
25
+ import os from 'node:os';
26
+ import path from 'node:path';
27
+
28
+ export const STATE_VERSION = 1;
29
+ const MACHINE_FILE = 'machine-id';
30
+
31
+ /**
32
+ * 读状态文件。不存在/结构不符都当「没有」,绝不抛。
33
+ * 结构不符时留一份备份,方便用户把地址找回来(与设备注册表同一取舍)。
34
+ */
35
+ export function readState(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') log?.(`tunnel 本地开通状态不可用:${err.message}`);
42
+ return null;
43
+ }
44
+ try {
45
+ const parsed = JSON.parse(raw);
46
+ if (!parsed || typeof parsed !== 'object' || parsed.version !== STATE_VERSION) throw new Error('结构不符');
47
+ return parsed;
48
+ } catch (err) {
49
+ const backup = `${file}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`;
50
+ try {
51
+ fs.renameSync(file, backup);
52
+ log?.(`tunnel 状态损坏,已备份到 ${path.basename(backup)}(${err.message})`);
53
+ } catch {
54
+ log?.(`tunnel 状态损坏且备份失败(${err.message})`);
55
+ }
56
+ return null;
57
+ }
58
+ }
59
+
60
+ export function writeState(file, state) {
61
+ if (!file) return;
62
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
63
+ const tmp = `${file}.${process.pid}.tmp`;
64
+ fs.writeFileSync(tmp, JSON.stringify({ version: STATE_VERSION, ...state }, null, 2), { mode: 0o600, flag: 'w' });
65
+ fs.renameSync(tmp, file);
66
+ try { fs.chmodSync(file, 0o600); } catch { /* 刚写即 0600 */ }
67
+ }
68
+
69
+ /**
70
+ * 本机的持久标识。
71
+ *
72
+ * 放在状态文件同目录(生产是 ~/.dsh/mobile-access/),0600。
73
+ * 为什么不用 hostname:改机器名、切网络都会变,拿它做身份会把正常机器判成新机器;
74
+ * 而 machine-id 只在首次运行时生成一次,稳定且不依赖系统信息。
75
+ * 目录整体被拷贝时 id 会跟着走——这种情况由 credentialsFile 存在性兜底(见 isStateUsable)。
76
+ */
77
+ export function machineIdentity({ stateFile = null, hostname = null } = {}) {
78
+ if (!stateFile) return null;
79
+ const dir = path.dirname(stateFile);
80
+ const file = path.join(dir, MACHINE_FILE);
81
+ let id = null;
82
+ try {
83
+ const raw = fs.readFileSync(file, 'utf8').trim();
84
+ if (/^[0-9a-f]{16,64}$/i.test(raw)) id = raw.toLowerCase();
85
+ } catch { /* 没有就建 */ }
86
+ if (!id) {
87
+ id = crypto.randomBytes(16).toString('hex');
88
+ try {
89
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
90
+ fs.writeFileSync(file, `${id}\n`, { mode: 0o600, flag: 'w' });
91
+ try { fs.chmodSync(file, 0o600); } catch { /* 刚写即 0600 */ }
92
+ } catch {
93
+ // 写不进去(只读目录/权限)不能挡住开通:退化成「无身份」,行为等同旧版本
94
+ return null;
95
+ }
96
+ }
97
+ return { id, hostname: hostname || os.hostname() };
98
+ }
99
+
100
+ /** 状态里记的机器身份是否与当前机器不同(不同 = 从别的电脑拷来的)。 */
101
+ export function isForeignState(state, machine) {
102
+ if (!state || !machine?.id) return false;
103
+ const recorded = state.machine?.id;
104
+ // 旧状态没有 machine 字段:无法判断,按「认领」处理(不重建,避免老用户地址漂移)
105
+ if (!recorded) return false;
106
+ return String(recorded).toLowerCase() !== String(machine.id).toLowerCase();
107
+ }
108
+
109
+ /**
110
+ * 这份状态在本机是否**可执行**:tunnel 凭据文件必须还在。
111
+ *
112
+ * 只查状态里记的路径(不探测网络):凭据缺失时隧道根本起不来,
113
+ * 继续对外宣称这个地址就是给用户一个必然失败的扫码结果。
114
+ */
115
+ export function hasLocalCredentials(state) {
116
+ if (!state?.credentialsFile) return false;
117
+ try {
118
+ return fs.statSync(state.credentialsFile).isFile();
119
+ } catch {
120
+ return false;
121
+ }
122
+ }
@@ -243,6 +243,262 @@ export function cnameBelongsTo(content, tunnelId) {
243
243
  return String(content).toLowerCase().startsWith(String(tunnelId).toLowerCase());
244
244
  }
245
245
 
246
+ /**
247
+ * 凭据状态码 → 面板一句话。blocking 的几种都是**确定不可用**,
248
+ * 其余(unknown / unreadable / no-token)只表示「查不清」,绝不能据此拦人。
249
+ */
250
+ export const CREDENTIAL_STATE_HINT = {
251
+ ok: '登录的 Cloudflare 账号可以管理这个域名',
252
+ missing: '主机还没有登录 Cloudflare',
253
+ unreadable: 'cert.pem 无法解析(可能是旧格式或文件损坏)',
254
+ 'no-token': 'cert.pem 里没有可用的 zone token(旧版证书)',
255
+ forbidden: '登录的 Cloudflare 账号没有这个域名的权限',
256
+ 'zone-missing': '当前登录的账号里看不到这个域名',
257
+ 'zone-scoped-other': '证书授权的是另一个域名,不是当前的固定地址域名',
258
+ 'account-mismatch': '证书所属账号与域名所在账号不是同一个',
259
+ 'stale-zone': 'cert.pem 指向的 zone 已失效(域名可能被删后重新接入)',
260
+ 'zone-moved': '域名已被另一个 Cloudflare 账号接管',
261
+ unknown: '暂时查不到凭据的可用性(网络不可达)',
262
+ };
263
+
264
+ /** 这些状态是「确定不可用」:可以放心在写 DNS 之前拦下,并给出对应修法。 */
265
+ const BLOCKING_STATES = new Set([
266
+ 'missing', 'forbidden', 'zone-missing', 'zone-scoped-other', 'account-mismatch', 'stale-zone', 'zone-moved',
267
+ ]);
268
+
269
+ /**
270
+ * 证书「看得到账号、却列不出这个域名」时,把证书真正授权的那把 zone 与账号名问出来。
271
+ *
272
+ * 为什么需要:`cloudflared tunnel login` 让人在浏览器里**选一个域名**,证书 token
273
+ * 只覆盖那一个 zone。如果当时点的是别的域名,`/zones?name=<目标>` 会返回空数组,
274
+ * 面板只能说「账号里看不到这个域名」——用户看着自己账号里明明有这个域名,无从下手。
275
+ * 问出「授权的是 xxx」之后,一句话就能说清下一步该做什么。
276
+ *
277
+ * 全部 best-effort:任何一步失败都不影响结论,只是少一句话。
278
+ */
279
+ async function probeCertScope(apiBase, cert, fetchImpl, timeoutMs) {
280
+ const out = { zoneName: null, zoneStatus: null, zoneGone: false, accountName: null };
281
+ if (cert.zoneId) {
282
+ const z = await cfRequest(apiBase, cert.apiToken, `/zones/${cert.zoneId}`, fetchImpl, timeoutMs);
283
+ if (z.ok && z.success) {
284
+ out.zoneName = z.result?.name || null;
285
+ out.zoneStatus = z.result?.status || null;
286
+ } else if (z.reached && (z.status === 400 || z.status === 404)) {
287
+ // 400 = Invalid zone identifier(zone 被删过),404 = 不存在
288
+ out.zoneGone = true;
289
+ }
290
+ }
291
+ if (cert.accountId) {
292
+ const a = await cfRequest(apiBase, cert.apiToken, `/accounts/${cert.accountId}`, fetchImpl, timeoutMs);
293
+ if (a.ok && a.success) out.accountName = a.result?.name || null;
294
+ }
295
+ return out;
296
+ }
297
+
298
+ /**
299
+ * 带 HTTP 状态的只读请求(cfGet 只关心 result,这里需要区分 403 与「断网」)。
300
+ * 任何异常都收敛成一个对象,绝不抛。
301
+ */
302
+ async function cfRequest(apiBase, apiToken, pathname, fetchImpl, timeoutMs = 4000) {
303
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
304
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
305
+ try {
306
+ const res = await fetchImpl(`${apiBase}${pathname}`, {
307
+ headers: { Authorization: `Bearer ${apiToken}` },
308
+ ...(controller ? { signal: controller.signal } : {}),
309
+ });
310
+ const text = await res.text();
311
+ let payload = null;
312
+ try { payload = text ? JSON.parse(text) : null; } catch { payload = null; }
313
+ return {
314
+ status: res.status,
315
+ ok: Boolean(res.ok),
316
+ success: payload?.success === true,
317
+ result: payload?.result ?? null,
318
+ errors: payload?.errors ?? [],
319
+ reached: true,
320
+ };
321
+ } catch (err) {
322
+ return { status: 0, ok: false, success: false, result: null, errors: [], reached: false, error: err?.message || String(err) };
323
+ } finally {
324
+ if (timer) clearTimeout(timer);
325
+ }
326
+ }
327
+
328
+ /**
329
+ * 开通前凭据预检:**这本 cert.pem 能不能写这个域名的 DNS**。
330
+ *
331
+ * 为什么必须在写 DNS 之前问:cross-account 的证书能列隧道、能建隧道(账号级权限正常),
332
+ * 只有写 DNS 会失败。等 CLI 报错时,用户已经拿到一个「隧道正常」的假象,
333
+ * 而错误又被截断成一行命令回显——这正是 2026-11-21 的现场。
334
+ *
335
+ * 判定口径(宁可放过,不可误杀):
336
+ * · 403 / success:false → 确定无权限(forbidden)
337
+ * · 200 且 zone 列表为空 → 这个 token 看不到该域名(zone-missing)
338
+ * · zone.account 与证书 account 不同 → account-mismatch
339
+ * · zone.id 与证书 zoneID 不同 → 证书指向旧 zone(stale-zone)
340
+ * · zone.status = moved → 域名被另一账号接管(zone-moved)
341
+ * · 断网/超时/无 token/解析失败 → unknown(不拦,交给 CLI 报错兜底)
342
+ *
343
+ * @returns {Promise<{state: string, blocking: boolean, hint: string|null,
344
+ * accountName: string|null, zoneName: string|null, zoneStatus: string|null,
345
+ * certAccountId: string|null, zoneId: string|null, detail: string|null}>}
346
+ */
347
+ export async function verifyCertAccess({
348
+ homeDir = os.homedir(),
349
+ baseDomain,
350
+ fetchImpl = globalThis.fetch,
351
+ apiBase = CF_API_BASE,
352
+ timeoutMs = 4000,
353
+ } = {}) {
354
+ const base = {
355
+ state: 'unknown',
356
+ blocking: false,
357
+ hint: CREDENTIAL_STATE_HINT.unknown,
358
+ accountName: null,
359
+ zoneName: baseDomain || null,
360
+ zoneStatus: null,
361
+ certAccountId: null,
362
+ certAccountName: null,
363
+ certZoneName: null,
364
+ zoneId: null,
365
+ detail: null,
366
+ };
367
+ const certFile = path.join(homeDir, '.cloudflared', 'cert.pem');
368
+ if (!fs.existsSync(certFile)) {
369
+ return { ...base, state: 'missing', blocking: true, hint: CREDENTIAL_STATE_HINT.missing, detail: '没有找到 cert.pem' };
370
+ }
371
+ if (typeof fetchImpl !== 'function') return { ...base, detail: '当前运行时不支持网络请求' };
372
+
373
+ const cert = readZoneCert({ homeDir });
374
+ if (!cert) {
375
+ return { ...base, state: 'unreadable', blocking: false, hint: CREDENTIAL_STATE_HINT.unreadable, detail: 'cert.pem 结构无法解析' };
376
+ }
377
+ if (!cert.apiToken) {
378
+ return {
379
+ ...base,
380
+ state: 'no-token',
381
+ blocking: false,
382
+ hint: CREDENTIAL_STATE_HINT['no-token'],
383
+ certAccountId: cert.accountId || null,
384
+ detail: '证书里没有 apiToken,无法预检',
385
+ };
386
+ }
387
+ if (!baseDomain) return { ...base, detail: '未配置固定地址域名' };
388
+
389
+ const list = await cfRequest(apiBase, cert.apiToken, `/zones?name=${encodeURIComponent(baseDomain)}`, fetchImpl, timeoutMs);
390
+ if (!list.reached) return { ...base, certAccountId: cert.accountId || null, detail: list.error || null };
391
+ if (!list.ok || !list.success) {
392
+ // 403 是确定无权限;其余 4xx/5xx 说不清,交给 CLI
393
+ if (list.status === 403 || list.status === 401) {
394
+ return {
395
+ ...base,
396
+ state: 'forbidden',
397
+ blocking: true,
398
+ hint: CREDENTIAL_STATE_HINT.forbidden,
399
+ certAccountId: cert.accountId || null,
400
+ detail: `HTTP ${list.status}`,
401
+ };
402
+ }
403
+ return { ...base, certAccountId: cert.accountId || null, detail: `HTTP ${list.status}` };
404
+ }
405
+
406
+ const zones = Array.isArray(list.result) ? list.result : [];
407
+ let zone = zones.find((z) => z && String(z.name).toLowerCase() === baseDomain.toLowerCase()) || null;
408
+ if (!zone) {
409
+ // 空列表 = 这个 token 看不到该域名。但「看不到」有三种完全不同的原因,
410
+ // 用户要做的事也不同,所以必须多问一句「证书到底授权给了谁」:
411
+ // · 登录时在浏览器里选了别的域名 → zone-scoped-other(重登录并选对域名)
412
+ // · 那把 zone 已被删除(域名删掉后重新接入会换 zoneID)→ stale-zone
413
+ // · 权限/账号问题 → zone-missing
414
+ // 顺带把证书账号名带回来:面板原来在这一步什么都不显示,用户无法确认
415
+ // 「我刚跑的 tunnel login 到底生效了没有」。
416
+ const scope = await probeCertScope(apiBase, cert, fetchImpl, timeoutMs);
417
+ const ident = {
418
+ ...base,
419
+ certAccountId: cert.accountId || null,
420
+ certAccountName: scope.accountName,
421
+ certZoneName: scope.zoneName,
422
+ };
423
+ if (scope.zoneName && scope.zoneName.toLowerCase() === baseDomain.toLowerCase()) {
424
+ // 按 ID 能读到、按名字列不出:token 权限怪,但证书本身确实指向这个域名。
425
+ // 这种情况不能拦(拦了就是误杀),继续走正常判定。
426
+ const byId = await cfRequest(apiBase, cert.apiToken, `/zones/${cert.zoneId}`, fetchImpl, timeoutMs);
427
+ zone = byId.ok && byId.success ? byId.result : null;
428
+ if (!zone) return { ...ident, detail: '按 ID 读取 zone 失败' };
429
+ } else if (scope.zoneName) {
430
+ return {
431
+ ...ident,
432
+ state: 'zone-scoped-other',
433
+ blocking: true,
434
+ hint: CREDENTIAL_STATE_HINT['zone-scoped-other'],
435
+ zoneName: scope.zoneName,
436
+ zoneStatus: scope.zoneStatus,
437
+ detail: `证书授权的是 ${scope.zoneName},不是 ${baseDomain}。`
438
+ + `重新执行 cloudflared tunnel login,并在浏览器里选择 ${baseDomain}。`,
439
+ };
440
+ } else if (scope.zoneGone) {
441
+ return {
442
+ ...ident,
443
+ state: 'stale-zone',
444
+ blocking: true,
445
+ hint: CREDENTIAL_STATE_HINT['stale-zone'],
446
+ detail: `证书里的 zone ${String(cert.zoneId || '').slice(0, 8)}… 在 Cloudflare 上已不存在`
447
+ + `(域名删掉后重新接入会换 zoneID)。重新执行 cloudflared tunnel login 即可换新证书。`,
448
+ };
449
+ } else {
450
+ return {
451
+ ...ident,
452
+ state: 'zone-missing',
453
+ blocking: true,
454
+ hint: CREDENTIAL_STATE_HINT['zone-missing'],
455
+ detail: `证书账号 ${scope.accountName || String(cert.accountId || '未知').slice(0, 8)} 下没有 ${baseDomain}。`
456
+ + '要么用持有该域名的账号重新授权,要么把域名加到当前账号再重试。',
457
+ };
458
+ }
459
+ }
460
+
461
+ const zoneAccountId = zone.account?.id || null;
462
+ const accountMismatch = Boolean(cert.accountId && zoneAccountId && cert.accountId !== zoneAccountId);
463
+ const staleZone = Boolean(cert.zoneId && zone.id && cert.zoneId !== zone.id);
464
+ let accountName = null;
465
+ if (zoneAccountId) {
466
+ const acc = await cfRequest(apiBase, cert.apiToken, `/accounts/${zoneAccountId}`, fetchImpl, timeoutMs);
467
+ if (acc.ok && acc.success) accountName = acc.result?.name || null;
468
+ }
469
+ const common = {
470
+ ...base,
471
+ accountName,
472
+ zoneName: zone.name || baseDomain,
473
+ zoneStatus: zone.status || null,
474
+ certAccountId: cert.accountId || null,
475
+ certAccountName: accountName,
476
+ certZoneName: zone.name || null,
477
+ zoneId: zone.id || null,
478
+ };
479
+ if (accountMismatch) {
480
+ return {
481
+ ...common,
482
+ state: 'account-mismatch',
483
+ blocking: true,
484
+ hint: CREDENTIAL_STATE_HINT['account-mismatch'],
485
+ detail: `证书账号 ${String(cert.accountId).slice(0, 8)}…,域名归属 ${String(zoneAccountId).slice(0, 8)}…`,
486
+ };
487
+ }
488
+ if (staleZone) {
489
+ return { ...common, state: 'stale-zone', blocking: true, hint: CREDENTIAL_STATE_HINT['stale-zone'] };
490
+ }
491
+ if (zone.status === 'moved') {
492
+ return { ...common, state: 'zone-moved', blocking: true, hint: CREDENTIAL_STATE_HINT['zone-moved'] };
493
+ }
494
+ return { ...common, state: 'ok', blocking: false, hint: CREDENTIAL_STATE_HINT.ok };
495
+ }
496
+
497
+ /** 预检结论 → 是否阻断(供不关心细节的调用方使用)。 */
498
+ export function isCredentialBlocking(verdict) {
499
+ return Boolean(verdict && BLOCKING_STATES.has(verdict.state));
500
+ }
501
+
246
502
  /** 稳定摘要,用于把「同一份 zone」与「另一份 zone」区分开(不写 ID,只做等值比较)。 */
247
503
  export function zoneFingerprint(zone) {
248
504
  const src = `${zone?.accountId || ''}|${zone?.zoneId || ''}|${zone?.zoneName || ''}`;