ssh-net 26.10.23 → 26.10.24

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
@@ -9,6 +9,49 @@
9
9
  故 26.9.12 之后跳号发 26.9.17(第 17 个包),13–16 永久空缺——序号从此与
10
10
  第几个包严格一致,看到版本号即知发布总数
11
11
 
12
+ ## [26.10.24] - 2026-10-01
13
+
14
+ ### 变更(topology 正名去 IP;Match 收归 install 渲染;edge 在线入口)
15
+
16
+ - **topology 文件改名 `~/.ssh/ssh-net/config` → `topology`,删掉 LAN_IP
17
+ 列**:从此只管名称(角色/主机名/别名/relay 口/用户),静态 IP 唯一来源
18
+ 是 `~/.ssh/config` 的 Host 块。host 行 7 列变 6 列
19
+ (`host core mac-mini-m4 m4 12022 aex`);install 校验名称↔地址契约
20
+ (relay/core/node 必须有 Host 块和 HostName,edge 豁免)
21
+ - **Match 选路块不再手写在 ~/.ssh/config**:`ssh-net install` 从 topology
22
+ 渲染成 `~/.ssh/ssh-net/conf.d/routes`(edge 专属;值全来自 topology,
23
+ 不含真实 IP),主 config 顶部加一行 `Include
24
+ ~/.ssh/ssh-net/conf.d/*` 接入。旧 `ON` 兼容判据同时收紧为只认 RELAY_ON
25
+ - **`m4-via-relay` 内部别名删除**:报名/status 实测 ssh 改命令行显式
26
+ `ssh -J s100 -p 12022 -o HostKeyAlias=m4 aex@127.0.0.1`(字面环回目标
27
+ 不命中 Match,绕开自动选路;跳板仍读 Host s100 块)。link-core argv
28
+ 相应变为 `<self> <peer> <relay别名> <relay端口> <peer用户> <转发规格…>`
29
+ - **core 新增 edge 在线入口**:edge 报名即写 `conf.d/edge-<别名>`,m4 上
30
+ 直接 `ssh mb5` 经公网 v6 一跳连上笔记本;六连败休眠/state 缺失/uninstall
31
+ 自动删除;v4-only 网络不报名、无入口(不提供经 relay 回连)
32
+ - **别名列支持附加 ssh 短名**:topology 写 `mb5,m5`——规范名 mb5 仍是
33
+ ssh-net 内部唯一名字(文件/state/job/Match),短名 m5 只进 core 入口
34
+ 的 Host 模式,`ssh mb5` 与 `ssh m5` 等价;mb1 同理配 m1
35
+ - **edge 入口片段可由 install 重建**:core install 把 conf.d/edge-* 对账
36
+ 成 state+topology 的视图(peer 稳态循环不报名,手删片段原本等不到自然
37
+ 恢复);无 state 支撑的假入口与 topology 已删 edge 的残留一并清。
38
+ status 新增片段体检:edge 的 routes、core 各在线 edge 的入口片段缺失/
39
+ 过期都报「跑 install 修复」(休眠态删片段是正确行为,不报)
40
+
41
+ **迁移窗口内置旧文件兜底**:`topology` 缺席时新包仍读旧名 `config`(7 列
42
+ 含 LAN_IP 也认,IP 列忽略)——因为 `dot apply ssh` 按整份 md 还原,
43
+ topology 与 Include 版 config 必然同时落地,无法分阶段。
44
+
45
+ 顺序是硬约束(详见 docs/migration.md 2026-10-01 段):
46
+ 1. 五台全部先 `npm i -g ssh-net@26.10.24 && ssh-net install`(吃旧文件,
47
+ routes 落盘但无 Include 不生效;install 提示「仍读旧文件兜底」属正常)
48
+ 2. dotfiles push,各机 `dot apply ssh`(topology 与 Include 版 config
49
+ 同时生效,兜底提示消失)
50
+ 3. edge `ssh-net checkin`,m4 上验证 `ssh mb5` / `ssh m5`
51
+ 4. 全部正常后手动删旧文件 `~/.ssh/ssh-net/config`
52
+
53
+ 另:core install 会清理 topology 已删 edge 的残留 conf.d 片段。
54
+
12
55
  ## [26.10.23] - 2026-10-01
13
56
 
14
57
  ### 变更(转发规格化;loopback6 目标按 peer/relay 选 v6/v4 环回)
package/README.md CHANGED
@@ -31,7 +31,9 @@
31
31
  fnm 切版本不影响常驻服务;包升级 `npm i -g` 后重跑 install 刷新,
32
32
  runtime-version 戳由 status 对账
33
33
  - **npm 包分发**:消费机 `npm i -g ssh-net`,不 clone;个人配置全部在 dotfiles
34
- 托管(`~/.ssh/ssh-net/config` 与 ssh config),包内零个人数据
34
+ 托管(`~/.ssh/ssh-net/topology` 与 ssh config 的静态 Host 块),包内零个人数据;
35
+ 选路 Match 与 core 上的 edge 入口由 install/报名渲染进
36
+ `~/.ssh/ssh-net/conf.d/`(生成物,ssh config 一行 Include 接入)
35
37
 
36
38
  ## edge 的三个开关
37
39
 
package/libexec/cli.mjs CHANGED
@@ -3,7 +3,8 @@
3
3
  // 本文件只做装配、帮助与错误边界。
4
4
  import fs from 'node:fs';
5
5
  import os from 'node:os';
6
- import { parseTopology } from './lib/config.mjs';
6
+ import { parseTopology, validateHostContract } from './lib/config.mjs';
7
+ import { parseStaticHosts } from './lib/sshconfig.mjs';
7
8
  import { localHostname, matchIdentity } from './lib/identity.mjs';
8
9
  import { machinePaths } from './lib/paths.mjs';
9
10
  import { createStateStore } from './lib/state.mjs';
@@ -41,24 +42,44 @@ function help() {
41
42
  .filter(([, c]) => !c.internal)
42
43
  .map(([name, c]) => ` ${name.padEnd(10)} ${c.desc}`),
43
44
  '',
44
- '配置: ~/.ssh/ssh-net/config(dotfiles 托管);运行时/状态: ~/.ssh/ssh-net/{bin,state}',
45
+ '配置: ~/.ssh/ssh-net/topology(dotfiles 托管);运行时/状态: ~/.ssh/ssh-net/{bin,state,conf.d}',
45
46
  ];
46
47
  return lines.join('\n');
47
48
  }
48
49
 
49
- /** 装配本机上下文;config 缺失或主机名不匹配在此硬失败。 */
50
+ /** 装配本机上下文;topology/ssh config 缺失或主机名不匹配在此硬失败。 */
50
51
  function buildContext() {
51
52
  const env = process.env;
52
53
  const paths = machinePaths(env);
54
+ // 新名 topology 优先;缺席时兜底读旧名 config(2026-10-01 改名的迁移窗口,
55
+ // 旧文件 7 列含 LAN_IP——解析但忽略该列;五台 dot apply 完即可删兜底)
53
56
  let text;
57
+ let legacyTopology = false;
54
58
  try {
55
- text = fs.readFileSync(paths.configFile, 'utf8');
59
+ text = fs.readFileSync(paths.topologyFile, 'utf8');
56
60
  } catch (err) {
57
- if (err && err.code === 'ENOENT')
58
- throw new Error(`缺配置 ${paths.configFile}(dotfiles apply ssh 后再 install)`);
59
- throw err;
61
+ if (!err || err.code !== 'ENOENT') throw err;
62
+ try {
63
+ text = fs.readFileSync(paths.legacyConfigFile, 'utf8');
64
+ legacyTopology = true;
65
+ } catch (err2) {
66
+ if (err2 && err2.code === 'ENOENT')
67
+ throw new Error(`缺配置 ${paths.topologyFile}(dotfiles apply ssh 后再 install;旧名 config 已改名 topology)`);
68
+ throw err2;
69
+ }
60
70
  }
61
- const topo = parseTopology(text);
71
+ const topo = parseTopology(text, { allowLegacyLanIp: legacyTopology });
72
+
73
+ // 静态主机表(IP 唯一来源);~/.ssh/config 缺失时给空表,契约校验报具体缺口
74
+ let sshConfigText = '';
75
+ try {
76
+ sshConfigText = fs.readFileSync(paths.sshConfigFile, 'utf8');
77
+ } catch (err) {
78
+ if (!err || err.code !== 'ENOENT') throw err;
79
+ }
80
+ const hostTable = parseStaticHosts(sshConfigText);
81
+ validateHostContract(topo, hostTable);
82
+
62
83
  const hostname = localHostname(os.hostname());
63
84
  const self = matchIdentity(topo, hostname);
64
85
  if (!self)
@@ -69,6 +90,8 @@ function buildContext() {
69
90
  env,
70
91
  paths,
71
92
  topo,
93
+ hostTable,
94
+ legacyTopology,
72
95
  self,
73
96
  role: self.role,
74
97
  runner: createRunner(env),
@@ -16,9 +16,10 @@ import path from 'node:path';
16
16
  import { explainV6Error } from '../lib/ipv6.mjs';
17
17
  import * as launchd from '../lib/launchd.mjs';
18
18
  import { syncPlist } from '../lib/manage.mjs';
19
+ import { syncConfFile, removeConfFile } from '../lib/conf.mjs';
19
20
  import { ensureRuntime } from '../lib/runtime.mjs';
20
21
  import {
21
- edgeLabel, edgeLinkName, plistFileName, renderUplinkEdgePlist,
22
+ edgeLabel, edgeLinkName, plistFileName, renderUplinkEdgePlist, renderEdgeHost,
22
23
  } from '../lib/render.mjs';
23
24
 
24
25
  /** 手动报名(edge):与 link-core 循环里的报名 ssh 同一命令形态与选项集。
@@ -34,11 +35,19 @@ export function runEdgeAnnounce(ctx) {
34
35
  const v6 = probe.stdout.trim();
35
36
  if (!v6)
36
37
  throw new Error('当前网络没有可用 IPv6,没有可报名的地址(中继不受影响)');
38
+ // 报名固定走 relay(relay 7×24 在;peer 僵尸时自动选路会把报名一起挂死)。
39
+ // 命令行显式 -J,不用 ~/.ssh/config 内部别名:字面目标 127.0.0.1 不命中
40
+ // Match originalhost <core>,绕开自动选路;跳板(relay.alias)的地址/用户
41
+ // 仍读 ssh config 的 Host 块;HostKeyAlias 保证三路径同一条 known_hosts。
42
+ // 与 ssh-net-link-core 循环里的报名 ssh 同一形态(design §6.1)。
37
43
  const r = ctx.runner.run('ssh', [
44
+ '-J', ctx.topo.relay.alias,
45
+ '-p', String(ctx.topo.core.relayPort),
46
+ '-o', `HostKeyAlias=${ctx.topo.core.alias}`,
38
47
  '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15',
39
48
  '-o', 'ServerAliveInterval=10', '-o', 'ServerAliveCountMax=2',
40
49
  '-o', 'ControlMaster=no', '-o', 'ControlPath=none',
41
- `${ctx.topo.core.alias}-via-relay`,
50
+ `${ctx.topo.core.user}@127.0.0.1`,
42
51
  `ssh-net _register ${ctx.self.alias} ${v6}`,
43
52
  ], { timeout: 60_000 });
44
53
  if (r.code !== 0)
@@ -47,12 +56,33 @@ export function runEdgeAnnounce(ctx) {
47
56
  return `已报名(本机 v6 ${v6},core 返回 ${core})。core 几秒内回拨建立 peer;ssh-net status 查看结果`;
48
57
  }
49
58
 
50
- /** kickstart 失败时把 state 回滚到 job 实际在拨的 v6(null = 删文件)。
51
- * 不回滚的话磁盘已是新 v6,下轮「running + v6 相同」会被 no-op 分支
59
+ /**
60
+ * edge 登记两处同写(唯一写者 _register):state/edges/<别名> 给
61
+ * uplink-edge 脚本机读,conf.d/edge-<别名> 是 core 上 `ssh <别名>` 的入口。
62
+ * @param {object} ctx
63
+ * @param {{alias:string, user:string}} edge topology edge 行
64
+ * @param {string} v6
65
+ */
66
+ function writeEdgeRegistration(ctx, edge, v6) {
67
+ ctx.state.writeEdgeV6(edge.alias, v6);
68
+ syncConfFile(
69
+ ctx.paths.edgeHostFile(edge.alias),
70
+ renderEdgeHost({ alias: edge.alias, aliases: edge.aliases, user: edge.user, v6 }),
71
+ );
72
+ }
73
+
74
+ /** 两处同删(未报名过的失败路径)。 */
75
+ function removeEdgeRegistration(ctx, alias) {
76
+ ctx.state.removeEdgeV6(alias);
77
+ removeConfFile(ctx.paths.edgeHostFile(alias));
78
+ }
79
+
80
+ /** kickstart 失败时把登记回滚到 job 实际在拨的 v6(null=两处都删)。
81
+ * 不回滚的话磁盘已是新 v6,下轮「running + v6 相同」会被 noop 分支
52
82
  * 误吞,job 拿旧 v6 拨到六连败休眠、再等下轮 checkin 唤醒才纠正。 */
53
- function rollbackEdgeV6(ctx, alias, prevV6) {
54
- if (prevV6 === null) ctx.state.removeEdgeV6(alias);
55
- else ctx.state.writeEdgeV6(alias, prevV6);
83
+ function rollbackEdgeRegistration(ctx, edge, prevV6) {
84
+ if (prevV6 === null) removeEdgeRegistration(ctx, edge.alias);
85
+ else writeEdgeRegistration(ctx, edge, prevV6);
56
86
  }
57
87
 
58
88
  /** start peer 与 checkin 共享的实现:置 relay+peer 开关 + 控制面立即报名。
@@ -122,7 +152,7 @@ export function runRegister(ctx, args = []) {
122
152
 
123
153
  // 未注册:首次报名,plist 后 enable + bootstrap
124
154
  if (!st.registered) {
125
- ctx.state.writeEdgeV6(alias, v6);
155
+ writeEdgeRegistration(ctx, edge, v6);
126
156
  const r = syncPlist(ctx, { label, plistPath, content });
127
157
  if (r.lintError) throw new Error(`uplink-edge plist 校验失败:${r.lintError}`);
128
158
  return `registered ${alias}`;
@@ -131,7 +161,7 @@ export function runRegister(ctx, args = []) {
131
161
  // 已注册但渲染结果与磁盘不符(topology 的 user 等变了):重新部署。
132
162
  // syncPlist 走 bootout→落盘→enable→bootstrap,bootstrap 即首发,无需 kickstart
133
163
  if (existing !== content) {
134
- ctx.state.writeEdgeV6(alias, v6);
164
+ writeEdgeRegistration(ctx, edge, v6);
135
165
  const r = syncPlist(ctx, { label, plistPath, content });
136
166
  if (r.lintError) throw new Error(`uplink-edge plist 校验失败:${r.lintError}`);
137
167
  return `redeployed ${alias}`;
@@ -140,25 +170,33 @@ export function runRegister(ctx, args = []) {
140
170
  // 休眠中:写 v6 → enable 清 override → kickstart 唤醒(enable 本身不首发)。
141
171
  // enable 失败不用回滚:disabled 分支排在 no-op 之前,下轮照走本分支
142
172
  if (st.disabled) {
143
- ctx.state.writeEdgeV6(alias, v6);
173
+ writeEdgeRegistration(ctx, edge, v6);
144
174
  let r = launchd.enable(ctx.runner, ctx.uid, label);
145
175
  if (r.code !== 0) throw new Error(`enable 失败:${r.stderr.trim()}`);
146
176
  r = launchd.kickstart(ctx.runner, ctx.uid, label);
147
177
  if (r.code !== 0) {
148
- rollbackEdgeV6(ctx, alias, prevV6);
178
+ rollbackEdgeRegistration(ctx, edge, prevV6);
149
179
  throw new Error(`kickstart 失败:${r.stderr.trim()}`);
150
180
  }
151
181
  return `woken ${alias}`;
152
182
  }
153
183
 
154
- // enabled + running 且 v6 相同:刻意 no-op(不动进程即不清零 fails)
155
- if (st.running && prevV6 === v6) return `noop ${alias}`;
184
+ // enabled + running 且 v6 相同:刻意 no-op(不动进程即不清零 fails)。
185
+ // 但片段仍 reconcile:uplink-edge 六连败休眠会删 conf.d/edge-<别名>,
186
+ // 与报名存在删/写竞态;TTL 重报周期经过本分支,缺则补、被改则还原
187
+ if (st.running && prevV6 === v6) {
188
+ syncConfFile(
189
+ ctx.paths.edgeHostFile(alias),
190
+ renderEdgeHost({ alias, aliases: edge.aliases, user: edge.user, v6 }),
191
+ );
192
+ return `noop ${alias}`;
193
+ }
156
194
 
157
195
  // enabled 但 v6 变了,或 enabled 未运行:写 v6 → kickstart
158
- ctx.state.writeEdgeV6(alias, v6);
196
+ writeEdgeRegistration(ctx, edge, v6);
159
197
  const r = launchd.kickstart(ctx.runner, ctx.uid, label);
160
198
  if (r.code !== 0) {
161
- rollbackEdgeV6(ctx, alias, prevV6);
199
+ rollbackEdgeRegistration(ctx, edge, prevV6);
162
200
  throw new Error(`kickstart 失败:${r.stderr.trim()}`);
163
201
  }
164
202
  return `kickstarted ${alias}`;
@@ -7,6 +7,7 @@ import path from 'node:path';
7
7
  import { buildForwardSpecs } from '../lib/config.mjs';
8
8
  import { CALLBACK_PORT } from '../lib/constants.mjs';
9
9
  import { syncPlist, writeFileAtomic } from '../lib/manage.mjs';
10
+ import { syncConfFile } from '../lib/conf.mjs';
10
11
  import { ensureRuntime } from '../lib/runtime.mjs';
11
12
  import * as launchd from '../lib/launchd.mjs';
12
13
  import * as systemd from '../lib/systemd.mjs';
@@ -19,7 +20,8 @@ import {
19
20
  relayLabel, relayLinkName, relayUnitName,
20
21
  edgeLinkName,
21
22
  plistFileName,
22
- renderEdgeLinkPlist, renderRelayPlist, renderRelayUnit,
23
+ renderEdgeLinkPlist, renderRelayPlist, renderRelayUnit, renderRoutes,
24
+ renderEdgeHost,
23
25
  } from '../lib/render.mjs';
24
26
 
25
27
  /** edge 端口预检(纯读 + banner 判定),冲突抛错并报持有者。 */
@@ -87,7 +89,10 @@ async function installEdge(ctx) {
87
89
  binDir: paths.binDir,
88
90
  coreAlias: topo.core.alias,
89
91
  selfAlias: ctx.self.alias,
90
- forwardArgs: buildForwardSpecs(topo.forwards),
92
+ relayAlias: topo.relay.alias,
93
+ relayPort: topo.core.relayPort,
94
+ coreUser: topo.core.user,
95
+ forwardArgs: buildForwardSpecs(topo.forwards, ctx.hostTable),
91
96
  relayOnFile: paths.switchFiles.relay,
92
97
  logsDir: paths.logsDir,
93
98
  });
@@ -96,9 +101,13 @@ async function installEdge(ctx) {
96
101
  plistPath: path.join(paths.launchAgentsDir, plistFileName(linkLabel(topo.core.alias))),
97
102
  content,
98
103
  });
104
+ // 选路片段(design §4.2):edge 是 routes 的唯一安装角色。RELAY_ON 只在
105
+ // edge 存在,其他机器写了也恒不命中;core/node 的 conf.d 没有本文件
106
+ const routesChanged = syncConfFile(paths.routesFile, renderRoutes(topo));
107
+ const routesMsg = routesChanged ? '(选路片段已更新)' : '';
99
108
  return r.unchanged
100
- ? `已安装,无需改动${notifyNote}`
101
- : `安装完成。隧道默认关闭——at home(或 ssh-net start)开启${notifyNote}`;
109
+ ? `已安装,无需改动${routesMsg}${notifyNote}`
110
+ : `安装完成。隧道默认关闭——at home(或 ssh-net start)开启${routesMsg}${notifyNote}`;
102
111
  }
103
112
 
104
113
  /** 磁盘上已注册的 uplink-edge 别名(plist glob;topology 已删的机器靠它兜底)。 */
@@ -113,6 +122,8 @@ function registeredEdgeAliases(ctx) {
113
122
 
114
123
  function installCore(ctx) {
115
124
  const { topo, paths } = ctx;
125
+ reconcileEdgeFragments(ctx);
126
+ // conf.d/edge-<别名> 不在此写:那是 _register(edge 报名)的产物,见 checkin.mjs。
116
127
  // 已注册的回拨组件在 install 时一并迁移/对账(旧版带机器名实体拷贝 →
117
128
  // 软链):否则 upgrade 后 core status 要对每台未联系的 edge 报组件异常,
118
129
  // 直到它下次报名才自愈(2026-09-30 补)
@@ -173,12 +184,53 @@ function installNode(ctx) {
173
184
  return `安装完成,relay 已开启(s100 入口 ${ctx.self.relayPort})`;
174
185
  }
175
186
 
187
+ /**
188
+ * core:把 conf.d/edge-* 严格对账成「topology 名单 + state 最新 v6」的视图——
189
+ * 文件是否存在完全由 state 有没有该 edge 的 v6 决定:
190
+ * - 在册且 state 有 v6:从 state 纯渲染(缺失补、过期改、相同不动)。这是
191
+ * 手删/磁盘丢失的恢复通道——peer 稳态的 link 循环不报名,等不到
192
+ * _register 自然补写
193
+ * - 在册但 state 无 v6(从没报名成功/state 被删):删掉残留片段——没有
194
+ * state 支撑的入口指向旧 v6,是必然失败的假入口
195
+ * - topology 已删 edge(改名/退役):删片段;state 同名残留不动(既有
196
+ * 现象,uninstall 才整棵清)
197
+ */
198
+ function reconcileEdgeFragments(ctx) {
199
+ const { topo, paths } = ctx;
200
+ let files = [];
201
+ try {
202
+ files = fs.readdirSync(paths.confDir).filter((f) => f.startsWith('edge-'));
203
+ } catch { files = []; }
204
+
205
+ for (const e of topo.edges) {
206
+ const file = paths.edgeHostFile(e.alias);
207
+ const v6 = ctx.state.readEdgeV6(e.alias);
208
+ if (v6) {
209
+ syncConfFile(
210
+ file,
211
+ renderEdgeHost({ alias: e.alias, aliases: e.aliases, user: e.user, v6 }),
212
+ );
213
+ } else {
214
+ fs.rmSync(file, { force: true });
215
+ }
216
+ files = files.filter((f) => f !== `edge-${e.alias}`);
217
+ }
218
+ // 剩下的都是 topology 不认识的孤儿
219
+ for (const f of files)
220
+ fs.rmSync(path.join(paths.confDir, f), { force: true });
221
+ }
222
+
176
223
  /** @param {object} ctx */
177
224
  export async function run(ctx) {
225
+ let result;
178
226
  switch (ctx.role) {
179
- case 'edge': return installEdge(ctx);
180
- case 'core': return installCore(ctx);
181
- case 'node': return installNode(ctx);
227
+ case 'edge': result = await installEdge(ctx); break;
228
+ case 'core': result = installCore(ctx); break;
229
+ case 'node': result = installNode(ctx); break;
182
230
  default: throw new Error(`未知角色:${ctx.role}`);
183
231
  }
232
+ // 迁移窗口提示:还在吃旧名 config,dot apply 出新 topology 后旧文件可手删
233
+ if (ctx.legacyTopology)
234
+ result += '(当前仍读旧文件 ~/.ssh/ssh-net/config 兜底——dotfiles apply ssh 后可删它)';
235
+ return result;
184
236
  }
@@ -1,10 +1,11 @@
1
1
  // status(design §6.7):只报本机角色,判据是 banner/端口/注册态真实探测。
2
2
  // collect 返回结构化对象(测试断言对象,不锁文本);renderText 给人看——
3
3
  // 2026-09-29 三开关起按「开关(意图)与就绪(实测)分开」组织:开关行报
4
- // RELAY_ON/PEER_ON/LINK_ON,线路行逐条实测(relay 就绪=经 m4-via-relay 真跑
5
- // 一条 ssh,不再从「probe 不通」推断),开关关的线路报「关」不探测。
4
+ // RELAY_ON/PEER_ON/LINK_ON,线路行逐条实测(relay 就绪=命令行 -J 经 relay
5
+ // 真跑一条 ssh,不再从「probe 不通」推断),开关关的线路报「关」不探测。
6
6
  // bin/ 体检(2026-09-30 软链方案):实体逐字节比对 + 服务软链指向/悬空检查。
7
7
  // 退出码:健康(含 edge 关闭态)0;有可行动问题 1。
8
+ import fs from 'node:fs';
8
9
  import path from 'node:path';
9
10
  import {
10
11
  auditScript, auditLink, readRuntimeVersion, runtimeVersionIssue,
@@ -15,9 +16,21 @@ import * as systemd from '../lib/systemd.mjs';
15
16
  import { peerProbeOk, tcpOpen, detectTerminalNotifier } from '../lib/probe.mjs';
16
17
  import {
17
18
  linkLabel, linkLinkName, relayLabel, relayLinkName, relayUnitName,
18
- edgeLabel, edgeLinkName,
19
+ edgeLabel, edgeLinkName, renderRoutes, renderEdgeHost,
19
20
  } from '../lib/render.mjs';
20
21
 
22
+ /**
23
+ * 读 conf.d 片段并与期望内容比对。
24
+ * @returns {'ok'|'stale'|'missing'}
25
+ */
26
+ function auditConfFragment(file, expected) {
27
+ let text = null;
28
+ try {
29
+ text = fs.readFileSync(file, 'utf8');
30
+ } catch { return 'missing'; }
31
+ return text === expected ? 'ok' : 'stale';
32
+ }
33
+
21
34
  /** 实体脚本体检列表。 */
22
35
  function auditRequired(ctx, entries) {
23
36
  return entries.map(([name, script]) => ({
@@ -71,11 +84,15 @@ async function relayPortListening(ctx, port) {
71
84
  return { port, reachable: true, listening: new RegExp(`127\\.0\\.0\\.1[:.]${port}\\b`).test(r.stdout) };
72
85
  }
73
86
 
74
- /** edge 的 relay 线路实测:经 m4-via-relay 跑一条真 ssh(报名/中继同信道)。 */
87
+ /** edge 的 relay 线路实测:命令行显式 -J 经 relay 跑一条真 ssh(报名/中继同
88
+ * 信道;字面 127.0.0.1 不命中 Match,绕开自动选路,design §6.7)。 */
75
89
  async function relayPathOk(ctx) {
76
90
  const r = await ctx.runner.runAsync('ssh', [
91
+ '-J', ctx.topo.relay.alias,
92
+ '-p', String(ctx.topo.core.relayPort),
93
+ '-o', `HostKeyAlias=${ctx.topo.core.alias}`,
77
94
  '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5',
78
- `${ctx.topo.core.alias}-via-relay`, 'true',
95
+ `${ctx.topo.core.user}@127.0.0.1`, 'true',
79
96
  ], { timeout: 8000 });
80
97
  return r.code === 0;
81
98
  }
@@ -98,6 +115,14 @@ async function collectEdge(ctx) {
98
115
  });
99
116
  issues.push(...rtIssues);
100
117
 
118
+ // 选路片段体检(已安装才查:没装时 rtIssues 已报「尚未安装」,别重复):
119
+ // routes 被手删/过期会让 ssh 静默退回 lan 直连,必须显眼
120
+ if (links.find((l) => l.link === 'ssh-net-link-core')?.audit === 'ok') {
121
+ const routeAudit = auditConfFragment(paths.routesFile, renderRoutes(topo));
122
+ if (routeAudit !== 'ok')
123
+ issues.push(`选路片段 conf.d/routes ${routeAudit === 'missing' ? '缺失' : '与 topology 不一致'}——跑一次 ssh-net install 刷新`);
124
+ }
125
+
101
126
  const label = linkLabel(topo.core.alias);
102
127
  const job = launchd.inspect(ctx.runner, ctx.uid, label);
103
128
  const switches = state.readSwitches();
@@ -114,9 +139,12 @@ async function collectEdge(ctx) {
114
139
  // status 要能区分「现有连接保持中」与「彻底没了」
115
140
  ...topo.forwards.map((f) => openTcp('127.0.0.1', f.listenPort)),
116
141
  ];
117
- // relay 开但 core 的 LAN 22 可达 = 人在办公室忘了关(只提示不纠偏)
118
- const lanIdx = switches.relay && topo.core.lanIp ? probes.length : -1;
119
- if (lanIdx >= 0) probes.push(openTcp(topo.core.lanIp, 22, 1200));
142
+ // relay 开但 core 的 LAN 22 可达 = 人在办公室忘了关(只提示不纠偏)。
143
+ // core 的 LAN IP 不进 topology,从 ~/.ssh/config 的静态 Host 块取(契约校验
144
+ // 已保证存在),不读 routes——Match 会把地址改写成环回口
145
+ const coreLanIp = ctx.hostTable.get(topo.core.alias)?.hostname;
146
+ const lanIdx = switches.relay && coreLanIp ? probes.length : -1;
147
+ if (lanIdx >= 0) probes.push(openTcp(coreLanIp, 22, 1200));
120
148
  const got = await Promise.all(probes);
121
149
  const relayReady = got[0];
122
150
  const peerReady = got[1];
@@ -125,7 +153,7 @@ async function collectEdge(ctx) {
125
153
  const lanReachable = lanIdx >= 0 ? got[lanIdx] : false;
126
154
 
127
155
  if (lanReachable)
128
- issues.push(`检测到 ${topo.core.alias}(${topo.core.lanIp})局域网直连可达——隧道可能在空转绕中继;人在办公室可 ssh-net stop`);
156
+ issues.push(`检测到 ${topo.core.alias}(${coreLanIp})局域网直连可达——隧道可能在空转绕中继;人在办公室可 ssh-net stop`);
129
157
 
130
158
  // relay 关(全关/级联)但转发口仍在听 = 孤儿进程;link 软关的口在听不报
131
159
  if (!switches.relay)
@@ -200,13 +228,28 @@ async function collectCore(ctx) {
200
228
  // ——别引导「重跑 install」,白跑;只能等该 edge 下次报名自动修复
201
229
  issues.push(`${e.alias} 的回拨组件异常(${bad.join('、')})——它下次报名时会自动刷新`);
202
230
  }
231
+ const v6 = ctx.state.readEdgeV6(e.alias);
232
+ // edge 入口片段体检:job 在册且未休眠(enabled)+ 有 v6 时,片段必须
233
+ // 与 state 一致——缺失(手删/磁盘丢失)或过期(短名/user 变更后没
234
+ // install)都会让 `ssh <别名>` 失败或解析错。休眠(disabled)时片段
235
+ // 本就该删(六连败收尸),不报;未注册无 v6 也不报
236
+ let fragmentAudit = null;
237
+ if (st.registered && !st.disabled && v6) {
238
+ fragmentAudit = auditConfFragment(
239
+ paths.edgeHostFile(e.alias),
240
+ renderEdgeHost({ alias: e.alias, aliases: e.aliases, user: e.user, v6 }),
241
+ );
242
+ if (fragmentAudit !== 'ok')
243
+ issues.push(`${e.alias} 的 ssh 入口片段${fragmentAudit === 'missing' ? '缺失' : '过期'}(state 有 v6、job 未休眠)——跑一次 ssh-net install 重建`);
244
+ }
203
245
  edges.push({
204
246
  alias: e.alias,
205
247
  registered: st.registered,
206
248
  disabled: st.disabled,
207
249
  running: st.running,
208
250
  lastExitCode: st.lastExitCode,
209
- v6: ctx.state.readEdgeV6(e.alias),
251
+ v6,
252
+ fragment: fragmentAudit,
210
253
  });
211
254
  }
212
255
 
@@ -327,7 +370,9 @@ export function renderText(s) {
327
370
  : e.disabled ? '休眠中(它下次开机报名/TTL 到点重报时自动唤醒)'
328
371
  : e.running ? `已连接(peer ${e.v6 ?? '?'})${exitNote(e.lastExitCode)}`
329
372
  : '已断开(自动重试中)';
330
- lines.push(` ${e.alias} ${state}`);
373
+ // 入口片段态只在异常时显形(正常时无需噪音;issues 区也会报)
374
+ const frag = e.fragment && e.fragment !== 'ok' ? ` · ssh 入口${e.fragment === 'missing' ? '缺失' : '过期'}` : '';
375
+ lines.push(` ${e.alias} ${state}${frag}`);
331
376
  }
332
377
  } else {
333
378
  lines.push(s.relayPort.listening
@@ -30,6 +30,7 @@ function uninstallEdge(ctx) {
30
30
  ));
31
31
  rm(ctx.paths.binDir);
32
32
  rm(ctx.paths.stateDir);
33
+ rm(ctx.paths.confDir); // routes(edge 装的);node 上不存在无害
33
34
  rm(ctx.paths.runtimeVersionFile);
34
35
  rm(path.join(ctx.paths.logsDir, `${label}.log`));
35
36
  return '已卸载。最后一步:npm uninstall -g ssh-net';
@@ -54,6 +55,7 @@ function uninstallCore(ctx) {
54
55
 
55
56
  rm(ctx.paths.binDir);
56
57
  rm(ctx.paths.stateDir);
58
+ rm(ctx.paths.confDir); // 全部 edge-<别名> 动态片段
57
59
  rm(ctx.paths.runtimeVersionFile);
58
60
  for (const label of [...edgeJobs.keys(), relay])
59
61
  rm(path.join(ctx.paths.logsDir, `${label}.log`));
@@ -74,6 +76,7 @@ function uninstallNode(ctx) {
74
76
  systemd.daemonReload(ctx.runner);
75
77
  rm(ctx.paths.binDir);
76
78
  rm(ctx.paths.stateDir);
79
+ rm(ctx.paths.confDir);
77
80
  rm(ctx.paths.runtimeVersionFile);
78
81
  return '已卸载。最后一步:npm uninstall -g ssh-net';
79
82
  }
@@ -0,0 +1,44 @@
1
+ // conf.d 片段的落盘原语(design §4.2,2026-10-01)。~/.ssh/config 顶部
2
+ // `Include ~/.ssh/ssh-net/conf.d/*` 会 glob 进本目录每个文件,所以:
3
+ // - tmp 文件绝不写在 conf.d/ 内(写入中的半截文件会被某次 ssh 扫到)——
4
+ // 写在上级目录 ~/.ssh/ssh-net/.<名>.tmp-<pid> 再原子 rename 进来
5
+ // - 目录 0700、片段 0600(与 ~/.ssh 权限纪律一致)
6
+ // - sync 幂等:内容字节相同不动盘(routes 每次 install 调,不产生无意义变更)
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ /** 确保 conf.d 存在且 0700(~/.ssh/ssh-net 已由 state 侧建为 0700)。 */
11
+ export function ensureConfDir(confDir) {
12
+ fs.mkdirSync(confDir, { recursive: true });
13
+ fs.chmodSync(confDir, 0o700);
14
+ }
15
+
16
+ /**
17
+ * 原子同步一个 Include 片段。
18
+ * @param {string} file 片段绝对路径(在 conf.d 内)
19
+ * @param {string} content 完整内容
20
+ * @returns {boolean} 是否实际重写
21
+ */
22
+ export function syncConfFile(file, content) {
23
+ let existing = null;
24
+ try {
25
+ existing = fs.readFileSync(file, 'utf8');
26
+ } catch {
27
+ existing = null;
28
+ }
29
+ if (existing === content) return false;
30
+
31
+ const dir = path.dirname(file);
32
+ ensureConfDir(dir);
33
+ // tmp 落 conf.d 的**上级**目录:glob conf.d/* 扫不到它
34
+ const tmp = path.join(path.dirname(dir), `.${path.basename(file)}.tmp-${process.pid}`);
35
+ fs.writeFileSync(tmp, content, { mode: 0o600 });
36
+ fs.renameSync(tmp, file);
37
+ fs.chmodSync(file, 0o600);
38
+ return true;
39
+ }
40
+
41
+ /** 删一个片段(不存在静默)。 */
42
+ export function removeConfFile(file) {
43
+ fs.rmSync(file, { force: true });
44
+ }
@@ -1,9 +1,9 @@
1
- // topology 配置(~/.ssh/ssh-net/config,dotfiles 托管)的解析与严格校验。
1
+ // topology(~/.ssh/ssh-net/topology,dotfiles 托管)的解析与严格校验。
2
2
  // 格式见 design §4.1:空格分隔、`#` 注释、空行忽略、无项填 `-`。
3
- // 解析期反规范化(forward local 的目标别名当场翻成 LAN IP),下游零查找。
4
- // 只登记控制面真正消费的事实:relay 的地址/用户在 ssh config Host 块
5
- // (dotfiles 同管),不在此重复登记。
6
-
3
+ // 只管名称:IP 不进 topology——静态主机地址的唯一来源是 ~/.ssh/config 的
4
+ // Host 块(lib/sshconfig.mjs 解析成 hostTable 传入),relay 地址/用户同理
5
+ // 由 Host s100 块提供。本文件只做语法解析与拓扑内部校验;别名→IP 的翻译
6
+ // 在 buildForwardSpecs 渲染时查 hostTable(install 时做,缺块即报错)。
7
7
  import net from 'node:net';
8
8
 
9
9
  export class ConfigError extends Error {
@@ -12,7 +12,7 @@ export class ConfigError extends Error {
12
12
  * @param {string} message
13
13
  */
14
14
  constructor(line, message) {
15
- super(line > 0 ? `config 第 ${line} 行:${message}` : message);
15
+ super(line > 0 ? `topology 第 ${line} 行:${message}` : message);
16
16
  this.name = 'ConfigError';
17
17
  this.line = line;
18
18
  }
@@ -29,8 +29,9 @@ const BIND = '127.0.0.1'; // 所有转发强制只绑环回(design §6.5)
29
29
  * @typedef {Object} HostRow
30
30
  * @property {'core'|'edge'|'node'} role
31
31
  * @property {string} hostname DOT_HOST 短主机名
32
- * @property {string} alias
33
- * @property {string|null} lanIp
32
+ * @property {string} alias 规范别名(ssh-net 内部一切命名:job/state/Match)
33
+ * @property {string[]} aliases 规范别名 + 给人用的附加 ssh 别名(逗号列声明,
34
+ * 如 ['mb5','m5'];目前只有 core 的 edge 入口片段渲染附加名)
34
35
  * @property {number|null} relayPort
35
36
  * @property {string} user
36
37
  *
@@ -38,9 +39,9 @@ const BIND = '127.0.0.1'; // 所有转发强制只绑环回(design §6.5)
38
39
  * @property {'dynamic'|'local'} kind
39
40
  * @property {string} bind 恒 127.0.0.1
40
41
  * @property {number} listenPort
41
- * @property {string} [targetAlias] 目标别名;'loopback'=落地机 v4 环回,
42
- * 'loopback6'=v6 环回偏好(peer 走 ::1、非 peer 退 127.0.0.1)
43
- * @property {string} [targetIp] 解析后的目标 IP(loopback6 记首选 ::1)
42
+ * @property {string} [targetAlias] 目标别名:'loopback'=落地机 v4 环回、
43
+ * 'loopback6'=v6 环回偏好(peer 走 ::1、非 peer 退 127.0.0.1),
44
+ * 其余=主机别名(渲染时查 ~/.ssh/config Host 块的 HostName)
44
45
  * @property {number} [targetPort]
45
46
  *
46
47
  * @typedef {Object} Topology
@@ -59,13 +60,34 @@ function parsePort(tok) {
59
60
  return Number(tok);
60
61
  }
61
62
 
63
+ /**
64
+ * 别名列:单个规范名,或逗号分隔的「规范名,附加名…」(无空格,文件本身
65
+ * 空白分列)。规范名是第一个,ssh-net 内部一切命名用它;附加名是给人用的
66
+ * ssh 别名(如 mb5,m5——内部都叫 mb5,人在 core 上 ssh m5/mb5 等价)。
67
+ * @param {string} tok
68
+ * @param {number} lineNo
69
+ * @returns {string[]}
70
+ */
71
+ function parseAliasList(tok, lineNo) {
72
+ const names = tok.split(',');
73
+ if (names.some((n) => !ALIAS_RE.test(n)))
74
+ throw new ConfigError(lineNo, `别名非法:${tok}`);
75
+ if (new Set(names).size !== names.length)
76
+ throw new ConfigError(lineNo, `别名列内重复:${tok}`);
77
+ return names;
78
+ }
79
+
62
80
  /**
63
81
  * @param {string} text
82
+ * @param {{allowLegacyLanIp?: boolean}} [opts] 兼容 2026-10-01 前的旧 7 列
83
+ * 格式(多一列 LAN_IP):仅在读旧名 `config` 兜底时传 true;该列只校验、
84
+ * 不进 HostRow。五台切换完成后连同文件名兜底一起删
64
85
  * @returns {Topology}
65
86
  */
66
- export function parseTopology(text) {
87
+ export function parseTopology(text, opts = {}) {
67
88
  if (typeof text !== 'string' || text.trim().length === 0)
68
- throw new ConfigError(0, 'config 为空');
89
+ throw new ConfigError(0, 'topology 为空');
90
+ const allowLegacy = opts.allowLegacyLanIp === true;
69
91
 
70
92
  /** @type {RelayRow|null} */
71
93
  let relay = null;
@@ -93,35 +115,49 @@ export function parseTopology(text) {
93
115
  }
94
116
 
95
117
  if (head === 'host') {
96
- if (cols.length !== 7)
118
+ let role;
119
+ let hostname;
120
+ let aliasTok;
121
+ let lanTok = null;
122
+ let portTok;
123
+ let user;
124
+ if (cols.length === 6) {
125
+ [, role, hostname, aliasTok, portTok, user] = cols;
126
+ } else if (cols.length === 7 && allowLegacy) {
127
+ // 旧 7 列:…<别名> <LAN_IP|-> <relay端口|-> <用户>。LAN_IP 只校验
128
+ // 不落对象(新格式里它归 ~/.ssh/config)
129
+ [, role, hostname, aliasTok, lanTok, portTok, user] = cols;
130
+ } else {
97
131
  throw new ConfigError(
98
132
  lineNo,
99
- 'host 需要 7 列:host <角色> <主机名> <别名> <LAN_IP|-> <relay端口|-> <用户>',
133
+ 'host 需要 6 列:host <角色> <主机名> <别名[,附加名…]> <relay端口|-> <用户>',
100
134
  );
101
- const [, role, hostname, alias, ipTok, portTok, user] = cols;
135
+ }
102
136
  if (!ROLES.has(role)) throw new ConfigError(lineNo, `未知角色:${role}(只允许 core/edge/node)`);
103
137
  if (!ALIAS_RE.test(hostname)) throw new ConfigError(lineNo, `主机名非法:${hostname}`);
104
- if (!ALIAS_RE.test(alias)) throw new ConfigError(lineNo, `别名非法:${alias}`);
138
+ const aliases = parseAliasList(aliasTok, lineNo);
139
+ const alias = aliases[0];
105
140
  if (!user || user === '-') throw new ConfigError(lineNo, '用户不能为空');
106
- /** @type {string|null} */
107
- let lanIp = null;
141
+ if (lanTok !== null) {
142
+ if (role === 'edge') {
143
+ if (lanTok !== '-')
144
+ throw new ConfigError(lineNo, 'edge 行的 LAN_IP 必须填 -');
145
+ } else if (net.isIP(lanTok) === 0) {
146
+ throw new ConfigError(lineNo, `LAN_IP 不是 IP 字面值:${lanTok}`);
147
+ }
148
+ }
108
149
  /** @type {number|null} */
109
150
  let relayPort = null;
110
151
  if (role === 'edge') {
111
- if (ipTok !== '-' || portTok !== '-')
112
- throw new ConfigError(lineNo, 'edge 行的 LAN_IP 与 relay 端口必须填 -');
152
+ if (portTok !== '-')
153
+ throw new ConfigError(lineNo, 'edge 行的 relay 端口必须填 -(edge 不注册口)');
113
154
  } else {
114
- if (ipTok === '-' || !ipTok)
115
- throw new ConfigError(lineNo, `${role} 行必须有 LAN_IP`);
116
- if (net.isIP(ipTok) === 0)
117
- throw new ConfigError(lineNo, `LAN_IP 不是 IP 字面值:${ipTok}`);
118
155
  const p = parsePort(portTok);
119
156
  if (!Number.isInteger(p) || p < 1 || p > 65535)
120
157
  throw new ConfigError(lineNo, `relay 端口非法:${portTok}`);
121
- lanIp = ipTok;
122
158
  relayPort = p;
123
159
  }
124
- hosts.push({ role, hostname, alias, lanIp, relayPort, user });
160
+ hosts.push({ role, hostname, alias, aliases: Object.freeze(aliases), relayPort, user });
125
161
  return;
126
162
  }
127
163
 
@@ -144,18 +180,17 @@ export function parseTopology(text) {
144
180
 
145
181
  const byAlias = new Map();
146
182
  const byHostname = new Map();
147
- // relay 别名、各 host 的别名与主机名同处一个命名空间(ssh Host/HostKeyAlias
148
- // 共用),任一重复都报错。
183
+ // relay 别名、各 host 的全部别名(含给人用的短名)与主机名同处一个命名空间
184
+ //(ssh Host/HostKeyAlias 共用),任一重复都报错。
149
185
  const names = new Set([relay.alias]);
150
186
  for (const h of hosts) {
151
- for (const [name, what] of [
152
- [h.alias, '别名'],
153
- [h.hostname, '主机名'],
154
- ]) {
155
- if (names.has(name)) throw new ConfigError(0, `${what}重复:${name}`);
187
+ for (const name of h.aliases) {
188
+ if (names.has(name)) throw new ConfigError(0, `别名重复:${name}`);
156
189
  names.add(name);
190
+ byAlias.set(name, h);
157
191
  }
158
- byAlias.set(h.alias, h);
192
+ if (names.has(h.hostname)) throw new ConfigError(0, `主机名重复:${h.hostname}`);
193
+ names.add(h.hostname);
159
194
  byHostname.set(h.hostname, h);
160
195
  }
161
196
 
@@ -182,36 +217,20 @@ export function parseTopology(text) {
182
217
  const targetPort = parsePort(cols[4]);
183
218
  if (!Number.isInteger(targetPort) || targetPort < 1 || targetPort > 65535)
184
219
  throw new ConfigError(line, `目标端口非法:${cols[4]}`);
185
- // 环回别名:目标服务在 ssh 落地机(link-core 两态都落地 core)的本机
186
- // 环回上,不在拓扑里、无 LAN IP 可翻(协议常量可入包代码):
187
- // loopback = 127.0.0.1(microsocks 只听 v4,故默认/v4 服务用它)
188
- // loopback6 = ::1(服务同听 v6 环回时用,如 macOS 屏幕共享;
189
- // link-core 渲染 ssh 参数时带方括号,见 buildForwardSpecs)
190
- const loopbackIp = { loopback: '127.0.0.1', loopback6: '::1' }[targetAlias];
191
- if (loopbackIp !== undefined) {
192
- forwards.push({
193
- kind,
194
- bind: BIND,
195
- listenPort,
196
- targetAlias,
197
- targetIp: loopbackIp,
198
- targetPort,
199
- });
200
- continue;
220
+ // 环回别名:目标服务在 ssh 落地机的本机环回上,不是主机名、无 Host 块:
221
+ // loopback = 127.0.0.1(microsocks 只听 v4)
222
+ // loopback6 = ::1(服务同听 v6 环回时用;link-core 渲染 ssh 参数时
223
+ // 按 mode 选族带方括号,见 buildForwardSpecs)
224
+ // 具名别名(core/node)的 HostName 来自 ~/.ssh/config Host 块,
225
+ // buildForwardSpecs 渲染时查 hostTable——topology 不存任何 IP。
226
+ if (targetAlias !== 'loopback' && targetAlias !== 'loopback6') {
227
+ const target = byAlias.get(targetAlias);
228
+ if (!target)
229
+ throw new ConfigError(line, `forward local 指向未知别名:${targetAlias}`);
230
+ if (target.role === 'edge')
231
+ throw new ConfigError(line, `forward local 目标 ${targetAlias} 是 edge(edge 无注册地址,不能做转发目标)`);
201
232
  }
202
- const target = byAlias.get(targetAlias);
203
- if (!target)
204
- throw new ConfigError(line, `forward local 指向未知别名:${targetAlias}`);
205
- if (target.lanIp === null)
206
- throw new ConfigError(line, `forward local 目标 ${targetAlias} 没有 LAN_IP(不能指向 edge)`);
207
- forwards.push({
208
- kind,
209
- bind: BIND,
210
- listenPort,
211
- targetAlias,
212
- targetIp: target.lanIp,
213
- targetPort,
214
- });
233
+ forwards.push({ kind, bind: BIND, listenPort, targetAlias, targetPort });
215
234
  }
216
235
  }
217
236
 
@@ -226,26 +245,64 @@ export function parseTopology(text) {
226
245
  });
227
246
  }
228
247
 
248
+ /**
249
+ * 名称↔地址契约校验(buildContext 装配时跑):topology 里凡需要被 ssh 拨到的
250
+ * 静态主机(relay/core/nodes)与具名转发目标,都必须在 ~/.ssh/config 有 Host
251
+ * 块且声明 HostName。edge 豁免(其入口是 core 上动态渲染的 conf.d/edge-*)。
252
+ * @param {Topology} topo
253
+ * @param {Map<string, {hostname?: string}>} hostTable parseStaticHosts 的产物
254
+ */
255
+ export function validateHostContract(topo, hostTable) {
256
+ /** @type {string[]} */
257
+ const missing = [];
258
+ const check = (alias) => {
259
+ const host = hostTable.get(alias);
260
+ if (!host || !host.hostname) missing.push(alias);
261
+ };
262
+ check(topo.relay.alias);
263
+ check(topo.core.alias);
264
+ for (const n of topo.nodes) check(n.alias);
265
+ for (const f of topo.forwards) {
266
+ const a = f.targetAlias;
267
+ if (a && a !== 'loopback' && a !== 'loopback6') check(a);
268
+ }
269
+ if (missing.length > 0)
270
+ throw new ConfigError(
271
+ 0,
272
+ `${missing.join('、')} 在 topology 有名称,但 ~/.ssh/config 缺 Host 块或 HostName`
273
+ + '(名称归 topology、静态地址归 ssh config,两处要对上;edge 豁免)',
274
+ );
275
+ }
276
+
229
277
  /**
230
278
  * 转发渲染成 link-core 的**转发规格**(plist argv 传它,不是裸 ssh 片段):
231
279
  * dynamic → `D:<listenPort>`
232
280
  * local → `L:<listenPort>:<targetPort>:<target>`
233
- * target 普通情况是解析期翻好的 IP(LAN IP / 127.0.0.1);`loopback6`
234
- * 保留为关键字——它要由 link-core 按当前 mode 渲染(peer→[::1]、relay 退
235
- * 127.0.0.1),解析期定不死。bind 不进规格(link-core 恒用 127.0.0.1)。
236
- * 注意:规格以冒号分隔,target 不支持 v6 字面量(v6 环回走 loopback6 关键字)。
281
+ * target:loopback=127.0.0.1;loopback6 保留关键字(link-core 按 mode 选族);
282
+ * 具名别名查 hostTable(~/.ssh/config Host 块的 HostName,IP 唯一来源)。
283
+ * bind 不进规格(link-core 恒用 127.0.0.1)。规格冒号分隔,target 不支持
284
+ * v6 字面量(v6 环回走 loopback6 关键字)。
237
285
  * @param {readonly Forward[]} forwards
286
+ * @param {Map<string, {hostname?: string}>} hostTable parseStaticHosts 的产物
238
287
  * @returns {string[]}
239
288
  */
240
- export function buildForwardSpecs(forwards) {
289
+ export function buildForwardSpecs(forwards, hostTable) {
241
290
  /** @type {string[]} */
242
291
  const specs = [];
243
292
  for (const f of forwards) {
244
293
  if (f.kind === 'dynamic') {
245
294
  specs.push(`D:${f.listenPort}`);
295
+ } else if (f.targetAlias === 'loopback6') {
296
+ specs.push(`L:${f.listenPort}:${f.targetPort}:loopback6`);
297
+ } else if (f.targetAlias === 'loopback') {
298
+ specs.push(`L:${f.listenPort}:${f.targetPort}:127.0.0.1`);
246
299
  } else {
247
- const target = f.targetAlias === 'loopback6' ? 'loopback6' : f.targetIp;
248
- specs.push(`L:${f.listenPort}:${f.targetPort}:${target}`);
300
+ const host = hostTable.get(f.targetAlias);
301
+ // 语法解析时只校验别名在 topology;此处才查 ssh config——install 时
302
+ // 暴露,错误直指缺 Host 块的那台机器
303
+ if (!host || !host.hostname)
304
+ throw new Error(`forward local 目标 ${f.targetAlias} 在 ~/.ssh/config 缺 Host 块或 HostName`);
305
+ specs.push(`L:${f.listenPort}:${f.targetPort}:${host.hostname}`);
249
306
  }
250
307
  }
251
308
  return specs;
@@ -19,7 +19,6 @@ export function localHostname(hostname = os.hostname()) {
19
19
  * @property {string} hostname
20
20
  * @property {string} alias
21
21
  * @property {string} user
22
- * @property {string|null} lanIp
23
22
  * @property {number|null} relayPort
24
23
  */
25
24
 
@@ -4,6 +4,15 @@
4
4
  // 运行时分发(design §2.3,2026-09-29 定):install 把包脚本**拷贝**进
5
5
  // ~/.ssh/ssh-net/bin/(不再软链 fnm alias)——运行时零 npm/fnm 依赖;
6
6
  // 状态与产物同住 ~/.ssh/ssh-net/ 一棵树(state/ 子目录)。
7
+ //
8
+ // 目录分工(2026-10-01 定):
9
+ // topology dotfiles 托管的拓扑(名/角色/relay 口/用户;旧名 config 退役)
10
+ // bin/ 包脚本实体 + 服务软链(install/checkin 对账)
11
+ // state/ 易变状态(开关、edges v6、ROUTE_PEER)
12
+ // conf.d/ 渲染给 ssh Include 的配置片段(生成物,不进 dotfiles):
13
+ // routes edge:Match 选路块(install 渲染)
14
+ // edge-<别名> core:edge 在线入口(_register 写/休眠删)
15
+ // ~/.ssh/config dotfiles 托管,顶部 Include conf.d/* + 静态主机块(IP 唯一来源)
7
16
  import path from 'node:path';
8
17
  import fs from 'node:fs';
9
18
  import { fileURLToPath } from 'node:url';
@@ -33,11 +42,21 @@ export function machinePaths(env = process.env) {
33
42
  return Object.freeze({
34
43
  home,
35
44
  sshDir: path.join(home, '.ssh'),
45
+ sshConfigFile: path.join(home, '.ssh', 'config'),
36
46
  sshNetDir,
37
- configFile: path.join(sshNetDir, 'config'),
47
+ topologyFile: path.join(sshNetDir, 'topology'),
48
+ // 旧名(2026-10-01 前):topology 缺席时兜底读它,新格式全面铺开后删兼容
49
+ legacyConfigFile: path.join(sshNetDir, 'config'),
38
50
  binDir: path.join(sshNetDir, 'bin'),
39
51
  runtimeVersionFile: path.join(sshNetDir, 'runtime-version'),
40
52
  stateDir,
53
+ // ssh Include 片段目录(design §4.2,2026-10-01):routes 仅 edge install
54
+ // 写;edge-<别名> 仅 core _register/休眠写删;node 不建。Include glob
55
+ // 零匹配静默,主 config 五台可同份
56
+ confDir: path.join(sshNetDir, 'conf.d'),
57
+ routesFile: path.join(sshNetDir, 'conf.d', 'routes'),
58
+ /** @param {string} alias edge 别名 */
59
+ edgeHostFile: (alias) => path.join(sshNetDir, 'conf.d', `edge-${alias}`),
41
60
  // 三开关(design §3):relay 是根(PathState 盯它),文件名与 bash 侧
42
61
  // link-core、dotfiles Match 三处硬编码互为契约,改则三处同步
43
62
  switchFiles: Object.freeze({
@@ -1,6 +1,8 @@
1
- // plist/systemd unit 的唯一渲染来源(design §2.3、§6.1、§6.2)。
2
- // 纯字符串函数:每机差异只以位置参数出现(端口、别名、user、转发列表)。
3
- // 渲染快照测试钉死输出;结构性断言(XML 闭合、只绑环回)在测试侧另查。
1
+ // 渲染唯一来源(design §2.3、§4.2、§6.1、§6.2):
2
+ // - plist/systemd unit:每机差异只以位置参数出现(端口、别名、user、转发列表)
3
+ // - conf.d 片段:routes(edge 选路 Match)与 edge-<别名>(core 上的 edge 入口)
4
+ // 纯字符串函数;渲染快照测试钉死输出;结构性断言(XML 闭合、只绑环回)在测试侧另查。
5
+ import { CALLBACK_PORT } from './constants.mjs';
4
6
 
5
7
  export const THROTTLE = 30; // launchd ThrottleInterval / 对应 systemd RestartSec
6
8
 
@@ -59,18 +61,106 @@ export const edgeLabel = (edgeAlias) => `local.${edgeLinkName(edgeAlias)}`;
59
61
  /** @param {string} label */
60
62
  export const plistFileName = (label) => `${label}.plist`;
61
63
 
64
+ // ---- conf.d 片段(~/.ssh/config 顶部 Include,design §4.2)----
65
+
66
+ const ROUTES_HEADER = `# 本文件由 \`ssh-net install\` 从 ~/.ssh/ssh-net/topology 渲染,勿手改。
67
+ # 改 topology(别名/relay 端口)后重跑 ssh-net install 刷新;卸载会删本文件。
68
+ #
69
+ # Match 必须排在主 config 的 Host 块之前(Include 在文件首行;ssh 首次取到的
70
+ # 值生效)。判据是 edge 根开关 RELAY_ON(只在 edge 存在,core/node 恒不命中)
71
+ # + sn-route 判决(link 发布 ROUTE_PEER 时复核一次 banner,design §2.2):
72
+ # core 两块一正一反互斥(Match 不是 if/elif,PROBE_FAIL 戳让两块只复核一次);
73
+ # node 无 v6 入站,只有 relay 兜底。User 不写——由主 config 的 Host 块补。
74
+ `;
75
+
76
+ /**
77
+ * edge 选路片段 conf.d/routes 的唯一渲染来源。值全部来自 topology + 冻结常量,
78
+ * 不出现任何真实 IP(环回口 + relay 别名)。
79
+ * @param {import('./config.mjs').Topology} topo
80
+ * @returns {string}
81
+ */
82
+ export function renderRoutes(topo) {
83
+ const state = '$HOME/.ssh/ssh-net/state';
84
+ const snRoute = '$HOME/.ssh/ssh-net/bin/sn-route';
85
+ /** @type {string[]} */
86
+ const blocks = [];
87
+
88
+ const match = (alias, cond) =>
89
+ `Match originalhost ${alias} exec "test -e ${state}/RELAY_ON${cond}"`;
90
+
91
+ // core:peer 一跳(link 判 peer 且 banner 复核通过)
92
+ blocks.push([
93
+ `# ${topo.core.alias}:peer(v6 回拨落在本机 [::1]:${CALLBACK_PORT},全 v6 环回)`,
94
+ match(topo.core.alias, ` && ${snRoute}`),
95
+ ' HostName ::1',
96
+ ` Port ${CALLBACK_PORT}`,
97
+ ` HostKeyAlias ${topo.core.alias}`,
98
+ ].join('\n'));
99
+ // core:relay 兜底(与上块互斥:sn-route 失败本块才成立)
100
+ blocks.push([
101
+ `# ${topo.core.alias}:relay 兜底(无判决/复核失败/僵尸窗口)`,
102
+ match(topo.core.alias, ` && ! ${snRoute}`),
103
+ ' HostName 127.0.0.1',
104
+ ` Port ${topo.core.relayPort}`,
105
+ ` ProxyJump ${topo.relay.alias}`,
106
+ ` HostKeyAlias ${topo.core.alias}`,
107
+ ].join('\n'));
108
+
109
+ // node:只有 relay(无公网入站)
110
+ for (const n of topo.nodes) {
111
+ blocks.push([
112
+ `# ${n.alias}:relay(node 无公网入站)`,
113
+ match(n.alias, ''),
114
+ ' HostName 127.0.0.1',
115
+ ` Port ${n.relayPort}`,
116
+ ` ProxyJump ${topo.relay.alias}`,
117
+ ` HostKeyAlias ${n.alias}`,
118
+ ].join('\n'));
119
+ }
120
+
121
+ return `${ROUTES_HEADER}\n${blocks.join('\n\n')}\n`;
122
+ }
123
+
124
+ /**
125
+ * core 上的 edge 在线入口片段 conf.d/edge-<规范别名>。Host 模式给全部别名:
126
+ * 规范名(ssh-net 内部用,如 mb5)在前,给人用的短名(如 m5)在后,
127
+ * `ssh mb5` 与 `ssh m5` 等价;文件/state/job 命名只用规范名。
128
+ * @param {{alias:string, aliases?:string[], user:string, v6:string}} opts
129
+ * @returns {string}
130
+ */
131
+ export function renderEdgeHost({ alias, aliases, user, v6 }) {
132
+ const patterns = aliases && aliases.length > 0 ? aliases.join(' ') : alias;
133
+ return `# 本文件由 ssh-net 维护:core 收到 ${alias} 的报名时写入,回拨 job 休眠
134
+ # (edge 关机/不可达,六连败)或 uninstall 时删除。存在即 edge 当前在线、
135
+ # 其上报 v6 可拨;勿手改(改了下次报名也会被覆盖)。
136
+ Host ${patterns}
137
+ User ${user}
138
+ HostName ${v6}
139
+ `;
140
+ }
141
+
62
142
  // ---- 三种 LaunchAgent plist ----
63
143
 
64
144
  /**
65
145
  * edge link job:PathState 盯根开关 RELAY_ON,不写 RunAtLoad。
66
146
  * @param {{binDir:string, coreAlias:string, selfAlias:string,
147
+ * relayAlias:string, relayPort:number, coreUser:string,
67
148
  * forwardArgs:readonly string[], relayOnFile:string, logsDir:string}} opts
68
- * forwardArgs 是 buildForwardSpecs 的转发规格(D:/L:),由 link-core 按 mode 渲染
149
+ * forwardArgs 是 buildForwardSpecs 的转发规格(D:/L:),由 link-core 按 mode 渲染。
150
+ * relay 三参(别名/端口/core 用户)喂给循环的报名 ssh:命令行显式 -J 走中继,
151
+ * 不再依赖 ~/.ssh/config 里的 <core>-via-relay 内部别名(design §6.1)
69
152
  */
70
153
  export function renderEdgeLinkPlist(opts) {
71
- const { binDir, coreAlias, selfAlias, forwardArgs, relayOnFile, logsDir } = opts;
154
+ const {
155
+ binDir, coreAlias, selfAlias, relayAlias, relayPort, coreUser,
156
+ forwardArgs, relayOnFile, logsDir,
157
+ } = opts;
72
158
  const label = linkLabel(coreAlias);
73
- const argv = [`${binDir}/${linkLinkName(coreAlias)}`, selfAlias, coreAlias, ...forwardArgs];
159
+ const argv = [
160
+ `${binDir}/${linkLinkName(coreAlias)}`,
161
+ selfAlias, coreAlias, relayAlias, String(relayPort), coreUser,
162
+ ...forwardArgs,
163
+ ];
74
164
  return `${XML_HEAD} <key>Label</key>
75
165
  <string>${label}</string>
76
166
  ${programArguments(argv)} <key>ProcessType</key>
@@ -0,0 +1,73 @@
1
+ // ~/.ssh/config 静态主机块的极简解析(2026-10-01,topology 去 IP 后的配套)。
2
+ // topology 只管名称,静态地址唯一来源是 ~/.ssh/config 的 Host 块:edge install
3
+ // 渲染 forward 目标、edge status 探 LAN、以及「名称↔地址」契约校验都查本表。
4
+ //
5
+ // 刻意不做完整 ssh 配置解析:
6
+ // - **不展开 Include**——conf.d/routes 是渲染产物,里面的 Match 写着
7
+ // HostName ::1/127.0.0.1,展开就会把隧道口当静态地址;本表只认主文件
8
+ // - **跳过 Match 块**(同理,Match 是条件覆盖,不是静态主机定义)
9
+ // - 只收录精确别名(无通配的 Host 模式);`Host *` / `Host n*` 不入表
10
+ // - 关键字大小写不敏感(ssh 规则),同块内同关键字取首次(ssh 首次生效)
11
+ // - 行首 `#` 注释、空行忽略;不处理行尾注释(ssh 不支持行尾注释)
12
+
13
+ /**
14
+ * @typedef {Object} StaticHost
15
+ * @property {string} [hostname] HostName;缺省时 ssh 以别名为地址
16
+ * @property {string} [user] User
17
+ */
18
+
19
+ const GLOB_CHARS = new Set(['*', '?', '!']);
20
+
21
+ /** @param {string} pattern Host 模式 */
22
+ function isExactPattern(pattern) {
23
+ return ![...pattern].some((c) => GLOB_CHARS.has(c));
24
+ }
25
+
26
+ /**
27
+ * 解析主 ssh config 的静态 Host 块。
28
+ * @param {string} text ~/.ssh/config 原文
29
+ * @returns {Map<string, StaticHost>} key=精确别名
30
+ */
31
+ export function parseStaticHosts(text) {
32
+ /** @type {Map<string, StaticHost>} */
33
+ const table = new Map();
34
+ /** @type {string[]} */
35
+ let currentPatterns = [];
36
+ let inMatch = false;
37
+
38
+ const putFirst = (host, key, value) => {
39
+ if (host[key] === undefined) host[key] = value;
40
+ };
41
+
42
+ for (const raw of text.split('\n')) {
43
+ const line = raw.trim();
44
+ if (line.length === 0 || line.startsWith('#')) continue;
45
+ const cols = line.split(/\s+/);
46
+ const keyword = cols[0].toLowerCase();
47
+
48
+ if (keyword === 'match') {
49
+ inMatch = true;
50
+ currentPatterns = [];
51
+ continue;
52
+ }
53
+ if (keyword === 'host') {
54
+ inMatch = false;
55
+ // 精确模式入表(多模式逐个);同一别名多个 Host 块时 ssh 取首次值——
56
+ // 已存在的记录对象继续沿用,putFirst 保证不被后块覆盖
57
+ currentPatterns = cols.slice(1).filter(isExactPattern);
58
+ for (const p of currentPatterns) {
59
+ if (!table.has(p)) table.set(p, {});
60
+ }
61
+ continue;
62
+ }
63
+ if (inMatch || currentPatterns.length === 0) continue;
64
+ if (keyword === 'hostname' || keyword === 'user') {
65
+ const value = cols.slice(1).join(' ');
66
+ if (value) {
67
+ for (const p of currentPatterns)
68
+ putFirst(table.get(p), keyword === 'hostname' ? 'hostname' : 'user', value);
69
+ }
70
+ }
71
+ }
72
+ return table;
73
+ }
@@ -1,6 +1,6 @@
1
1
  #!/bin/bash
2
2
  # ssh-net-link-core:edge 上到 core 的常驻隧道(-D SOCKS + -L VNC)。
3
- # argv: <self 别名> <peer 别名> <转发规格…>
3
+ # argv: <self 别名> <peer 别名> <relay 别名> <relay 端口> <peer 用户> <转发规格…>
4
4
  # 转发规格(buildForwardSpecs 产出,不是裸 ssh 片段):D:<本地口> 或
5
5
  # L:<本地口>:<目标口>:<目标>;目标是 IP,或关键字 loopback6——后者按当前
6
6
  # mode 渲染:peer 走 [::1]、relay/其他退 127.0.0.1(两态都落地 core,
@@ -38,7 +38,10 @@ RM=${RM:-/bin/rm}
38
38
 
39
39
  self=$1
40
40
  peer=$2
41
- shift 2
41
+ relay_alias=$3
42
+ relay_port=$4
43
+ peer_user=$5
44
+ shift 5
42
45
  fwd=("$@") # 转发规格(D:/L:),mode 确定后经 build_fwd_args 渲染
43
46
 
44
47
  # 转发规格 → ssh -D/-L 参数(结果写全局数组 FWD_SSH)。bind 恒 127.0.0.1
@@ -71,7 +74,21 @@ build_fwd_args() {
71
74
  # 事件日志:一行一事件(date 绝对路径,launchd 无交互 PATH)。ssh 自身的
72
75
  # stderr 照旧落同一文件但无时间戳——事件行负责锚定时刻(design §6.1)
73
76
  log() { echo "$(/bin/date '+%F %T') $*" >&2; }
74
- log "link 启动(self=$self peer=$peer 转发 ${#fwd[@]} 组)"
77
+ log "link 启动(self=$self peer=$peer relay=$relay_alias:$relay_port 转发 ${#fwd[@]} 组)"
78
+
79
+ # 报名 ssh(循环顶与 TTL 到点重报共用):固定经 relay,命令行显式 -J——
80
+ # 字面目标 127.0.0.1 不命中 Match originalhost "$peer",绕开自动选路
81
+ #(peer 僵尸/冷启动时自动选路会把报名一起挂死,故不碰 <peer>-via-relay 类
82
+ # 别名);跳板 relay_alias 的地址/用户由 ssh config Host 块提供;
83
+ # HostKeyAlias 让三路径共用同一条 known_hosts。参数 = 本次上报的 v6
84
+ announce() {
85
+ "$SSH" -J "$relay_alias" -p "$relay_port" \
86
+ -o HostKeyAlias="$peer" \
87
+ -o BatchMode=yes -o ConnectTimeout=15 \
88
+ -o ServerAliveInterval=10 -o ServerAliveCountMax=2 \
89
+ -o ControlMaster=no -o ControlPath=none \
90
+ "$peer_user@127.0.0.1" "ssh-net _register $self $1" >/dev/null 2>&1
91
+ }
75
92
 
76
93
  relay_on_file="$STATE_DIR/RELAY_ON"
77
94
  peer_on_file="$STATE_DIR/PEER_ON"
@@ -178,17 +195,14 @@ while :; do
178
195
  [ -z "$v6" ] && log "冷启动宽限:${V6_GRACE}s 内无 v6(v4-only 网络),落中继"
179
196
  fi
180
197
 
181
- # 报名(PEER_ON 控)无条件走固定 relay 别名(peer 僵尸/冷启动都可达);
198
+ # 报名(PEER_ON 控)固定经 relay(announce 封装,peer 僵尸/冷启动都可达);
182
199
  # 失败不阻断,只在日志留痕——报名长期失败(如 relay 别名漂移)是静默
183
200
  # 降级:中继照常工作、peer 永远建不起来,status 看不出区别,唯一的
184
201
  # 线索在这里。失败用短周期重试(下方 timer 的 RETRY_TTL),不再等
185
202
  # 600s 寿命
186
203
  announce_ok=1
187
204
  if [ -n "$v6" ] && [ "$peer_on" = 1 ]; then
188
- if ! "$SSH" -o BatchMode=yes -o ConnectTimeout=15 \
189
- -o ServerAliveInterval=10 -o ServerAliveCountMax=2 \
190
- -o ControlMaster=no -o ControlPath=none \
191
- "$peer-via-relay" "ssh-net _register $self $v6" >/dev/null 2>&1; then
205
+ if ! announce "$v6"; then
192
206
  announce_ok=0
193
207
  echo "$(/bin/date '+%F %T') 报名失败($self $v6):中继不受影响,${RETRY_TTL}s 后重试" >&2
194
208
  fi
@@ -316,10 +330,7 @@ while :; do
316
330
  # 两边互等;PEER_ON 关时不报,那是开关语义)
317
331
  if [ "$peer_on" = 1 ]; then
318
332
  fresh_v6=$("$BIN_DIR/sn-ipv6" 2>/dev/null)
319
- if [ -n "$fresh_v6" ] && "$SSH" -o BatchMode=yes -o ConnectTimeout=15 \
320
- -o ServerAliveInterval=10 -o ServerAliveCountMax=2 \
321
- -o ControlMaster=no -o ControlPath=none \
322
- "$peer-via-relay" "ssh-net _register $self $fresh_v6" >/dev/null 2>&1; then
333
+ if [ -n "$fresh_v6" ] && announce "$fresh_v6"; then
323
334
  log "到点探不中:已用实时 v6 重报($fresh_v6)"
324
335
  # 重报成功给回拨一个短窗口,命中即收编(core 唤醒/
325
336
  # kickstart 通常几秒内);不中落回循环头续睡
@@ -12,6 +12,9 @@ LAUNCHCTL=${LAUNCHCTL:-/bin/launchctl}
12
12
  ID=${ID:-/usr/bin/id}
13
13
  STATE_DIR=${SSH_NET_STATE_DIR:-$HOME/.ssh/ssh-net/state}
14
14
  BIN_DIR=${SSH_NET_BIN_DIR:-$HOME/.ssh/ssh-net/bin}
15
+ # core 上给人用的 edge 入口片段目录(design §4.2):休眠即删,喂参测试可注入
16
+ CONF_DIR=${SSH_NET_CONF_DIR:-$HOME/.ssh/ssh-net/conf.d}
17
+ RM=${RM:-/bin/rm}
15
18
  CLEAR_TTL=${SSH_NET_CLEAR_TTL:-30} # 持续存活满 30s 清零失败计数
16
19
  FAIL_LIMIT=${SSH_NET_FAIL_LIMIT:-6}
17
20
  RETRY_SLEEP=${SSH_NET_RETRY_SLEEP:-30}
@@ -53,6 +56,12 @@ start_clear_timer() {
53
56
 
54
57
  fails=0
55
58
  rounds=0
59
+
60
+ # 休眠 = edge 当前不在线:删掉给人用的 conf.d/edge-<别名> 入口,免得
61
+ # `ssh <别名>` 拨向必然失败的旧 v6;下次报名 _register 连同 state 写回。
62
+ # 与 _register 的写有竞态(本删晚于报名的写):edge 的 TTL 重报走 noop
63
+ # 分支会补写片段,最坏一个重报周期入口缺失(只影响人主动 ssh,不影响隧道)
64
+ retire_host_fragment() { "$RM" -f "$CONF_DIR/edge-$alias_name" 2>/dev/null || true; }
56
65
  while :; do
57
66
  if [ -n "${SSH_NET_MAX_ROUNDS:-}" ]; then
58
67
  rounds=$((rounds + 1))
@@ -69,6 +78,7 @@ while :; do
69
78
  # 不空转拨号,也不删任何东西
70
79
  if [ -z "$v6" ]; then
71
80
  log "state 无 v6(人工误删?)→ disable 休眠,等下次报名唤醒"
81
+ retire_host_fragment
72
82
  "$LAUNCHCTL" disable "gui/$("$ID" -u)/$label"
73
83
  exit 0
74
84
  fi
@@ -112,6 +122,7 @@ while :; do
112
122
  # 当下零重拉靠本 exit 0(SuccessfulExit=false 只在非自愿退出时重拉);
113
123
  # disable 管加载期拦截与跨登录持久(实测矩阵见 notes)
114
124
  log "$FAIL_LIMIT 次快速失败 → disable 休眠(正常路径:edge 关机/合盖/不可达;等下次报名唤醒)"
125
+ retire_host_fragment
115
126
  "$LAUNCHCTL" disable "gui/$("$ID" -u)/$label"
116
127
  exit 0
117
128
  fi
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ssh-net",
3
- "version": "26.10.23",
3
+ "version": "26.10.24",
4
4
  "type": "module",
5
5
  "description": "个人 SSH 组网:v6 直连优先、relay 兜底、关机有界重试后静默",
6
6
  "bin": {