dsh-plugin-mesh 0.5.8 → 0.5.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/cordis.patch.yml CHANGED
@@ -53,6 +53,12 @@
53
53
  # 若网络不完全可信(合租/公司/有访客设备),改成 true 再对齐配对码。
54
54
  requirePairing: false
55
55
 
56
+ # 陌生设备第一次派活时,本机先弹一次确认(默认开)。
57
+ # 允许过的设备写进 state.json 的 approvedPeers,同一台不再问。
58
+ # 开了 requirePairing 就不再重复问 —— 配对码是更强的信任动作。
59
+ # 想让内网完全免打扰(自己家几台机器)就改成 false。
60
+ requireApproval: true
61
+
56
62
  # 对端任务在本机新建会话时的选项
57
63
  agentPreset: standard
58
64
  # 对端派来的是外部不可信输入,默认不给 danger-full-access
@@ -0,0 +1,165 @@
1
+ /**
2
+ * 「陌生设备首次派活要确认」的自测。
3
+ *
4
+ * 这是安全相关判定,判错的后果是静默的:界面上写着"默认会先问你",实际上
5
+ * 陌生机器照样能直接让本机开一个 agent 会话。所以用断言盯死这几件事:
6
+ * · 缺省要拦(不能因为 config 里没写这个键就放行)
7
+ * · 显式 false 才不拦
8
+ * · 允许过一台,就只放行这一台(按机器名或地址命中)
9
+ * · 配对码开启时不重复问(它是更强的信任动作)
10
+ * · 撤销之后立刻重新拦
11
+ * · 坏数据(字符串、null、缺字段)不能把闸门炸开
12
+ *
13
+ * node lib/_selftest-approval.mjs
14
+ */
15
+ import { strict as assert } from "node:assert";
16
+ import {
17
+ MAX_APPROVED_PEERS,
18
+ approvePeer,
19
+ isApproved,
20
+ isReplyToOutbound,
21
+ needsApproval,
22
+ normalizeApproved,
23
+ peerOfTask,
24
+ revokePeer,
25
+ } from "./approval.js";
26
+
27
+ let passed = 0;
28
+ let failed = 0;
29
+ function test(name, fn) {
30
+ try {
31
+ fn();
32
+ passed += 1;
33
+ console.log(` ✓ ${name}`);
34
+ } catch (err) {
35
+ failed += 1;
36
+ console.log(` ✗ ${name}`);
37
+ console.log(` ${err?.message ?? err}`);
38
+ }
39
+ }
40
+
41
+ const taskFrom = (machine, address = "") => ({
42
+ id: "t-1",
43
+ from: `${machine}/peng`,
44
+ fromMachine: machine,
45
+ task: "报一下系统负载",
46
+ sourceAddress: address,
47
+ });
48
+
49
+ console.log("\n── 缺省必须拦:这是「装上就安全」的底线 ──");
50
+
51
+ test("config 里没有 requireApproval 这个键 → 仍然要拦", () => {
52
+ const peer = peerOfTask(taskFrom("陌生机"));
53
+ assert.equal(needsApproval({ config: {}, approved: [], peer }), true);
54
+ });
55
+
56
+ test("显式 requireApproval: false 才放行(老用户想回到零配置)", () => {
57
+ const peer = peerOfTask(taskFrom("陌生机"));
58
+ assert.equal(needsApproval({ config: { requireApproval: false }, approved: [], peer }), false);
59
+ });
60
+
61
+ test("配对码已开启 → 不再重复问(配对码是更强的信任动作)", () => {
62
+ const peer = peerOfTask(taskFrom("陌生机"));
63
+ assert.equal(needsApproval({ config: {}, approved: [], peer, pairingRequired: true }), false);
64
+ });
65
+
66
+ console.log("\n── 允许过的机器要记住,且只记这一台 ──");
67
+
68
+ test("允许 A 之后 A 免问、B 仍然要问", () => {
69
+ const a = peerOfTask(taskFrom("A机"));
70
+ const b = peerOfTask(taskFrom("B机"));
71
+ const approved = approvePeer([], a, "2026-01-01T00:00:00.000Z");
72
+ assert.equal(needsApproval({ config: {}, approved, peer: a }), false);
73
+ assert.equal(needsApproval({ config: {}, approved, peer: b }), true);
74
+ });
75
+
76
+ test("机器名大小写不敏感(Windows 上尤其重要)", () => {
77
+ const approved = approvePeer([], peerOfTask(taskFrom("DESKTOP-ABC")));
78
+ assert.equal(isApproved(approved, peerOfTask(taskFrom("desktop-abc"))), true);
79
+ });
80
+
81
+ test("只给了地址的对端也能被记住(旧版本对端)", () => {
82
+ // "unknown" 是老对端的占位符,不能当成一台叫 unknown 的机器
83
+ const peer = peerOfTask({ from: "unknown", sourceAddress: "192.168.1.9" });
84
+ assert.equal(peer.machine, "");
85
+ const approved = approvePeer([], peer);
86
+ assert.equal(isApproved(approved, { machine: "", address: "192.168.1.9" }), true);
87
+ // 另一个地址不能被顺带放行
88
+ assert.equal(isApproved(approved, { machine: "", address: "192.168.1.10" }), false);
89
+ });
90
+
91
+ test("有机器名就只认机器名 —— 不能因为地址相同就放行另一台(tailnet 反代下都是 127.0.0.1)", () => {
92
+ const a = peerOfTask({ fromMachine: "A机", sourceAddress: "127.0.0.1" });
93
+ const approved = approvePeer([], a);
94
+ const b = peerOfTask({ fromMachine: "B机", sourceAddress: "127.0.0.1" });
95
+ assert.equal(isApproved(approved, b), false);
96
+ });
97
+
98
+ test("重复允许同一台机器 → 幂等,不会长出两条记录", () => {
99
+ const a = peerOfTask(taskFrom("A机"));
100
+ const once = approvePeer([], a);
101
+ const twice = approvePeer(once, a);
102
+ assert.equal(twice.length, 1);
103
+ });
104
+
105
+ test("撤销之后立刻重新拦", () => {
106
+ const a = peerOfTask(taskFrom("A机"));
107
+ const approved = approvePeer([], a);
108
+ const revoked = revokePeer(approved, "a机");
109
+ assert.equal(needsApproval({ config: {}, approved: revoked, peer: a }), true);
110
+ });
111
+
112
+ console.log("\n── 坏数据不能把闸门炸开 ──");
113
+
114
+ test("approvedPeers 是 null / 字符串 / 混入坏条目 → 归一化成空或只留好条目", () => {
115
+ assert.deepEqual(normalizeApproved(null), []);
116
+ assert.deepEqual(normalizeApproved("oops"), []);
117
+ assert.deepEqual(normalizeApproved([null, 1, "x", {}, { machine: "ok" }]).length, 1);
118
+ });
119
+
120
+ test("既没有机器名也没有地址的对端 → 必须问(不能因为认不出来就放行)", () => {
121
+ const peer = peerOfTask({ from: "", sourceAddress: "" });
122
+ assert.equal(needsApproval({ config: {}, approved: [], peer }), true);
123
+ });
124
+
125
+ test("批准记录有上限,不会无限增长", () => {
126
+ let list = [];
127
+ for (let i = 0; i < MAX_APPROVED_PEERS + 10; i += 1) list = approvePeer(list, { machine: `m${i}`, address: "" });
128
+ assert.equal(list.length, MAX_APPROVED_PEERS);
129
+ // 最新的那台必须在,最旧的被挤掉
130
+ assert.equal(isApproved(list, { machine: `m${MAX_APPROVED_PEERS + 9}`, address: "" }), true);
131
+ assert.equal(isApproved(list, { machine: "m0", address: "" }), false);
132
+ });
133
+
134
+ console.log("\n── peerOfTask:机器名优先,地址兜底 ──");
135
+
136
+ test("优先用 fromMachine,不用 from 里拼出来的前缀", () => {
137
+ const p = peerOfTask({ from: "旧名字/peng", fromMachine: "新名字", sourceAddress: "10.0.0.5" });
138
+ assert.equal(p.machine, "新名字");
139
+ });
140
+
141
+ test("fromMachine 缺失时回退 from 的机器名部分", () => {
142
+ assert.equal(peerOfTask({ from: "hos/peng" }).machine, "hos");
143
+ });
144
+
145
+ console.log("\n── 回执必须绕过闸门(否则结果永远回不来)──");
146
+
147
+ test("同一台机器 + 同一 thread 的回执 → 是回执", () => {
148
+ const out = [{ toMachine: "hos", thread: "build-1" }];
149
+ assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "build-1" }, out), true);
150
+ });
151
+
152
+ test("换一台机器或换一个 thread → 不是回执(不能借旧 thread 名绕过)", () => {
153
+ const out = [{ toMachine: "hos", thread: "build-1" }];
154
+ assert.equal(isReplyToOutbound({ fromMachine: "evilbox", thread: "build-1" }, out), false);
155
+ assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "build-2" }, out), false);
156
+ });
157
+
158
+ test("没有 thread / 没有机器名 / outbound 不是数组 → 都不是回执", () => {
159
+ assert.equal(isReplyToOutbound({ fromMachine: "hos" }, [{ toMachine: "hos", thread: "" }]), false);
160
+ assert.equal(isReplyToOutbound({ thread: "x" }, [{ toMachine: "hos", thread: "x" }]), false);
161
+ assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "x" }, null), false);
162
+ });
163
+
164
+ console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
165
+ process.exit(failed === 0 ? 0 : 1);
@@ -9,7 +9,7 @@
9
9
  import { strict as assert } from "node:assert";
10
10
  import { homedir, tmpdir } from "node:os";
11
11
  import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
12
- import { join } from "node:path";
12
+ import { delimiter, join } from "node:path";
13
13
  import {
14
14
  augmentedPath,
15
15
  capabilityAge,
@@ -324,14 +324,14 @@ test("按 max 截断", () => {
324
324
  console.log("\n── augmentedPath:只许加,绝不许减 ──");
325
325
 
326
326
  test("原 PATH 的每一项都还在(补全不能把已有路径挤掉)", () => {
327
- const before = String(process.env.PATH ?? "").split(":").filter(Boolean);
328
- const after = new Set(augmentedPath().split(":").filter(Boolean));
327
+ const before = String(process.env.PATH ?? "").split(delimiter).filter(Boolean);
328
+ const after = new Set(augmentedPath().split(delimiter).filter(Boolean));
329
329
  for (const d of before) assert.ok(after.has(d), `补全后丢了 ${d}`);
330
330
  });
331
331
 
332
332
  test("没有重复项", () => {
333
333
  // 报出**是哪几个**重复:只报"不该有重复"的话,下次在别人机器上红了还是得猜。
334
- const parts = augmentedPath().split(":").filter(Boolean);
334
+ const parts = augmentedPath().split(delimiter).filter(Boolean);
335
335
  const seen = new Set();
336
336
  const dup = [];
337
337
  for (const d of parts) {
@@ -349,7 +349,7 @@ test("同一个目录换了写法(末尾斜杠)也只能出现一次", () =>
349
349
  const spelled = `${existing}/`;
350
350
  const out = augmentedPath(spelled, process.platform);
351
351
  const norm = (d) => __normPathForCompare(d, process.platform);
352
- const keys = out.split(":").filter(Boolean).map(norm);
352
+ const keys = out.split(delimiter).filter(Boolean).map(norm);
353
353
  assert.equal(new Set(keys).size, keys.length, `按目录判重后仍重复:${out}`);
354
354
  });
355
355
 
@@ -421,8 +421,12 @@ test("自校验式判据:问的是「我们自己的兜底有没有起作用
421
421
  __extraPathDirs(process.platform).filter((d) => !__storeAliasDir.test(d)).length === 0,
422
422
  "判据必须精确等价于「补全一个目录都没加进去」(Store 别名目录除外)",
423
423
  );
424
- // 本机 darwin 上 win32 那套 %ProgramFiles% 路径确实都不存在 → 判不可靠(可证)。
425
- assert.equal(__pathLookupUnreliable("win32"), true);
424
+ // 在非 Windows 开发机上,win32 那套 %ProgramFiles% 路径确实都不存在 → 判不可靠。
425
+ // 但**在 Windows runner 上这些目录是真实存在的**,这条断言不成立;所以只把
426
+ // 它当"非 Windows 上的可证性"检查,Windows 交给上面那条等价性断言。
427
+ if (process.platform !== "win32") {
428
+ assert.equal(__pathLookupUnreliable("win32"), true);
429
+ }
426
430
  });
427
431
 
428
432
  test("Store 别名目录(WindowsApps)不算「补全真的生效」的证据", () => {
@@ -8,6 +8,17 @@ import { tmpdir } from "node:os";
8
8
  import { join } from "node:path";
9
9
  import { conversationKey } from "./conversation.js";
10
10
 
11
+ // Node 20 + vm.SourceTextModule 双上下文:Linux 上稳定 SIGSEGV(2026-10-31 两次
12
+ // CI 复现),macOS 上偶发(2026-11-03 CI 门禁一次、本机一次)。段错误发生在任何
13
+ // 断言之前,进程里捕获不了 —— 只能让 Node 20 整体跳过。同一套件由 Node 24 的
14
+ // gate 和 Node 22 的 linux portability 覆盖;其它 suite 在 Node 20 上照常跑。
15
+ const NODE_MAJOR = Number(process.versions.node.split(".")[0]);
16
+ if (NODE_MAJOR === 20) {
17
+ console.log("skip: Node 20 在 vm.SourceTextModule 双上下文下会 SIGSEGV(上游 V8 bug,macOS/Linux 都出现过)");
18
+ console.log(" 该套件由 Node 22(linux portability)与 Node 24 gate 覆盖");
19
+ process.exit(0);
20
+ }
21
+
11
22
  const root = mkdtempSync(join(tmpdir(), "mesh-reply-test-"));
12
23
  const cleanups = [];
13
24
  const entryUrl = new URL("./index.js", import.meta.url);
@@ -10,6 +10,9 @@
10
10
  * node lib/_selftest-update.mjs
11
11
  */
12
12
  import { strict as assert } from "node:assert";
13
+ import { tmpdir } from "node:os";
14
+ import { join } from "node:path";
15
+ import { pathToFileURL } from "node:url";
13
16
  import {
14
17
  buildUpdateReport,
15
18
  buildUpgradeCommand,
@@ -101,9 +104,14 @@ test("更新量级:major / minor / patch / prerelease / none", () => {
101
104
 
102
105
  console.log("\n── 升级命令 / 安装目录 ──");
103
106
 
104
- test("插件安装目录从 import.meta.url 推出(lib/ 的上一级,带结尾斜杠)", () => {
105
- const dir = pluginDirFromUrl("file:///Users/peng/.dsh/profiles/desktop/node_modules/dsh-plugin-mesh/lib/index.js");
106
- assert.equal(dir, "/Users/peng/.dsh/profiles/desktop/node_modules/dsh-plugin-mesh/");
107
+ test("插件安装目录从 import.meta.url 推出(lib/ 的上一级,带结尾分隔符)", () => {
108
+ // 用 pathToFileURL 现造一个本机安装路径:Windows 上不能拿 POSIX 的
109
+ // `file:///Users/...` 去喂 fileURLToPath(没有盘符会直接抛),否则断言测的
110
+ // 是"非法 URL 返回空串",不是这个函数的行为。
111
+ const entryUrl = pathToFileURL(join(tmpdir(), "dsh-profiles", "node_modules", "dsh-plugin-mesh", "lib", "index.js")).href;
112
+ const dir = pluginDirFromUrl(entryUrl);
113
+ assert.ok(/dsh-plugin-mesh[\\/]$/.test(dir), dir);
114
+ assert.equal(dir.slice(0, -1).split(/[\\/]/).pop(), "dsh-plugin-mesh", dir);
107
115
  });
108
116
 
109
117
  test("升级命令用的是 release 真实资产名与 tag(与 scripts/release-plugin.sh 一致)", () => {
@@ -176,7 +176,11 @@ test("writeEntries 再兜一层:不接受写到目标目录之外", () => {
176
176
  }
177
177
  });
178
178
 
179
- test("写盘保留可执行位(脚本类文件不会丢权限)", () => {
179
+ test("写盘保留可执行位(POSIX;Windows 没有 POSIX 权限位)", () => {
180
+ if (process.platform === "win32") {
181
+ console.log(" (Windows 没有 POSIX 权限位,跳过)");
182
+ return;
183
+ }
180
184
  const dir = tempDir();
181
185
  try {
182
186
  const entries = extractTarball(makeTarGz([{ name: "package/run.sh", content: "#!/bin/sh\n", mode: 0o755 }]), { stripComponents: 1 });
@@ -145,7 +145,10 @@ const {
145
145
  HomeSwitchBar,
146
146
  UpdateLink,
147
147
  UpdateLinkView,
148
+ InstallConfirm,
148
149
  FeedbackLink,
150
+ DemoOverlay,
151
+ ApprovalBar,
149
152
  } = mod.__test;
150
153
 
151
154
  const noop = () => {};
@@ -1155,30 +1158,63 @@ test("有更新:一行小字「新版本 v0.6.0」,不铺命令、不占卡
1155
1158
  assert.ok(!txt.includes("curl"), "升级命令不再铺在页面上");
1156
1159
  });
1157
1160
 
1158
- test("一键安装:第一次点只是确认,第二次点才真的开始装", () => {
1159
- let installed = 0;
1160
- const view = (install) =>
1161
- UpdateLinkView({
1162
- phase: "done",
1163
- report: updateReport,
1164
- install,
1165
- onCheck: noop,
1166
- onInstall: () => {
1167
- installed += 1;
1168
- },
1169
- });
1170
- const findInstallBtn = (el) => {
1171
- let btn = null;
1172
- walk(el, (n) => {
1173
- if (n.type === "button" && textOf(n).join("").includes("确认安装")) btn = n;
1174
- });
1175
- return btn;
1176
- };
1177
- const armed = view({ state: "armed", error: "" });
1178
- const btn = findInstallBtn(armed);
1179
- assert.ok(btn, "确认态要有一个「确认安装 v0.6.0」按钮");
1161
+ test("一键安装:点「新版本」只打开确认弹窗,不会直接装", () => {
1162
+ let requested = 0;
1163
+ const el = UpdateLinkView({
1164
+ phase: "done",
1165
+ report: updateReport,
1166
+ install: { state: "idle", error: "" },
1167
+ onCheck: noop,
1168
+ onInstall: () => {
1169
+ requested += 1;
1170
+ },
1171
+ });
1172
+ let btn = null;
1173
+ walk(el, (n) => {
1174
+ if (n.type === "button" && textOf(n).join("").includes("新版本 v0.6.0")) btn = n;
1175
+ });
1176
+ assert.ok(btn, "缺少「新版本 v0.6.0」入口");
1180
1177
  btn.props.onClick();
1181
- assert.equal(installed, 1, "点击确认后才调用安装");
1178
+ assert.equal(requested, 1, "点击入口应当是打开确认,而不是直接安装");
1179
+ });
1180
+
1181
+ test("确认弹窗:说清版本、校验与重启代价,安装/取消各走各的", () => {
1182
+ let confirmed = 0;
1183
+ let cancelled = 0;
1184
+ const el = InstallConfirm({
1185
+ report: updateReport,
1186
+ busy: false,
1187
+ onCancel: () => {
1188
+ cancelled += 1;
1189
+ },
1190
+ onConfirm: () => {
1191
+ confirmed += 1;
1192
+ },
1193
+ });
1194
+ const txt = textOf(el).join(" ");
1195
+ assert.ok(txt.includes("安装 Mesh v0.6.0"), txt);
1196
+ assert.ok(txt.includes("v0.5.6") && txt.includes("v0.6.0"), txt);
1197
+ assert.ok(txt.includes("sha512"), "要说明会做完整性校验");
1198
+ assert.ok(txt.includes("备份"), "要说明旧版可回滚");
1199
+ assert.ok(txt.includes("重启"), "要提前说重启代价");
1200
+ let installBtn = null;
1201
+ let cancelBtn = null;
1202
+ walk(el, (n) => {
1203
+ const label = n.type === "button" ? textOf(n).join("") : "";
1204
+ if (label === "安装 v0.6.0") installBtn = n;
1205
+ if (label === "取消") cancelBtn = n;
1206
+ });
1207
+ assert.ok(installBtn && cancelBtn, "缺少安装或取消按钮");
1208
+ installBtn.props.onClick();
1209
+ cancelBtn.props.onClick();
1210
+ assert.equal(confirmed, 1);
1211
+ assert.equal(cancelled, 1);
1212
+ });
1213
+
1214
+ test("确认弹窗安装中:按钮显示「安装中…」,取消被禁用", () => {
1215
+ const el = InstallConfirm({ report: updateReport, busy: true, onCancel: noop, onConfirm: noop });
1216
+ const txt = textOf(el).join(" ");
1217
+ assert.ok(txt.includes("安装中…"), txt);
1182
1218
  });
1183
1219
 
1184
1220
  test("安装中 / 安装失败:状态写在字面上,失败不悄悄回到「有新版本」", () => {
@@ -1317,5 +1353,36 @@ test("点「检查更新」触发重查(不是跳页)", () => {
1317
1353
  assert.equal(checked, 1);
1318
1354
  });
1319
1355
 
1356
+ test("陌生设备首次派活:确认条说清「谁」和「要干什么」,并给出允许/拒绝", () => {
1357
+ const el = ApprovalBar({
1358
+ items: [{ id: "t-1", fromMachine: "hos", from: "hos/peng", task: "把插件升级到 0.5.8" }],
1359
+ busy: false,
1360
+ onDecide: noop,
1361
+ });
1362
+ const txt = textOf(el).join(" ");
1363
+ assert.ok(txt.includes("hos"), txt);
1364
+ assert.ok(txt.includes("把插件升级到 0.5.8"), txt);
1365
+ assert.ok(txt.includes("允许") && txt.includes("拒绝"), txt);
1366
+ let allow = null;
1367
+ walk(el, (n) => {
1368
+ if (n.type === "button" && textOf(n).join("") === "允许") allow = n;
1369
+ });
1370
+ assert.ok(allow, "缺少「允许」按钮");
1371
+ });
1372
+
1373
+ test("没有待确认项时确认条不渲染", () => {
1374
+ assert.equal(ApprovalBar({ items: [], onDecide: noop }), null);
1375
+ });
1376
+
1377
+ test("演示:单机也能看见完整闭环,且明说这是演示、不花 token", () => {
1378
+ const el = DemoOverlay({ open: true, onClose: noop });
1379
+ const txt = textOf(el).join(" ");
1380
+ assert.ok(txt.includes("演示"), txt);
1381
+ assert.ok(txt.includes("报一下你的系统和负载"), txt);
1382
+ assert.ok(txt.includes("结果回到这里"), txt);
1383
+ assert.ok(txt.includes("不花 token"), txt);
1384
+ assert.equal(DemoOverlay({ open: false, onClose: noop }), null);
1385
+ });
1386
+
1320
1387
  console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
1321
1388
  process.exit(failed ? 1 : 0);
@@ -0,0 +1,152 @@
1
+ /**
2
+ * 陌生设备第一次派活时的「确认一下」闸门 —— 纯函数,便于单测。
3
+ *
4
+ * 为什么要有它:默认零配置意味着同一网段里任何连得上 45917 的机器都能让本机
5
+ * 开一个 agent 会话跑东西。对"自己家三台电脑"这是方便,对"公司网络 / 合租 /
6
+ * 咖啡厅"就是敞着门。原来的答案是"你去开配对码",但那是个**设置项**,没人会
7
+ * 主动打开 —— 而恐惧是装之前就有的,不是用完才有的。
8
+ *
9
+ * 所以默认改成:陌生设备第一次派活 → 本机弹一次确认;你点过「允许」之后,
10
+ * 这台机器才不再问你。配对码(requirePairing)比它更强,开了配对码就说明
11
+ * 你已经用共享密钥表达过信任,不再多问一遍。
12
+ *
13
+ * 规则写在这里而不是埋进 3000 行的 index.js:这是安全相关判定,写错了会
14
+ * "看起来拦住了、实际放行",而这种错误没人会为它写测试。拆出来,单测它。
15
+ */
16
+
17
+ /** 一次批准记录最多留多少条:设备是有限的,留太多只会让 state.json 变脏。 */
18
+ export const MAX_APPROVED_PEERS = 50;
19
+
20
+ /**
21
+ * 从一条入站任务里取出"这是谁"。
22
+ *
23
+ * 识别优先级:机器名 > 来源地址。**机器名优先**,因为它稳定、可读,用户在
24
+ * 确认框里看到的就是这个名字;地址只作为兜底(旧版本对端、或机器名没填)。
25
+ *
26
+ * @param {object} task `/mesh/v1/task` 落下来的任务对象
27
+ * @returns {{machine: string, address: string, key: string}}
28
+ */
29
+ export function peerOfTask(task = {}) {
30
+ let machine = String(task?.fromMachine || "").trim() || String(task?.from || "").split("/")[0].trim();
31
+ // "unknown" 是旧版本对端没填名字时的占位符,不能当成一台叫 unknown 的机器 ——
32
+ // 否则所有老对端会共用一张信任记录。
33
+ if (machine.toLowerCase() === "unknown") machine = "";
34
+ const address = String(task?.sourceAddress || "").trim();
35
+ return { machine, address, key: (machine || address).toLowerCase() };
36
+ }
37
+
38
+ /** 把磁盘上读出来的批准列表归一化 —— 坏数据不能让闸门炸掉。 */
39
+ export function normalizeApproved(list) {
40
+ if (!Array.isArray(list)) return [];
41
+ return list
42
+ .filter((x) => x && typeof x === "object")
43
+ .map((x) => ({
44
+ machine: String(x.machine ?? "").trim(),
45
+ address: String(x.address ?? "").trim(),
46
+ at: typeof x.at === "string" ? x.at : "",
47
+ }))
48
+ .filter((x) => x.machine || x.address)
49
+ .slice(-MAX_APPROVED_PEERS);
50
+ }
51
+
52
+ /**
53
+ * 这台设备是否已经被允许过。
54
+ *
55
+ * **有机器名就只认机器名**;没有名字(旧版本对端)才退回地址。
56
+ * 不能"任一命中":tailnet 反代下多台对端的 sourceAddress 都是 127.0.0.1,
57
+ * 按地址匹配会让允许一台 = 允许全部 —— 闸门形同虚设(本地联调时实测到了)。
58
+ * 机器名大小写不敏感(Windows 上尤其重要)。
59
+ *
60
+ * @param {Array} approved state.json 里的 approvedPeers
61
+ * @param {{machine: string, address: string}} peer peerOfTask 的返回值
62
+ */
63
+ export function isApproved(approved, peer) {
64
+ const list = normalizeApproved(approved);
65
+ // 调用方可以只传 {machine, address},不必先过 peerOfTask;
66
+ // 认不出是谁才返回 false(宁可多问一次,也不默认放行)。
67
+ const machine = String(peer?.machine || "").trim().toLowerCase();
68
+ if (machine && machine !== "unknown") {
69
+ return list.some((x) => x.machine && x.machine.toLowerCase() === machine);
70
+ }
71
+ const address = String(peer?.address || "").trim();
72
+ if (!address) return false;
73
+ return list.some((x) => !x.machine && x.address === address);
74
+ }
75
+
76
+ /** 追加一条批准记录(幂等;超过上限丢最旧的)。 */
77
+ export function approvePeer(approved, peer, at = new Date().toISOString()) {
78
+ const machineKey = String(peer?.machine || "").trim().toLowerCase();
79
+ const addressKey = String(peer?.address || "").trim();
80
+ const list = normalizeApproved(approved).filter((x) => {
81
+ // 和 isApproved 同一套规则:有机器名只按机器名去重,没名字才按地址。
82
+ if (machineKey) return !(x.machine && x.machine.toLowerCase() === machineKey);
83
+ return !(!x.machine && addressKey && x.address === addressKey);
84
+ });
85
+ const entry = {
86
+ machine: String(peer?.machine ?? "").trim(),
87
+ address: String(peer?.address ?? "").trim(),
88
+ at,
89
+ };
90
+ if (!entry.machine && !entry.address) return normalizeApproved(approved);
91
+ return [...list, entry].slice(-MAX_APPROVED_PEERS);
92
+ }
93
+
94
+ /**
95
+ * 撤销一条批准(按机器名或地址,大小写不敏感)。
96
+ *
97
+ * @returns {Array} 新列表;没命中时原样返回
98
+ */
99
+ export function revokePeer(approved, target) {
100
+ const t = String(target ?? "").trim().toLowerCase();
101
+ if (!t) return normalizeApproved(approved);
102
+ return normalizeApproved(approved).filter(
103
+ (x) => x.machine.toLowerCase() !== t && String(x.address).toLowerCase() !== t,
104
+ );
105
+ }
106
+
107
+ /**
108
+ * 这条任务要不要先问用户。
109
+ *
110
+ * 只看三件事:配置开关、配对码是否已生效、这台设备是否已被允许。
111
+ * **不要**在这里判断"是不是自己派给自己"——那属于路由层,不属于信任层。
112
+ *
113
+ * @param {object} input
114
+ * @param {object} input.config 插件配置(读 requireApproval)
115
+ * @param {Array} input.approved state.json 的 approvedPeers
116
+ * @param {object} input.peer peerOfTask 的返回值
117
+ * @param {boolean} input.pairingRequired pairingRequired(config) 的结果
118
+ * @returns {boolean}
119
+ */
120
+ export function needsApproval({ config = {}, approved = [], peer = {}, pairingRequired = false }) {
121
+ // 显式 false 才关;缺省按开(schema 默认也是 true)。
122
+ if (config?.requireApproval === false) return false;
123
+ // 配对码是比"点一次允许"更强的信任动作:开了它就不再重复问。
124
+ if (pairingRequired) return false;
125
+ if (!peer || !(peer.machine || peer.address)) return true;
126
+ return !isApproved(approved, peer);
127
+ }
128
+
129
+ /**
130
+ * 这条入站任务是不是在「回答问题」而不是派新活?
131
+ *
132
+ * 判据和 handleInboundTask 里的一致:同一台机器 + 同一个 thread 上,我们确实
133
+ * 往外派过任务。回执**必须绕过**首次确认闸门,否则对方把结果派回来时会被本机
134
+ * 拦下,整条回路卡死在"等允许"。
135
+ *
136
+ * 抽成纯函数是为了能单测这条绕过 —— 写错了是静默灾难:要么结果回不来,
137
+ * 要么陌生机器能借一个旧 thread 名绕过闸门。
138
+ *
139
+ * @param {object} task 入站任务
140
+ * @param {Array} outbound 本机发出的任务记录
141
+ */
142
+ export function isReplyToOutbound(task = {}, outbound = []) {
143
+ const thread = String(task?.thread || "").trim();
144
+ if (!thread) return false;
145
+ const machine = String(task?.fromMachine || String(task?.from || "").split("/")[0] || "").trim();
146
+ if (!machine) return false;
147
+ return (Array.isArray(outbound) ? outbound : []).some(
148
+ (o) =>
149
+ String(o?.toMachine || "").trim() === machine &&
150
+ String(o?.thread || "").trim() === thread,
151
+ );
152
+ }