ssh-net 26.11.3 → 26.11.67

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
@@ -1,13 +1,37 @@
1
1
  # Changelog
2
2
 
3
- 本项目使用 npm 公共分发,版本号格式为**年.月.序号**:月内序号递增,
4
- 跨月从 1 开始;历史跳号不补、不另维护累计发包数。旧版本描述不改写为
5
- 当前事实。
3
+ 版本号采用**年.月.累计序号**。末位是本版发布后公共 npm 上的版本总数,包含早期的 `0.x` 版本。每发布一版加 1,跨月、跨年都接着计数。历史版本号保留原样
6
4
 
7
5
  更早的版本按月整月归档在 [docs/changelog/](docs/changelog/),归档规则见
8
6
  [docs/releasing.md](docs/releasing.md#changelog-归档)。新条目的小节限用
9
7
  五个词表:新增、修复、简化、文档、测试;历史条目的旧词头不追溯。
10
8
 
9
+ ## [26.11.67] - 2026-11-21
10
+
11
+ ### 修复
12
+
13
+ - `status --probe` 在转发任务换进程后,不再把旧进程留下的端口快照判成新任务健康
14
+ - 自动选路遇到没有 SSH 标识的旧监听时直接报名,不再额外查询和结束本机持口会话;人工 `start peer` 保留强恢复。本机查询超时会清除 FORCE 越过的旧失败印记,下条自动连接可立即重试
15
+
16
+ ### 简化
17
+
18
+ - 本地转发自己恢复直连时直接使用新连接,不再额外重连一次;其他连接恢复时仍按 relay 开关切换旧转发
19
+
20
+ ## [26.11.66] - 2026-11-20
21
+
22
+ ### 修复
23
+
24
+ - edge 开盖后,若旧回拨端口持续没有 SSH 标识,会在请求重拨前再探一次。直连已恢复就复用,仍无响应才尝试结束本用户的旧 SSH 会话。本轮等到直连时,正在运行的本地转发会重连一次,转发自己发起回拨时也一样
25
+ - 回拨报名使用本轮剩余等待时间,跳过尚未就绪或已失效的 IPv6 地址。edge 安装时会检查 `timeout`,缺少时提示安装 `coreutils`
26
+ - edge 安装失败会恢复原有选路片段、软链和任务禁用状态。`status --probe` 遇到转发进程重连时会复查端口归属,减少把已恢复端口报成关闭的情况
27
+ - Linux node 修改中继配置时,由 systemd 一次完成重启。安装断线后重试会核对实际运行的服务,已切换成功就保留现有连接。更新失败时恢复旧配置和自启状态,期间手动停用的中继保持停用。并发安装会依次执行
28
+ - relay 改名后重新安装会清理旧任务,失败时尝试恢复原服务。安装会核对 SSH 的 `Include` 位于首个 `Host` 或 `Match` 之前,并按 OpenSSH 版本判断 `${HOME}` 写法能否生效
29
+ - `update` 会核对正在使用的 npm 全局目录,从刚更新的包运行 `install`,避免切换 Node 环境后更新到另一份安装
30
+
31
+ ### 文档
32
+
33
+ - 恢复按 npm 累计发布次数编号,本版为第 66 个公开版本
34
+
11
35
  ## [26.11.3] - 2026-11-20
12
36
 
13
37
  ### 简化
package/README.md CHANGED
@@ -44,13 +44,16 @@ Linux devbox(node),也让 core/node 能连回 edge。五台工作机之外
44
44
 
45
45
  1. 五台工作机都有 Node 24+ 和 npm,非交互 SSH 的 PATH 已包含 npm 全局 bin,
46
46
  保证安装后能找到 `ssh-net`;node 的管理命令统一通过 `sudo -i` 运行,避免
47
- sudo 的 `secure_path` 丢掉 fnm 路径。node 安装时也会检查 `HOME` 与 root 账户的家目录一致
47
+ sudo 的 `secure_path` 丢掉 fnm 路径。在 node 上以 root 安装、升级、停止或卸载时,`HOME` 必须指向 root 的家目录
48
48
  2. 运行 `dot apply ssh`,落盘 `~/.ssh/ssh-net/topology`、静态 Host 块,以及
49
- 位于所有 Host 块之前的 `Include ~/.ssh/ssh-net/conf.d/*`。topology 管名称、
49
+ 位于首个 `Host` 或 `Match` 之前的 `Include ~/.ssh/ssh-net/conf.d/*`。topology 管名称、
50
50
  用户和端口,静态 IP 只放在 `~/.ssh/config`;格式见 [design §4](docs/design.md#4-个人配置dotfiles-托管)
51
51
  3. 按 [design §7](docs/design.md#7-安全模型与一次性准备) 完成系统准备:core
52
52
  自动登录、edge 远程登录、sshd 密钥认证与保活、私钥和 relay host key 预置
53
- 4. edge 会安装 topology 里配置的本地转发;要使用 SOCKS/VNC,需先在 core 上
53
+ 4. 只有 edge 需要 `timeout`,用来限制一次回拨报名的时长。系统自带时无需安装;
54
+ 如果 `ssh-net install` 提示缺少它,手动运行 `brew install coreutils`,再重跑
55
+ `ssh-net install`。Homebrew 装在默认位置时无需修改 `PATH`
56
+ 5. edge 会安装 topology 里配置的本地转发;要使用 SOCKS/VNC,需先在 core 上
54
57
  单独配置目标服务,ssh-net 不安装或启动这些服务。没有 `forward` 配置时,
55
58
  edge 仍可选路,也不会为转发保持 SSH 连接
56
59
 
@@ -120,12 +123,15 @@ edge 不自动判断所在网络,按下面的场景与需求手动操作:
120
123
 
121
124
  `start`、`stop` 只管理本机到 relay 的中继通道。core 到各 edge 的回连任务由
122
125
  edge 的通知和两次重试机制自动管理,不需要手动干预;node 的中继服务由 systemd
123
- 自动重启。需要手动重拉中继时,先 `stop` 再 `start`
126
+ 自动重启。需要手动重拉中继时,先 `stop` 再 `start`。如果 node 的 `status` 或
127
+ `start` 提示配置更新尚未完成,运行 `sudo -i ssh-net install` 继续上次安装
124
128
 
125
129
  core 的 status 中,edge 行只列出**自动连接任务**的注册、运行、休眠和上次
126
130
  退出事实;下方「ssh 入口」是最近登记的地址及其新旧。core/node 的 `status --probe`
127
131
  检查本机在 relay 上的注册端口是否在监听
128
132
 
133
+ relay 改名后,先把新的 topology 和 SSH 配置同步到各台工作机,再在 core、node 和每台 edge 上运行 `ssh-net install`。core 和 node 会切换中继任务,各台 edge 会更新选路配置。`status` 会提示残留的旧任务。部署新任务失败时,安装命令会尝试恢复原服务并报告原因
134
+
129
135
  ### 退出码
130
136
 
131
137
  - `status`:默认本地快查,0 表示没有本地「需要处理」事项,1 表示有处理项或
@@ -147,6 +153,7 @@ ssh-net update <版本号> # 切换或回滚;显式当前版也会重跑 i
147
153
  `ssh-net update <当前版本>`,或直接运行 `ssh-net install`
148
154
  - 查询失败或 registry 返回比当前更旧的版本时,在安装前停止,不退回 `@latest`;
149
155
  安装失败直接保留 npm 原因,刚发布遇到 ETARGET 时等几分钟,用同一明确版本号重试
156
+ - 如果使用 fnm 等工具切换过 Node 版本,先切回原来安装 `ssh-net` 的环境。当前 npm 的全局目录与原安装不一致时,`update` 会在换包前提示
150
157
  - node 使用 `sudo -i ssh-net update`;开发机的 `npm link` 状态不要用 update
151
158
  - edge 升级保留 relay/peer 开关。旧版没有安装 link 的机器也会装上转发任务;
152
159
  如配置的端口已被其他程序占用,先释放端口,再运行 `ssh-net install`
@@ -193,8 +200,8 @@ sudo -i npm uninstall -g ssh-net
193
200
  sshd 读不到用户密钥,core 无法回连
194
201
  - 休眠在当前登录会话内已验证;跨 core 重登录/重启的持久拦截尚未完成真机
195
202
  验证,不承诺这部分行为
196
- - 休眠唤醒后,旧回拨端口可能仍在监听。如果一秒内读不到 SSH 标识,本次连接走中继。
197
- 已有连接可以继续传输;若确实断线,等 sshd 回收旧监听后,下次连接会重新尝试直连
203
+ - 自动恢复遇到旧回拨端口没有 SSH 标识时直接报名,不额外查杀本机持口会话;报名本身仍会让 core 重拨。人工 `start peer` 还会尝试结束占口的 SSH 会话以加速释放端口,旧会话上的终端和 VNC 也可能断开
204
+ - 其他连接在等待期间恢复了直连时,正在运行的本地转发会重连一次;转发自己发起的恢复直接使用新连接,不再额外重启。等待已结束后才恢复的直连供后续连接使用
198
205
  - 6 秒是通知 core 并等待回连的预算,不包含本机 IPv6 查询的绝对硬超时
199
206
  - edge 入口地址 32 小时未刷新即不再采用;地址仍新鲜但机器离线时,连接会在
200
207
  5 秒 ConnectTimeout 后失败,没有第二级入口回退
package/libexec/cli.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  // 本文件只做装配、帮助与错误边界。
4
4
  import os from 'node:os';
5
5
  import { parseTopology, validateHostContract } from './lib/config.mjs';
6
- import { parseStaticHosts } from './lib/sshconfig.mjs';
6
+ import { parseStaticHosts, supportsIncludeEnv } from './lib/sshconfig.mjs';
7
7
  import { localHostname, matchIdentity } from './lib/identity.mjs';
8
8
  import { machinePaths } from './lib/paths.mjs';
9
9
  import { createStateStore } from './lib/state.mjs';
@@ -91,7 +91,9 @@ function buildTopologyContext() {
91
91
 
92
92
  function buildContext() {
93
93
  const ctx = buildTopologyContext();
94
- const hostTable = parseStaticHosts(readConfig(ctx.paths.sshConfigFile) ?? '');
94
+ let includeEnv;
95
+ const hostTable = parseStaticHosts(readConfig(ctx.paths.sshConfigFile) ?? '', ctx.paths,
96
+ () => includeEnv ??= supportsIncludeEnv(ctx.runner));
95
97
  validateHostContract(ctx.topo, hostTable);
96
98
  return { ...ctx, hostTable };
97
99
  }
@@ -9,17 +9,20 @@ import { removeJobs, syncPlist } from '../lib/manage.mjs';
9
9
  import { syncConfFile } from '../lib/conf.mjs';
10
10
  import { ensureRuntime } from '../lib/runtime.mjs';
11
11
  import { edgeLinkJob, coreRelayJob, nodeRelayJob } from '../lib/jobs.mjs';
12
+ import { requireNodeHome } from '../lib/identity.mjs';
12
13
  import * as launchd from '../lib/launchd.mjs';
13
14
  import * as systemd from '../lib/systemd.mjs';
14
15
  import {
15
- forwardListenerPids, lsofListen, v6LoopbackPids, peerProbeOk,
16
+ forwardListenerPids, hasRouteTimeout, lsofListen, v6ListenerScope, peerProbeOk,
16
17
  } from '../lib/probe.mjs';
17
- import { readDirOrEmpty } from '../lib/fsutil.mjs';
18
+ import { isExecutableFile, readDirOrEmpty, removeObsoleteNames } from '../lib/fsutil.mjs';
18
19
  import { packageScriptPath } from '../lib/paths.mjs';
19
20
  import {
20
21
  SN_PROBE, RESIDENT_SCRIPTS, edgeRuntimePlan, coreNodeRuntimePlan,
21
22
  } from '../lib/manifest.mjs';
22
- import { linkLabel, linkLinkName, renderEdgeHost, renderRoutes } from '../lib/render.mjs';
23
+ import {
24
+ edgeLabel, linkLabel, linkLinkName, relayLabel, relayLinkName, renderEdgeHost, renderRoutes,
25
+ } from '../lib/render.mjs';
23
26
 
24
27
  /** 只有常驻脚本本身发生变化,才提示要等进程重连 */
25
28
  function syncRuntime(ctx, { entities, links }) {
@@ -40,11 +43,13 @@ function deploymentNote(r, task, config) {
40
43
  return r.restarted ? `${config}已更新,可能断开当前连接` : `${task}已同步`;
41
44
  }
42
45
 
43
- function coreNodeInstallMsg(comp, entryChanged, result, relayLine) {
46
+ function coreNodeInstallMsg(ctx, comp, entryChanged, result, removed) {
47
+ const relayLine = `${ctx.topo.relay.alias} 入口 ${ctx.self.relayPort}`;
44
48
  const note = notesPart(
45
49
  comp,
46
50
  entryChanged ? 'edge 入口已更新' : '',
47
51
  deploymentNote(result, '中继任务', '中继服务配置'),
52
+ removed ? '旧中继组件已移除' : '',
48
53
  );
49
54
  if (!note)
50
55
  return `已安装,服务配置无需改动;中继通道已开启(${relayLine})`;
@@ -66,13 +71,13 @@ async function precheckEdgePorts({ runner, uid, topo }, labels) {
66
71
  }
67
72
  }
68
73
 
69
- // 只检查回拨使用的 IPv6 环回地址;同号的 IPv4 监听可以共存。
74
+ // 检查覆盖 [::1] 的 IPv6 监听;同号的纯 IPv4 监听可以共存。
70
75
  // 用包内探针读 SSH 标识,不能让磁盘上待修复的探针堵住 install
71
76
  const listeners = lsofListen(runner, CALLBACK_PORT);
72
- if (
73
- v6LoopbackPids(listeners, CALLBACK_PORT).length > 0
74
- && !(await peerProbeOk(runner, path.dirname(packageScriptPath(SN_PROBE))))
75
- ) {
77
+ const scope = v6ListenerScope(listeners, CALLBACK_PORT);
78
+ if (scope === 'wildcard')
79
+ throw new Error(`端口 ${CALLBACK_PORT} 的 IPv6 通配监听占用了回拨地址 [::1]:\n${listeners}`);
80
+ if (scope === 'loopback' && !(await peerProbeOk(runner, path.dirname(packageScriptPath(SN_PROBE))))) {
76
81
  throw new Error(
77
82
  `端口 ${CALLBACK_PORT} 有程序在监听但没有响应(多半是断线残留,或被别的程序占用):\n${listeners}`,
78
83
  );
@@ -88,36 +93,44 @@ export function notifyDepNote({ hasTerminalNotifier, hasOsascript }) {
88
93
  }
89
94
 
90
95
  function localNotifyDepNote() {
91
- const execOk = (p) => {
92
- try { fs.accessSync(p, fs.constants.X_OK); return true; } catch { return false; }
93
- };
94
96
  return notifyDepNote({
95
- hasTerminalNotifier: TERMINAL_NOTIFIER_PATHS.some(execOk),
96
- hasOsascript: execOk(OSASCRIPT_PATH),
97
+ hasTerminalNotifier: TERMINAL_NOTIFIER_PATHS.some(isExecutableFile),
98
+ hasOsascript: isExecutableFile(OSASCRIPT_PATH),
97
99
  });
98
100
  }
99
101
 
102
+ /** 只收回指定前缀下不再使用的文件;即使对应任务早已移除,也能清掉残留 */
103
+ function removeObsoleteFiles(dir, prefix, keep) {
104
+ const obsolete = readDirOrEmpty(dir).filter((name) => name.startsWith(prefix) && !keep.includes(name));
105
+ return removeObsoleteNames(dir, obsolete, keep);
106
+ }
107
+
100
108
  async function installEdge(ctx) {
101
109
  const { topo, paths } = ctx;
102
110
  const link = edgeLinkJob(ctx);
103
111
  const diskLabels = launchd.labelsOnDisk(paths.launchAgentsDir, linkLabel(''));
104
112
  const obsolete = diskLabels.filter((label) => label !== link?.label);
105
113
  await precheckEdgePorts(ctx, link ? [link.label, ...obsolete] : []);
106
- const runtime = edgeRuntimePlan(topo);
107
- const comp = syncRuntime(ctx, runtime);
108
- // relay 已开时,注册 link 就可能立即发起 ssh;先让它读到本次安装的选路配置
109
- const routesChanged = syncConfFile(paths.routesFile, renderRoutes(topo, ctx.self.alias));
110
- removeJobs(ctx, obsolete);
111
- for (const name of readDirOrEmpty(paths.binDir)) {
112
- if (name.startsWith(linkLinkName('')) && !runtime.links.some(([keep]) => name === keep))
113
- fs.rmSync(paths.binScript(name), { force: true });
114
- }
114
+ const comp = syncRuntime(ctx, edgeRuntimePlan(topo));
115
+ // link 可能在 bootstrap 内立即连接;新旧任务各自启动前都要读到配套的 routes
116
+ let routesChanged = false;
117
+ let restoreRoutes;
118
+ const routes = {
119
+ apply() {
120
+ routesChanged = syncConfFile(paths.routesFile, renderRoutes(topo, ctx.self.alias), restore => { restoreRoutes = restore; });
121
+ },
122
+ restore() { restoreRoutes?.(); },
123
+ };
115
124
  let linkNote = '';
116
125
  if (link) {
117
- const job = syncPlist(ctx, link);
126
+ const job = syncPlist(ctx, link, obsolete, routes);
118
127
  if (job.lintError) throw new Error(`link plist 校验失败:${job.lintError}`);
119
128
  linkNote = deploymentNote(job, '本地转发任务', '本地转发配置');
129
+ } else {
130
+ removeJobs(ctx, obsolete);
131
+ routes.apply();
120
132
  }
133
+ removeObsoleteFiles(paths.binDir, linkLinkName(''), [linkLinkName(topo.core.alias)]);
121
134
  fs.rmSync(paths.legacyLinkEnabledFile, { force: true });
122
135
 
123
136
  const note = notesPart(comp, linkNote, obsolete.length ? '旧转发任务已移除' : '',
@@ -131,59 +144,61 @@ async function installEdge(ctx) {
131
144
  function syncEdgeEntries(ctx) {
132
145
  const { topo, paths } = ctx;
133
146
  let changed = false;
134
- const keep = new Set();
147
+ const keep = [];
135
148
  for (const e of topo.edges) {
136
149
  const file = paths.edgeHostFile(e.alias);
137
- keep.add(path.basename(file));
150
+ keep.push(path.basename(file));
138
151
  if (syncConfFile(file, renderEdgeHost(e))) changed = true;
139
152
  }
140
- const existing = readDirOrEmpty(paths.confDir);
141
- const edgePrefix = path.basename(paths.edgeHostFile(''));
142
- for (const f of existing) {
143
- if (f.startsWith(edgePrefix) && !keep.has(f)) {
144
- fs.rmSync(path.join(paths.confDir, f), { force: true });
145
- changed = true;
146
- }
147
- }
148
- return changed;
153
+ const removed = removeObsoleteFiles(paths.confDir, path.basename(paths.edgeHostFile('')), keep);
154
+ return changed || removed;
149
155
  }
150
156
 
151
157
  function installCore(ctx) {
152
158
  const { topo, paths } = ctx;
159
+ const job = coreRelayJob(ctx);
160
+ const labels = launchd.labelsOnDisk(paths.launchAgentsDir);
161
+ const relayPrefix = relayLabel('');
162
+ const obsolete = labels.filter((label) => label.startsWith(relayPrefix) && label !== job.label);
153
163
  const entryChanged = syncEdgeEntries(ctx);
154
- // 更新时一并刷新已经登记的回拨脚本,不必等待各 edge 再次报名
155
- const edges = launchd.edgeAliasesOnDisk(paths.launchAgentsDir);
164
+ // 同一份磁盘清单里,旧中继要撤掉,已经登记的回拨只刷新脚本
165
+ const edgePrefix = edgeLabel('');
166
+ const edges = labels.filter((label) => label.startsWith(edgePrefix))
167
+ .map((label) => label.slice(edgePrefix.length));
156
168
  const comp = syncRuntime(ctx, coreNodeRuntimePlan(topo, edges));
157
- const r = syncPlist(ctx, coreRelayJob(ctx));
169
+ const r = syncPlist(ctx, job, obsolete);
158
170
  if (r.lintError) throw new Error(`relay plist 校验失败:${r.lintError}`);
159
- return coreNodeInstallMsg(comp, entryChanged, r,
160
- `${topo.relay.alias} 入口 ${topo.core.relayPort}`);
171
+ const removedLinks = removeObsoleteFiles(paths.binDir, relayLinkName(''), [relayLinkName(topo.relay.alias)]);
172
+ return coreNodeInstallMsg(ctx, comp, entryChanged, r, obsolete.length || removedLinks);
161
173
  }
162
174
 
163
- function installNode(ctx) {
164
- const { topo, runner } = ctx;
165
- if (ctx.uid !== 0)
166
- throw new Error('node 安装写 /etc/systemd/system 需要 root,请运行 sudo -i ssh-net install');
167
- const { home, ...job } = nodeRelayJob(ctx);
168
- if (ctx.env.HOME !== home)
169
- throw new Error('HOME 与 root 账户的家目录不一致,请运行 sudo -i ssh-net install');
170
- // ExecStart 按空白分词,HOME 含空白会拆断脚本路径
171
- if (/\s/.test(home))
172
- throw new Error(`node 的 HOME(${home})含空白字符:systemd ExecStart 无法转义,拒绝安装`);
175
+ function installNode(ctx, home) {
176
+ const { topo, paths, runner } = ctx;
177
+ const job = nodeRelayJob(ctx, home);
178
+ const obsolete = systemd.unitNamesOnDisk(paths.systemdUnitDir, relayLinkName(''))
179
+ .filter((unit) => unit !== job.unitName);
173
180
  const entryChanged = syncEdgeEntries(ctx);
174
181
  const comp = syncRuntime(ctx, coreNodeRuntimePlan(topo));
175
- const r = systemd.syncUnit(runner, job);
176
- return coreNodeInstallMsg(comp, entryChanged, r,
177
- `${topo.relay.alias} 入口 ${ctx.self.relayPort}`);
182
+ const r = systemd.syncUnit(runner, job, obsolete);
183
+ const removedLinks = removeObsoleteFiles(paths.binDir, relayLinkName(''), [relayLinkName(topo.relay.alias)]);
184
+ return coreNodeInstallMsg(ctx, comp, entryChanged, r, obsolete.length || removedLinks);
178
185
  }
179
186
 
180
187
  /** @param {object} ctx @param {string[]} [args] */
181
188
  export async function run(ctx, args = []) {
182
189
  if (args.length) throw new Error('用法:ssh-net install 不带参数');
183
- switch (ctx.role) {
184
- case 'edge': return installEdge(ctx);
185
- case 'core': return installCore(ctx);
186
- case 'node': return installNode(ctx);
187
- default: throw new Error(`未知角色:${ctx.role}`);
188
- }
190
+ if (ctx.role === 'core') return installCore(ctx);
191
+ if (!['edge', 'node'].includes(ctx.role)) throw new Error(`未知角色:${ctx.role}`);
192
+ if (ctx.role === 'edge' && !hasRouteTimeout(ctx.env))
193
+ throw new Error('缺少可执行的 timeout,未安装 edge 组件。请在这台机器上运行 brew install coreutils,再重跑 ssh-net install');
194
+ const home = ctx.role === 'node' ? requireNodeHome(ctx, 'install') : null;
195
+ // routes 和 systemd 恢复记录都跨多步更新。同一账户的两次安装不能替对方回滚
196
+ const fd = fs.openSync(ctx.paths.sshDir, 'r');
197
+ try {
198
+ const mac = (ctx.platform ?? process.platform) === 'darwin';
199
+ const lock = ctx.runner.run(mac ? 'lockf' : 'flock', mac ? ['-s', '-t', '0', '3'] : ['-n', '3'],
200
+ { stdio: ['ignore', 'pipe', 'pipe', fd] });
201
+ if (lock.code !== 0) throw new Error(`无法取得安装锁:${lock.error?.message || lock.stderr.trim() || '有其他安装正在运行,请稍后重试'}`);
202
+ return ctx.role === 'node' ? installNode(ctx, home) : await installEdge(ctx);
203
+ } finally { fs.closeSync(fd); }
189
204
  }
@@ -2,6 +2,7 @@
2
2
  // core 重新启用中继,node 走 systemctl。edge 的本地转发随 relay 启停。
3
3
  // 人工恢复 peer 复用 sn-route,不在控制面另维护一套报名实现
4
4
  import fs from 'node:fs';
5
+ import path from 'node:path';
5
6
  import * as systemd from '../lib/systemd.mjs';
6
7
  import { ensureLoaded } from '../lib/manage.mjs';
7
8
  import { SWITCH_NAMES } from '../lib/state.mjs';
@@ -73,7 +74,12 @@ export function run(ctx, args = []) {
73
74
  throw new Error('本机是单总开关,start 不带参数(-a/--all 亦可,等同缺省)');
74
75
  if (ctx.role === 'core') return startCore(ctx);
75
76
  if (ctx.role === 'node') {
76
- systemd.enableStart(ctx.runner, relayUnitName(ctx.topo.relay.alias));
77
+ const unit = relayUnitName(ctx.topo.relay.alias);
78
+ systemd.enableStart(ctx.runner, unit);
79
+ if (systemd.hasPendingUpdate(path.join(ctx.paths.systemdUnitDir, unit))) {
80
+ const text = '中继服务已启动,配置更新尚未完成——跑一次 ssh-net install 完成更新';
81
+ return { text, issues: [text] };
82
+ }
77
83
  return '中继通道已开启';
78
84
  }
79
85
  throw new Error(`未知角色:${ctx.role}`);
@@ -8,7 +8,7 @@ import { auditScript, auditLink } from '../lib/runtime.mjs';
8
8
  import { packageScriptPath } from '../lib/paths.mjs';
9
9
  import * as launchd from '../lib/launchd.mjs';
10
10
  import * as systemd from '../lib/systemd.mjs';
11
- import { peerProbeOk, tcpOpen, classifyV6Probe, forwardListenerPids } from '../lib/probe.mjs';
11
+ import { peerProbeOk, tcpOpen, classifyV6Probe, forwardListenerPids, hasRouteTimeout } from '../lib/probe.mjs';
12
12
  import { readFileOrNull } from '../lib/fsutil.mjs';
13
13
  import { LAN_ADDR_RE } from '../lib/constants.mjs';
14
14
  import {
@@ -17,7 +17,7 @@ import {
17
17
  } from '../lib/manifest.mjs';
18
18
  import { edgeLinkJob, coreRelayJob, nodeRelayJob } from '../lib/jobs.mjs';
19
19
  import {
20
- edgeLabel, linkLabel, renderEdgeHost, renderRoutes, coreViaRelayArgs, probeSshOpts,
20
+ edgeLabel, linkLabel, relayLabel, relayLinkName, renderEdgeHost, renderRoutes, coreViaRelayArgs, probeSshOpts,
21
21
  } from '../lib/render.mjs';
22
22
 
23
23
  /**
@@ -128,6 +128,26 @@ async function relayPathProbe(ctx) {
128
128
  return { ready: r.code === 0, detail: r.stderr.trim() };
129
129
  }
130
130
 
131
+ /** 在本地端口探测结束时确认进程归属,远端中继的响应时间不参与这个判断 */
132
+ async function probeForwardPorts(ctx, forwards, label, initialJob) {
133
+ const openTcp = ctx.openTcp ?? tcpOpen;
134
+ async function listeners({ listenPort }) {
135
+ if (!initialJob || !await openTcp('127.0.0.1', listenPort)) return [];
136
+ return forwardListenerPids(ctx.runner, listenPort);
137
+ }
138
+ const owners = await Promise.all(forwards.map(listeners));
139
+ const firstPid = initialJob?.pid;
140
+ const job = initialJob && owners.some(pids => !pids.includes(firstPid))
141
+ ? launchd.inspect(ctx.runner, ctx.uid, label) : initialJob;
142
+ const forwardViews = await Promise.all(forwards.map(async (f, i) => {
143
+ let ok = owners[i].includes(job?.pid);
144
+ // 探测可能恰好落在两任进程之间。只为换了进程又没认领的端口再查一次
145
+ if (!ok && job?.pid && job.pid !== firstPid) ok = (await listeners(f)).includes(job.pid);
146
+ return [forwardLabel(f), ok];
147
+ }));
148
+ return { job, forwardViews };
149
+ }
150
+
131
151
  async function collectEdge(ctx, probe) {
132
152
  const { topo, paths, state } = ctx;
133
153
  const { issues, entityAudits } = runtimeIssues(ctx, edgeRuntimePlan(topo));
@@ -136,22 +156,17 @@ async function collectEdge(ctx, probe) {
136
156
  const onDisk = launchd.labelsOnDisk(paths.launchAgentsDir, linkLabel(''));
137
157
  if (onDisk.some((label) => label !== link?.label))
138
158
  issues.push('有旧的本地转发任务——跑一次 ssh-net install 清理');
139
- let job = null;
159
+ let initialJob = null;
140
160
  if (link && (entityAudits.some((a) => a.audit !== 'missing') || onDisk.includes(link.label))) {
141
161
  const issue = configFileIssue(link.plistPath, link.content, '本地转发配置', '需要更新');
142
162
  if (issue) issues.push(issue);
143
- job = launchd.inspect(ctx.runner, ctx.uid, link.label);
144
- if (!job.registered || job.disabled)
145
- issues.push(`本地转发任务${job.registered ? '已禁用' : '未注册'}——跑一次 ssh-net install 修复`);
146
- else if (switches.relay && !job.running)
147
- issues.push('本地转发任务未在运行——先 stop 再按原开关 start,或跑 ssh-net install 修复');
148
- if (!switches.relay && job.running)
149
- issues.push('relay 已关但本地转发仍在运行——再跑一次 ssh-net stop');
163
+ initialJob = launchd.inspect(ctx.runner, ctx.uid, link.label);
150
164
  }
151
165
 
152
166
  // routes 被手删/过期会让 ssh 静默退回 lan 直连,是故障。sn-route 没装时
153
167
  // 上面已报「尚未安装」,不重复
154
168
  if (entityAudits.some((a) => a.name === SN_ROUTE && a.audit === 'ok')) {
169
+ if (!hasRouteTimeout(ctx.env)) issues.push('缺少可执行的 timeout,无法发起回拨——运行 brew install coreutils');
155
170
  const issue = configFileIssue(
156
171
  paths.routesFile, renderRoutes(topo, ctx.self.alias), 'ssh 自动选路配置',
157
172
  );
@@ -169,18 +184,21 @@ async function collectEdge(ctx, probe) {
169
184
  // 就绪实测并发。relay 关闭时不探测;peer 软关闭只停止主动恢复,已有直连
170
185
  // 仍可能被新 ssh 使用,所以只要 relay 开着就继续做 banner 探测
171
186
  const relayProbe = ctx.relayOk ?? relayPathProbe; // 测试可注入同形结果
172
- const openTcp = ctx.openTcp ?? tcpOpen;
173
187
  const forwards = probe && switches.relay ? topo.forwards : [];
174
- const [relayResult, peerReady, portsOk, v6Probe] = await Promise.all([
188
+ const [relayResult, peerReady, { job, forwardViews }, v6Probe] = await Promise.all([
175
189
  probe && switches.relay ? relayProbe(ctx) : null,
176
190
  probe && switches.relay ? peerProbeOk(ctx.runner, paths.binDir) : null,
177
- Promise.all(forwards.map(async ({ listenPort }) => {
178
- if (!job?.pid || !await openTcp('127.0.0.1', listenPort)) return false;
179
- const owners = await forwardListenerPids(ctx.runner, listenPort);
180
- return owners.includes(job.pid);
181
- })),
191
+ probeForwardPorts(ctx, forwards, link?.label, initialJob),
182
192
  v6P,
183
193
  ]);
194
+ if (job) {
195
+ if (!job.registered || job.disabled)
196
+ issues.push(`本地转发任务${job.registered ? '已禁用' : '未注册'}——跑一次 ssh-net install 修复`);
197
+ else if (switches.relay && !job.running)
198
+ issues.push('本地转发任务未在运行——先 stop 再按原开关 start,或跑 ssh-net install 修复');
199
+ if (!switches.relay && job.running)
200
+ issues.push('relay 已关但本地转发仍在运行——再跑一次 ssh-net stop');
201
+ }
184
202
  const relayReady = relayResult?.ready ?? null;
185
203
  const relayDetail = relayResult?.detail ?? '';
186
204
 
@@ -199,8 +217,7 @@ async function collectEdge(ctx, probe) {
199
217
 
200
218
  return {
201
219
  role: 'edge', alias: ctx.self.alias, switches, probed: probe, relayReady, peerReady,
202
- job,
203
- forwardViews: forwards.map((f, i) => [forwardLabel(f), portsOk[i]]),
220
+ job, forwardViews,
204
221
  coreAlias: topo.core.alias, relayAlias: topo.relay.alias,
205
222
  v6, v6ProbeOk, issues,
206
223
  };
@@ -213,15 +230,13 @@ async function collectCore(ctx, probe) {
213
230
  // disabled override 是整域同一份字典:relay job 与各 edge job 共用一次拉取
214
231
  const dmap = launchd.disabledMap(ctx.runner, ctx.uid);
215
232
  const relayDeployment = coreRelayJob(ctx);
233
+ if (launchd.labelsOnDisk(paths.launchAgentsDir, relayLabel('')).some((name) => name !== relayDeployment.label))
234
+ issues.push('有旧的中继任务——跑一次 ssh-net install 清理');
216
235
  const configIssue = configFileIssue(
217
236
  relayDeployment.plistPath, relayDeployment.content, '中继服务配置', '需要更新',
218
237
  );
219
238
  if (configIssue) issues.push(configIssue);
220
- const relayJob = launchd.inspectWith(ctx.runner, ctx.uid, relayDeployment.label, dmap);
221
- // 实测时先发起来,边等边做注册态体检;默认快查不发起 ssh
222
- const relayPortP = probe
223
- ? relayPortListening(ctx, topo.core.relayPort)
224
- : Promise.resolve(null);
239
+ const relayJob = launchd.inspect(ctx.runner, ctx.uid, relayDeployment.label, dmap);
225
240
 
226
241
  // 回拨实体全 core 一份:循环外体检一次,各已注册 edge 只检各自的软链
227
242
  const callbackEntityAudit = topo.edges.length > 0
@@ -232,7 +247,7 @@ async function collectCore(ctx, probe) {
232
247
  const edges = [];
233
248
  for (const entry of entries) {
234
249
  const { alias } = entry;
235
- const st = launchd.inspectWith(ctx.runner, ctx.uid, edgeLabel(alias), dmap);
250
+ const st = launchd.inspect(ctx.runner, ctx.uid, edgeLabel(alias), dmap);
236
251
  // 已连接过的 edge 体检回拨脚本/软链:漏刷会拿旧脚本拨号
237
252
  if (st.registered) {
238
253
  const [linkName, entityName] = edgeCallbacksPlan([alias]).links[0];
@@ -253,7 +268,8 @@ async function collectCore(ctx, probe) {
253
268
  });
254
269
  }
255
270
 
256
- const relayPort = await relayPortP;
271
+ // 本地任务查询出错时直接返回错误,不留下仍在等待的 SSH 探测
272
+ const relayPort = probe ? await relayPortListening(ctx, topo.core.relayPort) : null;
257
273
  if (!relayJob.running) issues.push('relay 未在运行——ssh-net start 可拉起');
258
274
  if (relayJob.registered && relayJob.disabled)
259
275
  issues.push('relay 已禁用,后续加载可能被拦截——ssh-net start 可重新启用');
@@ -272,10 +288,13 @@ async function collectNode(ctx, probe) {
272
288
  const entries = edgeEntries(ctx, issues);
273
289
 
274
290
  const deployment = nodeRelayJob(ctx);
291
+ if (systemd.unitNamesOnDisk(ctx.paths.systemdUnitDir, relayLinkName('')).some((name) => name !== deployment.unitName))
292
+ issues.push('有旧的中继任务——跑一次 ssh-net install 清理');
275
293
  const configIssue = configFileIssue(
276
294
  deployment.unitPath, deployment.content, '中继服务配置', '需要更新',
277
295
  );
278
296
  if (configIssue) issues.push(configIssue);
297
+ if (systemd.hasPendingUpdate(deployment.unitPath)) issues.push('中继服务更新尚未完成——跑一次 ssh-net install 完成更新');
279
298
  const unit = deployment.unitName;
280
299
  const active = systemd.isActive(ctx.runner, unit);
281
300
  const relayPort = probe ? await relayPortListening(ctx, ctx.self.relayPort) : null;
@@ -4,6 +4,7 @@
4
4
  import * as launchd from '../lib/launchd.mjs';
5
5
  import * as systemd from '../lib/systemd.mjs';
6
6
  import { reapEdgeLink } from '../lib/jobctl.mjs';
7
+ import { requireNodeHome } from '../lib/identity.mjs';
7
8
  import { SWITCH_NAMES } from '../lib/state.mjs';
8
9
  import { linkLabel, relayLabel, relayLinkName } from '../lib/render.mjs';
9
10
 
@@ -23,11 +24,6 @@ function stopRelayJob(ctx, label) {
23
24
  throw new Error(`bootout 失败(${label} 仍在注册表):${bo.stderr.trim()}`);
24
25
  }
25
26
 
26
- function stopNodeUnit(ctx, unit) {
27
- systemd.stopIfLoaded(ctx.runner, unit); // not-loaded(未装/已卸)无害,真失败抛出
28
- systemd.disableIfInstalled(ctx.runner, unit); // 未装/已卸幂等,与 mac bootout 113 同口径
29
- }
30
-
31
27
  function reapLinkOrThrow(ctx, label) {
32
28
  const { gone } = reapEdgeLink(ctx, label);
33
29
  if (!gone)
@@ -37,13 +33,15 @@ function reapLinkOrThrow(ctx, label) {
37
33
  /** 停止磁盘发现的全部 link/relay 任务;改名前的残留也一并覆盖。 */
38
34
  function stopJobs(ctx) {
39
35
  if ((ctx.platform ?? process.platform) === 'linux') {
40
- const units = systemd.unitNamesOnDisk(ctx.paths.systemdUnitDir, relayLinkName(''));
36
+ const units = systemd.unitNamesOnDisk(ctx.paths.systemdUnitDir, relayLinkName(''), true);
41
37
  if (units.length > 0 && ctx.uid !== 0)
42
38
  throw new Error('停止 node 的中继服务需要 root,请运行 sudo -i ssh-net stop');
43
- for (const unit of units) stopNodeUnit(ctx, unit);
39
+ ctx.state.removeOn(['relay', 'peer']);
40
+ for (const unit of units) systemd.stopInstalledUnit(ctx.runner, ctx.paths.systemdUnitDir, unit);
44
41
  return `已停止并禁用 ${units.length} 个中继服务`;
45
42
  }
46
43
 
44
+ ctx.state.removeOn(['relay', 'peer']);
47
45
  const links = launchd.labelsOnDisk(ctx.paths.launchAgentsDir, linkLabel(''));
48
46
  const relays = launchd.labelsOnDisk(ctx.paths.launchAgentsDir, relayLabel(''));
49
47
  for (const label of links) reapLinkOrThrow(ctx, label);
@@ -53,10 +51,10 @@ function stopJobs(ctx) {
53
51
 
54
52
  export function run(ctx, args = []) {
55
53
  const target = parseTarget(args);
54
+ if ((ctx.platform ?? process.platform) === 'linux' && ctx.uid === 0) requireNodeHome(ctx, 'stop');
56
55
  if (target === 'peer') {
57
56
  ctx.state.removeOn(['peer']);
58
57
  return 'peer 已关闭:不再主动恢复 IPv6 直连;现有直连断开前仍可供新 ssh 使用,断开后走中继';
59
58
  }
60
- ctx.state.removeOn(['relay', 'peer']);
61
59
  return `relay 和 peer 已一并关闭;${stopJobs(ctx)}`;
62
60
  }
@@ -4,6 +4,7 @@
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { removeJobs } from '../lib/manage.mjs';
7
+ import { requireNodeHome } from '../lib/identity.mjs';
7
8
  import * as launchd from '../lib/launchd.mjs';
8
9
  import * as systemd from '../lib/systemd.mjs';
9
10
  import {
@@ -28,31 +29,19 @@ function removeSshNetLogs(ctx) {
28
29
  }
29
30
  }
30
31
 
31
- function removeNodeUnits(ctx, units) {
32
- for (const unit of units) {
33
- // not-loaded(未装/已卸)无害,真失败必须报——否则删了 unit 文件、
34
- // systemd 里留下 ghost 态的在跑进程
35
- systemd.stopIfLoaded(ctx.runner, unit);
36
- systemd.disableIfInstalled(ctx.runner, unit);
37
- rm(path.join(ctx.paths.systemdUnitDir, unit));
38
- }
39
- // daemon-reload 失败不能吞:systemd 仍持有已删 unit,Restart=always 会
40
- // 留着/重拉 ghost 进程
41
- systemd.daemonReload(ctx.runner);
42
- }
43
-
44
32
  export function run(ctx, args = []) {
45
33
  if (args.length)
46
34
  throw new Error('用法:uninstall 不带参数');
47
35
 
48
36
  if ((ctx.platform ?? process.platform) === 'linux') {
49
- const units = systemd.unitNamesOnDisk(ctx.paths.systemdUnitDir, relayLinkName(''));
50
- if (units.length > 0 && ctx.uid !== 0)
51
- throw new Error('node 卸载写 /etc/systemd/system 需要 root,请运行 sudo -i ssh-net uninstall');
52
- if (units.length > 0) removeNodeUnits(ctx, units);
53
- // 上次可能已在删完 unit 后、daemon-reload 失败处中断;磁盘为空也必须补做,
54
- // 否则第二次卸载会留下 manager 内的旧定义却报成功。非 root 零产物仍纯本地清理。
55
- else if (ctx.uid === 0) systemd.daemonReload(ctx.runner);
37
+ const units = systemd.unitNamesOnDisk(ctx.paths.systemdUnitDir, relayLinkName(''), true);
38
+ // 非 root 且没有 unit 时只清理自己的文件。root 即使没有 unit,也不能到别人的 HOME 清理
39
+ if (ctx.uid === 0 || units.length) {
40
+ requireNodeHome(ctx, 'uninstall');
41
+ systemd.removeUnits(ctx.runner, ctx.paths.systemdUnitDir, units);
42
+ // 上次可能在删完文件后中断;root 即使遇到空目录也要补做 reload
43
+ systemd.daemonReload(ctx.runner);
44
+ }
56
45
  removeArtifacts(ctx);
57
46
  return '已卸载。最后一步:npm uninstall -g ssh-net';
58
47
  }