ssh-net 26.11.1 → 26.11.3

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.
@@ -1,46 +1,40 @@
1
- // install:对账到 topology 描述的稳态。幂等:运行时脚本内容相同不重写、
2
- // plist/unit 字节相同不 bootout(不断连)。edge 只注册 PathState job(RELAY_ON
3
- // 不在不启动);core/node 会恢复 stop 的中继服务;core 不预建 uplink-edge
4
- //(首次报名才生成),node 写 unit 并 enable --now。
1
+ // install 对账本机组件。edge 注册本地转发任务,是否启动由 RELAY_ON 决定;
2
+ // core/node 恢复中继服务,core 到 edge 的回拨任务仍在首次报名时才创建
5
3
  import fs from 'node:fs';
6
4
  import path from 'node:path';
7
5
  import {
8
6
  CALLBACK_PORT, TERMINAL_NOTIFIER_PATHS, OSASCRIPT_PATH,
9
7
  } from '../lib/constants.mjs';
10
- import { syncPlist, removeJob } from '../lib/manage.mjs';
8
+ import { removeJobs, syncPlist } from '../lib/manage.mjs';
11
9
  import { syncConfFile } from '../lib/conf.mjs';
12
10
  import { ensureRuntime } from '../lib/runtime.mjs';
13
11
  import { edgeLinkJob, coreRelayJob, nodeRelayJob } from '../lib/jobs.mjs';
14
12
  import * as launchd from '../lib/launchd.mjs';
15
13
  import * as systemd from '../lib/systemd.mjs';
16
14
  import {
17
- classifyLocalPort, lsofListen, v6LoopbackPids, peerProbeOk,
15
+ forwardListenerPids, lsofListen, v6LoopbackPids, peerProbeOk,
18
16
  } from '../lib/probe.mjs';
19
- import { readDirOrEmpty, writeFileAtomic } from '../lib/fsutil.mjs';
17
+ import { readDirOrEmpty } from '../lib/fsutil.mjs';
20
18
  import { packageScriptPath } from '../lib/paths.mjs';
21
19
  import {
22
20
  SN_PROBE, RESIDENT_SCRIPTS, edgeRuntimePlan, coreNodeRuntimePlan,
23
- edgeCallbacksPlan, linkAddonPlan, mergePlans,
24
21
  } from '../lib/manifest.mjs';
25
- import { linkLabel, renderEdgeHost, renderRoutes } from '../lib/render.mjs';
22
+ import { linkLabel, linkLinkName, renderEdgeHost, renderRoutes } from '../lib/render.mjs';
26
23
 
27
- /** 对账只汇总有无变化;具体差异看文件与 launchd/systemd,不维护逐态文案。 */
28
- function compNote(results, entities) {
24
+ /** 只有常驻脚本本身发生变化,才提示要等进程重连 */
25
+ function syncRuntime(ctx, { entities, links }) {
26
+ const results = ensureRuntime(ctx, entities, links);
29
27
  if (!results.some(Boolean)) return '';
30
- const residentUpdated = entities.some(([name], i) =>
31
- results[i] && RESIDENT_SCRIPTS.includes(name));
32
- return residentUpdated
28
+ return entities.some((name, i) => results[i] && RESIDENT_SCRIPTS.includes(name))
33
29
  ? '后台脚本已同步,常驻进程将在下次重连后使用新版'
34
30
  : '后台脚本已同步';
35
31
  }
36
32
 
37
- /** 安装结果文案:组件刷新/配置更新若干条 note 合并进一对括号(''=零附加信息)。 */
38
33
  function notesPart(...notes) {
39
34
  const parts = notes.filter(Boolean);
40
35
  return parts.length ? `(${parts.join(';')})` : '';
41
36
  }
42
37
 
43
- /** plist/unit 的同构部署结果统一变成用户可读的任务变化。 */
44
38
  function deploymentNote(r, task, config) {
45
39
  if (!r.changed) return '';
46
40
  return r.restarted ? `${config}已更新,可能断开当前连接` : `${task}已同步`;
@@ -57,29 +51,23 @@ function coreNodeInstallMsg(comp, entryChanged, result, relayLine) {
57
51
  return `安装完成${note},中继通道已开启(${relayLine})`;
58
52
  }
59
53
 
60
- /** edge 端口预检(纯读 + banner 判定),冲突抛错并报持有者。转发口只在
61
- * link 附加件本次会装时才查:默认零常驻不绑这些口,他进程(如 VS Code
62
- * 自动转发到本机的端口)占用与本服务无关。 */
63
- async function precheckEdgePorts(ctx, linkOn) {
64
-
65
- const { runner, uid, topo } = ctx;
66
- const forwardPorts = topo.forwards.map((f) => f.listenPort);
67
- if (linkOn && forwardPorts.length > 0) {
68
- // 只要 pid 判持口者归属(link-core 是 exec ssh,job pid 即持口者)
69
- const jobPid = launchd.printState(runner, uid, linkLabel(topo.core.alias), true).pid;
70
- for (const port of forwardPorts) {
71
- const c = classifyLocalPort(runner, port, jobPid);
72
- if (c.kind === 'foreign') {
73
- throw new Error(`端口 ${port} 被别的程序占用(pid ${c.pids.join(',')}):\n${lsofListen(runner, port)}`);
74
- }
54
+ /** 端口冲突时在写任何产物前退出。转发端口由 link 的 ssh 进程持有,回拨端口则由 sshd 持有 */
55
+ async function precheckEdgePorts({ runner, uid, topo }, labels) {
56
+ const jobPids = () => new Set(labels.map((label) => launchd.printState(runner, uid, label).pid));
57
+ let owned = jobPids();
58
+ for (const { listenPort: port } of topo.forwards) {
59
+ const listeners = await forwardListenerPids(runner, port);
60
+ if (listeners.every((pid) => owned.has(pid))) continue;
61
+ // launchd 可能恰好在查端口期间重连,按最新的任务 PID 确认归属
62
+ owned = jobPids();
63
+ const foreign = listeners.filter((pid) => !owned.has(pid));
64
+ if (foreign.length) {
65
+ throw new Error(`端口 ${port} 被别的程序占用(pid ${foreign.join(',')}):\n${lsofListen(runner, port)}`);
75
66
  }
76
67
  }
77
68
 
78
- // 10022 持口者永远是本机 sshd,无法按 pid 溯源:读到 SSH banner 才认。
79
- // 只盯 [::1](本服务的监听面);127.0.0.1:10022 的持有者如 VS Code 本地
80
- // 转发与本服务不同地址族、可共存,不判冲突。
81
- // 一次 lsof 同时拿持有者 pid 与报错展示文本。预检执行包内探针:
82
- // 不能用待修复的 bin/sn-probe,否则探针损坏会把 install 自己的修复入口堵住
69
+ // 只检查回拨使用的 IPv6 环回地址;同号的 IPv4 监听可以共存。
70
+ // 用包内探针读 SSH 标识,不能让磁盘上待修复的探针堵住 install
83
71
  const listeners = lsofListen(runner, CALLBACK_PORT);
84
72
  if (
85
73
  v6LoopbackPids(listeners, CALLBACK_PORT).length > 0
@@ -91,28 +79,6 @@ async function precheckEdgePorts(ctx, linkOn) {
91
79
  }
92
80
  }
93
81
 
94
- /** 解析 edge install 的 link 意图:true=--with-link、false=--without-link、
95
- * undefined=无 flag;两 flag 同现或夹带未知参数即用法错误 */
96
- function parseLinkFlag(args) {
97
- /** @type {boolean|undefined} */
98
- let flag;
99
- for (const a of args) {
100
- if (a === '--with-link' || a === '--without-link') {
101
- if (flag !== undefined)
102
- throw new Error('--with-link 与 --without-link 不能同时使用');
103
- flag = a === '--with-link';
104
- } else {
105
- throw new Error(`未知参数:${a}——edge install 只接受 --with-link / --without-link`);
106
- }
107
- }
108
- return flag;
109
- }
110
-
111
- // 回连桌面通知的可选依赖:sn-route 的 peer_ready 优先 terminal-notifier、
112
- // 缺它走系统 osascript(默认路径单源在 constants,与 bash 侧的一致性靠
113
- // constants.test 锚);两个都没有(Linux)则直连恢复时无通知。装的时候
114
- // 说清楚,别等第一次用时疑惑
115
-
116
82
  /** 通知依赖提示('\n' 前缀的独立行;terminal-notifier 齐备返回 '')。 */
117
83
  export function notifyDepNote({ hasTerminalNotifier, hasOsascript }) {
118
84
  if (hasTerminalNotifier) return '';
@@ -121,7 +87,6 @@ export function notifyDepNote({ hasTerminalNotifier, hasOsascript }) {
121
87
  return '\n提示:此机没有桌面通知工具,直连恢复时不会弹通知(不影响连接功能)';
122
88
  }
123
89
 
124
- /** 本机真实检测(分档文案由 notifyDepNote 纯函数测试锚定)。 */
125
90
  function localNotifyDepNote() {
126
91
  const execOk = (p) => {
127
92
  try { fs.accessSync(p, fs.constants.X_OK); return true; } catch { return false; }
@@ -132,71 +97,37 @@ function localNotifyDepNote() {
132
97
  });
133
98
  }
134
99
 
135
- async function installEdge(ctx, args) {
100
+ async function installEdge(ctx) {
136
101
  const { topo, paths } = ctx;
137
- const flag = parseLinkFlag(args);
138
- // 本次 install 后 link 在不在:显式 flag 说了算,无 flag 按 marker
139
- const linkOn = flag === true
140
- || (flag !== false && fs.existsSync(paths.linkEnabledFile));
141
- // 预检纯读且在落任何产物之前:被拒时 bin/ 一个都不建
142
- await precheckEdgePorts(ctx, linkOn);
143
-
144
- // 显式意图先落/删 marker;无参 install(含 update 内置)不触碰它
145
- if (flag === true) {
146
- fs.mkdirSync(paths.sshNetDir, { recursive: true });
147
- writeFileAtomic(paths.linkEnabledFile, '1\n', { mode: 0o600 });
102
+ const link = edgeLinkJob(ctx);
103
+ const diskLabels = launchd.labelsOnDisk(paths.launchAgentsDir, linkLabel(''));
104
+ const obsolete = diskLabels.filter((label) => label !== link?.label);
105
+ 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 });
148
114
  }
149
- if (flag === false) fs.rmSync(paths.linkEnabledFile, { force: true });
150
-
151
- // 实体/软链清单唯一来源在 manifest:基础 3 实体,linkOn 才加第 4 实体与
152
- // 带机器名软链。回拨通知与 link 秒切由 sn-route 成功点在本地执行
153
- const plan = edgeRuntimePlan(topo, linkOn);
154
- const comp = compNote(ensureRuntime(ctx, plan.entities, plan.links), plan.entities);
155
- let linkChanged = false;
156
115
  let linkNote = '';
157
-
158
- if (linkOn) {
159
- // 附加件:渲染纯 ssh plist 并对账(RELAY_ON 在 syncPlist 按 stopped 语义
160
- // 首发,不在注册待命);转发参数是最终 -L argv
161
- const r = syncPlist(ctx, edgeLinkJob(ctx));
162
- if (r.lintError) throw new Error(`link plist 校验失败:${r.lintError}`);
163
- linkChanged = r.changed;
164
- linkNote = deploymentNote(r, '本地转发任务', '本地转发配置');
165
- } else {
166
- // 默认零常驻:清掉加装过的 link 全部产物。plist 必须先 bootout,否则
167
- // 删了实体后 launchd 每 ThrottleInterval 刷 ENOENT
168
- const label = linkLabel(topo.core.alias);
169
- const plistPath = paths.plistFile(label);
170
- const jobRemoved = removeJob(ctx, label, plistPath);
171
- const addon = linkAddonPlan(topo);
172
- const addonPaths = [...addon.entities, ...addon.links].map(([name]) => paths.binScript(name));
173
- const addonRemoved = addonPaths.some((p) =>
174
- fs.lstatSync(p, { throwIfNoEntry: false }) !== undefined);
175
- for (const p of addonPaths) fs.rmSync(p, { force: true });
176
- linkChanged = jobRemoved || addonRemoved;
177
- if (linkChanged) linkNote = '本地转发任务与组件已移除';
116
+ if (link) {
117
+ const job = syncPlist(ctx, link);
118
+ if (job.lintError) throw new Error(`link plist 校验失败:${job.lintError}`);
119
+ linkNote = deploymentNote(job, '本地转发任务', '本地转发配置');
178
120
  }
121
+ fs.rmSync(paths.legacyLinkEnabledFile, { force: true });
179
122
 
180
- // conf.d 片段(design §4.2):edge 是 routes 的唯一安装角色——routes 含
181
- // 选路 Match 与尾部本机别名打标块
182
- const routesChanged = syncConfFile(paths.routesFile, renderRoutes(topo, ctx.self.alias));
183
- const depNote = localNotifyDepNote();
184
- const head = linkOn ? '安装完成(含本地端口转发)' : '安装完成';
185
- const base = (!comp && !linkChanged && !routesChanged && flag === undefined)
186
- ? '已安装,配置无需改动'
187
- : `${head}${notesPart(comp, linkNote, routesChanged ? 'ssh 配置片段已更新' : '')}`;
188
- const startNote = ctx.state.isOn('relay')
189
- ? ''
190
- : '\n当前为关闭状态;开启自动选路和 IPv6 直连:ssh-net start';
191
- return `${base}${startNote}${depNote}`;
123
+ const note = notesPart(comp, linkNote, obsolete.length ? '旧转发任务已移除' : '',
124
+ routesChanged ? 'ssh 配置片段已更新' : '');
125
+ const base = note ? `安装完成${note}` : '已安装,配置无需改动';
126
+ const startNote = ctx.state.isOn('relay') ? '' : '\n当前为关闭状态;开启自动选路和 IPv6 直连:ssh-net start';
127
+ return `${base}${startNote}${localNotifyDepNote()}`;
192
128
  }
193
129
 
194
- /**
195
- * core/node:按 topology 渲染每台 edge 的入口片段 conf.d/edge-<别名>(内容只随
196
- * topology 变,地址在 Include 的 state/addr 文件里),并删掉 topology 已没有的
197
- * 旧片段——conf.d/edge-* 全由本函数管。
198
- * @returns {boolean} 有无改动
199
- */
130
+ /** core/node 按 topology 写各 edge 的入口,并移除已经不在 topology 里的旧片段 */
200
131
  function syncEdgeEntries(ctx) {
201
132
  const { topo, paths } = ctx;
202
133
  let changed = false;
@@ -207,7 +138,6 @@ function syncEdgeEntries(ctx) {
207
138
  if (syncConfFile(file, renderEdgeHost(e))) changed = true;
208
139
  }
209
140
  const existing = readDirOrEmpty(paths.confDir);
210
- // 片段名公式唯一来源是 edgeHostFile(含 '' 即前缀),不抄 'edge-' 字面量
211
141
  const edgePrefix = path.basename(paths.edgeHostFile(''));
212
142
  for (const f of existing) {
213
143
  if (f.startsWith(edgePrefix) && !keep.has(f)) {
@@ -221,53 +151,39 @@ function syncEdgeEntries(ctx) {
221
151
  function installCore(ctx) {
222
152
  const { topo, paths } = ctx;
223
153
  const entryChanged = syncEdgeEntries(ctx);
224
- // 磁盘在册 edge 的回拨组件在 install 时一并对账:否则 update 后 core
225
- // status 要对每台未联系的 edge 报组件异常,直到它下次报名才自愈
154
+ // 更新时一并刷新已经登记的回拨脚本,不必等待各 edge 再次报名
226
155
  const edges = launchd.edgeAliasesOnDisk(paths.launchAgentsDir);
227
- // relay 基础形态 + 磁盘在册 edge 的回拨组件(清单与报名/status 体检同源)
228
- const plan = mergePlans(coreNodeRuntimePlan(topo), edgeCallbacksPlan(edges));
229
- const comp = compNote(ensureRuntime(ctx, plan.entities, plan.links), plan.entities);
156
+ const comp = syncRuntime(ctx, coreNodeRuntimePlan(topo, edges));
230
157
  const r = syncPlist(ctx, coreRelayJob(ctx));
231
- // lint 失败不能静默报「安装完成」:syncPlist 以返回值交错误(register 同判)
232
158
  if (r.lintError) throw new Error(`relay plist 校验失败:${r.lintError}`);
233
159
  return coreNodeInstallMsg(comp, entryChanged, r,
234
160
  `${topo.relay.alias} 入口 ${topo.core.relayPort}`);
235
161
  }
236
162
 
237
163
  function installNode(ctx) {
238
- const { topo, paths, runner } = ctx;
164
+ const { topo, runner } = ctx;
239
165
  if (ctx.uid !== 0)
240
166
  throw new Error('node 安装写 /etc/systemd/system 需要 root,请运行 sudo -i ssh-net install');
241
- const entryChanged = syncEdgeEntries(ctx);
242
- const plan = coreNodeRuntimePlan(topo);
243
- const comp = compNote(ensureRuntime(ctx, plan.entities, plan.links), plan.entities);
244
167
  const { home, ...job } = nodeRelayJob(ctx);
245
- // ExecStart 按空白分词、无 shell 引号转义通路,HOME 含空白会拆断 bin 路径
246
- // (plist 侧是 XML 数组无此问题)——当场拒绝比装出一个起不来的 unit 诚实
168
+ if (ctx.env.HOME !== home)
169
+ throw new Error('HOME 与 root 账户的家目录不一致,请运行 sudo -i ssh-net install');
170
+ // ExecStart 按空白分词,HOME 含空白会拆断脚本路径
247
171
  if (/\s/.test(home))
248
172
  throw new Error(`node 的 HOME(${home})含空白字符:systemd ExecStart 无法转义,拒绝安装`);
173
+ const entryChanged = syncEdgeEntries(ctx);
174
+ const comp = syncRuntime(ctx, coreNodeRuntimePlan(topo));
249
175
  const r = systemd.syncUnit(runner, job);
250
176
  return coreNodeInstallMsg(comp, entryChanged, r,
251
- `${ctx.topo.relay.alias} 入口 ${ctx.self.relayPort}`);
177
+ `${topo.relay.alias} 入口 ${ctx.self.relayPort}`);
252
178
  }
253
179
 
254
- /**
255
- * @param {object} ctx
256
- * @param {string[]} [args] edge 可带 --with-link/--without-link
257
- */
180
+ /** @param {object} ctx @param {string[]} [args] */
258
181
  export async function run(ctx, args = []) {
259
- let result;
182
+ if (args.length) throw new Error('用法:ssh-net install 不带参数');
260
183
  switch (ctx.role) {
261
- case 'edge': result = await installEdge(ctx, args); break;
262
- case 'core':
263
- case 'node':
264
- // --with-link 是 edge 附加件:core/node 上静默吞掉会让错打的 flag
265
- // 看起来被接受了
266
- if (args.length)
267
- throw new Error(`本机是 ${ctx.role},install 不接受参数(--with-link/--without-link 是 edge 上本地转发的开关)`);
268
- result = ctx.role === 'core' ? installCore(ctx) : installNode(ctx);
269
- break;
184
+ case 'edge': return installEdge(ctx);
185
+ case 'core': return installCore(ctx);
186
+ case 'node': return installNode(ctx);
270
187
  default: throw new Error(`未知角色:${ctx.role}`);
271
188
  }
272
- return result;
273
189
  }
@@ -41,8 +41,6 @@ export function runRegister(ctx, args = []) {
41
41
  binDir: ctx.paths.binDir, edgeAlias: alias, user: edge.user,
42
42
  logsDir: ctx.paths.logsDir,
43
43
  });
44
- const st = launchd.inspect(ctx.runner, ctx.uid, label);
45
-
46
44
  const plan = edgeCallbacksPlan([alias]);
47
45
  ensureRuntime(ctx, plan.entities, plan.links);
48
46
  ctx.state.writeEdgeV6(alias, v6);
@@ -50,6 +48,7 @@ export function runRegister(ctx, args = []) {
50
48
 
51
49
  // 未注册(首次报名)或 plist 与 topology 渲染不符(user 等变了):
52
50
  // 重新部署,syncPlist 的 bootstrap 即首发
51
+ const st = launchd.inspect(ctx.runner, ctx.uid, label);
53
52
  if (!st.registered || readFileOrNull(plistPath) !== content) {
54
53
  const r = syncPlist(ctx, { label, plistPath, content });
55
54
  if (r.lintError) throw new Error(`uplink-edge plist 校验失败:${r.lintError}`);
@@ -1,30 +1,25 @@
1
1
  // start:edge 两开关(缺省或 -a/--all=relay+peer,peer 自动补 relay);
2
- // core 重新 enable+bootstrap uplink-relay;node systemctl。link 不是
3
- // 运行时开关(转发口只取决于装没装附加件)。peer 路径复用 sn-route 做
4
- // 人工强制恢复,不在控制面另维护一套报名实现。
2
+ // core 重新启用中继,node 走 systemctl。edge 的本地转发随 relay 启停。
3
+ // 人工恢复 peer 复用 sn-route,不在控制面另维护一套报名实现
5
4
  import fs from 'node:fs';
6
5
  import * as systemd from '../lib/systemd.mjs';
7
6
  import { ensureLoaded } from '../lib/manage.mjs';
8
7
  import { SWITCH_NAMES } from '../lib/state.mjs';
9
8
  import { SN_ROUTE } from '../lib/manifest.mjs';
9
+ import { edgeLinkJob } from '../lib/jobs.mjs';
10
10
  import { relayLabel, relayUnitName, snRouteArgv } from '../lib/render.mjs';
11
11
 
12
- function parseTargets(args) {
12
+ function parseEdgeTarget(args) {
13
13
  if (args.length === 0 || (args.length === 1 && (args[0] === '-a' || args[0] === '--all')))
14
- return ['relay', 'peer'];
14
+ return 'peer';
15
15
  if (args.length === 1 && SWITCH_NAMES.includes(args[0]))
16
- return [args[0]];
17
- if (args.length === 1 && args[0] === 'link')
18
- throw new Error('link 不是运行时开关:本地转发口只取决于装没装 link 组件——启用 ssh-net install --with-link,移除 ssh-net install --without-link');
16
+ return args[0];
19
17
  throw new Error('用法:start [-a|--all|relay|peer](不带参数或 -a=relay+peer)');
20
18
  }
21
19
 
22
20
  /** 先保存开关,再沿日常 ssh 的选路路径强制确保一次;未就绪不撤销用户意图。 */
23
21
  function startEdgePeer(ctx) {
24
22
  const route = ctx.paths.binScript(SN_ROUTE);
25
- if (!fs.existsSync(route))
26
- throw new Error('未安装(缺 sn-route)——先跑 ssh-net install');
27
-
28
23
  const prefix = 'relay 和 peer 开关已开启';
29
24
  ctx.state.setOn(['relay', 'peer']);
30
25
  // FORCE 只跳过新鲜失败印记;probe、ENSURE 与等待预算都和普通 ssh 相同。
@@ -51,18 +46,24 @@ function startCore(ctx) {
51
46
  const plist = ctx.paths.plistFile(label);
52
47
  if (!fs.existsSync(plist)) throw new Error(`尚未安装(缺 ${plist}),先跑 ssh-net install`);
53
48
  // start 语义:在册但停着要踢活;在跑但 disabled 只清 override、不闪断
54
- ensureLoaded(ctx, { label, plistPath: plist }, { kickWhenStopped: true });
49
+ ensureLoaded(ctx, { label, plistPath: plist });
55
50
  return '中继通道已开启';
56
51
  }
57
52
 
58
53
  export function run(ctx, args = []) {
59
54
  if (ctx.role === 'edge') {
60
- const before = ctx.state.readSwitches();
61
- const targets = parseTargets(args); // ['relay','peer'] 或 ['relay']
62
-
63
- if (targets.includes('peer')) return startEdgePeer(ctx);
55
+ const target = parseEdgeTarget(args);
56
+ const peerWasOn = target === 'relay' && ctx.state.isOn('peer');
57
+ if (!fs.existsSync(ctx.paths.binScript(SN_ROUTE)) || !fs.existsSync(ctx.paths.routesFile))
58
+ throw new Error('未安装完整(缺 sn-route 或选路配置)——先跑 ssh-net install');
59
+ const link = edgeLinkJob(ctx);
60
+ if (link) {
61
+ if (!fs.existsSync(link.plistPath)) throw new Error('缺本地转发任务——先跑 ssh-net install');
62
+ ensureLoaded(ctx, link);
63
+ }
64
+ if (target === 'peer') return startEdgePeer(ctx);
64
65
  ctx.state.setOn(['relay']);
65
- const peerNote = before.peer
66
+ const peerNote = peerWasOn
66
67
  ? 'peer 保持开启,仍会主动恢复 IPv6 直连'
67
68
  : 'peer 仍关闭;需要自动恢复时运行 ssh-net start peer';
68
69
  return `relay 已开启(${peerNote})`;
@@ -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 } from '../lib/probe.mjs';
11
+ import { peerProbeOk, tcpOpen, classifyV6Probe, forwardListenerPids } 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, renderEdgeHost, renderRoutes, coreViaRelayArgs, probeSshOpts,
20
+ edgeLabel, linkLabel, renderEdgeHost, renderRoutes, coreViaRelayArgs, probeSshOpts,
21
21
  } from '../lib/render.mjs';
22
22
 
23
23
  /**
@@ -26,9 +26,9 @@ import {
26
26
  */
27
27
  function runtimeIssues(ctx, { entities, links }) {
28
28
  const issues = [];
29
- const entityAudits = entities.map(([name, script]) => ({
29
+ const entityAudits = entities.map((name) => ({
30
30
  name,
31
- audit: auditScript(ctx.paths.binScript(name), packageScriptPath(script)),
31
+ audit: auditScript(ctx.paths.binScript(name), packageScriptPath(name)),
32
32
  }));
33
33
  const allMissing = entityAudits.length > 0
34
34
  && entityAudits.every((a) => a.audit === 'missing');
@@ -130,15 +130,23 @@ async function relayPathProbe(ctx) {
130
130
 
131
131
  async function collectEdge(ctx, probe) {
132
132
  const { topo, paths, state } = ctx;
133
- const linkInstalled = fs.existsSync(paths.linkEnabledFile);
134
- const plan = edgeRuntimePlan(topo, linkInstalled);
135
- const { issues, entityAudits } = runtimeIssues(ctx, plan);
136
- const linkDeployment = linkInstalled ? edgeLinkJob(ctx) : null;
137
- if (linkDeployment) {
138
- const issue = configFileIssue(
139
- linkDeployment.plistPath, linkDeployment.content, '本地转发配置', '需要更新',
140
- );
133
+ const { issues, entityAudits } = runtimeIssues(ctx, edgeRuntimePlan(topo));
134
+ const switches = state.readSwitches();
135
+ const link = edgeLinkJob(ctx);
136
+ const onDisk = launchd.labelsOnDisk(paths.launchAgentsDir, linkLabel(''));
137
+ if (onDisk.some((label) => label !== link?.label))
138
+ issues.push('有旧的本地转发任务——跑一次 ssh-net install 清理');
139
+ let job = null;
140
+ if (link && (entityAudits.some((a) => a.audit !== 'missing') || onDisk.includes(link.label))) {
141
+ const issue = configFileIssue(link.plistPath, link.content, '本地转发配置', '需要更新');
141
142
  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');
142
150
  }
143
151
 
144
152
  // routes 被手删/过期会让 ssh 静默退回 lan 直连,是故障。sn-route 没装时
@@ -150,15 +158,6 @@ async function collectEdge(ctx, probe) {
150
158
  if (issue) issues.push(issue);
151
159
  }
152
160
 
153
- // link 未装时 job 无消费者(渲染走「未安装」分支)——默认零常驻形态不为它
154
- // 白跑一次 launchctl print
155
- const job = linkInstalled
156
- ? launchd.printState(ctx.runner, ctx.uid, linkDeployment.label, true)
157
- : null;
158
- const switches = state.readSwitches();
159
- if (linkInstalled && switches.relay && !job.running)
160
- issues.push('本地转发任务未在运行——先 stop 再按原开关 start,或跑 ssh-net install 修复');
161
-
162
161
  // v6 只是诊断线索不是判决,与就绪实测并发。探测没跑成时不能谎称「没有
163
162
  // IPv6」——那个结论只在 sn-ipv6 正常跑完且无输出时才成立
164
163
  const needV6 = probe && switches.relay
@@ -171,11 +170,15 @@ async function collectEdge(ctx, probe) {
171
170
  // 仍可能被新 ssh 使用,所以只要 relay 开着就继续做 banner 探测
172
171
  const relayProbe = ctx.relayOk ?? relayPathProbe; // 测试可注入同形结果
173
172
  const openTcp = ctx.openTcp ?? tcpOpen;
174
- const forwards = probe && linkInstalled && switches.relay ? topo.forwards : [];
173
+ const forwards = probe && switches.relay ? topo.forwards : [];
175
174
  const [relayResult, peerReady, portsOk, v6Probe] = await Promise.all([
176
175
  probe && switches.relay ? relayProbe(ctx) : null,
177
176
  probe && switches.relay ? peerProbeOk(ctx.runner, paths.binDir) : null,
178
- Promise.all(forwards.map((f) => openTcp('127.0.0.1', f.listenPort))),
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
+ })),
179
182
  v6P,
180
183
  ]);
181
184
  const relayReady = relayResult?.ready ?? null;
@@ -196,7 +199,7 @@ async function collectEdge(ctx, probe) {
196
199
 
197
200
  return {
198
201
  role: 'edge', alias: ctx.self.alias, switches, probed: probe, relayReady, peerReady,
199
- linkInstalled, job,
202
+ job,
200
203
  forwardViews: forwards.map((f, i) => [forwardLabel(f), portsOk[i]]),
201
204
  coreAlias: topo.core.alias, relayAlias: topo.relay.alias,
202
205
  v6, v6ProbeOk, issues,
@@ -309,7 +312,7 @@ function lineOf(name, ready, okText, failText) {
309
312
  function relayStatusLine(s) {
310
313
  if (!s.probed) return ' relay:未实测(需要时运行 ssh-net status --probe)';
311
314
  return s.relayPort.listening
312
- ? ` relay:✓ 可用(外部可经 ${s.relayAlias} 进入 ${s.alias} · 入口 ${s.relayPort.port})`
315
+ ? ` relay:✓ ${s.relayAlias} 注册口 ${s.relayPort.port} 在监听`
313
316
  : ` relay:✗ ${s.relayPort.reachable === false ? `连不上 ${s.relayAlias},入口状态未知` : `入口 ${s.relayPort.port} 没在监听`}`;
314
317
  }
315
318
 
@@ -339,11 +342,11 @@ function renderEdgeLines(s, lines) {
339
342
  } else {
340
343
  lines.push(' peer:关(当前无可用直连;不主动恢复)');
341
344
  }
342
- if (s.linkInstalled && s.forwardViews.length > 0) {
345
+ if (s.forwardViews.length > 0) {
343
346
  const bad = s.forwardViews.filter(([, ok]) => !ok).map(([l]) => l);
344
347
  lines.push(lineOf('link', bad.length === 0,
345
348
  `本地端口在听(${s.forwardViews.map(([l]) => l).join(' · ')})`,
346
- `本地端口未在听(${bad.join('、')};检查本地转发任务与中继线路)`));
349
+ `转发任务未监听这些端口(${bad.join('、')};检查本地转发任务与中继线路)`));
347
350
  }
348
351
  lines.push(s.v6 !== ''
349
352
  ? ` 对外地址:${s.v6}`
@@ -352,9 +355,7 @@ function renderEdgeLines(s, lines) {
352
355
  : ' 对外地址:当前没有可用 IPv6');
353
356
  }
354
357
  }
355
- lines.push(s.linkInstalled
356
- ? ` 本地转发(link):已安装(后台任务${s.job.running ? '运行中' : '未运行'})`
357
- : ' 本地转发(link):未安装(需要 SOCKS/VNC 端口:ssh-net install --with-link)');
358
+ if (s.job) lines.push(` 本地转发(link):后台任务${s.job.running ? '运行中' : '未运行'}`);
358
359
  }
359
360
 
360
361
  function edgeTaskState(e) {
@@ -11,8 +11,6 @@ function parseTarget(args) {
11
11
  if (args.length === 0 || args.length === 1 && ['-a', '--all'].includes(args[0]))
12
12
  return 'relay';
13
13
  if (args.length === 1 && SWITCH_NAMES.includes(args[0])) return args[0];
14
- if (args.length === 1 && args[0] === 'link')
15
- throw new Error('link 不是运行时开关:移除本地转发组件跑 ssh-net install --without-link(卸载会一并清掉)');
16
14
  throw new Error('用法:stop [-a|--all|relay|peer](不带参数或 -a=全部关闭)');
17
15
  }
18
16
 
@@ -3,7 +3,7 @@
3
3
  // plist/unit、运行时脚本、状态与日志;topology 改名前的残留由 glob 覆盖。
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
- import { removeJob } from '../lib/manage.mjs';
6
+ import { removeJobs } from '../lib/manage.mjs';
7
7
  import * as launchd from '../lib/launchd.mjs';
8
8
  import * as systemd from '../lib/systemd.mjs';
9
9
  import {
@@ -18,7 +18,7 @@ function removeArtifacts(ctx) {
18
18
  rm(ctx.paths.stateDir);
19
19
  rm(ctx.paths.confDir);
20
20
  rm(ctx.paths.legacyRuntimeVersionFile);
21
- rm(ctx.paths.linkEnabledFile);
21
+ rm(ctx.paths.legacyLinkEnabledFile);
22
22
  }
23
23
 
24
24
  function removeSshNetLogs(ctx) {
@@ -28,10 +28,6 @@ function removeSshNetLogs(ctx) {
28
28
  }
29
29
  }
30
30
 
31
- function removeJobs(ctx, labels) {
32
- for (const label of labels) removeJob(ctx, label, ctx.paths.plistFile(label));
33
- }
34
-
35
31
  function removeNodeUnits(ctx, units) {
36
32
  for (const unit of units) {
37
33
  // not-loaded(未装/已卸)无害,真失败必须报——否则删了 unit 文件、
@@ -4,14 +4,13 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
 
6
6
  /**
7
- * 读文件;不存在返回 null(仅吞 ENOENT,其余错误照抛)。
7
+ * 读取 UTF-8 文本,文件不存在时返回 null,其他错误照常抛出
8
8
  * @param {string} file
9
- * @param {BufferEncoding|null} [encoding] 缺省 utf8;传 null 读 Buffer
10
- * @returns {string|Buffer|null}
9
+ * @returns {string|null}
11
10
  */
12
- export function readFileOrNull(file, encoding = 'utf8') {
11
+ export function readFileOrNull(file) {
13
12
  try {
14
- return fs.readFileSync(file, encoding === null ? undefined : encoding);
13
+ return fs.readFileSync(file, 'utf8');
15
14
  } catch (err) {
16
15
  if (err && err.code === 'ENOENT') return null;
17
16
  throw err;
@@ -14,7 +14,7 @@ function sleepMs(ms) {
14
14
 
15
15
  function isGone(ctx, label) {
16
16
  // 停止路径不能把 launchd 查询失败当成已退出,否则会继续谎报关闭成功
17
- const st = launchd.printState(ctx.runner, ctx.uid, label, true);
17
+ const st = launchd.printState(ctx.runner, ctx.uid, label);
18
18
  return !st.registered || (!st.running && st.pid === null);
19
19
  }
20
20
 
@@ -8,20 +8,24 @@ import {
8
8
  renderEdgeLinkPlist, renderRelayPlist, renderRelayUnit,
9
9
  } from './render.mjs';
10
10
 
11
- /** edge 本地转发 LaunchAgent。 */
12
- export function edgeLinkJob(ctx) {
13
- const { topo, paths } = ctx;
11
+ /** 有转发端口才需要 LaunchAgent。启动只用任务路径,安装和体检才读取 plist 内容 */
12
+ export function edgeLinkJob({ topo, paths, hostTable }) {
13
+ if (!topo.forwards.length) return null;
14
14
  const label = linkLabel(topo.core.alias);
15
+ const pathStateFile = paths.switchFiles.relay;
15
16
  return {
16
17
  label,
17
18
  plistPath: paths.plistFile(label),
18
- content: renderEdgeLinkPlist({
19
- binDir: paths.binDir,
20
- coreAlias: topo.core.alias,
21
- forwardArgs: renderForwardArgs(topo.forwards, ctx.hostTable),
22
- relayOnFile: paths.switchFiles.relay,
23
- logsDir: paths.logsDir,
24
- }),
19
+ pathStateFile,
20
+ get content() {
21
+ return renderEdgeLinkPlist({
22
+ binDir: paths.binDir,
23
+ coreAlias: topo.core.alias,
24
+ forwardArgs: renderForwardArgs(topo.forwards, hostTable),
25
+ relayOnFile: pathStateFile,
26
+ logsDir: paths.logsDir,
27
+ });
28
+ },
25
29
  };
26
30
  }
27
31