dsh-plugin-mesh 0.5.5 → 0.5.7

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,380 @@
1
+ /**
2
+ * 本机到对端的 SSH 终端会话管理(含密钥自动登录)。
3
+ *
4
+ * 认证策略:
5
+ * 1. 本机有私钥 → 先用密钥登录;
6
+ * 2. 密钥不可用且给了密码 → 用密码登录,**成功后顺手把公钥部署过去**,
7
+ * 并用"只有私钥"的新连接自测一次;通过后以后不用再输密码。
8
+ *
9
+ * 安全边界:私钥与(可选的)密码只存本机 profile 的 mesh 状态目录,0600;
10
+ * 部署公钥只是往对端 ~/.ssh/authorized_keys 追加一行(幂等),不需要 sudo,
11
+ * 也不改 sshd_config。
12
+ */
13
+ import { createRequire } from "node:module";
14
+ import { randomUUID, generateKeyPairSync } from "node:crypto";
15
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
16
+ import { dirname, join } from "node:path";
17
+
18
+ /** 每个会话在内存里保留的最近输出上限。 */
19
+ const RING_LIMIT = 200 * 1024;
20
+
21
+ /**
22
+ * ssh2 必须**懒加载**,不能在模块顶层静态 import。
23
+ *
24
+ * 为什么:CI 里跑 `npm test` 的机器不装依赖(这个项目原来零运行时依赖,测试
25
+ * 也不需要 node_modules);静态 import 会让 `lib/index.js` 一被加载就
26
+ * ERR_MODULE_NOT_FOUND,连不碰 SSH 的整套自测都红(实测 2026-10-29,ci 三条
27
+ * job 全红)。改成用 createRequire 在真正要连 SSH 时再取,缺依赖就给出
28
+ * 一句能动手的话,而不是把插件拖垮。
29
+ */
30
+ let ssh2Module;
31
+ function loadSsh2() {
32
+ if (ssh2Module) return ssh2Module;
33
+ try {
34
+ const req = createRequire(import.meta.url);
35
+ const mod = req("ssh2");
36
+ ssh2Module = mod?.Client ? mod : mod?.default?.Client ? mod.default : mod;
37
+ if (!ssh2Module?.Client) throw new Error("模块里没有 Client");
38
+ return ssh2Module;
39
+ } catch (err) {
40
+ throw new Error(
41
+ `SSH 依赖 ssh2 不可用(插件安装不完整):${err?.message ?? err}。` +
42
+ "重装插件(会自动装依赖),或在插件目录执行 npm i ssh2。",
43
+ );
44
+ }
45
+ }
46
+
47
+ /** SSH 的 mpint 编码:4 字节长度 + 大端字节(最高位为 1 时补 0x00)。 */
48
+ function mpint(bytes) {
49
+ let body = Buffer.from(bytes);
50
+ while (body.length > 1 && body[0] === 0) body = body.subarray(1);
51
+ if (body[0] & 0x80) body = Buffer.concat([Buffer.from([0]), body]);
52
+ const len = Buffer.alloc(4);
53
+ len.writeUInt32BE(body.length);
54
+ return Buffer.concat([len, body]);
55
+ }
56
+
57
+ /** 生成 OpenSSH 单行公钥(RSA)。 */
58
+ function publicKeyLine(keyObject) {
59
+ const jwk = keyObject.export({ format: "jwk" });
60
+ const e = Buffer.from(jwk.e, "base64url");
61
+ const n = Buffer.from(jwk.n, "base64url");
62
+ const type = Buffer.from("ssh-rsa");
63
+ const len = Buffer.alloc(4);
64
+ len.writeUInt32BE(type.length);
65
+ return `ssh-rsa ${Buffer.concat([len, type, mpint(e), mpint(n)]).toString("base64")} dsh-mesh`;
66
+ }
67
+
68
+ /**
69
+ * 造一个 SSH 会话管理器。
70
+ * @param options - stateDir(存私钥)、credentialsPath(存用户名/是否已部署)、log、warn
71
+ */
72
+ export function createSshManager({ stateDir, credentialsPath, log = () => {}, warn = () => {} }) {
73
+ const sessions = new Map();
74
+ const keyPath = join(stateDir, "ssh-key", "id_rsa");
75
+ let cache;
76
+
77
+ const loadCredentials = () => {
78
+ if (cache !== undefined) return cache;
79
+ try {
80
+ const raw = JSON.parse(readFileSync(credentialsPath, "utf8"));
81
+ cache = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
82
+ } catch {
83
+ cache = {};
84
+ }
85
+ return cache;
86
+ };
87
+ const saveCredentials = () => {
88
+ try {
89
+ mkdirSync(dirname(credentialsPath), { recursive: true });
90
+ writeFileSync(credentialsPath, JSON.stringify(loadCredentials(), null, 2), { mode: 0o600 });
91
+ } catch (error) {
92
+ warn(`保存 SSH 凭据失败:${error?.message ?? error}`);
93
+ }
94
+ };
95
+ const remember = (machine, patch) => {
96
+ if (!machine) return;
97
+ loadCredentials()[machine] = { ...(loadCredentials()[machine] ?? {}), ...patch };
98
+ saveCredentials();
99
+ };
100
+ const known = (machine) => loadCredentials()[machine] ?? undefined;
101
+
102
+ /** 读(必要时生成)本机密钥对。 */
103
+ const ensureKey = () => {
104
+ try {
105
+ if (existsSync(keyPath)) return { pem: readFileSync(keyPath, "utf8"), path: keyPath };
106
+ // 用 RSA 而不是 ed25519:ssh2 只认 OpenSSH 格式的 ed25519 私钥,
107
+ // 而 Node 导不出那个格式;PKCS#1 的 RSA PEM 两边都认。
108
+ const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 3072 });
109
+ mkdirSync(dirname(keyPath), { recursive: true });
110
+ writeFileSync(keyPath, privateKey.export({ type: "pkcs1", format: "pem" }), { mode: 0o600 });
111
+ writeFileSync(`${keyPath}.pub`, `${publicKeyLine(publicKey)}\n`, { mode: 0o644 });
112
+ log(`已生成 SSH 密钥:${keyPath}`);
113
+ return { pem: readFileSync(keyPath, "utf8"), path: keyPath };
114
+ } catch (error) {
115
+ warn(`读/生成 SSH 密钥失败:${error?.message ?? error}`);
116
+ return undefined;
117
+ }
118
+ };
119
+ const publicLine = () => {
120
+ try {
121
+ return readFileSync(`${keyPath}.pub`, "utf8").trim();
122
+ } catch {
123
+ return "";
124
+ }
125
+ };
126
+
127
+ /** 在已建立的连接上执行一条命令,收集输出。 */
128
+ const exec = (client, command) =>
129
+ new Promise((resolve) => {
130
+ client.exec(command, (error, stream) => {
131
+ if (error) {
132
+ resolve({ ok: false, output: error.message });
133
+ return;
134
+ }
135
+ let output = "";
136
+ stream.on("data", (chunk) => (output += chunk.toString()));
137
+ stream.stderr.on("data", (chunk) => (output += chunk.toString()));
138
+ stream.on("close", (code) => resolve({ ok: code === 0 || code === undefined, output: output.trim() }));
139
+ });
140
+ });
141
+
142
+ /** 用"只有私钥"的新连接自测一次,确认免密可用。 */
143
+ const verifyKeyLogin = ({ host, port, username, pem }) =>
144
+ new Promise((resolve) => {
145
+ const probe = new (loadSsh2().Client)();
146
+ let settled = false;
147
+ const done = (ok) => {
148
+ if (settled) return;
149
+ settled = true;
150
+ try {
151
+ probe.end();
152
+ } catch {
153
+ /* 已断 */
154
+ }
155
+ resolve(ok);
156
+ };
157
+ probe.on("ready", () => done(true));
158
+ probe.on("error", () => done(false));
159
+ try {
160
+ probe.connect({ host, port, username, privateKey: pem, readyTimeout: 12000 });
161
+ } catch {
162
+ done(false);
163
+ }
164
+ });
165
+
166
+ /** 把公钥追加到对端(幂等),然后自测。 */
167
+ const deployKey = async (client, { host, port, username, machine }) => {
168
+ const pub = publicLine();
169
+ if (!pub) return false;
170
+ const quoted = pub.replace(/'/g, "'\\''");
171
+ const command =
172
+ "mkdir -p ~/.ssh && chmod 700 ~/.ssh && " +
173
+ "touch ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys && " +
174
+ `grep -qF '${quoted}' ~/.ssh/authorized_keys || echo '${quoted}' >> ~/.ssh/authorized_keys`;
175
+ const result = await exec(client, command);
176
+ if (!result.ok) {
177
+ warn(`部署公钥失败:${result.output.slice(0, 200)}`);
178
+ return false;
179
+ }
180
+ const ok = await verifyKeyLogin({ host, port, username, pem: ensureKey()?.pem ?? "" });
181
+ if (!ok) {
182
+ warn(`公钥已写入,但密钥登录自测没通过(${username}@${host})`);
183
+ return false;
184
+ }
185
+ remember(machine, { username, hasKey: true });
186
+ log(`已为 ${machine || host} 部署公钥,之后免密登录`);
187
+ return true;
188
+ };
189
+
190
+ /** 建立一个会话(给定连接参数)。 */
191
+ const startSession = ({ host, port, username, password, privateKey, cols, rows, machine }) =>
192
+ new Promise((resolve, reject) => {
193
+ const id = randomUUID();
194
+ const client = new (loadSsh2().Client)();
195
+ const session = { id, client, stream: undefined, ring: "", listeners: new Set(), machine: machine ?? "", closed: false };
196
+ let settled = false;
197
+ const finish = (error) => {
198
+ if (settled) return;
199
+ settled = true;
200
+ error ? reject(error) : resolve({ session, client });
201
+ };
202
+ const fail = (error) => {
203
+ session.closed = true;
204
+ sessions.delete(id);
205
+ try {
206
+ client.end();
207
+ } catch {
208
+ /* 已断 */
209
+ }
210
+ finish(error instanceof Error ? error : new Error(String(error)));
211
+ };
212
+
213
+ client.on("ready", () => {
214
+ client.shell({ term: "xterm-256color", cols, rows }, (error, stream) => {
215
+ if (error) {
216
+ fail(new Error(`开 shell 失败:${error.message}`));
217
+ return;
218
+ }
219
+ session.stream = stream;
220
+ stream.on("data", (chunk) => {
221
+ const text = chunk.toString("utf8");
222
+ session.ring = (session.ring + text).slice(-RING_LIMIT);
223
+ for (const listener of session.listeners) {
224
+ try {
225
+ listener(text);
226
+ } catch {
227
+ /* 单个订阅者失败不影响其它 */
228
+ }
229
+ }
230
+ });
231
+ stream.on("close", () => {
232
+ session.closed = true;
233
+ sessions.delete(id);
234
+ for (const listener of session.listeners) {
235
+ try {
236
+ listener(null);
237
+ } catch {
238
+ /* 同上 */
239
+ }
240
+ }
241
+ });
242
+ sessions.set(id, session);
243
+ finish();
244
+ });
245
+ });
246
+ client.on("error", (error) => fail(new Error(error.message)));
247
+ client.on("close", () => {
248
+ if (session.closed) return;
249
+ session.closed = true;
250
+ sessions.delete(id);
251
+ for (const listener of session.listeners) {
252
+ try {
253
+ listener(null);
254
+ } catch {
255
+ /* 同上 */
256
+ }
257
+ }
258
+ });
259
+
260
+ const options = {
261
+ host,
262
+ port,
263
+ username,
264
+ readyTimeout: 15000,
265
+ keepaliveInterval: 15000,
266
+ // 不做 known_hosts:对端是自己的机器,这是明确取舍(写在这里而不是假装做到)
267
+ };
268
+ if (privateKey) options.privateKey = privateKey;
269
+ else options.password = password;
270
+
271
+ try {
272
+ client.connect(options);
273
+ } catch (error) {
274
+ fail(error);
275
+ }
276
+ });
277
+
278
+ /**
279
+ * 开一个交互式 shell:先试密钥,再试密码;密码首登成功后自动部署公钥。
280
+ * @returns {Promise<string>} 会话 id
281
+ */
282
+ const open = async ({ host, port = 22, username, password = "", cols = 80, rows = 24, machine = "" }) => {
283
+ const key = ensureKey();
284
+ const saved = known(machine) ?? {};
285
+ // 密钥只对"当初部署它的那个用户名"有意义:换了用户名先试密钥只会换来一次
286
+ // 认证失败,还多等一轮。所以用户名不一致时直接走密码。
287
+ const keyApplies = !!key?.pem && (!saved.username || saved.username === username);
288
+ const attempts = [];
289
+ if (keyApplies) attempts.push("key");
290
+ if (password) attempts.push("password");
291
+ if (attempts.length === 0) throw new Error("没有可用凭据:请输入密码,或先部署密钥");
292
+
293
+ let lastError;
294
+ for (const mode of attempts) {
295
+ try {
296
+ const { session, client } = await startSession({
297
+ host,
298
+ port,
299
+ username,
300
+ cols,
301
+ rows,
302
+ machine,
303
+ password,
304
+ ...(mode === "key" ? { privateKey: key.pem } : {}),
305
+ });
306
+ log(`SSH 已连接 ${username}@${host}:${port}(${session.id.slice(0, 8)},${mode === "key" ? "密钥" : "密码"})`);
307
+ if (mode === "password" && key?.pem && known(machine)?.hasKey !== true) {
308
+ // 不阻塞会话:后台部署公钥 + 自测
309
+ void deployKey(client, { host, port, username, machine });
310
+ }
311
+ return session.id;
312
+ } catch (error) {
313
+ lastError = error;
314
+ warn(`SSH ${mode === "key" ? "密钥" : "密码"}登录失败 ${username}@${host}: ${error.message}`);
315
+ }
316
+ }
317
+ throw lastError ?? new Error("连接失败");
318
+ };
319
+
320
+ const subscribe = (id, listener) => {
321
+ const session = sessions.get(id);
322
+ if (!session) return () => {};
323
+ session.listeners.add(listener);
324
+ return () => session.listeners.delete(listener);
325
+ };
326
+
327
+ const write = (id, data) => {
328
+ const session = sessions.get(id);
329
+ if (!session?.stream) return false;
330
+ try {
331
+ session.stream.write(data);
332
+ return true;
333
+ } catch {
334
+ return false;
335
+ }
336
+ };
337
+
338
+ const resize = (id, cols, rows) => {
339
+ const session = sessions.get(id);
340
+ if (!session?.stream) return false;
341
+ try {
342
+ session.stream.setWindow(rows, cols, 0, 0);
343
+ return true;
344
+ } catch {
345
+ return false;
346
+ }
347
+ };
348
+
349
+ const close = (id) => {
350
+ const session = sessions.get(id);
351
+ if (!session) return;
352
+ sessions.delete(id);
353
+ session.closed = true;
354
+ try {
355
+ session.stream?.end();
356
+ } catch {
357
+ /* 已断 */
358
+ }
359
+ try {
360
+ session.client.end();
361
+ } catch {
362
+ /* 已断 */
363
+ }
364
+ };
365
+
366
+ const closeAll = () => {
367
+ for (const id of [...sessions.keys()]) close(id);
368
+ };
369
+
370
+ const list = () => [...sessions.values()].map((s) => ({ id: s.id, machine: s.machine, alive: !!s.stream, buffered: s.ring.length }));
371
+ const ring = (id) => sessions.get(id)?.ring ?? "";
372
+
373
+ /** 供面板使用:已知用户名 + 是否已部署密钥。 */
374
+ const describe = (machine) => {
375
+ const saved = known(machine) ?? {};
376
+ return { username: saved.username ?? "", hasKey: saved.hasKey === true, keyPath };
377
+ };
378
+
379
+ return { open, subscribe, write, resize, close, closeAll, list, ring, describe, remember };
380
+ }
package/lib/update.js ADDED
@@ -0,0 +1,232 @@
1
+ /**
2
+ * 「检查更新」:版本比较 + 向 npm registry 问一次最新版本。
3
+ *
4
+ * 为什么放在主机侧、而不是让浏览器直接 fetch registry:
5
+ * · 渲染层在 DSH Desktop 里有 CSP / 请求门禁,外网请求不一定发得出去;
6
+ * · 主机侧可以**带超时、带镜像回退、带缓存**,一次失败不会让整页变慢;
7
+ * · 失败必须能和「已是最新」区分开 —— 这是本项目最贵的一条教训
8
+ * (见 AGENTS.md 硬约束 1:探测失败不能被说成否定事实)。
9
+ *
10
+ * 所以这里只有两类结果:
11
+ * { ok: true, latest: "0.6.0", ... } —— 真的问到了
12
+ * { ok: false, error: "…超时…", failures: [...] } —— 没问到,原因逐条列出
13
+ * 绝不存在「问不到 → 当作没有更新」这种降级。
14
+ *
15
+ * 本文件是纯函数 + 一个可注入 fetch 的查询,便于无网络单测。
16
+ */
17
+ import { fileURLToPath } from "node:url";
18
+
19
+ export const RELEASE_REPO = "peng456/dsh-plugin-mesh";
20
+ export const NPM_PACKAGE = "dsh-plugin-mesh";
21
+
22
+ /**
23
+ * 版本源:官方 registry 优先,国内镜像兜底(作者的机器上官方源时常很慢)。
24
+ * 不按「谁快」做并发竞速:先问到的那个就够了,而且同时打两个源没有必要。
25
+ */
26
+ export const DEFAULT_REGISTRIES = [
27
+ `https://registry.npmjs.org/${NPM_PACKAGE}/latest`,
28
+ `https://registry.npmmirror.com/${NPM_PACKAGE}/latest`,
29
+ ];
30
+
31
+ /** 从 `import.meta.url` 推出插件安装目录(带结尾斜杠,可直接放进 tar -C)。 */
32
+ export function pluginDirFromUrl(metaUrl) {
33
+ try {
34
+ return fileURLToPath(new URL("../", metaUrl));
35
+ } catch {
36
+ return "";
37
+ }
38
+ }
39
+
40
+ /**
41
+ * 解析语义化版本;不是 `x.y.z[-pre][+build]` 就返回 null。
42
+ * 返回 null 意味着「无法比较」,调用方必须把它和「相等」区分开。
43
+ */
44
+ export function parseVersion(raw) {
45
+ const m = /^[vV]?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(String(raw ?? "").trim());
46
+ if (!m) return null;
47
+ return {
48
+ major: Number(m[1]),
49
+ minor: Number(m[2]),
50
+ patch: Number(m[3]),
51
+ pre: m[4] ? m[4].split(".").filter(Boolean) : [],
52
+ };
53
+ }
54
+
55
+ /** semver 的预发布段比较:1.0.0-beta < 1.0.0;数字段按数值、字母段按字典序。 */
56
+ function comparePrerelease(a, b) {
57
+ if (a.length === 0 && b.length === 0) return 0;
58
+ // 有预发布段的版本**小于**同号正式版
59
+ if (a.length === 0) return 1;
60
+ if (b.length === 0) return -1;
61
+ const len = Math.max(a.length, b.length);
62
+ for (let i = 0; i < len; i += 1) {
63
+ const x = a[i];
64
+ const y = b[i];
65
+ if (x === undefined) return -1;
66
+ if (y === undefined) return 1;
67
+ const nx = /^\d+$/.test(x);
68
+ const ny = /^\d+$/.test(y);
69
+ if (nx && ny) {
70
+ const d = Number(x) - Number(y);
71
+ if (d !== 0) return d < 0 ? -1 : 1;
72
+ continue;
73
+ }
74
+ if (nx !== ny) return nx ? -1 : 1;
75
+ if (x !== y) return x < y ? -1 : 1;
76
+ }
77
+ return 0;
78
+ }
79
+
80
+ /**
81
+ * 比较两个版本:a > b → 1,a < b → -1,相等 → 0。
82
+ * 任一版本无法解析时返回 **null**(不是 0)—— 让调用方去说"无法比较"。
83
+ */
84
+ export function compareVersions(a, b) {
85
+ const pa = parseVersion(a);
86
+ const pb = parseVersion(b);
87
+ if (!pa || !pb) return null;
88
+ for (const key of ["major", "minor", "patch"]) {
89
+ if (pa[key] !== pb[key]) return pa[key] < pb[key] ? -1 : 1;
90
+ }
91
+ return comparePrerelease(pa.pre, pb.pre);
92
+ }
93
+
94
+ /** 更新的"量级":用于界面上说人话(大版本 / 小版本 / 修订 / 预发布)。 */
95
+ export function updateKind(current, latest) {
96
+ const c = parseVersion(current);
97
+ const l = parseVersion(latest);
98
+ if (!c || !l) return "unknown";
99
+ if (compareVersions(latest, current) !== 1) return "none";
100
+ if (l.major !== c.major) return "major";
101
+ if (l.minor !== c.minor) return "minor";
102
+ if (l.patch !== c.patch) return "patch";
103
+ return "prerelease";
104
+ }
105
+
106
+ function hostOf(url) {
107
+ try {
108
+ return new URL(url).host;
109
+ } catch {
110
+ return String(url || "版本源");
111
+ }
112
+ }
113
+
114
+ /**
115
+ * 问一次最新版本。逐源尝试,**每条失败原因都保留**(超时 / HTTP 错误 / 响应
116
+ * 里没有 version),最终失败时一起返回,界面才有话可说。
117
+ *
118
+ * @returns {Promise<{ok: true, version: string, registry: string}
119
+ * | {ok: false, error: string, failures: string[]}>}
120
+ */
121
+ export async function fetchLatestVersion({
122
+ fetchImpl = globalThis.fetch,
123
+ timeoutMs = 5000,
124
+ registries = DEFAULT_REGISTRIES,
125
+ } = {}) {
126
+ if (typeof fetchImpl !== "function") {
127
+ return { ok: false, error: "当前运行环境没有 fetch,无法检查更新", failures: [] };
128
+ }
129
+ const failures = [];
130
+ for (const url of registries) {
131
+ try {
132
+ const signal =
133
+ typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function"
134
+ ? AbortSignal.timeout(timeoutMs)
135
+ : undefined;
136
+ const res = await fetchImpl(url, { signal, headers: { accept: "application/json" } });
137
+ if (!res || res.ok !== true) {
138
+ failures.push(`${hostOf(url)} HTTP ${res ? res.status : "无响应"}`);
139
+ continue;
140
+ }
141
+ const doc = await res.json();
142
+ const version = String(doc?.version ?? "").trim();
143
+ if (!version) {
144
+ failures.push(`${hostOf(url)} 响应里没有 version`);
145
+ continue;
146
+ }
147
+ if (!parseVersion(version)) {
148
+ failures.push(`${hostOf(url)} 返回了无法比较的版本号 ${version}`);
149
+ continue;
150
+ }
151
+ return { ok: true, version, registry: url };
152
+ } catch (err) {
153
+ const timedOut = err?.name === "TimeoutError" || err?.name === "AbortError";
154
+ failures.push(`${hostOf(url)} ${timedOut ? `超时(${timeoutMs}ms)` : String(err?.message ?? err)}`);
155
+ }
156
+ }
157
+ return {
158
+ ok: false,
159
+ failures,
160
+ error: failures.length ? `检查更新失败:${failures.join(";")}` : "没有可用的版本源",
161
+ };
162
+ }
163
+
164
+ /**
165
+ * 升级命令(与 scripts/release-plugin.sh 打出来的那条一致:release 资产是
166
+ * 不带顶层目录的源码包,所以可以直接 tar xz -C 插件目录覆盖)。
167
+ *
168
+ * 这里只给「下载并覆盖」这一条;重启、回滚与可加载校验写在 README 的升级小节,
169
+ * 界面不要假装一键升级 —— 覆盖完不重启等于没升级(VERSION 是启动时常量)。
170
+ */
171
+ export function buildUpgradeCommand({ version, pluginDir } = {}) {
172
+ const v = String(version ?? "").trim();
173
+ if (!v) return "";
174
+ const dir = String(pluginDir ?? "").trim() || "<插件目录>";
175
+ const asset = `${NPM_PACKAGE}-${v}.tar.gz`;
176
+ const url = `https://ghfast.top/https://github.com/${RELEASE_REPO}/releases/download/plugin-v${v}/${asset}`;
177
+ return `curl -L ${url} | tar xz -C "${dir}"`;
178
+ }
179
+
180
+ /**
181
+ * 组装返回给界面的报告。**不抛异常、不联网**,所有字段显式传入便于测试。
182
+ *
183
+ * `latest.ok !== true` 时返回 ok:false 并把原因带出去;界面据此显示"检查失败",
184
+ * 而不是"已是最新"。
185
+ */
186
+ export function buildUpdateReport({
187
+ current = "",
188
+ diskVersion = "",
189
+ latest = null,
190
+ pluginDir = "",
191
+ now = Date.now(),
192
+ } = {}) {
193
+ const currentVersion = String(current ?? "").trim();
194
+ const onDisk = String(diskVersion ?? "").trim();
195
+ const report = {
196
+ current: currentVersion,
197
+ diskVersion: onDisk,
198
+ /** 磁盘上已经不是进程正在跑的版本 = 升级了没重启(界面要明说) */
199
+ versionDrift: !!onDisk && onDisk !== currentVersion,
200
+ pluginDir: String(pluginDir ?? ""),
201
+ checkedAt: new Date(now).toISOString(),
202
+ releaseUrl: `https://github.com/${RELEASE_REPO}/releases`,
203
+ npmUrl: `https://www.npmjs.com/package/${NPM_PACKAGE}`,
204
+ };
205
+
206
+ if (!latest || latest.ok !== true) {
207
+ return {
208
+ ok: false,
209
+ ...report,
210
+ error: String(latest?.error || "没有可用的版本源"),
211
+ failures: Array.isArray(latest?.failures) ? latest.failures : [],
212
+ };
213
+ }
214
+
215
+ const latestVersion = String(latest.version);
216
+ const cmp = compareVersions(latestVersion, currentVersion);
217
+ const comparable = cmp !== null;
218
+ return {
219
+ ok: true,
220
+ ...report,
221
+ latest: latestVersion,
222
+ registry: String(latest.registry || ""),
223
+ /** false = 版本号无法比较(界面必须说"无法比较",不能说"已是最新") */
224
+ comparable,
225
+ /** 只有明确比较出「更新」才是 true */
226
+ hasUpdate: comparable ? cmp === 1 : false,
227
+ kind: comparable ? updateKind(currentVersion, latestVersion) : "unknown",
228
+ releaseUrl: `https://github.com/${RELEASE_REPO}/releases/tag/plugin-v${latestVersion}`,
229
+ npmUrl: `https://www.npmjs.com/package/${NPM_PACKAGE}/v/${latestVersion}`,
230
+ upgradeCommand: buildUpgradeCommand({ version: latestVersion, pluginDir }),
231
+ };
232
+ }