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.
- package/README.md +37 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/SKILL.md +4 -1
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/cloudflare.md +7 -6
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/jdxb.md +52 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/network-guide.md +2 -1
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/zeronews.md +56 -0
- package/lib/cloudflared/runner.cjs +110 -33
- package/lib/cloudflared/wiring.cjs +17 -1
- package/lib/impl.js +23 -4
- package/lib/jdxb/probe.cjs +165 -0
- package/lib/jdxb/provision.cjs +218 -0
- package/lib/mobile/history-derive.js +18 -0
- package/lib/mobile/question-reply.js +159 -0
- package/lib/mobile/stream.js +25 -2
- package/lib/panel/index.html +26 -46
- package/lib/relay/config-store.js +64 -5
- package/lib/relay/control.js +51 -3
- package/lib/relay/core.js +21 -0
- package/lib/relay/lan-proxy.js +50 -14
- package/lib/relay/public-ip.cjs +82 -0
- package/lib/remote/host-control.cjs +19 -1
- package/lib/routes/control-plane.js +225 -23
- package/lib/routes/mobile-api.js +22 -0
- package/lib/update-install.cjs +3 -2
- package/lib/zeronews/probe.cjs +126 -0
- package/lib/zeronews/provision.cjs +128 -0
- package/lib/zeronews/runner.cjs +303 -0
- package/lib/zeronews/watcher.cjs +78 -0
- package/lib/zeronews/wiring.cjs +159 -0
- package/package.json +1 -1
|
@@ -35,7 +35,10 @@ const { canListen } = require('../relay/port-allocator.cjs');
|
|
|
35
35
|
// ⚠️ 面板里**能被选中的**那份仍然只能是 `lan`(没有私网时才退 `public`)——它与
|
|
36
36
|
// `advertisedCandidates` 同口径。IPv6 那份只**显示**、不进那个选择:它由手机侧实测择优
|
|
37
37
|
// (和公网中转比速度),做成可选中等于骗人(同 A3-40 的刻意设计)。
|
|
38
|
-
const { lanCandidates, publicCandidates, ipv6Candidates, withManualIpv4Candidate, withManualIpv6Candidate } = require('../relay/lan-network.cjs');
|
|
38
|
+
const { lanCandidates, publicCandidates, ipv6Candidates, withManualIpv4Candidate, withManualIpv6Candidate, tcpDirectTarget } = require('../relay/lan-network.cjs');
|
|
39
|
+
// 面板 IPv4 那一格的自动候选:网卡枚举读不到 NAT 后面的公网地址,只能由本机去问一次回显
|
|
40
|
+
// 服务(顺序、校验与缓存的口径见 ../relay/public-ip.cjs 的文件头)。
|
|
41
|
+
const { detectPublicIpv4 } = require('../relay/public-ip.cjs');
|
|
39
42
|
// 「手机连不上时哪一环断了」这份连接自检:本机只读、不改任何东西(口径见
|
|
40
43
|
// connection-check.js 与 firewall-probe.js 的文件头)。
|
|
41
44
|
const { createConnectionCheck } = require('../relay/connection-check.js');
|
|
@@ -55,12 +58,78 @@ const { recordSessionRead } = require('../mobile/session-last-turn.js');
|
|
|
55
58
|
// 收件目录的占用与清理:和移动端那条路由是同一份实现(`lib/mobile/inbox-clean.js`)。
|
|
56
59
|
const { scanInbox, clearInbox, usageView, setAutoClear } = require('../mobile/inbox-clean.js');
|
|
57
60
|
const { handleFeedback } = require('./feedback.cjs');
|
|
61
|
+
// ZeroNews 公网地址一键读取:本机 node 进程去问 ZeroNews 客户端的本地 API(面板跨域读不到),
|
|
62
|
+
// 只读、不建隧道、不碰账号。详见 ../zeronews/probe.cjs 的文件头。
|
|
63
|
+
const { readZeroNewsEndpoints } = require('../zeronews/probe.cjs');
|
|
64
|
+
// 节点小宝设备端的状态与绑定链接:同样只读它的本地管理口,不启停它的进程(它以系统服务自装自启)。
|
|
65
|
+
const { readStatus: readJdxbStatus, readBindUrl: readJdxbBindUrl, lineOf: jdxbLineOf } = require('../jdxb/probe.cjs');
|
|
66
|
+
// 安装与启动:它必须装成系统服务(身份要写进系统目录才扛得住重启),这一步绕不开一次系统授权。
|
|
67
|
+
const { install: installJdxb, installedSync: jdxbInstalledSync } = require('../jdxb/provision.cjs');
|
|
58
68
|
|
|
59
69
|
/** 一次 desktop-read 上报最多带多少个会话 id(防灌爆;客户端半边一次最多也就几个)。 */
|
|
60
70
|
const MAX_DESKTOP_READ_IDS = 200;
|
|
61
71
|
/** 公用中转测速的单项超时:远端多半在境外,给足 6 秒但别让整页干等。 */
|
|
62
72
|
const RELAY_PROBE_TIMEOUT_MS = 6000;
|
|
63
73
|
|
|
74
|
+
/**
|
|
75
|
+
* 裸 TCP 目标的回环体检:连上 `host:port` 后手发一条 `GET /api/mobile/v1/health`,读回 JSON。
|
|
76
|
+
*
|
|
77
|
+
* TCP 直连这一路没有 TLS,手机也是裸 TCP 拨进来的;这里用同一层协议证明「这条通道绕回来
|
|
78
|
+
* 就是本机插件」。连不上 / 超时 / 响应不是 JSON 一律回 null(与 http 那路同口径)。
|
|
79
|
+
*
|
|
80
|
+
* 正文得按 HTTP 自己的分帧取:插件答这条健康请求时是 `Transfer-Encoding: chunked`
|
|
81
|
+
* (`res.end(JSON)` 不带 content-length 就是这样),把整段响应直接喂给 `JSON.parse`
|
|
82
|
+
* 必然失败 —— 那会让「TCP 直连」这颗检测永远报不通,地址完全正确也一样。
|
|
83
|
+
*/
|
|
84
|
+
function probeTcpHealth(host, port, timeoutMs) {
|
|
85
|
+
return new Promise((resolve) => {
|
|
86
|
+
let settled = false;
|
|
87
|
+
const chunks = [];
|
|
88
|
+
const finish = (value) => { if (settled) return; settled = true; try { socket.destroy(); } catch { /* 已关 */ } resolve(value); };
|
|
89
|
+
const socket = net.connect({ host, port });
|
|
90
|
+
socket.setTimeout(timeoutMs);
|
|
91
|
+
socket.once('connect', () => {
|
|
92
|
+
socket.write('GET /api/mobile/v1/health HTTP/1.1\r\nHost: probe\r\nAccept: application/json\r\nConnection: close\r\n\r\n');
|
|
93
|
+
});
|
|
94
|
+
socket.on('data', (chunk) => { chunks.push(chunk); });
|
|
95
|
+
socket.once('timeout', () => finish(null));
|
|
96
|
+
socket.once('error', () => finish(null));
|
|
97
|
+
socket.once('close', () => {
|
|
98
|
+
try { finish(JSON.parse(probeBodyOf(Buffer.concat(chunks)))); } catch { finish(null); }
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 从裸 TCP 收回来的一整段 HTTP 响应里取出正文,按 `Content-Length` / chunked 分好帧。
|
|
105
|
+
*
|
|
106
|
+
* 两个分帧头都没有时就当「读到连接关闭为止」,与大多数一次性响应一致。
|
|
107
|
+
*/
|
|
108
|
+
function probeBodyOf(raw) {
|
|
109
|
+
const sep = raw.indexOf('\r\n\r\n');
|
|
110
|
+
if (sep < 0) return '';
|
|
111
|
+
const head = raw.subarray(0, sep).toString('latin1').toLowerCase();
|
|
112
|
+
let body = raw.subarray(sep + 4);
|
|
113
|
+
if (/transfer-encoding:\s*chunked/.test(head)) {
|
|
114
|
+
const parts = [];
|
|
115
|
+
let offset = 0;
|
|
116
|
+
while (offset < body.length) {
|
|
117
|
+
const eol = body.indexOf('\r\n', offset);
|
|
118
|
+
if (eol < 0) break;
|
|
119
|
+
const size = Number.parseInt(body.subarray(offset, eol).toString('latin1').trim(), 16);
|
|
120
|
+
if (!Number.isFinite(size) || size <= 0) break;
|
|
121
|
+
const start = eol + 2;
|
|
122
|
+
parts.push(body.subarray(start, start + size));
|
|
123
|
+
offset = start + size + 2;
|
|
124
|
+
}
|
|
125
|
+
body = Buffer.concat(parts);
|
|
126
|
+
} else {
|
|
127
|
+
const length = /content-length:\s*(\d+)/.exec(head);
|
|
128
|
+
if (length) body = body.subarray(0, Number(length[1]));
|
|
129
|
+
}
|
|
130
|
+
return body.toString('utf8');
|
|
131
|
+
}
|
|
132
|
+
|
|
64
133
|
/**
|
|
65
134
|
* `preferredLanAddress` 是不是其实是一枚中转地址的 host。
|
|
66
135
|
*
|
|
@@ -417,6 +486,13 @@ function registerControlPlaneRoutes(deps) {
|
|
|
417
486
|
ipv6: withManualIpv6Candidate(ipv6Candidates(port), manualIpv6),
|
|
418
487
|
})
|
|
419
488
|
}) })
|
|
489
|
+
// 面板 IPv4 那一栏的自动候选:本机公网地址不在网卡清单里(NAT 后面),只能去外网回显服务问。
|
|
490
|
+
// 只给面板看,不进二维码 / 移动端候选 —— 那份取舍仍归 `advertisedCandidates`。
|
|
491
|
+
// 结果在进程内缓存(成功 5 分钟、失败 60 秒),面板反复开页不会每次都重新打四个外网。
|
|
492
|
+
registerRoute({ kind: 'exact', path: '/api/relay/public-ip', handler: localOnly('GET', async (_req, res) => {
|
|
493
|
+
const result = await detectPublicIpv4()
|
|
494
|
+
sendJson(res, 200, { ok: true, ...result })
|
|
495
|
+
}) })
|
|
420
496
|
/**
|
|
421
497
|
* 公用中转候选的测速(`POST /api/relay/probe-relays`,body `{ urls: string[] }`)。
|
|
422
498
|
*
|
|
@@ -472,27 +548,45 @@ function registerControlPlaneRoutes(deps) {
|
|
|
472
548
|
registerRoute({ kind: 'exact', path: '/api/relay/probe-direct', handler: localOnly('POST', async (req, res) => {
|
|
473
549
|
const body = await readJson(req)
|
|
474
550
|
const raw = typeof body?.url === 'string' ? body.url.trim().replace(/\/+$/, '') : ''
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
const
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
551
|
+
// 两种目标:`http(s)://...` 域名/地址直接 fetch;`主机:端口` 走裸 TCP 再手发一次健康请求
|
|
552
|
+
// (TCP 直连没有 TLS,手机也是裸 TCP 拨)。两条都验「service=dsh-mobile-plugin 且 instanceId
|
|
553
|
+
// 与本机一致」,也就是回环命中本机插件才算通。
|
|
554
|
+
if (/^https?:\/\//i.test(raw)) {
|
|
555
|
+
const controller = new AbortController()
|
|
556
|
+
const timer = setTimeout(() => controller.abort(), RELAY_PROBE_TIMEOUT_MS)
|
|
557
|
+
const started = Date.now()
|
|
558
|
+
try {
|
|
559
|
+
const who = await fetch(`${raw}/api/mobile/v1/health`, { signal: controller.signal, redirect: 'follow' })
|
|
560
|
+
.then((r) => (r.ok ? r.json() : null))
|
|
561
|
+
.catch(() => null)
|
|
562
|
+
if (!who || typeof who !== 'object') return sendJson(res, 200, { ok: true, ms: null })
|
|
563
|
+
return sendJson(res, 200, {
|
|
564
|
+
ok: true,
|
|
565
|
+
ms: Date.now() - started,
|
|
566
|
+
service: typeof who.service === 'string' ? who.service : '',
|
|
567
|
+
instanceId: typeof who.instanceId === 'string' ? who.instanceId : '',
|
|
568
|
+
apiVersion: who.apiVersion,
|
|
569
|
+
})
|
|
570
|
+
} catch {
|
|
571
|
+
return sendJson(res, 200, { ok: true, ms: null })
|
|
572
|
+
} finally {
|
|
573
|
+
clearTimeout(timer)
|
|
574
|
+
}
|
|
495
575
|
}
|
|
576
|
+
const target = /^(\[[^\]]+\]|[^:/\s]+):(\d{1,5})$/.exec(raw)
|
|
577
|
+
if (!target) return sendJson(res, 200, { ok: true, ms: null })
|
|
578
|
+
const host = target[1].replace(/^\[|\]$/g, '')
|
|
579
|
+
const port = Number(target[2])
|
|
580
|
+
const started = Date.now()
|
|
581
|
+
const who = await probeTcpHealth(host, port, RELAY_PROBE_TIMEOUT_MS)
|
|
582
|
+
if (!who || typeof who !== 'object') return sendJson(res, 200, { ok: true, ms: null })
|
|
583
|
+
sendJson(res, 200, {
|
|
584
|
+
ok: true,
|
|
585
|
+
ms: Date.now() - started,
|
|
586
|
+
service: typeof who.service === 'string' ? who.service : '',
|
|
587
|
+
instanceId: typeof who.instanceId === 'string' ? who.instanceId : '',
|
|
588
|
+
apiVersion: who.apiVersion,
|
|
589
|
+
})
|
|
496
590
|
}) })
|
|
497
591
|
/**
|
|
498
592
|
* 配了几台手机、最近一次连线是什么时候。
|
|
@@ -532,7 +626,7 @@ function registerControlPlaneRoutes(deps) {
|
|
|
532
626
|
return false
|
|
533
627
|
}
|
|
534
628
|
}
|
|
535
|
-
registerRoute({ kind: 'exact', path: '/api/relay/status', handler: localOnly('GET', async (req, res) => sendJson(res, 200, { ...status(), shellChanged: shellChangedNow(), tailcat: deps.tailcat && typeof deps.tailcat.status === 'function' ? deps.tailcat.status() : null, frp: deps.frp && typeof deps.frp.status === 'function' ? deps.frp.status() : null, cloudflare: deps.cloudflare && typeof deps.cloudflare.status === 'function' ? deps.cloudflare.status() : null, panelUrl: panelUrlOf(req), panelScope: panelScopeOf(req), devices: deviceSummary(), ...mobileActivity(), selfCheck: selfCheck.snapshot() })) })
|
|
629
|
+
registerRoute({ kind: 'exact', path: '/api/relay/status', handler: localOnly('GET', async (req, res) => sendJson(res, 200, { ...status(), shellChanged: shellChangedNow(), tailcat: deps.tailcat && typeof deps.tailcat.status === 'function' ? deps.tailcat.status() : null, frp: deps.frp && typeof deps.frp.status === 'function' ? deps.frp.status() : null, cloudflare: deps.cloudflare && typeof deps.cloudflare.status === 'function' ? deps.cloudflare.status() : null, zeroNews: deps.zeroNews && typeof deps.zeroNews.status === 'function' ? deps.zeroNews.status() : null, panelUrl: panelUrlOf(req), panelScope: panelScopeOf(req), devices: deviceSummary(), ...mobileActivity(), selfCheck: selfCheck.snapshot() })) })
|
|
536
630
|
|
|
537
631
|
// ── 手机直连隧道(Tailcat):面板查看与管理 ────────────────────────────────
|
|
538
632
|
//
|
|
@@ -608,7 +702,9 @@ function registerControlPlaneRoutes(deps) {
|
|
|
608
702
|
return sendJson(res, 503, { ok: false, error: { code: 'frp-unavailable', message: '这台宿主没有接入 frpc 运行能力' } })
|
|
609
703
|
}
|
|
610
704
|
const stopped = await deps.frp.clear()
|
|
611
|
-
|
|
705
|
+
// 停掉 frpc 就等于这条线路没了:清掉 `frpUrl`,别让手机继续拨一个已经断掉的地址。
|
|
706
|
+
// 「TCP 直连」是用户自己填的,不归这里管,一个字都不动。
|
|
707
|
+
await settings.update({ frpUrl: '' })
|
|
612
708
|
sendJson(res, 200, { ok: true, status: stopped })
|
|
613
709
|
}) })
|
|
614
710
|
|
|
@@ -641,6 +737,97 @@ function registerControlPlaneRoutes(deps) {
|
|
|
641
737
|
sendJson(res, 500, { ok: false, error: { code: 'cloudflare-stop-failed', message: err && err.message ? err.message : String(err) } })
|
|
642
738
|
}
|
|
643
739
|
}) })
|
|
740
|
+
|
|
741
|
+
// ── ZeroNews 线路:面板「保存并连接 / 断开」——自动下载客户端、写 AuthToken、建隧道、拿域名 ──
|
|
742
|
+
// token 由用户在「快速开始」页复制后粘进面板(厂商现行 CLI 用 `authtoken`);body 里没带就退回
|
|
743
|
+
// 原有的浏览器登录那条路。token 只在这次请求里经过,不落盘、不记日志。
|
|
744
|
+
registerRoute({ kind: 'exact', path: '/api/relay/zeronews/connect', handler: localOnly('POST', async (req, res) => {
|
|
745
|
+
if (!deps.zeroNews || typeof deps.zeroNews.start !== 'function') {
|
|
746
|
+
return sendJson(res, 503, { ok: false, error: { code: 'zeronews-unavailable', message: '这台宿主没有接入 ZeroNews 线路能力' } })
|
|
747
|
+
}
|
|
748
|
+
let body = null
|
|
749
|
+
try { body = await readJson(req) } catch { body = null }
|
|
750
|
+
const token = body && typeof body.token === 'string' ? body.token.trim().slice(0, 512) : ''
|
|
751
|
+
try {
|
|
752
|
+
const current = await deps.zeroNews.start(token)
|
|
753
|
+
sendJson(res, 200, { ok: true, ...(current || {}) })
|
|
754
|
+
} catch (err) {
|
|
755
|
+
sendJson(res, 500, { ok: false, error: { code: 'zeronews-connect-failed', message: err && err.message ? err.message : String(err) } })
|
|
756
|
+
}
|
|
757
|
+
}) })
|
|
758
|
+
// 第一次接入的第一步:把客户端下载好,再把登录页交给系统浏览器。用户登录、复制 token 之后
|
|
759
|
+
// 由面板带着 token 再来调 connect —— 这里不等登录,也不碰账号。
|
|
760
|
+
registerRoute({ kind: 'exact', path: '/api/relay/zeronews/prepare', handler: localOnly('POST', async (_req, res) => {
|
|
761
|
+
if (!deps.zeroNews || typeof deps.zeroNews.prepare !== 'function') {
|
|
762
|
+
return sendJson(res, 503, { ok: false, error: { code: 'zeronews-unavailable', message: '这台宿主没有接入 ZeroNews 线路能力' } })
|
|
763
|
+
}
|
|
764
|
+
try {
|
|
765
|
+
const result = await deps.zeroNews.prepare()
|
|
766
|
+
sendJson(res, 200, { ok: true, ...(result || {}) })
|
|
767
|
+
} catch (err) {
|
|
768
|
+
sendJson(res, 500, { ok: false, error: { code: 'zeronews-prepare-failed', message: err && err.message ? err.message : String(err) } })
|
|
769
|
+
}
|
|
770
|
+
}) })
|
|
771
|
+
registerRoute({ kind: 'exact', path: '/api/relay/zeronews/disconnect', handler: localOnly('POST', async (_req, res) => {
|
|
772
|
+
if (!deps.zeroNews || typeof deps.zeroNews.stop !== 'function') {
|
|
773
|
+
return sendJson(res, 503, { ok: false, error: { code: 'zeronews-unavailable', message: '这台宿主没有接入 ZeroNews 线路能力' } })
|
|
774
|
+
}
|
|
775
|
+
try {
|
|
776
|
+
const current = await deps.zeroNews.stop()
|
|
777
|
+
sendJson(res, 200, { ok: true, ...(current || {}) })
|
|
778
|
+
} catch (err) {
|
|
779
|
+
sendJson(res, 500, { ok: false, error: { code: 'zeronews-disconnect-failed', message: err && err.message ? err.message : String(err) } })
|
|
780
|
+
}
|
|
781
|
+
}) })
|
|
782
|
+
|
|
783
|
+
// ── ZeroNews 公网地址读取:面板「直连地址」栏的「从 ZeroNews 读取」按钮 ──────────
|
|
784
|
+
// 只读本机 ZeroNews 客户端已建好的 HTTPS 隧道地址,交给面板填进直连栏。不写配置、不建隧道、
|
|
785
|
+
// 不碰账号——用户自己在 ZeroNews 注册建隧道,插件只帮忙把地址抄过来(见 zeronews/probe.cjs)。
|
|
786
|
+
// 客户端没起 / 超时 / 没有可用隧道都按 200 回,用 ok / urls / error 三格如实说明,别用 HTTP 状态码
|
|
787
|
+
// 把「没装客户端」伪装成「接口坏了」。
|
|
788
|
+
registerRoute({ kind: 'exact', path: '/api/relay/zeronews/endpoints', handler: localOnly('GET', async (_req, res) => {
|
|
789
|
+
const result = await readZeroNewsEndpoints()
|
|
790
|
+
sendJson(res, 200, result)
|
|
791
|
+
}) })
|
|
792
|
+
|
|
793
|
+
// ── 节点小宝线路:本机设备端状态、绑定链接、手填线路地址 ──────────────────────
|
|
794
|
+
// 它跟我们接入的其它线路不一样:设备端是以系统服务装进机器的,插件不启动也不管理它的进程,
|
|
795
|
+
// 这里只读它的本地管理口(macOS 2080 / Linux 9118),把「装没装、绑没绑」如实交给面板。
|
|
796
|
+
// 线路地址来自它的云端控制台(账号数据,插件不去碰),由用户抄一次写进 jdxbUrl。
|
|
797
|
+
registerRoute({ kind: 'exact', path: '/api/relay/jdxb/status', handler: localOnly('GET', async (_req, res) => {
|
|
798
|
+
const snapshot = await readJdxbStatus()
|
|
799
|
+
const line = jdxbLineOf(state.jdxbUrl)
|
|
800
|
+
sendJson(res, 200, { ok: true, url: line ? line.url : '', transport: line ? line.transport : '', service: { installed: jdxbInstalledSync() }, ...snapshot })
|
|
801
|
+
}) })
|
|
802
|
+
// 一键安装 / 启动:插件自己下载官方设备端、以系统服务装好并拉起。会弹一次系统的管理员授权框
|
|
803
|
+
// (macOS 的 Touch ID / 密码);授权不归我们管,但整件事用户只点这一下。
|
|
804
|
+
registerRoute({ kind: 'exact', path: '/api/relay/jdxb/install', handler: localOnly('POST', async (_req, res) => {
|
|
805
|
+
const result = await installJdxb()
|
|
806
|
+
sendJson(res, result.ok ? 200 : 500, { ...result, service: { installed: jdxbInstalledSync() } })
|
|
807
|
+
}) })
|
|
808
|
+
// 没绑时把设备端的绑定链接取出来;已经绑了就不再去要(它那边也不会给)。
|
|
809
|
+
registerRoute({ kind: 'exact', path: '/api/relay/jdxb/bind', handler: localOnly('GET', async (_req, res) => {
|
|
810
|
+
const snapshot = await readJdxbStatus()
|
|
811
|
+
if (snapshot.installed && snapshot.bound) return sendJson(res, 200, { ok: true, url: '', bound: true, error: '' })
|
|
812
|
+
const result = await readJdxbBindUrl({ port: snapshot.port || undefined })
|
|
813
|
+
sendJson(res, 200, { ...result, bound: false })
|
|
814
|
+
}) })
|
|
815
|
+
// 写入那条线路的外网地址;空串 = 撤掉这条线路。只落盘、不通知重配 —— 它不进 sidecar 配置,
|
|
816
|
+
// 下一轮心跳会把线路清单带上(同 ZeroNews 写 zeroNewsUrl 的口径)。
|
|
817
|
+
registerRoute({ kind: 'exact', path: '/api/relay/jdxb/url', handler: localOnly('POST', async (req, res) => {
|
|
818
|
+
const body = await readJson(req)
|
|
819
|
+
const raw = body && typeof body.url === 'string' ? body.url.trim() : ''
|
|
820
|
+
if (!raw) {
|
|
821
|
+
await settings.update({ jdxbUrl: '' }, { notify: false })
|
|
822
|
+
return sendJson(res, 200, { ok: true, url: '', transport: '' })
|
|
823
|
+
}
|
|
824
|
+
const line = jdxbLineOf(raw)
|
|
825
|
+
if (!line) {
|
|
826
|
+
return sendJson(res, 400, { ok: false, error: { code: 'jdxb-bad-url', message: '地址要写成 https://域名(网页服务)或「域名:端口」(TCP 服务)' } })
|
|
827
|
+
}
|
|
828
|
+
await settings.update({ jdxbUrl: line.url }, { notify: false })
|
|
829
|
+
sendJson(res, 200, { ok: true, url: line.url, transport: line.transport })
|
|
830
|
+
}) })
|
|
644
831
|
const tailcatSnapshot = () => {
|
|
645
832
|
const state = deps.tailcat && typeof deps.tailcat.status === 'function' ? deps.tailcat.status() : null
|
|
646
833
|
const allowed = deps.tailcat && typeof deps.tailcat.allowedClients === 'function' ? deps.tailcat.allowedClients() : []
|
|
@@ -1323,6 +1510,8 @@ function registerControlPlaneRoutes(deps) {
|
|
|
1323
1510
|
// 控制面路由清单:不再参与放行判断,保留用于路由盘点与契约测试。
|
|
1324
1511
|
const WEB_ACCESS_ROUTES = new Set([
|
|
1325
1512
|
'/api/relay/addresses',
|
|
1513
|
+
// 面板 IPv4 栏的自动候选:本机去问一次回显服务,结果缓存,只读。
|
|
1514
|
+
'/api/relay/public-ip',
|
|
1326
1515
|
'/api/relay/probe-relays',
|
|
1327
1516
|
'/api/relay/probe-direct',
|
|
1328
1517
|
'/api/relay/status',
|
|
@@ -1354,6 +1543,17 @@ const WEB_ACCESS_ROUTES = new Set([
|
|
|
1354
1543
|
// Cloudflare 兜底隧道的启停:与其它管理动作一样不按来源拦,仍留在清单里保持盘点完整。
|
|
1355
1544
|
'/api/cloudflare/start',
|
|
1356
1545
|
'/api/cloudflare/stop',
|
|
1546
|
+
// ZeroNews 公网地址读取:localOnly 的本机只读路由,留在清单里保持盘点完整。
|
|
1547
|
+
'/api/relay/zeronews/endpoints',
|
|
1548
|
+
'/api/relay/zeronews/prepare',
|
|
1549
|
+
// ZeroNews 线路连接 / 断开:与其它管理动作一样不按来源拦,留在清单里保持盘点完整。
|
|
1550
|
+
'/api/relay/zeronews/connect',
|
|
1551
|
+
'/api/relay/zeronews/disconnect',
|
|
1552
|
+
// 节点小宝线路:设备端状态 / 绑定链接 / 手填线路地址,都是 localOnly 的本机路由。
|
|
1553
|
+
'/api/relay/jdxb/status',
|
|
1554
|
+
'/api/relay/jdxb/bind',
|
|
1555
|
+
'/api/relay/jdxb/install',
|
|
1556
|
+
'/api/relay/jdxb/url',
|
|
1357
1557
|
// 点对点隧道的现状与启停(没有白名单:能连上的前提就是密钥对得上)。
|
|
1358
1558
|
'/api/relay/p2p',
|
|
1359
1559
|
'/api/relay/p2p/enabled',
|
|
@@ -1381,10 +1581,12 @@ const WEB_ACCESS_ROUTES = new Set([
|
|
|
1381
1581
|
|
|
1382
1582
|
// `panelDiagnosis` 一并导出,只为让 test/panel-artifact.test.cjs 能拿临时目录跑那三条分支:
|
|
1383
1583
|
// 三种「读不到」的文案分别对应「重启 / 升级 / 构建」,它们混起来就是这个 bug 的原样。
|
|
1584
|
+
// `probeTcpHealth` 同理,给 test/tcp-probe.test.cjs 直接拨一台本地服务验证正文分帧。
|
|
1384
1585
|
module.exports = {
|
|
1385
1586
|
registerControlPlaneRoutes,
|
|
1386
1587
|
panelDiagnosis,
|
|
1387
1588
|
panelUrlOf,
|
|
1388
1589
|
panelScopeOf,
|
|
1590
|
+
probeTcpHealth,
|
|
1389
1591
|
WEB_ACCESS_ROUTES,
|
|
1390
1592
|
};
|
package/lib/routes/mobile-api.js
CHANGED
|
@@ -240,6 +240,28 @@ function registerMobileRoutes(deps) {
|
|
|
240
240
|
// 手机按该口说话、不自己猜。它是独立线路自己的状态,和 p2p / 中转互不覆盖;宿主没接这一
|
|
241
241
|
// 块(老装配 / 运行时没起)时为 null,手机当「没有这条线路」处理。
|
|
242
242
|
cloudflare: deps.cloudflare && typeof deps.cloudflare.status === 'function' ? deps.cloudflare.status() : null,
|
|
243
|
+
// 通用线路清单(ZeroNews 等第三方线路):心跳每轮都带,手机据此把线路落进会话、进自动档候选。
|
|
244
|
+
// 与控制面上报同一份来源(state.zeroNewsUrl + state.customRoutes),空表 = 电脑上一条都没接。
|
|
245
|
+
customRoutes: (() => {
|
|
246
|
+
const out = [];
|
|
247
|
+
const seen = new Set();
|
|
248
|
+
const zero = typeof state.zeroNewsUrl === 'string' ? state.zeroNewsUrl.trim().replace(/\/+$/, '') : '';
|
|
249
|
+
if (zero) { out.push({ url: zero, name: 'ZeroNews', transport: 'http' }); seen.add(zero); }
|
|
250
|
+
// 节点小宝那条线路:与控制面上报同一份来源、同一个形状校验(https 域名 / 主机:端口)。
|
|
251
|
+
const jdxb = require('../jdxb/probe.cjs').lineOf(state.jdxbUrl);
|
|
252
|
+
if (jdxb && !seen.has(jdxb.url)) { out.push({ url: jdxb.url, name: '节点小宝', transport: jdxb.transport }); seen.add(jdxb.url); }
|
|
253
|
+
// FRP 隧道:本机 frpc 分到的地址,独立一条线路(与用户手填的 TCP 直连无关)。
|
|
254
|
+
const frp = require('../jdxb/probe.cjs').lineOf(state.frpUrl);
|
|
255
|
+
if (frp && !seen.has(frp.url)) { out.push({ url: frp.url, name: 'FRP', transport: frp.transport }); seen.add(frp.url); }
|
|
256
|
+
for (const route of (Array.isArray(state.customRoutes) ? state.customRoutes : [])) {
|
|
257
|
+
if (!route || typeof route !== 'object') continue;
|
|
258
|
+
const url = typeof route.url === 'string' ? route.url.trim().replace(/\/+$/, '') : '';
|
|
259
|
+
if (!url || seen.has(url)) continue;
|
|
260
|
+
seen.add(url);
|
|
261
|
+
out.push({ url, name: typeof route.name === 'string' ? route.name.trim().slice(0, 80) : '', transport: route.transport === 'tcp' ? 'tcp' : 'http' });
|
|
262
|
+
}
|
|
263
|
+
return out;
|
|
264
|
+
})(),
|
|
243
265
|
// 公用中转被宿主强制停用了(用户配了公网可达的自建:自建中转 / 直连 / TCP 直连)。
|
|
244
266
|
// 面板那份 status(control-plane.js)早就带这一格,手机走的这条心跳原先没带 ——
|
|
245
267
|
// 于是手机永远按「公用中转还开着」画网络页:选择线路里仍摆「只走公用中转」、
|
package/lib/update-install.cjs
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* 自己装新版:在 profile 里跑它自己的包管理器,把本插件换到指定版本;不借道插件市场,也不自己实现包管理。
|
|
9
|
-
* 必要开关(auto-install-peers / minimum-release-age / ignore-workspace-root-check)命令行与环境变量各带一份,因为 pnpm 12 会静默忽略部分 --config
|
|
9
|
+
* 必要开关(auto-install-peers / minimum-release-age / ignore-workspace-root-check / strict-dep-builds)命令行与环境变量各带一份,因为 pnpm 12 会静默忽略部分 --config。最后那一格管的是 profile 里别的插件批没批安装脚本:那件事与这一版装没装上无关,不关掉的话 pnpm 在装完之后仍以 ERR_PNPM_IGNORED_BUILDS 非零退出,更新被当成失败还回滚。
|
|
10
10
|
* 装完把版本登记进 profile 的 minimumReleaseAgeExclude,否则 pnpm 校验整份 lockfile 会把整台机器的安装都拒掉;包管理器优先用宿主发布的那份(PATH 版本不同会 ERR_PNPM_UNEXPECTED_STORE)。
|
|
11
11
|
* 环境对不上时按 ERR_PNPM_*_DIFF / store 不一致各修一次再重试;装前先看有没有 agent 在跑(force 与 auto 跳过这道闸);失败要带出包管理器自己的报错正文;Windows 上是 .cmd,见 `cmdInvocation`。
|
|
12
12
|
*/
|
|
@@ -154,6 +154,7 @@ const POLICY_ENV = {
|
|
|
154
154
|
PNPM_CONFIG_AUTO_INSTALL_PEERS: 'false',
|
|
155
155
|
PNPM_CONFIG_MINIMUM_RELEASE_AGE: '0',
|
|
156
156
|
PNPM_CONFIG_IGNORE_WORKSPACE_ROOT_CHECK: 'true',
|
|
157
|
+
PNPM_CONFIG_STRICT_DEP_BUILDS: 'false',
|
|
157
158
|
};
|
|
158
159
|
|
|
159
160
|
/** 「配置里这个包用的是哪个注册表」缓存多久:查更新两分钟一轮,源不常换。 */
|
|
@@ -777,7 +778,7 @@ async function installLatest({
|
|
|
777
778
|
|
|
778
779
|
// 一律带上:自动更新是「一检测到就装」,手动点的那一下同样是「现在就要」,没理由先让这道
|
|
779
780
|
// 策略挡一次、再靠失败重试绕过来。命令行与环境变量各带一份,pnpm 12 只认后者(见 POLICY_ENV)。
|
|
780
|
-
const policyArgs = ['--config.auto-install-peers=false', '--config.minimum-release-age=0', '--config.ignore-workspace-root-check=true'];
|
|
781
|
+
const policyArgs = ['--config.auto-install-peers=false', '--config.minimum-release-age=0', '--config.ignore-workspace-root-check=true', '--config.strict-dep-builds=false'];
|
|
781
782
|
const installArgs = (target) => picked.manager === 'pnpm'
|
|
782
783
|
? ['add', `${name}@${target}`, ...policyArgs]
|
|
783
784
|
: ['install', `${name}@${target}`, '--no-audit', '--no-fund'];
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// 从本机 ZeroNews 客户端读取「已建好的隧道公网地址」,给面板的「一键填入直连地址」用。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* ZeroNews 是账号制内网穿透:隧道由用户自己在它的控制台/客户端建好,插件不碰账号、不建隧道、
|
|
6
|
+
* 不占它「一个免费账号一条隧道」的限额。这里只做一件只读的事——问本机那个已经跑着的
|
|
7
|
+
* ZeroNews 客户端「你现在有哪些可用的 HTTPS 隧道」,把公网地址交给面板填进「直连地址」栏。
|
|
8
|
+
*
|
|
9
|
+
* 为什么走宿主而不是面板直接 fetch:ZeroNews 本地 API 监听 127.0.0.1:37271,面板在浏览器里
|
|
10
|
+
* 跨域读它会被 CORS 挡下(实测无 Access-Control-Allow-* 头);宿主是本机 node 进程,读本地
|
|
11
|
+
* 回环地址没有跨域问题,而且这条路径本身是 localOnly 控制面,只有本机面板能调。
|
|
12
|
+
*
|
|
13
|
+
* 只认 HTTPS、只认 active 的 endpoint:TCP 隧道是「主机:端口」不是 http(s) 地址,填进直连栏
|
|
14
|
+
* 会被当成域名解析而失败;非 active 的(建到一半 / 已断开)填进去是个当下就拨不通的地址。
|
|
15
|
+
* 一条都没有就返回空清单,面板据此说「本机没有可用的 ZeroNews 隧道」。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** ZeroNews 客户端本地 API 默认监听地址与端点路径。 */
|
|
19
|
+
const DEFAULT_BASE = 'http://127.0.0.1:37271';
|
|
20
|
+
const ENDPOINTS_PATH = '/api/v1/endpoints';
|
|
21
|
+
/** 本地回环读取也要设超时:客户端没起 / 端口被别的程序占住时不能让面板一直转。 */
|
|
22
|
+
const DEFAULT_TIMEOUT_MS = 3000;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 一条地址长得像不像能填进「直连地址」的 https URL。
|
|
26
|
+
* 复用Config 那侧的口径:只认 http(s)、必须能解析出主机。这里更严一点只收 https——
|
|
27
|
+
* ZeroNews 对外就是 https 域名,明文 http 的隧道没有意义,也不该被一键填进去。
|
|
28
|
+
*/
|
|
29
|
+
function httpsUrlOf(value) {
|
|
30
|
+
if (typeof value !== 'string') return '';
|
|
31
|
+
const url = value.trim().replace(/\/+$/, '');
|
|
32
|
+
if (!/^https:\/\/[^\s/]+/i.test(url)) return '';
|
|
33
|
+
try {
|
|
34
|
+
if (!new URL(url).hostname) return '';
|
|
35
|
+
} catch {
|
|
36
|
+
return '';
|
|
37
|
+
}
|
|
38
|
+
return url;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 从 ZeroNews 本地 API 的响应体里挑出可用的 HTTPS 公网地址。
|
|
43
|
+
* 兼容两种形状:官方文档的 `{ code:200, data:{ items:[...] } }`,以及某些版本回的裸数组 / `{ endpoints:[...] }`。
|
|
44
|
+
* 每条 endpoint 的域名可能在 `domain` 或 `public_url`;端口由 ZeroNews 自己管,域名不带端口。
|
|
45
|
+
*/
|
|
46
|
+
function extractEndpoints(payload) {
|
|
47
|
+
const data = payload && typeof payload === 'object' && 'data' in payload ? payload.data : payload;
|
|
48
|
+
let items = [];
|
|
49
|
+
if (Array.isArray(data)) items = data;
|
|
50
|
+
else if (data && Array.isArray(data.items)) items = data.items;
|
|
51
|
+
else if (data && Array.isArray(data.endpoints)) items = data.endpoints;
|
|
52
|
+
const out = [];
|
|
53
|
+
const seen = new Set();
|
|
54
|
+
for (const item of items) {
|
|
55
|
+
if (!item || typeof item !== 'object') continue;
|
|
56
|
+
const status = String(item.status || '').toLowerCase();
|
|
57
|
+
if (status && status !== 'active') continue;
|
|
58
|
+
const type = String(item.type || '').toUpperCase();
|
|
59
|
+
if (type && type !== 'HTTPS') continue;
|
|
60
|
+
const domain = typeof item.domain === 'string' && item.domain
|
|
61
|
+
? item.domain
|
|
62
|
+
: typeof item.public_url === 'string' ? item.public_url : '';
|
|
63
|
+
const url = httpsUrlOf(domain.includes('://') ? domain : `https://${domain}`);
|
|
64
|
+
if (!url || seen.has(url)) continue;
|
|
65
|
+
seen.add(url);
|
|
66
|
+
out.push(url);
|
|
67
|
+
}
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* 读本机 ZeroNews 的可用隧道地址。
|
|
73
|
+
*
|
|
74
|
+
* @param {object} [options]
|
|
75
|
+
* @param {string} [options.base] 本地 API 根地址(测试可注入)。
|
|
76
|
+
* @param {(url: string, init: object) => Promise<any>} [options.fetchImpl] fetch 注入(测试用)。
|
|
77
|
+
* @param {number} [options.timeoutMs] 读取超时。
|
|
78
|
+
* @returns {Promise<{ ok: boolean, urls: string[], error: string, available: boolean }>}
|
|
79
|
+
* available=false 表示本机 API 连不上(客户端没装 / 没起);连得上但没有可用隧道时
|
|
80
|
+
* ok=true、urls 为空。两种情况面板给不同提示。
|
|
81
|
+
*/
|
|
82
|
+
async function readZeroNewsEndpoints(options = {}) {
|
|
83
|
+
const base = String(options.base || DEFAULT_BASE).replace(/\/+$/, '');
|
|
84
|
+
const url = `${base}${ENDPOINTS_PATH}`;
|
|
85
|
+
const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : DEFAULT_TIMEOUT_MS;
|
|
86
|
+
const doFetch = typeof options.fetchImpl === 'function'
|
|
87
|
+
? options.fetchImpl
|
|
88
|
+
: (typeof globalThis.fetch === 'function' ? globalThis.fetch : null);
|
|
89
|
+
if (!doFetch) {
|
|
90
|
+
return { ok: false, urls: [], available: false, error: '当前环境没有可用的 fetch' };
|
|
91
|
+
}
|
|
92
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
93
|
+
const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
|
|
94
|
+
try {
|
|
95
|
+
const response = await doFetch(url, {
|
|
96
|
+
headers: { accept: 'application/json' },
|
|
97
|
+
...(controller ? { signal: controller.signal } : {}),
|
|
98
|
+
});
|
|
99
|
+
if (!response || response.ok !== true) {
|
|
100
|
+
const status = response && response.status ? ` HTTP ${response.status}` : '';
|
|
101
|
+
return { ok: false, urls: [], available: false, error: `本机 ZeroNews 客户端没有回应${status}` };
|
|
102
|
+
}
|
|
103
|
+
const payload = await response.json();
|
|
104
|
+
// code 是 ZeroNews 的业务码:非 200 一律当读失败,别把错误体当隧道清单。
|
|
105
|
+
if (payload && typeof payload === 'object' && 'code' in payload && payload.code !== 200) {
|
|
106
|
+
return { ok: false, urls: [], available: true, error: 'ZeroNews 客户端返回了错误' };
|
|
107
|
+
}
|
|
108
|
+
return { ok: true, urls: extractEndpoints(payload), available: true, error: '' };
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (controller && controller.signal.aborted) {
|
|
111
|
+
return { ok: false, urls: [], available: false, error: '读取本机 ZeroNews 超时,请确认客户端正在运行' };
|
|
112
|
+
}
|
|
113
|
+
const raw = error && error.message ? error.message : String(error);
|
|
114
|
+
return { ok: false, urls: [], available: false, error: `连不上本机 ZeroNews 客户端:${raw}` };
|
|
115
|
+
} finally {
|
|
116
|
+
if (timer) clearTimeout(timer);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
module.exports = {
|
|
121
|
+
DEFAULT_BASE,
|
|
122
|
+
ENDPOINTS_PATH,
|
|
123
|
+
httpsUrlOf,
|
|
124
|
+
extractEndpoints,
|
|
125
|
+
readZeroNewsEndpoints,
|
|
126
|
+
};
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// ZeroNews 客户端获取层:自带 → 系统 PATH → 缓存 → 官方地址下载,四平台固定路径。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 在用户电脑上弄到一份能用的 zeronews 可执行文件。像 cloudflared 那样单独一层:
|
|
6
|
+
* 用户不用自己装——插件按平台从官方地址下载、落到自己的运行目录。
|
|
7
|
+
*
|
|
8
|
+
* 官方下载地址(2026-11-22 实测 HEAD 均为 200):
|
|
9
|
+
* macOS arm64 https://download.zeronews.cc/macos/arm/zeronews
|
|
10
|
+
* macOS x64 https://download.zeronews.cc/macos/amd/zeronews
|
|
11
|
+
* 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.0.tar (包内 zeronews/zeronews)
|
|
13
|
+
* Linux arm64 https://download.v2.zeronews.cc/linux/arm64/zeronews-linux-4.1.0.tar
|
|
14
|
+
*
|
|
15
|
+
* 三条来源按优先级:环境变量 / PATH 里已有 → 缓存 → 下载。Linux 下官方给的是 .tar,
|
|
16
|
+
* 这里只挑出里面的 zeronews 可执行文件落盘。所有 I/O 都可注入,守卫用假体走完整条分支。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const fs = require('node:fs');
|
|
20
|
+
const path = require('node:path');
|
|
21
|
+
const { dshHome } = require('../shared/paths.js');
|
|
22
|
+
|
|
23
|
+
const VERSION = '4.1.0';
|
|
24
|
+
const DOWNLOADS = {
|
|
25
|
+
'darwin-arm64': 'https://download.zeronews.cc/macos/arm/zeronews',
|
|
26
|
+
'darwin-x64': 'https://download.zeronews.cc/macos/amd/zeronews',
|
|
27
|
+
'win32-x64': 'https://download.zeronews.cc/windows/x64/zeronews.exe',
|
|
28
|
+
'linux-x64': `https://download.v2.zeronews.cc/linux/x86_x64/zeronews-linux-${VERSION}.tar`,
|
|
29
|
+
'linux-arm64': `https://download.v2.zeronews.cc/linux/arm64/zeronews-linux-${VERSION}.tar`,
|
|
30
|
+
};
|
|
31
|
+
/** Linux 下载的是 tar 包,其余平台就是裸可执行文件。 */
|
|
32
|
+
const TAR_PLATFORMS = new Set(['linux-x64', 'linux-arm64']);
|
|
33
|
+
|
|
34
|
+
function platformId(platform, arch) {
|
|
35
|
+
const p = platform || process.platform;
|
|
36
|
+
const a = arch || process.arch;
|
|
37
|
+
const key = `${p}-${a}`;
|
|
38
|
+
return DOWNLOADS[key] ? key : '';
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function downloadUrlOf(platform, arch) {
|
|
42
|
+
return DOWNLOADS[platformId(platform, arch)] || '';
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function runDir(root) {
|
|
46
|
+
return root || path.join(dshHome(), 'zeronews-run');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 从一份 tar 二进制流里挑出 zeronews 可执行文件(不落盘其它成员)。 */
|
|
50
|
+
function extractFromTar(buf) {
|
|
51
|
+
// tar 每 512 字节一个头;头里 name[0..100]、size[124..136](八进制)、typeflag[156]。
|
|
52
|
+
let offset = 0;
|
|
53
|
+
while (offset + 512 <= buf.length) {
|
|
54
|
+
const header = buf.subarray(offset, offset + 512);
|
|
55
|
+
if (header.every((byte) => byte === 0)) break;
|
|
56
|
+
const name = header.subarray(0, 100).toString('utf8').replace(/\0.*$/, '');
|
|
57
|
+
const sizeText = header.subarray(124, 136).toString('utf8').replace(/\0.*$/, '').trim();
|
|
58
|
+
const size = parseInt(sizeText, 8);
|
|
59
|
+
const typeflag = String.fromCharCode(header[156]);
|
|
60
|
+
const body = buf.subarray(offset + 512, offset + 512 + size);
|
|
61
|
+
if ((name === 'zeronews' || name.endsWith('/zeronews')) && (typeflag === '0' || typeflag === '\0') && body.length) {
|
|
62
|
+
return Buffer.from(body);
|
|
63
|
+
}
|
|
64
|
+
offset += 512 + Math.ceil(size / 512) * 512;
|
|
65
|
+
}
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* @param {object} options
|
|
71
|
+
* @param {() => string} [options.env] 读环境变量(PATH / DSHM_ZERONEWS_BIN)
|
|
72
|
+
* @param {object} [options.fsImpl] 文件系统注入
|
|
73
|
+
* @param {(url: string) => Promise<{ok:boolean, arrayBuffer:()=>Promise<ArrayBuffer>}>} [options.fetchImpl]
|
|
74
|
+
* @param {object} [options.platform] { platform, arch }
|
|
75
|
+
* @param {string} [options.root] 运行目录
|
|
76
|
+
*/
|
|
77
|
+
async function ensureZeroNews(options = {}) {
|
|
78
|
+
const fsImpl = options.fsImpl || fs;
|
|
79
|
+
const readEnv = typeof options.env === 'function' ? options.env : (key) => process.env[key] || '';
|
|
80
|
+
const doFetch = typeof options.fetchImpl === 'function'
|
|
81
|
+
? options.fetchImpl
|
|
82
|
+
: (typeof globalThis.fetch === 'function' ? globalThis.fetch : null);
|
|
83
|
+
const plat = options.platform || {};
|
|
84
|
+
const key = platformId(plat.platform, plat.arch);
|
|
85
|
+
const dir = runDir(options.root);
|
|
86
|
+
const binName = (plat.platform || process.platform) === 'win32' ? 'zeronews.exe' : 'zeronews';
|
|
87
|
+
const cached = path.join(dir, binName);
|
|
88
|
+
const exists = (p) => { try { return fsImpl.statSync(p).isFile(); } catch { return false; } };
|
|
89
|
+
|
|
90
|
+
// ① 用户显式指定 / PATH 上已有,直接用。
|
|
91
|
+
const explicit = readEnv('DSHM_ZERONEWS_BIN');
|
|
92
|
+
if (explicit && exists(explicit)) return { ok: true, path: explicit, source: 'env' };
|
|
93
|
+
// macOS 上官方默认装到 /Applications/zeronews/zeronews(那份可能已经登录),优先复用,别另起一份未登录的。
|
|
94
|
+
if ((plat.platform || process.platform) === 'darwin') {
|
|
95
|
+
const systemInstalled = path.join('/Applications/zeronews', binName);
|
|
96
|
+
if (exists(systemInstalled)) return { ok: true, path: systemInstalled, source: 'system' };
|
|
97
|
+
}
|
|
98
|
+
for (const entry of String(readEnv('PATH') || '').split(path.delimiter).filter(Boolean)) {
|
|
99
|
+
const candidate = path.join(entry, binName);
|
|
100
|
+
if (exists(candidate)) return { ok: true, path: candidate, source: 'path' };
|
|
101
|
+
}
|
|
102
|
+
// ② 以前下载过的缓存。
|
|
103
|
+
if (exists(cached)) return { ok: true, path: cached, source: 'cache' };
|
|
104
|
+
// ③ 都不支持或没网,如实说。
|
|
105
|
+
if (!key) return { ok: false, code: 'unsupported-platform', path: '', source: '' };
|
|
106
|
+
if (!doFetch) return { ok: false, code: 'download-failed', path: '', source: '' };
|
|
107
|
+
|
|
108
|
+
const url = DOWNLOADS[key];
|
|
109
|
+
try {
|
|
110
|
+
const response = await doFetch(url);
|
|
111
|
+
if (!response || response.ok !== true) return { ok: false, code: 'download-failed', path: '', source: '' };
|
|
112
|
+
let bytes = Buffer.from(await response.arrayBuffer());
|
|
113
|
+
if (TAR_PLATFORMS.has(key)) {
|
|
114
|
+
const extracted = extractFromTar(bytes);
|
|
115
|
+
if (!extracted) return { ok: false, code: 'extract-failed', path: '', source: '' };
|
|
116
|
+
bytes = extracted;
|
|
117
|
+
}
|
|
118
|
+
fsImpl.mkdirSync(dir, { recursive: true });
|
|
119
|
+
fsImpl.writeFileSync(cached, bytes, { mode: 0o755 });
|
|
120
|
+
return { ok: true, path: cached, source: 'downloaded' };
|
|
121
|
+
} catch {
|
|
122
|
+
return { ok: false, code: 'download-failed', path: '', source: '' };
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
module.exports = {
|
|
127
|
+
VERSION, DOWNLOADS, platformId, downloadUrlOf, runDir, extractFromTar, ensureZeroNews,
|
|
128
|
+
};
|