ssh-net 26.10.54 → 26.10.56

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,9 +1,8 @@
1
- // status:只报本机角色,三类信息——开关(意图)、线路就绪(实测)、安装产物
2
- // 一致性(bin/ 实体逐字节、服务软链、版本戳、edge 的 routes、core/node 的 edge
3
- // 入口片段)。core/node 另列每台 edge 当前的 ssh 入口地址。开关关的线路
4
- // 报「关」不探测。relay 就绪 = 命令行 -J 经 relay 真跑一条 ssh,不从「probe
5
- // 不通」推断。collect 返回结构化对象(测试断言对象),renderText 给人看。
6
- // 退出码:健康(含 edge 全关态)0;有可行动问题 1。
1
+ // status:默认只查本机开关、后台任务与安装产物;--probe 增加线路实测。
2
+ // edge 的 peer 用 banner 探测,即使 peer 软关闭也报告已有直连;core 的 edge 行
3
+ // 只表示 launchd 连接任务,不把进程 running 误写成线路已连接。
4
+ // 退出码:无「需要处理」事项 0;有可行动问题 1。线路关闭或 peer 暂不可用不等于
5
+ // 安装故障;实测发现中继不可用会进入处理项。
7
6
  import fs from 'node:fs';
8
7
  import {
9
8
  auditScript, auditLink, runtimeVersionIssue,
@@ -24,8 +23,8 @@ import {
24
23
  } from '../lib/render.mjs';
25
24
 
26
25
  /**
27
- * 各角色共用的实体+软链体检。
28
- * @returns {{issues:string[], entityAudits:{name:string,audit:string}[]}}
26
+ * 各角色共用的实体+软链体检;完全未安装只报根因,不级联报版本戳和悬链。
27
+ * @returns {{issues:string[], entityAudits:{name:string,audit:string}[], allMissing:boolean}}
29
28
  */
30
29
  function runtimeIssues(ctx, { entities, links }) {
31
30
  const issues = [];
@@ -33,27 +32,31 @@ function runtimeIssues(ctx, { entities, links }) {
33
32
  name,
34
33
  audit: auditScript(ctx.paths.binScript(name), packageScriptPath(script)),
35
34
  }));
35
+ const allMissing = entityAudits.length > 0
36
+ && entityAudits.every((a) => a.audit === 'missing');
36
37
  if (entityAudits.some((a) => a.audit === 'stale'))
37
38
  issues.push('后台脚本与所装版本不一致——跑一次 ssh-net install 刷新');
38
- if (entityAudits.every((a) => a.audit === 'missing'))
39
+ if (allMissing) {
39
40
  issues.push('尚未安装(先跑 ssh-net install)');
40
- else if (entityAudits.some((a) => a.audit === 'missing'))
41
- // 部分缺失:探针丢了会让开着的隧道恒判中继,不能只显示不报
42
- issues.push(`后台脚本不完整(缺 ${entityAudits.filter((a) => a.audit === 'missing').map((a) => a.name).join('、')})——跑一次 ssh-net install 修复`);
43
- for (const [linkName, entityName] of links) {
44
- const r = auditLink(ctx.paths.binScript(linkName), entityName);
45
- if (r !== 'ok')
46
- issues.push(`后台脚本异常(${linkName}:${r})——跑一次 ssh-net install 修复`);
41
+ } else {
42
+ if (entityAudits.some((a) => a.audit === 'missing'))
43
+ // 部分缺失:探针丢了会让开着的隧道恒判中继,不能只显示不报
44
+ issues.push(`后台脚本不完整(缺 ${entityAudits.filter((a) => a.audit === 'missing').map((a) => a.name).join('、')})——跑一次 ssh-net install 修复`);
45
+ for (const [linkName, entityName] of links) {
46
+ const r = auditLink(ctx.paths.binScript(linkName), entityName);
47
+ if (r !== 'ok')
48
+ issues.push(`后台脚本异常(${linkName}:${r})——跑一次 ssh-net install 修复`);
49
+ }
47
50
  }
48
- return { issues, entityAudits };
51
+ return { issues, entityAudits, allMissing };
49
52
  }
50
53
 
51
54
  /** 三个 collector 的共同前奏:版本戳问题 + 实体/软链体检。 */
52
55
  function baseAudit(ctx, plan) {
53
56
  const issues = [];
57
+ const { issues: rtIssues, entityAudits, allMissing } = runtimeIssues(ctx, plan);
54
58
  const vIssue = runtimeVersionIssue(ctx.paths);
55
- if (vIssue) issues.push(vIssue);
56
- const { issues: rtIssues, entityAudits } = runtimeIssues(ctx, plan);
59
+ if (vIssue && !allMissing) issues.push(vIssue);
57
60
  issues.push(...rtIssues);
58
61
  return { issues, entityAudits };
59
62
  }
@@ -130,16 +133,16 @@ async function relayPortListening(ctx, port) {
130
133
  /** edge 的 relay 线路实测:命令行显式 -J 经 relay 跑一条真 ssh(字面
131
134
  * 127.0.0.1 不命中 Match,绕开自动选路)。探测不接受新 host key——与无人
132
135
  * 值守报名的 accept-new 是刻意分级(design §4.3)。 */
133
- async function relayPathOk(ctx) {
136
+ async function relayPathProbe(ctx) {
134
137
  const r = await ctx.runner.runAsync(
135
138
  'ssh',
136
139
  coreViaRelayArgs(ctx.topo, { connectTimeout: 5, remoteCommand: 'true' }),
137
140
  { timeout: 8000 },
138
141
  );
139
- return r.code === 0;
142
+ return { ready: r.code === 0, detail: r.stderr.trim() };
140
143
  }
141
144
 
142
- async function collectEdge(ctx) {
145
+ async function collectEdge(ctx, probe) {
143
146
  const { topo, paths, state } = ctx;
144
147
  const linkInstalled = fs.existsSync(paths.linkEnabledFile);
145
148
  const plan = edgeRuntimePlan(topo, linkInstalled);
@@ -149,7 +152,7 @@ async function collectEdge(ctx) {
149
152
  // 上面已报「尚未安装」,不重复
150
153
  if (entityAudits.some((a) => a.name === SN_ROUTE && a.audit === 'ok')) {
151
154
  const issue = confFragmentIssue(
152
- paths.routesFile, renderRoutes(topo, ctx.self.alias), 'ssh 配置 routes ',
155
+ paths.routesFile, renderRoutes(topo, ctx.self.alias), 'ssh 自动选路配置',
153
156
  );
154
157
  if (issue) issues.push(issue);
155
158
  }
@@ -163,23 +166,25 @@ async function collectEdge(ctx) {
163
166
 
164
167
  // v6 只是诊断线索不是判决,与就绪实测并发。探测没跑成时不能谎称「没有
165
168
  // IPv6」——那个结论只在 sn-ipv6 正常跑完且无输出时才成立
166
- const needV6 = switches.relay
169
+ const needV6 = probe && switches.relay
167
170
  && entityAudits.some((a) => a.name === SN_IPV6 && a.audit === 'ok');
168
171
  const v6P = needV6
169
172
  ? ctx.runner.runRawAsync(paths.binScript(SN_IPV6), [], { timeout: 5000 })
170
173
  : Promise.resolve(null);
171
174
 
172
- // 就绪实测并发(开关是意图、ready 是事实;开关关的线路不探测=null)。
173
- // 转发口只有装了 link 且 relay 开才可能在听
174
- const relayOk = ctx.relayOk ?? relayPathOk; // 测试可注入
175
+ // 就绪实测并发。relay 关闭时不探测;peer 软关闭只停止主动恢复,已有直连
176
+ // 仍可能被新 ssh 使用,所以只要 relay 开着就继续做 banner 探测
177
+ const relayProbe = ctx.relayOk ?? relayPathProbe; // 测试可注入同形结果
175
178
  const openTcp = ctx.openTcp ?? tcpOpen;
176
- const forwards = linkInstalled && switches.relay ? topo.forwards : [];
177
- const [relayReady, peerReady, portsOk, v6Probe] = await Promise.all([
178
- switches.relay ? relayOk(ctx) : null,
179
- switches.relay && switches.peer ? peerProbeOk(ctx.runner, paths.binDir) : null,
179
+ const forwards = probe && linkInstalled && switches.relay ? topo.forwards : [];
180
+ const [relayResult, peerReady, portsOk, v6Probe] = await Promise.all([
181
+ probe && switches.relay ? relayProbe(ctx) : null,
182
+ probe && switches.relay ? peerProbeOk(ctx.runner, paths.binDir) : null,
180
183
  Promise.all(forwards.map((f) => openTcp('127.0.0.1', f.listenPort))),
181
184
  v6P,
182
185
  ]);
186
+ const relayReady = relayResult?.ready ?? null;
187
+ const relayDetail = relayResult?.detail ?? '';
183
188
 
184
189
  let v6 = '';
185
190
  let v6ProbeOk = false;
@@ -189,8 +194,13 @@ async function collectEdge(ctx) {
189
194
  v6ProbeOk = c.state !== 'failed';
190
195
  }
191
196
 
197
+ if (probe && switches.relay && relayReady === false) {
198
+ const detail = relayDetail ? `(${relayDetail.replace(/\s*\n\s*/g, ';')})` : '';
199
+ issues.push(`中继线路不可用${detail}——检查 ${topo.relay.alias} 可达性,以及 core 上的 ssh-net status --probe`);
200
+ }
201
+
192
202
  return {
193
- role: 'edge', alias: ctx.self.alias, switches, relayReady, peerReady,
203
+ role: 'edge', alias: ctx.self.alias, switches, probed: probe, relayReady, peerReady,
194
204
  linkInstalled, job,
195
205
  forwardViews: forwards.map((f, i) => [forwardLabel(f), portsOk[i]]),
196
206
  coreAlias: topo.core.alias, relayAlias: topo.relay.alias,
@@ -198,15 +208,17 @@ async function collectEdge(ctx) {
198
208
  };
199
209
  }
200
210
 
201
- async function collectCore(ctx) {
211
+ async function collectCore(ctx, probe) {
202
212
  const { topo, paths } = ctx;
203
213
  const { issues } = baseAudit(ctx, coreNodeRuntimePlan(topo));
204
214
 
205
215
  // disabled override 是整域同一份字典:relay job 与各 edge job 共用一次拉取
206
216
  const dmap = launchd.disabledMap(ctx.runner, ctx.uid);
207
217
  const relayJob = launchd.inspectWith(ctx.runner, ctx.uid, relayLabel(topo.relay.alias), dmap);
208
- // relay 口实测是 8s 超时的真 ssh:先发起来,边等边做注册态体检
209
- const relayPortP = relayPortListening(ctx, topo.core.relayPort);
218
+ // 实测时先发起来,边等边做注册态体检;默认快查不发起 ssh
219
+ const relayPortP = probe
220
+ ? relayPortListening(ctx, topo.core.relayPort)
221
+ : Promise.resolve(null);
210
222
 
211
223
  // 回拨实体全 core 一份:循环外体检一次,各已注册 edge 只检各自的软链
212
224
  const callbackEntityAudit = topo.edges.length > 0
@@ -243,38 +255,39 @@ async function collectCore(ctx) {
243
255
 
244
256
  const relayPort = await relayPortP;
245
257
  if (!relayJob.running) issues.push('relay 未在运行——ssh-net start 可拉起');
246
- if (!relayPort.listening)
258
+ if (relayPort && !relayPort.listening)
247
259
  issues.push(relayPortIssue(topo.relay.alias, topo.core.relayPort, relayPort));
248
260
 
249
261
  return {
250
- role: 'core', alias: ctx.self.alias,
262
+ role: 'core', alias: ctx.self.alias, probed: probe,
251
263
  relayAlias: topo.relay.alias, relayJob, relayPort, edges, issues,
252
264
  };
253
265
  }
254
266
 
255
- async function collectNode(ctx) {
267
+ async function collectNode(ctx, probe) {
256
268
  const { topo } = ctx;
257
269
  const { issues } = baseAudit(ctx, coreNodeRuntimePlan(topo));
258
270
  const entries = edgeEntries(ctx, issues);
259
271
 
260
272
  const unit = relayUnitName(topo.relay.alias);
261
273
  const active = systemd.isActive(ctx.runner, unit);
262
- const relayPort = await relayPortListening(ctx, ctx.self.relayPort);
274
+ const relayPort = probe ? await relayPortListening(ctx, ctx.self.relayPort) : null;
263
275
  if (active !== 'active')
264
276
  issues.push(`系统服务 ${unit} 状态 ${active}——systemctl status ${unit} 查看`);
265
- if (!relayPort.listening)
277
+ if (relayPort && !relayPort.listening)
266
278
  issues.push(relayPortIssue(topo.relay.alias, ctx.self.relayPort, relayPort));
267
279
 
268
280
  return {
269
- role: 'node', alias: ctx.self.alias,
281
+ role: 'node', alias: ctx.self.alias, probed: probe,
270
282
  relayAlias: topo.relay.alias, active, relayPort, entries, issues,
271
283
  };
272
284
  }
273
285
 
274
- export async function collect(ctx) {
275
- if (ctx.role === 'edge') return collectEdge(ctx);
276
- if (ctx.role === 'core') return collectCore(ctx);
277
- if (ctx.role === 'node') return collectNode(ctx);
286
+ /** 默认只做本地采集;需要线路实测的调用方显式传 probe:true。 */
287
+ export async function collect(ctx, { probe = false } = {}) {
288
+ if (ctx.role === 'edge') return collectEdge(ctx, probe);
289
+ if (ctx.role === 'core') return collectCore(ctx, probe);
290
+ if (ctx.role === 'node') return collectNode(ctx, probe);
278
291
  throw new Error(`未知角色:${ctx.role}`);
279
292
  }
280
293
 
@@ -284,68 +297,86 @@ const exitNote = (code) => (code && code !== '0' ? `(上次退出 ${code})`
284
297
  /** 线路行的统一形状:✓ 就绪 / ✗ 未就绪。「关」只有 peer 有,由调用方自写。 */
285
298
  function lineOf(name, ready, okText, failText) {
286
299
  return ready
287
- ? ` ${name}: ✓ ${okText}`
288
- : ` ${name}: ✗ ${failText}`;
300
+ ? ` ${name}:✓ ${okText}`
301
+ : ` ${name}:✗ ${failText}`;
289
302
  }
290
303
 
291
- /** core/node 共用的 relay 状态行。 */
304
+ /** core/node 共用的 relay 状态行,未实测不猜端口状态。 */
292
305
  function relayStatusLine(s) {
306
+ if (!s.probed) return ' relay:未实测(需要时运行 ssh-net status --probe)';
293
307
  return s.relayPort.listening
294
- ? ` relay: ✓ 开着(在外面经 ${s.relayAlias} 进入 ${s.alias} · 入口 ${s.relayPort.port})`
295
- : ` relay: ✗ ${s.relayPort.reachable === false ? `连不上 ${s.relayAlias},入口状态未知` : `入口 ${s.relayPort.port} 没在监听`}`;
308
+ ? ` relay:✓ 可用(外部可经 ${s.relayAlias} 进入 ${s.alias} · 入口 ${s.relayPort.port})`
309
+ : ` relay:✗ ${s.relayPort.reachable === false ? `连不上 ${s.relayAlias},入口状态未知` : `入口 ${s.relayPort.port} 没在监听`}`;
296
310
  }
297
311
 
298
312
  function renderEdgeLines(s, lines) {
299
313
  const sw = s.switches;
300
314
  if (!sw.relay) {
301
- lines.push(' 开关: 全关(在办公室,局域网直连即可;需要时 ssh-net start)');
315
+ lines.push(' 开关:全关(ssh 使用静态 Host 地址;恢复自动选路:ssh-net start)');
302
316
  } else {
303
- lines.push(` 开关: relay 开 · peer ${sw.peer ? '开' : '关'}`);
304
- lines.push(lineOf('relay', s.relayReady,
305
- `可用(经 ${s.relayAlias} 连到 ${s.coreAlias})`,
306
- `不可用(经 ${s.relayAlias} 连不上 ${s.coreAlias};刚开启请等几秒再看,持续出现查 ${s.relayAlias} 或 core 侧 ssh-net status)`));
307
- const peerUnready = !s.v6ProbeOk
308
- ? '未就绪(本机 v6 探测没跑成,直连状态未知;中继不受影响)'
309
- : s.v6 === ''
310
- ? '未就绪(本网络没有 IPv6,直连建不起来;中继不受影响)'
311
- : '未就绪(等 core 连过来;ssh-net doctor 立即重试,中继不受影响)';
312
- lines.push(!sw.peer
313
- ? ' peer: 关(不通知 core,它不会连过来)'
314
- : lineOf('peer', s.peerReady,
315
- `已就绪(v6 直达 ${s.coreAlias},一条 ssh)`,
316
- peerUnready));
317
- if (s.linkInstalled && s.forwardViews.length > 0) {
318
- const bad = s.forwardViews.filter(([, ok]) => !ok).map(([l]) => l);
319
- lines.push(lineOf('link', bad.length === 0,
320
- `就绪(${s.forwardViews.map(([l]) => l).join(' · ')})`,
321
- `未就绪(${bad.join('、')} 没在听;刚开启请等几秒,持续出现查 ${s.coreAlias} 上的转发目标服务)`));
317
+ lines.push(` 开关:relay 开 · peer ${sw.peer ? '开(允许主动恢复直连)' : '关(只停止主动恢复)'}`);
318
+ if (!s.probed) {
319
+ lines.push(' 线路:未实测(需要时运行 ssh-net status --probe)');
320
+ } else {
321
+ lines.push(lineOf('relay', s.relayReady,
322
+ `可用(经 ${s.relayAlias} 连到 ${s.coreAlias})`,
323
+ `不可用(经 ${s.relayAlias} 连不上 ${s.coreAlias};刚开启请等几秒,持续出现查 ${s.relayAlias} 或 core 侧 ssh-net status --probe)`));
324
+ const peerUnready = !s.v6ProbeOk
325
+ ? '未就绪(本机 IPv6 探测失败,直连状态未知)'
326
+ : s.v6 === ''
327
+ ? '未就绪(当前网络没有可用 IPv6)'
328
+ : '未就绪(core 尚未连过来;可运行 ssh-net doctor 立即重试)';
329
+ if (sw.peer) {
330
+ lines.push(lineOf('peer', s.peerReady,
331
+ `IPv6 直连已就绪(到 ${s.coreAlias},一条 ssh)`,
332
+ peerUnready));
333
+ } else if (s.peerReady) {
334
+ lines.push(' peer:✓ 现有 IPv6 直连仍可用(不主动恢复)');
335
+ } else {
336
+ lines.push(' peer:关(当前无可用直连;不主动恢复)');
337
+ }
338
+ if (s.linkInstalled && s.forwardViews.length > 0) {
339
+ const bad = s.forwardViews.filter(([, ok]) => !ok).map(([l]) => l);
340
+ lines.push(lineOf('link', bad.length === 0,
341
+ `本地端口在听(${s.forwardViews.map(([l]) => l).join(' · ')})`,
342
+ `本地端口未在听(${bad.join('、')};检查本地转发任务与中继线路)`));
343
+ }
344
+ lines.push(s.v6 !== ''
345
+ ? ` 对外地址:${s.v6}`
346
+ : !s.v6ProbeOk
347
+ ? ' 对外地址:未知(IPv6 探测失败,稍后再试)'
348
+ : ' 对外地址:当前没有可用 IPv6');
322
349
  }
323
- lines.push(s.v6 !== ''
324
- ? ` 对外地址: ${s.v6}`
325
- : !s.v6ProbeOk
326
- ? ' 对外地址: 未知(v6 探测没跑成,稍后再试)'
327
- : ` 对外地址: 无 v6${sw.peer ? '(peer 建不起来,只能走 relay)' : ''}`);
328
350
  }
329
351
  lines.push(s.linkInstalled
330
- ? ` link 附加件: 已安装(${s.job.running ? '运行中' : '未运行'})`
331
- : ' link 附加件: 未安装(要 SOCKS/VNC 转发口:ssh-net install --with-link)');
352
+ ? ` 本地转发(link):已安装(后台任务${s.job.running ? '运行中' : '未运行'})`
353
+ : ' 本地转发(link):未安装(需要 SOCKS/VNC 端口:ssh-net install --with-link)');
354
+ }
355
+
356
+ function edgeTaskState(e) {
357
+ const failed = Boolean(e.lastExitCode && e.lastExitCode !== '0');
358
+ if (!e.registered) {
359
+ return e.v6
360
+ ? `当前未加载(曾收到地址 ${e.v6};它下次连接时自动恢复)`
361
+ : '尚未建立(等这台笔记本第一次发起连接)';
362
+ }
363
+ if (e.disabled) {
364
+ if (e.running) return '已标记休眠,进程尚未退出';
365
+ if (failed) return `已标记休眠,但上次退出 ${e.lastExitCode};launchd 仍可能自动重拉`;
366
+ return '休眠中(这台笔记本下次 ssh 或 start peer 时自动唤醒)';
367
+ }
368
+ if (e.running) return `运行中(仅表示任务进程,不代表线路已通)${exitNote(e.lastExitCode)}`;
369
+ if (failed) return `未运行(上次退出 ${e.lastExitCode},launchd 会自动重拉)`;
370
+ return '未运行(对端下次通知时会重新拉起)';
332
371
  }
333
372
 
334
373
  function renderCoreLines(s, lines) {
335
374
  lines.push(relayStatusLine(s));
336
- lines.push(` relay 进程: ${s.relayJob.running ? `运行中${exitNote(s.relayJob.lastExitCode)}` : '未运行'}`);
337
- lines.push(' edge:');
375
+ lines.push(` relay 进程:${s.relayJob.running ? `运行中${exitNote(s.relayJob.lastExitCode)}` : '未运行'}`);
376
+ lines.push(' edge 自动连接任务:');
338
377
  for (const e of s.edges) {
339
- // 未注册分两态:state 无 v6 = 真从未连接;有 v6 = 曾报名过(休眠后 gui 域
340
- // 会话重建会这样),等它下次报名自愈——别说成「到场装机」
341
- const state = !e.registered
342
- ? (e.v6
343
- ? `曾连接过(地址 ${e.v6}),现在没在拨——休眠/重启后的正常态,它下次来连时自动恢复`
344
- : '从未连接(到场装机后自动出现)')
345
- : e.disabled ? '休眠中(这台笔记本下次 ssh 或 start peer 时自动唤醒)'
346
- : e.running ? `已连接(地址 ${e.v6 ?? '?'})${exitNote(e.lastExitCode)}`
347
- : '已断开(自动重试中)';
348
- lines.push(` ${e.alias} ${state}`);
378
+ // 这里只报告 launchd 任务,不把进程 running 当作 SSH 线路已连通
379
+ lines.push(` ${e.alias} ${edgeTaskState(e)}`);
349
380
  lines.push(` ${addrNote(e.entry)}`);
350
381
  }
351
382
  }
@@ -356,20 +387,20 @@ export function renderText(s) {
356
387
  else if (s.role === 'core') renderCoreLines(s, lines);
357
388
  else {
358
389
  lines.push(relayStatusLine(s));
359
- lines.push(` relay 进程: ${s.active === 'active' ? '运行中(systemd)' : `${s.active}(systemd)`}`);
360
- lines.push(' edge:');
390
+ lines.push(` relay 进程:${s.active === 'active' ? '运行中(systemd)' : `${s.active}(systemd)`}`);
391
+ lines.push(' edge 的 ssh 入口:');
361
392
  for (const e of s.entries) lines.push(` ${e.alias} ${addrNote(e)}`);
362
393
  }
363
394
  if (s.issues.length) {
364
- lines.push('需要处理:');
395
+ lines.push('需要处理:');
365
396
  for (const i of s.issues) lines.push(` - ${i}`);
366
397
  }
367
398
  return lines.join('\n');
368
399
  }
369
400
 
370
401
  export async function run(ctx, args = []) {
371
- if (args.length)
372
- throw new Error('用法:status 不带参数');
373
- const s = await collect(ctx);
402
+ if (args.length > 1 || (args.length === 1 && args[0] !== '--probe'))
403
+ throw new Error('用法:status [--probe]');
404
+ const s = await collect(ctx, { probe: args[0] === '--probe' });
374
405
  return { text: renderText(s), issues: s.issues };
375
406
  }
@@ -6,9 +6,9 @@
6
6
  import * as launchd from '../lib/launchd.mjs';
7
7
  import * as systemd from '../lib/systemd.mjs';
8
8
  import { reapEdgeLink } from '../lib/jobctl.mjs';
9
- import { assertUnitSwitchArgs } from '../lib/cliargs.mjs';
9
+ import { assertUnitSwitchArgs, recoveryResult } from '../lib/cliargs.mjs';
10
10
  import { SWITCH_NAMES } from '../lib/state.mjs';
11
- import { relayLabel, relayUnitName } from '../lib/render.mjs';
11
+ import { linkLabel, relayLabel, relayLinkName, relayUnitName } from '../lib/render.mjs';
12
12
 
13
13
  function parseTarget(args) {
14
14
  if (args.length === 0 || args.length === 1 && (args[0] === '-a' || args[0] === '--all'))
@@ -20,18 +20,57 @@ function parseTarget(args) {
20
20
  throw new Error('用法:stop [-a|--all|relay|peer](不带参数或 -a=全部关闭)');
21
21
  }
22
22
 
23
- function stopCore(ctx) {
24
- const label = relayLabel(ctx.topo.relay.alias);
23
+ /** 三类停止原语:正常与恢复路径只负责发现 label/unit,顺序和失败处理共用。 */
24
+ function stopRelayJob(ctx, label) {
25
25
  const d = launchd.disable(ctx.runner, ctx.uid, label);
26
- if (d.code !== 0) throw new Error(`disable 失败:${d.stderr.trim()}`);
26
+ if (d.code !== 0) throw new Error(`disable 失败(${label}):${d.stderr.trim()}`);
27
27
  const bo = launchd.bootout(ctx.runner, ctx.uid, label);
28
28
  // 113 = 未注册(竞态下消失);其余失败必须报,否则 stop 谎报成功、隧道还活着
29
29
  if (bo.code !== 0 && bo.code !== 113)
30
- throw new Error(`bootout 失败(job 仍在注册表):${bo.stderr.trim()}`);
31
- return 'relay 已关闭(edge 的 peer 连接不受影响)';
30
+ throw new Error(`bootout 失败(${label} 仍在注册表):${bo.stderr.trim()}`);
31
+ }
32
+
33
+ function stopNodeUnit(ctx, unit) {
34
+ systemd.stopIfLoaded(ctx.runner, unit); // not-loaded(未装/已卸)无害,真失败抛出
35
+ systemd.disableIfInstalled(ctx.runner, unit); // 未装/已卸幂等,与 mac bootout 113 同口径
36
+ }
37
+
38
+ function reapLinkOrThrow(ctx, label) {
39
+ const { gone } = reapEdgeLink(ctx, label);
40
+ if (!gone)
41
+ throw new Error(`${label} 发 TERM 后仍在运行。手工排查:launchctl print gui/${ctx.uid}/${label}`);
42
+ }
43
+
44
+ /** 配置不可用:只按磁盘上的 link/relay 任务全停,不猜 topology,也不动 edge 回拨任务。 */
45
+ function stopRecoveryResult(ctx, action) {
46
+ return `${recoveryResult(ctx, action)}\n修复配置:dot apply ssh;之后运行 ssh-net status 检查`;
47
+ }
48
+
49
+ function stopRecovery(ctx, args) {
50
+ assertUnitSwitchArgs(args, 'stop',
51
+ '配置不可用时 stop 只支持不带参数或 -a/--all;修复配置后再按 relay/peer 分别操作');
52
+ if ((ctx.platform ?? process.platform) === 'linux') {
53
+ const units = systemd.unitNamesOnDisk(ctx.paths.systemdUnitDir, relayLinkName(''));
54
+ if (units.length > 0 && ctx.uid !== 0)
55
+ throw new Error('停止 node 的中继服务需要 root,请运行 sudo -i ssh-net stop');
56
+ ctx.state.removeOn(['relay', 'peer']);
57
+ for (const unit of units) stopNodeUnit(ctx, unit);
58
+ return stopRecoveryResult(ctx, units.length
59
+ ? `已停止并禁用 ${units.length} 个中继服务`
60
+ : '未发现中继服务;已清除本机开关');
61
+ }
62
+
63
+ const links = launchd.labelsOnDisk(ctx.paths.launchAgentsDir, linkLabel(''));
64
+ const relays = launchd.labelsOnDisk(ctx.paths.launchAgentsDir, relayLabel(''));
65
+ ctx.state.removeOn(['relay', 'peer']);
66
+ for (const label of links) reapLinkOrThrow(ctx, label);
67
+ for (const label of relays) stopRelayJob(ctx, label);
68
+ return stopRecoveryResult(ctx,
69
+ `已清除 relay/peer 开关,停止 ${links.length} 个本地转发任务和 ${relays.length} 个中继任务`);
32
70
  }
33
71
 
34
72
  export function run(ctx, args = []) {
73
+ if (ctx.configError) return stopRecovery(ctx, args);
35
74
  if (ctx.role === 'edge') {
36
75
  const target = parseTarget(args);
37
76
  const before = ctx.state.readSwitches();
@@ -41,34 +80,31 @@ export function run(ctx, args = []) {
41
80
  if (!before.peer) return 'peer 已是关闭状态(无需改动)';
42
81
  // 软关:不再通知 core 来连。已建立的连接继续用;装了 link,其转发 ssh
43
82
  // 重连时也不会通知,自然只走中继
44
- return 'peer 已关闭(不再通知 core 来连。已建立的连接继续用,新连接走中继)';
83
+ return 'peer 已关闭:不再主动通知 core 恢复 IPv6 直连;现有直连断开前仍可供新 ssh 使用,断开后走中继';
45
84
  }
46
85
  // 全关 / 只关 relay:级联删两开关(peer 依赖 relay),硬停 link job
47
86
  // (PathState 见 RELAY_ON 消失不再重拉;未装附加件直接 gone)
48
87
  const alreadyAllOff = !before.relay && !before.peer;
49
88
  ctx.state.removeOn(['relay', 'peer']);
50
- const { gone, label } = reapEdgeLink(ctx);
51
- if (!gone)
52
- throw new Error(
53
- `${label} 发 TERM 后仍在运行。手工排查:launchctl print gui/${ctx.uid}/${label}`,
54
- );
89
+ reapLinkOrThrow(ctx, linkLabel(ctx.topo.core.alias));
55
90
  if (target === null) {
56
91
  return alreadyAllOff
57
92
  ? '隧道已是关闭状态(无需改动)'
58
- : '隧道已关闭。几分钟后 core 会停止尝试连过来(正常,下次开启自动恢复)';
93
+ : '隧道已关闭;core 会在现有连接退出后停止重试,下次开启自动恢复';
59
94
  }
60
95
  return alreadyAllOff
61
96
  ? 'relay 已是关闭状态(peer 本就没开)'
62
- : 'relay 已关闭(peer 一并关闭——它依赖 relay)。几分钟后 core 会停止尝试连过来';
97
+ : 'relay 和 peer 已一并关闭;core 会在现有连接退出后停止重试,下次开启自动恢复';
63
98
  }
64
99
  // core/node 是单总开关(等同 --all):显式 -a/--all 收下,其余参数拒绝
65
100
  assertUnitSwitchArgs(args, 'stop');
66
- if (ctx.role === 'core') return stopCore(ctx);
101
+ if (ctx.role === 'core') {
102
+ stopRelayJob(ctx, relayLabel(ctx.topo.relay.alias));
103
+ return '中继通道已关闭(现有 IPv6 直连不受影响)';
104
+ }
67
105
  if (ctx.role === 'node') {
68
- const unit = relayUnitName(ctx.topo.relay.alias);
69
- systemd.stopIfLoaded(ctx.runner, unit); // not-loaded(未装/已卸)无害,真失败抛出
70
- systemd.disableIfInstalled(ctx.runner, unit); // 未装/已卸幂等,与 mac bootout 113 同口径
71
- return 'relay 已关闭(重启后保持关闭)';
106
+ stopNodeUnit(ctx, relayUnitName(ctx.topo.relay.alias));
107
+ return '中继通道已关闭(重启后保持关闭)';
72
108
  }
73
109
  throw new Error(`未知角色:${ctx.role}`);
74
110
  }
@@ -10,6 +10,7 @@ import {
10
10
  linkLabel,
11
11
  relayLabel, relayLinkName, relayUnitName, edgeLabel,
12
12
  } from '../lib/render.mjs';
13
+ import { recoveryResult } from '../lib/cliargs.mjs';
13
14
 
14
15
  const rm = (p) => fs.rmSync(p, { recursive: true, force: true });
15
16
 
@@ -23,17 +24,46 @@ function removeArtifacts(ctx) {
23
24
  rm(ctx.paths.linkEnabledFile);
24
25
  }
25
26
 
27
+ /** 日志也按工具独占前缀清理,覆盖 plist 已丢但日志仍在的恢复场景。 */
28
+ function removeSshNetLogs(ctx) {
29
+ let files = [];
30
+ try { files = fs.readdirSync(ctx.paths.logsDir); } catch (err) {
31
+ if (err.code !== 'ENOENT') throw err;
32
+ }
33
+ for (const file of files) {
34
+ if (file.startsWith('local.ssh-net-') && file.endsWith('.log'))
35
+ rm(path.join(ctx.paths.logsDir, file));
36
+ }
37
+ }
38
+
39
+ /** 删除原语由正常与恢复路径共用;目标清单的发现方式留在各入口。 */
40
+ function removeJobs(ctx, labels) {
41
+ for (const label of labels) removeJob(ctx, label, ctx.paths.plistFile(label));
42
+ }
43
+
44
+ function removeNodeUnits(ctx, units) {
45
+ for (const unit of units) {
46
+ // not-loaded(未装/已卸)无害,真失败必须报——否则删了 unit 文件、
47
+ // systemd 里留下 ghost 态的在跑进程
48
+ systemd.stopIfLoaded(ctx.runner, unit);
49
+ systemd.disableIfInstalled(ctx.runner, unit);
50
+ rm(path.join(ctx.paths.systemdUnitDir, unit));
51
+ }
52
+ // daemon-reload 失败不能吞:systemd 仍持有已删 unit,Restart=always 会
53
+ // 留着/重拉 ghost 进程(与 stopIfLoaded 注释防的是同一个谎报成功)
54
+ const dr = systemd.daemonReload(ctx.runner);
55
+ if (dr.code !== 0) throw new Error(`systemctl daemon-reload 失败:${dr.stderr.trim()}`);
56
+ }
57
+
26
58
  function uninstallEdge(ctx) {
27
59
  // 当前 topology 只提供现名;磁盘 glob 同时覆盖 core 改名前的 link job
28
60
  const labels = new Set([
29
61
  linkLabel(ctx.topo.core.alias),
30
62
  ...launchd.labelsOnDisk(ctx.paths.launchAgentsDir, linkLabel('')),
31
63
  ]);
32
- for (const label of labels) {
33
- removeJob(ctx, label, ctx.paths.plistFile(label));
34
- rm(path.join(ctx.paths.logsDir, `${label}.log`));
35
- }
64
+ removeJobs(ctx, labels);
36
65
  removeArtifacts(ctx);
66
+ removeSshNetLogs(ctx);
37
67
  return '已卸载。最后一步:npm uninstall -g ssh-net';
38
68
  }
39
69
 
@@ -44,20 +74,17 @@ function uninstallCore(ctx) {
44
74
  edgeJobs.set(edgeLabel(alias), alias);
45
75
  for (const e of ctx.topo.edges)
46
76
  edgeJobs.set(edgeLabel(e.alias), e.alias);
47
- for (const [label] of edgeJobs)
48
- removeJob(ctx, label, ctx.paths.plistFile(label));
77
+ removeJobs(ctx, edgeJobs.keys());
49
78
 
50
79
  const relays = new Set([
51
80
  relayLabel(ctx.topo.relay.alias),
52
81
  ...launchd.labelsOnDisk(ctx.paths.launchAgentsDir, relayLabel('')),
53
82
  ]);
54
- for (const relay of relays)
55
- removeJob(ctx, relay, ctx.paths.plistFile(relay));
83
+ removeJobs(ctx, relays);
56
84
 
57
85
  removeArtifacts(ctx); // 全部 edge-<别名> 动态片段随 conf.d 整棵删
58
- for (const label of [...edgeJobs.keys(), ...relays])
59
- rm(path.join(ctx.paths.logsDir, `${label}.log`));
60
- return `已卸载(relay 通道与 ${edgeJobs.size} 台笔记本的自动连接任务)。最后一步:npm uninstall -g ssh-net`;
86
+ removeSshNetLogs(ctx);
87
+ return `已卸载(中继通道与 ${edgeJobs.size} 台笔记本的自动连接任务)。最后一步:npm uninstall -g ssh-net`;
61
88
  }
62
89
 
63
90
  function uninstallNode(ctx) {
@@ -67,24 +94,37 @@ function uninstallNode(ctx) {
67
94
  relayUnitName(ctx.topo.relay.alias),
68
95
  ...systemd.unitNamesOnDisk(ctx.paths.systemdUnitDir, relayLinkName('')),
69
96
  ]);
70
- for (const unit of units) {
71
- // not-loaded(未装/已卸)无害,真失败必须报——否则删了 unit 文件、
72
- // systemd 里留下 ghost 态的在跑进程
73
- systemd.stopIfLoaded(ctx.runner, unit);
74
- systemd.disableIfInstalled(ctx.runner, unit); // 未装/已卸幂等,真失败抛出
75
- rm(path.join(ctx.paths.systemdUnitDir, unit));
76
- }
77
- // daemon-reload 失败不能吞:systemd 仍持有已删 unit,Restart=always 会
78
- // 留着/重拉 ghost 进程(与 stopIfLoaded 注释防的是同一个谎报成功)
79
- const dr = systemd.daemonReload(ctx.runner);
80
- if (dr.code !== 0) throw new Error(`systemctl daemon-reload 失败:${dr.stderr.trim()}`);
97
+ removeNodeUnits(ctx, units);
81
98
  removeArtifacts(ctx);
82
99
  return '已卸载。最后一步:npm uninstall -g ssh-net';
83
100
  }
84
101
 
102
+ /** 配置不可用:按磁盘上的全部 ssh-net 任务卸载,不需要猜本机角色或别名。 */
103
+ function uninstallRecovery(ctx) {
104
+ if ((ctx.platform ?? process.platform) === 'linux') {
105
+ const units = systemd.unitNamesOnDisk(ctx.paths.systemdUnitDir, relayLinkName(''));
106
+ if (units.length > 0 && ctx.uid !== 0)
107
+ throw new Error('卸载 node 的中继服务需要 root,请运行 sudo -i ssh-net uninstall');
108
+ if (units.length > 0) removeNodeUnits(ctx, units);
109
+ removeArtifacts(ctx);
110
+ return recoveryResult(ctx, `已删除 ${units.length} 个中继服务及本机 ssh-net 产物。最后一步:npm uninstall -g ssh-net`);
111
+ }
112
+
113
+ const labels = new Set([
114
+ ...launchd.labelsOnDisk(ctx.paths.launchAgentsDir, linkLabel('')),
115
+ ...launchd.labelsOnDisk(ctx.paths.launchAgentsDir, relayLabel('')),
116
+ ...launchd.labelsOnDisk(ctx.paths.launchAgentsDir, edgeLabel('')),
117
+ ]);
118
+ removeJobs(ctx, labels);
119
+ removeArtifacts(ctx);
120
+ removeSshNetLogs(ctx);
121
+ return recoveryResult(ctx, `已停止并删除 ${labels.size} 个后台任务及本机 ssh-net 产物。最后一步:npm uninstall -g ssh-net`);
122
+ }
123
+
85
124
  export function run(ctx, args = []) {
86
125
  if (args.length)
87
126
  throw new Error('用法:uninstall 不带参数');
127
+ if (ctx.configError) return uninstallRecovery(ctx);
88
128
  switch (ctx.role) {
89
129
  case 'edge': return uninstallEdge(ctx);
90
130
  case 'core': return uninstallCore(ctx);