dsh-mobile-ios 0.2.17 → 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.
- package/README.md +27 -0
- package/entries/plugin.mjs +25 -51
- package/entries/sidecar.mjs +12 -31
- package/lib/client.js +146 -13
- package/package.json +2 -2
- package/src/cloudflare.mjs +40 -3
- package/src/provision-local.mjs +361 -38
- package/src/provision-select.mjs +105 -0
- package/src/rest.mjs +35 -0
- package/src/tunnel-error.mjs +91 -0
- package/src/tunnel-state.mjs +122 -0
- package/src/zone-health.mjs +179 -0
package/src/rest.mjs
CHANGED
|
@@ -101,6 +101,7 @@ const DESKTOP_CORS_PATHS = [
|
|
|
101
101
|
/^\/mobile\/v1\/tunnel\/provision$/,
|
|
102
102
|
/^\/mobile\/v1\/tunnel\/install-cloudflared$/,
|
|
103
103
|
/^\/mobile\/v1\/tunnel\/recheck-dns$/,
|
|
104
|
+
/^\/mobile\/v1\/tunnel\/reset$/,
|
|
104
105
|
/^\/mobile\/v1\/plugin\/self-update$/,
|
|
105
106
|
];
|
|
106
107
|
|
|
@@ -263,6 +264,9 @@ export function createRestRouter({ core, pairing, host, tickets, config = {}, lo
|
|
|
263
264
|
// 面板据此给**不同**的修法,而不是一律「等 NS 生效」。
|
|
264
265
|
zone: prov?.zone ?? null,
|
|
265
266
|
warning: prov?.warning ?? null,
|
|
267
|
+
// 凭据预检结论(local 形态才有):state=障碍类型,blocking=是否**确定**不可写。
|
|
268
|
+
// 面板因此能在用户点「开启远程」之前就提示「登录的账号不对」,而不是等写 DNS 才崩。
|
|
269
|
+
credentials: prov?.credentials ?? null,
|
|
266
270
|
// 面板据此决定是否显示「自动安装 cloudflared」入口:仅在缺失且有官方构建时为 true。
|
|
267
271
|
canAutoInstall: base.executable === 'missing' && !!resolveAsset({}),
|
|
268
272
|
};
|
|
@@ -572,6 +576,34 @@ export function createRestRouter({ core, pairing, host, tickets, config = {}, lo
|
|
|
572
576
|
}, DESKTOP_CORS);
|
|
573
577
|
});
|
|
574
578
|
|
|
579
|
+
/**
|
|
580
|
+
* 重置本机的固定地址状态(面板兜底动作)。
|
|
581
|
+
*
|
|
582
|
+
* 存在的理由:状态文件被跨机拷贝、或损坏到无法自愈时,用户原来只能手删
|
|
583
|
+
* ~/.dsh/mobile-access/tunnel-named.json——那是「只有开发者才会的操作」。
|
|
584
|
+
* 这里把「清本地状态」变成一次点击,并明确边界:
|
|
585
|
+
* · 只清本机状态与 ingress 配置,**不删** cert.pem;
|
|
586
|
+
* · **不删** Cloudflare 上的隧道与 DNS 记录(用户账号资产,删了不可恢复);
|
|
587
|
+
* · 幂等:重复点不会报错。
|
|
588
|
+
* 回环-only:管理面动作,与开通/启停同一道门。
|
|
589
|
+
*/
|
|
590
|
+
route('POST', /^\/mobile\/v1\/tunnel\/reset$/, async (ctx) => {
|
|
591
|
+
loopbackOnly(ctx, '重置固定地址只允许在主机本机操作');
|
|
592
|
+
const prov = config.tunnelProvisioner;
|
|
593
|
+
if (typeof prov?.reset !== 'function') {
|
|
594
|
+
throw fail(4021, '当前主机没有可重置的固定地址状态', { method: 'tunnel.reset' });
|
|
595
|
+
}
|
|
596
|
+
// 先停隧道:进程还挂着旧配置时删配置,下一轮重拉会读到一个不存在的 ingress
|
|
597
|
+
try {
|
|
598
|
+
await config.tunnel?.stop?.();
|
|
599
|
+
} catch (err) {
|
|
600
|
+
log(`rest tunnel reset 前停止隧道失败(继续重置)${err?.message || err}`);
|
|
601
|
+
}
|
|
602
|
+
const result = await prov.reset();
|
|
603
|
+
log(`rest tunnel reset 完成 hadState=${result.hadState} removed=${(result.removed || []).join(',') || '(无文件)'}`);
|
|
604
|
+
return send(ctx.res, 200, { ...result, status: tunnelSnapshot() }, DESKTOP_CORS);
|
|
605
|
+
});
|
|
606
|
+
|
|
575
607
|
/**
|
|
576
608
|
* 插件自更新(不依赖宿主 pluginManager)。
|
|
577
609
|
*
|
|
@@ -909,6 +941,9 @@ export function createRestRouter({ core, pairing, host, tickets, config = {}, lo
|
|
|
909
941
|
code,
|
|
910
942
|
message: err.message || meta.message,
|
|
911
943
|
...(err.extra?.detail ? { detail: err.extra.detail } : {}),
|
|
944
|
+
// 机器可读的失败原因(credentials / zone / conflict …):面板据此决定
|
|
945
|
+
// 「给登录指引」还是「给 NS 修法」,不靠中文字符串匹配。
|
|
946
|
+
...(err.extra?.reason ? { reason: err.extra.reason } : {}),
|
|
912
947
|
traceId,
|
|
913
948
|
...(err.extra?.retryAfterMs ? { retryAfterMs: err.extra.retryAfterMs } : {}),
|
|
914
949
|
...(err.extra?.attemptsRemaining !== undefined ? { retryAfterMs: err.extra.retryAfterMs, attemptsRemaining: err.extra.attemptsRemaining } : {}),
|
|
@@ -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
|
+
}
|
package/src/zone-health.mjs
CHANGED
|
@@ -243,6 +243,185 @@ 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
|
+
'account-mismatch': '证书所属账号与域名所在账号不是同一个',
|
|
258
|
+
'stale-zone': 'cert.pem 指向的 zone 已失效(域名可能被删后重新接入)',
|
|
259
|
+
'zone-moved': '域名已被另一个 Cloudflare 账号接管',
|
|
260
|
+
unknown: '暂时查不到凭据的可用性(网络不可达)',
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
/** 这些状态是「确定不可用」:可以放心在写 DNS 之前拦下,并给出对应修法。 */
|
|
264
|
+
const BLOCKING_STATES = new Set(['missing', 'forbidden', 'zone-missing', 'account-mismatch', 'stale-zone', 'zone-moved']);
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* 带 HTTP 状态的只读请求(cfGet 只关心 result,这里需要区分 403 与「断网」)。
|
|
268
|
+
* 任何异常都收敛成一个对象,绝不抛。
|
|
269
|
+
*/
|
|
270
|
+
async function cfRequest(apiBase, apiToken, pathname, fetchImpl, timeoutMs = 4000) {
|
|
271
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
272
|
+
const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
|
|
273
|
+
try {
|
|
274
|
+
const res = await fetchImpl(`${apiBase}${pathname}`, {
|
|
275
|
+
headers: { Authorization: `Bearer ${apiToken}` },
|
|
276
|
+
...(controller ? { signal: controller.signal } : {}),
|
|
277
|
+
});
|
|
278
|
+
const text = await res.text();
|
|
279
|
+
let payload = null;
|
|
280
|
+
try { payload = text ? JSON.parse(text) : null; } catch { payload = null; }
|
|
281
|
+
return {
|
|
282
|
+
status: res.status,
|
|
283
|
+
ok: Boolean(res.ok),
|
|
284
|
+
success: payload?.success === true,
|
|
285
|
+
result: payload?.result ?? null,
|
|
286
|
+
errors: payload?.errors ?? [],
|
|
287
|
+
reached: true,
|
|
288
|
+
};
|
|
289
|
+
} catch (err) {
|
|
290
|
+
return { status: 0, ok: false, success: false, result: null, errors: [], reached: false, error: err?.message || String(err) };
|
|
291
|
+
} finally {
|
|
292
|
+
if (timer) clearTimeout(timer);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* 开通前凭据预检:**这本 cert.pem 能不能写这个域名的 DNS**。
|
|
298
|
+
*
|
|
299
|
+
* 为什么必须在写 DNS 之前问:cross-account 的证书能列隧道、能建隧道(账号级权限正常),
|
|
300
|
+
* 只有写 DNS 会失败。等 CLI 报错时,用户已经拿到一个「隧道正常」的假象,
|
|
301
|
+
* 而错误又被截断成一行命令回显——这正是 2026-11-21 的现场。
|
|
302
|
+
*
|
|
303
|
+
* 判定口径(宁可放过,不可误杀):
|
|
304
|
+
* · 403 / success:false → 确定无权限(forbidden)
|
|
305
|
+
* · 200 且 zone 列表为空 → 这个 token 看不到该域名(zone-missing)
|
|
306
|
+
* · zone.account 与证书 account 不同 → account-mismatch
|
|
307
|
+
* · zone.id 与证书 zoneID 不同 → 证书指向旧 zone(stale-zone)
|
|
308
|
+
* · zone.status = moved → 域名被另一账号接管(zone-moved)
|
|
309
|
+
* · 断网/超时/无 token/解析失败 → unknown(不拦,交给 CLI 报错兜底)
|
|
310
|
+
*
|
|
311
|
+
* @returns {Promise<{state: string, blocking: boolean, hint: string|null,
|
|
312
|
+
* accountName: string|null, zoneName: string|null, zoneStatus: string|null,
|
|
313
|
+
* certAccountId: string|null, zoneId: string|null, detail: string|null}>}
|
|
314
|
+
*/
|
|
315
|
+
export async function verifyCertAccess({
|
|
316
|
+
homeDir = os.homedir(),
|
|
317
|
+
baseDomain,
|
|
318
|
+
fetchImpl = globalThis.fetch,
|
|
319
|
+
apiBase = CF_API_BASE,
|
|
320
|
+
timeoutMs = 4000,
|
|
321
|
+
} = {}) {
|
|
322
|
+
const base = {
|
|
323
|
+
state: 'unknown',
|
|
324
|
+
blocking: false,
|
|
325
|
+
hint: CREDENTIAL_STATE_HINT.unknown,
|
|
326
|
+
accountName: null,
|
|
327
|
+
zoneName: baseDomain || null,
|
|
328
|
+
zoneStatus: null,
|
|
329
|
+
certAccountId: null,
|
|
330
|
+
zoneId: null,
|
|
331
|
+
detail: null,
|
|
332
|
+
};
|
|
333
|
+
const certFile = path.join(homeDir, '.cloudflared', 'cert.pem');
|
|
334
|
+
if (!fs.existsSync(certFile)) {
|
|
335
|
+
return { ...base, state: 'missing', blocking: true, hint: CREDENTIAL_STATE_HINT.missing, detail: '没有找到 cert.pem' };
|
|
336
|
+
}
|
|
337
|
+
if (typeof fetchImpl !== 'function') return { ...base, detail: '当前运行时不支持网络请求' };
|
|
338
|
+
|
|
339
|
+
const cert = readZoneCert({ homeDir });
|
|
340
|
+
if (!cert) {
|
|
341
|
+
return { ...base, state: 'unreadable', blocking: false, hint: CREDENTIAL_STATE_HINT.unreadable, detail: 'cert.pem 结构无法解析' };
|
|
342
|
+
}
|
|
343
|
+
if (!cert.apiToken) {
|
|
344
|
+
return {
|
|
345
|
+
...base,
|
|
346
|
+
state: 'no-token',
|
|
347
|
+
blocking: false,
|
|
348
|
+
hint: CREDENTIAL_STATE_HINT['no-token'],
|
|
349
|
+
certAccountId: cert.accountId || null,
|
|
350
|
+
detail: '证书里没有 apiToken,无法预检',
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
if (!baseDomain) return { ...base, detail: '未配置固定地址域名' };
|
|
354
|
+
|
|
355
|
+
const list = await cfRequest(apiBase, cert.apiToken, `/zones?name=${encodeURIComponent(baseDomain)}`, fetchImpl, timeoutMs);
|
|
356
|
+
if (!list.reached) return { ...base, certAccountId: cert.accountId || null, detail: list.error || null };
|
|
357
|
+
if (!list.ok || !list.success) {
|
|
358
|
+
// 403 是确定无权限;其余 4xx/5xx 说不清,交给 CLI
|
|
359
|
+
if (list.status === 403 || list.status === 401) {
|
|
360
|
+
return {
|
|
361
|
+
...base,
|
|
362
|
+
state: 'forbidden',
|
|
363
|
+
blocking: true,
|
|
364
|
+
hint: CREDENTIAL_STATE_HINT.forbidden,
|
|
365
|
+
certAccountId: cert.accountId || null,
|
|
366
|
+
detail: `HTTP ${list.status}`,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
return { ...base, certAccountId: cert.accountId || null, detail: `HTTP ${list.status}` };
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const zones = Array.isArray(list.result) ? list.result : [];
|
|
373
|
+
const zone = zones.find((z) => z && String(z.name).toLowerCase() === baseDomain.toLowerCase()) || null;
|
|
374
|
+
if (!zone) {
|
|
375
|
+
// 空列表 = 这个 token 看不到该域名(zone 范围的 token 只列得出自己那把 zone)
|
|
376
|
+
return {
|
|
377
|
+
...base,
|
|
378
|
+
state: 'zone-missing',
|
|
379
|
+
blocking: true,
|
|
380
|
+
hint: CREDENTIAL_STATE_HINT['zone-missing'],
|
|
381
|
+
certAccountId: cert.accountId || null,
|
|
382
|
+
detail: `证书指向 zone ${String(cert.zoneId || '未知').slice(0, 8)}…,但它已不在任何可访问的 ${baseDomain} 之下`,
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const zoneAccountId = zone.account?.id || null;
|
|
387
|
+
const accountMismatch = Boolean(cert.accountId && zoneAccountId && cert.accountId !== zoneAccountId);
|
|
388
|
+
const staleZone = Boolean(cert.zoneId && zone.id && cert.zoneId !== zone.id);
|
|
389
|
+
let accountName = null;
|
|
390
|
+
if (zoneAccountId) {
|
|
391
|
+
const acc = await cfRequest(apiBase, cert.apiToken, `/accounts/${zoneAccountId}`, fetchImpl, timeoutMs);
|
|
392
|
+
if (acc.ok && acc.success) accountName = acc.result?.name || null;
|
|
393
|
+
}
|
|
394
|
+
const common = {
|
|
395
|
+
...base,
|
|
396
|
+
accountName,
|
|
397
|
+
zoneName: zone.name || baseDomain,
|
|
398
|
+
zoneStatus: zone.status || null,
|
|
399
|
+
certAccountId: cert.accountId || null,
|
|
400
|
+
zoneId: zone.id || null,
|
|
401
|
+
};
|
|
402
|
+
if (accountMismatch) {
|
|
403
|
+
return {
|
|
404
|
+
...common,
|
|
405
|
+
state: 'account-mismatch',
|
|
406
|
+
blocking: true,
|
|
407
|
+
hint: CREDENTIAL_STATE_HINT['account-mismatch'],
|
|
408
|
+
detail: `证书账号 ${String(cert.accountId).slice(0, 8)}…,域名归属 ${String(zoneAccountId).slice(0, 8)}…`,
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
if (staleZone) {
|
|
412
|
+
return { ...common, state: 'stale-zone', blocking: true, hint: CREDENTIAL_STATE_HINT['stale-zone'] };
|
|
413
|
+
}
|
|
414
|
+
if (zone.status === 'moved') {
|
|
415
|
+
return { ...common, state: 'zone-moved', blocking: true, hint: CREDENTIAL_STATE_HINT['zone-moved'] };
|
|
416
|
+
}
|
|
417
|
+
return { ...common, state: 'ok', blocking: false, hint: CREDENTIAL_STATE_HINT.ok };
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** 预检结论 → 是否阻断(供不关心细节的调用方使用)。 */
|
|
421
|
+
export function isCredentialBlocking(verdict) {
|
|
422
|
+
return Boolean(verdict && BLOCKING_STATES.has(verdict.state));
|
|
423
|
+
}
|
|
424
|
+
|
|
246
425
|
/** 稳定摘要,用于把「同一份 zone」与「另一份 zone」区分开(不写 ID,只做等值比较)。 */
|
|
247
426
|
export function zoneFingerprint(zone) {
|
|
248
427
|
const src = `${zone?.accountId || ''}|${zone?.zoneId || ''}|${zone?.zoneName || ''}`;
|