ssh-net 26.10.35 → 26.10.36

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/CHANGELOG.md CHANGED
@@ -7,6 +7,27 @@
7
7
  GitHub Release(Actions 自动跑测试后 npm publish;跳号与 0.x 的完整
8
8
  考据见 git 史)。
9
9
 
10
+ ## [26.10.36] - 2026-10-03
11
+
12
+ ### 精简:清单单一来源补齐 + 一个报名竞态修复
13
+
14
+ - **uplink-edge 组件清单三处合一**:core install、`_register` 报名对账、
15
+ status 体检此前各抄一份实体/软链知识,收敛进 manifest
16
+ (`edgeCallbacksPlan`/`linkAddonPlan`),`install --without-link` 的
17
+ 删除也由清单驱动;脚本名改常量引用,改名一处即可
18
+ - **报名 ssh 两源对齐**:`start peer` 的 ConnectTimeout 15 与额外保活
19
+ 选项是相对 design 冻结表(5s)的静默漂移,改为与 sn-route 现场报名
20
+ 完全同形(外层 60s timeout 仍兜底挂死)
21
+ - **sn-route 单飞竞态修复**:leader 报名秒败删锁的瞬间,晚启动的
22
+ follower 可能夹在「印记已写、锁已删」之间误接管、重复报名;抢空锁后
23
+ 复查 PROBE_FAIL,新鲜则认 follower 不报名
24
+ - **退役产物清理统一**:bin/state/conf.d 三类退役清单合并为 STALE_FILES;
25
+ stop 的进程收束不再偷删开关(策略回命令层);lsof 预检两跑合一;
26
+ launchd/systemd 若干死代码清理
27
+ - **测试**:命令测试沙箱收敛为 makeCommandHarness(t.after 自动回收,
28
+ 失败不泄漏临时目录)、fixture 加载单一入口、镜像脚手架合并;新增报名
29
+ argv/label 公式/片段名三处跨语言锚测试;全套 9.6s→7.5s
30
+
10
31
  ## [26.10.35] - 2026-10-03
11
32
 
12
33
  ### 精简:控制面重复收敛(纯内部重构,对外行为不变)
package/libexec/cli.mjs CHANGED
@@ -77,7 +77,7 @@ function buildContext() {
77
77
  role: self.role,
78
78
  runner: createRunner(env),
79
79
  state: createStateStore(paths),
80
- uid: typeof process.getuid === 'function' ? process.getuid() : null,
80
+ uid: process.getuid(),
81
81
  };
82
82
  }
83
83
 
@@ -2,7 +2,7 @@
2
2
  // show:它会 probe、经 relay 报名、等回拨(6s 预算),进度直接显示在终端。
3
3
  // doctor 只负责关态分诊与结果转述。不新增状态、不踢常驻服务(默认形态没有
4
4
  // 常驻)。仅 edge 有动作:core 的恢复靠 edge 报名,node 由 systemd 自动重启。
5
- import path from 'node:path';
5
+ import { SN_ROUTE } from '../lib/manifest.mjs';
6
6
  import { snRouteArgv } from '../lib/render.mjs';
7
7
 
8
8
  export async function run(ctx) {
@@ -19,7 +19,7 @@ export async function run(ctx) {
19
19
  // stdio:'inherit':sn-route 进度直达终端,同时其 [ -t 2 ] 才成立;
20
20
  // timeout 略大于 6s 预算
21
21
  const r = ctx.runner.runRaw(
22
- path.join(paths.binDir, 'sn-route'),
22
+ paths.binScript(SN_ROUTE),
23
23
  snRouteArgv(topo, self.alias, 'show'),
24
24
  { stdio: 'inherit', timeout: 8000 },
25
25
  );
@@ -13,16 +13,19 @@ import { ensureRuntime } from '../lib/runtime.mjs';
13
13
  import * as launchd from '../lib/launchd.mjs';
14
14
  import * as systemd from '../lib/systemd.mjs';
15
15
  import {
16
- classifyLocalPort, listV6LoopbackListeners, processTree,
16
+ classifyLocalPort, lsofListen, v6LoopbackPids, processTree,
17
17
  peerProbeOk,
18
18
  } from '../lib/probe.mjs';
19
19
  import { writeFileAtomic } from '../lib/fsutil.mjs';
20
- import { edgeRuntimePlan, relayRuntimePlan } from '../lib/manifest.mjs';
20
+ import {
21
+ SN_PROBE, edgeRuntimePlan, relayRuntimePlan,
22
+ edgeCallbacksPlan, linkAddonPlan, mergePlans,
23
+ } from '../lib/manifest.mjs';
21
24
  import { edgeFragmentContent, edgeFragmentShouldExist } from '../lib/registration.mjs';
22
25
  import {
23
- linkLabel, linkLinkName,
26
+ linkLabel,
24
27
  relayLabel, relayUnitName,
25
- edgeLabel, edgeLinkName,
28
+ edgeLabel,
26
29
  plistFileName,
27
30
  renderEdgeLinkPlist, renderRelayPlist, renderRelayUnit, renderRoutes,
28
31
  } from '../lib/render.mjs';
@@ -60,8 +63,7 @@ async function precheckEdgePorts(ctx, linkOn) {
60
63
  for (const port of forwardPorts) {
61
64
  const c = classifyLocalPort(runner, port, jobPid, tree);
62
65
  if (c.kind === 'foreign') {
63
- const who = runner.run('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN']).stdout.trim();
64
- throw new Error(`端口 ${port} 被非本服务进程占用(pid ${c.pids.join(',')}):\n${who}`);
66
+ throw new Error(`端口 ${port} 被非本服务进程占用(pid ${c.pids.join(',')}):\n${lsofListen(runner, port)}`);
65
67
  }
66
68
  }
67
69
  }
@@ -69,16 +71,16 @@ async function precheckEdgePorts(ctx, linkOn) {
69
71
  // 10022 持口者永远是本机 sshd,无法按 pid 溯源:读到 SSH banner 才认。
70
72
  // 只盯 [::1](peer 全 v6 环回后的本服务监听面;127.0.0.1:10022 的持有
71
73
  // 者如 VS Code 本地转发与本服务可共存,2026-09-30 起不判冲突——edge 实案)。
72
- // 首装时 bin/sn-probe 还没拷上,探针缺失不判僵尸(install 随后就拷)
73
- const holders = listV6LoopbackListeners(runner, CALLBACK_PORT);
74
+ // 一次 lsof 同时拿持有者 pid 与报错展示文本;首装时 bin/sn-probe 还没拷上,
75
+ // 探针缺失不判僵尸(install 随后就拷)
76
+ const listeners = lsofListen(runner, CALLBACK_PORT);
74
77
  if (
75
- holders.length > 0
76
- && fs.existsSync(path.join(paths.binDir, 'sn-probe'))
78
+ v6LoopbackPids(listeners, CALLBACK_PORT).length > 0
79
+ && fs.existsSync(paths.binScript(SN_PROBE))
77
80
  && !(await peerProbeOk(runner, paths.binDir))
78
81
  ) {
79
- const who = runner.run('lsof', ['-nP', `-iTCP:${CALLBACK_PORT}`, '-sTCP:LISTEN']).stdout.trim();
80
82
  throw new Error(
81
- `端口 ${CALLBACK_PORT} 在听但读不到 SSH banner(僵尸监听或他进程占用):\n${who}`,
83
+ `端口 ${CALLBACK_PORT} 在听但读不到 SSH banner(僵尸监听或他进程占用):\n${listeners}`,
82
84
  );
83
85
  }
84
86
  }
@@ -140,18 +142,14 @@ async function installEdge(ctx, args) {
140
142
  // 默认零常驻:清掉旧版/加装过的 link 全部产物。升级时旧 plist 必须
141
143
  // bootout,否则 launchd 每 ThrottleInterval 刷 ENOENT
142
144
  removeJob(ctx, label, plistPath);
143
- fs.rmSync(path.join(paths.binDir, 'ssh-net-link-core'), { force: true });
144
- fs.rmSync(path.join(paths.binDir, linkLinkName(topo.core.alias)), { force: true });
145
- // 退役状态残留(26.10.31 退役;按约定一个月后删本两行)
146
- fs.rmSync(path.join(paths.stateDir, 'ROUTE_PEER'), { force: true });
147
- fs.rmSync(path.join(paths.stateDir, 'LINK_ON'), { force: true });
145
+ const addon = linkAddonPlan(topo);
146
+ for (const [name] of [...addon.entities, ...addon.links])
147
+ fs.rmSync(paths.binScript(name), { force: true });
148
148
  }
149
149
 
150
150
  // conf.d 片段(design §4.2):edge 是 routes 的唯一安装角色——routes 含
151
151
  // 选路 Match 与尾部 VS Code 打标块;新签名带本机别名
152
152
  const routesChanged = syncConfFile(paths.routesFile, renderRoutes(topo, ctx.self.alias));
153
- // 打标块并入 routes 后的旧文件清理(26.10.32 退役;按约定一个月后删本行)
154
- fs.rmSync(path.join(paths.confDir, 'vscode-mark'), { force: true });
155
153
  const fragMsg = routesChanged ? '(选路片段已更新)' : '';
156
154
  if (!comp && !routesChanged && flag === undefined) {
157
155
  return linkOn
@@ -170,11 +168,8 @@ function installCore(ctx) {
170
168
  // 软链):否则 upgrade 后 core status 要对每台未联系的 edge 报组件异常,
171
169
  // 直到它下次报名才自愈(2026-09-30 补)
172
170
  const edges = launchd.edgeAliasesOnDisk(paths.launchAgentsDir);
173
- // relay 基础形态 + 磁盘在册 edge 的回拨组件(一份实体,每台一条带别名软链)
174
- const plan = relayRuntimePlan(topo);
175
- if (edges.length > 0)
176
- plan.entities.push(['ssh-net-uplink-edge', 'ssh-net-uplink-edge']);
177
- plan.links.push(...edges.map((alias) => [edgeLinkName(alias), 'ssh-net-uplink-edge']));
171
+ // relay 基础形态 + 磁盘在册 edge 的回拨组件(清单与报名/status 体检同源)
172
+ const plan = mergePlans(relayRuntimePlan(topo), edgeCallbacksPlan(edges));
178
173
  const comp = compNote(ensureRuntime(ctx, plan.entities, plan.links));
179
174
  const label = relayLabel(topo.relay.alias);
180
175
  const content = renderRelayPlist({
@@ -21,15 +21,16 @@ import { readFileOrNull } from '../lib/fsutil.mjs';
21
21
  import {
22
22
  writeEdgeRegistration, removeEdgeRegistration,
23
23
  } from '../lib/registration.mjs';
24
+ import { edgeCallbacksPlan } from '../lib/manifest.mjs';
24
25
  import {
25
- edgeLabel, edgeLinkName, plistFileName, renderUplinkEdgePlist, coreViaRelayArgs,
26
+ edgeLabel, plistFileName, renderUplinkEdgePlist, coreViaRelayArgs,
26
27
  } from '../lib/render.mjs';
27
28
 
28
29
  /** edge 侧报名:取 v6 + 命令行 -J 经 relay 调 core 的 _register。
29
30
  * start peer 用——控制面直接报一次名让 core 马上回拨。 */
30
31
  function runEdgeAnnounce(ctx) {
31
32
  const probe = ctx.runner.runRaw(
32
- path.join(ctx.paths.binDir, 'sn-ipv6'), [], { timeout: 5000 },
33
+ ctx.paths.binScript('sn-ipv6'), [], { timeout: 5000 },
33
34
  );
34
35
  // bin/sn-ipv6 缺失(未 install)别误报成「无 IPv6」。fatal 哨兵属性:
35
36
  // enablePeer 靠它区分「没有现场选路可指望」的致命错与可重试的报名失败,
@@ -54,12 +55,12 @@ function runEdgeAnnounce(ctx) {
54
55
  const v6Err = explainV6Error(v6);
55
56
  if (v6Err) throw new Error(`本机 v6 选取异常(sn-ipv6 输出不是可报名地址:${v6Err})`);
56
57
  // 报名固定走 relay(relay 7×24 在;peer 僵尸时自动选路会把报名一起挂死)。
57
- // 无人值守首连信任 accept-new(探测侧 status 不带它,差异在 coreViaRelayArgs
58
- // 显式)+ IdentitiesOnly 防多 key 试错撞 MaxAuthTries(design §4.3)。
58
+ // argv 与 sn-route 的现场报名完全同一形态(coreViaRelayArgs 默认 ConnectTimeout
59
+ // 5,design §3 冻结):无人值守首连信任 accept-new(探测侧 status 不带它,
60
+ // 差异在 coreViaRelayArgs 显式)+ IdentitiesOnly 防多 key 试错撞 MaxAuthTries
61
+ //(design §4.3)。挂死由外层 60s timeout 兜底
59
62
  const r = ctx.runner.run('ssh', coreViaRelayArgs(ctx.topo, {
60
- connectTimeout: 15,
61
63
  acceptHost: true,
62
- extraOpts: ['-o', 'ServerAliveInterval=10', '-o', 'ServerAliveCountMax=2'],
63
64
  remoteCommand: `ssh-net _register ${ctx.self.alias} ${v6}`,
64
65
  }), { timeout: 60_000 });
65
66
  if (r.code !== 0)
@@ -141,9 +142,8 @@ export function runRegister(ctx, args = []) {
141
142
 
142
143
  // 脚本对账无条件先行(幂等):脚本被删/过期/参数变更时,四个状态分支
143
144
  // 里的任何一个都可能成为重建通道,不能只靠首次报名那一次
144
- ensureRuntime(ctx,
145
- [['ssh-net-uplink-edge', 'ssh-net-uplink-edge']],
146
- [[edgeLinkName(alias), 'ssh-net-uplink-edge']]);
145
+ const plan = edgeCallbacksPlan([alias]);
146
+ ensureRuntime(ctx, plan.entities, plan.links);
147
147
 
148
148
  // 未注册(首次报名)或已注册但渲染结果与磁盘不符(topology 的 user 等变了):
149
149
  // 重新部署。syncPlist 走 bootout→落盘→enable→bootstrap,bootstrap 即首发,
@@ -5,7 +5,6 @@
5
5
  // 状态」。
6
6
  import fs from 'node:fs';
7
7
  import path from 'node:path';
8
- import * as launchd from '../lib/launchd.mjs';
9
8
  import * as systemd from '../lib/systemd.mjs';
10
9
  import { ensureLoaded } from '../lib/manage.mjs';
11
10
  import { assertUnitSwitchArgs } from '../lib/cliargs.mjs';
@@ -7,7 +7,6 @@
7
7
  // bin/ 体检(2026-09-30 软链方案):实体逐字节比对 + 服务软链指向/悬空检查。
8
8
  // 退出码:健康(含 edge 关闭态)0;有可行动问题 1。
9
9
  import fs from 'node:fs';
10
- import path from 'node:path';
11
10
  import {
12
11
  auditScript, auditLink, runtimeVersionIssue,
13
12
  } from '../lib/runtime.mjs';
@@ -16,11 +15,14 @@ import * as launchd from '../lib/launchd.mjs';
16
15
  import * as systemd from '../lib/systemd.mjs';
17
16
  import { peerProbeOk, tcpOpen } from '../lib/probe.mjs';
18
17
  import { readFileOrNull } from '../lib/fsutil.mjs';
19
- import { edgeRuntimePlan, relayRuntimePlan } from '../lib/manifest.mjs';
18
+ import {
19
+ SN_ROUTE, SN_IPV6, UPLINK_EDGE,
20
+ edgeRuntimePlan, relayRuntimePlan, edgeCallbacksPlan,
21
+ } from '../lib/manifest.mjs';
20
22
  import { edgeFragmentContent, edgeFragmentShouldExist } from '../lib/registration.mjs';
21
23
  import {
22
24
  linkLabel, relayLabel, relayUnitName,
23
- edgeLabel, edgeLinkName,
25
+ edgeLabel,
24
26
  renderRoutes, coreViaRelayArgs,
25
27
  } from '../lib/render.mjs';
26
28
 
@@ -34,13 +36,17 @@ function auditConfFragment(file, expected) {
34
36
  return text === expected ? 'ok' : 'stale';
35
37
  }
36
38
 
37
- /** 各角色共用的实体+软链体检,返回人话问题列表(空=健康)。 */
39
+ /**
40
+ * 各角色共用的实体+软链体检。
41
+ * @returns {{issues:string[], entityAudits:{name:string,audit:string}[]}}
42
+ * issues 是人话问题列表(空=健康)
43
+ */
38
44
  function runtimeIssues(ctx, { entities, links }) {
39
45
  const issues = [];
40
46
  // 实体逐字节比对(name 是 bin 实体名,不是软链)
41
47
  const entityAudits = entities.map(([name, script]) => ({
42
48
  name,
43
- audit: auditScript(path.join(ctx.paths.binDir, name), packageScriptPath(script)),
49
+ audit: auditScript(ctx.paths.binScript(name), packageScriptPath(script)),
44
50
  }));
45
51
  if (entityAudits.some((a) => a.audit === 'stale'))
46
52
  issues.push('隧道组件与所装版本不一致——跑一次 ssh-net install 刷新');
@@ -50,13 +56,23 @@ function runtimeIssues(ctx, { entities, links }) {
50
56
  // 部分缺失:探针丢了会让开着的隧道恒判中继,不能只显示不报
51
57
  issues.push(`隧道组件不完整(缺 ${entityAudits.filter((a) => a.audit === 'missing').map((a) => a.name).join('、')})——跑一次 ssh-net install 修复`);
52
58
  for (const [linkName, entityName] of links) {
53
- const r = auditLink(path.join(ctx.paths.binDir, linkName), entityName);
59
+ const r = auditLink(ctx.paths.binScript(linkName), entityName);
54
60
  if (r !== 'ok')
55
61
  issues.push(`隧道组件异常(${linkName}:${r})——跑一次 ssh-net install 修复`);
56
62
  }
57
63
  return { issues, entityAudits };
58
64
  }
59
65
 
66
+ /** 三个 collector 的共同前奏:版本戳问题 + 实体/软链体检。 */
67
+ function baseAudit(ctx, plan) {
68
+ const issues = [];
69
+ const vIssue = runtimeVersionIssue(ctx.paths);
70
+ if (vIssue) issues.push(vIssue);
71
+ const { issues: rtIssues, entityAudits } = runtimeIssues(ctx, plan);
72
+ issues.push(...rtIssues);
73
+ return { issues, entityAudits };
74
+ }
75
+
60
76
  /** forward 的人话标签:写出目标(loopback 是落地机环回)。 */
61
77
  function forwardLabel(f) {
62
78
  const target = f.targetAlias === 'loopback'
@@ -104,20 +120,16 @@ async function relayPathOk(ctx) {
104
120
 
105
121
  async function collectEdge(ctx) {
106
122
  const { topo, paths, state } = ctx;
107
- const issues = [];
108
- const vIssue = runtimeVersionIssue(ctx.paths);
109
- if (vIssue) issues.push(vIssue);
110
123
  // link 附加件以 marker 为准:默认只有 3 实体、无服务软链;装了才加
111
124
  // link-core(转发口只取决于装没装,不是运行时开关)
112
125
  const linkInstalled = fs.existsSync(paths.linkEnabledFile);
113
126
  const plan = edgeRuntimePlan(topo, linkInstalled);
114
- const { issues: rtIssues, entityAudits } = runtimeIssues(ctx, plan);
115
- issues.push(...rtIssues);
127
+ const { issues, entityAudits } = baseAudit(ctx, plan);
116
128
 
117
129
  // routes 体检(sn-route 实体在才查:没装时 rtIssues 已报「尚未安装」):
118
130
  // routes 被手删/过期会让 ssh 静默退回 lan 直连,是故障、进 issues。文件尾部
119
131
  // 的 VS Code 打标块同属这份内容,逐字节对账一并覆盖,不用单独体检
120
- if (entityAudits.some((a) => a.name === 'sn-route' && a.audit === 'ok')) {
132
+ if (entityAudits.some((a) => a.name === SN_ROUTE && a.audit === 'ok')) {
121
133
  const routeAudit = auditConfFragment(paths.routesFile, renderRoutes(topo, ctx.self.alias));
122
134
  if (routeAudit !== 'ok')
123
135
  issues.push(`选路片段 conf.d/routes ${routeAudit === 'missing' ? '缺失' : '与 topology 不一致'}——跑一次 ssh-net install 刷新`);
@@ -139,9 +151,9 @@ async function collectEdge(ctx) {
139
151
  // 探测没跑成(超时/非零退出/实体缺失)时不能谎称「没有 IPv6」——那个
140
152
  // 结论只在 sn-ipv6 正常跑完且无输出时才成立
141
153
  const needV6 = (switches.relay || switches.peer)
142
- && entityAudits.some((a) => a.name === 'sn-ipv6' && a.audit === 'ok');
154
+ && entityAudits.some((a) => a.name === SN_IPV6 && a.audit === 'ok');
143
155
  const v6P = needV6
144
- ? ctx.runner.runRawAsync(path.join(paths.binDir, 'sn-ipv6'), [], { timeout: 5000 })
156
+ ? ctx.runner.runRawAsync(paths.binScript(SN_IPV6), [], { timeout: 5000 })
145
157
  : Promise.resolve(null);
146
158
 
147
159
  // 就绪实测并发(On 是意图、ready 是事实;开关关的线路不探测=null)。
@@ -204,11 +216,7 @@ async function collectEdge(ctx) {
204
216
 
205
217
  async function collectCore(ctx) {
206
218
  const { topo, paths } = ctx;
207
- const issues = [];
208
- const vIssue = runtimeVersionIssue(ctx.paths);
209
- if (vIssue) issues.push(vIssue);
210
- const { issues: rtIssues } = runtimeIssues(ctx, relayRuntimePlan(topo));
211
- issues.push(...rtIssues);
219
+ const { issues } = baseAudit(ctx, relayRuntimePlan(topo));
212
220
 
213
221
  // disabled override 是整域同一份字典:relay job 与各 edge job 共用一次拉取
214
222
  const dmap = launchd.disabledMap(ctx.runner, ctx.uid);
@@ -217,11 +225,11 @@ async function collectCore(ctx) {
217
225
  // relay 口实测是 8s 超时的真 ssh:先发起来,边等边做下面的注册态体检
218
226
  const relayPortP = relayPortListening(ctx, topo.core.relayPort);
219
227
 
220
- // 回拨实体与 edge 别名无关:循环外体检一次,各 edge 只检各自的软链
221
- const callbackEntityAudit = auditScript(
222
- path.join(paths.binDir, 'ssh-net-uplink-edge'),
223
- packageScriptPath('ssh-net-uplink-edge'),
224
- );
228
+ // 回拨组件清单与 install/报名同源(manifest):实体与别名无关,循环外体检
229
+ // 一次,各已注册 edge 只检各自的带别名软链。topology 无 edge 时不审
230
+ const callbackEntityAudit = topo.edges.length > 0
231
+ ? auditScript(paths.binScript(UPLINK_EDGE), packageScriptPath(UPLINK_EDGE))
232
+ : null;
225
233
 
226
234
  const edges = [];
227
235
  for (const e of topo.edges) {
@@ -230,12 +238,10 @@ async function collectCore(ctx) {
230
238
  // 已连接过的随身机,回拨组件一并体检:回拨脚本/软链只有 _register
231
239
  // (报名)这条刷新通道,漏刷会拿旧脚本拨号
232
240
  if (st.registered) {
241
+ const [linkName, entityName] = edgeCallbacksPlan([e.alias]).links[0];
233
242
  const bad = [];
234
243
  if (callbackEntityAudit !== 'ok') bad.push('回拨脚本');
235
- const linkState = auditLink(
236
- path.join(paths.binDir, edgeLinkName(e.alias)),
237
- 'ssh-net-uplink-edge',
238
- );
244
+ const linkState = auditLink(paths.binScript(linkName), entityName);
239
245
  if (linkState !== 'ok') bad.push(`软链(${linkState})`);
240
246
  if (bad.length)
241
247
  // 已注册 edge 的实体/软链其实会被 install 刷新(26.9.19 起),但
@@ -287,11 +293,7 @@ async function collectCore(ctx) {
287
293
 
288
294
  async function collectNode(ctx) {
289
295
  const { topo } = ctx;
290
- const issues = [];
291
- const vIssue = runtimeVersionIssue(ctx.paths);
292
- if (vIssue) issues.push(vIssue);
293
- const { issues: rtIssues } = runtimeIssues(ctx, relayRuntimePlan(topo));
294
- issues.push(...rtIssues);
296
+ const { issues } = baseAudit(ctx, relayRuntimePlan(topo));
295
297
 
296
298
  const unit = relayUnitName(topo.relay.alias);
297
299
  const active = systemd.isActive(ctx.runner, unit);
@@ -6,7 +6,7 @@
6
6
  // node stop+disable。
7
7
  import * as launchd from '../lib/launchd.mjs';
8
8
  import * as systemd from '../lib/systemd.mjs';
9
- import { stopEdgeLink } from '../lib/jobctl.mjs';
9
+ import { reapEdgeLink } from '../lib/jobctl.mjs';
10
10
  import { assertUnitSwitchArgs } from '../lib/cliargs.mjs';
11
11
  import { relayLabel, relayUnitName } from '../lib/render.mjs';
12
12
 
@@ -45,9 +45,11 @@ export function run(ctx, args = []) {
45
45
  // 时 sn-route 不报名,自然只走中继
46
46
  return 'peer 已关闭(软生效:停止报名。已建立的连接继续用,断了重连就只走中继)';
47
47
  }
48
- // 全关 / 只关 relay:级联删两开关,硬停 link job(未装附加件则直接 gone)
48
+ // 全关 / 只关 relay:级联删两开关(peer 依赖 relay,见 design §5),
49
+ // 硬停 link job(PathState 见 RELAY_ON 消失不再重拉;未装附加件直接 gone)
49
50
  const alreadyAllOff = !before.relay && !before.peer;
50
- const { gone, label } = stopEdgeLink(ctx);
51
+ ctx.state.removeOn(['relay', 'peer']);
52
+ const { gone, label } = reapEdgeLink(ctx);
51
53
  if (!gone)
52
54
  throw new Error(
53
55
  `${label} 仍在运行(TERM 已发两次)。手工排查:launchctl print gui/${ctx.uid}/${label}`,
@@ -13,16 +13,22 @@ import {
13
13
 
14
14
  const rm = (p) => fs.rmSync(p, { recursive: true, force: true });
15
15
 
16
+ /** 三角色共同产物:整棵 bin/state/conf.d + 版本戳 + link 意图 marker
17
+ * (marker 只 edge 可能有,其余角色 force rm 不存在的文件无害)。 */
18
+ function removeArtifacts(ctx) {
19
+ rm(ctx.paths.binDir);
20
+ rm(ctx.paths.stateDir);
21
+ rm(ctx.paths.confDir);
22
+ rm(ctx.paths.runtimeVersionFile);
23
+ rm(ctx.paths.linkEnabledFile);
24
+ }
25
+
16
26
  function uninstallEdge(ctx) {
17
27
  const label = linkLabel(ctx.topo.core.alias);
18
28
  removeJob(ctx, label, path.join(
19
29
  ctx.paths.launchAgentsDir, plistFileName(label),
20
30
  ));
21
- rm(ctx.paths.binDir);
22
- rm(ctx.paths.stateDir);
23
- rm(ctx.paths.confDir); // routes(edge 装的);node 上不存在无害
24
- rm(ctx.paths.runtimeVersionFile);
25
- rm(ctx.paths.linkEnabledFile); // link 附加件意图
31
+ removeArtifacts(ctx);
26
32
  rm(path.join(ctx.paths.logsDir, `${label}.log`));
27
33
  return '已卸载。最后一步:npm uninstall -g ssh-net';
28
34
  }
@@ -45,10 +51,7 @@ function uninstallCore(ctx) {
45
51
  const relay = relayLabel(ctx.topo.relay.alias);
46
52
  removeJob(ctx, relay, path.join(dir, plistFileName(relay)));
47
53
 
48
- rm(ctx.paths.binDir);
49
- rm(ctx.paths.stateDir);
50
- rm(ctx.paths.confDir); // 全部 edge-<别名> 动态片段
51
- rm(ctx.paths.runtimeVersionFile);
54
+ removeArtifacts(ctx); // 全部 edge-<别名> 动态片段随 conf.d 整棵删
52
55
  for (const label of [...edgeJobs.keys(), relay])
53
56
  rm(path.join(ctx.paths.logsDir, `${label}.log`));
54
57
  return `已卸载(relay 通道与 ${edgeJobs.size} 个 edge 的回拨作业)。最后一步:npm uninstall -g ssh-net`;
@@ -64,10 +67,7 @@ function uninstallNode(ctx) {
64
67
  systemd.disableUnit(ctx.runner, unit); // 已禁无害
65
68
  rm(path.join(ctx.paths.systemdUnitDir, unit));
66
69
  systemd.daemonReload(ctx.runner);
67
- rm(ctx.paths.binDir);
68
- rm(ctx.paths.stateDir);
69
- rm(ctx.paths.confDir);
70
- rm(ctx.paths.runtimeVersionFile);
70
+ removeArtifacts(ctx);
71
71
  return '已卸载。最后一步:npm uninstall -g ssh-net';
72
72
  }
73
73
 
@@ -1,6 +1,7 @@
1
- // edge stop 的进程收束(design §5):rm 两开关后 launchctl kill TERM,轮询
2
- // 校验纯 ssh job 真退出(信号直达 ssh)。未装 link(label 不在册)直接
3
- // gone。预算内补发一次 TERM,仍在则报错给手工排障命令,绝不自动 KILL。
1
+ // edge link job 的进程收束(design §5):纯机制——在册才 launchctl kill TERM
2
+ // 并轮询校验纯 ssh job 真退出(信号直达 ssh),不碰开关;删哪些开关是 stop
3
+ // 的命令语义,由命令层显式做。未装 link(label 不在册)直接 gone。预算内
4
+ // 补发一次 TERM,仍在则报错给手工排障命令,绝不自动 KILL。
4
5
  // 同步 CLI 用 Atomics.wait 节流。
5
6
  import * as launchd from './launchd.mjs';
6
7
  import { linkLabel } from './render.mjs';
@@ -24,11 +25,8 @@ function isGone(ctx, label) {
24
25
  * @param {object} ctx
25
26
  * @returns {{gone:boolean, label:string}}
26
27
  */
27
- export function stopEdgeLink(ctx) {
28
+ export function reapEdgeLink(ctx) {
28
29
  const label = linkLabel(ctx.topo.core.alias);
29
- // 删两开关(peer 依赖 relay,见 design §5)。PathState:rm RELAY_ON 不杀
30
- // 进程,但阻止退出后重拉
31
- ctx.state.removeOn(['relay', 'peer']);
32
30
  if (!launchd.printState(ctx.runner, ctx.uid, label).registered)
33
31
  return { gone: true, label };
34
32
 
@@ -12,6 +12,12 @@ export const guiDomain = (uid) => `gui/${uid}`;
12
12
 
13
13
  const EDGE_PLIST_PREFIX = edgeLabel(''); // 'local.ssh-net-uplink-edge-'
14
14
 
15
+ /** 未注册状态的固定形状(parsePrint 与两个 inspect 的未注册返回共用)。 */
16
+ const NOT_REGISTERED_PRINT = Object.freeze(
17
+ { registered: false, running: false, pid: null, runs: null, lastExitCode: null },
18
+ );
19
+ const NOT_REGISTERED = Object.freeze({ disabled: false, ...NOT_REGISTERED_PRINT });
20
+
15
21
  /**
16
22
  * 磁盘 LaunchAgents 里 uplink-edge job plist 的别名清单(install/status/
17
23
  * uninstall 共用;topology 已删的机器只能靠这个 glob 兜底发现,目录不存在
@@ -42,9 +48,7 @@ export function parsePrint(result) {
42
48
  // enable+bootstrap 会以真实报错浮出(2026-09-29 真机确认 113 语义)
43
49
  const registered =
44
50
  result.code === 0 && !/Could not find service/.test(result.stderr ?? '');
45
- if (!registered) {
46
- return { registered: false, running: false, pid: null, runs: null, lastExitCode: null };
47
- }
51
+ if (!registered) return NOT_REGISTERED_PRINT;
48
52
  const out = result.stdout ?? '';
49
53
  const pidMatch = out.match(/^\s*pid\s*=\s*(\d+)/m);
50
54
  const runsMatch = out.match(/^\s*runs\s*=\s*(\d+)/m);
@@ -105,9 +109,7 @@ export function disabledMap(runner, uid) {
105
109
  */
106
110
  export function inspectWith(runner, uid, label, map) {
107
111
  const printed = printState(runner, uid, label);
108
- if (!printed.registered) {
109
- return { registered: false, disabled: false, running: false, pid: null, runs: null, lastExitCode: null };
110
- }
112
+ if (!printed.registered) return NOT_REGISTERED;
111
113
  return { ...printed, disabled: map.get(label) === true };
112
114
  }
113
115
 
@@ -121,9 +123,7 @@ export function inspectWith(runner, uid, label, map) {
121
123
  */
122
124
  export function inspect(runner, uid, label) {
123
125
  const printed = printState(runner, uid, label);
124
- if (!printed.registered) {
125
- return { registered: false, disabled: false, running: false, pid: null, runs: null, lastExitCode: null };
126
- }
126
+ if (!printed.registered) return NOT_REGISTERED;
127
127
  return { ...printed, disabled: disabledMap(runner, uid).get(label) === true };
128
128
  }
129
129
 
@@ -1,11 +1,29 @@
1
- // 运行时实体/服务软链清单的单一来源(install 对账与 status 体检共用,
2
- // design §2.3)。清单即契约:新增包脚本只改这里,漏装与假报「组件异常」
3
- // 不会再分叉。
1
+ // 运行时实体/服务软链清单的单一来源(install 对账、报名对账与 status 体检
2
+ // 共用,design §2.3)。清单即契约:新增包脚本只改这里,漏装与假报「组件
3
+ // 异常」不会再分叉。
4
4
  //
5
5
  // entities:[bin 名, 包脚本名]——原名实体;links:[带机器名软链, 实体名]。
6
- // core 安装时按磁盘在册 edge 追加 uplink-edge(见 installCore),单台 edge
7
- // 报名时的一对固定对账直接写在 register.mjs——都只有一个消费方,不进这里。
8
- import { linkLinkName, relayLinkName } from './render.mjs';
6
+ import { edgeLinkName, linkLinkName, relayLinkName } from './render.mjs';
7
+
8
+ // bin 脚本名:plan 清单与按名判断(status 体检、install 预检)共用,改名一处
9
+ export const SN_PROBE = 'sn-probe';
10
+ export const SN_ROUTE = 'sn-route';
11
+ export const SN_IPV6 = 'sn-ipv6';
12
+ export const LINK_CORE = 'ssh-net-link-core';
13
+ export const UPLINK_RELAY = 'ssh-net-uplink-relay';
14
+ export const UPLINK_EDGE = 'ssh-net-uplink-edge';
15
+
16
+ /**
17
+ * link 附加件专属产物:第 4 实体 + 带机器名软链。edgeRuntimePlan 装了 link
18
+ * 时并入;install --without-link 按这份清单删。
19
+ * @param {import('./config.mjs').Topology} topo
20
+ */
21
+ export function linkAddonPlan(topo) {
22
+ return {
23
+ entities: [[LINK_CORE, LINK_CORE]],
24
+ links: [[linkLinkName(topo.core.alias), LINK_CORE]],
25
+ };
26
+ }
9
27
 
10
28
  /**
11
29
  * edge 形态:基础三件套恒装;装了 link 附加件才加第 4 实体与带机器名软链。
@@ -15,27 +33,44 @@ import { linkLinkName, relayLinkName } from './render.mjs';
15
33
  export function edgeRuntimePlan(topo, linkInstalled) {
16
34
  /** @type {[string,string][]} */
17
35
  const entities = [
18
- ['sn-probe', 'sn-probe'],
19
- ['sn-route', 'sn-route'], // Match exec 按需选路 + 成功后本地通知/秒切(design §2.2)
20
- ['sn-ipv6', 'sn-ipv6'],
36
+ [SN_PROBE, SN_PROBE],
37
+ [SN_ROUTE, SN_ROUTE], // Match exec 按需选路 + 成功后本地通知/秒切(design §2.2)
38
+ [SN_IPV6, SN_IPV6],
21
39
  ];
22
- /** @type {[string,string][]} */
23
- const links = [];
24
- if (linkInstalled) {
25
- entities.push(['ssh-net-link-core', 'ssh-net-link-core']);
26
- links.push([linkLinkName(topo.core.alias), 'ssh-net-link-core']);
27
- }
28
- return { entities, links };
40
+ return linkInstalled
41
+ ? mergePlans({ entities, links: [] }, linkAddonPlan(topo))
42
+ : { entities, links: [] };
29
43
  }
30
44
 
31
45
  /**
32
- * relay 一件套:core/node 常驻服务的基础形态(installCore 在其上追加在册
46
+ * relay 一件套:core/node 常驻服务的基础形态(installCore 在其上并入在册
33
47
  * edge 的回拨组件)。
34
48
  * @param {import('./config.mjs').Topology} topo
35
49
  */
36
50
  export function relayRuntimePlan(topo) {
37
51
  return {
38
- entities: [['ssh-net-uplink-relay', 'ssh-net-uplink-relay']],
39
- links: [[relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay']],
52
+ entities: [[UPLINK_RELAY, UPLINK_RELAY]],
53
+ links: [[relayLinkName(topo.relay.alias), UPLINK_RELAY]],
54
+ };
55
+ }
56
+
57
+ /**
58
+ * core 侧在册 edge 的回拨组件并集:uplink-edge 全 core 一份实体,每台 edge
59
+ * 一条带别名软链(install 按磁盘在册、_register 传单台、status 按 topology
60
+ * 在册,三方同源)。
61
+ * @param {readonly string[]} aliases
62
+ */
63
+ export function edgeCallbacksPlan(aliases) {
64
+ return {
65
+ entities: aliases.length ? [[UPLINK_EDGE, UPLINK_EDGE]] : [],
66
+ links: aliases.map((alias) => [edgeLinkName(alias), UPLINK_EDGE]),
67
+ };
68
+ }
69
+
70
+ /** 多份计划并集(顺序拼接;调用方保证各份之间实体/软链不重复)。 */
71
+ export function mergePlans(...plans) {
72
+ return {
73
+ entities: plans.flatMap((p) => p.entities),
74
+ links: plans.flatMap((p) => p.links),
40
75
  };
41
76
  }
@@ -49,6 +49,8 @@ export function machinePaths(env = process.env) {
49
49
  sshNetDir,
50
50
  topologyFile: path.join(sshNetDir, 'topology'),
51
51
  binDir: path.join(sshNetDir, 'bin'),
52
+ /** @param {string} name bin/ 下产物名(实体或服务软链) */
53
+ binScript: (name) => path.join(sshNetDir, 'bin', name),
52
54
  runtimeVersionFile: path.join(sshNetDir, 'runtime-version'),
53
55
  stateDir,
54
56
  // ssh Include 片段目录(design §4.2,2026-10-01):routes 仅 edge install
@@ -47,24 +47,39 @@ export function listListeners(runner, port) {
47
47
  }
48
48
 
49
49
  /**
50
- * 端口的 v6 环回([::1])监听者 pid 列表(peer 回拨口专用,2026-09-30 起
51
- * 10022 只听 [::1])。v4 环回(127.0.0.1)上的同名端口持有者——如 VS Code
52
- * 本地转发——与本服务不同地址族、可共存,不算冲突。用全输出 lsof 按
53
- * `[::1]:<port>` 行过滤(lsof 的 -iTCP@ 过滤对 v6 字面量支持不稳)。
50
+ * 全输出 lsof 查某端口 LISTEN 持有者(无监听返回 '')。预检报冲突与僵尸
51
+ * 判定都用它:一次调用同时拿 pid 与给人看的持有者文本。
54
52
  * @param {import('./exec.mjs').Runner} runner
55
53
  * @param {number} port
56
- * @returns {number[]}
54
+ * @returns {string}
57
55
  */
58
- export function listV6LoopbackListeners(runner, port) {
56
+ export function lsofListen(runner, port) {
59
57
  const r = runner.run('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN']);
60
- if (r.code !== 0) return [];
61
- return r.stdout
58
+ return r.code === 0 ? r.stdout.trim() : '';
59
+ }
60
+
61
+ /**
62
+ * 从 lsof 全输出解析 v6 环回([::1])监听者 pid(lsof 的 -iTCP@ 过滤对 v6
63
+ * 字面量支持不稳,按行过滤)。v4 环回(127.0.0.1)上的同名端口持有者——如
64
+ * VS Code 本地转发——与本服务不同地址族、可共存,不算冲突。
65
+ * @param {string} text lsofListen 的输出
66
+ * @param {number} port
67
+ * @returns {number[]}
68
+ */
69
+ export function v6LoopbackPids(text, port) {
70
+ return text
62
71
  .split('\n')
63
72
  .filter((l) => l.includes(`[::1]:${port}`))
64
73
  .map((l) => Number(l.match(/\s(\d+)\s/)?.[1]))
65
74
  .filter((n) => Number.isInteger(n));
66
75
  }
67
76
 
77
+ /** 端口的 v6 环回([::1])监听者 pid 列表(peer 回拨口专用,2026-09-30 起
78
+ * 10022 只听 [::1])。 */
79
+ export function listV6LoopbackListeners(runner, port) {
80
+ return v6LoopbackPids(lsofListen(runner, port), port);
81
+ }
82
+
68
83
  /**
69
84
  * 全机 pid→ppid 表。
70
85
  * @param {import('./exec.mjs').Runner} runner
@@ -62,17 +62,23 @@ export function ensureLink(linkPath, entityName) {
62
62
  }
63
63
 
64
64
  /**
65
- * 已退役脚本的原名清单:bin/ 是本工具独占目录,对账时静默删除。条目注释带
66
- * 退役日期,保留约一个月后随版本删除(见 CLAUDE.md「约定」),别让一次性
67
- * 兜底变成永久代码。
65
+ * 已退役产物清单:bin/state/conf.d 都是本工具独占位置,install 对账时静默
66
+ * 删除,三种产物的退役清理只有这一个入口。条目带退役版本,保留约一个月后
67
+ * 随版本删除(见 CLAUDE.md「约定」),别让一次性兜底变成永久代码。
68
+ * dir 是 ctx.paths 的目录键。
69
+ * @type {{dir:'binDir'|'stateDir'|'confDir', name:string, retired:string}[]}
68
70
  */
69
- const STALE_SCRIPTS = [
70
- 'sn-notify', // 26.10.31 退役:通知内联 sn-route,无独立脚本
71
- 'sn-signal', // 26.10.31 退役:跨机反拨通道取消,通知/秒切改 edge 本地做
71
+ const STALE_FILES = [
72
+ { dir: 'binDir', name: 'sn-notify', retired: '26.10.31' }, // 通知内联 sn-route
73
+ { dir: 'binDir', name: 'sn-signal', retired: '26.10.31' }, // 跨机反拨通道取消
74
+ { dir: 'stateDir', name: 'ROUTE_PEER', retired: '26.10.31' }, // 开关收敛为 relay/peer
75
+ { dir: 'stateDir', name: 'LINK_ON', retired: '26.10.31' }, // link 退化为纯 ssh
76
+ { dir: 'confDir', name: 'vscode-mark', retired: '26.10.32' }, // 打标块并入 routes
72
77
  ];
73
78
 
74
79
  /**
75
- * 幂等对账 bin/:退役旧名清理 + 实体拷贝 + 服务软链 + 版本戳。
80
+ * 幂等对账 bin/:退役产物清理 + 实体拷贝 + 服务软链 + 版本戳。所有 install
81
+ * 路径(edge/core/node,含 link 形态切换分支)都先经这里,退役清理无死角。
76
82
  * @param {object} ctx
77
83
  * @param {readonly (readonly [string, string])[]} entries [bin 名, 包脚本名] 实体
78
84
  * @param {readonly (readonly [string, string])[]} links [链名, 实体 bin 名]
@@ -80,8 +86,8 @@ const STALE_SCRIPTS = [
80
86
  */
81
87
  export function ensureRuntime(ctx, entries, links = []) {
82
88
  fs.mkdirSync(ctx.paths.binDir, { recursive: true });
83
- for (const name of STALE_SCRIPTS)
84
- fs.rmSync(path.join(ctx.paths.binDir, name), { force: true });
89
+ for (const { dir, name } of STALE_FILES)
90
+ fs.rmSync(path.join(ctx.paths[dir], name), { force: true });
85
91
  const results = entries.map(([name, scriptName]) =>
86
92
  ensureScript(path.join(ctx.paths.binDir, name), packageScriptPath(scriptName)));
87
93
  for (const [name, entityName] of links) {
@@ -20,14 +20,13 @@ export const isActive = (runner, unit) =>
20
20
  sc(runner, ['is-active', unit]).stdout.trim();
21
21
 
22
22
  /**
23
- * unit 文件校验;systemd-analyze 不存在时返回 skipped=true(不阻塞)。
24
- * @returns {{ok:boolean, skipped?:boolean, stdout:string, stderr:string}}
23
+ * unit 文件校验;systemd-analyze 不存在(ENOENT)视为通过——lint 是尽力而为,
24
+ * 不该让装不了 systemd-analyze 的机器无法安装。
25
+ * @returns {{ok:boolean, stdout:string, stderr:string}}
25
26
  */
26
27
  export function verifyUnit(runner, unitPath) {
27
28
  const r = runner.run('systemdAnalyze', ['verify', unitPath]);
28
- if (r.error && r.error.code === 'ENOENT') {
29
- return { ok: true, skipped: true, stdout: r.stdout, stderr: r.stderr };
30
- }
29
+ if (r.error && r.error.code === 'ENOENT') return { ok: true, stdout: r.stdout, stderr: r.stderr };
31
30
  // verify 对只告警也可能非零;这里把非零视为失败,命令层打印 stderr
32
31
  return { ok: r.code === 0, stdout: r.stdout, stderr: r.stderr };
33
32
  }
@@ -65,7 +64,7 @@ export function syncUnit(runner, { unitPath, unitName, content }) {
65
64
 
66
65
  writeFileAtomic(unitPath, content, { mode: 0o644 });
67
66
  const verify = verifyUnit(runner, unitPath);
68
- if (!verify.ok && !verify.skipped)
67
+ if (!verify.ok)
69
68
  throw new Error(`systemd-analyze verify 失败:\n${verify.stderr}`);
70
69
  for (const r of [
71
70
  daemonReload(runner),
package/libexec/sn-route CHANGED
@@ -86,8 +86,7 @@ probe() (
86
86
  exec 2>/dev/null
87
87
  exec 3<>"/dev/tcp/$HOST/$PORT" || exit 1
88
88
  # read 必须显式 <&3:fd0 在 Match exec 下是 /dev/null,漏了会立即 EOF
89
- IFS= read -t "$PROBE_W" -r line <&3
90
- [ "$?" -eq 0 ] || exit 1
89
+ IFS= read -t "$PROBE_W" -r line <&3 || exit 1
91
90
  case "$line" in SSH-*) exit 0 ;; *) exit 1 ;; esac
92
91
  )
93
92
 
@@ -252,8 +251,15 @@ while time_left; do
252
251
  if ! stamp_fresh "$lock" "$LOCK_STALE" "$now"; then
253
252
  "$RM" -f "$lock" 2>/dev/null
254
253
  if trylock; then
255
- role=leader
256
- announce_now
254
+ # 抢空锁后复查失败印记:锁也可能是 leader 秒败刚删的——双
255
+ # Match 并发的晚到者可能正夹在「印记已写、锁已删」之间跳过
256
+ # 上面那条检查。新鲜印记下认 follower、释放空锁,不重复报名
257
+ if stamp_fresh "$STATE_DIR/PROBE_FAIL" "$FAIL_TTL"; then
258
+ "$RM" -f "$lock" 2>/dev/null
259
+ else
260
+ role=leader
261
+ announce_now
262
+ fi
257
263
  fi
258
264
  fi
259
265
  fi
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ssh-net",
3
- "version": "26.10.35",
3
+ "version": "26.10.36",
4
4
  "type": "module",
5
5
  "description": "个人 SSH 组网:v6 直连优先、relay 兜底、关机有界重试后静默",
6
6
  "bin": {