ssh-net 26.10.25 → 26.10.27

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.
@@ -3,6 +3,7 @@
3
3
  // uplink-relay、不预建 uplink-edge(首次 checkin 才生成);node 写 unit 并
4
4
  // enable --now。
5
5
  import fs from 'node:fs';
6
+ import os from 'node:os';
6
7
  import path from 'node:path';
7
8
  import { buildForwardSpecs } from '../lib/config.mjs';
8
9
  import { CALLBACK_PORT } from '../lib/constants.mjs';
@@ -24,8 +25,26 @@ import {
24
25
  renderEdgeHost,
25
26
  } from '../lib/render.mjs';
26
27
 
28
+ /** ensureRuntime 结果的人话摘要('' = 组件零变更)。install/upgrade 后
29
+ * 给用户对账反馈——「组件到底刷没刷」此前从输出里看不出来(结果被丢弃)。 */
30
+ function compNote(results) {
31
+ const LABELS = {
32
+ created: '新建', updated: '更新', repaired: '补可执行位',
33
+ linked: '新建软链', relinked: '重指软链', replaced: '替换旧实体为软链',
34
+ };
35
+ const counts = new Map();
36
+ for (const s of results) {
37
+ if (s === 'unchanged') continue;
38
+ counts.set(s, (counts.get(s) ?? 0) + 1);
39
+ }
40
+ if (counts.size === 0) return '';
41
+ const parts = [...counts].map(([k, n]) => `${LABELS[k] ?? k} ${n} 项`);
42
+ return `(组件对账:${parts.join('、')})`;
43
+ }
44
+
27
45
  /** edge 端口预检(纯读 + banner 判定),冲突抛错并报持有者。 */
28
46
  async function precheckEdgePorts(ctx) {
47
+
29
48
  const { runner, paths, uid, topo } = ctx;
30
49
  const jobPid = launchd.inspect(runner, uid, linkLabel(topo.core.alias)).pid;
31
50
 
@@ -39,7 +58,7 @@ async function precheckEdgePorts(ctx) {
39
58
 
40
59
  // 10022 持口者永远是本机 sshd,无法按 pid 溯源:读到 SSH banner 才认。
41
60
  // 只盯 [::1](peer 全 v6 环回后的本服务监听面;127.0.0.1:10022 的持有
42
- // 者如 VS Code 本地转发与本服务可共存,2026-09-30 起不判冲突——mb5 实案)。
61
+ // 者如 VS Code 本地转发与本服务可共存,2026-09-30 起不判冲突——edge 实案)。
43
62
  // 首装时 bin/sn-probe 还没拷上,探针缺失不判僵尸(install 随后就拷)
44
63
  const holders = listV6LoopbackListeners(runner, CALLBACK_PORT);
45
64
  if (
@@ -60,7 +79,7 @@ async function installEdge(ctx) {
60
79
  await precheckEdgePorts(ctx);
61
80
  // bin/ 形态(design §2.3):实体原名 + 带机器名软链(plist argv[0] 经软链,
62
81
  // 进程第一列可辨识);sn-* 工具全角色同名,服务链名带对端别名
63
- ensureRuntime(ctx,
82
+ const comp = compNote(ensureRuntime(ctx,
64
83
  [
65
84
  ['ssh-net-link-core', 'ssh-net-link-core'],
66
85
  ['sn-probe', 'sn-probe'],
@@ -69,11 +88,11 @@ async function installEdge(ctx) {
69
88
  ['sn-signal', 'sn-signal'], // 机器间信令(recv:core 信令接收端在本机的入口)
70
89
  ['sn-notify', 'sn-notify'], // link 线路状态通知(mode 变化时调)
71
90
  ],
72
- [[linkLinkName(topo.core.alias), 'ssh-net-link-core']]);
91
+ [[linkLinkName(topo.core.alias), 'ssh-net-link-core']]));
73
92
 
74
93
  // 线路通知组件(用户视角提示,2026-09-30):已装则顺手 open 一次它的
75
94
  // .app 触发通知授权注册(terminal-notifier 不主动请求权限,首次发通知
76
- // 静默收不到;open 过再发就通——mb5 实测)。未装不替用户 brew install
95
+ // 静默收不到;open 过再发就通——edge 实测)。未装不替用户 brew install
77
96
  // (改变系统的动作留给用户),给出确切命令
78
97
  const tn = ctx.tnPath === undefined ? detectTerminalNotifier() : ctx.tnPath;
79
98
  let notifyNote = '';
@@ -105,9 +124,12 @@ async function installEdge(ctx) {
105
124
  // edge 存在,其他机器写了也恒不命中;core/node 的 conf.d 没有本文件
106
125
  const routesChanged = syncConfFile(paths.routesFile, renderRoutes(topo));
107
126
  const routesMsg = routesChanged ? '(选路片段已更新)' : '';
108
- return r.unchanged
109
- ? `已安装,无需改动${routesMsg}${notifyNote}`
110
- : `安装完成。隧道默认关闭——at home(或 ssh-net start)开启${routesMsg}${notifyNote}`;
127
+ if (r.unchanged) {
128
+ return comp
129
+ ? `组件已刷新${comp};plist 无需改动${routesMsg}${notifyNote}`
130
+ : `已安装,无需改动${routesMsg}${notifyNote}`;
131
+ }
132
+ return `安装完成${comp}。隧道默认关闭——at home(或 ssh-net start)开启${routesMsg}${notifyNote}`;
111
133
  }
112
134
 
113
135
  /** 磁盘上已注册的 uplink-edge 别名(plist glob;topology 已删的机器靠它兜底)。 */
@@ -133,10 +155,10 @@ function installCore(ctx) {
133
155
  ['sn-signal', 'sn-signal'], // 信令发送端(send:uplink-edge 的 LocalCommand 挂钩调)
134
156
  ];
135
157
  if (edges.length) entities.push(['ssh-net-uplink-edge', 'ssh-net-uplink-edge']);
136
- ensureRuntime(ctx, entities, [
158
+ const comp = compNote(ensureRuntime(ctx, entities, [
137
159
  [relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay'],
138
160
  ...edges.map((alias) => [edgeLinkName(alias), 'ssh-net-uplink-edge']),
139
- ]);
161
+ ]));
140
162
  const label = relayLabel(topo.relay.alias);
141
163
  const content = renderRelayPlist({
142
164
  binDir: paths.binDir,
@@ -149,27 +171,54 @@ function installCore(ctx) {
149
171
  plistPath: path.join(paths.launchAgentsDir, plistFileName(label)),
150
172
  content,
151
173
  });
152
- return r.unchanged
153
- ? '已安装,无需改动'
154
- : `安装完成,relay 已开启(s100 入口 ${topo.core.relayPort})`;
174
+ if (r.unchanged) {
175
+ return comp
176
+ ? `组件已刷新${comp};plist 无需改动`
177
+ : '已安装,无需改动';
178
+ }
179
+ return `安装完成${comp},relay 已开启(${topo.relay.alias} 入口 ${topo.core.relayPort})`;
155
180
  }
156
181
 
157
182
  function installNode(ctx) {
158
183
  const { topo, paths, runner } = ctx;
159
184
  if (ctx.uid !== 0)
160
185
  throw new Error('node 安装写 /etc/systemd/system 需要 root,请以 root 运行');
161
- ensureRuntime(ctx,
186
+ const comp = compNote(ensureRuntime(ctx,
162
187
  [['ssh-net-uplink-relay', 'ssh-net-uplink-relay']],
163
- [[relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay']]);
188
+ [[relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay']]));
164
189
  const unitName = relayUnitName(topo.relay.alias);
165
190
  const unitPath = path.join(paths.systemdUnitDir, unitName);
191
+ // HOME 用 root 的真实家目录(getpwuid),不取 $HOME:sudo 保留 HOME 的环境
192
+ // (sudo -E,或部分发行版的默认值)会把调用者的家目录写进 unit——root
193
+ // 运行的 ssh 将去读别人的 ~/.ssh/config,relay 别名解析错配且无声
194
+ const home = ctx.nodeHome ?? os.userInfo().homedir;
166
195
  const content = renderRelayUnit({
167
196
  binDir: paths.binDir,
168
197
  relayAlias: topo.relay.alias,
169
198
  relayPort: ctx.self.relayPort,
170
- home: ctx.env.HOME ?? '/root',
199
+ home,
171
200
  });
172
201
  fs.mkdirSync(paths.systemdUnitDir, { recursive: true });
202
+
203
+ // 幂等(对齐 mac 侧 syncPlist 的「字节相同不动盘」与 design §5「install
204
+ // 幂等不断连」):unit 内容一致时只确保 enable + 在跑(start 对 active
205
+ // 单元是 no-op),不重写、不 restart——重复 install 不再把健康隧道
206
+ // 白断一次;内容变了才走写 + verify + reload + restart 全序列
207
+ let existing = null;
208
+ try {
209
+ existing = fs.readFileSync(unitPath, 'utf8');
210
+ } catch {
211
+ existing = null;
212
+ }
213
+ if (existing === content) {
214
+ for (const r of [systemd.enableUnit(runner, unitName), systemd.startUnit(runner, unitName)]) {
215
+ if (r.code !== 0) throw new Error(`systemctl 失败:${r.stderr.trim()}`);
216
+ }
217
+ return comp
218
+ ? `组件已刷新${comp};unit 无需改动`
219
+ : '已安装,无需改动';
220
+ }
221
+
173
222
  writeFileAtomic(unitPath, content, 0o644);
174
223
  const verify = systemd.verifyUnit(runner, unitPath);
175
224
  if (!verify.ok && !verify.skipped)
@@ -181,7 +230,7 @@ function installNode(ctx) {
181
230
  ]) {
182
231
  if (r.code !== 0) throw new Error(`systemctl 失败:${r.stderr.trim()}`);
183
232
  }
184
- return `安装完成,relay 已开启(s100 入口 ${ctx.self.relayPort})`;
233
+ return `安装完成${comp},relay 已开启(${ctx.topo.relay.alias} 入口 ${ctx.self.relayPort})`;
185
234
  }
186
235
 
187
236
  /**
@@ -75,9 +75,12 @@ function forwardLabel(f) {
75
75
 
76
76
  async function relayPortListening(ctx, port) {
77
77
  // relay 别名的 User/HostName 由 ssh config Host 块提供;
78
- // BatchMode 防换机器/换钥匙时在终端闪密码提示(与运行时五个 ssh 同约定)
78
+ // BatchMode 防换机器/换钥匙时在终端闪密码提示;IdentitiesOnly 防 agent
79
+ // 多 key 试错撞 MaxAuthTries 把探测误报成「不可达」(与运行时五个 ssh
80
+ // 同约定,status 是探测、结果必须诚实)
79
81
  const r = await ctx.runner.runAsync('ssh', [
80
82
  '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5',
83
+ '-o', 'IdentitiesOnly=yes',
81
84
  ctx.topo.relay.alias, 'ss', '-tlnH',
82
85
  ], { timeout: 8000 });
83
86
  if (r.code !== 0) return { port, reachable: false, listening: false, detail: r.stderr.trim() };
@@ -92,6 +95,7 @@ async function relayPathOk(ctx) {
92
95
  '-p', String(ctx.topo.core.relayPort),
93
96
  '-o', `HostKeyAlias=${ctx.topo.core.alias}`,
94
97
  '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5',
98
+ '-o', 'IdentitiesOnly=yes',
95
99
  `${ctx.topo.core.user}@127.0.0.1`, 'true',
96
100
  ], { timeout: 8000 });
97
101
  return r.code === 0;
@@ -127,6 +131,14 @@ async function collectEdge(ctx) {
127
131
  const job = launchd.inspect(ctx.runner, ctx.uid, label);
128
132
  const switches = state.readSwitches();
129
133
 
134
+ // 非法组合:peer/link 依赖 relay,控制面置开关有级联保证,但开关是
135
+ // 「文件即接口」——手 touch/rm state 里的标记可造出组合(设计接受手改,
136
+ // 这里负责显眼地指出,而不是让线路行各说各话)
137
+ if (switches.peer && !switches.relay)
138
+ issues.push('开关组合异常:peer 开但 relay 关(peer 依赖 relay,多半是 state 里的开关文件被手动改动)——跑一次 ssh-net stop 清零后再按需要的 start');
139
+ if (switches.link && !switches.relay)
140
+ issues.push('开关组合异常:link 开但 relay 关(link 依赖 relay,多半是 state 里的开关文件被手动改动)——跑一次 ssh-net stop 清零后再按需要的 start');
141
+
130
142
  // 就绪实测全部并发(On 是意图、ready 是事实;开关关的线路不探测=null):
131
143
  // relay 实测 ssh(8s 超时)与 peer probe(5s)串行要 13s+,转发口/LAN 的
132
144
  // TCP 探测随其一起发起,最坏耗时取决于最慢一条
@@ -168,9 +180,17 @@ async function collectEdge(ctx) {
168
180
  if (f.kind === 'local' && f.targetAlias === 'loopback' && !ports[f.listenPort])
169
181
  issues.push(`${forwardLabel(f)} 未就绪:edge 侧正常时多半是 core 上的出口代理(microsocks)没跑——到 core 上查 local.microsocks`);
170
182
 
183
+ // v6 只是诊断线索不是判决:探测没跑成(超时被杀/非零退出/实体缺失)时
184
+ // 不能谎称「没有 IPv6」——那个结论只在 sn-ipv6 正常跑完且无输出时才成立
185
+ //(与 doctor 的 probeOk 同判据;sn-ipv6 自身退出码恒 0,code!==0 只会是
186
+ // 超时或崩溃)
171
187
  let v6 = '';
172
- if (links.find((l) => l.link === 'sn-ipv6')?.audit === 'ok')
173
- v6 = ctx.runner.runRaw(path.join(paths.binDir, 'sn-ipv6'), [], { timeout: 5000 }).stdout.trim();
188
+ let v6ProbeOk = false;
189
+ if (links.find((l) => l.link === 'sn-ipv6')?.audit === 'ok') {
190
+ const probe = ctx.runner.runRaw(path.join(paths.binDir, 'sn-ipv6'), [], { timeout: 5000 });
191
+ v6 = probe.stdout.trim();
192
+ v6ProbeOk = !probe.error && probe.code === 0;
193
+ }
174
194
 
175
195
  const forwardViews = topo.forwards.map((f) => [forwardLabel(f), ports[f.listenPort]]);
176
196
  // 线路通知组件(用户视角提示,2026-09-30):未装不算故障(sn-notify
@@ -178,8 +198,8 @@ async function collectEdge(ctx) {
178
198
  const notify = ctx.tnPath === undefined ? detectTerminalNotifier() : ctx.tnPath;
179
199
  return {
180
200
  role: 'edge', alias: ctx.self.alias, switches, relayReady, peerReady,
181
- job, links, ports, forwardViews, coreAlias: topo.core.alias,
182
- v6, runtimeVersion, issues, notify,
201
+ job, links, ports, forwardViews, coreAlias: topo.core.alias, relayAlias: topo.relay.alias,
202
+ v6, v6ProbeOk, runtimeVersion, issues, notify,
183
203
  };
184
204
  }
185
205
 
@@ -199,7 +219,7 @@ async function collectCore(ctx) {
199
219
 
200
220
  const relayLabelName = relayLabel(topo.relay.alias);
201
221
  const relayJob = launchd.inspect(ctx.runner, ctx.uid, relayLabelName);
202
- // s100 口实测是 8s 超时的真 ssh:先发起来,边等边做下面的注册态体检
222
+ // relay 口实测是 8s 超时的真 ssh:先发起来,边等边做下面的注册态体检
203
223
  const relayPortP = relayPortListening(ctx, topo.core.relayPort);
204
224
 
205
225
  const edges = [];
@@ -256,7 +276,20 @@ async function collectCore(ctx) {
256
276
  const relayPort = await relayPortP;
257
277
  if (!relayJob.running) issues.push('relay 未在运行——ssh-net start 可拉起');
258
278
  if (!relayPort.listening)
259
- issues.push(`s100 入口 ${topo.core.relayPort} 没在监听:在外面暂时进不来(断线会自动重连;持续出现请查 s100 或本机网络)`);
279
+ issues.push(`${topo.relay.alias} 入口 ${topo.core.relayPort} 没在监听:在外面暂时进不来(断线会自动重连;持续出现请查 ${topo.relay.alias} 或本机网络)`);
280
+
281
+ // topology 已删(edge 改名/退役)但磁盘上还有回拨 job:不渲染成 edges 行
282
+ //(state/conf.d 都按新别名走),单独点破。残留无害——六连败后自休眠、
283
+ // 端口争抢由胜者持有且监听功能等价——但不可见会让改名现场少一条线索
284
+ const knownAliases = new Set(topo.edges.map((e) => e.alias));
285
+ try {
286
+ for (const f of fs.readdirSync(paths.launchAgentsDir)) {
287
+ if (!f.startsWith('local.ssh-net-uplink-edge-') || !f.endsWith('.plist')) continue;
288
+ const alias = f.slice('local.ssh-net-uplink-edge-'.length, -'.plist'.length);
289
+ if (!knownAliases.has(alias))
290
+ issues.push(`${alias} 的回拨 job 还在但 topology 已没有这个 edge(改名/退役残留,无害)——清理:launchctl bootout gui/${ctx.uid}/${f.replace(/\.plist$/, '')} 后删该 plist;或无视(它六连败后会自休眠)`);
291
+ }
292
+ } catch { /* LaunchAgents 目录不存在(未装) */ }
260
293
 
261
294
  return {
262
295
  role: 'core', alias: ctx.self.alias, runtimeVersion,
@@ -281,7 +314,7 @@ async function collectNode(ctx) {
281
314
  if (active !== 'active')
282
315
  issues.push(`系统服务 ${unit} 状态 ${active}——systemctl status ${unit} 查看`);
283
316
  if (!relayPort.listening)
284
- issues.push(`s100 入口 ${ctx.self.relayPort} 没在监听:在外面暂时进不来(断线会自动重连;持续出现请查 s100 或本机网络)`);
317
+ issues.push(`${ctx.topo.relay.alias} 入口 ${ctx.self.relayPort} 没在监听:在外面暂时进不来(断线会自动重连;持续出现请查 ${ctx.topo.relay.alias} 或本机网络)`);
285
318
 
286
319
  return {
287
320
  role: 'node', alias: ctx.self.alias, runtimeVersion,
@@ -329,20 +362,25 @@ export function renderText(s) {
329
362
  lines.push(` 形态: ${profileOf(sw)}`);
330
363
  lines.push(lineOf('relay', sw.relay, s.relayReady,
331
364
  `可用(经 ${s.coreAlias} 的中继信道)`,
332
- '不可用(经 s100 连不上 core;刚开启请等几秒再看,持续出现查 s100 或 core 侧 ssh-net status)',
365
+ `不可用(经 ${s.relayAlias} 连不上 core;刚开启请等几秒再看,持续出现查 ${s.relayAlias} 或 core 侧 ssh-net status)`,
333
366
  '按开关'));
334
367
  // peer/link 依赖 relay:relay 关时一并显示关(手动 touch 出的非法定态)
368
+ const peerUnready = !s.v6ProbeOk
369
+ ? '未就绪(本机 v6 探测没跑成:sn-ipv6 超时或异常,直连状态未知;中继不受影响)'
370
+ : s.v6 === ''
371
+ ? '未就绪(本网络没有 IPv6,直连建不起来;中继不受影响)'
372
+ : '未就绪(等 core 回拨建立;ssh-net doctor 立即重估,中继不受影响)';
335
373
  lines.push(lineOf('peer', sw.relay && sw.peer, s.peerReady,
336
374
  `已就绪(v6 直达 ${s.coreAlias},一条 ssh)`,
337
- s.v6 === ''
338
- ? '未就绪(本网络没有 IPv6,直连建不起来;中继不受影响)'
339
- : '未就绪(等 core 回拨建立;ssh-net doctor 立即重估,中继不受影响)',
375
+ peerUnready,
340
376
  '按开关:不报名,core 不会回拨'));
341
377
  if (!(sw.relay && sw.link)) {
342
- // 软生效:关开关不杀旧连接,口还在听=现有转发保持中
378
+ // stop link 的主路径是 kickstart 立即断开(design §5);转发口仍在听
379
+ // 只剩两种成因:开关文件被手改绕过控制面,或 kickstart 失败降级——
380
+ // 都属非预期,文案直接说破而不是按软关常态描述
343
381
  const lingering = s.forwardViews.some(([, ok]) => ok);
344
382
  lines.push(lingering
345
- ? ' link: 关(按开关;现有转发连接保持中,断开后不再重建,要立即断开跑 ssh-net restart)'
383
+ ? ' link: 关(按开关;转发口仍在听属非预期——stop link 本应立即使其断开:开关文件被手改过,或当时断开请求失败。要立即断开跑 ssh-net restart)'
346
384
  : ' link: 关(按开关,本地无转发口;core 仍可经回拨进入本机)');
347
385
  } else {
348
386
  const views = s.forwardViews;
@@ -353,20 +391,33 @@ export function renderText(s) {
353
391
  }
354
392
  lines.push(s.v6 !== ''
355
393
  ? ` 对外地址: ${s.v6}`
356
- : ` 对外地址: 无 v6${sw.peer ? '(peer 建不起来,只能走 relay)' : ''}`);
394
+ : !s.v6ProbeOk
395
+ ? ' 对外地址: 未知(v6 探测没跑成:sn-ipv6 超时或异常——vpn 重环境下 route 查询可能拖过探测时限,稍后再试)'
396
+ : ` 对外地址: 无 v6${sw.peer ? '(peer 建不起来,只能走 relay)' : ''}`);
357
397
  }
358
398
  lines.push(` 后台任务: ${!s.job.registered ? '未安装' : s.job.running ? '运行中' : '已停止'}`);
359
- lines.push(s.notify
360
- ? ' 通知: terminal-notifier(已装;系统设置→通知里允许后,线路切换会弹系统通知)'
361
- : ' 通知: 未装 terminal-notifier,线路切换通知走 osascript 兜底(能弹但图标是脚本编辑器、点击会打开它;brew install terminal-notifier 体验更好,装完 open 一次它的 .app 触发授权)');
399
+ // 通知行按平台分文案:terminal-notifier/osascript/brew 是 mac 世界的
400
+ // 东西;Linux(node 角色)的兜底是 notify-send,照实说,别引导 brew
401
+ if (s.notify)
402
+ lines.push(' 通知: terminal-notifier(已装;系统设置→通知里允许后,线路切换会弹系统通知)');
403
+ else if (process.platform === 'darwin')
404
+ lines.push(' 通知: 未装 terminal-notifier,线路切换通知走 osascript 兜底(能弹但图标是脚本编辑器、点击会打开它;brew install terminal-notifier 体验更好,装完 open 一次它的 .app 触发授权)');
405
+ else
406
+ lines.push(' 通知: 线路切换通知走 notify-send(Linux 兜底;不发通知不影响隧道)');
362
407
  } else if (s.role === 'core') {
363
408
  lines.push(s.relayPort.listening
364
409
  ? ` relay: ✓ 开着(在外面经 ${s.relayAlias} 进入 ${s.alias} · 入口 ${s.relayPort.port})`
365
- : ` relay: ✗ ${s.relayPort.reachable === false ? '连不上 s100,入口状态未知' : `入口 ${s.relayPort.port} 没在监听`}`);
410
+ : ` relay: ✗ ${s.relayPort.reachable === false ? `连不上 ${s.relayAlias},入口状态未知` : `入口 ${s.relayPort.port} 没在监听`}`);
366
411
  lines.push(` relay 进程: ${s.relayJob.running ? `运行中${exitNote(s.relayJob.lastExitCode)}` : '未运行'}`);
367
412
  lines.push(' edge:');
368
413
  for (const e of s.edges) {
369
- const state = !e.registered ? '从未连接(到场装机后自动出现)'
414
+ // 未注册分两态:state 无 v6 = 真从未连接;有 v6 = 曾报名过(休眠后
415
+ // gui 域会话重建/boout 残留会这样),等它下次报名走未注册分支自愈
416
+ //(enable→bootstrap 实测通)——别说成「到场装机」,那是误导
417
+ const state = !e.registered
418
+ ? (e.v6
419
+ ? `曾连接(peer ${e.v6}),当前未加载——休眠/会话重建后的正常态,它下次报名自动唤醒`
420
+ : '从未连接(到场装机后自动出现)')
370
421
  : e.disabled ? '休眠中(它下次开机报名/TTL 到点重报时自动唤醒)'
371
422
  : e.running ? `已连接(peer ${e.v6 ?? '?'})${exitNote(e.lastExitCode)}`
372
423
  : '已断开(自动重试中)';
@@ -80,7 +80,11 @@ export function run(ctx, args = []) {
80
80
  if (ctx.role === 'core') return stopCore(ctx);
81
81
  if (ctx.role === 'node') {
82
82
  const unit = relayUnitName(ctx.topo.relay.alias);
83
- systemd.stopUnit(ctx.runner, unit);
83
+ const s = systemd.stopUnit(ctx.runner, unit);
84
+ // 与 uninstallNode 同规则:unit 未加载(未装/已卸)的无害失败放行;
85
+ // 真失败必须报——否则「已关闭」是谎报,在跑进程仍在外面监听
86
+ if (s.code !== 0 && !/not loaded/.test(s.stderr))
87
+ throw new Error(`systemctl stop 失败:${s.stderr.trim()}`);
84
88
  const d = systemd.disableUnit(ctx.runner, unit);
85
89
  if (d.code !== 0) throw new Error(`systemctl disable 失败:${d.stderr.trim()}`);
86
90
  return 'relay 已关闭(重启后保持关闭)';
@@ -0,0 +1,63 @@
1
+ // upgrade:一键升级——npm i -g @latest 后重跑 install 刷新运行时。
2
+ // 把消费机「最高频运维动作」的两步纪律(README/CHANGELOG 反复强调的顺序,
3
+ // 以及 ETARGET 传播窗口的 --prefer-online 重试)内置成一条命令,
4
+ // 从根上消掉「npm 升了包却忘重跑 install」的静默版本差。
5
+ //
6
+ // 刻意「换装后重新 exec 新 bin」而不是在当前进程里直接调 installRun:
7
+ // 当前进程的 pkg 版本常量与包内路径都属于旧包(模块已加载),npm 换装后
8
+ // 只有新进程才读得到新 package.json——ensureRuntime 落盘的
9
+ // runtime-version 戳与 status 的对账都依赖新进程里的新常量,用旧进程
10
+ // 跑 install 会盖一个旧版本戳、越对账越乱。
11
+ //
12
+ // 边界:node 角色需要 root(install 写 /etc/systemd/system),先检查再动
13
+ // npm,避免「包装上了、install 被拒」的半截态;core 侧 uplink-edge 组件
14
+ // 不在 install 刷新范围(等各 edge 下次报名自动对账,design §5)。
15
+ import { readRuntimeVersion, RUNTIME_VERSION } from '../lib/runtime.mjs';
16
+
17
+ const NPM_TIMEOUT = 180_000; // 慢网络下全局装包的余量
18
+ const INSTALL_TIMEOUT = 120_000;
19
+
20
+ export async function run(ctx) {
21
+ if (ctx.role === 'node' && ctx.uid !== 0)
22
+ throw new Error('node 上升级要写 /etc/systemd/system(install 步骤),请以 root 运行(sudo ssh-net upgrade)');
23
+
24
+ const npmArgs = ['install', '-g', 'ssh-net@latest'];
25
+ let r = ctx.runner.run('npm', npmArgs, { timeout: NPM_TIMEOUT });
26
+ if (r.error && r.error.code === 'ENOENT')
27
+ throw new Error('PATH 上找不到 npm(非交互环境的 node/npm 由 dotfiles 保证,见 design §7.5)——检查 ~/.zshenv 或 .bashrc 登录链后重试');
28
+ if (r.code !== 0 && /ETARGET/.test(r.stderr)) {
29
+ // 刚发布后 registry 元数据有数分钟传播窗口(notes「发布传播延迟」):
30
+ // 强刷一次在线元数据再判,仍失败才让人等
31
+ r = ctx.runner.run('npm', [...npmArgs, '--prefer-online'], { timeout: NPM_TIMEOUT });
32
+ if (r.code !== 0)
33
+ throw new Error(
34
+ `安装最新版失败(ETARGET:registry 元数据还没传播过来,常见于刚发布几分钟内)——等几分钟再跑 ssh-net upgrade,或手动 npm i -g ssh-net@<版本> --prefer-online。npm 输出:${r.stderr.trim()}`,
35
+ );
36
+ }
37
+ if (r.code !== 0)
38
+ throw new Error(`npm 升级失败:${r.stderr.trim() || `exit ${r.code}`}(网络或 registry 问题;已装的版本不受影响,稍后重试)`);
39
+
40
+ // 换装后用新 bin 跑 install:对账运行时实体/软链/plist/unit 并落
41
+ // runtime-version 戳(幂等,健康的 job 不断连)。PATH 上找 ssh-net:
42
+ // 非交互环境由 dotfiles 保证(同 checkin RPC 的前提,design §7.5)
43
+ const upToDate = /up to date/.test(r.stdout); // npm 零变更:如实说,不硬报「升级完成」
44
+ const inst = ctx.runner.run('ssh-net', ['install'], { timeout: INSTALL_TIMEOUT });
45
+ if (inst.error && inst.error.code === 'ENOENT')
46
+ throw new Error('npm 换装后 PATH 上找不到 ssh-net(全局 bin 未生效)——新开一个 shell 或手动跑一次 ssh-net install;若反复出现,检查 fnm 的 global 包路径');
47
+ if (inst.code !== 0)
48
+ throw new Error(`包已升级,但 install 刷新没成功:${inst.stderr.trim() || `exit ${inst.code}`}——手动跑一次 ssh-net install 修复`);
49
+
50
+ // 后置校验:真换装后新 bin 的 install 必把版本戳刷到新版本(ensureRuntime
51
+ // 无条件 refreshStamp);戳仍是本进程——即旧包——的版本,说明 PATH 解析到
52
+ // 了旧 ssh-net,install 跑在旧代码上、升级静默没生效(status 的
53
+ // runtime-version 对账能查到,但当场报比事后对账快)。up to date 时新旧
54
+ // 版本恒等,该校验无意义,跳过
55
+ const stamp = readRuntimeVersion(ctx.paths);
56
+ if (!upToDate && stamp !== null && stamp === RUNTIME_VERSION)
57
+ return `升级完成。${inst.stdout.trim()}⚠️ 但运行时版本戳仍是 ${stamp}——install 跑的不是新装的 ssh-net(PATH 可能解析到旧安装,如 fnm 多版本残留):which -a ssh-net 排查,再手动跑一次 ssh-net install 完成对账`;
58
+ // 文件已全部对账,但**在跑的 job 进程仍是旧脚本**(install 幂等不断连,
59
+ // 不重启健康服务)——新行为要等进程自然重建(断线/重启)后生效;多数
60
+ // 运行时改动不影响已建立的隧道,不主动 restart(那会把连接断掉)
61
+ const rollover = '(在跑的隧道进程继续用旧脚本直到下次重建;如需立刻加载新行为,ssh-net restart 会断当前连接。core 侧的回拨组件随各 edge 下次报名自动对账)';
62
+ return `${upToDate ? '已是最新版本' : '升级完成'}。${inst.stdout.trim()}${rollover}`;
63
+ }
@@ -2,7 +2,7 @@
2
2
  // 格式见 design §4.1:空格分隔、`#` 注释、空行忽略、无项填 `-`。
3
3
  // 只管名称:IP 不进 topology——静态主机地址的唯一来源是 ~/.ssh/config 的
4
4
  // Host 块(lib/sshconfig.mjs 解析成 hostTable 传入),relay 地址/用户同理
5
- // 由 Host s100 块提供。本文件只做语法解析与拓扑内部校验;别名→IP 的翻译
5
+ // 由 Host <relay 别名> 块提供。本文件只做语法解析与拓扑内部校验;别名→IP 的翻译
6
6
  // 在 buildForwardSpecs 渲染时查 hostTable(install 时做,缺块即报错)。
7
7
  import net from 'node:net';
8
8
 
@@ -31,7 +31,7 @@ const BIND = '127.0.0.1'; // 所有转发强制只绑环回(design §6.5)
31
31
  * @property {string} hostname DOT_HOST 短主机名
32
32
  * @property {string} alias 规范别名(ssh-net 内部一切命名:job/state/Match)
33
33
  * @property {string[]} aliases 规范别名 + 给人用的附加 ssh 别名(逗号列声明,
34
- * 如 ['mb5','m5'];目前只有 core 的 edge 入口片段渲染附加名)
34
+ * 如 ['edge1','e1'];目前只有 core 的 edge 入口片段渲染附加名)
35
35
  * @property {number|null} relayPort
36
36
  * @property {string} user
37
37
  *
@@ -63,7 +63,7 @@ function parsePort(tok) {
63
63
  /**
64
64
  * 别名列:单个规范名,或逗号分隔的「规范名,附加名…」(无空格,文件本身
65
65
  * 空白分列)。规范名是第一个,ssh-net 内部一切命名用它;附加名是给人用的
66
- * ssh 别名(如 mb5,m5——内部都叫 mb5,人在 core 上 ssh m5/mb5 等价)。
66
+ * ssh 别名(如 edge1,e1——内部都叫 edge1,人在 core 上 ssh e1/edge1 等价)。
67
67
  * @param {string} tok
68
68
  * @param {number} lineNo
69
69
  * @returns {string[]}
@@ -72,6 +72,10 @@ function parseAliasList(tok, lineNo) {
72
72
  const names = tok.split(',');
73
73
  if (names.some((n) => !ALIAS_RE.test(n)))
74
74
  throw new ConfigError(lineNo, `别名非法:${tok}`);
75
+ // loopback/loopback6 是 forward local 的环回目标关键字:别名占了这两个
76
+ // 名字会让指向该机的转发被静默翻成落地机环回,必须在解析层拒绝
77
+ if (names.some((n) => n === 'loopback' || n === 'loopback6'))
78
+ throw new ConfigError(lineNo, `别名不能用保留字 loopback/loopback6(环回目标关键字):${tok}`);
75
79
  if (new Set(names).size !== names.length)
76
80
  throw new ConfigError(lineNo, `别名列内重复:${tok}`);
77
81
  return names;
@@ -109,6 +113,8 @@ export function parseTopology(text, opts = {}) {
109
113
  throw new ConfigError(lineNo, 'relay 需要 2 列:relay <别名>');
110
114
  const [, alias] = cols;
111
115
  if (!ALIAS_RE.test(alias)) throw new ConfigError(lineNo, `别名非法:${alias}`);
116
+ if (alias === 'loopback' || alias === 'loopback6')
117
+ throw new ConfigError(lineNo, `别名不能用保留字 loopback/loopback6(环回目标关键字):${alias}`);
112
118
  if (relay) throw new ConfigError(lineNo, 'relay 只能有一行');
113
119
  relay = { alias };
114
120
  return;
@@ -137,6 +143,11 @@ export function parseTopology(text, opts = {}) {
137
143
  if (!ALIAS_RE.test(hostname)) throw new ConfigError(lineNo, `主机名非法:${hostname}`);
138
144
  const aliases = parseAliasList(aliasTok, lineNo);
139
145
  const alias = aliases[0];
146
+ // 附加名目前只消费在 core 侧 edge 入口片段(renderEdgeHost 的 Host
147
+ // 模式):core/node 行写了没有任何渲染吃它,Match 选路与契约校验都
148
+ // 只认规范名——ssh 附加名会静默绕开选路段,直接拒
149
+ if (role !== 'edge' && aliases.length > 1)
150
+ throw new ConfigError(lineNo, `只有 edge 行支持附加名(core 侧入口渲染用):${aliasTok}`);
140
151
  if (!user || user === '-') throw new ConfigError(lineNo, '用户不能为空');
141
152
  if (lanTok !== null) {
142
153
  if (role === 'edge') {
@@ -1,4 +1,4 @@
1
- // mac gui 域 launchctl 编排。行为矩阵全部经 2026-09-28 m4 macOS 27 实测
1
+ // mac gui 域 launchctl 编排。行为矩阵全部经 2026-09-28 core 机(macOS 27)实测
2
2
  // (notes「launchctl gui 域实测矩阵」):
3
3
  // - 未注册 print exit 113 + “Could not find service”
4
4
  // - 休眠判据只用 print-disabled 字典(print 正文无稳定字段)
@@ -1,5 +1,5 @@
1
1
  // 真实探测,不信声明(design §5 端口预检、§6.7 status)。
2
- // - 1080/15900 的持口者是 link bash 的 ssh 子进程,要用 ps 父子表判后代
2
+ // - 本地转发口(-D/-L)的持口者是 link bash 的 ssh 子进程,要用 ps 父子表判后代
3
3
  // - 10022 的持口者永远是本机 sshd(-R 服务端持口),无法按 pid 溯源,
4
4
  // 只能以 sn-probe 是否读到 SSH banner 认定是不是本服务
5
5
  import fs from 'node:fs';
@@ -107,7 +107,7 @@ export function descendantsOf(tree, root) {
107
107
  }
108
108
 
109
109
  /**
110
- * 1080/15900 预检:无监听=空闲;持口者全是 job 后代=本服务;否则冲突。
110
+ * 本地转发口(-D/-L)预检:无监听=空闲;持口者全是 job 后代=本服务;否则冲突。
111
111
  * @param {import('./exec.mjs').Runner} runner
112
112
  * @param {number} port
113
113
  * @param {number|null} jobPid link job 的 pid(未注册给 null)
@@ -123,8 +123,8 @@ export function renderRoutes(topo) {
123
123
 
124
124
  /**
125
125
  * core 上的 edge 在线入口片段 conf.d/edge-<规范别名>。Host 模式给全部别名:
126
- * 规范名(ssh-net 内部用,如 mb5)在前,给人用的短名(如 m5)在后,
127
- * `ssh mb5` 与 `ssh m5` 等价;文件/state/job 命名只用规范名。
126
+ * 规范名(ssh-net 内部用,如 edge1)在前,给人用的短名(如 e1)在后,
127
+ * `ssh edge1` 与 `ssh e1` 等价;文件/state/job 命名只用规范名。
128
128
  * @param {{alias:string, aliases?:string[], user:string, v6:string}} opts
129
129
  * @returns {string}
130
130
  */
@@ -2,7 +2,7 @@
2
2
  // 2026-09-30 定(取代 0.1.x 的 aliases/default 软链与 26.9 的带机器名实体拷贝):
3
3
  // - bin/ 只放包脚本的**原名实体**(0755),服务 job 经「带机器名软链」引用——
4
4
  // 程序永远只有一份(升级原子换一份、N 个 job 自动跟新),进程 argv[0] 第
5
- // 一列仍带机器名可辨识(ssh-net-uplink-edge-mb5 等)
5
+ // 一列仍带机器名可辨识(ssh-net-uplink-edge-<别名> 等)
6
6
  // - 实体/软链都幂等:内容相同不重写(只补可执行位)、链指向正确不动
7
7
  // - 运行时零 npm/fnm 依赖;包升级后重跑 install 刷新(core 侧 uplink-edge
8
8
  // 由 checkin 每次报名自动对账),runtime-version 戳记安装版本,status 见
package/libexec/sn-route CHANGED
@@ -39,15 +39,20 @@ FAIL_TTL=${SSH_NET_ROUTE_FAIL_TTL:-1} # 失败去重戳寿命(秒)
39
39
  DATE=${DATE:-/bin/date}
40
40
  MV=${MV:-/bin/mv}
41
41
  RM=${RM:-/bin/rm}
42
+ CAT=${CAT:-/bin/cat}
42
43
 
43
44
  relay_on="$STATE_DIR/RELAY_ON"
44
45
  route="$STATE_DIR/ROUTE_PEER"
45
46
  fail="$STATE_DIR/PROBE_FAIL"
46
47
 
47
- # 原子写失败戳(tmp+rename,state 目录 0700);写戳自身失败静默——
48
- # 最坏退化为不复用去重、多探一次,不影响判决正确性
48
+ # 原子写失败戳(tmp+rename,state 目录 0700);umask 077 对齐 design §3 的
49
+ # 0600 纪律。时戳写盘当下现取、不回填探测前的时刻——僵尸复核吃满
50
+ # WTIMEOUT(2s)后回填会让戳落地即过期(FAIL_TTL 1s),去重落空。
51
+ # 写戳自身失败静默——最坏退化为不复用去重、多探一次,不影响判决正确性
49
52
  mark_fail() {
50
- printf '%s\n' "$1" >"$fail.tmp.$$" 2>/dev/null || return 0
53
+ local t
54
+ t=$("$DATE" +%s) || return 0
55
+ ( umask 077; printf '%s\n' "$t" >"$fail.tmp.$$" ) 2>/dev/null || return 0
51
56
  "$MV" -f "$fail.tmp.$$" "$fail" 2>/dev/null
52
57
  "$RM" -f "$fail.tmp.$$" 2>/dev/null
53
58
  }
@@ -55,13 +60,13 @@ mark_fail() {
55
60
  [ -e "$relay_on" ] || exit 1
56
61
 
57
62
  # ROUTE_PEER 内容为 epoch 秒(link-core 原子写);空/非数/不可读按陈旧处理
58
- ts=$(cat "$route" 2>/dev/null) || exit 1
63
+ ts=$("$CAT" "$route" 2>/dev/null) || exit 1
59
64
  case "$ts" in ''|*[!0-9]*) exit 1 ;; esac
60
65
  now=$("$DATE" +%s) || exit 1
61
66
  [ $((now - ts)) -le "$ROUTE_TTL" ] 2>/dev/null || exit 1
62
67
 
63
68
  # 失败去重戳(内容同为 epoch);损坏按无效处理,继续现场复核
64
- fts=$(cat "$fail" 2>/dev/null)
69
+ fts=$("$CAT" "$fail" 2>/dev/null)
65
70
  case "$fts" in
66
71
  ''|*[!0-9]*) ;;
67
72
  *) [ $((now - fts)) -le "$FAIL_TTL" ] 2>/dev/null && exit 1 ;;
@@ -70,17 +75,17 @@ esac
70
75
  # 现场 banner 复核,与 sn-probe 同构(不调它:省一次 fork,且本脚本要写
71
76
  # PROBE_FAIL)。fd2 先重定向再开 fd3,拒连报错才不漏(见 sn-probe 头注释)
72
77
  if ! exec 2>/dev/null 3<>"/dev/tcp/$HOST/$PORT"; then
73
- mark_fail "$now"
78
+ mark_fail
74
79
  exit 1
75
80
  fi
76
81
  IFS= read -t "$WTIMEOUT" -r line <&3
77
82
  rc=$?
78
83
  exec 3<&- 3>&-
79
84
  if [ "$rc" -ne 0 ]; then
80
- mark_fail "$now"
85
+ mark_fail
81
86
  exit 1
82
87
  fi
83
88
  case "$line" in
84
89
  SSH-*) exit 0 ;;
85
- *) mark_fail "$now"; exit 1 ;;
90
+ *) mark_fail; exit 1 ;;
86
91
  esac
package/libexec/sn-signal CHANGED
@@ -40,9 +40,12 @@ case "${1:-}" in
40
40
  "$user@$v6" '~/.ssh/ssh-net/bin/sn-signal recv' >/dev/null 2>&1 || true
41
41
  ;;
42
42
  recv)
43
- # pkill -f 的匹配串 'ssh-net-link-core' 只存在于本文件内容、不出现在
44
- # 任何进程命令行上(本脚本文件名与 argv 都不含它),不会自匹配,
45
- # 无需字符类花招
43
+ # pkill -f 按完整命令行匹配:link 主进程与它的全部 fork 子 shell
44
+ # 命令行相同(fork 不重置 argv),一发 USR1 实际打中整棵进程树。
45
+ # 契约是「只有主进程响应」——对端 link-core 的各子 shell 开头已
46
+ # 显式 trap '' USR1 忽略广播,本端无需也无法再区分(命令行相同)。
47
+ # 匹配串 'ssh-net-link-core' 只存在于本文件内容、不出现在任何进程
48
+ # 命令行上(本脚本文件名与 argv 都不含它),不会自匹配。
46
49
  i=1
47
50
  while [ "$i" -le 3 ]; do
48
51
  "$PKILL" -USR1 -f 'ssh-net-link-core' 2>/dev/null