ssh-net 26.9.4 → 26.9.5

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
@@ -4,6 +4,34 @@
4
4
  版本号格式为**年.月.序号**(如 26.9.1),序号每月重置——2026-09-29 起
5
5
  启用;此前的 0.x 为过渡期编号。
6
6
 
7
+ ## [26.9.5] - 2026-09-29
8
+
9
+ ### 变更(edge 三开关:一个总开关拆成 relay/peer/link;开关与就绪分开报)
10
+
11
+ - **开关拆分**:`~/.ssh/ssh-net/state/` 下 `RELAY_ON`(根,job PathState
12
+ 盯它)/`PEER_ON`(控报名与接受回拨)/`LINK_ON`(控本地转发口),存在=开。
13
+ 依赖:peer、link 都要求 relay(报名信道必经 relay)。`start`/`stop` 缺省
14
+ 全开/全关,可带 `relay|peer|link` 细粒度;start peer/link 自动补 relay,
15
+ stop relay 级联全关。细粒度是软生效(零闪断):关 link 只是不再重建转发,
16
+ 关 peer 只是不再报名;要立即生效用 `restart`
17
+ - **纯报名形态**:link 关、peer 开时 link-core 不起转发 ssh,只做报名维护
18
+ (「只要被连接、不要本地 SOCKS」);relay 开但 peer/link 全关时 30s 空转
19
+ 轮询等开关变化(plist 的 PathState 只盯 RELAY_ON)
20
+ - **`ssh-net checkin` 双语义**:edge 上无参数=手动报名一次(取本机 v6 走
21
+ m4-via-relay 发 RPC 并转述结果;一次性,v6 变化后需重跑);core 上带参
22
+ 的内部 RPC 不变
23
+ - **status 按意图/事实分行**:开关行报三开关,线路行逐条实测——relay
24
+ 就绪=经 m4-via-relay 真跑一条 ssh(不再从「probe 不通」推断)、peer
25
+ 就绪=probe、link 就绪=转发口探活;开关关的线路报「关」不探测。新增
26
+ LAN 空转提示(relay 开且 core LAN 22 可达)与 loopback 转发未就绪时的
27
+ microsocks 根因提示(出口在 core 本机环回,ssh-net 管辖外)
28
+ - **迁移**:install 见到旧 `ON` 即按全开迁移为三个新标记并删;dotfiles 的
29
+ Match exec 兼容期认 `ON -o RELAY_ON`(先发 dotfiles 再升级本包,五台
30
+ 升级完收紧)。**升级必须重跑 `ssh-net install`**(plist 的 PathState
31
+ 换了盯的文件;start 会检测旧 plist 并拒绝引导 install)
32
+ - **cleanup 迁移工具退役**(连同其测试);命令面回到八个公开命令,
33
+ checkin 从内部 RPC 转公开
34
+
7
35
  ## [26.9.4] - 2026-09-29
8
36
 
9
37
  ### 变更(forward local 支持 loopback 目标:SOCKS 从 -D 换 -L 落 core 本机代理)
package/README.md CHANGED
@@ -33,6 +33,20 @@
33
33
  - **npm 包分发**:消费机 `npm i -g ssh-net`,不 clone;个人配置全部在 dotfiles
34
34
  托管(`~/.ssh/ssh-net/config` 与 ssh config),包内零个人数据
35
35
 
36
+ ## edge 的三个开关
37
+
38
+ 隧道不是单一开关,按意图拆三层(`~/.ssh/ssh-net/state/` 空标记,存在=开):
39
+
40
+ | 开关 | 管什么 | 依赖 |
41
+ | --- | --- | --- |
42
+ | `relay`(根) | job 生死与出站中继线路、报名信道 | —— |
43
+ | `peer` | 报名 v6、接受 core 回拨(被入站直连) | 需要 relay |
44
+ | `link` | 本地转发口(SOCKS/VNC) | 需要 relay |
45
+
46
+ `ssh-net start` / `stop` 缺省全开/全关;`start peer`、`stop link` 细粒度
47
+ (依赖自动级联)。只要被连接、不要本地 SOCKS:`ssh-net start relay peer` 的
48
+ 稳态即 `link` 关。人在 edge 上手动报名一次:`ssh-net checkin`。
49
+
36
50
  ## 安装
37
51
 
38
52
  需要 Node 24+(fnm 的 default 版本,非交互 ssh 经 `~/.zshenv` 同样可用)。
@@ -78,7 +92,6 @@ npm link # 开发机:控制面改即时生效(运行时脚本仍
78
92
 
79
93
  ## 状态
80
94
 
81
- 26.9.1 已发布 npm(版本号自本版起用「年.月.序号」,序号每月重置)。部署:
82
- m4/n007/n061/mb5 四台上线;文案为用户视角(peer/relay 原词 + 括号解释),
83
- edge 开关文件为大写 `ON`。在家项(公网 v6 闸门/合盖开盖)与 mb1
84
- (Phase 5)待办。
95
+ 26.9.5 已发布 npm(版本号「年.月.序号」,序号每月重置)。部署:五台上线;
96
+ edge 开关拆为 relay/peer/link 三个(旧 `ON` 由 install 自动迁移);
97
+ status 的「开关(意图)」与「就绪(实测)」分行;cleanup 迁移工具已退役。
package/libexec/cli.mjs CHANGED
@@ -18,18 +18,16 @@ import { run as restartRun } from './commands/restart.mjs';
18
18
  import { run as statusRun } from './commands/status.mjs';
19
19
  import { run as checkinRun } from './commands/checkin.mjs';
20
20
  import { run as doctorRun } from './commands/doctor.mjs';
21
- import { run as cleanupRun } from './commands/cleanup.mjs';
22
21
 
23
22
  const COMMANDS = {
24
23
  install: { run: installRun, desc: '按本机角色安装(拷贝运行时脚本 + 渲染 plist/unit)' },
25
24
  uninstall: { run: uninstallRun, desc: '停用并删除全部作业、运行时与状态(再 npm uninstall -g)' },
26
- start: { run: startRun, desc: 'edge 置 on / core 拉起 relay / node 启动' },
27
- stop: { run: stopRun, desc: 'edge 删 on 并停 link / core 停 relay / node 停服' },
25
+ start: { run: startRun, desc: 'edge 开隧道(可带 relay|peer|link,缺省全开)/ core·node 启动' },
26
+ stop: { run: stopRun, desc: 'edge 关隧道(可带 relay|peer|link,缺省全关)/ core·node 停服' },
28
27
  restart: { run: restartRun, desc: 'kickstart/restart 让循环重来' },
29
- status: { run: statusRun, desc: '本机角色状态(真实探测)' },
28
+ status: { run: statusRun, desc: '本机角色状态(开关与线路分开实测)' },
30
29
  doctor: { run: doctorRun, desc: '立即重估线路(edge):peer 不通时重新报名+选路,不等定时器' },
31
- cleanup: { run: cleanupRun, desc: '清旧隧道编排(ssh-socks/ssh-reverse)与 0.1.x 遗留(迁移期工具)' },
32
- checkin: { run: checkinRun, desc: 'RPC(仅 core):edge 报名 <别名> <v6>', internal: true },
30
+ checkin: { run: checkinRun, desc: '手动报名一次(edge,取本机 v6 发给 core)' },
33
31
  };
34
32
 
35
33
  function help() {
@@ -1,8 +1,12 @@
1
- // checkin RPC:edge 经 `ssh m4-via-relay 'ssh-net checkin <别名> <v6>'` 触发,
2
- // 仅 core 接受。四态显式处理(design §6.3,实测矩阵见 notes);四态之前先
3
- // 对账运行时脚本与 plist——install 不预建 uplink-edge,其脚本与 job 参数
4
- // (user 等)变更只有这条更新通道,缺了会永远用旧参数/旧目标拨号、六连败
5
- // 休眠循环。launchctl 真返回成功才退出 0;失败非零,edge 下一轮自然重试。
1
+ // checkin 双语义(design §6.3,2026-09-29 定):
2
+ // - edge 上 `ssh-net checkin`(无参数)= 手动报名一次:取本机 v6 走
3
+ // m4-via-relay 发给 core 的 RPC 并转述结果。不受开关控制(显式动作);
4
+ // 一次性——v6 变化后失联需重跑,常驻维护用 start peer
5
+ // - core 上 `checkin <别名> <v6>` = 内部 RPC。四态显式处理(design §6.3,
6
+ // 实测矩阵见 notes);四态之前先对账运行时脚本与 plist——install 不预建
7
+ // uplink-edge,其脚本与 job 参数(user 等)变更只有这条更新通道,缺了会
8
+ // 永远用旧参数/旧目标拨号、六连败休眠循环。launchctl 真返回成功才退出 0;
9
+ // 失败非零,edge 下一轮自然重试。
6
10
  import fs from 'node:fs';
7
11
  import path from 'node:path';
8
12
  import { explainV6Error } from '../lib/ipv6.mjs';
@@ -13,6 +17,26 @@ import {
13
17
  edgeLabel, edgeLinkName, plistFileName, renderUplinkEdgePlist,
14
18
  } from '../lib/render.mjs';
15
19
 
20
+ /** 手动报名(edge):与 link-core 循环里的报名 ssh 同一命令形态与选项集。 */
21
+ function runEdgeAnnounce(ctx) {
22
+ const v6 = ctx.runner.runRaw(
23
+ path.join(ctx.paths.binDir, 'v6-address'), [], { timeout: 5000 },
24
+ ).stdout.trim();
25
+ if (!v6)
26
+ throw new Error('当前网络没有可用 IPv6,没有可报名的地址(中继不受影响)');
27
+ const r = ctx.runner.run('ssh', [
28
+ '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15',
29
+ '-o', 'ServerAliveInterval=10', '-o', 'ServerAliveCountMax=2',
30
+ '-o', 'ControlMaster=no', '-o', 'ControlPath=none',
31
+ `${ctx.topo.core.alias}-via-relay`,
32
+ `ssh-net checkin ${ctx.self.alias} ${v6}`,
33
+ ], { timeout: 60_000 });
34
+ if (r.code !== 0)
35
+ throw new Error(`报名失败(${r.stderr.trim() || `exit ${r.code}`}):检查 s100 与 core 侧 relay 是否可用,稍后重试`);
36
+ const core = r.stdout.trim();
37
+ return `已报名(本机 v6 ${v6},core 返回 ${core})。core 几秒内回拨建立 peer;ssh-net status 查看结果`;
38
+ }
39
+
16
40
  /** kickstart 失败时把 state 回滚到 job 实际在拨的 v6(null = 删文件)。
17
41
  * 不回滚的话磁盘已是新 v6,下轮「running + v6 相同」会被 no-op 分支
18
42
  * 误吞,job 拿旧 v6 拨到六连败休眠、再等下轮 checkin 唤醒才纠正。 */
@@ -23,12 +47,16 @@ function rollbackEdgeV6(ctx, alias, prevV6) {
23
47
 
24
48
  /**
25
49
  * @param {object} ctx
26
- * @param {string[]} args [别名, v6]
50
+ * @param {string[]} args edge 无参;core 为 [别名, v6]
27
51
  * @returns {string} 给 edge 的简短结果
28
52
  */
29
- export function run(ctx, args) {
53
+ export function run(ctx, args = []) {
54
+ if (ctx.role === 'edge') {
55
+ if (args.length) throw new Error('edge 上 checkin 不带参数:直接 ssh-net checkin 报名本机 v6');
56
+ return runEdgeAnnounce(ctx);
57
+ }
30
58
  if (ctx.role !== 'core')
31
- throw new Error(`checkin 仅 core 接受,本机角色是 ${ctx.role}`);
59
+ throw new Error(`checkin 仅 edge(手动报名)或 core(内部 RPC)接受,本机角色是 ${ctx.role}`);
32
60
  const [alias, v6] = args;
33
61
  if (!alias || !v6) throw new Error('用法:checkin <edge 别名> <v6>');
34
62
 
@@ -16,8 +16,10 @@ export function run(ctx) {
16
16
  return '本机不是 edge,无需处理:core 等对应笔记本报名自动恢复,node 由 systemd 自动重启';
17
17
 
18
18
  // off 的回答不依赖注册态(未注册在 start 时自然暴露),先答最关心的
19
- if (!ctx.state.isOn())
19
+ if (!ctx.state.isOn('relay'))
20
20
  return '隧道关着(在办公室,局域网直连即可)。需要时:ssh-net start';
21
+ if (!ctx.state.isOn('peer'))
22
+ return 'peer 开关关着:重估也不会报名,kickstart 无意义。要被 core 回拨:ssh-net start peer';
21
23
 
22
24
  const label = linkLabel(ctx.topo.core.alias);
23
25
  const st = launchd.inspect(ctx.runner, ctx.uid, label);
@@ -47,6 +47,8 @@ function installEdge(ctx) {
47
47
  const { topo, paths } = ctx;
48
48
  // 预检纯读且在落任何产物之前:被拒时 bin/ 与软链一个都不建
49
49
  precheckEdgePorts(ctx);
50
+ // 26.9.5 前的总开关:见到即按「全开」迁移(迁移失败不阻断安装)
51
+ const migrated = ctx.state.migrateLegacyOn();
50
52
  ensureRuntime(ctx, [
51
53
  [linkLinkName(topo.core.alias), 'ssh-net-link-core'],
52
54
  ['peer-probe', 'peer-probe'],
@@ -58,7 +60,7 @@ function installEdge(ctx) {
58
60
  coreAlias: topo.core.alias,
59
61
  selfAlias: ctx.self.alias,
60
62
  forwardArgs: buildForwardArgs(topo.forwards),
61
- onFile: paths.onFile,
63
+ relayOnFile: paths.switchFiles.relay,
62
64
  logsDir: paths.logsDir,
63
65
  });
64
66
  const r = syncPlist(ctx, {
@@ -66,9 +68,12 @@ function installEdge(ctx) {
66
68
  plistPath: path.join(paths.launchAgentsDir, plistFileName(linkLabel(topo.core.alias))),
67
69
  content,
68
70
  });
71
+ const note = migrated
72
+ ? '(已把旧开关 ON 迁移为 relay/peer/link 三个开关,全部保持开启)'
73
+ : '';
69
74
  return r.unchanged
70
- ? '已安装,无需改动'
71
- : '安装完成。隧道默认关闭——at home(或 ssh-net start)开启';
75
+ ? `已安装,无需改动${note}`
76
+ : `安装完成。隧道默认关闭——at home(或 ssh-net start)开启${note}`;
72
77
  }
73
78
 
74
79
  function installCore(ctx) {
@@ -6,7 +6,7 @@ import { linkLabel, relayLabel, relayUnitName } from '../lib/render.mjs';
6
6
 
7
7
  export function run(ctx) {
8
8
  if (ctx.role === 'edge') {
9
- if (!ctx.state.isOn()) throw new Error('隧道未开启——先 ssh-net start');
9
+ if (!ctx.state.isOn('relay')) throw new Error('隧道未开启——先 ssh-net start');
10
10
  const label = linkLabel(ctx.topo.core.alias);
11
11
  // kickstartEnabled:与 core 同规则,残留 disabled override 时不被拒
12
12
  const r = launchd.kickstartEnabled(ctx.runner, ctx.uid, label);
@@ -1,11 +1,21 @@
1
- // start(design §5):edge touch on(PathState 同秒拉起);core 重新
2
- // enable+bootstrap uplink-relay(stop 只 bootout 不删 plist);node systemctl。
1
+ // start(design §5):edge 置开关(缺省全开;peer/link 自动补 relay,PathState
2
+ // 同秒拉起);core 重新 enable+bootstrap uplink-relay(stop 只 bootout 不删
3
+ // plist);node systemctl。三开关语义与级联见 design §5「edge 开关行为」。
3
4
  import fs from 'node:fs';
4
5
  import path from 'node:path';
5
6
  import * as launchd from '../lib/launchd.mjs';
6
7
  import * as systemd from '../lib/systemd.mjs';
7
8
  import { linkLabel, relayLabel, relayUnitName, plistFileName } from '../lib/render.mjs';
8
9
 
10
+ const TARGETS = ['relay', 'peer', 'link'];
11
+
12
+ function parseTargets(args) {
13
+ if (args.length === 0) return ['relay', 'peer', 'link'];
14
+ if (args.length > 1 || !TARGETS.includes(args[0]))
15
+ throw new Error(`用法:start [relay|peer|link](不带参数=全部开启)`);
16
+ return [args[0]];
17
+ }
18
+
9
19
  function startCore(ctx) {
10
20
  const label = relayLabel(ctx.topo.relay.alias);
11
21
  const plist = path.join(ctx.paths.launchAgentsDir, plistFileName(label));
@@ -28,14 +38,33 @@ function startCore(ctx) {
28
38
  return 'relay 已在运行';
29
39
  }
30
40
 
31
- export function run(ctx) {
41
+ export function run(ctx, args = []) {
32
42
  if (ctx.role === 'edge') {
33
43
  const label = linkLabel(ctx.topo.core.alias);
34
- if (!launchd.inspect(ctx.runner, ctx.uid, label).registered)
44
+ const st = launchd.inspect(ctx.runner, ctx.uid, label);
45
+ if (!st.registered)
35
46
  throw new Error(`link job 未注册(先 ssh-net install):launchctl print gui/${ctx.uid}/${label}`);
36
- ctx.state.setOn();
37
- return '隧道已开启(数秒内建立;ssh-net status 查看线路)';
47
+ // 防「新包 + 旧 plist」:plist 还是盯 ON 的旧模板时置 RELAY_ON 拉不起
48
+ // job,start 会谎报成功(npm 升级后没重跑 install 的典型姿势)
49
+ const plist = fs.readFileSync(
50
+ path.join(ctx.paths.launchAgentsDir, plistFileName(label)), 'utf8',
51
+ );
52
+ if (!plist.includes('RELAY_ON'))
53
+ throw new Error('job 配置还是旧版(盯 ON 标记)——先跑一次 ssh-net install 再 start');
54
+
55
+ const targets = new Set(parseTargets(args));
56
+ if (targets.has('peer') || targets.has('link')) targets.add('relay'); // 依赖级联
57
+ ctx.state.setOn([...targets]);
58
+
59
+ if (targets.size === 3)
60
+ return '隧道已开启(relay · peer · link;数秒内建立,ssh-net status 查看线路)';
61
+ if (targets.has('peer'))
62
+ return `peer 已开启(relay 一并开启;报名与回拨几秒内开始,要立即报名可跑 ssh-net checkin)`;
63
+ if (targets.has('link'))
64
+ return 'link 已开启(relay 一并开启;本地转发口几秒内建立)';
65
+ return 'relay 已开启(peer/link 维持原状:未开时不报名、无本地转发口)';
38
66
  }
67
+ if (args.length) throw new Error('本机是单总开关,start 不带参数');
39
68
  if (ctx.role === 'core') return startCore(ctx);
40
69
  if (ctx.role === 'node') {
41
70
  const r = systemd.startUnit(ctx.runner, relayUnitName(ctx.topo.relay.alias));
@@ -1,7 +1,8 @@
1
1
  // status(design §6.7):只报本机角色,判据是 banner/端口/注册态真实探测。
2
2
  // collect 返回结构化对象(测试断言对象,不锁文本);renderText 给人看——
3
- // 2026-09-29 起按用户视角组织:先答「隧道开没开、现在走哪条路、东西能不能用」,
4
- // 内部名词(脚本/注册口/last exit)只在异常时出现,且每条问题都带下一步动作。
3
+ // 2026-09-29 三开关起按「开关(意图)与就绪(实测)分开」组织:开关行报
4
+ // RELAY_ON/PEER_ON/LINK_ON,线路行逐条实测(relay 就绪=经 m4-via-relay 真跑
5
+ // 一条 ssh,不再从「probe 不通」推断),开关关的线路报「关」不探测。
5
6
  // 退出码:健康(含 edge 关闭态)0;有可行动问题 1。
6
7
  import path from 'node:path';
7
8
  import { auditScript, readRuntimeVersion, runtimeVersionIssue } from '../lib/runtime.mjs';
@@ -45,6 +46,15 @@ function relayPortListening(ctx, port) {
45
46
  return { port, reachable: true, listening: new RegExp(`127\\.0\\.0\\.1[:.]${port}\\b`).test(r.stdout) };
46
47
  }
47
48
 
49
+ /** edge 的 relay 线路实测:经 m4-via-relay 跑一条真 ssh(报名/中继同信道)。 */
50
+ function relayPathOk(ctx) {
51
+ const r = ctx.runner.run('ssh', [
52
+ '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5',
53
+ `${ctx.topo.core.alias}-via-relay`, 'true',
54
+ ], { timeout: 8000 });
55
+ return r.code === 0;
56
+ }
57
+
48
58
  async function collectEdge(ctx) {
49
59
  const { topo, paths, state } = ctx;
50
60
  const issues = [];
@@ -66,24 +76,41 @@ async function collectEdge(ctx) {
66
76
 
67
77
  const label = linkLabel(topo.core.alias);
68
78
  const job = launchd.inspect(ctx.runner, ctx.uid, label);
69
- const on = state.isOn();
70
-
71
- let route = 'lan';
72
- let peer = null;
73
- const ports = {};
74
- if (on) {
75
- peer = peerProbeOk(ctx.runner, paths.binDir);
76
- route = peer ? 'peer' : 'relay';
77
- // 开着但 probe 不通可能只是回拨尚未建立;不当作问题(中继同期可用)
79
+ const switches = state.readSwitches();
80
+
81
+ // 就绪实测(On 是意图、ready 是事实):开关关的线路不探测(null=按开关关)
82
+ const relayOk = ctx.relayOk ?? relayPathOk; // 测试可注入
83
+ const openTcp = ctx.openTcp ?? tcpOpen;
84
+ const relayReady = switches.relay ? relayOk(ctx) : null;
85
+ const peerReady = switches.relay && switches.peer
86
+ ? peerProbeOk(ctx.runner, paths.binDir)
87
+ : null;
88
+
89
+ const ports = {}; // link 关时不探,保持 undefined(区别于「探了不在听」)
90
+ if (switches.link)
91
+ for (const f of topo.forwards) ports[f.listenPort] = await openTcp('127.0.0.1', f.listenPort);
92
+
93
+ // relay 开但 core 的 LAN 22 可达 = 人在办公室忘了关(只提示不纠偏)
94
+ if (switches.relay && topo.core.lanIp) {
95
+ const lanReachable = await openTcp(topo.core.lanIp, 22, 1200);
96
+ if (lanReachable)
97
+ issues.push(`检测到 ${topo.core.alias}(${topo.core.lanIp})局域网直连可达——隧道可能在空转绕中继;人在办公室可 ssh-net stop`);
78
98
  }
79
- const openTcp = ctx.openTcp ?? tcpOpen; // 测试可注入,避免连真端口
80
- for (const f of topo.forwards) ports[f.listenPort] = await openTcp('127.0.0.1', f.listenPort);
81
99
 
82
100
  // 关着但转发口仍在听 = 孤儿进程
83
- if (!on)
84
- for (const f of topo.forwards)
85
- if (ports[f.listenPort])
101
+ if (!switches.relay)
102
+ for (const f of topo.forwards) {
103
+ const listening = await openTcp('127.0.0.1', f.listenPort);
104
+ if (listening)
86
105
  issues.push(`隧道已关但 ${forwardLabel(f)} 仍被占用——疑似残留进程:lsof -nP -iTCP:${f.listenPort} -sTCP:LISTEN 查占用者`);
106
+ }
107
+
108
+ // loopback 转发的出口在 core 本机环回(microsocks),ssh-net 管辖外:
109
+ // 未就绪时给根因提示,别让排障只在 edge 侧打转
110
+ if (switches.link)
111
+ for (const f of topo.forwards)
112
+ if (f.kind === 'local' && f.targetAlias === 'loopback' && !ports[f.listenPort])
113
+ issues.push(`${forwardLabel(f)} 未就绪:edge 侧正常时多半是 core 上的出口代理(microsocks)没跑——到 core 上查 local.microsocks`);
87
114
 
88
115
  let v6 = '';
89
116
  if (links.find((l) => l.link === 'v6-address')?.audit === 'ok')
@@ -91,8 +118,9 @@ async function collectEdge(ctx) {
91
118
 
92
119
  const forwardViews = topo.forwards.map((f) => [forwardLabel(f), ports[f.listenPort]]);
93
120
  return {
94
- role: 'edge', alias: ctx.self.alias, on, route, peer, job, links, ports,
95
- forwardViews, coreAlias: topo.core.alias, v6, runtimeVersion, issues,
121
+ role: 'edge', alias: ctx.self.alias, switches, relayReady, peerReady,
122
+ job, links, ports, forwardViews, coreAlias: topo.core.alias,
123
+ v6, runtimeVersion, issues,
96
124
  };
97
125
  }
98
126
 
@@ -189,25 +217,47 @@ export async function collect(ctx) {
189
217
  /** 上次退出码非 0 才值得看;0 与从未退出都不显示。 */
190
218
  const exitNote = (code) => (code && code !== '0' ? `(上次退出 ${code})` : '');
191
219
 
220
+ /** 线路行的统一形状:✓ 已就绪 / ✗ 未就绪 / 关(按开关)。 */
221
+ function lineOf(name, on, ready, okText, failText, offText) {
222
+ if (!on) return ` ${name}: 关(${offText})`;
223
+ return ready
224
+ ? ` ${name}: ✓ ${okText}`
225
+ : ` ${name}: ✗ ${failText}`;
226
+ }
227
+
192
228
  export function renderText(s) {
193
229
  const lines = [];
194
230
  lines.push(`ssh-net ${s.role} ${s.alias}`);
195
231
 
196
232
  if (s.role === 'edge') {
197
- if (!s.on) {
198
- lines.push(' 隧道开关: 关(在办公室,局域网直连即可)');
233
+ const sw = s.switches;
234
+ if (!sw.relay && !sw.peer && !sw.link) {
235
+ lines.push(' 开关: 全关(在办公室,局域网直连即可)');
199
236
  } else {
200
- lines.push(' 隧道开关: 开');
201
- lines.push(s.peer
202
- ? ` 当前线路: peer(v6 直达 ${s.coreAlias},一条 ssh)`
203
- : ' 当前线路: relay(经 s100 中转;peer 恢复后自动切回)');
237
+ lines.push(` 开关: relay ${sw.relay ? '开' : '关'} · peer ${sw.peer ? '开' : '关'} · link ${sw.link ? '开' : '关'}`);
238
+ lines.push(lineOf('relay', sw.relay, s.relayReady,
239
+ `可用(经 ${s.coreAlias} 的中继信道)`,
240
+ '不可用(经 s100 连不上 core;刚开启请等几秒再看,持续出现查 s100 或 core 侧 ssh-net status)',
241
+ '按开关'));
242
+ // peer/link 依赖 relay:relay 关时一并显示关(手动 touch 出的非法定态)
243
+ lines.push(lineOf('peer', sw.relay && sw.peer, s.peerReady,
244
+ `已就绪(v6 直达 ${s.coreAlias},一条 ssh)`,
245
+ '未就绪(等 core 回拨建立;ssh-net doctor 立即重估,中继不受影响)',
246
+ '按开关:不报名,core 不会回拨'));
247
+ if (!(sw.relay && sw.link)) {
248
+ lines.push(` link: 关(按开关,本地无转发口;core 仍可经回拨进入本机)`);
249
+ } else {
250
+ const views = s.forwardViews;
251
+ const allOk = views.length > 0 && views.every(([, ok]) => ok);
252
+ lines.push(allOk
253
+ ? ` link: ✓ 就绪(${views.map(([l]) => l).join(' · ')})`
254
+ : ` link: ✗ 未就绪(${views.filter(([, ok]) => !ok).map(([l]) => l).join('、')} 没在听;隧道建立中或已断)`);
255
+ }
204
256
  lines.push(s.v6 !== ''
205
257
  ? ` 对外地址: ${s.v6}`
206
- : ` 对外地址: 无 v6${s.peer ? '' : '(只能走 relay)'}`);
258
+ : ` 对外地址: 无 v6${sw.peer ? '(peer 建不起来,只能走 relay)' : ''}`);
207
259
  }
208
260
  lines.push(` 后台任务: ${!s.job.registered ? '未安装' : s.job.running ? '运行中' : '已停止'}`);
209
- for (const [label, ok] of s.forwardViews)
210
- lines.push(` ${ok ? '✓' : '✗'} ${label}${ok ? '' : '(未就绪)'}`);
211
261
  } else if (s.role === 'core') {
212
262
  lines.push(s.relayPort.listening
213
263
  ? ` relay: ✓ 开着(在外面经 ${s.relayAlias} 进入 ${s.alias} · 入口 ${s.relayPort.port})`
@@ -1,10 +1,21 @@
1
- // stop(design §5):edge rm on + TERM 并校验真退出;core disable+bootout
2
- // uplink-relay(不动 uplink-edge);node stop+disable。
1
+ // stop(design §5):edge 关开关——缺省或带 relay=级联全关(删三开关 +
2
+ // TERM 并校验真退出);只关 peer/link 是软关(只删标记,零闪断,design
3
+ // §5「软生效」)。core disable+bootout uplink-relay(不动 uplink-edge);
4
+ // node stop+disable。
3
5
  import * as launchd from '../lib/launchd.mjs';
4
6
  import * as systemd from '../lib/systemd.mjs';
5
7
  import { stopEdgeLink } from '../lib/jobctl.mjs';
6
8
  import { relayLabel, relayUnitName } from '../lib/render.mjs';
7
9
 
10
+ const TARGETS = ['relay', 'peer', 'link'];
11
+
12
+ function parseTarget(args) {
13
+ if (args.length === 0) return null; // 全关
14
+ if (args.length > 1 || !TARGETS.includes(args[0]))
15
+ throw new Error('用法:stop [relay|peer|link](不带参数=全部关闭)');
16
+ return args[0];
17
+ }
18
+
8
19
  function stopCore(ctx) {
9
20
  const label = relayLabel(ctx.topo.relay.alias);
10
21
  const d = launchd.disable(ctx.runner, ctx.uid, label);
@@ -16,15 +27,28 @@ function stopCore(ctx) {
16
27
  return 'relay 已关闭(edge 的 peer 连接不受影响)';
17
28
  }
18
29
 
19
- export function run(ctx) {
30
+ export function run(ctx, args = []) {
20
31
  if (ctx.role === 'edge') {
32
+ const target = parseTarget(args);
33
+ if (target === 'peer') {
34
+ ctx.state.removeOn(['peer']);
35
+ return 'peer 已关闭(软生效:停止报名,已建立的回拨随网络变化自然消亡;下一轮循环起不再报名)';
36
+ }
37
+ if (target === 'link') {
38
+ ctx.state.removeOn(['link']);
39
+ return 'link 已关闭(软生效:现有转发连接保持到自然断开、不再重建;要立即断开跑 ssh-net restart)';
40
+ }
41
+ // 全关 / 只关 relay:级联删三个(peer、link 都依赖 relay),硬停 job
21
42
  const { gone, label } = stopEdgeLink(ctx);
22
43
  if (!gone)
23
44
  throw new Error(
24
45
  `${label} 仍在运行(TERM 已发两次)。手工排查:launchctl print gui/${ctx.uid}/${label}`,
25
46
  );
26
- return '隧道已关闭。几分钟后办公室侧会停止回拨并静默(正常现象,下次开启自动恢复)';
47
+ if (target === null)
48
+ return '隧道已关闭。几分钟后办公室侧会停止回拨并静默(正常现象,下次开启自动恢复)';
49
+ return 'relay 已关闭(peer、link 一并关闭——它们都依赖 relay)。几分钟后办公室侧会停止回拨并静默';
27
50
  }
51
+ if (args.length) throw new Error('本机是单总开关,stop 不带参数');
28
52
  if (ctx.role === 'core') return stopCore(ctx);
29
53
  if (ctx.role === 'node') {
30
54
  const unit = relayUnitName(ctx.topo.relay.alias);
@@ -23,7 +23,9 @@ function isGone(ctx, label) {
23
23
  */
24
24
  export function stopEdgeLink(ctx) {
25
25
  const label = linkLabel(ctx.topo.core.alias);
26
- ctx.state.removeOn(); // PathState:rm 不杀进程,但阻止退出后重拉
26
+ // 级联删三个开关(peer/link 依赖 relay,见 design §5)。PathState:rm
27
+ // 不杀进程,但阻止退出后重拉
28
+ ctx.state.removeOn(['relay', 'peer', 'link']);
27
29
  if (!launchd.inspect(ctx.runner, ctx.uid, label).registered) return { gone: true, label };
28
30
 
29
31
  let remaining = TERM_BUDGET_MS;
@@ -38,7 +38,14 @@ export function machinePaths(env = process.env) {
38
38
  binDir: path.join(sshNetDir, 'bin'),
39
39
  runtimeVersionFile: path.join(sshNetDir, 'runtime-version'),
40
40
  stateDir,
41
- onFile: path.join(stateDir, 'ON'),
41
+ // 三开关(design §3):relay 是根(PathState 盯它),文件名与 bash 侧
42
+ // link-core、dotfiles Match 三处硬编码互为契约,改则三处同步
43
+ switchFiles: Object.freeze({
44
+ relay: path.join(stateDir, 'RELAY_ON'),
45
+ peer: path.join(stateDir, 'PEER_ON'),
46
+ link: path.join(stateDir, 'LINK_ON'),
47
+ }),
48
+ legacyOnFile: path.join(stateDir, 'ON'),
42
49
  edgesDir: path.join(stateDir, 'edges'),
43
50
  launchAgentsDir: path.join(home, 'Library', 'LaunchAgents'),
44
51
  logsDir: path.join(home, 'Library', 'Logs'),
@@ -62,12 +62,12 @@ export const plistFileName = (label) => `${label}.plist`;
62
62
  // ---- 三种 LaunchAgent plist ----
63
63
 
64
64
  /**
65
- * edge link job:PathState on 期间常驻,不写 RunAtLoad。
65
+ * edge link job:PathState 盯根开关 RELAY_ON,不写 RunAtLoad。
66
66
  * @param {{binDir:string, coreAlias:string, selfAlias:string,
67
- * forwardArgs:readonly string[], onFile:string, logsDir:string}} opts
67
+ * forwardArgs:readonly string[], relayOnFile:string, logsDir:string}} opts
68
68
  */
69
69
  export function renderEdgeLinkPlist(opts) {
70
- const { binDir, coreAlias, selfAlias, forwardArgs, onFile, logsDir } = opts;
70
+ const { binDir, coreAlias, selfAlias, forwardArgs, relayOnFile, logsDir } = opts;
71
71
  const label = linkLabel(coreAlias);
72
72
  const argv = [`${binDir}/${linkLinkName(coreAlias)}`, selfAlias, coreAlias, ...forwardArgs];
73
73
  return `${XML_HEAD} <key>Label</key>
@@ -78,7 +78,7 @@ ${programArguments(argv)} <key>ProcessType</key>
78
78
  <dict>
79
79
  <key>PathState</key>
80
80
  <dict>
81
- <key>${xmlEscape(onFile)}</key>
81
+ <key>${xmlEscape(relayOnFile)}</key>
82
82
  <true/>
83
83
  </dict>
84
84
  </dict>
@@ -1,14 +1,19 @@
1
- // 易变状态的全部 IO(design §3):state 目录只有 on 空标记与 edges/<别名>
2
- // (最近上报的 v6)。没有心跳、时间戳、checkout。目录 0700、文件 0600,
1
+ // 易变状态的全部 IO(design §3):state 目录只有三个开关空标记(RELAY_ON
2
+ // 是根、PEER_ON 控报名、LINK_ON 控本地转发)与 edges/<别名>(最近上报的
3
+ // v6)。没有心跳、时间戳、checkout。目录 0700、文件 0600,
3
4
  // 写 v6 走 tmp+rename 防 checkin 与 uplink-edge 读到半截。
4
5
  import fs from 'node:fs';
5
6
  import path from 'node:path';
6
7
 
8
+ const SWITCH_NAMES = ['relay', 'peer', 'link'];
9
+
7
10
  /**
8
11
  * @typedef {Object} StateStore
9
- * @property {() => boolean} isOn
10
- * @property {() => void} setOn
11
- * @property {() => boolean} removeOn 删除前是否存在
12
+ * @property {(name: 'relay'|'peer'|'link') => boolean} isOn
13
+ * @property {(names: Array<'relay'|'peer'|'link'>) => void} setOn 幂等 touch
14
+ * @property {(names: Array<'relay'|'peer'|'link'>) => void} removeOn 幂等删除
15
+ * @property {() => {relay: boolean, peer: boolean, link: boolean}} readSwitches
16
+ * @property {() => boolean} migrateLegacyOn 旧 ON 在 → 迁移为三开关(全开)并删
12
17
  * @property {(alias: string) => string | null} readEdgeV6
13
18
  * @property {(alias: string, v6: string) => void} writeEdgeV6
14
19
  * @property {(alias: string) => void} removeEdgeV6 不存在时静默
@@ -21,35 +26,67 @@ import path from 'node:path';
21
26
  */
22
27
  export function createStateStore(stateDir) {
23
28
  const edgesDir = path.join(stateDir, 'edges');
24
- const onFile = path.join(stateDir, 'ON');
29
+ const files = {
30
+ relay: path.join(stateDir, 'RELAY_ON'),
31
+ peer: path.join(stateDir, 'PEER_ON'),
32
+ link: path.join(stateDir, 'LINK_ON'),
33
+ };
34
+ const legacyOnFile = path.join(stateDir, 'ON');
25
35
 
26
36
  const ensureState = () => {
27
37
  fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
28
38
  };
29
39
 
40
+ const assertNames = (names) => {
41
+ for (const n of names)
42
+ if (!SWITCH_NAMES.includes(n)) throw new Error(`未知开关:${n}(合法:${SWITCH_NAMES.join('/')})`);
43
+ };
44
+
30
45
  return {
31
- isOn() {
32
- return fs.existsSync(onFile);
46
+ isOn(name) {
47
+ assertNames([name]);
48
+ return fs.existsSync(files[name]);
33
49
  },
34
50
 
35
- setOn() {
51
+ setOn(names) {
52
+ assertNames(names);
36
53
  ensureState();
37
- // 'a':不截断、已存在不报错(touch 语义)
38
- const fd = fs.openSync(onFile, 'a');
39
- fs.closeSync(fd);
40
- fs.chmodSync(onFile, 0o600);
54
+ for (const n of names) {
55
+ // 'a':不截断、已存在不报错(touch 语义)
56
+ const fd = fs.openSync(files[n], 'a');
57
+ fs.closeSync(fd);
58
+ fs.chmodSync(files[n], 0o600);
59
+ }
41
60
  },
42
61
 
43
- removeOn() {
44
- try {
45
- fs.unlinkSync(onFile);
46
- return true;
47
- } catch (err) {
48
- if (err && err.code === 'ENOENT') return false;
49
- throw err;
62
+ removeOn(names) {
63
+ assertNames(names);
64
+ for (const n of names) {
65
+ try {
66
+ fs.unlinkSync(files[n]);
67
+ } catch (err) {
68
+ if (err && err.code === 'ENOENT') continue;
69
+ throw err;
70
+ }
50
71
  }
51
72
  },
52
73
 
74
+ readSwitches() {
75
+ return {
76
+ relay: fs.existsSync(files.relay),
77
+ peer: fs.existsSync(files.peer),
78
+ link: fs.existsSync(files.link),
79
+ };
80
+ },
81
+
82
+ // 26.9.5 前的总开关:见到即按「全开」迁移(install 时调,输出提示由调用方给)
83
+ migrateLegacyOn() {
84
+ if (!fs.existsSync(legacyOnFile)) return false;
85
+ this.setOn(SWITCH_NAMES);
86
+ fs.unlinkSync(legacyOnFile);
87
+ return true;
88
+ },
89
+
53
90
  readEdgeV6(alias) {
54
91
  try {
55
92
  const v6 = fs.readFileSync(path.join(edgesDir, alias), 'utf8').trim();
@@ -1,8 +1,11 @@
1
1
  #!/bin/bash
2
- # ssh-net-link-core:edge 上到 core 的常驻转发 ssh(-D SOCKS + -L VNC)。
2
+ # ssh-net-link-core:edge 上到 core 的常驻隧道(-D SOCKS + -L VNC)。
3
3
  # argv: <self 别名> <peer 别名> <转发参数…>
4
4
  # 不做状态机:走 peer 还是 relay 由 ssh config Match(peer-probe)决定,
5
5
  # 循环只做「自检开关 → 报名 → 给回拨窗口 → 起一条 ssh」(design §6.1)。
6
+ # 三开关(design §3,2026-09-29 拆分):RELAY_ON 是根(launchd PathState 盯
7
+ # 它,不在即退出);PEER_ON 控报名与回拨窗口;LINK_ON 控本地转发口——
8
+ # LINK_ON 不在时循环退化为纯报名维护(被连接方向照常,不起 ssh)。
6
9
  set -u
7
10
  LC_ALL=C
8
11
  export LC_ALL
@@ -14,13 +17,16 @@ V6_POLL=${SSH_NET_V6_POLL:-15} # 无 v6 的 relay 态:轮询 v6 恢复
14
17
  PEER_WINDOW=${SSH_NET_PEER_WINDOW:-8} # 回拨建立窗口(秒)
15
18
  PROBE_INTERVAL=${SSH_NET_PROBE_INTERVAL:-1}
16
19
  LOOP_SLEEP=${SSH_NET_LOOP_SLEEP:-5}
20
+ IDLE_POLL=${SSH_NET_IDLE_POLL:-30} # relay 开但 peer/link 全关:空转轮询开关变化
17
21
 
18
22
  self=$1
19
23
  peer=$2
20
24
  shift 2
21
25
  fwd=("$@")
22
26
 
23
- on_file="$STATE_DIR/ON"
27
+ relay_on_file="$STATE_DIR/RELAY_ON"
28
+ peer_on_file="$STATE_DIR/PEER_ON"
29
+ link_on_file="$STATE_DIR/LINK_ON"
24
30
  ssh_pid=
25
31
  timer_pid=
26
32
  mode=
@@ -52,15 +58,20 @@ while :; do
52
58
  [ "$rounds" -gt "$SSH_NET_MAX_ROUNDS" ] && exit 0
53
59
  fi
54
60
 
55
- # stop 复活防线:on 没了就不再报名/重连
56
- [ -e "$on_file" ] || exit 0
61
+ # stop 复活防线:根开关没了就不再报名/重连(PathState 同步收尸)
62
+ [ -e "$relay_on_file" ] || exit 0
57
63
 
58
64
  v6=$("$BIN_DIR/v6-address" 2>/dev/null)
65
+ peer_on=0
66
+ [ -e "$peer_on_file" ] && peer_on=1
67
+ link_on=0
68
+ [ -e "$link_on_file" ] && link_on=1
59
69
 
60
- # 报名无条件但走固定 relay 别名(peer 僵尸/冷启动都可达);失败不阻断,
61
- # 只在日志留痕——报名长期失败(如 relay 别名漂移)是静默降级:中继照常
62
- # 工作、peer 永远建不起来,status 看不出区别,唯一的线索在这里
63
- if [ -n "$v6" ]; then
70
+ # 报名(PEER_ON 控)无条件走固定 relay 别名(peer 僵尸/冷启动都可达);
71
+ # 失败不阻断,只在日志留痕——报名长期失败(如 relay 别名漂移)是静默
72
+ # 降级:中继照常工作、peer 永远建不起来,status 看不出区别,唯一的
73
+ # 线索在这里
74
+ if [ -n "$v6" ] && [ "$peer_on" = 1 ]; then
64
75
  if ! "$SSH" -o BatchMode=yes -o ConnectTimeout=15 \
65
76
  -o ServerAliveInterval=10 -o ServerAliveCountMax=2 \
66
77
  -o ControlMaster=no -o ControlPath=none \
@@ -69,9 +80,10 @@ while :; do
69
80
  fi
70
81
  fi
71
82
 
72
- # 给 core 回拨建立窗口:窗口内轮询 probe,命中即 peer;无 v6 不等
83
+ # 给 core 回拨建立窗口(PEER_ON 在才等):窗口内轮询 probe,命中即
84
+ # peer;无 v6 不等
73
85
  mode=relay
74
- if [ -n "$v6" ]; then
86
+ if [ -n "$v6" ] && [ "$peer_on" = 1 ]; then
75
87
  ticks=$((PEER_WINDOW / PROBE_INTERVAL))
76
88
  i=0
77
89
  while [ "$i" -lt "$ticks" ]; do
@@ -84,25 +96,42 @@ while :; do
84
96
  done
85
97
  fi
86
98
 
87
- # 唯一一条转发 ssh(转发参数来自 argv;bash 3.2 空数组展开写法)
88
- "$SSH" -N ${fwd[@]+"${fwd[@]}"} \
89
- -o ExitOnForwardFailure=yes -o BatchMode=yes -o IdentitiesOnly=yes \
90
- -o ControlMaster=no -o ControlPath=none \
91
- -o ServerAliveInterval=35 -o ServerAliveCountMax=3 \
92
- -o ConnectTimeout=15 \
93
- "$peer" &
94
- ssh_pid=$!
99
+ # 唯一一条转发 ssh(转发参数来自 argv;LINK_ON 不在=纯报名维护,不起
100
+ # ssh——「只要被连接、不要本地转发口」的形态;bash 3.2 空数组展开写法)
101
+ ssh_pid=
102
+ if [ "$link_on" = 1 ]; then
103
+ "$SSH" -N ${fwd[@]+"${fwd[@]}"} \
104
+ -o ExitOnForwardFailure=yes -o BatchMode=yes -o IdentitiesOnly=yes \
105
+ -o ControlMaster=no -o ControlPath=none \
106
+ -o ServerAliveInterval=35 -o ServerAliveCountMax=3 \
107
+ -o ConnectTimeout=15 \
108
+ "$peer" &
109
+ ssh_pid=$!
110
+ fi
95
111
 
96
- # relay 态两种挂法(peer 不挂寿命):
97
- # - 有 v6 但 probe 不中:600s 寿命到点回循环重报重探(入站恢复的重估节奏)
98
- # - 无 v6:v6 一出现就杀 ssh 回循环(15s 粒度轮询本机 v6-address)。不用
99
- # 短寿命断连重估——那会让 relay 上的长连接(SSH 会话/VNC)周期性闪断;
100
- # watcher 方案连接期间零闪断,换回有 v6 的网络 ~15s 内升级 peer
112
+ # 等待定时器,三种形态(peer 态有 ssh 不挂;trap 与下一轮入口都清理):
113
+ # - relay 态有 ssh:有 v6=600s 寿命到点杀 ssh 回循环重估(入站恢复的
114
+ # 重估节奏);无 v6=v6-watcher 每 15s 查 v6-address,出现即杀回循环
115
+ # 重估——不用短寿命断连重估(relay 上的长连接会周期闪断),连接期
116
+ # 间零闪断
117
+ # - 纯报名态(LINK_ON 关、无 ssh):同上节奏,到点回循环顶重报
118
+ # - relay 开但 peer/link 全关:30s 空转轮询等开关变化。不能裸退——
119
+ # PathState 只盯 RELAY_ON,退出后只有 RELAY_ON 翻转才会被拉起
101
120
  timer_pid=
102
- if [ "$mode" = relay ]; then
121
+ if [ "$peer_on" = 0 ] && [ "$link_on" = 0 ]; then
122
+ (
123
+ trap 'kill "$sleep_pid" 2>/dev/null; exit 0' TERM INT
124
+ /bin/sleep "$IDLE_POLL" & sleep_pid=$!
125
+ wait "$sleep_pid"
126
+ ) &
127
+ timer_pid=$!
128
+ elif [ "$mode" = relay ]; then
103
129
  (
104
130
  trap 'kill "$sleep_pid" 2>/dev/null; exit 0' TERM INT
105
- if [ -n "$v6" ]; then
131
+ # 有 v6 → 寿命重估;无 v6 且 peer 开 → v6-watcher 盯网络恢复
132
+ # (出现即回循环报名);无 v6 且 peer 关 → 同睡寿命,只等开关
133
+ # 变化,不盯 v6(v6 出现也不会报名,白闪一次连接)
134
+ if [ -n "$v6" ] || [ "$peer_on" = 0 ]; then
106
135
  /bin/sleep "$RELAY_TTL" & sleep_pid=$!
107
136
  wait "$sleep_pid"
108
137
  else
@@ -114,18 +143,27 @@ while :; do
114
143
  [ -n "$("$BIN_DIR/v6-address" 2>/dev/null)" ] && break
115
144
  done
116
145
  fi
117
- kill "$ssh_pid" 2>/dev/null
146
+ [ -n "$ssh_pid" ] && kill "$ssh_pid" 2>/dev/null
118
147
  ) &
119
148
  timer_pid=$!
120
149
  fi
121
150
 
122
151
  # USR1 信令会中断 wait 内置(bash 3.2,同 uplink-edge 的清零信号):
123
152
  # 必须循环等到 ssh 真退出,否则信令打断 wait 后活连接还在、误入下一轮
124
- # 造成双 ssh 并发
153
+ # 造成双 ssh 并发。timer 的收法按形态分:转发态(有 ssh)随 ssh 结束
154
+ # 即杀(timer 使命是杀 ssh,ssh 死了它没存在意义;watcher 形态是无限
155
+ # 循环,等它等于死等);纯报名态(无 ssh)timer 是本轮唯一节奏器,
156
+ # 等它自然到点(寿命/出现 v6)再回循环顶
125
157
  while kill -0 "$ssh_pid" 2>/dev/null; do
126
158
  wait "$ssh_pid" 2>/dev/null
127
159
  done
128
- [ -n "$timer_pid" ] && kill "$timer_pid" 2>/dev/null
160
+ if [ -n "$ssh_pid" ]; then
161
+ [ -n "$timer_pid" ] && kill "$timer_pid" 2>/dev/null
162
+ elif [ -n "$timer_pid" ]; then
163
+ while kill -0 "$timer_pid" 2>/dev/null; do
164
+ wait "$timer_pid" 2>/dev/null
165
+ done
166
+ fi
129
167
  timer_pid=
130
168
  ssh_pid=
131
169
  /bin/sleep "$LOOP_SLEEP"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ssh-net",
3
- "version": "26.9.4",
3
+ "version": "26.9.5",
4
4
  "type": "module",
5
5
  "description": "个人 SSH 组网:v6 直连优先、relay 兜底、关机有界重试后静默",
6
6
  "bin": {
@@ -1,98 +0,0 @@
1
- // cleanup(迁移期工具,Phase 6 验收后随 migration.md 一起删):清旧隧道编排
2
- // ssh-socks / ssh-reverse 的全部产物,顺带清 ssh-net 0.1.x 遗留(旧
3
- // ~/.local/state/ssh-net 状态目录与 known-hosts 骨架,0.2.0 起均废弃)。
4
- // 幂等:不存在的项静默通过。mac 的 system 域 Daemon 与非 root 的 linux
5
- // unit 属提权项,打印现成命令不代跑。
6
- import fs from 'node:fs';
7
- import path from 'node:path';
8
- import * as launchd from '../lib/launchd.mjs';
9
- import * as systemd from '../lib/systemd.mjs';
10
-
11
- const rm = (p) => fs.rmSync(p, { recursive: true, force: true });
12
-
13
- const SOCKS_LABEL = 'local.ssh-socks-m4';
14
- const REVERSE_LABEL = 'local.ssh-reverse-s100';
15
-
16
- function cleanupDarwin(ctx, out) {
17
- const { runner, uid, paths } = ctx;
18
-
19
- // ssh-socks(旧 edge 侧 agent,gui 域,可全自助)
20
- const st = launchd.inspect(runner, uid, SOCKS_LABEL);
21
- if (st.registered) {
22
- const bo = launchd.bootout(runner, uid, SOCKS_LABEL);
23
- if (bo.code !== 0 && bo.code !== 113)
24
- throw new Error(`bootout 失败(${SOCKS_LABEL}):${bo.stderr.trim()}`);
25
- out.push(`已停旧 agent:bootout gui/${uid}/${SOCKS_LABEL}`);
26
- }
27
- let socksFiles = 0;
28
- for (const f of [
29
- path.join(paths.home, '.local/bin/ssh-socks-m4'),
30
- path.join(paths.home, 'Library/LaunchAgents/local.ssh-socks-m4.plist'),
31
- path.join(paths.home, 'Library/Logs/ssh-socks-m4.log'),
32
- ]) {
33
- if (fs.existsSync(f)) { rm(f); socksFiles += 1; out.push(`已删: ${f}`); }
34
- }
35
- if (!st.registered && socksFiles === 0) out.push('ssh-socks:无残留');
36
-
37
- // ssh-reverse(旧 core 侧,system 域 Daemon;m4 已在 Phase 2 清过,这里是
38
- // 兜底:注册态可读,plist/软链归 root,只报命令;日志归本用户,直接删)
39
- const registered = runner.run('launchctl', ['print', `system/${REVERSE_LABEL}`]).code === 0;
40
- const leftovers = [
41
- `/Library/LaunchDaemons/${REVERSE_LABEL}.plist`,
42
- '/usr/local/bin/ssh-reverse-s100',
43
- path.join(paths.home, 'Library/Logs/ssh-reverse-s100.log'),
44
- ].filter((f) => fs.existsSync(f));
45
- for (const f of leftovers.filter((f) => f.startsWith(paths.home))) {
46
- rm(f);
47
- out.push(`已删: ${f}`);
48
- }
49
- const rootOwned = leftovers.filter((f) => !f.startsWith(paths.home));
50
- if (registered || rootOwned.length) {
51
- out.push('ssh-reverse 有提权残留,请手动执行:');
52
- if (registered) out.push(` sudo launchctl bootout system/${REVERSE_LABEL}`);
53
- for (const f of rootOwned) out.push(` sudo rm -f ${f}`);
54
- } else if (!leftovers.length) {
55
- out.push('ssh-reverse:无残留');
56
- }
57
- }
58
-
59
- function cleanupLinux(ctx, out) {
60
- const { runner, paths } = ctx;
61
- const unit = 'ssh-reverse-s100.service';
62
- const unitPath = path.join(paths.systemdUnitDir, unit);
63
- const loaded = runner.run('systemctl', ['is-enabled', unit]).code === 0;
64
- if (loaded || fs.existsSync(unitPath)) {
65
- if (ctx.uid === 0) {
66
- systemd.stopUnit(runner, unit);
67
- systemd.disableUnit(runner, unit);
68
- rm(unitPath);
69
- systemd.daemonReload(runner);
70
- out.push(`已清 ssh-reverse unit:${unit}`);
71
- } else {
72
- out.push('ssh-reverse 残留需 root,请手动执行:');
73
- out.push(` systemctl disable --now ${unit} && sudo rm -f ${unitPath} && systemctl daemon-reload`);
74
- }
75
- } else {
76
- out.push('ssh-reverse:无残留');
77
- }
78
- }
79
-
80
- export function run(ctx) {
81
- const out = [];
82
- if (process.platform === 'darwin') cleanupDarwin(ctx, out);
83
- else cleanupLinux(ctx, out);
84
-
85
- // 11022 人工试验隧道(无自灭、不受管理);pkill 退出 1 = 无匹配
86
- const pk = ctx.runner.run('pkill', ['-f', 'ssh .*11022']);
87
- out.push(pk.code === 0 ? '已清 11022 试验隧道进程(如有)' : '11022:无进程');
88
-
89
- // ssh-net 0.1.x 遗留
90
- const legacyState = path.join(ctx.paths.home, '.local/state/ssh-net');
91
- if (fs.existsSync(legacyState)) { rm(legacyState); out.push(`已删旧状态目录: ${legacyState}`); }
92
- const legacyKh = path.join(ctx.paths.sshNetDir, 'known-hosts');
93
- if (fs.existsSync(legacyKh)) {
94
- rm(legacyKh);
95
- out.push('已删 ssh-net/known-hosts(0.2.0 起废弃,host key 走默认 known_hosts)');
96
- }
97
- return out.join('\n');
98
- }