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/provision-local.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
52
|
-
|
|
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,94 @@ 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
|
+
zoneName: verdict.zoneName ?? null,
|
|
181
|
+
zoneStatus: verdict.zoneStatus ?? null,
|
|
182
|
+
checkedAt: this._auth?.at ? new Date(this._auth.at).toISOString() : null,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
#certFingerprint() {
|
|
187
|
+
const file = path.join(this.homeDir, '.cloudflared', 'cert.pem');
|
|
188
|
+
try {
|
|
189
|
+
const st = fs.statSync(file);
|
|
190
|
+
return `${st.size}:${Math.round(st.mtimeMs)}`;
|
|
191
|
+
} catch {
|
|
192
|
+
return 'none';
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* 凭据预检:当前 cert.pem 能不能管理 baseDomain。
|
|
198
|
+
*
|
|
199
|
+
* 只在**要写 Cloudflare** 的路径上作为硬门槛;日常启动命中缓存时只用于提示,
|
|
200
|
+
* 绝不因为「账号对不上」去拦一个本来能跑的隧道(cloudflared 运行时只需要
|
|
201
|
+
* credentials 文件,不需要 cert.pem)。
|
|
202
|
+
*/
|
|
203
|
+
async checkCredentials({ force = false } = {}) {
|
|
204
|
+
if (typeof this.verifyAccess !== 'function') {
|
|
205
|
+
return { state: 'unknown', blocking: false, hint: null, accountName: null, checkedAt: null };
|
|
206
|
+
}
|
|
207
|
+
const fp = this.#certFingerprint();
|
|
208
|
+
const now = Date.now();
|
|
209
|
+
if (!force && this._auth && this._auth.fp === fp && now - this._auth.at < AUTH_TTL_MS) {
|
|
210
|
+
return this.#authSnapshot(this._auth.verdict);
|
|
211
|
+
}
|
|
212
|
+
let verdict = null;
|
|
213
|
+
try {
|
|
214
|
+
verdict = await this.verifyAccess({ homeDir: this.homeDir, baseDomain: this.baseDomain });
|
|
215
|
+
} catch (err) {
|
|
216
|
+
verdict = { state: 'unknown', blocking: false, hint: null, detail: err?.message || String(err) };
|
|
217
|
+
}
|
|
218
|
+
if (!verdict || typeof verdict !== 'object') verdict = { state: 'unknown', blocking: false, hint: null };
|
|
219
|
+
this._auth = { at: now, fp, verdict };
|
|
220
|
+
if (verdict.blocking) this.log(`tunnel 凭据预检未通过(${verdict.state}):${verdict.hint || ''}`);
|
|
221
|
+
return this.#authSnapshot(verdict);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** 凭据不可用时抛出的统一错误(带可执行修法)。 */
|
|
225
|
+
#credentialError(verdict) {
|
|
226
|
+
const hint = verdict?.hint || '当前登录的 Cloudflare 账号无法管理这个域名';
|
|
227
|
+
const exe = findCloudflared(this.executable, this.env) || findCloudflared('auto', this.env) || this.executable;
|
|
228
|
+
const account = verdict?.accountName ? `(当前证书属于 ${verdict.accountName})` : '';
|
|
229
|
+
return fail(4021, `${hint}${account}`, {
|
|
230
|
+
detail: `在这台电脑的终端执行:${exe} tunnel login,`
|
|
231
|
+
+ `在浏览器里选择持有 ${this.baseDomain} 的账号完成授权(会覆盖 ~/.cloudflared/cert.pem),`
|
|
232
|
+
+ '然后回到面板重新点「开启远程」。重装插件、重启宿主、改 NS 都不能替代这一步。',
|
|
233
|
+
reason: 'credentials',
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
|
|
161
237
|
get notConfiguredMessage() {
|
|
162
238
|
return '主机还没有登录 Cloudflare';
|
|
163
239
|
}
|
|
@@ -235,7 +311,10 @@ export class LocalProvisioner {
|
|
|
235
311
|
|
|
236
312
|
status() {
|
|
237
313
|
const s = this.state;
|
|
238
|
-
|
|
314
|
+
// credentials 是「预检结论」,未预检过就是 null——面板据此决定要不要提示
|
|
315
|
+
// 「账号对不上」。它不是开通状态的替代品:隧道能跑 ≠ 能改写 DNS。
|
|
316
|
+
const credentials = this.credentials;
|
|
317
|
+
if (!s) return { kind: 'local', provisioned: false, hostname: null, url: null, tunnelId: null, credentials };
|
|
239
318
|
return {
|
|
240
319
|
kind: 'local',
|
|
241
320
|
provisioned: true,
|
|
@@ -250,6 +329,7 @@ export class LocalProvisioner {
|
|
|
250
329
|
// 面板据此给出**不同**的修法,而不是一律「等 NS 生效」。
|
|
251
330
|
zone: s.zone ?? this._zone ?? null,
|
|
252
331
|
warning: dnsWarningFor(s),
|
|
332
|
+
credentials,
|
|
253
333
|
createdAt: s.createdAt ?? null,
|
|
254
334
|
updatedAt: s.updatedAt ?? null,
|
|
255
335
|
};
|
|
@@ -263,8 +343,11 @@ export class LocalProvisioner {
|
|
|
263
343
|
* 于是 NS 改好了也永远停在「解析异常」,只能删状态文件才恢复(自锁死)。
|
|
264
344
|
*/
|
|
265
345
|
async recheckDns() {
|
|
346
|
+
// 顺手强制刷一次凭据预检:用户改完账号跑 login 后,面板点「重新检测」就应
|
|
347
|
+
// 立刻看到结论变化(cert.pem 指纹变了会自动失效缓存,这里再加一层强制)。
|
|
348
|
+
const credentials = await this.checkCredentials({ force: true });
|
|
266
349
|
const s = this.state;
|
|
267
|
-
if (!s?.hostname) return { provisioned: false, ok: false, tampered: false, warning: null, publicNs: [], zone: null };
|
|
350
|
+
if (!s?.hostname) return { provisioned: false, ok: false, tampered: false, warning: null, publicNs: [], zone: null, credentials };
|
|
268
351
|
const { verdict, zone } = await this.#evaluate(s.hostname, s.tunnelId);
|
|
269
352
|
const next = {
|
|
270
353
|
...s,
|
|
@@ -285,9 +368,43 @@ export class LocalProvisioner {
|
|
|
285
368
|
warning: dnsWarningFor(next),
|
|
286
369
|
checkedAt: next.dnsCheckedAt,
|
|
287
370
|
zone,
|
|
371
|
+
credentials,
|
|
288
372
|
};
|
|
289
373
|
}
|
|
290
374
|
|
|
375
|
+
/**
|
|
376
|
+
* 清空本机的固定地址状态(面板「重置本机隧道状态」)。
|
|
377
|
+
*
|
|
378
|
+
* 用途:状态文件被跨机拷贝、或结构损坏到无法自愈时,给用户一条不用手改文件系统的出路。
|
|
379
|
+
* 边界(刻意保守):
|
|
380
|
+
* · 只删**本模块自己写的**两个文件(状态 + ingress 配置),不碰 cert.pem;
|
|
381
|
+
* · 不删 Cloudflare 上的隧道与 DNS 记录——那是用户账号资产,删了不可恢复;
|
|
382
|
+
* · 幂等:反复调用都返回成功,不会因为文件已不在而报错。
|
|
383
|
+
*/
|
|
384
|
+
async reset() {
|
|
385
|
+
const removed = [];
|
|
386
|
+
const targets = [this.stateFile, this.state?.configFile || this.configFile];
|
|
387
|
+
for (const file of targets) {
|
|
388
|
+
if (!file) continue;
|
|
389
|
+
try {
|
|
390
|
+
if (fs.statSync(file).isFile()) {
|
|
391
|
+
fs.unlinkSync(file);
|
|
392
|
+
removed.push(path.basename(file));
|
|
393
|
+
}
|
|
394
|
+
} catch {
|
|
395
|
+
/* 不存在即目标状态 */
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
const hadState = Boolean(this.state?.hostname);
|
|
399
|
+
if (hadState) {
|
|
400
|
+
this.log(`tunnel 已重置本机固定地址状态(原地址 ${this.state.hostname},Cloudflare 侧的隧道与记录未删除)`);
|
|
401
|
+
}
|
|
402
|
+
this._state = null;
|
|
403
|
+
this._auth = null;
|
|
404
|
+
this._zone = null;
|
|
405
|
+
return { reset: true, hadState, removed, hostname: null, provisioned: false };
|
|
406
|
+
}
|
|
407
|
+
|
|
291
408
|
async #exec(args) {
|
|
292
409
|
const { stdout, stderr } = await execFileAsync(this.#resolveExecutable(), args, {
|
|
293
410
|
timeout: CLI_TIMEOUT_MS,
|
|
@@ -339,9 +456,54 @@ export class LocalProvisioner {
|
|
|
339
456
|
return list.some((t) => isLiveTunnel(t) && t.id === tunnelId);
|
|
340
457
|
}
|
|
341
458
|
|
|
459
|
+
/** 状态里记的地址是否仍属当前域名(运营换 baseDomain 后旧地址要重写)。 */
|
|
460
|
+
#hostnameBelongs(hostname) {
|
|
461
|
+
const h = String(hostname || '').toLowerCase();
|
|
462
|
+
return h.endsWith(`.${this.baseDomain}`) && h.length > this.baseDomain.length + 1;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** 写状态时顺带记下本机身份:下次从别处拷来的状态就能被识别出来。 */
|
|
466
|
+
#withMachine(state) {
|
|
467
|
+
const m = this.machine;
|
|
468
|
+
if (!m) return state;
|
|
469
|
+
const prev = state?.machine;
|
|
470
|
+
if (prev?.id === m.id && prev?.hostname === m.hostname) return state;
|
|
471
|
+
return { ...state, machine: { id: m.id, hostname: m.hostname } };
|
|
472
|
+
}
|
|
473
|
+
|
|
342
474
|
async ensure({ port, force = false } = {}) {
|
|
343
475
|
if (!Number.isInteger(port) || port <= 0) throw fail(4400, '开通隧道需要有效端口');
|
|
344
|
-
|
|
476
|
+
const account = readZoneCert({ homeDir: this.homeDir })?.accountId || null;
|
|
477
|
+
// 记下进入本次调用前的地址:跨机状态/凭据缺失会把 cached 清空,
|
|
478
|
+
// 用这个变量才能如实回答「地址有没有变」(changed 供调用方记日志/判断漂移)。
|
|
479
|
+
const previousHostname = this.state?.hostname || null;
|
|
480
|
+
let cached = this.state;
|
|
481
|
+
let rebuild = false;
|
|
482
|
+
|
|
483
|
+
// ── 0) 状态归属校验(跨机拷贝是「分发后分配不出地址」的第二大来源)──
|
|
484
|
+
// · machine.id 不是本机 → 整份作废,重新分配地址(不能对外宣称别人的地址);
|
|
485
|
+
// · tunnel 凭据文件不在了 → 状态在本机跑不起来,同样重新分配。
|
|
486
|
+
if (cached && isForeignState(cached, this.machine)) {
|
|
487
|
+
this.log(`tunnel 状态来自另一台电脑(${String(cached.machine?.id || '').slice(0, 8)}… ≠ ${String(this.machine?.id || '').slice(0, 8)}…),重新分配固定地址`);
|
|
488
|
+
cached = null;
|
|
489
|
+
} else if (cached?.tunnelId && !hasLocalCredentials(cached)) {
|
|
490
|
+
this.log('tunnel 状态里的 tunnel 凭据文件已不存在,重新分配固定地址');
|
|
491
|
+
cached = null;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// 域名变更(运营换 baseDomain):子域可沿用,但要按新域名重写地址与记录
|
|
495
|
+
if (cached?.hostname && !this.#hostnameBelongs(cached.hostname)) {
|
|
496
|
+
if (cached.subdomain && isValidLabel(cached.subdomain)) {
|
|
497
|
+
this.log(`tunnel 记录的地址 ${cached.hostname} 不属于当前域名 ${this.baseDomain},按原前缀重写`);
|
|
498
|
+
cached = { ...cached, hostname: `${cached.subdomain}.${this.baseDomain}`, dnsOk: null, zone: null };
|
|
499
|
+
rebuild = true;
|
|
500
|
+
} else {
|
|
501
|
+
this.log('tunnel 记录的地址与当前域名不符且前缀不可用,重新分配');
|
|
502
|
+
cached = null;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// ── 1) 账号可能变过(域名迁到另一个 Cloudflare 账号后重新 login 就是这种情况)──
|
|
345
507
|
// 旧 tunnel 属于上一个账号,继续拿它的 id 去 route dns 只会得到 "tunnel not found",
|
|
346
508
|
// 或者更糟——静默写不进去却以为自己开通成功。真判定有两条线:
|
|
347
509
|
// 1) 状态文件记了 account 且与当前 cert 不一致 → 确知换了账号;
|
|
@@ -350,9 +512,6 @@ export class LocalProvisioner {
|
|
|
350
512
|
// 注意线 2) 只在「不知道归属」时才走:两种情况都清楚了还去拉子进程,会让面板每次
|
|
351
513
|
// 点开通都多几百毫秒(tunnel-named 里「重复开通不再调 CLI」这条契约就是拦这个的)。
|
|
352
514
|
// 账号变了就当新装:重建隧道、保留同一个子域(地址不变,用户不用重新记/重新扫码)。
|
|
353
|
-
const account = readZoneCert({ homeDir: this.homeDir })?.accountId || null;
|
|
354
|
-
let cached = this.state;
|
|
355
|
-
let rebuild = false;
|
|
356
515
|
if (cached?.tunnelId) {
|
|
357
516
|
const knownMismatch = Boolean(cached.account && account && cached.account !== account);
|
|
358
517
|
// 只有「当前证书能读出账号,但状态文件没记」才算归属未知。反过来若连证书都解析
|
|
@@ -381,23 +540,29 @@ export class LocalProvisioner {
|
|
|
381
540
|
// 校验通过:把归属记下来。否则每次开通都因为「不知道归谁」再问一遍 Cloudflare,
|
|
382
541
|
// 白白多一个子进程的延迟(这条路径就是给老状态文件补账的)。
|
|
383
542
|
cached = { ...cached, account };
|
|
384
|
-
this._state = cached;
|
|
385
|
-
writeState(this.stateFile,
|
|
543
|
+
this._state = this.#withMachine(cached);
|
|
544
|
+
writeState(this.stateFile, this._state);
|
|
386
545
|
}
|
|
387
546
|
}
|
|
388
547
|
// 走完整开通:缓存里的 port/hostname 看着都可用,但它们描述的是上一个账号的隧道,
|
|
389
548
|
// 跳过缓存才不会「解析通了就以为没事」。
|
|
390
549
|
if (!force && !rebuild && cached?.hostname && cached.port === port) {
|
|
550
|
+
// 老状态文件没有 machine 字段:命中缓存时顺手认领(一次性,之后就是本机状态)
|
|
551
|
+
if (!cached.machine && this.machine) {
|
|
552
|
+
cached = this.#withMachine(cached);
|
|
553
|
+
this._state = cached;
|
|
554
|
+
writeState(this.stateFile, cached);
|
|
555
|
+
}
|
|
391
556
|
// 与 BaseProvisioner 同策略:没确认过就现场验一次(含防篡改评估)
|
|
392
557
|
if (cached.dnsOk !== true) {
|
|
393
558
|
const { verdict, zone } = await this.#evaluate(cached.hostname, cached.tunnelId);
|
|
394
|
-
const next = {
|
|
559
|
+
const next = this.#withMachine({
|
|
395
560
|
...cached,
|
|
396
561
|
dnsOk: verdict.ok,
|
|
397
562
|
dnsTampered: verdict.tampered,
|
|
398
563
|
dnsCheckedAt: new Date().toISOString(),
|
|
399
564
|
zone,
|
|
400
|
-
};
|
|
565
|
+
});
|
|
401
566
|
this._state = next;
|
|
402
567
|
writeState(this.stateFile, next);
|
|
403
568
|
return {
|
|
@@ -433,7 +598,7 @@ export class LocalProvisioner {
|
|
|
433
598
|
hostname: cached.hostname,
|
|
434
599
|
port,
|
|
435
600
|
}), { mode: 0o600 });
|
|
436
|
-
const next = { ...cached, port, updatedAt: new Date().toISOString() };
|
|
601
|
+
const next = this.#withMachine({ ...cached, port, updatedAt: new Date().toISOString() });
|
|
437
602
|
this._state = next;
|
|
438
603
|
writeState(this.stateFile, next);
|
|
439
604
|
return {
|
|
@@ -447,6 +612,13 @@ export class LocalProvisioner {
|
|
|
447
612
|
};
|
|
448
613
|
}
|
|
449
614
|
|
|
615
|
+
// ── 以下每一步都要写 Cloudflare:先在本地把凭据问清楚 ──
|
|
616
|
+
// 这一步就是 2026-11-21 事故的正解:跨账号的 cert.pem 能列/建隧道,只有写 DNS 才失败,
|
|
617
|
+
// 等 CLI 报错时用户已经拿到「隧道正常」的假象。预检把失败提前到**任何写入之前**,
|
|
618
|
+
// 并直接说清「用哪个账号重跑 login」。网络不可达时结论是 unknown,不拦(降级原则)。
|
|
619
|
+
const auth = await this.checkCredentials();
|
|
620
|
+
if (auth.blocking) throw this.#credentialError(auth);
|
|
621
|
+
|
|
450
622
|
const installationId = cached?.installationId || crypto.randomBytes(16).toString('hex');
|
|
451
623
|
const label = cached?.subdomain || deriveSubdomain(this.seed || installationId, { prefix: this.prefix });
|
|
452
624
|
if (!isValidLabel(label)) throw fail(4400, `派生出的子域不合法:${label}`);
|
|
@@ -459,7 +631,23 @@ export class LocalProvisioner {
|
|
|
459
631
|
if (found) {
|
|
460
632
|
tunnelId = found.id;
|
|
461
633
|
} else {
|
|
462
|
-
|
|
634
|
+
let out;
|
|
635
|
+
try {
|
|
636
|
+
out = await this.run(['tunnel', 'create', label]);
|
|
637
|
+
} catch (err) {
|
|
638
|
+
// 建隧道也会因为凭据/账号问题失败:同样把真实原因透传出来,不要只留一行命令回显
|
|
639
|
+
const explained = explainTunnelFailure(err, {
|
|
640
|
+
baseDomain: this.baseDomain,
|
|
641
|
+
operation: 'create-tunnel',
|
|
642
|
+
accountName: auth.accountName || null,
|
|
643
|
+
exe: this.#exeLabel(),
|
|
644
|
+
});
|
|
645
|
+
this.log(`tunnel 创建隧道失败 ${explained.reason} ${explained.message}`);
|
|
646
|
+
throw fail(4500, explained.message, {
|
|
647
|
+
detail: explained.detail,
|
|
648
|
+
reason: explained.reason,
|
|
649
|
+
});
|
|
650
|
+
}
|
|
463
651
|
const m = UUID_PATTERN.exec(out);
|
|
464
652
|
if (!m) throw fail(4500, 'cloudflared 没有返回 tunnel id', { detail: String(out).slice(-300) });
|
|
465
653
|
tunnelId = m[1];
|
|
@@ -497,8 +685,19 @@ export class LocalProvisioner {
|
|
|
497
685
|
try {
|
|
498
686
|
await this.run(['tunnel', 'route', 'dns', '--overwrite-dns', label, hostname]);
|
|
499
687
|
} catch (err) {
|
|
500
|
-
|
|
501
|
-
|
|
688
|
+
// 关键修复:不再 `split('\n')[0]`。真实原因在第二行
|
|
689
|
+
// (`Failed to add route: code: 10000, reason: Authentication error`),
|
|
690
|
+
// 旧代码把它丢掉,只留下 `Command failed: …` 的命令回显,患者无从下手。
|
|
691
|
+
const explained = explainTunnelFailure(err, {
|
|
692
|
+
baseDomain: this.baseDomain,
|
|
693
|
+
operation: 'route-dns',
|
|
694
|
+
accountName: auth.accountName || null,
|
|
695
|
+
exe: this.#exeLabel(),
|
|
696
|
+
});
|
|
697
|
+
this.log(`tunnel 写 DNS 失败 ${explained.reason}${explained.code ? ` code=${explained.code}` : ''} ${explained.message}`);
|
|
698
|
+
throw fail(4500, explained.message, {
|
|
699
|
+
detail: explained.detail,
|
|
700
|
+
reason: explained.reason,
|
|
502
701
|
});
|
|
503
702
|
}
|
|
504
703
|
|
|
@@ -519,7 +718,7 @@ export class LocalProvisioner {
|
|
|
519
718
|
this.log(`tunnel 警告 固定地址写入成功但公网解析不到 ${hostname}`);
|
|
520
719
|
}
|
|
521
720
|
|
|
522
|
-
const next = {
|
|
721
|
+
const next = this.#withMachine({
|
|
523
722
|
...cached,
|
|
524
723
|
installationId,
|
|
525
724
|
// 记下这本证书属于哪个 Cloudflare 账号:下次若换了账号,能识别出「旧隧道不再可用」
|
|
@@ -536,7 +735,7 @@ export class LocalProvisioner {
|
|
|
536
735
|
zone,
|
|
537
736
|
createdAt: cached?.createdAt ?? now,
|
|
538
737
|
updatedAt: now,
|
|
539
|
-
};
|
|
738
|
+
});
|
|
540
739
|
this._state = next;
|
|
541
740
|
writeState(this.stateFile, next);
|
|
542
741
|
this.log(`tunnel 固定地址就绪 ${hostname}(${created ? '新建' : '复用'},本地管理型)`);
|
|
@@ -545,16 +744,140 @@ export class LocalProvisioner {
|
|
|
545
744
|
url: `https://${hostname}`,
|
|
546
745
|
tunnelId,
|
|
547
746
|
created,
|
|
548
|
-
changed: Boolean(
|
|
747
|
+
changed: Boolean(previousHostname && previousHostname !== hostname),
|
|
549
748
|
dnsOk: verdict.ok,
|
|
550
749
|
zone,
|
|
551
750
|
warning,
|
|
552
751
|
};
|
|
553
752
|
}
|
|
554
753
|
|
|
754
|
+
/** 面板/报错里展示用的 cloudflared 名字(找不到时退回配置值,不发明路径)。 */
|
|
755
|
+
#exeLabel() {
|
|
756
|
+
return findCloudflared(this.executable, this.env) || findCloudflared('auto', this.env) || this.executable;
|
|
757
|
+
}
|
|
758
|
+
|
|
555
759
|
async credential({ port }) {
|
|
556
760
|
await this.ensure({ port });
|
|
557
761
|
if (!this.state?.configFile) throw fail(4500, '隧道配置缺失,请重新开通固定地址');
|
|
558
762
|
return { hostname: this.state.hostname, configFile: this.state.configFile };
|
|
559
763
|
}
|
|
560
764
|
}
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* 只读本地状态的开通器(cert.pem 不在了 / 被删了也能继续用固定地址)。
|
|
768
|
+
*
|
|
769
|
+
* 为什么需要:本地管理型的 ingress 与 tunnel 凭据(<uuid>.json)都在本机,
|
|
770
|
+
* 日常启动**不需要** zone 凭据——cert.pem 只在开通时用来写 DNS。
|
|
771
|
+
* 早先这种情况会掉回 Quick Tunnel(随机地址),用户会以为「固定地址丢了」。
|
|
772
|
+
*
|
|
773
|
+
* 边界:
|
|
774
|
+
* · 绝不写 DNS、绝不建隧道(没有 zone 凭据,做不到也不该假装做到);
|
|
775
|
+
* · 端口变了只重写本地 ingress(纯本地操作,安全);
|
|
776
|
+
* · 状态必须属于本机、凭据文件必须存在,否则 configured=false(不冒充别人的地址)。
|
|
777
|
+
*/
|
|
778
|
+
export class LocalStateProvisioner {
|
|
779
|
+
constructor({ stateFile = null, configFile = null, baseDomain = 'matrixboard.cn', log = () => {}, homeDir = os.homedir() } = {}) {
|
|
780
|
+
this.stateFile = stateFile;
|
|
781
|
+
this.configFile = configFile || (stateFile ? path.join(path.dirname(stateFile), 'tunnel-config.yml') : null);
|
|
782
|
+
this.baseDomain = String(baseDomain || '').replace(/^\./, '').toLowerCase();
|
|
783
|
+
this.log = log;
|
|
784
|
+
this.homeDir = homeDir;
|
|
785
|
+
this._state = undefined;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
get kind() {
|
|
789
|
+
return 'state';
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
get state() {
|
|
793
|
+
if (this._state === undefined) this._state = readState(this.stateFile, this.log);
|
|
794
|
+
return this._state;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
get configured() {
|
|
798
|
+
const s = this.state;
|
|
799
|
+
if (!s?.hostname || !s.configFile || !s.credentialsFile) return false;
|
|
800
|
+
if (isForeignState(s, machineIdentity({ stateFile: this.stateFile }))) return false;
|
|
801
|
+
if (!fs.existsSync(s.configFile)) return false;
|
|
802
|
+
return hasLocalCredentials(s);
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
get credentials() {
|
|
806
|
+
return null;
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/** 没有 cert.pem 也就没有写入能力:这里只保证「能起隧道」。 */
|
|
810
|
+
async ensure({ port } = {}) {
|
|
811
|
+
const s = this.state;
|
|
812
|
+
if (!s?.hostname || !s.configFile) throw fail(4021, '这台主机还没有可复用的固定地址');
|
|
813
|
+
if (Number.isInteger(port) && port > 0 && port !== s.port) {
|
|
814
|
+
try {
|
|
815
|
+
fs.mkdirSync(path.dirname(s.configFile), { recursive: true, mode: 0o700 });
|
|
816
|
+
fs.writeFileSync(s.configFile, renderConfig({
|
|
817
|
+
tunnelId: s.tunnelId,
|
|
818
|
+
credentialsFile: s.credentialsFile,
|
|
819
|
+
hostname: s.hostname,
|
|
820
|
+
port,
|
|
821
|
+
}), { mode: 0o600 });
|
|
822
|
+
const next = { ...s, port, updatedAt: new Date().toISOString() };
|
|
823
|
+
this._state = next;
|
|
824
|
+
writeState(this.stateFile, next);
|
|
825
|
+
this.log(`tunnel 端口顺延 ${s.port} → ${port}(本地 ingress 已重写,DNS 未改动)`);
|
|
826
|
+
} catch (err) {
|
|
827
|
+
this.log(`tunnel 重写 ingress 失败:${err.message}`);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
return {
|
|
831
|
+
hostname: s.hostname,
|
|
832
|
+
url: `https://${s.hostname}`,
|
|
833
|
+
tunnelId: s.tunnelId,
|
|
834
|
+
created: false,
|
|
835
|
+
changed: false,
|
|
836
|
+
dnsOk: s.dnsOk ?? null,
|
|
837
|
+
warning: dnsWarningFor(s),
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
async credential({ port } = {}) {
|
|
842
|
+
const r = await this.ensure({ port });
|
|
843
|
+
return { hostname: r.hostname, configFile: this.state?.configFile };
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
/** 与 LocalProvisioner.reset 同语义:只清本机状态与 ingress,不碰 Cloudflare 侧。 */
|
|
847
|
+
async reset() {
|
|
848
|
+
const removed = [];
|
|
849
|
+
const hadState = Boolean(this.state?.hostname);
|
|
850
|
+
for (const file of [this.stateFile, this.state?.configFile || this.configFile]) {
|
|
851
|
+
if (!file) continue;
|
|
852
|
+
try {
|
|
853
|
+
if (fs.statSync(file).isFile()) {
|
|
854
|
+
fs.unlinkSync(file);
|
|
855
|
+
removed.push(path.basename(file));
|
|
856
|
+
}
|
|
857
|
+
} catch { /* 不存在即目标状态 */ }
|
|
858
|
+
}
|
|
859
|
+
if (hadState) this.log('tunnel 已重置本机固定地址状态(Cloudflare 侧的隧道与记录未删除)');
|
|
860
|
+
this._state = null;
|
|
861
|
+
return { reset: true, hadState, removed, hostname: null, provisioned: false };
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
status() {
|
|
865
|
+
const s = this.state;
|
|
866
|
+
if (!s) return { kind: 'state', provisioned: false, hostname: null, url: null, tunnelId: null };
|
|
867
|
+
return {
|
|
868
|
+
kind: 'state',
|
|
869
|
+
provisioned: true,
|
|
870
|
+
hostname: s.hostname,
|
|
871
|
+
url: `https://${s.hostname}`,
|
|
872
|
+
tunnelId: s.tunnelId,
|
|
873
|
+
port: s.port ?? null,
|
|
874
|
+
dnsOk: s.dnsOk ?? null,
|
|
875
|
+
dnsCheckedAt: s.dnsCheckedAt ?? null,
|
|
876
|
+
zone: s.zone ?? null,
|
|
877
|
+
warning: dnsWarningFor(s),
|
|
878
|
+
credentials: null,
|
|
879
|
+
createdAt: s.createdAt ?? null,
|
|
880
|
+
updatedAt: s.updatedAt ?? null,
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
}
|
|
@@ -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
|
+
}
|