dsh-plugin-mesh 0.5.2 → 0.5.4

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/osinfo.js ADDED
@@ -0,0 +1,352 @@
1
+ /**
2
+ * 设备系统身份(osInfo / systems):平台、展示名、版本、发行版、内核、桌面环境、架构。
3
+ *
4
+ * 三层数据:
5
+ * · osInfo —— 宿主机(老 UI / 老对端只认这一份)
6
+ * · systems[] —— 这台机器上可用的系统列表:宿主机 + WSL 发行版(Windows)
7
+ * · capabilities —— 运行时环境(node/python/...),仍走原来的能力名片
8
+ *
9
+ * 为什么单独一个模块:
10
+ * · 探测有平台分支(sw_vers / /etc/os-release / 注册表 / getprop),散在 discovery 里很难测;
11
+ * · 结果在进程生命周期内不变,探测一次即可 —— 心跳每 5s 一次,不能每条都跑子进程;
12
+ * · 对端名片是网络输入,接收侧必须清洗(sanitizeOsInfo / sanitizeSystems)。
13
+ *
14
+ * WSL 只读注册表,不启动已停止的发行版:要的是"这台机器上有哪些系统",不是把它们
15
+ * 一个个拉起来(那会有几十秒副作用)。运行中的发行版才尝试读 /etc/os-release 补版本。
16
+ */
17
+ import os from "node:os";
18
+ import { execFileSync } from "node:child_process";
19
+ import { readFileSync } from "node:fs";
20
+
21
+ const FIELD_MAX = {
22
+ name: 48,
23
+ version: 48,
24
+ distro: 32,
25
+ kernel: 64,
26
+ desktop: 32,
27
+ arch: 16,
28
+ };
29
+
30
+ const PLATFORMS = new Set(["win32", "darwin", "linux", "android"]);
31
+ const KINDS = new Set(["host", "wsl", "vm", "container"]);
32
+ /** 一台机器的名片最多列几个系统(宿主机 + 3 个额外环境),避免名片无限膨胀。 */
33
+ const MAX_SYSTEMS = 4;
34
+ /** Docker/Rancher/Podman 的 WSL 发行版不是用户系统,不列。 */
35
+ const NON_USER_WSL = /^(docker-desktop|rancher-desktop|podman-machine)/i;
36
+ const WSL_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Lxss";
37
+
38
+ /** 去控制字符、折叠空白、按字段截断。 */
39
+ function clean(value, max) {
40
+ return String(value ?? "")
41
+ .replace(/[\u0000-\u001f\u007f]/g, "")
42
+ .replace(/\s+/g, " ")
43
+ .trim()
44
+ .slice(0, max);
45
+ }
46
+
47
+ /** 命令输出只取第一行(getprop / sw_vers 都可能带换行)。 */
48
+ function firstLine(value, max) {
49
+ return clean(String(value ?? "").split("\n")[0], max);
50
+ }
51
+
52
+ /** 解析 /etc/os-release;引号可有可无,值里允许 `=`。 */
53
+ function parseOsRelease(text) {
54
+ const out = {};
55
+ for (const line of String(text ?? "").split("\n")) {
56
+ const m = /^([A-Z_]+)=(.*)$/.exec(line.trim());
57
+ if (!m) continue;
58
+ let value = m[2].trim();
59
+ if (
60
+ (value.startsWith('"') && value.endsWith('"')) ||
61
+ (value.startsWith("'") && value.endsWith("'"))
62
+ ) {
63
+ value = value.slice(1, -1);
64
+ }
65
+ out[m[1]] = value;
66
+ }
67
+ return out;
68
+ }
69
+
70
+ /** XDG_CURRENT_DESKTOP 常是 "ubuntu:GNOME",取最后一段。 */
71
+ function desktopEnv(env) {
72
+ const raw = String(env?.XDG_CURRENT_DESKTOP || env?.DESKTOP_SESSION || "").trim();
73
+ if (!raw) return "";
74
+ const parts = raw.split(":").map((s) => s.trim()).filter(Boolean);
75
+ return parts[parts.length - 1] ?? "";
76
+ }
77
+
78
+ function defaultRun(cmd, args) {
79
+ return execFileSync(cmd, args, {
80
+ encoding: "utf8",
81
+ timeout: 2000,
82
+ windowsHide: true,
83
+ stdio: ["ignore", "pipe", "ignore"],
84
+ }).trim();
85
+ }
86
+
87
+ /**
88
+ * 探测宿主机系统身份。所有参数都可注入,方便在非目标平台上用 fixture 单测。
89
+ *
90
+ * 失败一律降级为空字段 / 平台通用名,**绝不抛**:名片的缺失不能拖垮启动,
91
+ * 也不能把"没探到"伪装成某个具体结论。
92
+ */
93
+ export function detectOsInfo(opts = {}) {
94
+ const platformRaw = String(opts.platform ?? process.platform).toLowerCase();
95
+ const platform = PLATFORMS.has(platformRaw) ? platformRaw : "";
96
+ const release = clean(opts.release ?? os.release(), FIELD_MAX.kernel);
97
+ const arch = clean(opts.arch ?? os.arch(), FIELD_MAX.arch);
98
+ const env = opts.env ?? process.env;
99
+ const osVersion =
100
+ opts.osVersion ??
101
+ (() => {
102
+ try {
103
+ return os.version();
104
+ } catch {
105
+ return "";
106
+ }
107
+ });
108
+ const readFile = opts.readFile ?? ((path) => readFileSync(path, "utf8"));
109
+ const run = opts.run ?? defaultRun;
110
+
111
+ let name = "";
112
+ let version = "";
113
+ let distro = "";
114
+ let desktop = "";
115
+
116
+ if (platformRaw === "win32") {
117
+ // Node 13+ 的 os.version() 已经是 "Windows 11 Home China" 这类产品名。
118
+ name = firstLine(osVersion(), FIELD_MAX.name) || "Windows";
119
+ version = release;
120
+ } else if (platformRaw === "darwin") {
121
+ try {
122
+ name = firstLine(run("sw_vers", ["-productName"]), FIELD_MAX.name);
123
+ } catch {
124
+ name = "";
125
+ }
126
+ try {
127
+ version = firstLine(run("sw_vers", ["-productVersion"]), FIELD_MAX.version);
128
+ } catch {
129
+ version = "";
130
+ }
131
+ name = name || "macOS";
132
+ } else if (platformRaw === "linux") {
133
+ try {
134
+ const rel = parseOsRelease(readFile("/etc/os-release"));
135
+ name = clean(rel.NAME || rel.PRETTY_NAME || rel.ID || "Linux", FIELD_MAX.name);
136
+ version = clean(rel.VERSION_ID || "", FIELD_MAX.version);
137
+ distro = clean(rel.ID || "", FIELD_MAX.distro);
138
+ } catch {
139
+ name = "Linux";
140
+ }
141
+ desktop = clean(desktopEnv(env), FIELD_MAX.desktop);
142
+ } else if (platformRaw === "android") {
143
+ name = "Android";
144
+ try {
145
+ version = firstLine(run("getprop", ["ro.build.version.release"]), FIELD_MAX.version);
146
+ } catch {
147
+ version = "";
148
+ }
149
+ } else {
150
+ // 未知平台(FreeBSD 等)至少给个可读名字;platform 留空让 UI 用回退徽章。
151
+ name = clean(platformRaw, FIELD_MAX.name);
152
+ version = release;
153
+ }
154
+
155
+ return sanitizeOsInfo({
156
+ platform,
157
+ name,
158
+ version,
159
+ distro,
160
+ kernel: release,
161
+ desktop,
162
+ arch,
163
+ });
164
+ }
165
+
166
+ /**
167
+ * 清洗对端名片里的单个系统。
168
+ *
169
+ * platform 走白名单(UI 的 logo 映射只认这四个);文本字段控制字符剥掉并截断。
170
+ * 返回 null 表示"对端没报 / 报的东西不可用",UI 应回退到老的 os 字符串。
171
+ */
172
+ export function sanitizeOsInfo(raw) {
173
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
174
+ const platform = PLATFORMS.has(String(raw.platform ?? "").toLowerCase())
175
+ ? String(raw.platform).toLowerCase()
176
+ : "";
177
+ const out = {
178
+ platform,
179
+ name: clean(raw.name, FIELD_MAX.name),
180
+ version: clean(raw.version, FIELD_MAX.version),
181
+ distro: clean(raw.distro, FIELD_MAX.distro),
182
+ kernel: clean(raw.kernel, FIELD_MAX.kernel),
183
+ desktop: clean(raw.desktop, FIELD_MAX.desktop),
184
+ arch: clean(raw.arch, FIELD_MAX.arch),
185
+ };
186
+ if (!out.platform && !out.name) return null;
187
+ return out;
188
+ }
189
+
190
+ /** 解析 `reg query ...\Lxss /s` 的输出,每个 `{guid}` 块一条记录。 */
191
+ function parseWslRegistry(text) {
192
+ const blocks = [];
193
+ let cur = null;
194
+ for (const raw of String(text ?? "").split(/\r?\n/)) {
195
+ const line = raw.trim();
196
+ if (!line) continue;
197
+ if (/^HKEY_/i.test(line)) {
198
+ if (cur) blocks.push(cur);
199
+ cur = {};
200
+ continue;
201
+ }
202
+ const m = /^(\w+)\s+REG_(?:SZ|DWORD|EXPAND_SZ)\s+(.+)$/i.exec(line);
203
+ if (m && cur) cur[m[1]] = m[2].trim();
204
+ }
205
+ if (cur) blocks.push(cur);
206
+ return blocks.filter((b) => b && b.DistributionName);
207
+ }
208
+
209
+ /**
210
+ * 运行中的 WSL 发行版,尝试从 9p 挂载读 /etc/os-release 补版本。
211
+ * 停着的发行版不碰(不启动它);读不到就只报注册表里的名字。
212
+ */
213
+ function readWslOsRelease(name, readFile) {
214
+ for (const root of ["\\\\wsl.localhost\\", "\\\\wsl$\\"]) {
215
+ try {
216
+ const rel = parseOsRelease(readFile(`${root}${name}\\etc\\os-release`));
217
+ if (rel.NAME || rel.ID) return rel;
218
+ } catch {
219
+ /* 没运行 / 9p 不可访问 */
220
+ }
221
+ }
222
+ return null;
223
+ }
224
+
225
+ /**
226
+ * 从注册表列 WSL 发行版(只读,不启动任何发行版)。
227
+ * 运行时探测也用它判断哪些发行版处于 running 状态。
228
+ */
229
+ export function wslTargets(opts = {}) {
230
+ const run = opts.run ?? defaultRun;
231
+ let text;
232
+ try {
233
+ text = run("reg", ["query", WSL_KEY, "/s"]);
234
+ } catch {
235
+ return [];
236
+ }
237
+
238
+ const out = [];
239
+ for (const block of parseWslRegistry(text)) {
240
+ const name = String(block.DistributionName ?? "").trim();
241
+ if (!name || NON_USER_WSL.test(name)) continue;
242
+ out.push({
243
+ name,
244
+ running: parseInt(String(block.State ?? ""), 0) === 1,
245
+ osVersion: String(block.OsVersion ?? "").trim(),
246
+ flavor: String(block.Flavor ?? "").trim().toLowerCase(),
247
+ });
248
+ if (out.length >= MAX_SYSTEMS - 1) break;
249
+ }
250
+ return out;
251
+ }
252
+
253
+ /** 把注册表目标变成 systems[] 里的条目(运行中的才补 os-release 版本)。 */
254
+ function detectWsl(opts = {}) {
255
+ const readFile = opts.readFile ?? ((path) => readFileSync(path, "utf8"));
256
+ const out = [];
257
+ for (const target of wslTargets(opts)) {
258
+ let name = target.name;
259
+ let version = target.osVersion;
260
+ let distro = target.flavor;
261
+
262
+ if ((!version || !distro) && target.running) {
263
+ const rel = readWslOsRelease(target.name, readFile);
264
+ if (rel) {
265
+ name = clean(rel.NAME || name, FIELD_MAX.name);
266
+ version = version || clean(rel.VERSION_ID || "", FIELD_MAX.version);
267
+ distro = distro || clean(rel.ID || "", FIELD_MAX.distro).toLowerCase();
268
+ }
269
+ }
270
+
271
+ out.push({
272
+ kind: "wsl",
273
+ platform: "linux",
274
+ name: clean(name, FIELD_MAX.name),
275
+ version: clean(version, FIELD_MAX.version),
276
+ distro: clean(distro, FIELD_MAX.distro),
277
+ // WSL 的 kernel/desktop/arch 不启动发行版拿不到,留空比瞎猜好。
278
+ kernel: "",
279
+ desktop: "",
280
+ arch: "",
281
+ });
282
+ }
283
+ return out;
284
+ }
285
+
286
+ /** 本机系统列表:宿主机第一,后面是 WSL 等额外环境。 */
287
+ export function detectSystems(opts = {}) {
288
+ const host = detectOsInfo(opts);
289
+ const platform = String(opts.platform ?? process.platform);
290
+ const extra = platform === "win32" ? detectWsl(opts) : [];
291
+ return sanitizeSystems([{ kind: "host", ...host }, ...extra]) ?? [];
292
+ }
293
+
294
+ /**
295
+ * 清洗对端名片里的 systems[]:逐项复用 sanitizeOsInfo,kind 走白名单,
296
+ * 去重、最多 MAX_SYSTEMS 项,宿主机排第一。
297
+ */
298
+ export function sanitizeSystems(raw) {
299
+ if (!Array.isArray(raw)) return null;
300
+ const out = [];
301
+ const seen = new Set();
302
+ for (const item of raw) {
303
+ const info = sanitizeOsInfo(item);
304
+ if (!info) continue;
305
+ const kindRaw = String(item?.kind ?? "").toLowerCase();
306
+ const kind = KINDS.has(kindRaw) ? kindRaw : "";
307
+ const key = `${kind}|${info.platform}|${info.name}|${info.version}`;
308
+ if (seen.has(key)) continue;
309
+ seen.add(key);
310
+ out.push({ kind, ...info });
311
+ if (out.length >= MAX_SYSTEMS * 2) break;
312
+ }
313
+ if (out.length === 0) return null;
314
+ // 宿主机排第一;其余保持到达顺序(stable sort)。
315
+ out.sort((a, b) => (a.kind === "host" ? 0 : 1) - (b.kind === "host" ? 0 : 1));
316
+ return out.slice(0, MAX_SYSTEMS);
317
+ }
318
+
319
+ let cached;
320
+ let cachedSystems;
321
+
322
+ /** 宿主机系统身份,进程内只探测一次。 */
323
+ export function osInfo() {
324
+ if (cached === undefined) {
325
+ try {
326
+ cached = detectOsInfo();
327
+ } catch {
328
+ cached = null;
329
+ }
330
+ }
331
+ return cached;
332
+ }
333
+
334
+ /** 本机系统列表(宿主机 + WSL),进程内只探测一次。 */
335
+ export function systems() {
336
+ if (cachedSystems === undefined) {
337
+ try {
338
+ const host = osInfo();
339
+ const extra = process.platform === "win32" ? detectWsl() : [];
340
+ cachedSystems = sanitizeSystems(host ? [{ kind: "host", ...host }, ...extra] : extra);
341
+ } catch {
342
+ cachedSystems = null;
343
+ }
344
+ }
345
+ return cachedSystems;
346
+ }
347
+
348
+ /** 只为自测:清掉缓存,避免 fixture 之间互相污染。 */
349
+ export function __resetOsInfoCache() {
350
+ cached = undefined;
351
+ cachedSystems = undefined;
352
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * tailnet 通道列表的解析(纯函数,便于自测)。
3
+ *
4
+ * 一台机器可以同时加入多个 tailnet:每个通道一个 sidecar、一个 tailnet 地址。
5
+ * **设备身份仍然只有一个** —— instanceId 不变,通道只是这个节点的多条可达路径。
6
+ *
7
+ * 优先级:
8
+ * 1. profile 配置里的 `tsnetChannels`(部署方钉死,界面改不了)
9
+ * 2. `state.json` 里的 `tsnetChannels`(界面添加/编辑的,0600)
10
+ * 3. 都没有时退回旧版单授权码字段,合成一个 id = `default` 的通道
11
+ *
12
+ * 这一层刻意不碰文件与网络:调用方把 config / state 传进来,输出可预测。
13
+ * 通道 id 会进 sidecar 的状态目录,所以它的稳定性就是 tailnet 里的设备身份。
14
+ */
15
+ import { createHash } from "node:crypto";
16
+ import { channelKey } from "./manager.js";
17
+
18
+ /** 没给 id 时按「显示名 + 控制服务器」推导一个稳定 id。 */
19
+ export function deriveChannelId(label, controlUrl) {
20
+ return `ch-${createHash("sha256").update(`${label}\n${controlUrl}`).digest("hex").slice(0, 10)}`;
21
+ }
22
+
23
+ /**
24
+ * @param {object} args
25
+ * @param {object} args.config profile 配置(只读其中的 tsnet* 字段)
26
+ * @param {object} args.state state.json 解析结果
27
+ * @returns {{id,label,authKey,controlUrl,hostname,enabled,legacy,source}[]}
28
+ */
29
+ export function resolveTailnetChannels({ config = {}, state = {} } = {}) {
30
+ const pick = (fromConfig, fromState) => String(fromConfig ?? "").trim() || String(fromState ?? "").trim();
31
+ const cfgList = Array.isArray(config.tsnetChannels) ? config.tsnetChannels : [];
32
+ const stList = Array.isArray(state.tsnetChannels) ? state.tsnetChannels : [];
33
+ const raw = cfgList.length > 0 ? cfgList : stList;
34
+ const fromConfigFile = cfgList.length > 0;
35
+
36
+ const list = [];
37
+ const used = new Set();
38
+ const add = (item) => {
39
+ let id = channelKey(item.id, "");
40
+ if (!id) id = deriveChannelId(String(item.label ?? "").trim(), String(item.controlUrl ?? "").trim());
41
+ if (used.has(id)) {
42
+ let n = 2;
43
+ while (used.has(`${id}-${n}`)) n += 1;
44
+ id = `${id}-${n}`;
45
+ }
46
+ used.add(id);
47
+ list.push({
48
+ id,
49
+ label: String(item.label ?? "").trim() || (id === "default" ? "Tailscale" : `Tailnet ${list.length + 1}`),
50
+ authKey: String(item.authKey ?? "").trim(),
51
+ controlUrl: String(item.controlUrl ?? "").trim(),
52
+ hostname: String(item.hostname ?? "").trim(),
53
+ enabled: item.enabled !== false,
54
+ legacy: item.legacy === true,
55
+ source: fromConfigFile ? "config" : "state",
56
+ });
57
+ };
58
+
59
+ if (raw.length > 0) {
60
+ for (const c of raw) if (c && typeof c === "object") add(c);
61
+ } else {
62
+ // 旧版单通道:`default` 沿用旧目录,升级不丢设备身份。
63
+ const enabled = config.tsnetEnabled === true || state.tsnetEnabled === true;
64
+ const authKey = pick(config.tsnetAuthKey, state.tsnetAuthKey);
65
+ const controlUrl = pick(config.tsnetControlUrl, state.tsnetControlUrl);
66
+ const hostname = pick(config.tsnetHostname, state.tsnetHostname);
67
+ if (enabled || authKey || controlUrl) {
68
+ add({ id: "default", label: "Tailscale", authKey, controlUrl, hostname, enabled, legacy: true });
69
+ }
70
+ }
71
+ return list;
72
+ }