dsh-plugin-mesh 0.5.3 → 0.5.5

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/switch.js ADDED
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Mesh 一键关闭(kill switch)的判定与合并 —— 纯函数,便于单测。
3
+ *
4
+ * 单独成模块的理由和 pairing.js 一样:这是**安全相关**的判定。用户点了一键
5
+ * 关闭,如果判定写错(比如把字符串 "true" 当关闭、或者"关闭全部"只关了一半),
6
+ * 界面上照样显示"已关闭",实际上端口还开着、组播还发着 —— 这种错误看不见。
7
+ * 埋在一个 3000 行的文件里没人会为它写测试,所以拆出来、单测它。
8
+ *
9
+ * 三种范围:
10
+ * · `lan` 局域网 mesh:组播广播、主动扫描、ping,对端 HTTP 端口只绑回环
11
+ * · `internet` 互联网 mesh:停掉全部 tailnet sidecar(通道配置保留,可再打开)
12
+ * · `all` 两者都关 —— 就是「一键关闭 Mesh」
13
+ *
14
+ * 状态存在 state.json 的 `shutdown` 字段里:
15
+ *
16
+ * { "lan": true, "internet": false, "at": "2026-01-01T00:00:00.000Z", "by": "ui" }
17
+ *
18
+ * `true` = **已关闭**;缺失 / false = 开着(与历史行为一致 —— 升级不会突然把
19
+ * 所有人的 mesh 断开)。落盘而不是只放内存:一键关闭的语义是"我现在不想让这台
20
+ * 机器被找到、被派活",重启 DSH 后自己悄悄恢复是最坏的结果。
21
+ */
22
+
23
+ /** 允许的范围。顺序即界面顺序:全部 → 局域网 → 互联网。 */
24
+ export const MESH_SWITCH_SCOPES = ["all", "lan", "internet"];
25
+
26
+ /** 范围的中文名(日志、工具回执、界面共用同一套说法)。 */
27
+ export const MESH_SWITCH_LABEL = {
28
+ all: "全部 mesh",
29
+ lan: "局域网 mesh",
30
+ internet: "互联网 mesh",
31
+ };
32
+
33
+ /**
34
+ * 把用户/agent 传来的范围归一化。
35
+ *
36
+ * 除了英文 id,也接受界面上那三个中文词 —— agent 很容易直接照着界面文案
37
+ * 传「局域网」,拒掉它只会让人以为功能坏了。
38
+ *
39
+ * @returns {"all"|"lan"|"internet"|""} 不认识时返回空串(调用方报错)
40
+ */
41
+ export function normalizeSwitchScope(raw) {
42
+ const s = String(raw ?? "").trim().toLowerCase();
43
+ if (!s) return "";
44
+ if (s === "all" || s === "全部" || s === "全部mesh" || s === "全部 mesh") return "all";
45
+ if (s === "lan" || s === "局域网" || s === "局域网mesh" || s === "局域网 mesh") return "lan";
46
+ if (s === "internet" || s === "互联网" || s === "互联网mesh" || s === "互联网 mesh") return "internet";
47
+ return "";
48
+ }
49
+
50
+ /**
51
+ * state.json 里的 `shutdown` → 期望状态。
52
+ *
53
+ * 只有严格的布尔 true 才算关闭。从 YAML / 手工编辑里读出来的字符串 "true"
54
+ * 不算 —— 和 pairing.js 同一条规则:宁可当作"没关",也不要让一个看起来
55
+ * 生效、实际没生效的开关骗人。
56
+ *
57
+ * @param {object} state state.json 解析结果
58
+ * @returns {{lan: boolean, internet: boolean, all: boolean, at: string, by: string}}
59
+ * lan/internet = **是否已关闭**;all = 两者都关。
60
+ */
61
+ export function resolveMeshSwitch(state = {}) {
62
+ const raw = state && typeof state === "object" ? state.shutdown : null;
63
+ const off = (v) => v === true;
64
+ const lan = off(raw?.lan);
65
+ const internet = off(raw?.internet);
66
+ return {
67
+ lan,
68
+ internet,
69
+ all: lan && internet,
70
+ at: typeof raw?.at === "string" ? raw.at : "",
71
+ by: typeof raw?.by === "string" ? raw.by : "",
72
+ };
73
+ }
74
+
75
+ /**
76
+ * 一次开关操作之后要写进 `state.shutdown` 的对象(不修改入参)。
77
+ *
78
+ * `off` 默认 **true**:一键关闭是主动作,调用方漏传时按"关"处理更像用户的意图。
79
+ * 但这只影响 `off` 的缺省,不影响范围 —— 范围不认识就直接抛错,绝不猜。
80
+ *
81
+ * @param {{lan?: boolean, internet?: boolean}|null} current 当前状态(resolveMeshSwitch 的结果)
82
+ * @param {{scope?: string, off?: boolean, by?: string, at?: string}} op
83
+ * @returns {{lan: boolean, internet: boolean, at: string, by: string}}
84
+ */
85
+ export function applyMeshSwitch(current, { scope, off = true, by = "ui", at = new Date().toISOString() } = {}) {
86
+ const s = normalizeSwitchScope(scope);
87
+ if (!s) {
88
+ throw new Error(`未知的开关范围:${String(scope)}(应为 all / lan / internet)`);
89
+ }
90
+ const want = off !== false;
91
+ const next = {
92
+ lan: current ? current.lan === true : false,
93
+ internet: current ? current.internet === true : false,
94
+ };
95
+ if (s === "all" || s === "lan") next.lan = want;
96
+ if (s === "all" || s === "internet") next.internet = want;
97
+ return { ...next, at, by: String(by || "ui") };
98
+ }
99
+
100
+ /**
101
+ * 一行中文摘要,给工具回执 / mesh_peers 用。
102
+ *
103
+ * 刻意把"关"和"开"都说出来(不只说关了什么):agent 读到这行时要能判断
104
+ * 现在到底能不能派任务,而不是靠猜。
105
+ */
106
+ export function describeMeshSwitch(sw = {}) {
107
+ const state = (off) => (off ? "已关闭" : "开启");
108
+ if (sw.lan === true && sw.internet === true) return "mesh 已全部关闭(局域网 + 互联网)";
109
+ return `局域网 ${state(sw.lan)} · 互联网 ${state(sw.internet)}`;
110
+ }
@@ -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
+ }