dsh-mobile-ios 0.2.8 → 0.2.10
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/lib/client.js +345 -71
- package/package.json +53 -53
- package/src/cloudflare.mjs +73 -6
- package/src/dns-probe.mjs +24 -4
- package/src/plugin-update.mjs +148 -0
- package/src/provision-local.mjs +137 -6
- package/src/rest.mjs +79 -0
- package/src/zone-health.mjs +251 -0
package/package.json
CHANGED
|
@@ -1,53 +1,53 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "dsh-mobile-ios",
|
|
3
|
-
"version": "0.2.
|
|
4
|
-
"type": "module",
|
|
5
|
-
"description": "DSH iOS移动伴侣:iPhone/iPad 扫码连接 DSH 桌面端,局域网直连 + Cloudflare Tunnel 固定域名远程两种通道",
|
|
6
|
-
"main": "entries/plugin.mjs",
|
|
7
|
-
"icon": "assets/brand/plugin-icon.png",
|
|
8
|
-
"engines": {
|
|
9
|
-
"node": ">=20",
|
|
10
|
-
"dsh": ">=0.2.1-alpha.4"
|
|
11
|
-
},
|
|
12
|
-
"keywords": [
|
|
13
|
-
"dsh-plugin",
|
|
14
|
-
"dsh",
|
|
15
|
-
"ios",
|
|
16
|
-
"mobile-companion",
|
|
17
|
-
"pairing"
|
|
18
|
-
],
|
|
19
|
-
"license": "MIT",
|
|
20
|
-
"files": [
|
|
21
|
-
"assets/",
|
|
22
|
-
"entries/",
|
|
23
|
-
"lib/",
|
|
24
|
-
"src/",
|
|
25
|
-
"cordis.patch.yml",
|
|
26
|
-
"README.md",
|
|
27
|
-
"LICENSE"
|
|
28
|
-
],
|
|
29
|
-
"scripts": {
|
|
30
|
-
"start": "node entries/sidecar.mjs --host=mock --dev",
|
|
31
|
-
"start:lan": "node entries/sidecar.mjs --host=mock --dev --lan=true",
|
|
32
|
-
"probe": "node spike0/probe.mjs",
|
|
33
|
-
"test": "node test/selftest.mjs && node test/version.mjs && node test/update-dialog.mjs && node test/ops.mjs && node test/resilience.mjs && node test/borrowed.mjs && node test/mux-table.mjs && node test/live-frames.mjs && node test/artifacts.mjs && node test/attachments.mjs && node test/session-actions.mjs && node test/enhance.mjs && node test/tunnel-named.mjs && node test/cloudflared-install.mjs && node test/install-continue.mjs"
|
|
34
|
-
},
|
|
35
|
-
"dsh": {
|
|
36
|
-
"bundle": {
|
|
37
|
-
"patch": "./cordis.patch.yml"
|
|
38
|
-
},
|
|
39
|
-
"client": {
|
|
40
|
-
"platform": "web",
|
|
41
|
-
"immediately": true
|
|
42
|
-
}
|
|
43
|
-
},
|
|
44
|
-
"exports": {
|
|
45
|
-
".": {
|
|
46
|
-
"default": "./entries/plugin.mjs"
|
|
47
|
-
},
|
|
48
|
-
"./client": {
|
|
49
|
-
"default": "./lib/client.js"
|
|
50
|
-
},
|
|
51
|
-
"./package.json": "./package.json"
|
|
52
|
-
}
|
|
53
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "dsh-mobile-ios",
|
|
3
|
+
"version": "0.2.10",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "DSH iOS移动伴侣:iPhone/iPad 扫码连接 DSH 桌面端,局域网直连 + Cloudflare Tunnel 固定域名远程两种通道",
|
|
6
|
+
"main": "entries/plugin.mjs",
|
|
7
|
+
"icon": "assets/brand/plugin-icon.png",
|
|
8
|
+
"engines": {
|
|
9
|
+
"node": ">=20",
|
|
10
|
+
"dsh": ">=0.2.1-alpha.4"
|
|
11
|
+
},
|
|
12
|
+
"keywords": [
|
|
13
|
+
"dsh-plugin",
|
|
14
|
+
"dsh",
|
|
15
|
+
"ios",
|
|
16
|
+
"mobile-companion",
|
|
17
|
+
"pairing"
|
|
18
|
+
],
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"files": [
|
|
21
|
+
"assets/",
|
|
22
|
+
"entries/",
|
|
23
|
+
"lib/",
|
|
24
|
+
"src/",
|
|
25
|
+
"cordis.patch.yml",
|
|
26
|
+
"README.md",
|
|
27
|
+
"LICENSE"
|
|
28
|
+
],
|
|
29
|
+
"scripts": {
|
|
30
|
+
"start": "node entries/sidecar.mjs --host=mock --dev",
|
|
31
|
+
"start:lan": "node entries/sidecar.mjs --host=mock --dev --lan=true",
|
|
32
|
+
"probe": "node spike0/probe.mjs",
|
|
33
|
+
"test": "node test/selftest.mjs && node test/version.mjs && node test/update-dialog.mjs && node test/ops.mjs && node test/resilience.mjs && node test/borrowed.mjs && node test/mux-table.mjs && node test/live-frames.mjs && node test/artifacts.mjs && node test/attachments.mjs && node test/session-actions.mjs && node test/enhance.mjs && node test/tunnel-named.mjs && node test/cloudflared-install.mjs && node test/install-continue.mjs && node test/dns-recheck.mjs && node test/plugin-selfupdate.mjs && node test/zone-moved.mjs"
|
|
34
|
+
},
|
|
35
|
+
"dsh": {
|
|
36
|
+
"bundle": {
|
|
37
|
+
"patch": "./cordis.patch.yml"
|
|
38
|
+
},
|
|
39
|
+
"client": {
|
|
40
|
+
"platform": "web",
|
|
41
|
+
"immediately": true
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
"exports": {
|
|
45
|
+
".": {
|
|
46
|
+
"default": "./entries/plugin.mjs"
|
|
47
|
+
},
|
|
48
|
+
"./client": {
|
|
49
|
+
"default": "./lib/client.js"
|
|
50
|
+
},
|
|
51
|
+
"./package.json": "./package.json"
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/cloudflare.mjs
CHANGED
|
@@ -22,7 +22,8 @@ import path from 'node:path';
|
|
|
22
22
|
import { fail } from './protocol.mjs';
|
|
23
23
|
import { deriveSubdomain, isValidLabel } from './dns-label.mjs';
|
|
24
24
|
import { DNS_PENDING_HINT, DNS_TAMPER_HINT, dnsWarningFor, evaluateDnsAnswer, probeDns } from './dns-probe.mjs';
|
|
25
|
-
import { LocalProvisioner } from './provision-local.mjs';
|
|
25
|
+
import { LocalProvisioner, sanitizeZone } from './provision-local.mjs';
|
|
26
|
+
import { diagnoseZone, findDnsOwner, ZONE_STATUS_HINT } from './zone-health.mjs';
|
|
26
27
|
|
|
27
28
|
// 兼容既有调用方与测试:子域规则从 dns-label.mjs 来,这里一并导出
|
|
28
29
|
export { deriveSubdomain, isValidLabel };
|
|
@@ -72,13 +73,16 @@ function saveState(file, state) {
|
|
|
72
73
|
}
|
|
73
74
|
|
|
74
75
|
class BaseProvisioner {
|
|
75
|
-
constructor({ stateFile = null, log = () => {}, baseDomain = 'matrixboard.cn', probe = null } = {}) {
|
|
76
|
+
constructor({ stateFile = null, log = () => {}, baseDomain = 'matrixboard.cn', probe = null, zoneDiagnose = null } = {}) {
|
|
76
77
|
this.stateFile = stateFile;
|
|
77
78
|
this.log = log;
|
|
78
79
|
this.baseDomain = String(baseDomain).replace(/^\./, '').toLowerCase();
|
|
79
80
|
this._state = undefined; // undefined=未读;null=没有
|
|
80
81
|
// 可注入:测试里不该真发 DNS 查询(依赖外网且要等重试)
|
|
81
82
|
this.probe = probe || probeDns;
|
|
83
|
+
// 解析失败时进一步归因(moved / pending / ns-mismatch);不注入就只报「解析不到」
|
|
84
|
+
this.zoneDiagnose = zoneDiagnose;
|
|
85
|
+
this._zone = null;
|
|
82
86
|
}
|
|
83
87
|
|
|
84
88
|
/**
|
|
@@ -96,8 +100,25 @@ class BaseProvisioner {
|
|
|
96
100
|
// 记录若被人改指到别的隧道/服务器,解析照样「成功」,流量却会落到对方 ingress——
|
|
97
101
|
// 这时按「地址不可用」处理,绝不下发。
|
|
98
102
|
const verdict = evaluateDnsAnswer(check, current?.tunnelId);
|
|
103
|
+
// 解析不到时再问一句「这域名现在归谁」:moved(被别的账号接管)与 pending(NS 还没指过来)
|
|
104
|
+
// 的修法完全不同,笼统一句「等 NS 生效」会让人白等。
|
|
105
|
+
let zone = null;
|
|
106
|
+
if (!verdict.ok && typeof this.zoneDiagnose === 'function') {
|
|
107
|
+
try {
|
|
108
|
+
zone = sanitizeZone(await this.zoneDiagnose({ baseDomain: this.baseDomain, dnsOk: false }));
|
|
109
|
+
} catch {
|
|
110
|
+
zone = null;
|
|
111
|
+
}
|
|
112
|
+
this._zone = zone;
|
|
113
|
+
}
|
|
99
114
|
if (current && current.hostname === hostname) {
|
|
100
|
-
this.#persist({
|
|
115
|
+
this.#persist({
|
|
116
|
+
...current,
|
|
117
|
+
dnsOk: verdict.ok,
|
|
118
|
+
dnsTampered: verdict.tampered,
|
|
119
|
+
dnsCheckedAt: new Date().toISOString(),
|
|
120
|
+
zone,
|
|
121
|
+
});
|
|
101
122
|
}
|
|
102
123
|
if (verdict.tampered) {
|
|
103
124
|
this.log(`tunnel 警告 固定地址解析被改指 ${hostname} → ${verdict.target}(期望 ${verdict.expected}),拒绝下发该地址`);
|
|
@@ -109,6 +130,28 @@ class BaseProvisioner {
|
|
|
109
130
|
return verdict;
|
|
110
131
|
}
|
|
111
132
|
|
|
133
|
+
/**
|
|
134
|
+
* 面板「重新检测解析」:强制重探一次并写回状态,不做缓存短路。
|
|
135
|
+
* 与 LocalProvisioner.recheckDns 同一契约,面板对两种开通形态一视同仁。
|
|
136
|
+
*/
|
|
137
|
+
async recheckDns() {
|
|
138
|
+
const s = this.state;
|
|
139
|
+
if (!s?.hostname) return { provisioned: false, ok: false, tampered: false, warning: null, zone: null };
|
|
140
|
+
const verdict = await this.verifyDns(s.hostname);
|
|
141
|
+
const now = this.state;
|
|
142
|
+
return {
|
|
143
|
+
provisioned: true,
|
|
144
|
+
hostname: now.hostname,
|
|
145
|
+
ok: Boolean(verdict.ok),
|
|
146
|
+
tampered: Boolean(verdict.tampered),
|
|
147
|
+
expected: verdict.expected ?? null,
|
|
148
|
+
target: verdict.target ?? null,
|
|
149
|
+
warning: dnsWarningFor(now),
|
|
150
|
+
checkedAt: now.dnsCheckedAt ?? null,
|
|
151
|
+
zone: now.zone ?? this._zone ?? null,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
112
155
|
/** 状态文件里的缓存(读一次后常驻;写穿时同步更新)。 */
|
|
113
156
|
get state() {
|
|
114
157
|
if (this._state === undefined) this._state = loadState(this.stateFile, this.log);
|
|
@@ -143,6 +186,8 @@ class BaseProvisioner {
|
|
|
143
186
|
port: s.port ?? null,
|
|
144
187
|
// null = 还没验过;true/false = 验过且结论明确
|
|
145
188
|
dnsOk: s.dnsOk ?? null,
|
|
189
|
+
dnsCheckedAt: s.dnsCheckedAt ?? null,
|
|
190
|
+
zone: s.zone ?? this._zone ?? null,
|
|
146
191
|
warning: dnsWarningFor(s),
|
|
147
192
|
createdAt: s.createdAt ?? null,
|
|
148
193
|
updatedAt: s.updatedAt ?? null,
|
|
@@ -244,8 +289,9 @@ export class CloudflareProvisioner extends BaseProvisioner {
|
|
|
244
289
|
apiBase = CF_API_BASE,
|
|
245
290
|
log = () => {},
|
|
246
291
|
probe = null,
|
|
292
|
+
zoneDiagnose = null,
|
|
247
293
|
} = {}) {
|
|
248
|
-
super({ stateFile, log, baseDomain, probe });
|
|
294
|
+
super({ stateFile, log, baseDomain, probe, zoneDiagnose });
|
|
249
295
|
this.apiToken = apiToken;
|
|
250
296
|
this.accountId = accountId;
|
|
251
297
|
this.zoneId = zoneId;
|
|
@@ -253,6 +299,15 @@ export class CloudflareProvisioner extends BaseProvisioner {
|
|
|
253
299
|
this.seed = seed;
|
|
254
300
|
this.fetchImpl = fetchImpl;
|
|
255
301
|
this.apiBase = String(apiBase).replace(/\/$/, '');
|
|
302
|
+
// API 形态本身就有 zone 级凭据,不必借 cert.pem:解析失败时直接问清 zone 现状
|
|
303
|
+
this.zoneDiagnose = zoneDiagnose || ((args = {}) => diagnoseZone({
|
|
304
|
+
...args,
|
|
305
|
+
apiToken: this.apiToken,
|
|
306
|
+
zoneId: this.zoneId,
|
|
307
|
+
baseDomain: args.baseDomain || this.baseDomain,
|
|
308
|
+
fetchImpl: this.fetchImpl,
|
|
309
|
+
apiBase: this.apiBase,
|
|
310
|
+
}));
|
|
256
311
|
}
|
|
257
312
|
|
|
258
313
|
get kind() {
|
|
@@ -339,8 +394,17 @@ export class CloudflareProvisioner extends BaseProvisioner {
|
|
|
339
394
|
});
|
|
340
395
|
}
|
|
341
396
|
if (zone.status && zone.status !== 'active') {
|
|
342
|
-
|
|
343
|
-
|
|
397
|
+
// 状态不同,修法完全不同:moved 说明域名已被另一个 Cloudflare 账号接管,
|
|
398
|
+
// 在本账号重试一万次也不会生效;pending 只是 NS 还没指过来。
|
|
399
|
+
const hint = ZONE_STATUS_HINT[zone.status] || `状态 ${zone.status}`;
|
|
400
|
+
const ns = (zone.name_servers || []).join(' / ') || '(当前账号未分配)';
|
|
401
|
+
throw fail(4021, `域名 ${this.baseDomain} 未生效:${hint}`, {
|
|
402
|
+
detail: zone.status === 'moved'
|
|
403
|
+
? `本账号分配的公网 NS 是 ${ns}。域名现在被另一个 Cloudflare 账号接管,本账号写入的记录不会下发——`
|
|
404
|
+
+ '要么在注册商把 NS 改回这一对,要么统一只用同一个 Cloudflare 账号登录(两边互斥,只能二选一)。'
|
|
405
|
+
: `本账号分配的公网 NS 是 ${ns};到域名注册商把 NS 改成这一对,生效后再开通。`,
|
|
406
|
+
zoneStatus: zone.status,
|
|
407
|
+
expectedNs: zone.name_servers || [],
|
|
344
408
|
});
|
|
345
409
|
}
|
|
346
410
|
this.zoneId = zone.id;
|
|
@@ -604,6 +668,9 @@ export function createProvisioner(config = {}, { log = () => {}, stateFile = nul
|
|
|
604
668
|
configFile: config.configFile || null,
|
|
605
669
|
seed: config.seed || null,
|
|
606
670
|
log,
|
|
671
|
+
// 生产路径才接真实探测:测试直接 new LocalProvisioner 时保持零网络依赖
|
|
672
|
+
zoneDiagnose: diagnoseZone,
|
|
673
|
+
ownerLookup: findDnsOwner,
|
|
607
674
|
});
|
|
608
675
|
}
|
|
609
676
|
if (kind === 'state') {
|
package/src/dns-probe.mjs
CHANGED
|
@@ -10,9 +10,22 @@
|
|
|
10
10
|
|
|
11
11
|
import dns from 'node:dns';
|
|
12
12
|
|
|
13
|
-
export const DNS_PENDING_HINT = '域名在当前 Cloudflare
|
|
13
|
+
export const DNS_PENDING_HINT = '域名在当前 Cloudflare 账号里还没生效(zone pending):公网 NS 指向的是另一份 zone。'
|
|
14
14
|
+ '要么把这个域名的 NS 改成该账号分配的 nameserver,要么换用持有生效 zone 的账号重新登录授权。';
|
|
15
15
|
|
|
16
|
+
// 本账号的 zone 已被另一个 Cloudflare 账号接管(status=moved)。这时改本账号的
|
|
17
|
+
// 记录、重装插件、重启隧道统统没用——公网根本不读这份 zone,必须动注册商 NS 或换账号。
|
|
18
|
+
export const DNS_MOVED_HINT = '域名已被另一个 Cloudflare 账号接管(zone moved):本机写入的记录不会下发到公网。'
|
|
19
|
+
+ '在域名注册商处把 NS 改回本账号分配的一对,或统一只用同一个 Cloudflare 账号登录。';
|
|
20
|
+
|
|
21
|
+
export const DNS_NS_MISMATCH_HINT = '域名在本账号显示已生效,但公网 NS 与本账号分配的不一致,记录暂时查不到。'
|
|
22
|
+
+ '确认注册商处两处 NS 都已改完,再点「重新检测」。';
|
|
23
|
+
|
|
24
|
+
// zone 已 active、NS 也对,公网却还是没有这条记录:多半是刚写入的记录还在传播,
|
|
25
|
+
// 或者记录被手动删了。这时重装/重开都没意义,等一下再重检即可。
|
|
26
|
+
export const DNS_UNRESOLVED_HINT = '域名在 Cloudflare 已生效,但公网暂时查不到这台主机的记录:'
|
|
27
|
+
+ '记录可能刚写入(等 1–2 分钟),或已被删除。稍后点「重新检测」,仍不行就重新「开启远程」重建记录。';
|
|
28
|
+
|
|
16
29
|
// 防劫持:CNAME 没有指向本机隧道。解析「成功」但流量会落到别人的 ingress,
|
|
17
30
|
// 扫码连接等于把指令发给未知服务器——必须当作地址不可用处理。
|
|
18
31
|
export const DNS_TAMPER_HINT = '固定域名解析异常:CNAME 已不指向本机隧道(可能被篡改或误改)。'
|
|
@@ -33,11 +46,18 @@ export function evaluateDnsAnswer(check, tunnelId) {
|
|
|
33
46
|
return { ...check, ok: Boolean(check?.ok) && !tampered, tampered, target, expected };
|
|
34
47
|
}
|
|
35
48
|
|
|
36
|
-
/** 状态 → 面板提示。篡改优先于
|
|
49
|
+
/** 状态 → 面板提示。篡改优先于 zone 故障:两者都真时,先让人处理更危险的那个。 */
|
|
37
50
|
export function dnsWarningFor(state) {
|
|
38
51
|
if (state?.dnsTampered) return DNS_TAMPER_HINT;
|
|
39
|
-
if (state?.dnsOk
|
|
40
|
-
|
|
52
|
+
if (state?.dnsOk !== false) return null;
|
|
53
|
+
// zone 层面已经诊断出结论时,用结论而不是笼统的「pending」——
|
|
54
|
+
// moved / pending / ns-mismatch 的修法完全不同,猜错等于让人白跑一趟。
|
|
55
|
+
const code = state?.zone?.code;
|
|
56
|
+
if (code === 'moved') return DNS_MOVED_HINT;
|
|
57
|
+
if (code === 'ns-mismatch') return DNS_NS_MISMATCH_HINT;
|
|
58
|
+
if (code === 'unresolved') return DNS_UNRESOLVED_HINT;
|
|
59
|
+
if (code === 'pending') return DNS_PENDING_HINT;
|
|
60
|
+
return DNS_PENDING_HINT;
|
|
41
61
|
}
|
|
42
62
|
|
|
43
63
|
/**
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// plugin-update.mjs — 插件自更新(不依赖宿主插件管理器)
|
|
2
|
+
//
|
|
3
|
+
// 为什么需要它:宿主是否暴露 `remote.pluginManager.installBundle` 取决于版本与平台,
|
|
4
|
+
// 拿不到时面板只能让用户「复制包名 → 去插件页粘贴」,而 dsh-app:// 这类自定义协议
|
|
5
|
+
// 页面里 navigator.clipboard 与 document.execCommand('copy') 都可能不可用,
|
|
6
|
+
// 于是「一键更新」在最需要它的机器上恰恰用不了。
|
|
7
|
+
//
|
|
8
|
+
// 这里走的是网关进程自己动手:从 npm registry 取 tarball → 按 dist.shasum 校验 →
|
|
9
|
+
// 解包到临时目录 → 备份旧目录 → 覆盖安装目录。全程不依赖宿主 API、不依赖 shell 别名,
|
|
10
|
+
// 只用 Node 内置能力 + 系统 tar(Win10 1803+ 自带的 bsdtar 命名为 tar.exe)。
|
|
11
|
+
//
|
|
12
|
+
// 边界与克制:
|
|
13
|
+
// · 只装本插件自己的 npm 包,不接受任意包名/任意 URL(避免变成通用下载执行器);
|
|
14
|
+
// · 校验 shasum 不通过一律中止,绝不落盘;
|
|
15
|
+
// · 覆盖前先整目录备份,失败可回滚(返回 backup 路径);
|
|
16
|
+
// · 不做「静默后台更新」,只由面板弹窗里的明确点击触发。
|
|
17
|
+
|
|
18
|
+
import { createHash } from 'node:crypto';
|
|
19
|
+
import { execFile as nodeExecFile } from 'node:child_process';
|
|
20
|
+
import fs from 'node:fs';
|
|
21
|
+
import os from 'node:os';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
import { promisify } from 'node:util';
|
|
24
|
+
import { fileURLToPath } from 'node:url';
|
|
25
|
+
|
|
26
|
+
const execFileAsync = promisify(nodeExecFile);
|
|
27
|
+
|
|
28
|
+
export const PLUGIN_NAME = 'dsh-mobile-ios';
|
|
29
|
+
|
|
30
|
+
/** 官方源优先,镜像作备用(国内网络下官方源偶发超时)。 */
|
|
31
|
+
export const PLUGIN_REGISTRIES = [
|
|
32
|
+
'https://registry.npmjs.org',
|
|
33
|
+
'https://registry.npmmirror.com',
|
|
34
|
+
];
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 本模块所在包根目录(`<...>/node_modules/dsh-mobile-ios`)。
|
|
38
|
+
* `src/plugin-update.mjs` 的上一级目录就是包根。
|
|
39
|
+
*/
|
|
40
|
+
export function pluginRootFrom(url = import.meta.url) {
|
|
41
|
+
return path.dirname(path.dirname(fileURLToPath(url)));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function readVersion(root) {
|
|
45
|
+
try {
|
|
46
|
+
return JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).version || null;
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function sha1(buf) {
|
|
53
|
+
return createHash('sha1').update(buf).digest('hex');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 取 registry 元数据:目标版本(缺省 latest)的 tarball 地址与 shasum。 */
|
|
57
|
+
async function loadMetadata(registry, { name = PLUGIN_NAME, target = null, fetchImpl }) {
|
|
58
|
+
const res = await fetchImpl(`${registry}/${name}`, {
|
|
59
|
+
headers: { accept: 'application/vnd.npm.install-v1+json, application/json' },
|
|
60
|
+
});
|
|
61
|
+
if (!res.ok) throw new Error(`registry ${registry} 返回 ${res.status}`);
|
|
62
|
+
const body = await res.json();
|
|
63
|
+
const version = target || body?.['dist-tags']?.latest;
|
|
64
|
+
if (!version) throw new Error('registry 元数据里没有可安装版本');
|
|
65
|
+
const entry = body?.versions?.[version];
|
|
66
|
+
if (!entry?.dist?.tarball) throw new Error(`registry 缺少 ${version} 的 tarball 信息`);
|
|
67
|
+
return { version, tarball: entry.dist.tarball, shasum: entry.dist.shasum || null };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 下载并安装指定版本到 `pluginRoot`。
|
|
72
|
+
*
|
|
73
|
+
* @param {object} opts
|
|
74
|
+
* @param {string|null} opts.target 目标版本;null = 跟随 registry latest
|
|
75
|
+
* @param {string|null} opts.registry 指定源;null = 官方源优先、镜像备用
|
|
76
|
+
* @param {string} opts.pluginRoot 安装目录(默认本包根)
|
|
77
|
+
* @param {Function} opts.fetchImpl 可注入(测试不联网)
|
|
78
|
+
* @param {Function} opts.execImpl 可注入(测试不解包)
|
|
79
|
+
* @returns {Promise<{ok:boolean, from:string|null, to:string, changed:boolean, root:string, backup:string|null, restartRequired:boolean}>}
|
|
80
|
+
*/
|
|
81
|
+
export async function selfUpdatePlugin({
|
|
82
|
+
target = null,
|
|
83
|
+
registry = null,
|
|
84
|
+
pluginRoot = pluginRootFrom(),
|
|
85
|
+
fetchImpl = globalThis.fetch,
|
|
86
|
+
execImpl = execFileAsync,
|
|
87
|
+
log = () => {},
|
|
88
|
+
} = {}) {
|
|
89
|
+
const registries = registry ? [registry] : PLUGIN_REGISTRIES;
|
|
90
|
+
let meta = null;
|
|
91
|
+
let lastError = null;
|
|
92
|
+
for (const reg of registries) {
|
|
93
|
+
try {
|
|
94
|
+
meta = await loadMetadata(reg, { target, fetchImpl });
|
|
95
|
+
break;
|
|
96
|
+
} catch (err) {
|
|
97
|
+
lastError = err;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (!meta) throw new Error(`无法获取版本信息:${lastError?.message || '未知错误'}`);
|
|
101
|
+
|
|
102
|
+
const from = readVersion(pluginRoot);
|
|
103
|
+
if (from === meta.version) {
|
|
104
|
+
log(`plugin 已是 ${from},无需更新`);
|
|
105
|
+
return { ok: true, from, to: meta.version, changed: false, root: pluginRoot, backup: null, restartRequired: false };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-plugin-update-'));
|
|
109
|
+
const tgz = path.join(tmpRoot, 'pkg.tgz');
|
|
110
|
+
const outDir = path.join(tmpRoot, 'unpacked');
|
|
111
|
+
try {
|
|
112
|
+
log(`plugin 下载 ${meta.tarball}`);
|
|
113
|
+
const res = await fetchImpl(meta.tarball);
|
|
114
|
+
if (!res.ok) throw new Error(`下载 tarball 失败:HTTP ${res.status}`);
|
|
115
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
116
|
+
if (buf.length < 1024) throw new Error(`下载内容异常(${buf.length} 字节)`);
|
|
117
|
+
if (meta.shasum) {
|
|
118
|
+
const actual = sha1(buf);
|
|
119
|
+
if (actual !== String(meta.shasum).toLowerCase()) {
|
|
120
|
+
throw new Error(`完整性校验失败(期望 ${meta.shasum},实际 ${actual})`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
fs.writeFileSync(tgz, buf);
|
|
124
|
+
|
|
125
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
126
|
+
await execImpl('tar', ['-xzf', tgz, '-C', outDir], { timeout: 120_000 });
|
|
127
|
+
|
|
128
|
+
const unpacked = path.join(outDir, 'package');
|
|
129
|
+
if (!fs.existsSync(path.join(unpacked, 'package.json'))) throw new Error('解包后缺少 package.json');
|
|
130
|
+
const got = readVersion(unpacked);
|
|
131
|
+
if (got !== meta.version) throw new Error(`解包版本不符(期望 ${meta.version},实际 ${got})`);
|
|
132
|
+
|
|
133
|
+
// 备份:整目录复制到同级,命名为 .<name>.backup-<from>-<ts>
|
|
134
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
135
|
+
const backup = path.join(path.dirname(pluginRoot), `.${path.basename(pluginRoot)}.backup-${from || 'unknown'}-${stamp}`);
|
|
136
|
+
fs.cpSync(pluginRoot, backup, { recursive: true, force: true });
|
|
137
|
+
log(`plugin 已备份到 ${backup}`);
|
|
138
|
+
|
|
139
|
+
fs.cpSync(unpacked, pluginRoot, { recursive: true, force: true });
|
|
140
|
+
const now = readVersion(pluginRoot);
|
|
141
|
+
if (now !== meta.version) throw new Error(`覆盖后版本仍为 ${now},更新未生效`);
|
|
142
|
+
|
|
143
|
+
log(`plugin 已更新 ${from || '?'} → ${meta.version}`);
|
|
144
|
+
return { ok: true, from, to: meta.version, changed: true, root: pluginRoot, backup, restartRequired: true };
|
|
145
|
+
} finally {
|
|
146
|
+
try { fs.rmSync(tmpRoot, { recursive: true, force: true }); } catch { /* 临时目录清理失败不影响结果 */ }
|
|
147
|
+
}
|
|
148
|
+
}
|