dsh-mobile-plugin 0.5.135 → 0.5.136
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/config/agent-presets/standard/skills/dsh-mobile-kb/references/zeronews.md +1 -1
- package/lib/cloudflared/runner.cjs +10 -5
- package/lib/cloudflared/wiring.cjs +10 -9
- package/lib/impl.js +1 -1
- package/lib/panel/index.html +4 -4
- package/lib/relay/pairing-check.cjs +9 -1
- package/lib/zeronews/account.cjs +45 -6
- package/lib/zeronews/provision.cjs +78 -3
- package/lib/zeronews/purge.cjs +3 -1
- package/lib/zeronews/runner.cjs +82 -12
- package/lib/zeronews/upgrade.cjs +260 -0
- package/lib/zeronews/watcher.cjs +2 -2
- package/lib/zeronews/wiring.cjs +183 -13
- package/package.json +14 -15
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 2026-11-28:服务商 TCP 线路(FRP)在码里是裸 host:port,自检前补 tcp:// 才拨得通。
|
|
1
2
|
// 2026-11-26:配对地址自检——把二维码里要带的每条地址真拨一次,拨不通的别写进码里。
|
|
2
3
|
'use strict';
|
|
3
4
|
|
|
@@ -70,7 +71,14 @@ function targetsOf(payload) {
|
|
|
70
71
|
|
|
71
72
|
if (typeof p.relayUrl === 'string' && p.relayUrl) add({ kind: 'relay', url: p.relayUrl });
|
|
72
73
|
for (const row of Array.isArray(p.routes) ? p.routes : []) {
|
|
73
|
-
|
|
74
|
+
const url = row && typeof row.url === 'string' ? row.url.trim().replace(/\/+$/, '') : '';
|
|
75
|
+
// FRP 这类 TCP 线路在码里是裸 `host:port`(见 provider-lines.cjs),和下面 tcpUrl 那一支
|
|
76
|
+
// 走同一口径补上 scheme,probeTarget 的 new URL 才认得。customRoutes 里可能已带 scheme,
|
|
77
|
+
// 幂等:有 scheme 就不动。
|
|
78
|
+
const normalized = row && row.transport === 'tcp' && url && !/^[a-z][a-z0-9+.-]*:\/\//i.test(url)
|
|
79
|
+
? `tcp://${url}`
|
|
80
|
+
: url;
|
|
81
|
+
add({ kind: 'route', url: normalized, name: row && row.name, transport: row && row.transport });
|
|
74
82
|
}
|
|
75
83
|
if (typeof p.directUrl === 'string' && p.directUrl) add({ kind: 'direct', url: p.directUrl });
|
|
76
84
|
if (typeof p.tcpUrl === 'string' && p.tcpUrl) add({ kind: 'tcp', url: `tcp://${p.tcpUrl}`, transport: 'tcp' });
|
package/lib/zeronews/account.cjs
CHANGED
|
@@ -6,13 +6,16 @@
|
|
|
6
6
|
* · `status --json` —— 登录 / 连接状态、client_id、节点、主机、版本、最近心跳、套餐名、账号;
|
|
7
7
|
* · `show devices --json` —— 账号下所有设备(在线、版本、系统、IP、接入时间……);
|
|
8
8
|
* · `show tunnels --json` —— 账号下所有隧道(域名、协议、带宽、状态、转发到本机哪个端口……);
|
|
9
|
-
* · `show domains --json` —— 账号下的域名(默认域名 /
|
|
9
|
+
* · `show domains --json` —— 账号下的域名(默认域名 / 自有域名);
|
|
10
|
+
* · `show traffic --json` —— 本计费周期的流量用量(4.1.1 起才有)。
|
|
10
11
|
*
|
|
11
12
|
* 这里只做「读 + 归一」,全部字段按官方 JSON 的真实形状挑,缺字段就给空值,不让界面出现 undefined。
|
|
12
13
|
* 定位可执行文件走 provision 的 locate(只找不下),客户端没装就如实回 available:false,绝不顺手下载。
|
|
13
14
|
*
|
|
14
|
-
* 官方 CLI 与本地 API
|
|
15
|
-
*
|
|
15
|
+
* 官方 CLI 与本地 API 都没暴露「隧道 / 设备」的配额上限,只有套餐名与已用数量,所以这两项只给
|
|
16
|
+
* 「套餐名 + 已用数量」,不编造上限。流量那格反过来:CLI 直接给总量与已用量,照原样透出,
|
|
17
|
+
* 只在两个数都读得出时标一下是否已经超出(超出会被限速,是「连上了却很慢」最常见的解释)。
|
|
18
|
+
* 所有命令 / 定位都可注入,守卫用假体走完整条分支。
|
|
16
19
|
*/
|
|
17
20
|
|
|
18
21
|
const { execFile } = require('node:child_process');
|
|
@@ -75,6 +78,36 @@ function totalOf(page, items) {
|
|
|
75
78
|
return items.length;
|
|
76
79
|
}
|
|
77
80
|
|
|
81
|
+
/** 流量字符串里的单位换算成字节数:`1.41 GiB` → 1513975972。认不出就 0。 */
|
|
82
|
+
const SIZE_UNITS = {
|
|
83
|
+
B: 1, KB: 1e3, MB: 1e6, GB: 1e9, TB: 1e12,
|
|
84
|
+
KIB: 1024, MIB: 1024 ** 2, GIB: 1024 ** 3, TIB: 1024 ** 4,
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
function sizeBytes(value) {
|
|
88
|
+
const match = /^\s*([\d.]+)\s*([A-Za-z]+)\s*$/.exec(String(value || ''));
|
|
89
|
+
if (!match) return 0;
|
|
90
|
+
const unit = SIZE_UNITS[match[2].toUpperCase()];
|
|
91
|
+
const amount = Number(match[1]);
|
|
92
|
+
if (!unit || !Number.isFinite(amount)) return 0;
|
|
93
|
+
return Math.round(amount * unit);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* `show traffic --json` 归一。官方回的键是中文(`总流量` / `已使用流量`),值自带单位,
|
|
98
|
+
* 照原样显示,别自己换算成别的单位。老客户端没有这条命令、或键名变了,一律给 null,
|
|
99
|
+
* 面板据此不显示这一行。
|
|
100
|
+
*/
|
|
101
|
+
function normalizeTraffic(raw) {
|
|
102
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
103
|
+
const total = str(raw['总流量']).trim();
|
|
104
|
+
const used = str(raw['已使用流量']).trim();
|
|
105
|
+
if (!total && !used) return null;
|
|
106
|
+
const totalBytes = sizeBytes(total);
|
|
107
|
+
const usedBytes = sizeBytes(used);
|
|
108
|
+
return { total, used, totalBytes, usedBytes, over: totalBytes > 0 && usedBytes > totalBytes };
|
|
109
|
+
}
|
|
110
|
+
|
|
78
111
|
/** status --json 归一到面板用的字段。 */
|
|
79
112
|
function normalizeClient(raw) {
|
|
80
113
|
if (!raw || typeof raw !== 'object') return null;
|
|
@@ -207,6 +240,7 @@ function emptySnapshot(extra = {}) {
|
|
|
207
240
|
client: null,
|
|
208
241
|
account: { planName: '', userId: '', userTel: '' },
|
|
209
242
|
counts: { tunnels: 0, devices: 0, domains: 0 },
|
|
243
|
+
traffic: null,
|
|
210
244
|
tunnels: [],
|
|
211
245
|
devices: [],
|
|
212
246
|
domains: [],
|
|
@@ -257,11 +291,14 @@ function createZeroNewsAccountReader(options = {}) {
|
|
|
257
291
|
resourcesLoaded: false,
|
|
258
292
|
});
|
|
259
293
|
}
|
|
260
|
-
//
|
|
261
|
-
|
|
294
|
+
// 几张清单彼此独立,一起拉;某一张读失败就空着,不把整页带崩。
|
|
295
|
+
// 流量是 4.1.1 才有的命令,老客户端执行它只会打帮助文本、照样退 0;
|
|
296
|
+
// 读不出就 traffic 为空,面板不显示这一行,别让它把「清单读失败」的提示带出来。
|
|
297
|
+
const [devicesRes, tunnelsRes, domainsRes, trafficRes] = await Promise.all([
|
|
262
298
|
runJson(binary, ['show', 'devices', '--json']),
|
|
263
299
|
runJson(binary, ['show', 'tunnels', '--json']),
|
|
264
300
|
runJson(binary, ['show', 'domains', '--json']),
|
|
301
|
+
runJson(binary, ['show', 'traffic', '--json']),
|
|
265
302
|
]);
|
|
266
303
|
const deviceItems = itemsOf(devicesRes.parsed);
|
|
267
304
|
const tunnelItems = itemsOf(tunnelsRes.parsed);
|
|
@@ -280,6 +317,7 @@ function createZeroNewsAccountReader(options = {}) {
|
|
|
280
317
|
tunnels: totalOf(tunnelsRes.parsed, tunnelItems),
|
|
281
318
|
domains: totalOf(domainsRes.parsed, domainItems),
|
|
282
319
|
},
|
|
320
|
+
traffic: normalizeTraffic(trafficRes.parsed),
|
|
283
321
|
devices: compact(deviceItems.map(normalizeDevice)),
|
|
284
322
|
tunnels: compact(tunnelItems.map(normalizeTunnel)),
|
|
285
323
|
domains: compact(domainItems.map(normalizeDomain)),
|
|
@@ -291,5 +329,6 @@ function createZeroNewsAccountReader(options = {}) {
|
|
|
291
329
|
|
|
292
330
|
module.exports = {
|
|
293
331
|
DEFAULT_TIMEOUT_MS, parseJson, normalizeClient, normalizeAccount, normalizeDevice,
|
|
294
|
-
normalizeTunnel, normalizeDomain, tunnelLocal, tunnelDomain,
|
|
332
|
+
normalizeTunnel, normalizeDomain, normalizeTraffic, sizeBytes, tunnelLocal, tunnelDomain,
|
|
333
|
+
createZeroNewsAccountReader,
|
|
295
334
|
};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 2026-11-28:补 downloadClientTo:换代时把新版下到 <bin>.next,旁边在跑的那份原样不动。
|
|
1
2
|
// ZeroNews 客户端获取层:自带 → 系统 PATH → 缓存 → 官方地址下载,四平台固定路径。
|
|
2
3
|
'use strict';
|
|
3
4
|
|
|
@@ -9,8 +10,8 @@
|
|
|
9
10
|
* macOS arm64 https://download.zeronews.cc/macos/arm/zeronews
|
|
10
11
|
* macOS x64 https://download.zeronews.cc/macos/amd/zeronews
|
|
11
12
|
* Windows x64 https://download.zeronews.cc/windows/x64/zeronews.exe
|
|
12
|
-
* Linux x64 https://download.v2.zeronews.cc/linux/x86_x64/zeronews-linux-4.1.
|
|
13
|
-
* Linux arm64 https://download.v2.zeronews.cc/linux/arm64/zeronews-linux-4.1.
|
|
13
|
+
* Linux x64 https://download.v2.zeronews.cc/linux/x86_x64/zeronews-linux-4.1.1.tar (包内 zeronews/zeronews)
|
|
14
|
+
* Linux arm64 https://download.v2.zeronews.cc/linux/arm64/zeronews-linux-4.1.1.tar
|
|
14
15
|
*
|
|
15
16
|
* 三条来源按优先级:环境变量 / PATH 里已有 → 缓存 → 下载。Linux 下官方给的是 .tar,
|
|
16
17
|
* 这里只挑出里面的 zeronews 可执行文件落盘。所有 I/O 都可注入,守卫用假体走完整条分支。
|
|
@@ -20,7 +21,7 @@ const fs = require('node:fs');
|
|
|
20
21
|
const path = require('node:path');
|
|
21
22
|
const { dshHome } = require('../shared/paths.js');
|
|
22
23
|
|
|
23
|
-
const VERSION = '4.1.
|
|
24
|
+
const VERSION = '4.1.1';
|
|
24
25
|
const DOWNLOADS = {
|
|
25
26
|
'darwin-arm64': 'https://download.zeronews.cc/macos/arm/zeronews',
|
|
26
27
|
'darwin-x64': 'https://download.zeronews.cc/macos/amd/zeronews',
|
|
@@ -88,6 +89,12 @@ function locateZeroNews(options = {}) {
|
|
|
88
89
|
|
|
89
90
|
const explicit = readEnv('DSHM_ZERONEWS_BIN');
|
|
90
91
|
if (explicit && exists(explicit)) return { ok: true, path: explicit, source: 'env' };
|
|
92
|
+
// 用户自己装的客户端在只读位置时,换代会把它搬到插件目录并在这里记一笔;之后一律用这一份。
|
|
93
|
+
const active = typeof options.active === 'function' ? options.active() : options.active;
|
|
94
|
+
const activePath = typeof active === 'string' && active ? active : (() => {
|
|
95
|
+
try { return String(fsImpl.readFileSync(activeMarkerPath(options), 'utf8')).trim(); } catch { return ''; }
|
|
96
|
+
})();
|
|
97
|
+
if (activePath && exists(activePath)) return { ok: true, path: activePath, source: 'active' };
|
|
91
98
|
// macOS 上官方默认装到 /Applications/zeronews/zeronews(那份可能已经登录),优先复用,别另起一份未登录的。
|
|
92
99
|
if ((plat.platform || process.platform) === 'darwin') {
|
|
93
100
|
const systemInstalled = path.join('/Applications/zeronews', binName);
|
|
@@ -101,6 +108,73 @@ function locateZeroNews(options = {}) {
|
|
|
101
108
|
return { ok: false, path: '', source: '', code: 'not-installed' };
|
|
102
109
|
}
|
|
103
110
|
|
|
111
|
+
function permissionCode(error) {
|
|
112
|
+
const code = error && typeof error.code === 'string' ? error.code : '';
|
|
113
|
+
return code === 'EACCES' || code === 'EPERM' || code === 'EROFS' || code === 'EBUSY' || code === 'ENOTDIR';
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** 插件自己那份客户端的落点(换代时搬到这里,位置一定可写)。 */
|
|
117
|
+
function ownBinaryPath(options = {}) {
|
|
118
|
+
const binName = (options.platform && options.platform.platform ? options.platform.platform : process.platform) === 'win32' ? 'zeronews.exe' : 'zeronews';
|
|
119
|
+
return path.join(runDir(options.root), binName);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* 插件自己选定的那份客户端(搬到自己目录之后用):内容是一行绝对路径。
|
|
124
|
+
* 放文件而不是塞进设置,是为了不扩移动端设置契约 —— 它只影响本机用哪个可执行文件。
|
|
125
|
+
*/
|
|
126
|
+
function activeMarkerPath(options = {}) {
|
|
127
|
+
return path.join(runDir(options.root), '.active-binary');
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* 把官方客户端下载到指定路径(换代用:落到 `<bin>.next`,正在跑的那份原样不动)。
|
|
132
|
+
*
|
|
133
|
+
* 先写 `dest.download` 再改名:中途断网只会留下一个临时文件,不会出现半截可执行文件被当成新版。
|
|
134
|
+
* 平台认不出 / 没网 / 下载失败都如实回,绝不覆盖调用方已有的东西。
|
|
135
|
+
*
|
|
136
|
+
* @param {string} dest 目标文件路径
|
|
137
|
+
* @param {object} [options] 与 ensureZeroNews 同一组注入点
|
|
138
|
+
* @returns {Promise<{ok:boolean, path:string, code?:string}>}
|
|
139
|
+
*/
|
|
140
|
+
async function downloadClientTo(dest, options = {}) {
|
|
141
|
+
const doFetch = typeof options.fetchImpl === 'function'
|
|
142
|
+
? options.fetchImpl
|
|
143
|
+
: (typeof globalThis.fetch === 'function' ? globalThis.fetch : null);
|
|
144
|
+
const plat = options.platform || {};
|
|
145
|
+
const key = platformId(plat.platform, plat.arch);
|
|
146
|
+
if (!key) return { ok: false, path: '', code: 'unsupported-platform' };
|
|
147
|
+
if (!doFetch || !dest) return { ok: false, path: '', code: 'download-failed' };
|
|
148
|
+
const fsImpl = options.fsImpl || fs;
|
|
149
|
+
const staging = `${dest}.download`;
|
|
150
|
+
// 换代这条路跑在体检定时器里:下载要是挂住,后面的体检也跟着停。给个上限,超时当这次没下成。
|
|
151
|
+
const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : 180_000;
|
|
152
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
153
|
+
const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
|
|
154
|
+
try {
|
|
155
|
+
const response = await doFetch(DOWNLOADS[key], controller ? { signal: controller.signal } : undefined);
|
|
156
|
+
if (!response || response.ok !== true) return { ok: false, path: '', code: 'download-failed' };
|
|
157
|
+
let bytes = Buffer.from(await response.arrayBuffer());
|
|
158
|
+
if (TAR_PLATFORMS.has(key)) {
|
|
159
|
+
const extracted = extractFromTar(bytes);
|
|
160
|
+
if (!extracted) return { ok: false, path: '', code: 'extract-failed' };
|
|
161
|
+
bytes = extracted;
|
|
162
|
+
}
|
|
163
|
+
fsImpl.mkdirSync(path.dirname(dest), { recursive: true });
|
|
164
|
+
fsImpl.writeFileSync(staging, bytes, { mode: 0o755 });
|
|
165
|
+
fsImpl.rmSync(dest, { force: true });
|
|
166
|
+
fsImpl.renameSync(staging, dest);
|
|
167
|
+
return { ok: true, path: dest };
|
|
168
|
+
} catch (error) {
|
|
169
|
+
try { fsImpl.rmSync(staging, { force: true }); } catch { /* 清不掉也不影响返回 */ }
|
|
170
|
+
// 只读安装位置(用户自己装在 /usr/local/bin、Program Files 这种)与「没网」要分开:
|
|
171
|
+
// 前者只能换到插件自己的目录去升级,后者等下一轮再试就行。
|
|
172
|
+
return { ok: false, path: '', code: permissionCode(error) ? 'no-permission' : 'download-failed' };
|
|
173
|
+
} finally {
|
|
174
|
+
if (timer) clearTimeout(timer);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
104
178
|
/**
|
|
105
179
|
* @param {object} options
|
|
106
180
|
* @param {() => string} [options.env] 读环境变量(PATH / DSHM_ZERONEWS_BIN)
|
|
@@ -147,4 +221,5 @@ async function ensureZeroNews(options = {}) {
|
|
|
147
221
|
|
|
148
222
|
module.exports = {
|
|
149
223
|
VERSION, DOWNLOADS, platformId, downloadUrlOf, runDir, extractFromTar, locateZeroNews, ensureZeroNews,
|
|
224
|
+
downloadClientTo, ownBinaryPath, activeMarkerPath,
|
|
150
225
|
};
|
package/lib/zeronews/purge.cjs
CHANGED
|
@@ -17,7 +17,7 @@ const fs = require('node:fs');
|
|
|
17
17
|
const os = require('node:os');
|
|
18
18
|
const path = require('node:path');
|
|
19
19
|
const { execFile } = require('node:child_process');
|
|
20
|
-
const { locateZeroNews, runDir } = require('./provision.cjs');
|
|
20
|
+
const { locateZeroNews, runDir, activeMarkerPath } = require('./provision.cjs');
|
|
21
21
|
|
|
22
22
|
/** 卸载系统服务 + 删配置可能比普通命令慢,给足一分半。 */
|
|
23
23
|
const RESET_TIMEOUT_MS = 90_000;
|
|
@@ -124,6 +124,8 @@ async function purgeZeroNews(options = {}) {
|
|
|
124
124
|
}
|
|
125
125
|
|
|
126
126
|
// 只删插件自己下载的缓存二进制;系统安装 / PATH 上那份不归我们管。
|
|
127
|
+
// 搬到自己目录时留的那行标记也一起清掉,否则下次会指着一个已经删掉的文件。
|
|
128
|
+
try { fsImpl.rmSync(activeMarkerPath({ root: options.root }), { force: true }); } catch { /* 没标记就算了 */ }
|
|
127
129
|
try {
|
|
128
130
|
fsImpl.rmSync(cached, { force: true });
|
|
129
131
|
result.cacheRemoved = true;
|
package/lib/zeronews/runner.cjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 2026-11-28:官方 4.1.1 起可用 `tunnel <id> set-local` 原地把旧隧道改到当前端口,失配时自动改,不再只报错。
|
|
1
2
|
// 2026-11-27:复用本机已在跑的客户端前比对 client_id / cloud_server_addr,另一个身份占位就明确报错不 attach。
|
|
2
3
|
// 2026-11-27:外部把隧道重建到新端口时,先用 endpoints 的落点刷新本次比对值,第一次 connect 就认下新端口。
|
|
3
4
|
// 2026-11-26:体检发现旧隧道落点端口没人监听就判失效(只改本机状态,不删不建云端隧道),交接线层清地址让兜底顶上。
|
|
@@ -93,7 +94,11 @@ function localPortOf(item) {
|
|
|
93
94
|
return 0;
|
|
94
95
|
}
|
|
95
96
|
|
|
96
|
-
/**
|
|
97
|
+
/**
|
|
98
|
+
* 从 endpoints 响应里取第一条 active 的 HTTPS 隧道:{ url, localPort, tunnelId },没有就 null。
|
|
99
|
+
* tunnelId 用来在落点失配时调 `tunnel <id> set-local` 原地改端口:本地 API 平铺给 `tunnel_id`,
|
|
100
|
+
* 账号侧那份是 `id`,两个都认。
|
|
101
|
+
*/
|
|
97
102
|
function pickEndpointDetail(payload) {
|
|
98
103
|
const data = payload && typeof payload === 'object' && 'data' in payload ? payload.data : payload;
|
|
99
104
|
const items = Array.isArray(data) ? data
|
|
@@ -108,7 +113,11 @@ function pickEndpointDetail(payload) {
|
|
|
108
113
|
const domain = typeof item.domain === 'string' && item.domain ? item.domain
|
|
109
114
|
: typeof item.public_url === 'string' ? item.public_url : '';
|
|
110
115
|
const url = endpointUrl(domain.includes('://') ? domain : `https://${domain}`);
|
|
111
|
-
if (url)
|
|
116
|
+
if (url) {
|
|
117
|
+
const tunnelId = typeof item.tunnel_id === 'string' && item.tunnel_id ? item.tunnel_id
|
|
118
|
+
: typeof item.id === 'string' ? item.id : '';
|
|
119
|
+
return { url, localPort: localPortOf(item), tunnelId };
|
|
120
|
+
}
|
|
112
121
|
}
|
|
113
122
|
return null;
|
|
114
123
|
}
|
|
@@ -180,6 +189,7 @@ function terminalError(message, reason) {
|
|
|
180
189
|
* @param {(bin:string,args:string[],opts:object)=>Promise<{code:number,stdout:string,stderr:string}>} [options.runImpl] 一次性命令注入
|
|
181
190
|
* @param {(port:number)=>Promise<boolean>} [options.probePort] 隧道落点端口有没有人监听(体检用,测试注入)
|
|
182
191
|
* @param {() => {clientId:string,node:string}} [options.identityOf] 当前配置记录的客户端身份(接线层从落盘状态读)
|
|
192
|
+
* @param {(binary:string)=>void} [options.onBinary] 拿到可执行文件后的回调(换代收尾用)
|
|
183
193
|
* @param {string} [options.base] 本地 API 根
|
|
184
194
|
*/
|
|
185
195
|
function createZeroNewsRunner(options = {}) {
|
|
@@ -191,6 +201,7 @@ function createZeroNewsRunner(options = {}) {
|
|
|
191
201
|
const runImpl = typeof options.runImpl === 'function' ? options.runImpl : defaultRun;
|
|
192
202
|
const probePort = typeof options.probePort === 'function' ? options.probePort : defaultProbePort;
|
|
193
203
|
const identityOf = typeof options.identityOf === 'function' ? options.identityOf : () => ({});
|
|
204
|
+
const onBinary = typeof options.onBinary === 'function' ? options.onBinary : null;
|
|
194
205
|
const base = String(options.base || DEFAULT_BASE).replace(/\/+$/, '');
|
|
195
206
|
const sleep = typeof options.sleepImpl === 'function' ? options.sleepImpl : (ms) => new Promise((r) => setTimeout(r, ms));
|
|
196
207
|
|
|
@@ -302,10 +313,12 @@ function createZeroNewsRunner(options = {}) {
|
|
|
302
313
|
}
|
|
303
314
|
|
|
304
315
|
/** 轮询 status.login,等浏览器确认完成(或超时 / 出现明确失败原因)。 */
|
|
305
|
-
async function waitLogin(timeoutMs) {
|
|
316
|
+
async function waitLogin(timeoutMs, gen) {
|
|
306
317
|
const deadline = Date.now() + timeoutMs;
|
|
307
318
|
for (let i = 0; i < LOGIN_POLL_MAX && Date.now() < deadline; i += 1) {
|
|
319
|
+
if (gen !== generation) return false;
|
|
308
320
|
const s = await cliStatus();
|
|
321
|
+
if (gen !== generation) return false;
|
|
309
322
|
if (s && (s.login === true || s.login === 'true')) return true;
|
|
310
323
|
// 明确失败(配额 / 拒绝 / 过期)就别再空等,交给上面按原因报错。
|
|
311
324
|
if (s && s.loginError) return false;
|
|
@@ -315,10 +328,12 @@ function createZeroNewsRunner(options = {}) {
|
|
|
315
328
|
}
|
|
316
329
|
|
|
317
330
|
/** 轮询 endpoints 拿到隧道域名,最多等到 START_TIMEOUT_MS。 */
|
|
318
|
-
async function waitEndpoint(timeoutMs, port) {
|
|
331
|
+
async function waitEndpoint(timeoutMs, port, gen) {
|
|
319
332
|
const deadline = Date.now() + timeoutMs;
|
|
320
333
|
for (let i = 0; i < START_POLL_MAX && Date.now() < deadline; i += 1) {
|
|
334
|
+
if (gen !== generation) return '';
|
|
321
335
|
const payload = await api('/api/v1/endpoints');
|
|
336
|
+
if (gen !== generation) return '';
|
|
322
337
|
const found = pickEndpoint(payload, port);
|
|
323
338
|
if (found) return found;
|
|
324
339
|
await sleep(1500);
|
|
@@ -326,13 +341,38 @@ function createZeroNewsRunner(options = {}) {
|
|
|
326
341
|
return '';
|
|
327
342
|
}
|
|
328
343
|
|
|
344
|
+
/**
|
|
345
|
+
* 把一条已经建好的隧道改指到本机当前端口:官方 4.1.1 起的
|
|
346
|
+
* `tunnel <id> set-local <ip> <port> --json`,原地改、不删隧道、不占额度、公网域名不变。
|
|
347
|
+
* 老客户端(4.1.0 及以前)没有这个子命令,却照样以 0 退出、只打帮助文本 ——
|
|
348
|
+
* 所以判据只认 JSON 里的 `ok: true`,认不出就当「不支持」,绝不把帮助文本当成功。
|
|
349
|
+
*/
|
|
350
|
+
async function repointTunnel(tunnelId, port, gen) {
|
|
351
|
+
const result = await runImpl(binary, ['tunnel', tunnelId, 'set-local', '127.0.0.1', String(port), '--json'], { timeoutMs: 20_000 });
|
|
352
|
+
if (gen !== generation) return { ok: false, supported: false, detail: '' };
|
|
353
|
+
const text = String((result && result.stdout) || '').trim();
|
|
354
|
+
const start = text.indexOf('{');
|
|
355
|
+
const end = text.lastIndexOf('}');
|
|
356
|
+
if (start >= 0 && end > start) {
|
|
357
|
+
try {
|
|
358
|
+
const parsed = JSON.parse(text.slice(start, end + 1));
|
|
359
|
+
if (parsed && parsed.ok === true) return { ok: true, supported: true, detail: '' };
|
|
360
|
+
} catch { /* 落到下面按原文报 */ }
|
|
361
|
+
}
|
|
362
|
+
const raw = String((result && result.stderr) || '').trim() || text.split('\n')[0];
|
|
363
|
+
const code = result && typeof result.code === 'number' ? result.code : 0;
|
|
364
|
+
if (code !== 0) return { ok: false, supported: true, detail: raw || `改端口退出码 ${code}` };
|
|
365
|
+
return { ok: false, supported: false, detail: raw };
|
|
366
|
+
}
|
|
367
|
+
|
|
329
368
|
/**
|
|
330
369
|
* 确保有一条指向本机端口的 HTTPS 隧道:已有一条就复用(免费档只有一条额度)。
|
|
331
370
|
* 建隧道走 CLI `add https --port N --json`(官方稳定接口;本地 /api/v1/tunnels 的字段口径会变,
|
|
332
371
|
* 直接用裸 API 会因未知字段被拒)。`add` 的 JSON 里带 public_url 就直接用,没有就回读 endpoints。
|
|
333
372
|
*/
|
|
334
|
-
async function ensureTunnel(port) {
|
|
373
|
+
async function ensureTunnel(port, gen) {
|
|
335
374
|
const found = pickEndpointDetail(await api('/api/v1/endpoints'));
|
|
375
|
+
if (gen !== generation) return '';
|
|
336
376
|
const requested = Number.isInteger(port) && port > 0 ? port : 0;
|
|
337
377
|
if (found) {
|
|
338
378
|
// portOf() 优先返回上一轮记下的隧道端口;本次传入值与缓存相同就说明它来自缓存。
|
|
@@ -343,9 +383,21 @@ function createZeroNewsRunner(options = {}) {
|
|
|
343
383
|
if (fromCache && Number.isInteger(found.localPort) && found.localPort > 0) current = found.localPort;
|
|
344
384
|
tunnelLocalPort = Number.isInteger(found.localPort) && found.localPort > 0 ? found.localPort : 0;
|
|
345
385
|
// 只有字段明确在、且指向另一个端口才算失配:老接口的 endpoints 没有 local_port,
|
|
346
|
-
//
|
|
347
|
-
//
|
|
386
|
+
// 那种照旧复用。失配时先用官方 `set-local` 把这条隧道原地指到当前端口(不删、不建、
|
|
387
|
+
// 不占额度、域名不变);客户端太旧没有这个子命令、或账号侧拒绝,才如实报错让用户自己处理。
|
|
348
388
|
if (current > 0 && found.localPort > 0 && found.localPort !== current) {
|
|
389
|
+
const moved = found.tunnelId ? await repointTunnel(found.tunnelId, current, gen) : null;
|
|
390
|
+
if (gen !== generation) return '';
|
|
391
|
+
if (moved && moved.ok) {
|
|
392
|
+
tunnelLocalPort = current;
|
|
393
|
+
return found.url;
|
|
394
|
+
}
|
|
395
|
+
if (moved && moved.supported) {
|
|
396
|
+
throw terminalError(`旧隧道指向旧端口,自动改到当前端口失败(${moved.detail}):请在 ZeroNews 控制台把隧道目标改成 ${current} 后重试(旧端口 ${found.localPort})`, 'port-mismatch');
|
|
397
|
+
}
|
|
398
|
+
if (moved) {
|
|
399
|
+
throw terminalError(`旧隧道指向旧端口,本机客户端不支持自动改端口:请把 ZeroNews 客户端升级到 4.1.1 后重试,或在控制台把隧道目标改成 ${current}(旧端口 ${found.localPort})`, 'port-mismatch');
|
|
400
|
+
}
|
|
349
401
|
throw terminalError(`旧隧道指向旧端口,请删除后重试(旧端口 ${found.localPort},当前本机端口 ${current})`, 'port-mismatch');
|
|
350
402
|
}
|
|
351
403
|
return found.url;
|
|
@@ -357,6 +409,7 @@ function createZeroNewsRunner(options = {}) {
|
|
|
357
409
|
let addError = '';
|
|
358
410
|
try {
|
|
359
411
|
const result = await runImpl(binary, ['add', 'https', `--port=${port}`, '--json'], { timeoutMs: 20000 });
|
|
412
|
+
if (gen !== generation) return '';
|
|
360
413
|
const text = String((result && result.stdout) || '').trim();
|
|
361
414
|
if (result && result.code !== 0) {
|
|
362
415
|
addError = String(result.stderr || result.stdout || '').trim() || `建隧道退出码 ${result.code}`;
|
|
@@ -372,7 +425,9 @@ function createZeroNewsRunner(options = {}) {
|
|
|
372
425
|
}
|
|
373
426
|
// 新建成功:记住它落在哪个端口上,下次启动沿用,不再判成「旧隧道指向旧端口」。
|
|
374
427
|
if (added) { tunnelLocalPort = port; return added; }
|
|
375
|
-
|
|
428
|
+
if (gen !== generation) return '';
|
|
429
|
+
const waited = await waitEndpoint(START_TIMEOUT_MS, port, gen);
|
|
430
|
+
if (gen !== generation) return '';
|
|
376
431
|
if (waited) { tunnelLocalPort = port; return waited; }
|
|
377
432
|
// 免费档只有 1 条 1Mbps 隧道;额度被旧隧道占住、或账号侧拒绝时,原文要透出来,
|
|
378
433
|
// 别让用户只看到「连上了但拿不到地址」这种猜不出原因的提示。
|
|
@@ -391,11 +446,15 @@ function createZeroNewsRunner(options = {}) {
|
|
|
391
446
|
try {
|
|
392
447
|
phase = 'installing';
|
|
393
448
|
const got = await ensure();
|
|
449
|
+
if (gen !== generation) return status();
|
|
394
450
|
if (!got || !got.ok) throw new Error(got && got.code === 'unsupported-platform' ? '这台系统不支持自动安装 ZeroNews 客户端' : '下载 ZeroNews 客户端失败,请稍后重试');
|
|
395
451
|
binary = got.path;
|
|
452
|
+
// 换代的收尾(上次切换断在中间)在进程起来之前做完:宁可回到能跑的旧版,也别留一个空位。
|
|
453
|
+
if (onBinary) { try { onBinary(binary); } catch { /* 收尾失败不挡启动 */ } }
|
|
396
454
|
|
|
397
455
|
phase = 'login';
|
|
398
456
|
const st = await cliStatus();
|
|
457
|
+
if (gen !== generation) return status();
|
|
399
458
|
clientId = (st && st.clientId) || '';
|
|
400
459
|
node = (st && st.node) || '';
|
|
401
460
|
// 先看明确失败:配额满了 / 被拒 / 过期,都属于「别再等、直接告诉用户怎么办」。
|
|
@@ -410,6 +469,7 @@ function createZeroNewsRunner(options = {}) {
|
|
|
410
469
|
pendingToken = '';
|
|
411
470
|
if (token) {
|
|
412
471
|
const applied = await runImpl(binary, ['authtoken', token], { timeoutMs: 15000 });
|
|
472
|
+
if (gen !== generation) return status();
|
|
413
473
|
const detail = String((applied && (applied.stderr || applied.stdout)) || '').trim();
|
|
414
474
|
// 官方有一条明确的坑:本机已有 config.yml 时 token 会被忽略并保留旧配置(退出码可能仍是 0)。
|
|
415
475
|
// 不认这条就会「以为写成功了」,接着起客户端、建隧道,最后卡在拿不到地址,报错对不上真因。
|
|
@@ -429,10 +489,11 @@ function createZeroNewsRunner(options = {}) {
|
|
|
429
489
|
configured = true;
|
|
430
490
|
} else if (st && st.loginPending) {
|
|
431
491
|
// 已经发起登录、正在等确认:不重新拉起 login(会顶掉设备码),只轮询 status 让它兑换授权。
|
|
432
|
-
const loggedIn = await waitLogin(LOGIN_TIMEOUT_MS);
|
|
492
|
+
const loggedIn = await waitLogin(LOGIN_TIMEOUT_MS, gen);
|
|
433
493
|
if (gen !== generation) return status();
|
|
434
494
|
if (!loggedIn) {
|
|
435
495
|
const after = await cliStatus();
|
|
496
|
+
if (gen !== generation) return status();
|
|
436
497
|
if (after && after.loginError) throw terminalError(loginErrorHint(after.loginError));
|
|
437
498
|
if (after && after.loginPending) throw new Error('还在浏览器里等确认登录;确认完成后点「我已登录,重试」即可继续。');
|
|
438
499
|
throw new Error('还没有完成登录,请先点「开始接入」在浏览器里确认登录。');
|
|
@@ -480,11 +541,16 @@ function createZeroNewsRunner(options = {}) {
|
|
|
480
541
|
phase = 'connecting';
|
|
481
542
|
const healthDeadline = Date.now() + START_TIMEOUT_MS;
|
|
482
543
|
for (let i = 0; i < START_POLL_MAX && Date.now() < healthDeadline; i += 1) {
|
|
483
|
-
if (
|
|
544
|
+
if (gen !== generation) return status();
|
|
545
|
+
const healthy = await api('/healthz');
|
|
546
|
+
if (gen !== generation) return status();
|
|
547
|
+
if (healthy) break;
|
|
484
548
|
await sleep(1000);
|
|
485
549
|
}
|
|
486
|
-
url = await ensureTunnel(portOf());
|
|
487
550
|
if (gen !== generation) return status();
|
|
551
|
+
const resolvedUrl = await ensureTunnel(portOf(), gen);
|
|
552
|
+
if (gen !== generation) return status();
|
|
553
|
+
url = resolvedUrl;
|
|
488
554
|
if (!url) throw new Error('客户端已连上,但还没拿到隧道公网地址,请稍后刷新');
|
|
489
555
|
phase = 'connected';
|
|
490
556
|
// 隧道地址是从守护进程的本地 API 读到的:能读到就说明它活着,running 认这一格。
|
|
@@ -576,7 +642,11 @@ function createZeroNewsRunner(options = {}) {
|
|
|
576
642
|
return status();
|
|
577
643
|
}
|
|
578
644
|
|
|
579
|
-
|
|
645
|
+
/** 这次用的可执行文件:换代要拿着它下载新版、改名切换。单独给,不塞进 status——
|
|
646
|
+
* 那份会原样转发给手机,本机路径不进契约。 */
|
|
647
|
+
function binaryPath() { return binary; }
|
|
648
|
+
|
|
649
|
+
return { start, stop, status, checkAlive, pickEndpoint, endpointUrl, binaryPath };
|
|
580
650
|
}
|
|
581
651
|
|
|
582
652
|
module.exports = { DEFAULT_BASE, LOGIN_TIMEOUT_MS, START_TIMEOUT_MS, endpointUrl, pickEndpoint, createZeroNewsRunner };
|