dsh-mobile-plugin 0.5.95 → 0.5.97

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,303 @@
1
+ // ZeroNews 客户端运行器:ensure→login→start→建隧道→读域名,进程生命周期与状态。
2
+ 'use strict';
3
+
4
+ /**
5
+ * 把官方客户端从「没有」带到「有一个指向本机端口、拿到公网域名的隧道」。顺序照厂商现行流程:
6
+ * ① ensureZeroNews 拿到可执行文件(用户不装);
7
+ * ② 认证:优先用面板里粘贴的 AuthToken 跑 `authtoken`(厂商现行 CLI 的做法);没给 token 时才退回
8
+ * `login` 拉起浏览器让用户确认(login_pending / status.login 判定)。浏览器这条是给「这台机器
9
+ * 早就登录过」的用户留的快捷路,新机器一律要 token —— 快速开始页上的那串就是它;
10
+ * ③ `start` 起本地客户端 + HTTP API(幂等,已登录已运行就跳过);
11
+ * ④ 本地 API 建一条 HTTPS 隧道指向本机端口(已有则复用,免费档一条额度,绝不重复建);
12
+ * ⑤ 读 endpoints 拿公网域名 → 交调用方写进线路清单。
13
+ *
14
+ * 所有进程 / 网络 / 时钟都可注入,守卫用假体走完整条链,不连真网、不起真进程。
15
+ */
16
+
17
+ const { spawn, execFile } = require('node:child_process');
18
+ const path = require('node:path');
19
+
20
+ const DEFAULT_BASE = 'http://127.0.0.1:37271';
21
+ const LOGIN_TIMEOUT_MS = 5 * 60 * 1000; // 浏览器确认最长等 5 分钟,别一直挂在「登录中」。
22
+ const START_TIMEOUT_MS = 40_000;
23
+ // 轮询也按次数封顶:光看 wall-clock 的话,时钟源被替换或定时器被加速时会无限空转。
24
+ const LOGIN_POLL_MAX = 300;
25
+ const START_POLL_MAX = 40;
26
+
27
+ function endpointUrl(text) {
28
+ const raw = String(text || '').trim();
29
+ if (!/^https:\/\/[^\s/]+/i.test(raw)) return '';
30
+ try { return new URL(raw).hostname ? raw.replace(/\/+$/, '') : ''; } catch { return ''; }
31
+ }
32
+
33
+ /** 默认的一次性命令执行器:execFile 拿到 stdout/stderr/退出码,不经过 shell。 */
34
+ function defaultRun(binary, args, opts = {}) {
35
+ return new Promise((resolve) => {
36
+ execFile(binary, args, { timeout: opts.timeoutMs || 8000, cwd: path.dirname(binary), maxBuffer: 1 << 20 }, (err, stdout, stderr) => {
37
+ let code = 0;
38
+ if (err) code = typeof err.code === 'number' ? err.code : 1;
39
+ resolve({ code, stdout: String(stdout || ''), stderr: String(stderr || '') });
40
+ });
41
+ });
42
+ }
43
+
44
+ /** 从 endpoints 响应里取第一条 active 的 HTTPS 域名(兼容 data.items / 裸数组 / endpoints)。 */
45
+ function pickEndpoint(payload) {
46
+ const data = payload && typeof payload === 'object' && 'data' in payload ? payload.data : payload;
47
+ const items = Array.isArray(data) ? data
48
+ : (data && Array.isArray(data.items)) ? data.items
49
+ : (data && Array.isArray(data.endpoints)) ? data.endpoints : [];
50
+ for (const item of items) {
51
+ if (!item || typeof item !== 'object') continue;
52
+ const status = String(item.status || '').toLowerCase();
53
+ if (status && status !== 'active') continue;
54
+ const type = String(item.type || '').toUpperCase();
55
+ if (type && type !== 'HTTPS') continue;
56
+ const domain = typeof item.domain === 'string' && item.domain ? item.domain
57
+ : typeof item.public_url === 'string' ? item.public_url : '';
58
+ const url = endpointUrl(domain.includes('://') ? domain : `https://${domain}`);
59
+ if (url) return url;
60
+ }
61
+ return '';
62
+ }
63
+
64
+ /**
65
+ * @param {object} options
66
+ * @param {() => Promise<{ok:boolean,path:string,code?:string}>} options.ensure 取二进制(provision)
67
+ * @param {() => number} options.portOf 本机要映射的 LAN 端口
68
+ * @param {object} [options.spawnImpl] spawn 注入
69
+ * @param {(url:string, init:object)=>Promise<any>} [options.fetchImpl] 本地 API fetch 注入
70
+ * @param {(bin:string,args:string[],opts:object)=>Promise<{code:number,stdout:string,stderr:string}>} [options.runImpl] 一次性命令注入
71
+ * @param {string} [options.base] 本地 API 根
72
+ */
73
+ function createZeroNewsRunner(options = {}) {
74
+ const ensure = options.ensure;
75
+ const portOf = typeof options.portOf === 'function' ? options.portOf : () => 0;
76
+ const spawnImpl = typeof options.spawnImpl === 'function' ? options.spawnImpl : spawn;
77
+ const doFetch = typeof options.fetchImpl === 'function' ? options.fetchImpl
78
+ : (typeof globalThis.fetch === 'function' ? globalThis.fetch : null);
79
+ const runImpl = typeof options.runImpl === 'function' ? options.runImpl : defaultRun;
80
+ const base = String(options.base || DEFAULT_BASE).replace(/\/+$/, '');
81
+ const sleep = typeof options.sleepImpl === 'function' ? options.sleepImpl : (ms) => new Promise((r) => setTimeout(r, ms));
82
+
83
+ // 客户端退出(非我们主动 stop)时的回调:交接线层去安排自动重连,别让线路卡死在错误上。
84
+ const onUnexpectedExit = typeof options.onUnexpectedExit === 'function' ? options.onUnexpectedExit : null;
85
+
86
+ let child = null;
87
+ /** 本机已有一个不是我这次拉起的客户端在跑(插件重载 / 自动更新后常见):复用,不再重复起一个。 */
88
+ let attached = false;
89
+ /** 面板递进来、还没写进客户端配置的 AuthToken;只在本进程内存里停一下,不落盘、不记日志。 */
90
+ let pendingToken = '';
91
+ /** 这台机器的客户端有没有账户身份(token 写成功 / CLI 报已登录都算)。面板据此收起粘贴框。 */
92
+ let configured = false;
93
+ /** 同一次 start 只跑一份:自动重连、点「连接」、watch 触发撞在一起时,别并发拉起两个客户端。 */
94
+ let startPromise = null;
95
+ let binary = '';
96
+ let error = '';
97
+ let url = '';
98
+ let phase = 'off'; // off | installing | login | starting | connecting | connected | error
99
+ let generation = 0;
100
+
101
+ function status() {
102
+ return {
103
+ available: Boolean(binary) || phase !== 'off',
104
+ running: Boolean(child) || attached,
105
+ phase,
106
+ url: phase === 'connected' ? url : '',
107
+ error,
108
+ // 只反映这一进程里见过的身份;落盘的那份由接线层并进来(见 wiring.cjs 的 statusOf)。
109
+ configured,
110
+ };
111
+ }
112
+
113
+ /** 一次性跑一条命令,汇总 stdout/stderr/退出码(login 起浏览器那条用 spawn 不 wait)。 */
114
+ async function run(args) {
115
+ const result = await runImpl(binary, args, { timeoutMs: 8000 });
116
+ if (result && result.code !== 0) {
117
+ const msg = String(result.stderr || result.stdout || '').trim();
118
+ throw new Error(msg || `zeronews ${args[0]} 退出码 ${result.code}`);
119
+ }
120
+ return result;
121
+ }
122
+
123
+ /**
124
+ * 登录状态只信 CLI `status --json`,不信本地 HTTP API:
125
+ * 实测同一台已登录机器,CLI 报 `login:true`,而 `/api/v1/status` 报 `login:false`,两者不一致。
126
+ * 厂商 AI 指引的完成判据也是「`status --json` 为 `login:true` 且 running」。
127
+ */
128
+ async function cliStatus() {
129
+ try {
130
+ const result = await runImpl(binary, ['status', '--json'], { timeoutMs: 5000 });
131
+ const text = String((result && result.stdout) || '').trim();
132
+ const start = text.indexOf('{');
133
+ const end = text.lastIndexOf('}');
134
+ if (start < 0 || end <= start) return null;
135
+ return JSON.parse(text.slice(start, end + 1));
136
+ } catch { return null; }
137
+ }
138
+
139
+ async function api(pathname, init) {
140
+ if (!doFetch) return null;
141
+ let res;
142
+ try {
143
+ res = await doFetch(`${base}${pathname}`, { headers: { accept: 'application/json' }, ...(init || {}) });
144
+ } catch {
145
+ // 客户端刚起、端口还没监听时连不上是常态:返回 null 让上层继续轮询,不要当场抛。
146
+ return null;
147
+ }
148
+ if (!res || res.ok !== true) return null;
149
+ try { return await res.json(); } catch { return null; }
150
+ }
151
+
152
+ /** 轮询 status.login,等浏览器确认完成(或超时)。 */
153
+ async function waitLogin(timeoutMs) {
154
+ const deadline = Date.now() + timeoutMs;
155
+ for (let i = 0; i < LOGIN_POLL_MAX && Date.now() < deadline; i += 1) {
156
+ const s = await cliStatus();
157
+ if (s && (s.login === true || s.login === 'true')) return true;
158
+ await sleep(1000);
159
+ }
160
+ return false;
161
+ }
162
+
163
+ /** 轮询 endpoints 拿到隧道域名,最多等到 START_TIMEOUT_MS。 */
164
+ async function waitEndpoint(timeoutMs) {
165
+ const deadline = Date.now() + timeoutMs;
166
+ for (let i = 0; i < START_POLL_MAX && Date.now() < deadline; i += 1) {
167
+ const payload = await api('/api/v1/endpoints');
168
+ const found = pickEndpoint(payload);
169
+ if (found) return found;
170
+ await sleep(1500);
171
+ }
172
+ return '';
173
+ }
174
+
175
+ /**
176
+ * 确保有一条指向本机端口的 HTTPS 隧道:已有一条就复用(免费档只有一条额度)。
177
+ * 建隧道走 CLI `add https --port N --json`(官方稳定接口;本地 /api/v1/tunnels 的字段口径会变,
178
+ * 直接用裸 API 会因未知字段被拒)。`add` 的 JSON 里带 public_url 就直接用,没有就回读 endpoints。
179
+ */
180
+ async function ensureTunnel(port) {
181
+ const existing = pickEndpoint(await api('/api/v1/endpoints'));
182
+ if (existing) return existing;
183
+ if (!Number.isInteger(port) || port <= 0) return '';
184
+ let added = '';
185
+ try {
186
+ const result = await runImpl(binary, ['add', 'https', `--port=${port}`, '--json'], { timeoutMs: 20000 });
187
+ const text = String((result && result.stdout) || '').trim();
188
+ const start = text.indexOf('{');
189
+ const end = text.lastIndexOf('}');
190
+ if (start >= 0 && end > start) {
191
+ const parsed = JSON.parse(text.slice(start, end + 1));
192
+ added = endpointUrl(parsed.public_url || parsed.domain || '');
193
+ }
194
+ } catch { /* add 失败(可能已有隧道额度占满)就回读 endpoints */ }
195
+ if (added) return added;
196
+ return waitEndpoint(START_TIMEOUT_MS);
197
+ }
198
+
199
+ async function runStart() {
200
+ const gen = ++generation;
201
+ error = '';
202
+ url = '';
203
+ try {
204
+ phase = 'installing';
205
+ const got = await ensure();
206
+ if (!got || !got.ok) throw new Error(got && got.code === 'unsupported-platform' ? '这台系统不支持自动安装 ZeroNews 客户端' : '下载 ZeroNews 客户端失败,请稍后重试');
207
+ binary = got.path;
208
+
209
+ phase = 'login';
210
+ const already = await cliStatus();
211
+ // 有 token 就先写进客户端配置:之后照常起客户端、建隧道,不再拉浏览器。
212
+ // 写完就把内存里那份清掉 —— 失败也一样,避免自动重连拿同一串无效 token 反复试。
213
+ const token = pendingToken;
214
+ pendingToken = '';
215
+ if (token) {
216
+ const applied = await runImpl(binary, ['authtoken', token], { timeoutMs: 15000 });
217
+ if (!applied || applied.code !== 0) {
218
+ const detail = String((applied && (applied.stderr || applied.stdout)) || '').trim();
219
+ throw new Error(detail || 'AuthToken 写入失败,请确认从「快速开始」页复制完整');
220
+ }
221
+ configured = true;
222
+ } else if (already && (already.login === true || already.login === 'true')) {
223
+ // 这台机器早就有身份(以前登录过 / 以前粘过 token):记下来,面板不用再要一次。
224
+ configured = true;
225
+ } else {
226
+ // 没给 token 且这台机器没登录过:拉起浏览器登录,等用户确认。
227
+ const who = spawnImpl(binary, ['login'], { stdio: 'ignore', cwd: path.dirname(binary) });
228
+ if (who && typeof who.on === 'function') who.on('error', () => {});
229
+ const loggedIn = await waitLogin(LOGIN_TIMEOUT_MS);
230
+ if (gen !== generation) return status();
231
+ if (!loggedIn) throw new Error('等待浏览器确认登录超时;请把「快速开始」页的 AuthToken 粘到面板里再试');
232
+ }
233
+
234
+ phase = 'starting';
235
+ // 本机已经有一个客户端在跑(插件重载 / 自动更新后没被这次拉起、上一条还活着):直接复用它,
236
+ // 绝不再 spawn 第二个 —— 免费档只认一台设备,重复拉起会让第二个自己退出,表现成「客户端意外退出」。
237
+ const externalRunning = Boolean(already && (already.running === true || already.running === 'true'));
238
+ // start 常驻:后台拉起,不 wait;已运行时官方命令自身幂等。
239
+ if (!child && !externalRunning) {
240
+ child = spawnImpl(binary, ['start'], { stdio: 'ignore', detached: true, cwd: path.dirname(binary) });
241
+ if (child && typeof child.on === 'function') {
242
+ child.on('error', () => {});
243
+ child.on('exit', () => {
244
+ if (gen !== generation) return;
245
+ child = null;
246
+ // 只在「已经连上之后」退出才算意外;连接过程中的退出交给后面 healthz / 建隧道去判失败,
247
+ // 免得把「start 命令自己后台化后正常退出」误报成崩溃。
248
+ if (phase === 'connected') {
249
+ url = '';
250
+ phase = 'error';
251
+ error = 'ZeroNews 客户端意外退出';
252
+ if (onUnexpectedExit) { try { onUnexpectedExit(error); } catch { /* 回调失败不影响状态 */ } }
253
+ }
254
+ });
255
+ if (typeof child.unref === 'function') child.unref();
256
+ }
257
+ } else if (externalRunning) {
258
+ attached = true;
259
+ }
260
+ phase = 'connecting';
261
+ const healthDeadline = Date.now() + START_TIMEOUT_MS;
262
+ for (let i = 0; i < START_POLL_MAX && Date.now() < healthDeadline; i += 1) {
263
+ if (await api('/healthz')) break;
264
+ await sleep(1000);
265
+ }
266
+ url = await ensureTunnel(portOf());
267
+ if (gen !== generation) return status();
268
+ if (!url) throw new Error('客户端已连上,但还没拿到隧道公网地址,请稍后刷新');
269
+ phase = 'connected';
270
+ } catch (err) {
271
+ if (gen !== generation) return status();
272
+ phase = 'error';
273
+ error = err && err.message ? err.message : String(err);
274
+ }
275
+ return status();
276
+ }
277
+
278
+ /**
279
+ * 同一时刻只跑一次 start:并发调用共享同一个在飞 Promise,避免自动重连 + 点连接 + watch 撞车各起一个客户端。
280
+ * `options.token` 是面板里粘贴的 AuthToken;不给就走「已登录」或浏览器登录那条老路。
281
+ */
282
+ function start(options = {}) {
283
+ if (options && typeof options.token === 'string' && options.token.trim()) pendingToken = options.token.trim();
284
+ if (startPromise) return startPromise;
285
+ startPromise = runStart().finally(() => { startPromise = null; });
286
+ return startPromise;
287
+ }
288
+
289
+ function stop() {
290
+ generation += 1;
291
+ if (child && typeof child.kill === 'function') { try { child.kill(); } catch {} }
292
+ child = null;
293
+ attached = false;
294
+ url = '';
295
+ error = '';
296
+ phase = 'off';
297
+ return status();
298
+ }
299
+
300
+ return { start, stop, status, pickEndpoint, endpointUrl };
301
+ }
302
+
303
+ module.exports = { DEFAULT_BASE, LOGIN_TIMEOUT_MS, START_TIMEOUT_MS, endpointUrl, pickEndpoint, createZeroNewsRunner };
@@ -0,0 +1,78 @@
1
+ // ZeroNews 线路观察器:插件自己读本机 API,把隧道地址作为第一条通用线路写进状态。
2
+ 'use strict';
3
+
4
+ /**
5
+ * 只读本机 ZeroNews 客户端的 endpoints,不建隧道、不碰账号、不问用户要任何东西。
6
+ * 读到 active 的 HTTPS 隧道就写进独立字段 `zeroNewsUrl`,总控据此上报 `kind:'custom'`;
7
+ * 客户端没装 / 没起 / 隧道撤了就把这一格清空,手机那边随之撤销这条线路。
8
+ *
9
+ * 写入用 notify:false(这不是远程控制配置,不该触发 sidecar 重配),写成功再请调用方
10
+ * 把新清单推给总控。读取失败不改现有值——本机客户端偶尔重启,别把一条还能用的线路抖掉。
11
+ */
12
+
13
+ const { readZeroNewsEndpoints } = require('./probe.cjs');
14
+
15
+ const DEFAULT_INTERVAL_MS = 60_000;
16
+
17
+ /**
18
+ * @param {object} options
19
+ * @param {object} options.settings 配置仓(update(patch, { notify: false }))
20
+ * @param {() => object} options.getState 当前状态取值器
21
+ * @param {() => void} [options.onChange] 地址真的变了之后通知总控重推
22
+ * @param {(result: object) => Promise<object>} [options.readEndpoints] 读取层注入(测试用)
23
+ * @param {number} [options.intervalMs] 轮询间隔
24
+ * @param {(msg: string) => void} [options.log]
25
+ */
26
+ function createZeroNewsWatcher(options = {}) {
27
+ const { settings, getState, onChange = () => {}, readEndpoints = readZeroNewsEndpoints,
28
+ intervalMs = DEFAULT_INTERVAL_MS, log = () => {} } = options;
29
+ let timer = null;
30
+ let running = false;
31
+ let stopped = false;
32
+ let inFlight = null;
33
+
34
+ async function refresh() {
35
+ if (stopped || inFlight) return;
36
+ inFlight = (async () => {
37
+ const result = await readEndpoints();
38
+ if (stopped) return;
39
+ // 只有「本机 API 正常回应」才按清单更新;连不上/读失败时保留现有线路,别抖。
40
+ if (!result || result.ok !== true) return;
41
+ const url = Array.isArray(result.urls) && result.urls.length ? result.urls[0] : '';
42
+ const current = typeof getState().zeroNewsUrl === 'string' ? getState().zeroNewsUrl : '';
43
+ if (url === current) return;
44
+ try {
45
+ await settings.update({ zeroNewsUrl: url }, { notify: false });
46
+ onChange();
47
+ } catch (error) {
48
+ log(`[zeronews] 线路地址写回失败:${error && error.message ? error.message : error}`);
49
+ }
50
+ })();
51
+ try { await inFlight; } finally { inFlight = null; }
52
+ }
53
+
54
+ function schedule() {
55
+ if (!running || stopped) return;
56
+ clearTimeout(timer);
57
+ timer = setTimeout(() => { void refresh().finally(schedule); }, intervalMs);
58
+ timer.unref?.();
59
+ }
60
+
61
+ function start() {
62
+ if (running) return;
63
+ running = true;
64
+ stopped = false;
65
+ void refresh().finally(schedule);
66
+ }
67
+
68
+ function stop() {
69
+ running = false;
70
+ stopped = true;
71
+ clearTimeout(timer);
72
+ timer = null;
73
+ }
74
+
75
+ return { start, stop, refresh };
76
+ }
77
+
78
+ module.exports = { createZeroNewsWatcher, DEFAULT_INTERVAL_MS };
@@ -0,0 +1,159 @@
1
+ // ZeroNews 线路挂载:把运行器接进装配层,隧道地址写回独立字段,随 effect 启停。
2
+ 'use strict';
3
+
4
+ /**
5
+ * 单独一个 wiring 是因为 `lib/impl.js` 有代码行数上限(test/assembly-layer.test.cjs 钉着):
6
+ * 那儿只留一句 require、一句 mount,进程生命周期在 runner.cjs,二进制获取在 provision.cjs。
7
+ *
8
+ * 面板点「连接」→ runner 走 ensure→login→start→建隧道→读域名;这里把域名写进独立字段
9
+ * `zeroNewsUrl`(总控按 kind:'custom' 上报),并随配置变化自动重连 / 卸载时停进程。
10
+ *
11
+ * **稳定门面**:就地重载会重新 apply、新建一个 runner,但控制面路由只认第一次挂上去的那个
12
+ * 对象引用。所以对外的 start/stop/status 一律转发到模块级 `current`(最新一次 mount 出来的
13
+ * 那套 runner+写回),重载后路由调到的仍是最新实现。
14
+ */
15
+
16
+ const { execFile } = require('node:child_process');
17
+
18
+ const { createZeroNewsRunner } = require('./runner.cjs');
19
+ const { ensureZeroNews } = require('./provision.cjs');
20
+
21
+ /** 用户登录 ZeroNews 控制台、拿到 AuthToken 的那一页。 */
22
+ const CONSOLE_URL = 'https://user.zeronews.cc/setup';
23
+
24
+ /**
25
+ * 用系统默认浏览器打开一个地址。
26
+ *
27
+ * 面板跑在 DSH 的网页壳里,`window.open` 能不能落到系统浏览器取决于宿主;这里是本机 node
28
+ * 进程,`open` / `start` / `xdg-open` 一定到得了。打不开就回 false,让面板把地址写出来给人
29
+ * 手动点 —— 不假装开过。
30
+ */
31
+ function openInBrowser(url) {
32
+ const platform = process.platform;
33
+ const command = platform === 'darwin' ? 'open' : platform === 'win32' ? 'cmd' : 'xdg-open';
34
+ const args = platform === 'win32' ? ['/c', 'start', '', url] : [url];
35
+ return new Promise((resolve) => {
36
+ try {
37
+ const child = execFile(command, args, { windowsHide: true }, () => {});
38
+ if (child && typeof child.on === 'function') child.on('error', () => resolve(false));
39
+ else resolve(false);
40
+ } catch { resolve(false); }
41
+ });
42
+ }
43
+
44
+ /** 最新一次 mount 出来的操作集。放 globalThis:就地重载会换掉整个模块作用域,只有全局变量
45
+ * 能跨代存活,保证路由手里那份门面永远转发到最新一份实现。 */
46
+ const GLOBAL_KEY = '__dshZeroNewsCurrent';
47
+ const readCurrent = () => globalThis[GLOBAL_KEY] || null;
48
+ /** 只建一次的门面,路由长期持有;方法都转发到全局 current。 */
49
+ const facade = {
50
+ start: (token) => (readCurrent() ? readCurrent().start(token) : Promise.resolve({ phase: 'off' })),
51
+ stop: () => (readCurrent() ? readCurrent().stop() : Promise.resolve({ phase: 'off' })),
52
+ status: () => (readCurrent() ? readCurrent().status() : { available: false, running: false, phase: 'off', url: '', error: '', configured: false }),
53
+ prepare: () => (readCurrent() ? readCurrent().prepare() : Promise.resolve({ ok: false, error: '这台宿主没有接入 ZeroNews 线路能力' })),
54
+ };
55
+
56
+ /** @param {{mount:Function, settings:object, getState:Function, control:object, warn:Function, ctx:object, name:string, portOf?:Function, runnerFactory?:Function, ensure?:Function}} options */
57
+ function mountZeroNews(options) {
58
+ const { mount, settings, getState, control, warn, ctx, name } = options;
59
+ const makeRunner = typeof options.runnerFactory === 'function' ? options.runnerFactory : createZeroNewsRunner;
60
+ const provision = typeof options.ensure === 'function' ? options.ensure : ensureZeroNews;
61
+ // 自愈:客户端意外退出 / 启动失败时,只要还「配置过」,就按退避自动重连,别让线路卡死在错误上。
62
+ // 插件自动更新 / 就地重载后由新实例重新挂载,这条重连负责把上一轮断掉的客户端重新接上。
63
+ const retryBaseMs = Number(options.retryBaseMs) > 0 ? Number(options.retryBaseMs) : 3000;
64
+ let retryTimer = null;
65
+ let retryMs = retryBaseMs;
66
+ const isConfigured = () => {
67
+ const s = getState() || {};
68
+ return s.zeroNewsEnabled === true || (typeof s.zeroNewsUrl === 'string' && s.zeroNewsUrl.trim() !== '');
69
+ };
70
+ const clearRetry = () => { if (retryTimer) { clearTimeout(retryTimer); retryTimer = null; } };
71
+ const scheduleRetry = () => {
72
+ if (retryTimer || !isConfigured()) return;
73
+ const delay = retryMs;
74
+ retryMs = Math.min(Math.round(retryMs * 2), 60_000);
75
+ retryTimer = setTimeout(() => { retryTimer = null; void start().catch(() => {}); }, delay);
76
+ if (retryTimer && typeof retryTimer.unref === 'function') retryTimer.unref();
77
+ };
78
+
79
+ /** 身份看过没有:runner 这一进程见过的,或者落盘记录里做过都算。 */
80
+ const statusOf = () => {
81
+ const current = runner.status();
82
+ return { ...current, configured: current.configured === true || getState().zeroNewsBound === true };
83
+ };
84
+
85
+ const runner = makeRunner({
86
+ ensure: provision,
87
+ portOf: () => Number(options.portOf && options.portOf()) || 0,
88
+ // 客户端在我们「以为还连着」的时候退出(插件重载 / 自动更新 / 偶发崩溃):安排一次自愈重连。
89
+ onUnexpectedExit: () => scheduleRetry(),
90
+ });
91
+
92
+ const start = async (token) => {
93
+ clearRetry();
94
+ let result;
95
+ try {
96
+ result = await runner.start({ token });
97
+ } catch (error) {
98
+ result = runner.status();
99
+ warn('启动 ZeroNews 线路失败:%s', error && error.message ? error.message : error);
100
+ }
101
+ // 拿到域名就写回状态;settings.update 会经 watch → applyServices → control.sync() 报给总控。
102
+ if (result && result.phase === 'connected' && result.url && getState().zeroNewsUrl !== result.url) {
103
+ try { await settings.update({ zeroNewsUrl: result.url, zeroNewsEnabled: true }); }
104
+ catch (error) { warn('把 ZeroNews 地址写回状态失败:%s', error && error.message ? error.message : error); }
105
+ }
106
+ // 一旦确认这台机器有身份就落盘标记,面板下次不必再让人粘一遍 token(token 本身不存)。
107
+ if (result && result.configured === true && getState().zeroNewsBound !== true) {
108
+ try { await settings.update({ zeroNewsBound: true }); }
109
+ catch (error) { warn('记录 ZeroNews 身份状态失败:%s', error && error.message ? error.message : error); }
110
+ }
111
+ // 连上就把退避重置;还停在错误上就安排下一轮自愈,实现自动更新 / 重载后自己恢复。
112
+ if (result && result.phase === 'connected') retryMs = retryBaseMs;
113
+ else if (result && result.phase === 'error') scheduleRetry();
114
+ return statusOf();
115
+ };
116
+
117
+ /**
118
+ * 第一次接入:把客户端装好,再把登录页丢给系统浏览器。
119
+ *
120
+ * 下载可能要几十秒,所以这里只做到「装完 + 开页」就返回,不在服务端等用户登录 —— 登录、
121
+ * 复制 token、粘回面板是用户那边的事,等他点「保存并连接」时再走 start(token)。
122
+ */
123
+ const prepare = async () => {
124
+ let got;
125
+ try {
126
+ got = await provision();
127
+ } catch (error) {
128
+ return { ok: false, error: error && error.message ? error.message : String(error) };
129
+ }
130
+ if (!got || !got.ok) {
131
+ return { ok: false, error: got && got.code === 'unsupported-platform' ? '这台系统不支持自动安装 ZeroNews 客户端' : '下载 ZeroNews 客户端失败,请稍后重试' };
132
+ }
133
+ const opened = await (typeof options.openUrl === 'function' ? options.openUrl(CONSOLE_URL) : openInBrowser(CONSOLE_URL));
134
+ return { ok: true, downloaded: got.source === 'downloaded', opened: opened === true, url: CONSOLE_URL };
135
+ };
136
+
137
+ const stop = async () => {
138
+ clearRetry();
139
+ retryMs = retryBaseMs;
140
+ const result = runner.stop();
141
+ try { await settings.update({ zeroNewsUrl: '', zeroNewsEnabled: false }); } catch { /* 停的时候写不回也不阻断 */ }
142
+ return result;
143
+ };
144
+
145
+ globalThis[GLOBAL_KEY] = { start, stop, status: statusOf, prepare };
146
+
147
+ mount('ZeroNews 线路', () => ctx.effect(() => {
148
+ // 只要「配置过」就自动重连:zeroNewsEnabled 为真,或者状态里还留着上次连上的隧道地址
149
+ // (zeroNewsUrl 非空 = 用户连过、且没显式断开,因为断开时会清空)。断开会把两者都清掉,
150
+ // 所以清空之后不会自动再拉起。连不上让状态停在错误上,不阻塞启动。
151
+ const s = getState();
152
+ const configured = s.zeroNewsEnabled === true || (typeof s.zeroNewsUrl === 'string' && s.zeroNewsUrl.trim() !== '');
153
+ if (configured) { void start().catch(() => {}); }
154
+ return () => { clearRetry(); runner.stop(); };
155
+ }, `${name}: zeronews runner`));
156
+ return facade;
157
+ }
158
+
159
+ module.exports = { mountZeroNews };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-plugin",
3
- "version": "0.5.95",
3
+ "version": "0.5.97",
4
4
  "description": "Mobile API (/api/mobile/v1) and relay client for the DSH mobile app — desktop profile build (dsh 0.2.x, peers resolved by the host)",
5
5
  "license": "MIT",
6
6
  "icon": "./icon.png",