dsh-mobile-plugin 0.5.141 → 0.5.142

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.
@@ -0,0 +1,205 @@
1
+ // Cloudflare 命名隧道的 provision:两种凭证模式都复用现成的 cloudflared 二进制获取,
2
+ // 差别只在「隧道 id / token / hostname 从哪来」——模式 A 用户给,模式 B 我们调 API 建。
3
+ //
4
+ // 落盘分两份,都在用户自己电脑的 dshHome 下、0600:
5
+ // tunnel.json —— 对外只读标识(模式 / hostname / id / url),可被状态投影读取。
6
+ // credentials.json —— 用户贴进来的 token(tunnel token 或 API Token),只给本进程起隧道 /
7
+ // 改 ingress / 删隧道用。绝不进 relay.json、二维码、心跳、日志、诊断。
8
+ 'use strict';
9
+
10
+ const fs = require('node:fs');
11
+ const path = require('node:path');
12
+ const { dshHome } = require('../shared/paths.js');
13
+ const quickProvision = require('../cloudflared/provision.cjs');
14
+ const api = require('./api.cjs');
15
+
16
+ function namedPaths(root) {
17
+ const dir = root || path.join(dshHome(), 'cloudflare-named');
18
+ return {
19
+ dir,
20
+ meta: path.join(dir, 'tunnel.json'),
21
+ creds: path.join(dir, 'credentials.json'),
22
+ };
23
+ }
24
+
25
+ function writeJson(file, obj) {
26
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
27
+ fs.writeFileSync(file, JSON.stringify(obj, null, 2), { mode: 0o600 });
28
+ try { fs.chmodSync(file, 0o600); } catch { /* Windows 上 chmod 无效,ACL 兜底 */ }
29
+ }
30
+
31
+ /** 对外只读的那份:绝不含任何 token。状态投影/诊断只准读这份。 */
32
+ function writeMeta(meta, root) {
33
+ const paths = namedPaths(root);
34
+ const safe = {
35
+ mode: meta.mode === 'token' ? 'token' : 'api',
36
+ hostname: typeof meta.hostname === 'string' ? meta.hostname.trim() : '',
37
+ tunnelId: typeof meta.tunnelId === 'string' ? meta.tunnelId : '',
38
+ url: typeof meta.url === 'string' ? meta.url : '',
39
+ localPort: Number(meta.localPort) || 0,
40
+ createdAt: typeof meta.createdAt === 'number' ? meta.createdAt : Date.now(),
41
+ };
42
+ writeJson(paths.meta, safe);
43
+ return safe;
44
+ }
45
+
46
+ /** 本机凭据那份:只在需要起隧道/改配置/删隧道时读,绝不回显给面板以外的任何人。 */
47
+ function writeCredentials(creds, root) {
48
+ const paths = namedPaths(root);
49
+ const safe = {
50
+ tunnelToken: typeof creds.tunnelToken === 'string' ? creds.tunnelToken : '',
51
+ apiToken: typeof creds.apiToken === 'string' ? creds.apiToken : '',
52
+ accountId: typeof creds.accountId === 'string' ? creds.accountId : '',
53
+ zoneId: typeof creds.zoneId === 'string' ? creds.zoneId : '',
54
+ tunnelId: typeof creds.tunnelId === 'string' ? creds.tunnelId : '',
55
+ };
56
+ writeJson(paths.creds, safe);
57
+ return safe;
58
+ }
59
+
60
+ function readJson(file) {
61
+ try {
62
+ const obj = JSON.parse(fs.readFileSync(file, 'utf8'));
63
+ return obj && typeof obj === 'object' ? obj : null;
64
+ } catch {
65
+ return null;
66
+ }
67
+ }
68
+ const readMeta = (root) => readJson(namedPaths(root).meta);
69
+ const readCredentials = (root) => readJson(namedPaths(root).creds);
70
+
71
+ function clearAll(root) {
72
+ const paths = namedPaths(root);
73
+ for (const file of [paths.meta, paths.creds]) {
74
+ try { fs.unlinkSync(file); } catch { /* 没有就算清过了 */ }
75
+ }
76
+ }
77
+
78
+ /** 确保 cloudflared 二进制可用:与快速隧道共用缓存,不重复下载。 */
79
+ async function ensureBinary(options = {}) {
80
+ return quickProvision.ensureCloudflared(options);
81
+ }
82
+ function platformId() {
83
+ return quickProvision.platformId();
84
+ }
85
+
86
+ function urlOf(hostname) {
87
+ const host = typeof hostname === 'string'
88
+ ? hostname.trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\.$/, '').replace(/\/+$/, '')
89
+ : '';
90
+ return host ? `https://${host}` : '';
91
+ }
92
+
93
+ /** 校验 hostname 是合法 FQDN(末尾点容忍,禁止裸 IP / 路径 / scheme / 非 ASCII)。 */
94
+ function validateHostname(hostname) {
95
+ const host = typeof hostname === 'string' ? hostname.trim().replace(/\.$/, '') : '';
96
+ if (!host || host.length > 253) return false;
97
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(host)) return false;
98
+ if (/[^\u0000-\u007f]/.test(host)) return false;
99
+ return /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(host);
100
+ }
101
+
102
+ function normalizeLocalPort(value) {
103
+ const port = Number(value);
104
+ if (!Number.isInteger(port) || port < 1024 || port > 65535) {
105
+ throw api.cfError('CF_PORT_INVALID', '本机端口要在 1024–65535 之间');
106
+ }
107
+ return port;
108
+ }
109
+
110
+ /**
111
+ * 模式 B:用 API Token 建隧道 + 写 ingress + 写 DNS。
112
+ * 返回 { id, token, hostname, url, localPort, credentials }。token 只在内存与 0600 凭据文件里。
113
+ * 建之前查同名 CNAME:已有指向别处的记录直接拒绝,不静默覆盖用户 DNS。
114
+ */
115
+ async function provisionWithApi(input, options = {}) {
116
+ const token = (input.apiToken || '').trim();
117
+ const accountId = (input.accountId || '').trim();
118
+ const zoneId = (input.zoneId || '').trim();
119
+ const hostname = (input.hostname || '').trim().toLowerCase().replace(/\.$/, '');
120
+ const localPort = normalizeLocalPort(input.localPort);
121
+ if (!token) throw api.cfError('CF_TOKEN_MISSING', '还没填 Cloudflare API Token');
122
+ if (!accountId) throw api.cfError('CF_ACCOUNT_MISSING', '还没填 Cloudflare Account ID');
123
+ if (!zoneId) throw api.cfError('CF_ZONE_MISSING', '还没填 Cloudflare Zone ID');
124
+ if (!validateHostname(hostname)) throw api.cfError('CF_HOST_INVALID', '域名格式不对,请填完整域名(如 tunnel.example.com)');
125
+ const opts = { fetchImpl: options.fetchImpl };
126
+
127
+ let existing = [];
128
+ try {
129
+ const listed = await api.listDnsRecords(token, zoneId, hostname, opts);
130
+ existing = Array.isArray(listed) ? listed : [];
131
+ } catch (err) {
132
+ throw err; // 查不到就不能盲目往下建,宁可停下
133
+ }
134
+ const conflict = existing.find(r => r && r.content && !String(r.content).replace(/\.$/, '').endsWith('.cfargotunnel.com'));
135
+ if (conflict) throw api.cfError('CF_DNS_CONFLICT', `域名 ${hostname} 已有一条指向别处的记录,请先到 Cloudflare 后台处理,插件不会覆盖`);
136
+
137
+ const created = await api.createTunnel(token, accountId, `dsh-${hostname.split('.')[0]}`, opts);
138
+ try {
139
+ await api.putIngress(token, accountId, created.id, hostname, localPort, opts);
140
+ await api.createDnsRecord(token, zoneId, hostname, created.id, opts);
141
+ } catch (err) {
142
+ try { await api.deleteTunnel(token, accountId, created.id, opts); } catch { /* 清理失败不掩盖原始错误 */ }
143
+ throw err;
144
+ }
145
+ return {
146
+ mode: 'api',
147
+ id: created.id,
148
+ tunnelToken: created.token,
149
+ hostname,
150
+ url: urlOf(hostname),
151
+ localPort,
152
+ credentials: { apiToken: token, accountId, zoneId, tunnelId: created.id },
153
+ };
154
+ }
155
+
156
+ /**
157
+ * 模式 A:用户已在自己 CF 后台建好隧道、配好 DNS 和 ingress,只粘隧道 token。
158
+ * 不做任何 API 调用;hostname 与本地端口都要用户填(token 里没有域名)。
159
+ */
160
+ function provisionWithToken(input) {
161
+ const tunnelToken = (input.tunnelToken || '').trim();
162
+ const hostname = (input.hostname || '').trim().toLowerCase().replace(/\.$/, '');
163
+ const localPort = normalizeLocalPort(input.localPort);
164
+ if (!tunnelToken) throw api.cfError('CF_TUNNEL_TOKEN_MISSING', '还没填 Cloudflare 隧道 Token');
165
+ if (!validateHostname(hostname)) throw api.cfError('CF_HOST_INVALID', '域名格式不对,请填完整域名(如 tunnel.example.com)');
166
+ return {
167
+ mode: 'token',
168
+ hostname,
169
+ url: urlOf(hostname),
170
+ localPort,
171
+ tunnelToken,
172
+ credentials: { tunnelToken },
173
+ };
174
+ }
175
+
176
+ /**
177
+ * 本机端口变了以后,模式 B 需要把远端 ingress 的 service 同步到新端口(否则手机拨进来转到旧口)。
178
+ * 模式 A 的 ingress 在用户自己后台,插件改不到,如实返回 false 让面板提示用户去后台改。
179
+ */
180
+ async function updateLocalPort(meta, credentials, newPort, options = {}) {
181
+ const port = normalizeLocalPort(newPort);
182
+ if (meta.mode !== 'api') return false;
183
+ if (!credentials || !credentials.apiToken || !credentials.accountId || !credentials.tunnelId || !meta.hostname) {
184
+ throw api.cfError('CF_CREDS_MISSING', '本机缺少 Cloudflare 凭据,请重新连接一次');
185
+ }
186
+ await api.putIngress(credentials.apiToken, credentials.accountId, credentials.tunnelId, meta.hostname, port, { fetchImpl: options.fetchImpl });
187
+ return true;
188
+ }
189
+
190
+ module.exports = {
191
+ namedPaths,
192
+ writeMeta,
193
+ writeCredentials,
194
+ readMeta,
195
+ readCredentials,
196
+ clearAll,
197
+ ensureBinary,
198
+ platformId,
199
+ urlOf,
200
+ validateHostname,
201
+ normalizeLocalPort,
202
+ provisionWithApi,
203
+ provisionWithToken,
204
+ updateLocalPort,
205
+ };
@@ -0,0 +1,252 @@
1
+ // Cloudflare 命名隧道的进程生命周期:起停、连通判定、崩溃退避、token 绝不进日志/状态。
2
+ // 与快速隧道 runner 分开:命名隧道跑 `tunnel run --token`(无 --url),公网地址来自我们配置的
3
+ // hostname,不是 banner 正则;连通信号仍是日志里的 Registered tunnel connection。
4
+ 'use strict';
5
+
6
+ const fs = require('node:fs');
7
+ const path = require('node:path');
8
+ const { spawn } = require('node:child_process');
9
+ const { dshHome } = require('../shared/paths.js');
10
+ const { nextRestartDelay } = require('../shared/restart-backoff.cjs');
11
+ const { cloudflaredEdgeIpVersion } = require('../relay/net-family.cjs');
12
+
13
+ const RESTART_DELAYS_MS = [1000, 2000, 4000, 8000, 16000];
14
+ const CONNECT_TIMEOUT_MS = 40_000;
15
+ const CONNECTED_RE = /Registered tunnel connection/i;
16
+ const DISCONNECTED_RE = /Connection terminated|Unregistered tunnel connection|Lost connection with the edge/i;
17
+ const ANSI_RE = /\u001b\[[0-9;]*m/g;
18
+
19
+ function describeSpawnFailure(err, binary) {
20
+ const code = err && err.code ? String(err.code) : '';
21
+ const raw = err && err.message ? err.message : String(err || '未知错误');
22
+ const where = binary ? `(${binary})` : '';
23
+ if (code === 'UNKNOWN') return `系统拒绝运行 cloudflared${where},请把它加入安全软件信任名单`;
24
+ if (code === 'ENOEXEC') return `cloudflared${where} 与本机架构不符,请重新获取`;
25
+ if (code === 'EACCES' || code === 'EPERM') return `系统不允许运行 cloudflared${where},权限被拒`;
26
+ if (code === 'ENOENT') return `找不到 cloudflared 可执行文件${where}`;
27
+ return `启动 cloudflared 失败:${raw}`;
28
+ }
29
+
30
+ /** 把一行日志收拾成人话;token 若被 cloudflared 原样打出来,先抹掉再往外送。 */
31
+ function cleanLogLine(line, secret) {
32
+ let text = String(line || '').trim().replace(/^\S+\s+/, '').replace(/^ERR\s*/, '').trim();
33
+ if (secret) text = text.split(secret).join('[redacted]');
34
+ return text.length > 160 ? `${text.slice(0, 157)}…` : text;
35
+ }
36
+
37
+ function connectFailureText(reason, timeoutMs) {
38
+ const seconds = Math.max(1, Math.round(timeoutMs / 1000));
39
+ const detail = reason ? `;cloudflared 报:${reason}` : '';
40
+ return `启动后 ${seconds} 秒还没连上 Cloudflare 边缘(常见原因是网络挡了 7844),仍在后台重试${detail}`;
41
+ }
42
+
43
+ /**
44
+ * @param {object} options 依赖注入(测试用真实假体)
45
+ * @param {() => string} options.tokenOf 隧道 token(每次启动现读,不缓存到状态)
46
+ * @param {() => string} options.hostnameOf 公网域名(拼对外地址用)
47
+ * @param {() => number} options.portOf 本机落点端口(只用于状态显示,命名隧道不靠它拨号)
48
+ * @param {() => object} [options.ensureBin] 拿二进制(复用 provision.ensureBinary)
49
+ * @param {(url: string) => void} [options.onAddress] 连上后报地址
50
+ * @param {() => void} [options.onAddressGone] 地址该撤回时通知
51
+ */
52
+ function createNamedRunner(options = {}) {
53
+ const tokenOf = typeof options.tokenOf === 'function' ? options.tokenOf : () => '';
54
+ const hostnameOf = typeof options.hostnameOf === 'function' ? options.hostnameOf : () => '';
55
+ const portOf = typeof options.portOf === 'function' ? options.portOf : () => 0;
56
+ const ensureBin = typeof options.ensureBin === 'function' ? options.ensureBin : async () => {
57
+ const p = require('./provision.cjs');
58
+ return p.ensureBinary();
59
+ };
60
+ const spawnImpl = typeof options.spawnImpl === 'function' ? options.spawnImpl : spawn;
61
+ const fsImpl = options.fsImpl || fs;
62
+ const setTimer = options.setTimerImpl || setTimeout;
63
+ const clearTimer = options.clearTimerImpl || clearTimeout;
64
+ const setConnectTimer = options.connectTimerImpl || setTimeout;
65
+ const clearConnectTimer = options.clearConnectTimerImpl || clearTimeout;
66
+ const ipVersionPolicyOf = typeof options.ipVersionPolicy === 'function' ? options.ipVersionPolicy : () => options.ipVersionPolicy;
67
+ const connectTimeoutMs = Number(options.connectTimeoutMs) > 0 ? Number(options.connectTimeoutMs) : CONNECT_TIMEOUT_MS;
68
+ const addressListener = typeof options.onAddress === 'function' ? options.onAddress : null;
69
+ const goneListener = typeof options.onAddressGone === 'function' ? options.onAddressGone : null;
70
+
71
+ let child = null;
72
+ let binary = '';
73
+ let error = '';
74
+ let startedAt = 0;
75
+ let registered = false;
76
+ let publishedUrl = '';
77
+ let lineBuf = '';
78
+ let desired = false;
79
+ let generation = 0;
80
+ let retryTimer = null;
81
+ let connectTimer = null;
82
+ let retries = 0;
83
+ const exists = (p) => { try { return fsImpl.existsSync(p); } catch { return false; } };
84
+ const urlOfHost = () => {
85
+ const h = String(hostnameOf() || '').trim().replace(/^https?:\/\//, '').replace(/\/+$/, '');
86
+ return h ? `https://${h}` : '';
87
+ };
88
+
89
+ function clearConnectTimerNow() {
90
+ if (connectTimer) { clearConnectTimer(connectTimer); connectTimer = null; }
91
+ }
92
+ function publishAddress() {
93
+ const url = urlOfHost();
94
+ if (url && url !== publishedUrl) {
95
+ publishedUrl = url;
96
+ if (addressListener) addressListener(url);
97
+ }
98
+ }
99
+ function retractAddress() {
100
+ if (publishedUrl && goneListener) goneListener(publishedUrl);
101
+ publishedUrl = '';
102
+ }
103
+ function cleanup(gen) {
104
+ if (gen !== generation) return;
105
+ clearConnectTimerNow();
106
+ registered = false;
107
+ retractAddress();
108
+ }
109
+
110
+ async function launch() {
111
+ const gen = ++generation;
112
+ retries = 0;
113
+ error = '';
114
+ registered = false;
115
+ startedAt = Date.now();
116
+ try {
117
+ const resolved = await ensureBin({ ipVersionPolicy: ipVersionPolicyOf() });
118
+ binary = typeof resolved === 'string' ? resolved : (resolved && resolved.binary ? resolved.binary : '');
119
+ } catch (err) {
120
+ error = err && err.message ? err.message : String(err);
121
+ return;
122
+ }
123
+ if (gen !== generation || !desired) return;
124
+
125
+ const token = String(tokenOf() || '').trim();
126
+ if (!token) {
127
+ error = '缺少 Cloudflare 隧道 token,请在面板重新连接一次';
128
+ return;
129
+ }
130
+ // 命名隧道:不传 --url,服务地址在 Cloudflare 后台 ingress 里;token 走命令行参数,
131
+ // 绝不拼进任何对外状态或日志(cleanLogLine 会把原文里出现的 token 抹掉)。
132
+ const args = ['tunnel', 'run', '--token', token, '--no-autoupdate'];
133
+ const edge = cloudflaredEdgeIpVersion(ipVersionPolicyOf());
134
+ if (edge) args.push(`--edge-ip-version=${edge}`);
135
+
136
+ let proc;
137
+ try {
138
+ proc = spawnImpl(binary, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
139
+ } catch (err) {
140
+ error = describeSpawnFailure(err, binary);
141
+ return;
142
+ }
143
+ child = proc;
144
+ const onData = (chunk) => {
145
+ if (gen !== generation) return;
146
+ lineBuf += String(chunk || '');
147
+ const lines = lineBuf.split(/\r?\n/);
148
+ lineBuf = lines.pop() || '';
149
+ for (const raw of lines) {
150
+ const line = String(raw || '').replace(ANSI_RE, '');
151
+ if (CONNECTED_RE.test(line)) {
152
+ if (!registered) {
153
+ registered = true;
154
+ clearConnectTimerNow();
155
+ publishAddress();
156
+ }
157
+ } else if (DISCONNECTED_RE.test(line)) {
158
+ registered = false;
159
+ retractAddress();
160
+ } else if (/\bERR\b/i.test(line)) {
161
+ error = cleanLogLine(line, token);
162
+ }
163
+ }
164
+ };
165
+ if (proc.stdout) proc.stdout.on('data', onData);
166
+ if (proc.stderr) proc.stderr.on('data', onData);
167
+ const onExit = () => {
168
+ if (child === proc) child = null;
169
+ cleanup(gen);
170
+ if (gen !== generation || !desired) return;
171
+ const delay = nextRestartDelay(RESTART_DELAYS_MS, retries);
172
+ retries += 1;
173
+ retryTimer = setTimer(() => { retryTimer = null; void launch(); }, delay);
174
+ };
175
+ proc.on('error', (err) => {
176
+ if (gen !== generation) return;
177
+ error = describeSpawnFailure(err, binary);
178
+ try { proc.kill(); } catch { /* 已经没了 */ }
179
+ });
180
+ proc.on('exit', onExit);
181
+ proc.on('close', onExit);
182
+
183
+ clearConnectTimerNow();
184
+ connectTimer = setConnectTimer(() => {
185
+ connectTimer = null;
186
+ if (gen !== generation || !desired || registered) return;
187
+ error = connectFailureText(error, connectTimeoutMs);
188
+ }, connectTimeoutMs);
189
+ }
190
+
191
+ function stop() {
192
+ generation += 1;
193
+ desired = false;
194
+ retries = 0;
195
+ if (retryTimer) { clearTimer(retryTimer); retryTimer = null; }
196
+ clearConnectTimerNow();
197
+ const proc = child;
198
+ child = null;
199
+ retractAddress();
200
+ registered = false;
201
+ if (proc) {
202
+ try { proc.kill(); } catch { /* 已经没了 */ }
203
+ }
204
+ }
205
+
206
+ function start() {
207
+ if (desired) return Promise.resolve(status());
208
+ desired = true;
209
+ void launch();
210
+ return Promise.resolve(status());
211
+ }
212
+
213
+ /** 端口/域名变了要重启进程让新 token/配置生效(token 现读)。 */
214
+ function reconfigure() {
215
+ if (!desired) return Promise.resolve(status());
216
+ const proc = child;
217
+ child = null;
218
+ generation += 1;
219
+ if (retryTimer) { clearTimer(retryTimer); retryTimer = null; }
220
+ clearConnectTimerNow();
221
+ retractAddress();
222
+ if (proc) { try { proc.kill(); } catch { /* 忽略 */ } }
223
+ return start();
224
+ }
225
+
226
+ function status() {
227
+ const url = urlOfHost();
228
+ return {
229
+ available: platformSupported(),
230
+ running: Boolean(child && registered && desired),
231
+ pid: child && child.pid ? child.pid : null,
232
+ url: registered ? url : '',
233
+ error,
234
+ startedAt,
235
+ starting: Boolean(desired && !child && !error),
236
+ retrying: Boolean(desired && !registered && retries > 0),
237
+ waitingForPort: false,
238
+ enabled: desired,
239
+ localPort: Number(portOf()) || 0,
240
+ };
241
+ }
242
+
243
+ function platformSupported() {
244
+ try { return require('./provision.cjs').platformId() !== null; } catch { return true; }
245
+ }
246
+
247
+ function dispose() { stop(); }
248
+
249
+ return { start, stop, reconfigure, status, dispose };
250
+ }
251
+
252
+ module.exports = { createNamedRunner, connectFailureText };
@@ -0,0 +1,155 @@
1
+ // Cloudflare 命名隧道接线:把 runner 挂进装配层,连上后把固定地址写进独立字段
2
+ // `cloudflareNamedUrl`(与快速隧道的 cloudflareUrl 并列,命名隧道优先),停用/失败时撤回。
3
+ // 端口变化经 provision.updateLocalPort 同步远端 ingress(仅模式 B;模式 A 提示用户去后台改)。
4
+ 'use strict';
5
+
6
+ const { createNamedRunner } = require('./runner.cjs');
7
+ const provision = require('./provision.cjs');
8
+ const api = require('./api.cjs');
9
+
10
+ /**
11
+ * @param {object} options
12
+ * @param {(label: string, fn: Function) => any} options.mount
13
+ * @param {(message: string, ...rest: any[]) => void} options.warn
14
+ * @param {object} options.state relay.json 内存状态(唯一真值)
15
+ * @param {{ update: (patch: object) => Promise<any> }} options.settings
16
+ * @param {() => number} options.portOf 本机落点端口
17
+ * @param {object} options.ctx 插件 ctx(只为 ctx.get)
18
+ * @param {string} options.name 插件名
19
+ */
20
+ function mountNamedCloudflare(options) {
21
+ const { mount, warn, state, settings, portOf, ctx, name } = options;
22
+ // root 只给测试注入;生产用默认的 dshHome 0600 目录。
23
+ const root = options.root;
24
+
25
+ // 从本机 0600 文件读模式 / hostname / token —— 绝不从 relay.json 的对外投影读 token。
26
+ const readCreds = () => {
27
+ const meta = provision.readMeta(root);
28
+ const creds = provision.readCredentials(root);
29
+ return { meta, creds };
30
+ };
31
+
32
+ let runner;
33
+ try {
34
+ runner = createNamedRunner({
35
+ tokenOf: () => {
36
+ const { creds } = readCreds();
37
+ return creds && creds.tunnelToken ? creds.tunnelToken : '';
38
+ },
39
+ hostnameOf: () => {
40
+ const { meta } = readCreds();
41
+ return meta && meta.hostname ? meta.hostname : '';
42
+ },
43
+ portOf: () => {
44
+ const { meta } = readCreds();
45
+ return meta && meta.localPort ? meta.localPort : Number(portOf()) || 0;
46
+ },
47
+ ipVersionPolicy: () => state.ipVersionPolicy,
48
+ onAddress: (url) => { void settings.update({ cloudflareNamedUrl: url }).catch(warn); },
49
+ onAddressGone: () => { void settings.update({ cloudflareNamedUrl: '' }).catch(warn); },
50
+ });
51
+ } catch (error) {
52
+ warn('Cloudflare 命名隧道运行器创建失败:%s', error && error.message ? error.message : error);
53
+ const degraded = () => ({ available: false, running: false, url: '', error: `命名隧道初始化失败:${error && error.message ? error.message : error}`, configured: false });
54
+ return { start: async () => degraded(), stop: async () => degraded(), status: degraded, configure: async () => degraded(), disconnect: async () => degraded(), remove: async () => degraded() };
55
+ }
56
+
57
+ /** 面板读状态:对外只报 hostname/url/id 等标识,不含任何 token。 */
58
+ function status() {
59
+ const { meta } = readCreds();
60
+ const base = runner.status();
61
+ return {
62
+ ...base,
63
+ configured: Boolean(meta && meta.hostname),
64
+ mode: meta && meta.mode ? meta.mode : '',
65
+ hostname: meta && meta.hostname ? meta.hostname : '',
66
+ tunnelId: meta && meta.tunnelId ? meta.tunnelId : '',
67
+ };
68
+ }
69
+
70
+ /**
71
+ * 面板配置并连接:按模式建/读凭据、落 0600、起进程。
72
+ * input: { mode:'api'|'token', hostname, localPort, apiToken?, accountId?, zoneId?, tunnelToken? }
73
+ */
74
+ async function configure(input = {}) {
75
+ const mode = input.mode === 'token' ? 'token' : 'api';
76
+ const localPort = Number(input.localPort) || Number(portOf()) || 0;
77
+ const result = mode === 'api'
78
+ ? await provision.provisionWithApi({ ...input, localPort })
79
+ : provision.provisionWithToken({ ...input, localPort });
80
+
81
+ // 先停旧进程(避免两条命名隧道并存),再落新凭据与标识,再起。
82
+ runner.stop();
83
+ provision.writeMeta({
84
+ mode: result.mode,
85
+ hostname: result.hostname,
86
+ url: result.url,
87
+ localPort: result.localPort,
88
+ tunnelId: result.id || '',
89
+ }, root);
90
+ provision.writeCredentials({
91
+ ...result.credentials,
92
+ tunnelToken: result.tunnelToken || (result.credentials && result.credentials.tunnelToken) || '',
93
+ tunnelId: result.id || '',
94
+ }, root);
95
+ await runner.reconfigure();
96
+ return status();
97
+ }
98
+
99
+ async function stop() {
100
+ runner.stop();
101
+ await settings.update({ cloudflareNamedUrl: '' }).catch(warn);
102
+ return status();
103
+ }
104
+
105
+ async function start() {
106
+ const { meta } = readCreds();
107
+ if (!meta || !meta.hostname) throw api.cfError('CF_NOT_CONFIGURED', '还没配置 Cloudflare 命名隧道');
108
+ await runner.start();
109
+ return status();
110
+ }
111
+
112
+ /** 断开:停进程并清对外地址;保留凭据供下次一键重连(和 ZeroNews 的 stop/purge 分开同口径)。 */
113
+ async function disconnect() {
114
+ return stop();
115
+ }
116
+
117
+ /** 删除:显式二次确认后才删隧道与 DNS,清本机凭据。不可逆,面板必须先确认。 */
118
+ async function remove() {
119
+ const { meta, creds } = readCreds();
120
+ if (meta && meta.mode === 'api' && creds && creds.apiToken && creds.accountId && meta.tunnelId) {
121
+ try {
122
+ await api.deleteTunnel(creds.apiToken, creds.accountId, meta.tunnelId);
123
+ } catch (err) {
124
+ // 删云端失败就别清本地凭据:留着用户还能重试,不制造「本地没了云端还在」的孤儿。
125
+ throw err;
126
+ }
127
+ }
128
+ runner.stop();
129
+ await settings.update({ cloudflareNamedUrl: '' }).catch(warn);
130
+ provision.clearAll(root);
131
+ return status();
132
+ }
133
+
134
+ /** 本机落点端口变了:模式 B 同步远端 ingress;模式 A 返回 false 让面板提示去后台改。 */
135
+ async function syncLocalPort() {
136
+ const { meta, creds } = readCreds();
137
+ if (!meta || !meta.hostname) return false;
138
+ const port = Number(portOf());
139
+ if (!Number.isInteger(port) || port < 1024 || port > 65535) return false;
140
+ if (meta.localPort === port) return false;
141
+ const changed = await provision.updateLocalPort(meta, creds, port);
142
+ if (changed) {
143
+ provision.writeMeta({ ...meta, localPort: port }, root);
144
+ await runner.reconfigure();
145
+ }
146
+ return changed;
147
+ }
148
+
149
+ // 外壳持有 runner 时沿用(换代不重启隧道);本模块自带 runner 已够用,这里只做挂载标记。
150
+ mount('cloudflareNamed', () => runner);
151
+
152
+ return { start, stop, configure, disconnect, remove, status, syncLocalPort };
153
+ }
154
+
155
+ module.exports = { mountNamedCloudflare };
@@ -1,4 +1,5 @@
1
1
  // FRP 下载逐源分配预算,响应体同样受时限约束,坏校验不阻断后续镜像。
2
+ // 2026-11-29:本机到点掐断单独报「超时没下完」,不再把 AbortError 当成连不上。
2
3
  'use strict';
3
4
 
4
5
  // 2026-11-18:下载加国内镜像回退(官方不通自动换源,仍按同一份 sha256 校验),失败文案挖出 cause 真话。
@@ -260,7 +261,8 @@ async function downloadTo({ url, asset, dir, fetchImpl, timeoutMs = DOWNLOAD_TIM
260
261
  const doFetch = fetchImpl || globalThis.fetch;
261
262
  if (typeof doFetch !== 'function') throw codedError('no-fetch', '当前环境没有可用的 fetch');
262
263
  const controller = typeof AbortController === 'function' ? new AbortController() : null;
263
- const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
264
+ let timedOut = false;
265
+ const timer = controller ? setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs) : null;
264
266
  let buffer;
265
267
  try {
266
268
  const response = await doFetch(url, controller ? { signal: controller.signal } : {});
@@ -269,6 +271,9 @@ async function downloadTo({ url, asset, dir, fetchImpl, timeoutMs = DOWNLOAD_TIM
269
271
  }
270
272
  buffer = Buffer.from(await response.arrayBuffer());
271
273
  } catch (error) {
274
+ // 到点是我们自己掐断的,不是对端连不上。别把 AbortError 的 "This operation was aborted"
275
+ // 当成底层原因往外报——那会把排查引向 VPN / 代理,真相只是这一源没在时限内下完。
276
+ if (timedOut) throw codedError('download-failed', `本源 ${Math.max(1, Math.round(timeoutMs / 1000))} 秒内没下完(本机时限,不是连不上)`);
272
277
  throw codedError('download-failed', `下载 frpc 失败:${fetchErrorMessage(error)}`);
273
278
  } finally {
274
279
  if (timer) clearTimeout(timer);