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.
@@ -71,8 +71,31 @@ async function makeNode(machine) {
71
71
  node.agents.set(id, { messages: [], followup(message) { this.messages.push(message); } });
72
72
  return id;
73
73
  } } };
74
- const options = { ...node, discovery, config: node.config, log: noop, warn: noop, waker, capFor: () => node.config.maxWakesPerThread, capOverrides: new Map(), throttled: new Map() };
75
- node.port = await module.namespace.startPeerServer(ctx, options);
74
+ // 一键关闭的门面:这里用可观测的替身,验证工具的参数处理与回报文案;
75
+ // 真正的停/启逻辑由 applyUnsafe 的运行时 + /mesh/api/switch 承担。
76
+ node.switchCalls = [];
77
+ node.switchStatus = () => ({
78
+ lan: { off: false, active: true, bind: "0.0.0.0", port: node.port, multicast: false, note: "" },
79
+ internet: { off: false, active: false, running: 0, configured: 0, note: "" },
80
+ all: false,
81
+ at: "",
82
+ by: "",
83
+ summary: "局域网 开启 · 互联网 开启",
84
+ });
85
+ const meshSwitch = {
86
+ status: () => node.switchStatus(),
87
+ set: async (opts) => {
88
+ node.switchCalls.push(opts);
89
+ return { changed: true, scope: opts.scope, status: node.switchStatus() };
90
+ },
91
+ };
92
+ const options = { ...node, discovery, config: node.config, log: noop, warn: noop, waker, meshSwitch, capFor: () => node.config.maxWakesPerThread, capOverrides: new Map(), throttled: new Map() };
93
+ // startPeerServer 现在返回句柄(一键关闭要重绑监听地址),端口在 handle.port 上。
94
+ const handle = await module.namespace.startPeerServer(ctx, options);
95
+ node.port = handle.port;
96
+ node.server = handle.server;
97
+ cleanups.push(() => handle.server.close());
98
+ node.gate = module.namespace.transportGate;
76
99
  module.namespace.registerTools(ctx, options);
77
100
  node.peer = { machine, id: machine, online: true, host: "127.0.0.1", port: node.port,
78
101
  endpoints: [{ transport: "lan", host: "127.0.0.1", port: node.port, lastSeen: Date.now() }] };
@@ -82,6 +105,15 @@ async function makeNode(machine) {
82
105
  return node;
83
106
  }
84
107
 
108
+ /**
109
+ * 一键关闭的入站闸门必须真有牙:gate 关掉后连 health 都要 503,
110
+ * 打开后立刻恢复。这条同时守住"别只改界面不改后端"。
111
+ */
112
+ async function probeHealth(node) {
113
+ const res = await fetch(`http://127.0.0.1:${node.port}/mesh/v1/health`);
114
+ return { status: res.status, body: await res.json().catch(() => ({})) };
115
+ }
116
+
85
117
  async function until(check) {
86
118
  const end = Date.now() + 3000;
87
119
  while (!check()) {
@@ -158,6 +190,52 @@ try {
158
190
  assert.equal(a.created, 1);
159
191
  console.log("✓ noWake, wake cap and explicit newSession still apply");
160
192
 
193
+ // 一键关闭的工具面:三个范围、默认关闭、不认识的范围要明确报错。
194
+ const switchTool = b.tools.get("mesh_switch");
195
+ assert.ok(switchTool, "必须注册 mesh_switch");
196
+ const offText = await switchTool.execute({ scope: "局域网", action: "off" });
197
+ assert.match(offText, /局域网 mesh已关闭/, offText);
198
+ assert.match(offText, /当前:局域网 开启/, offText);
199
+ // 注意:工具在 vm 里执行,跨 realm 的对象原型不同,不能 deepStrictEqual
200
+ assert.equal(b.switchCalls.at(-1).scope, "lan");
201
+ assert.equal(b.switchCalls.at(-1).off, true);
202
+ assert.equal(b.switchCalls.at(-1).by, "tool");
203
+ await switchTool.execute({ scope: "all" });
204
+ assert.equal(b.switchCalls.at(-1).off, true, "action 省略时默认关闭");
205
+ const onText = await switchTool.execute({ scope: "internet", action: "on" });
206
+ assert.equal(b.switchCalls.at(-1).off, false);
207
+ assert.match(onText, /互联网 mesh已打开/, onText);
208
+ assert.match(await switchTool.execute({ scope: "wifi" }), /scope 不合法/);
209
+ assert.match(await switchTool.execute({ scope: "lan", action: "shutdown" }), /action 不合法/);
210
+ assert.match(await b.tools.get("mesh_peers").execute({}), /开关: 局域网 开启/, "mesh_peers 要带上开关状态");
211
+
212
+ // 全部关闭时,派发与扫描都必须直接拒绝并说明原因(不是"对端离线")。
213
+ b.switchStatus = () => ({
214
+ lan: { off: true, active: false, bind: "", port: 0, multicast: false, note: "" },
215
+ internet: { off: true, active: false, running: 0, configured: 0, note: "" },
216
+ all: true,
217
+ at: "",
218
+ by: "tool",
219
+ summary: "mesh 已全部关闭(局域网 + 互联网)",
220
+ });
221
+ assert.match(await b.send("A", "closed", "mesh-B-1"), /已全部关闭/);
222
+ assert.match(await b.tools.get("mesh_scan").execute({}), /已全部关闭/);
223
+ assert.match(await b.tools.get("mesh_peers").execute({}), /已全部关闭/);
224
+ assert.doesNotMatch(await b.tools.get("mesh_peers").execute({}), /^没有发现其他 DSH 机器/, "关闭导致的空列表不能说成「没发现」");
225
+ console.log("✓ mesh_switch: scopes, default off, invalid input, and closed-state refusals");
226
+
227
+ // 一键关闭:入站闸门要对 health 也生效,打开后立刻恢复。
228
+ a.gate.lan = false;
229
+ const closed = await probeHealth(a);
230
+ assert.equal(closed.status, 503, "局域网关闭后,对端健康探测必须被拒绝");
231
+ assert.equal(closed.body.closed, true);
232
+ assert.match(String(closed.body.error || ""), /局域网 mesh 已关闭/);
233
+ a.gate.lan = true;
234
+ const reopened = await probeHealth(a);
235
+ assert.equal(reopened.status, 200, "打开后必须恢复");
236
+ assert.equal(reopened.body.ok, true);
237
+ console.log("✓ kill switch closes the inbound peer API and reopens it");
238
+
161
239
  // Missing thread or originating session must not create a reply binding.
162
240
  const bindings = a.threadState.size;
163
241
  await a.send("B", "", "original-session", { noWake: true });
@@ -0,0 +1,142 @@
1
+ /**
2
+ * 一键关闭(kill switch)判定的自测。
3
+ *
4
+ * 这段和配对码一样**安全相关**,而且判错的后果同样是静默的:界面显示
5
+ * "已关闭",端口却还开在 0.0.0.0 上。必须用断言盯着这几件事:
6
+ * · 缺省是"开着"(升级不会突然断开所有人)
7
+ * · 关"全部"必须两个范围都关(不能只关一半)
8
+ * · 只认严格布尔 true(防手工编辑/YAML 字符串坑)
9
+ * · 打开其中一个范围时,另一个范围保持原样(不能顺带把别人开了/关了)
10
+ *
11
+ * node lib/_selftest-switch.mjs
12
+ */
13
+ import { strict as assert } from "node:assert";
14
+ import {
15
+ MESH_SWITCH_SCOPES,
16
+ applyMeshSwitch,
17
+ describeMeshSwitch,
18
+ normalizeSwitchScope,
19
+ resolveMeshSwitch,
20
+ } from "./switch.js";
21
+
22
+ let passed = 0;
23
+ let failed = 0;
24
+ function test(name, fn) {
25
+ try {
26
+ fn();
27
+ passed += 1;
28
+ console.log(` ✓ ${name}`);
29
+ } catch (err) {
30
+ failed += 1;
31
+ console.log(` ✗ ${name}`);
32
+ console.log(` ${err?.message ?? err}`);
33
+ }
34
+ }
35
+
36
+ console.log("\n── 缺省:都开着(升级不会突然断开)──");
37
+
38
+ test("空 state / 空入参 → 都开着", () => {
39
+ for (const st of [{}, null, undefined, { shutdown: null }, { shutdown: {} }]) {
40
+ const r = resolveMeshSwitch(st);
41
+ assert.equal(r.lan, false);
42
+ assert.equal(r.internet, false);
43
+ assert.equal(r.all, false);
44
+ }
45
+ });
46
+
47
+ test("只写了一个范围 → 另一个范围仍是开着", () => {
48
+ const r = resolveMeshSwitch({ shutdown: { lan: true } });
49
+ assert.equal(r.lan, true);
50
+ assert.equal(r.internet, false);
51
+ assert.equal(r.all, false);
52
+ });
53
+
54
+ console.log("\n── 只认严格布尔 true ──");
55
+
56
+ test('字符串 "true" / 数字 1 都不算关闭 —— 否则会让人以为关了、实际没关', () => {
57
+ for (const v of ["true", 1, "1", "yes", {}, []]) {
58
+ const r = resolveMeshSwitch({ shutdown: { lan: v, internet: v } });
59
+ assert.equal(r.lan, false, `lan=${JSON.stringify(v)}`);
60
+ assert.equal(r.internet, false, `internet=${JSON.stringify(v)}`);
61
+ }
62
+ });
63
+
64
+ console.log("\n── 合并:关全部 = 两个都关,别只关一半 ──");
65
+
66
+ test("关 all → lan 与 internet 都为 true(已关闭)", () => {
67
+ const next = applyMeshSwitch(resolveMeshSwitch({}), { scope: "all", off: true, by: "ui", at: "T" });
68
+ assert.deepEqual(next, { lan: true, internet: true, at: "T", by: "ui" });
69
+ });
70
+
71
+ test("只关局域网 → 互联网不受影响", () => {
72
+ const next = applyMeshSwitch(resolveMeshSwitch({}), { scope: "lan", off: true, at: "T" });
73
+ assert.equal(next.lan, true);
74
+ assert.equal(next.internet, false);
75
+ });
76
+
77
+ test("只关互联网 → 局域网不受影响", () => {
78
+ const next = applyMeshSwitch(resolveMeshSwitch({}), { scope: "internet", off: true, at: "T" });
79
+ assert.equal(next.lan, false);
80
+ assert.equal(next.internet, true);
81
+ });
82
+
83
+ test("从「全部关闭」只打开局域网 → 互联网保持关闭(不能顺带全开)", () => {
84
+ const closed = resolveMeshSwitch({ shutdown: { lan: true, internet: true } });
85
+ const next = applyMeshSwitch(closed, { scope: "lan", off: false, at: "T" });
86
+ assert.equal(next.lan, false);
87
+ assert.equal(next.internet, true);
88
+ assert.equal(resolveMeshSwitch({ shutdown: next }).all, false);
89
+ });
90
+
91
+ test("从「全部关闭」打开全部 → 都开", () => {
92
+ const closed = resolveMeshSwitch({ shutdown: { lan: true, internet: true } });
93
+ const next = applyMeshSwitch(closed, { scope: "all", off: false, at: "T" });
94
+ assert.equal(next.lan, false);
95
+ assert.equal(next.internet, false);
96
+ });
97
+
98
+ test("applyMeshSwitch 不修改入参", () => {
99
+ const before = { lan: false, internet: true, at: "", by: "" };
100
+ const frozen = JSON.stringify(before);
101
+ applyMeshSwitch(before, { scope: "all", off: true });
102
+ assert.equal(JSON.stringify(before), frozen);
103
+ });
104
+
105
+ test("off 漏传时按「关闭」处理(一键关闭是主动作)", () => {
106
+ const next = applyMeshSwitch(resolveMeshSwitch({}), { scope: "lan" });
107
+ assert.equal(next.lan, true);
108
+ });
109
+
110
+ console.log("\n── 范围归一化:中英文都收,不认识的必须报错而不是乱猜 ──");
111
+
112
+ test("英文 id 与界面中文词都能识别", () => {
113
+ assert.equal(normalizeSwitchScope("all"), "all");
114
+ assert.equal(normalizeSwitchScope("LAN"), "lan");
115
+ assert.equal(normalizeSwitchScope(" 互联网 "), "internet");
116
+ assert.equal(normalizeSwitchScope("局域网 mesh"), "lan");
117
+ assert.equal(normalizeSwitchScope("全部"), "all");
118
+ });
119
+
120
+ test("不认识的 scope 直接抛错(不静默关掉全部,也不静默什么都不做)", () => {
121
+ for (const bad of ["", "everything", "wifi", null, undefined, 0]) {
122
+ assert.throws(() => applyMeshSwitch(resolveMeshSwitch({}), { scope: bad }), /未知的开关范围/);
123
+ }
124
+ });
125
+
126
+ test("MESH_SWITCH_SCOPES 与界面顺序一致", () => {
127
+ assert.deepEqual(MESH_SWITCH_SCOPES, ["all", "lan", "internet"]);
128
+ });
129
+
130
+ console.log("\n── 摘要文案:读的人要能判断现在能不能派任务 ──");
131
+
132
+ test("全部关闭时明确说「全部关闭」", () => {
133
+ assert.match(describeMeshSwitch({ lan: true, internet: true }), /全部关闭/);
134
+ });
135
+ test("只说一个范围时,另一个也要说清楚是开着的", () => {
136
+ const txt = describeMeshSwitch({ lan: true, internet: false });
137
+ assert.match(txt, /局域网 已关闭/);
138
+ assert.match(txt, /互联网 开启/);
139
+ });
140
+
141
+ console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
142
+ process.exit(failed === 0 ? 0 : 1);
@@ -16,7 +16,18 @@ import { tmpdir } from "node:os";
16
16
  import { dirname, join } from "node:path";
17
17
  import { detectTarget, assetName, candidateUrls, binDir, binaryPath, binaryInfo, cacheIsCurrent, downloadToBuffer, SIDECAR_PROTOCOL } from "./tsnet/download.js";
18
18
  import { PINNED_CHECKSUMS } from "./tsnet/checksums.js";
19
- import { toHostname, TsnetNode } from "./tsnet/manager.js";
19
+ import {
20
+ toHostname,
21
+ TsnetNode,
22
+ channelKey,
23
+ channelDir,
24
+ channelStateDir,
25
+ extractLoginFailure,
26
+ explainTailnetFailure,
27
+ evaluateTailnetProgress,
28
+ TSNET_STALL_MS,
29
+ } from "./tsnet/manager.js";
30
+ import { resolveTailnetChannels } from "./tsnet/channels.js";
20
31
  import { tailnetOrigin, isTailnetAddress } from "./tsnet/bridge.js";
21
32
  import { MeshDiscovery, orderedEndpoints, endpointAlive } from "./discovery.js";
22
33
  import { conversationKey, replyTarget } from "./conversation.js";
@@ -294,6 +305,177 @@ check("一条通道过期不会删掉设备(另一条还活着)", () => {
294
305
  assert.ok(d.peers()[0].endpoints.length === 2);
295
306
  });
296
307
 
308
+ check("多 tailnet:同一台设备两条 tailnet 端点互不覆盖", () => {
309
+ const d = new MeshDiscovery({ id: "self-1", port: 45917, meta: { machine: "me" } });
310
+ d.note({ app: "dsh-mesh", id: "dev", machine: "hos", host: "192.168.1.7", port: 45917 }, "192.168.1.7");
311
+ d.note({ app: "dsh-mesh", id: "dev", machine: "hos", host: "192.168.1.7", port: 45917 }, "100.64.0.9", {
312
+ transport: "tsnet",
313
+ channel: "tsnet:personal",
314
+ });
315
+ // 第二个 tailnet 给出**同一个** 100.x 地址(不同 tailnet 的 CGNAT 网段可以重叠)
316
+ d.note({ app: "dsh-mesh", id: "dev", machine: "hos", host: "192.168.1.7", port: 45917 }, "100.64.0.9", {
317
+ transport: "tsnet",
318
+ channel: "tsnet:company",
319
+ });
320
+ const p = d.peers().find((x) => x.id === "dev");
321
+ assert.equal(p.endpoints.length, 3, `应有 lan + 两条 tailnet,实际 ${p.endpoints.length}`);
322
+ const keys = p.endpoints.map((e) => e.channel).sort();
323
+ assert.deepEqual(keys, ["lan", "tsnet:company", "tsnet:personal"]);
324
+
325
+ // 一条 tailnet 失败不该影响另一条
326
+ d.markEndpoint("dev", "tsnet:personal", { ok: false });
327
+ d.markEndpoint("dev", "tsnet:personal", { ok: false });
328
+ const after = d.peers().find((x) => x.id === "dev");
329
+ assert.equal(after.online, true, "company 通道还通,设备必须仍在线");
330
+ const company = after.endpoints.find((e) => e.channel === "tsnet:company");
331
+ assert.equal(company.downUntil, 0, "company 通道不应被 personal 的失败连坐");
332
+ });
333
+
334
+ check("多 tailnet:名片里的 tailnetIps 每个地址各记一条候选端点", () => {
335
+ const d = new MeshDiscovery({ id: "self-1", port: 45917, meta: { machine: "me" } });
336
+ d.note(
337
+ {
338
+ app: "dsh-mesh",
339
+ id: "dev",
340
+ machine: "hos",
341
+ host: "192.168.1.7",
342
+ port: 45917,
343
+ tailnetIps: ["100.64.0.9", "100.88.0.3"],
344
+ },
345
+ "192.168.1.7",
346
+ );
347
+ const p = d.peers().find((x) => x.id === "dev");
348
+ const cands = p.endpoints.filter((e) => e.candidate === true);
349
+ assert.equal(cands.length, 2, `应有两个候选地址,实际 ${cands.length}`);
350
+ assert.deepEqual(cands.map((e) => e.host).sort(), ["100.64.0.9", "100.88.0.3"]);
351
+ assert.ok(cands.every((e) => e.verified === false), "候选端点一律不算已验证");
352
+ assert.equal(p.online, true, "局域网端点仍然在线");
353
+ });
354
+
355
+ check("多 tailnet:老对端的单个 tailnetIp 仍能被识别", () => {
356
+ const d = new MeshDiscovery({ id: "self-1", port: 45917, meta: { machine: "me" } });
357
+ d.note({ app: "dsh-mesh", id: "dev", machine: "hos", host: "192.168.1.7", port: 45917, tailnetIp: "100.64.0.9" }, "192.168.1.7");
358
+ const p = d.peers().find((x) => x.id === "dev");
359
+ assert.equal(p.endpoints.filter((e) => e.transport === "tsnet").length, 1);
360
+ });
361
+
362
+ check("多 tailnet:快照恢复保留通道 key,不把两条 tailnet 合并成一条", () => {
363
+ const d = new MeshDiscovery({ id: "self-1", port: 45917, meta: { machine: "me" } });
364
+ d.restore([
365
+ {
366
+ record: { app: "dsh-mesh", id: "dev", machine: "hos", host: "192.168.1.7", port: 45917 },
367
+ endpoints: [
368
+ { channel: "lan", transport: "lan", host: "192.168.1.7", port: 45917, lastSeen: Date.now() },
369
+ { channel: "tsnet:a", transport: "tsnet", host: "100.64.0.9", port: 45917, lastSeen: Date.now() },
370
+ { channel: "tsnet:b", transport: "tsnet", host: "100.88.0.3", port: 45917, lastSeen: Date.now() },
371
+ ],
372
+ },
373
+ ]);
374
+ const p = d.peers().find((x) => x.id === "dev");
375
+ assert.equal(p.endpoints.length, 3, `恢复后应保留 3 条端点,实际 ${p.endpoints.length}`);
376
+ assert.equal(p.restored, true);
377
+ assert.ok(p.endpoints.some((e) => e.channel === "tsnet:b"));
378
+ });
379
+
380
+ check("多 tailnet:设备上的 tailnetIps 会随名片对外广播", () => {
381
+ const d = new MeshDiscovery({ id: "self-1", port: 45917, meta: { machine: "me" } });
382
+ d.setMeta({ tailnetIps: ["100.64.0.9", "100.88.0.3"] });
383
+ const rec = d.selfRecord();
384
+ assert.deepEqual(rec.tailnetIps, ["100.64.0.9", "100.88.0.3"]);
385
+ assert.equal(rec.tailnetIp, "100.64.0.9", "老字段要保留第一项,供老对端读取");
386
+ });
387
+
388
+ check("通道 id 只保留安全字符,空值落到 default", () => {
389
+ assert.equal(channelKey("Company Tailnet"), "company-tailnet");
390
+ assert.equal(channelKey("../../etc/passwd"), "etc-passwd");
391
+ assert.equal(channelKey(""), "default");
392
+ assert.equal(channelKey("!!!"), "default");
393
+ });
394
+
395
+ check("default 沿用旧目录,其它通道各自独立(身份不能共享)", () => {
396
+ const prev = process.env.DSH_HOME;
397
+ const home = mkdtempSync(join(tmpdir(), "mesh-selftest-channels-"));
398
+ process.env.DSH_HOME = home;
399
+ try {
400
+ const root = join(home, "mesh", "tsnet");
401
+ assert.equal(channelDir("default"), root, "default 必须是旧布局,升级不丢设备身份");
402
+ assert.equal(channelDir("company"), join(root, "company"));
403
+ assert.notEqual(channelStateDir("company"), channelStateDir("personal"));
404
+ assert.equal(channelStateDir("company"), join(root, "company", "state"));
405
+ } finally {
406
+ if (prev === undefined) delete process.env.DSH_HOME;
407
+ else process.env.DSH_HOME = prev;
408
+ rmSync(home, { recursive: true, force: true });
409
+ }
410
+ });
411
+
412
+ check("TsnetNode 暴露通道 id/label,且签名随授权码变化(不泄露明文)", () => {
413
+ const a = new TsnetNode({ channel: { id: "company", label: "公司", authKey: "tskey-auth-aaa", controlUrl: "", hostname: "" }, machineName: "mac" });
414
+ const b = new TsnetNode({ channel: { id: "company", label: "公司", authKey: "tskey-auth-bbb", controlUrl: "", hostname: "" }, machineName: "mac" });
415
+ assert.equal(a.channelKey, "company");
416
+ assert.equal(a.label, "公司");
417
+ assert.notEqual(a.signature, b.signature, "换授权码后必须判定为配置变更,否则会留在旧 tailnet");
418
+ assert.equal(a.signature.length, 12);
419
+ assert.ok(!a.signature.includes("tskey"), "签名里不能出现授权码明文");
420
+ // 旧调用方式(只传 config)仍然工作,并落到 default 通道
421
+ const legacy = new TsnetNode({ config: { tsnetAuthKey: "tskey-auth-ccc" }, machineName: "mac" });
422
+ assert.equal(legacy.channelKey, "default");
423
+ });
424
+
425
+ check("通道解析:配置优先于 state.json", () => {
426
+ const list = resolveTailnetChannels({
427
+ config: { tsnetChannels: [{ id: "corp", label: "公司", authKey: "k1", enabled: true }] },
428
+ state: { tsnetChannels: [{ id: "home", label: "家里", authKey: "k2", enabled: true }] },
429
+ });
430
+ assert.equal(list.length, 1);
431
+ assert.equal(list[0].id, "corp");
432
+ assert.equal(list[0].source, "config");
433
+ });
434
+
435
+ check("通道解析:没有通道列表时退回旧版单 key,并落到 default", () => {
436
+ const list = resolveTailnetChannels({ config: {}, state: { tsnetAuthKey: "tskey-auth-old", tsnetEnabled: true } });
437
+ assert.equal(list.length, 1);
438
+ assert.equal(list[0].id, "default");
439
+ assert.equal(list[0].legacy, true);
440
+ assert.equal(list[0].authKey, "tskey-auth-old");
441
+ assert.equal(list[0].enabled, true);
442
+ });
443
+
444
+ check("通道解析:没给 id 的通道按 label + 控制服务器推导稳定 id", () => {
445
+ const a = resolveTailnetChannels({ config: { tsnetChannels: [{ label: "公司", controlUrl: "https://hs.example" }] } });
446
+ const b = resolveTailnetChannels({ config: { tsnetChannels: [{ label: "公司", controlUrl: "https://hs.example" }] } });
447
+ assert.match(a[0].id, /^ch-[0-9a-f]{10}$/);
448
+ assert.equal(a[0].id, b[0].id, "同样的配置必须得到同一个 id(否则每次重启都重新注册设备)");
449
+ const renamed = resolveTailnetChannels({ config: { tsnetChannels: [{ label: "公司2", controlUrl: "https://hs.example" }] } });
450
+ assert.notEqual(renamed[0].id, a[0].id, "推导 id 依赖显示名,改名前必须显式固定 id(文档已注明)");
451
+ });
452
+
453
+ check("通道解析:重复 id 自动去重,不会共享 sidecar 状态目录", () => {
454
+ const list = resolveTailnetChannels({
455
+ config: {
456
+ tsnetChannels: [
457
+ { id: "dup", label: "A" },
458
+ { id: "dup", label: "B" },
459
+ ],
460
+ },
461
+ });
462
+ assert.equal(list.length, 2);
463
+ assert.notEqual(list[0].id, list[1].id);
464
+ });
465
+
466
+ check("通道解析:enabled 默认 true,显式 false 才停用", () => {
467
+ const list = resolveTailnetChannels({
468
+ config: {
469
+ tsnetChannels: [
470
+ { id: "a", label: "A" },
471
+ { id: "b", label: "B", enabled: false },
472
+ ],
473
+ },
474
+ });
475
+ assert.equal(list[0].enabled, true);
476
+ assert.equal(list[1].enabled, false);
477
+ });
478
+
297
479
  console.log("\n── 身份:指纹认领与冲突 ──");
298
480
 
299
481
  check("同指纹不同 instanceId → 认领为同一台(旧记录立刻淘汰)", () => {
@@ -668,5 +850,80 @@ check("回信地址与会话键是两件事,不能混用", () => {
668
850
  assert.ok(!conversationKey(t).includes("sess-remote-123"));
669
851
  });
670
852
 
853
+ console.log("\n── 启动受阻:不能永远显示「正在启动」──");
854
+
855
+ check("从 sidecar 诊断里取出登录失败原因(真机 2026-10-29 原文)", () => {
856
+ const diag = [
857
+ "health(warnable=warming-up): ok",
858
+ "control: [v1] TryLogin: register request: Post \"https://controlplane.tailscale.com/machine/register\": connection attempts aborted by context: context deadline exceeded",
859
+ "health(warnable=login-state): error: You are logged out. The last login error was: register request: Post \"https://controlplane.tailscale.com/machine/register\": connection attempts aborted by context: context deadline exceeded",
860
+ "control: authRoutine: [v1] backoff: 50 msec",
861
+ ];
862
+ const text = extractLoginFailure(diag);
863
+ assert.match(text, /deadline exceeded/, text);
864
+ assert.ok(!text.startsWith("You are logged out"), "要去掉套话,只留能读的原因");
865
+ });
866
+
867
+ check("没有登录错误时返回空串(不要凭空编一个原因)", () => {
868
+ assert.equal(extractLoginFailure([]), "");
869
+ assert.equal(extractLoginFailure(["netmap: self: [x] ..."]), "");
870
+ assert.equal(extractLoginFailure(null), "");
871
+ });
872
+
873
+ check("超时类错误 → 提示检查代理(sidecar 走裸 TCP)", () => {
874
+ const hint = explainTailnetFailure("register request: ... context deadline exceeded");
875
+ assert.match(hint, /代理/);
876
+ assert.match(hint, /裸 TCP/);
877
+ });
878
+
879
+ check("授权码类错误 → 指向 Reusable auth key", () => {
880
+ assert.match(explainTailnetFailure("invalid key: empty"), /Reusable/);
881
+ assert.match(explainTailnetFailure("401 Unauthorized"), /Reusable/);
882
+ });
883
+
884
+ check("认不出的错误不给建议(宁可不猜)", () => {
885
+ assert.equal(explainTailnetFailure("something odd happened"), "");
886
+ assert.equal(explainTailnetFailure(""), "");
887
+ });
888
+
889
+ check("受阻阈值足够长:正常的十几秒握手不会被误报", () => {
890
+ assert.ok(TSNET_STALL_MS >= 60000, `TSNET_STALL_MS=${TSNET_STALL_MS}`);
891
+ });
892
+
893
+ check("卡满阈值 → 判受阻;刚启动 / 已有地址 / 等授权都不算", () => {
894
+ const now = 1_000_000;
895
+ const base = { now, stallMs: 60000, startingSince: now - 61000 };
896
+ assert.equal(evaluateTailnetProgress({ ...base, phase: "starting" }).stalled, true, "卡了 61s 应判受阻");
897
+ assert.equal(evaluateTailnetProgress({ ...base, phase: "starting", selfIpv4: "100.64.0.9" }).stalled, false, "有地址不算受阻");
898
+ assert.equal(evaluateTailnetProgress({ ...base, phase: "starting", authUrl: "https://x" }).stalled, false, "等授权不算受阻");
899
+ assert.equal(evaluateTailnetProgress({ ...base, startingSince: now - 1000, phase: "starting" }).stalled, false, "刚启动不算");
900
+ assert.equal(evaluateTailnetProgress({ ...base, phase: "running" }).stalled, false, "已连接不算");
901
+ assert.equal(evaluateTailnetProgress({ ...base, phase: "starting", startingSince: 0 }).stalled, false, "没有计时不清空前提");
902
+ });
903
+
904
+ check("needs-login 但没有授权链接 → 也算受阻(实测形状:只显示「需要授权」却没链接可点)", () => {
905
+ const now = 1_000_000;
906
+ const base = { now, stallMs: 60000, startingSince: now - 61000, selfIpv4: "" };
907
+ assert.equal(evaluateTailnetProgress({ ...base, phase: "needs-login", authUrl: "" }).stalled, true);
908
+ assert.equal(evaluateTailnetProgress({ ...base, phase: "needs-login", authUrl: "https://login" }).stalled, false);
909
+ });
910
+
911
+ check("受阻状态从 starting 变来,恢复时退回 starting(不谎报已连接)", () => {
912
+ const now = 1_000_000;
913
+ const stalled = evaluateTailnetProgress({ phase: "starting", startingSince: now - 120000, now, stallMs: 60000 });
914
+ assert.equal(stalled.phase, "stalled");
915
+ const recovering = evaluateTailnetProgress({ phase: "stalled", startingSince: now - 120000, now, stallMs: 60000, selfIpv4: "100.64.0.9" });
916
+ assert.equal(recovering.stalled, false);
917
+ assert.equal(recovering.phase, "starting");
918
+ });
919
+
920
+ check("新节点默认不显示受阻,且带 stalled 字段给界面用", () => {
921
+ const node = new TsnetNode({ channel: { id: "t1", label: "T", authKey: "", controlUrl: "", hostname: "" }, machineName: "m" });
922
+ const st = node.status();
923
+ assert.equal(st.stalled, false);
924
+ assert.equal(st.stalledReason, "");
925
+ assert.equal(st.phase, "idle");
926
+ });
927
+
671
928
  console.log(`\n结果:${passed} 通过,${failed} 失败\n`);
672
929
  process.exit(failed === 0 ? 0 : 1);