ssh-net 0.1.1 → 0.2.1

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
@@ -2,6 +2,33 @@
2
2
 
3
3
  本项目版本号与发布节奏仿 mihomo-cli:npm 公共分发,版本即升级动作。
4
4
 
5
+ ## [0.2.1] - 2026-09-29
6
+
7
+ ### 变更
8
+
9
+ - 用户可见文案整体翻新(status / 命令返回 / 问题提示):status 按
10
+ 「隧道开关 → 当前线路 → 可用性」组织,内部术语(脚本 ok、注册口、
11
+ last exit 等)只在异常处出现,每条问题都附下一步动作;健康时更安静
12
+ (版本一致不再单列版本行)。命令返回改说结果(「安装完成,对外通道
13
+ 已开启」「隧道已开启(数秒内建立)」),不再暴露 launchd/PathState
14
+ 等机制词。
15
+
16
+ ## [0.2.0] - 2026-09-29
17
+
18
+ ### 变更(产物布局变化:升级后各机需重跑 `ssh-net install`)
19
+
20
+ - **运行时分发改实体拷贝**:install 把五个包脚本拷贝成
21
+ `~/.ssh/ssh-net/bin/` 下实体文件(0755;0.1.x 的 aliases/default 软链
22
+ 原位替换),运行时零 npm/fnm 依赖——npm 误卸载、fnm 切版本不再影响
23
+ 常驻服务。`runtime-version` 戳记录安装时包版本,status 对账,包升级后
24
+ 重跑 install 刷新(core 侧 uplink-edge 脚本由下次 checkin 自动刷新)
25
+ - **状态目录搬进 `~/.ssh/ssh-net/state/`**(原 `~/.local/state/ssh-net/`),
26
+ 配置/运行时/状态一棵树;旧目录由 cleanup 清
27
+ - **弃 `ssh-net/known-hosts` 信任本**:uplink-edge 回拨改默认 known_hosts +
28
+ `accept-new`(user key 认证兜底;edge host key 轮换零人工恢复)
29
+ - 新增 `ssh-net cleanup`(迁移期工具):清旧 ssh-socks / ssh-reverse 全部
30
+ 产物、11022 试验隧道与 0.1.x 遗留;system 域/root 项打印现成命令不自作主张
31
+
5
32
  ## [0.1.1] - 2026-09-29
6
33
 
7
34
  ### 新增
package/README.md CHANGED
@@ -24,11 +24,12 @@
24
24
  ## 设计原则
25
25
 
26
26
  - **常驻进程只有套着薄脚本的原生 ssh**:npm 包内每类一个 bash 脚本,install
27
- 按机器名建软链(差异只走参数),不做心跳、TTL、janitor、消息队列——在线
28
- 状态就是 TCP 会话本身
27
+ 按机器名拷贝进 `~/.ssh/ssh-net/bin`(差异只走参数),不做心跳、TTL、
28
+ janitor、消息队列——在线状态就是 TCP 会话本身
29
29
  - **控制面与运行时分离**:控制面是 Node 24+ 的 mjs(install/start/status/RPC);
30
- 运行时是纯 bash 脚本 + ssh,脚本内零 node;软链经 fnm `aliases/default`
31
- 稳定路径,fnm 升级 node 后重装包即自动跟随,包升级无需重跑 install
30
+ 运行时是纯 bash 脚本 + ssh 的**实体拷贝**,零 npm/fnm 依赖——npm 误卸载、
31
+ fnm 切版本不影响常驻服务;包升级 `npm i -g` 后重跑 install 刷新,
32
+ runtime-version 戳由 status 对账
32
33
  - **npm 包分发**:消费机 `npm i -g ssh-net`,不 clone;个人配置全部在 dotfiles
33
34
  托管(`~/.ssh/ssh-net/config` 与 ssh config),包内零个人数据
34
35
 
@@ -50,8 +51,8 @@ cd ~/space/ssh-net && npm link
50
51
  安装后按 [docs/migration.md](docs/migration.md) 的分阶段方案在各角色机器上执行
51
52
  `ssh-net install`。
52
53
 
53
- **卸载顺序**:先 `ssh-net uninstall`(移除 launchd/systemd 作业与软链),
54
- 再 `npm uninstall -g ssh-net`;反过来会留下悬空软链与反复重启的注册作业。
54
+ **卸载顺序**:先 `ssh-net uninstall`(移除 launchd/systemd 作业、运行时
55
+ 脚本与状态),再 `npm uninstall -g ssh-net`;反过来会留下反复重启的注册作业。
55
56
 
56
57
  ## 开发
57
58
 
@@ -60,7 +61,7 @@ cd ~/space/ssh-net && npm link
60
61
  ```bash
61
62
  node --test # 全部测试(纯模块 + shell 喂参 + 命令编排)
62
63
  npm pack --dry-run # 发布前核对产物(五脚本可执行位、files 清单)
63
- npm link # 开发机:全局 ssh-net 指向本仓,改脚本即时生效
64
+ npm link # 开发机:控制面改即时生效(运行时脚本仍靠 ssh-net install 拷贝落盘)
64
65
  ```
65
66
 
66
67
  发布物零真实拓扑数据:别名、主机名、环回注册端口只在私有文档与个人配置里,
@@ -77,7 +78,8 @@ npm link # 开发机:全局 ssh-net 指向本仓,改脚本即时
77
78
 
78
79
  ## 状态
79
80
 
80
- 0.1.0 已发布 npm(2026-09-29,GitHub Actions 自动发布)。部署:m4(core)与
81
- n007/n061(node)已切换至 ssh-net(2026-09-29,服务端三台齐、旧 ssh-reverse
82
- 三台清零,s100 上 12022/12031/12032 均为新链);edge 侧按 docs/migration.md
83
- Phase 4/5 待 mb5/mb1 到场(known-hosts 待填 edge 公钥)。
81
+ 0.2.0 已发布 npm(2026-09-29:运行时实体拷贝 + runtime-version 戳、状态并入
82
+ `~/.ssh/ssh-net/`、弃 known-hosts、新增迁移期 cleanup)。部署:m4/n007/
83
+ n061/mb5 四台已上线,新 Match 与 at 联动在办公室实测全通(peer 一跳登 m4、
84
+ SOCKS 1090、VNC、node relay);在家项(公网 v6 闸门/回落演练/合盖开盖)与
85
+ mb1(Phase 5)待办。
package/libexec/cli.mjs CHANGED
@@ -17,14 +17,16 @@ import { run as stopRun } from './commands/stop.mjs';
17
17
  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
+ import { run as cleanupRun } from './commands/cleanup.mjs';
20
21
 
21
22
  const COMMANDS = {
22
- install: { run: installRun, desc: '按本机角色安装(建软链 + 渲染 plist/unit)' },
23
- uninstall: { run: uninstallRun, desc: '停用并删除全部作业、软链与状态(再 npm uninstall -g)' },
23
+ install: { run: installRun, desc: '按本机角色安装(拷贝运行时脚本 + 渲染 plist/unit)' },
24
+ uninstall: { run: uninstallRun, desc: '停用并删除全部作业、运行时与状态(再 npm uninstall -g)' },
24
25
  start: { run: startRun, desc: 'edge 置 on / core 拉起 relay / node 启动' },
25
26
  stop: { run: stopRun, desc: 'edge 删 on 并停 link / core 停 relay / node 停服' },
26
27
  restart: { run: restartRun, desc: 'kickstart/restart 让循环重来' },
27
28
  status: { run: statusRun, desc: '本机角色状态(真实探测)' },
29
+ cleanup: { run: cleanupRun, desc: '清旧隧道编排(ssh-socks/ssh-reverse)与 0.1.x 遗留(迁移期工具)' },
28
30
  checkin: { run: checkinRun, desc: 'RPC(仅 core):edge 报名 <别名> <v6>', internal: true },
29
31
  };
30
32
 
@@ -38,7 +40,7 @@ function help() {
38
40
  .filter(([, c]) => !c.internal)
39
41
  .map(([name, c]) => ` ${name.padEnd(10)} ${c.desc}`),
40
42
  '',
41
- '配置: ~/.ssh/ssh-net/config(dotfiles 托管);状态: ~/.local/state/ssh-net/',
43
+ '配置: ~/.ssh/ssh-net/config(dotfiles 托管);运行时/状态: ~/.ssh/ssh-net/{bin,state}',
42
44
  ];
43
45
  return lines.join('\n');
44
46
  }
@@ -1,13 +1,14 @@
1
1
  // checkin RPC:edge 经 `ssh m4-via-relay 'ssh-net checkin <别名> <v6>'` 触发,
2
2
  // 仅 core 接受。四态显式处理(design §6.3,实测矩阵见 notes);四态之前先
3
- // 对账软链与 plist——install 不预建 uplink-edge,其软链与 job 参数(user 等)
4
- // 变更只有这条更新通道,缺了会永远用旧参数/旧目标拨号、六连败休眠循环。
5
- // launchctl 真返回成功才退出 0;失败非零,edge 下一轮自然重试。
3
+ // 对账运行时脚本与 plist——install 不预建 uplink-edge,其脚本与 job 参数
4
+ // (user 等)变更只有这条更新通道,缺了会永远用旧参数/旧目标拨号、六连败
5
+ // 休眠循环。launchctl 真返回成功才退出 0;失败非零,edge 下一轮自然重试。
6
6
  import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import { explainV6Error } from '../lib/ipv6.mjs';
9
9
  import * as launchd from '../lib/launchd.mjs';
10
- import { ensureBinLinks, syncPlist } from '../lib/manage.mjs';
10
+ import { syncPlist } from '../lib/manage.mjs';
11
+ import { ensureRuntime } from '../lib/runtime.mjs';
11
12
  import {
12
13
  edgeLabel, edgeLinkName, plistFileName, renderUplinkEdgePlist,
13
14
  } from '../lib/render.mjs';
@@ -44,9 +45,9 @@ export function run(ctx, args) {
44
45
  const prevV6 = ctx.state.readEdgeV6(alias);
45
46
  const st = launchd.inspect(ctx.runner, ctx.uid, label);
46
47
 
47
- // 软链对账无条件先行(幂等):软链被删/悬空/参数变更时,四个状态分支
48
+ // 脚本对账无条件先行(幂等):脚本被删/过期/参数变更时,四个状态分支
48
49
  // 里的任何一个都可能成为重建通道,不能只靠首次报名那一次
49
- ensureBinLinks(ctx, [[edgeLinkName(alias), 'ssh-net-uplink-edge']]);
50
+ ensureRuntime(ctx, [[edgeLinkName(alias), 'ssh-net-uplink-edge']]);
50
51
 
51
52
  // 未注册:首次报名,plist 后 enable + bootstrap
52
53
  if (!st.registered) {
@@ -0,0 +1,98 @@
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
+ }
@@ -1,13 +1,13 @@
1
- // install(design §5)。幂等:软链目标正确不重建、plist 字节相同不 bootout。
2
- // edge 只注册 PathState job(on 不在不启动);core 装完即启 uplink-relay、
3
- // 不预建 uplink-edge(首次 checkin 才生成);node 写 unit 并 enable --now。
1
+ // install(design §5)。幂等:运行时脚本内容相同不重写、plist 字节相同不
2
+ // bootout。edge 只注册 PathState job(on 不在不启动);core 装完即启
3
+ // uplink-relay、不预建 uplink-edge(首次 checkin 才生成);node 写 unit 并
4
+ // enable --now。
4
5
  import fs from 'node:fs';
5
6
  import path from 'node:path';
6
7
  import { buildForwardArgs } from '../lib/config.mjs';
7
8
  import { CALLBACK_PORT } from '../lib/constants.mjs';
8
- import {
9
- ensureBinLinks, syncPlist, writeFileAtomic,
10
- } from '../lib/manage.mjs';
9
+ import { syncPlist, writeFileAtomic } from '../lib/manage.mjs';
10
+ import { ensureRuntime } from '../lib/runtime.mjs';
11
11
  import * as launchd from '../lib/launchd.mjs';
12
12
  import * as systemd from '../lib/systemd.mjs';
13
13
  import {
@@ -47,7 +47,7 @@ function installEdge(ctx) {
47
47
  const { topo, paths } = ctx;
48
48
  // 预检纯读且在落任何产物之前:被拒时 bin/ 与软链一个都不建
49
49
  precheckEdgePorts(ctx);
50
- ensureBinLinks(ctx, [
50
+ ensureRuntime(ctx, [
51
51
  [linkLinkName(topo.core.alias), 'ssh-net-link-core'],
52
52
  ['peer-probe', 'peer-probe'],
53
53
  ['v6-address', 'v6-address'],
@@ -65,12 +65,14 @@ function installEdge(ctx) {
65
65
  plistPath: path.join(paths.launchAgentsDir, plistFileName(linkLabel(topo.core.alias))),
66
66
  content,
67
67
  });
68
- return `edge link 已${r.unchanged ? '就位(未改动)' : '注册'},on 不在不启动`;
68
+ return r.unchanged
69
+ ? '已安装,无需改动'
70
+ : '安装完成。隧道默认关闭——at home(或 ssh-net start)开启';
69
71
  }
70
72
 
71
73
  function installCore(ctx) {
72
74
  const { topo, paths } = ctx;
73
- ensureBinLinks(ctx, [
75
+ ensureRuntime(ctx, [
74
76
  [relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay'],
75
77
  ]);
76
78
  const label = relayLabel(topo.relay.alias);
@@ -85,14 +87,16 @@ function installCore(ctx) {
85
87
  plistPath: path.join(paths.launchAgentsDir, plistFileName(label)),
86
88
  content,
87
89
  });
88
- return `core uplink-relay ${r.unchanged ? '已在跑(未改动)' : '已启动'}`;
90
+ return r.unchanged
91
+ ? '已安装,无需改动'
92
+ : `安装完成,对外通道已开启(s100 入口 ${topo.core.relayPort})`;
89
93
  }
90
94
 
91
95
  function installNode(ctx) {
92
96
  const { topo, paths, runner } = ctx;
93
97
  if (ctx.uid !== 0)
94
98
  throw new Error('node 安装写 /etc/systemd/system 需要 root,请以 root 运行');
95
- ensureBinLinks(ctx, [
99
+ ensureRuntime(ctx, [
96
100
  [relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay'],
97
101
  ]);
98
102
  const unitName = relayUnitName(topo.relay.alias);
@@ -115,7 +119,7 @@ function installNode(ctx) {
115
119
  ]) {
116
120
  if (r.code !== 0) throw new Error(`systemctl 失败:${r.stderr.trim()}`);
117
121
  }
118
- return `node uplink-relay unit 已启用并启动:${unitName}`;
122
+ return `安装完成,对外通道已开启(s100 入口 ${ctx.self.relayPort})`;
119
123
  }
120
124
 
121
125
  /** @param {object} ctx */
@@ -10,21 +10,21 @@ export function run(ctx) {
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);
13
- if (r.code !== 0) throw new Error(`kickstart 失败:${r.stderr.trim()}`);
14
- return 'edge link 已 kickstart(循环重来)';
13
+ if (r.code !== 0) throw new Error(`重启失败:${r.stderr.trim()}`);
14
+ return '隧道已重启(重新选路中)';
15
15
  }
16
16
  if (ctx.role === 'core') {
17
17
  const label = relayLabel(ctx.topo.relay.alias);
18
18
  if (!launchd.inspect(ctx.runner, ctx.uid, label).registered)
19
19
  throw new Error('uplink-relay 未注册(已 stop?先 ssh-net start)');
20
20
  const r = launchd.kickstartEnabled(ctx.runner, ctx.uid, label);
21
- if (r.code !== 0) throw new Error(`kickstart 失败:${r.stderr.trim()}`);
22
- return 'core uplink-relay 已 kickstart';
21
+ if (r.code !== 0) throw new Error(`重启失败:${r.stderr.trim()}`);
22
+ return '对外通道已重启';
23
23
  }
24
24
  if (ctx.role === 'node') {
25
25
  const r = systemd.restartUnit(ctx.runner, relayUnitName(ctx.topo.relay.alias));
26
26
  if (r.code !== 0) throw new Error(`systemctl restart 失败:${r.stderr.trim()}`);
27
- return 'node uplink-relay 已 restart';
27
+ return '对外通道已重启';
28
28
  }
29
29
  throw new Error(`未知角色:${ctx.role}`);
30
30
  }
@@ -9,23 +9,23 @@ import { linkLabel, relayLabel, relayUnitName, plistFileName } from '../lib/rend
9
9
  function startCore(ctx) {
10
10
  const label = relayLabel(ctx.topo.relay.alias);
11
11
  const plist = path.join(ctx.paths.launchAgentsDir, plistFileName(label));
12
- if (!fs.existsSync(plist)) throw new Error(`缺少 ${plist},请先 ssh-net install`);
12
+ if (!fs.existsSync(plist)) throw new Error(`尚未安装(缺 ${plist}),先跑 ssh-net install`);
13
13
  const st = launchd.inspect(ctx.runner, ctx.uid, label);
14
14
  if (!st.registered) {
15
15
  launchd.enable(ctx.runner, ctx.uid, label);
16
16
  const r = launchd.bootstrap(ctx.runner, ctx.uid, plist);
17
- if (r.code !== 0) throw new Error(`bootstrap 失败:${r.stderr.trim()}`);
18
- return 'core uplink-relay 已拉起';
17
+ if (r.code !== 0) throw new Error(`启动失败:${r.stderr.trim()}`);
18
+ return '对外通道已开启';
19
19
  }
20
20
  if (!st.running) {
21
21
  // kickstartEnabled:kickstart 对 disabled job 被拒(stop 中途失败/手工
22
22
  // disable 的残留态),先幂等 enable
23
23
  const r = launchd.kickstartEnabled(ctx.runner, ctx.uid, label);
24
- if (r.code !== 0) throw new Error(`kickstart 失败:${r.stderr.trim()}`);
25
- return 'core uplink-relay 已 kickstart';
24
+ if (r.code !== 0) throw new Error(`启动失败:${r.stderr.trim()}`);
25
+ return '对外通道已重新拉起';
26
26
  }
27
27
  if (st.disabled) launchd.enable(ctx.runner, ctx.uid, label); // 在跑但 override 残留:清掉防退出后不重拉
28
- return 'core uplink-relay 已在运行';
28
+ return '对外通道已在运行';
29
29
  }
30
30
 
31
31
  export function run(ctx) {
@@ -34,13 +34,13 @@ export function run(ctx) {
34
34
  if (!launchd.inspect(ctx.runner, ctx.uid, label).registered)
35
35
  throw new Error(`link job 未注册(先 ssh-net install):launchctl print gui/${ctx.uid}/${label}`);
36
36
  ctx.state.setOn();
37
- return 'on 已置,link 由 launchd PathState 拉起';
37
+ return '隧道已开启(数秒内建立;ssh-net status 查看线路)';
38
38
  }
39
39
  if (ctx.role === 'core') return startCore(ctx);
40
40
  if (ctx.role === 'node') {
41
41
  const r = systemd.startUnit(ctx.runner, relayUnitName(ctx.topo.relay.alias));
42
42
  if (r.code !== 0) throw new Error(`systemctl start 失败:${r.stderr.trim()}`);
43
- return 'node uplink-relay 已启动';
43
+ return '对外通道已开启';
44
44
  }
45
45
  throw new Error(`未知角色:${ctx.role}`);
46
46
  }
@@ -1,10 +1,11 @@
1
1
  // status(design §6.7):只报本机角色,判据是 banner/端口/注册态真实探测。
2
- // collect 返回结构化对象(测试断言对象,不锁文本);renderText 给人看。
3
- // 退出码:健康(含 edge off)0;有可行动问题(悬空链/该听没听/软链缺失)1。
4
- // on 在但 probe 不通不算问题:可能只是回拨尚未建立(relay 同期可用)。
2
+ // collect 返回结构化对象(测试断言对象,不锁文本);renderText 给人看——
3
+ // 2026-09-29 起按用户视角组织:先答「隧道开没开、现在走哪条路、东西能不能用」,
4
+ // 内部名词(脚本/注册口/last exit)只在异常时出现,且每条问题都带下一步动作。
5
+ // 退出码:健康(含 edge 关闭态)0;有可行动问题 1。
5
6
  import path from 'node:path';
6
- import { auditLink } from '../lib/links.mjs';
7
- import { packageScriptTarget } from '../lib/paths.mjs';
7
+ import { auditScript, readRuntimeVersion, runtimeVersionIssue } from '../lib/runtime.mjs';
8
+ import { packageScriptPath } from '../lib/paths.mjs';
8
9
  import * as launchd from '../lib/launchd.mjs';
9
10
  import * as systemd from '../lib/systemd.mjs';
10
11
  import { peerProbeOk, tcpOpen } from '../lib/probe.mjs';
@@ -14,13 +15,23 @@ import {
14
15
  } from '../lib/render.mjs';
15
16
 
16
17
  function auditRequired(ctx, entries) {
17
- return entries.map(([name, script]) => {
18
- const expected = packageScriptTarget(script, ctx.env);
19
- return {
20
- link: name,
21
- audit: auditLink(path.join(ctx.paths.binDir, name), expected),
22
- };
23
- });
18
+ return entries.map(([name, script]) => ({
19
+ link: name,
20
+ audit: auditScript(path.join(ctx.paths.binDir, name), packageScriptPath(script)),
21
+ }));
22
+ }
23
+
24
+ /** 版本对账问题(各角色共用);版本值不单列展示,不一致才说话。 */
25
+ function versionInfo(ctx) {
26
+ const issue = runtimeVersionIssue(ctx.paths);
27
+ return { issue, runtimeVersion: readRuntimeVersion(ctx.paths) };
28
+ }
29
+
30
+ /** forward 的人话标签:dynamic 是 SOCKS,local 写出目标。 */
31
+ function forwardLabel(f) {
32
+ return f.kind === 'dynamic'
33
+ ? `SOCKS 代理 127.0.0.1:${f.listenPort}`
34
+ : `端口转发 127.0.0.1:${f.listenPort} → ${f.targetAlias}:${f.targetPort}`;
24
35
  }
25
36
 
26
37
  function relayPortListening(ctx, port) {
@@ -30,25 +41,27 @@ function relayPortListening(ctx, port) {
30
41
  '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5',
31
42
  ctx.topo.relay.alias, 'ss', '-tlnH',
32
43
  ], { timeout: 8000 });
33
- if (r.code !== 0) return { reachable: false, listening: false, detail: r.stderr.trim() };
34
- return { reachable: true, listening: new RegExp(`127\\.0\\.0\\.1[:.]${port}\\b`).test(r.stdout) };
44
+ if (r.code !== 0) return { port, reachable: false, listening: false, detail: r.stderr.trim() };
45
+ return { port, reachable: true, listening: new RegExp(`127\\.0\\.0\\.1[:.]${port}\\b`).test(r.stdout) };
35
46
  }
36
47
 
37
48
  async function collectEdge(ctx) {
38
49
  const { topo, paths, state } = ctx;
39
50
  const issues = [];
51
+ const { issue: vIssue, runtimeVersion } = versionInfo(ctx);
52
+ if (vIssue) issues.push(vIssue);
40
53
  const links = auditRequired(ctx, [
41
54
  [linkLinkName(topo.core.alias), 'ssh-net-link-core'],
42
55
  ['peer-probe', 'peer-probe'],
43
56
  ['v6-address', 'v6-address'],
44
57
  ]);
45
- if (links.some((l) => l.audit === 'dangling' || l.audit === 'foreign'))
46
- issues.push('运行时链异常(悬空或指向不符):npm i -g ssh-net 后恢复,或重新 install');
58
+ if (links.some((l) => l.audit === 'stale'))
59
+ issues.push('隧道组件与所装版本不一致——跑一次 ssh-net install 刷新');
47
60
  if (links.every((l) => l.audit === 'missing'))
48
- issues.push('运行时未安装(ssh-net install)');
61
+ issues.push('尚未安装(先跑 ssh-net install)');
49
62
  else if (links.some((l) => l.audit === 'missing'))
50
- // 部分缺失:peer-probe 丢了会让 on 态恒判 relay,不能只显示不报
51
- issues.push('部分运行时软链缺失:重新 ssh-net install 恢复');
63
+ // 部分缺失:peer-probe 丢了会让开着的隧道恒判中继,不能只显示不报
64
+ issues.push(`隧道组件不完整(缺 ${links.filter((l) => l.audit === 'missing').map((l) => l.link).join('、')})——跑一次 ssh-net install 修复`);
52
65
 
53
66
  const label = linkLabel(topo.core.alias);
54
67
  const job = launchd.inspect(ctx.runner, ctx.uid, label);
@@ -60,33 +73,40 @@ async function collectEdge(ctx) {
60
73
  if (on) {
61
74
  peer = peerProbeOk(ctx.runner, paths.binDir);
62
75
  route = peer ? 'peer' : 'relay';
63
- // on 但 probe 不通可能只是回拨尚未建立;不当作问题(relay 同期可用)
76
+ // 开着但 probe 不通可能只是回拨尚未建立;不当作问题(中继同期可用)
64
77
  }
65
78
  const openTcp = ctx.openTcp ?? tcpOpen; // 测试可注入,避免连真端口
66
79
  for (const f of topo.forwards) ports[f.listenPort] = await openTcp('127.0.0.1', f.listenPort);
67
80
 
68
- // off 时转发口仍在听=孤儿进程
81
+ // 关着但转发口仍在听 = 孤儿进程
69
82
  if (!on)
70
- for (const [p, listening] of Object.entries(ports))
71
- if (listening) issues.push(`on 不在但端口 ${p} 仍在监听(孤儿转发进程?)`);
83
+ for (const f of topo.forwards)
84
+ if (ports[f.listenPort])
85
+ issues.push(`隧道已关但 ${forwardLabel(f)} 仍被占用——疑似残留进程:lsof -nP -iTCP:${f.listenPort} -sTCP:LISTEN 查占用者`);
72
86
 
73
87
  let v6 = '';
74
88
  if (links.find((l) => l.link === 'v6-address')?.audit === 'ok')
75
89
  v6 = ctx.runner.runRaw(path.join(paths.binDir, 'v6-address'), [], { timeout: 5000 }).stdout.trim();
76
90
 
77
- return { role: 'edge', alias: ctx.self.alias, on, route, peer, job, links, ports, v6, issues };
91
+ const forwardViews = topo.forwards.map((f) => [forwardLabel(f), ports[f.listenPort]]);
92
+ return {
93
+ role: 'edge', alias: ctx.self.alias, on, route, peer, job, links, ports,
94
+ forwardViews, coreAlias: topo.core.alias, v6, runtimeVersion, issues,
95
+ };
78
96
  }
79
97
 
80
98
  async function collectCore(ctx) {
81
99
  const { topo, paths } = ctx;
82
100
  const issues = [];
101
+ const { issue: vIssue, runtimeVersion } = versionInfo(ctx);
102
+ if (vIssue) issues.push(vIssue);
83
103
  const links = auditRequired(ctx, [
84
104
  [relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay'],
85
105
  ]);
86
- if (links.some((l) => l.audit === 'dangling' || l.audit === 'foreign'))
87
- issues.push('uplink-relay 软链悬空或指向不符:npm i -g ssh-net 后恢复');
106
+ if (links.some((l) => l.audit === 'stale'))
107
+ issues.push('常驻隧道组件与所装版本不一致——跑一次 ssh-net install 刷新');
88
108
  if (links.every((l) => l.audit === 'missing'))
89
- issues.push('运行时未安装(ssh-net install)');
109
+ issues.push('尚未安装(先跑 ssh-net install)');
90
110
 
91
111
  const relayLabelName = relayLabel(topo.relay.alias);
92
112
  const relayJob = launchd.inspect(ctx.runner, ctx.uid, relayLabelName);
@@ -96,15 +116,15 @@ async function collectCore(ctx) {
96
116
  for (const e of topo.edges) {
97
117
  const label = edgeLabel(e.alias);
98
118
  const st = launchd.inspect(ctx.runner, ctx.uid, label);
99
- // 已注册(= 报过名、checkin 建过链)的 edge 链一并体检:与 relay 链
100
- // 同一故障面(fnm 切版本悬空、手工误删),悬空只看 last exit 不显眼
119
+ // 已连接过的随身机,回拨组件一并体检:包升级后它只有 checkin/install
120
+ // 两条刷新通道,漏刷会拿旧脚本拨号
101
121
  if (st.registered) {
102
- const a = auditLink(
122
+ const a = auditScript(
103
123
  path.join(paths.binDir, edgeLinkName(e.alias)),
104
- packageScriptTarget('ssh-net-uplink-edge', ctx.env),
124
+ packageScriptPath('ssh-net-uplink-edge'),
105
125
  );
106
126
  if (a !== 'ok')
107
- issues.push(`edge ${e.alias} 运行时软链异常(${a}):npm i -g ssh-net 后恢复,或等下次 checkin 对账`);
127
+ issues.push(`${e.alias} 的回拨组件异常(${a})——重跑 ssh-net install,或等它下次报名自动修复`);
108
128
  }
109
129
  edges.push({
110
130
  alias: e.alias,
@@ -116,30 +136,41 @@ async function collectCore(ctx) {
116
136
  });
117
137
  }
118
138
 
119
- if (!relayJob.running) issues.push('uplink-relay 未在运行');
120
- if (!relayPort.listening) issues.push(`s100 环回口 ${topo.core.relayPort} 未在监听`);
139
+ if (!relayJob.running) issues.push('常驻隧道未在运行——ssh-net start 可拉起');
140
+ if (!relayPort.listening)
141
+ issues.push(`s100 入口 ${topo.core.relayPort} 没在监听:在外面暂时进不来(断线会自动重连;持续出现请查 s100 或本机网络)`);
121
142
 
122
- return { role: 'core', alias: ctx.self.alias, links, relayJob, relayPort, edges, issues };
143
+ return {
144
+ role: 'core', alias: ctx.self.alias, links, runtimeVersion,
145
+ relayAlias: topo.relay.alias, relayJob, relayPort, edges, issues,
146
+ };
123
147
  }
124
148
 
125
149
  function collectNode(ctx) {
126
150
  const { topo } = ctx;
127
151
  const issues = [];
152
+ const { issue: vIssue, runtimeVersion } = versionInfo(ctx);
153
+ if (vIssue) issues.push(vIssue);
128
154
  const links = auditRequired(ctx, [
129
155
  [relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay'],
130
156
  ]);
131
- if (links.some((l) => l.audit === 'dangling' || l.audit === 'foreign'))
132
- issues.push('uplink-relay 软链悬空或指向不符:npm i -g ssh-net 后恢复');
157
+ if (links.some((l) => l.audit === 'stale'))
158
+ issues.push('常驻隧道组件与所装版本不一致——跑一次 ssh-net install 刷新');
133
159
  if (links.every((l) => l.audit === 'missing'))
134
- issues.push('运行时未安装(ssh-net install)');
160
+ issues.push('尚未安装(先跑 ssh-net install)');
135
161
 
136
162
  const unit = relayUnitName(topo.relay.alias);
137
163
  const active = systemd.isActive(ctx.runner, unit);
138
164
  const relayPort = relayPortListening(ctx, ctx.self.relayPort);
139
- if (active !== 'active') issues.push(`unit ${unit} 非 active(${active})`);
140
- if (!relayPort.listening) issues.push(`s100 环回口 ${ctx.self.relayPort} 未在监听`);
141
-
142
- return { role: 'node', alias: ctx.self.alias, links, unit, active, relayPort, issues };
165
+ if (active !== 'active')
166
+ issues.push(`系统服务 ${unit} 状态 ${active}——systemctl status ${unit} 查看`);
167
+ if (!relayPort.listening)
168
+ issues.push(`s100 入口 ${ctx.self.relayPort} 没在监听:在外面暂时进不来(断线会自动重连;持续出现请查 s100 或本机网络)`);
169
+
170
+ return {
171
+ role: 'node', alias: ctx.self.alias, links, runtimeVersion,
172
+ relayAlias: topo.relay.alias, unit, active, relayPort, issues,
173
+ };
143
174
  }
144
175
 
145
176
  export async function collect(ctx) {
@@ -149,33 +180,48 @@ export async function collect(ctx) {
149
180
  throw new Error(`未知角色:${ctx.role}`);
150
181
  }
151
182
 
183
+ /** 上次退出码非 0 才值得看;0 与从未退出都不显示。 */
184
+ const exitNote = (code) => (code && code !== '0' ? `(上次退出 ${code})` : '');
185
+
152
186
  export function renderText(s) {
153
187
  const lines = [];
154
188
  lines.push(`ssh-net ${s.role} ${s.alias}`);
155
- for (const l of s.links)
156
- lines.push(` 链 ${l.link}: ${l.audit}`);
157
189
 
158
190
  if (s.role === 'edge') {
159
- lines.push(` on: ${s.on ? '在' : '不在(LAN 直连)'}`);
160
- if (s.on) lines.push(` 路径: ${s.route}(peer-probe ${s.peer ? '见 banner' : '未见 banner'})`);
161
- if (s.v6 !== '') lines.push(` v6: ${s.v6}`);
162
- lines.push(` link job: ${s.job.registered ? (s.job.running ? 'running' : 'not running') : '未注册'}`);
163
- for (const [p, ok] of Object.entries(s.ports))
164
- lines.push(` 端口 ${p}: ${ok ? '在听' : '未听'}`);
191
+ if (!s.on) {
192
+ lines.push(' 隧道开关: 关(在办公室,局域网直连即可)');
193
+ } else {
194
+ lines.push(' 隧道开关: 开');
195
+ lines.push(s.peer
196
+ ? ` 当前线路: 直连(一条 ssh 到 ${s.coreAlias},最快)`
197
+ : ' 当前线路: 中继(经 s100 转发;直连暂不可用,恢复后自动切回)');
198
+ lines.push(s.v6 !== '' ? ` 对外地址: ${s.v6}` : ' 对外地址: 无 v6(只能走中继)');
199
+ }
200
+ lines.push(` 后台任务: ${!s.job.registered ? '未安装' : s.job.running ? '运行中' : '已停止'}`);
201
+ for (const [label, ok] of s.forwardViews)
202
+ lines.push(` ${ok ? '✓' : '✗'} ${label}${ok ? '' : '(未就绪)'}`);
165
203
  } else if (s.role === 'core') {
166
- lines.push(` uplink-relay: ${s.relayJob.running ? 'running' : 'not running'}(last exit ${s.relayJob.lastExitCode})`);
167
- lines.push(` s100 注册口: ${s.relayPort.listening ? '在听' : `未听${s.relayPort.reachable === false ? '(s100 不可达)' : ''}`}`);
204
+ lines.push(s.relayPort.listening
205
+ ? ` 对外通道: ✓ 开着(在外面经 ${s.relayAlias} 进入 ${s.alias} · 入口 ${s.relayPort.port})`
206
+ : ` 对外通道: ✗ ${s.relayPort.reachable === false ? '连不上 s100,入口状态未知' : `入口 ${s.relayPort.port} 没在监听`}`);
207
+ lines.push(` 常驻隧道: ${s.relayJob.running ? `运行中${exitNote(s.relayJob.lastExitCode)}` : '未运行'}`);
208
+ lines.push(' 随身机:');
168
209
  for (const e of s.edges) {
169
- const state = !e.registered ? '未注册' : e.disabled ? 'disabled(休眠,等 checkin 唤醒)' : e.running ? 'running' : 'enabled/未运行';
170
- lines.push(` edge ${e.alias}: ${state}${e.v6 ? ` v6=${e.v6}` : ''}${e.registered ? ` last=${e.lastExitCode}` : ''}`);
210
+ const state = !e.registered ? '从未连接(到场装机后自动出现)'
211
+ : e.disabled ? '休眠中(它下次开机报名时自动唤醒)'
212
+ : e.running ? `已连接(直连 ${e.v6 ?? '?'})${exitNote(e.lastExitCode)}`
213
+ : '已断开(自动重试中)';
214
+ lines.push(` ${e.alias} ${state}`);
171
215
  }
172
216
  } else {
173
- lines.push(` unit ${s.unit}: ${s.active}`);
174
- lines.push(` s100 注册口: ${s.relayPort.listening ? '在听' : '未听'}`);
217
+ lines.push(s.relayPort.listening
218
+ ? ` 对外通道: ✓ 开着(在外面经 ${s.relayAlias} 进入 ${s.alias} · 入口 ${s.relayPort.port})`
219
+ : ` 对外通道: ✗ 入口 ${s.relayPort.port} 没在监听`);
220
+ lines.push(` 常驻隧道: ${s.active === 'active' ? '运行中(systemd)' : `${s.active}(systemd)`}`);
175
221
  }
176
222
 
177
223
  if (s.issues.length) {
178
- lines.push('问题:');
224
+ lines.push('需要处理:');
179
225
  for (const i of s.issues) lines.push(` - ${i}`);
180
226
  }
181
227
  return lines.join('\n');
@@ -13,7 +13,7 @@ function stopCore(ctx) {
13
13
  // 113 = 未注册(竞态下消失);其余失败必须报,否则 stop 谎报成功、隧道还活着
14
14
  if (bo.code !== 0 && bo.code !== 113)
15
15
  throw new Error(`bootout 失败(job 仍在注册表):${bo.stderr.trim()}`);
16
- return 'core uplink-relay 已 disable 并 bootout(uplink-edge 不受影响)';
16
+ return '对外通道已关闭(随身机的直连不受影响)';
17
17
  }
18
18
 
19
19
  export function run(ctx) {
@@ -23,7 +23,7 @@ export function run(ctx) {
23
23
  throw new Error(
24
24
  `${label} 仍在运行(TERM 已发两次)。手工排查:launchctl print gui/${ctx.uid}/${label}`,
25
25
  );
26
- return 'on 已删,link 已退出(core 侧回拨 job 将自行休眠)';
26
+ return '隧道已关闭。几分钟后办公室侧会停止回拨并静默(正常现象,下次开启自动恢复)';
27
27
  }
28
28
  if (ctx.role === 'core') return stopCore(ctx);
29
29
  if (ctx.role === 'node') {
@@ -31,7 +31,7 @@ export function run(ctx) {
31
31
  systemd.stopUnit(ctx.runner, unit);
32
32
  const d = systemd.disableUnit(ctx.runner, unit);
33
33
  if (d.code !== 0) throw new Error(`systemctl disable 失败:${d.stderr.trim()}`);
34
- return `node ${unit} 已停止并 disable`;
34
+ return '对外通道已关闭(重启后保持关闭)';
35
35
  }
36
36
  throw new Error(`未知角色:${ctx.role}`);
37
37
  }
@@ -1,6 +1,6 @@
1
1
  // uninstall(design §5):先 bootout 全部 job(TERM trap 转发,不留孤儿 ssh),
2
- // 再删 plist/软链/状态/日志。不发 RPC、不手动 disable(override root 持有,
3
- // 重装时 install 的 enable-first 兜底)。
2
+ // 再删 plist/运行时脚本/状态/日志。不发 RPC、不手动 disable(override root
3
+ // 持有,重装时 install 的 enable-first 兜底)。
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { removeJob } from '../lib/manage.mjs';
@@ -30,8 +30,9 @@ function uninstallEdge(ctx) {
30
30
  ));
31
31
  rm(ctx.paths.binDir);
32
32
  rm(ctx.paths.stateDir);
33
+ rm(ctx.paths.runtimeVersionFile);
33
34
  rm(path.join(ctx.paths.logsDir, `${label}.log`));
34
- return 'edge 作业、软链与状态已清除';
35
+ return '已卸载。最后一步:npm uninstall -g ssh-net';
35
36
  }
36
37
 
37
38
  function uninstallCore(ctx) {
@@ -53,9 +54,10 @@ function uninstallCore(ctx) {
53
54
 
54
55
  rm(ctx.paths.binDir);
55
56
  rm(ctx.paths.stateDir);
57
+ rm(ctx.paths.runtimeVersionFile);
56
58
  for (const label of [...edgeJobs.keys(), relay])
57
59
  rm(path.join(ctx.paths.logsDir, `${label}.log`));
58
- return `core 作业已清除(relay + ${edgeJobs.size} 个 uplink-edge)`;
60
+ return `已卸载(常驻通道与 ${edgeJobs.size} 台随身机的回拨作业)。最后一步:npm uninstall -g ssh-net`;
59
61
  }
60
62
 
61
63
  function uninstallNode(ctx) {
@@ -72,7 +74,8 @@ function uninstallNode(ctx) {
72
74
  systemd.daemonReload(ctx.runner);
73
75
  rm(ctx.paths.binDir);
74
76
  rm(ctx.paths.stateDir);
75
- return `node unit ${unit} 已停用并删除(journald 日志保留)`;
77
+ rm(ctx.paths.runtimeVersionFile);
78
+ return '已卸载。最后一步:npm uninstall -g ssh-net';
76
79
  }
77
80
 
78
81
  export function run(ctx) {
@@ -1,27 +1,10 @@
1
- // install 与 checkin 共享的落地原语:bin 软链幂等、plist 原子落盘 +
2
- // launchctl 注册态同步。核心承诺(design §5):渲染结果与现文件字节相同则
3
- // 不 bootout——install 幂等不断连。
1
+ // install 与 checkin 共享的落地原语:plist 原子落盘 + launchctl 注册态同步
2
+ // (bin 运行时脚本的拷贝对账在 runtime.mjs)。核心承诺(design §5):
3
+ // 渲染结果与现文件字节相同则不 bootout——install 幂等不断连。
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
- import { ensureLink } from './links.mjs';
7
- import { packageScriptTarget } from './paths.mjs';
8
6
  import * as launchd from './launchd.mjs';
9
7
 
10
- /**
11
- * 幂等对账 bin/ 软链(带机器名 → 包脚本)。
12
- * @param {object} ctx
13
- * @param {readonly (readonly [string, string])[]} entries [软链名, 包脚本名]
14
- * @returns {('created'|'unchanged'|'replaced')[]}
15
- */
16
- export function ensureBinLinks(ctx, entries) {
17
- fs.mkdirSync(ctx.paths.binDir, { recursive: true });
18
- return entries.map(([linkName, scriptName]) =>
19
- ensureLink(
20
- path.join(ctx.paths.binDir, linkName),
21
- packageScriptTarget(scriptName, ctx.env),
22
- ));
23
- }
24
-
25
8
  /** 同目录 tmp + rename 原子落盘。 */
26
9
  export function writeFileAtomic(file, content, mode = 0o644) {
27
10
  const tmp = `${file}.tmp-${process.pid}`;
@@ -1,71 +1,42 @@
1
- // 路径与软链目标规范化。纯函数 + 少量环境派生常量;需要注入的场景(测试)
2
- // 一律走参数,不读模块级可变状态。
1
+ // 路径常量。纯函数 + 少量环境派生;需要注入的场景(测试)一律走参数,
2
+ // 不读模块级可变状态。
3
3
  //
4
- // 软链规则(design §2.3,唯一真相):cli/lib 经 import.meta.url(Node 默认
5
- // realpath 符号链)落在 fnm 的具体版本目录
6
- // `$FNM_DIR/node-versions/<ver>/installation/lib/node_modules/ssh-net/...`,
7
- // 建链前把该前缀替换为稳定的 `$FNM_DIR/aliases/default/`;npm link 开发态
8
- // realpath 在 ~/space/ssh-net,不匹配前缀,原样指仓实体。
4
+ // 运行时分发(design §2.3,2026-09-29 定):install 把包脚本**拷贝**进
5
+ // ~/.ssh/ssh-net/bin/(不再软链 fnm alias)——运行时零 npm/fnm 依赖;
6
+ // 状态与产物同住 ~/.ssh/ssh-net/ 一棵树(state/ 子目录)。
9
7
  import path from 'node:path';
10
8
  import fs from 'node:fs';
11
9
  import { fileURLToPath } from 'node:url';
12
10
 
13
- /**
14
- * fnm 根目录。
15
- * @param {NodeJS.ProcessEnv} [env]
16
- * @returns {string}
17
- */
18
- export function fnmDir(env = process.env) {
19
- return env.FNM_DIR && env.FNM_DIR.length > 0
20
- ? env.FNM_DIR
21
- : path.join(env.HOME ?? '', '.local', 'share', 'fnm');
22
- }
23
-
24
- /**
25
- * 把包内实体的真实路径规范化为 fnm aliases/default 形态;非 fnm 版本目录
26
- * (npm link 开发态等)原样返回。
27
- * @param {string} realPath 经 realpath 解析后的绝对路径
28
- * @param {NodeJS.ProcessEnv} [env]
29
- * @returns {string}
30
- */
31
- export function normalizeScriptTarget(realPath, env = process.env) {
32
- const versionsRoot = path.join(fnmDir(env), 'node-versions');
33
- if (!realPath.startsWith(versionsRoot + path.sep)) return realPath;
34
- const rel = path.relative(versionsRoot, realPath).split(path.sep);
35
- // rel = [<ver>, 'installation', 'lib', 'node_modules', ...]
36
- if (rel.length < 3 || rel[1] !== 'installation') return realPath;
37
- return path.join(fnmDir(env), 'aliases', 'default', ...rel.slice(2));
38
- }
39
-
40
11
  /** 包内 libexec 实体所在的真实目录(本文件经 realpath 后位于 libexec/lib)。 */
41
12
  const LIB_REAL = fs.realpathSync(fileURLToPath(import.meta.url));
42
13
  const LIBEXEC_REAL = path.dirname(path.dirname(LIB_REAL));
43
14
 
44
15
  /**
45
- * 包脚本经 fnm alias 规范化后的目标路径(install/checkin 软链指向它)。
16
+ * 包内脚本的实体路径(install/checkin 拷贝源)。
46
17
  * @param {string} scriptName libexec 下脚本名,如 ssh-net-link-core
47
- * @param {NodeJS.ProcessEnv} [env]
48
18
  * @returns {string}
49
19
  */
50
- export function packageScriptTarget(scriptName, env = process.env) {
51
- return normalizeScriptTarget(path.join(LIBEXEC_REAL, scriptName), env);
20
+ export function packageScriptPath(scriptName) {
21
+ return path.join(LIBEXEC_REAL, scriptName);
52
22
  }
53
23
 
54
24
  /**
55
- * 本机全部产物与配置路径。config/known-hosts 在 dotfiles,state/bin 是本工具产物。
25
+ * 本机全部产物与配置路径。config 在 dotfiles;bin/state/runtime-version 是
26
+ * 本工具产物,全部收在 ~/.ssh/ssh-net/ 一棵树。
56
27
  * @param {NodeJS.ProcessEnv} [env]
57
28
  */
58
29
  export function machinePaths(env = process.env) {
59
30
  const home = env.HOME ?? '';
60
31
  const sshNetDir = path.join(home, '.ssh', 'ssh-net');
61
- const stateDir = path.join(home, '.local', 'state', 'ssh-net');
32
+ const stateDir = path.join(sshNetDir, 'state');
62
33
  return Object.freeze({
63
34
  home,
64
35
  sshDir: path.join(home, '.ssh'),
65
36
  sshNetDir,
66
37
  configFile: path.join(sshNetDir, 'config'),
67
- knownHostsFile: path.join(sshNetDir, 'known-hosts'),
68
38
  binDir: path.join(sshNetDir, 'bin'),
39
+ runtimeVersionFile: path.join(sshNetDir, 'runtime-version'),
69
40
  stateDir,
70
41
  onFile: path.join(stateDir, 'on'),
71
42
  edgesDir: path.join(stateDir, 'edges'),
@@ -0,0 +1,121 @@
1
+ // 运行时脚本的拷贝对账(install/checkin/status 三方共享,design §2.3)。
2
+ // 2026-09-29 定:bin/ 放包脚本的**实体拷贝**(0755),不再软链 fnm alias——
3
+ // 运行时零 npm/fnm 依赖,npm 误卸载/切版本不影响常驻服务;代价是包升级后
4
+ // 要重跑 install 刷新(core 侧 checkin 每次报名自动对账刷新 uplink-edge),
5
+ // runtime-version 戳记录安装时的包版本,status 见版本差不一致即报。
6
+ // 幂等:内容相同不重写(只补可执行位);0.1.x 遗留的软链原位替换成实体。
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { packageScriptPath } from './paths.mjs';
10
+ import pkg from '../../package.json' with { type: 'json' };
11
+
12
+ export const RUNTIME_VERSION = pkg.version;
13
+
14
+ /**
15
+ * 拷贝单脚本到 bin/。
16
+ * @param {string} dstPath
17
+ * @param {string} srcPath 包内脚本实体
18
+ * @returns {'created'|'updated'|'unchanged'|'repaired'}
19
+ */
20
+ export function ensureScript(dstPath, srcPath) {
21
+ const src = fs.readFileSync(srcPath);
22
+ // 先判软链(lstat 不跟随):0.1.x 遗留软链即使内容巧合相同也必须替换成
23
+ // 实体——readFileSync 会跟随目标骗过内容比对
24
+ let isLink = false;
25
+ try {
26
+ isLink = fs.lstatSync(dstPath).isSymbolicLink();
27
+ } catch { /* 不存在 */ }
28
+ let cur = null;
29
+ if (!isLink) {
30
+ try {
31
+ cur = fs.readFileSync(dstPath);
32
+ } catch (err) {
33
+ if (!err || err.code !== 'ENOENT') throw err;
34
+ }
35
+ }
36
+ if (cur !== null && cur.equals(src)) {
37
+ // 内容对但可执行位丢了(cp/同步工具吃掉 mode):补上
38
+ if (fs.statSync(dstPath).mode & 0o111) return 'unchanged';
39
+ fs.chmodSync(dstPath, 0o755);
40
+ return 'repaired';
41
+ }
42
+ // 缺失 / 旧内容 / 0.1.x 软链:unlink 后落实体
43
+ try {
44
+ fs.unlinkSync(dstPath);
45
+ } catch (err) {
46
+ if (!err || err.code !== 'ENOENT') throw err;
47
+ }
48
+ const tmp = `${dstPath}.tmp-${process.pid}`;
49
+ fs.writeFileSync(tmp, src, { mode: 0o755 });
50
+ fs.renameSync(tmp, dstPath);
51
+ fs.chmodSync(dstPath, 0o755);
52
+ return isLink || cur !== null ? 'updated' : 'created';
53
+ }
54
+
55
+ /**
56
+ * 幂等对账 bin/ 运行时脚本(带机器名 → 包脚本)并刷新版本戳。
57
+ * @param {object} ctx
58
+ * @param {readonly (readonly [string, string])[]} entries [脚本名, 包脚本名]
59
+ * @returns {('created'|'updated'|'unchanged'|'repaired')[]}
60
+ */
61
+ export function ensureRuntime(ctx, entries) {
62
+ fs.mkdirSync(ctx.paths.binDir, { recursive: true });
63
+ const r = entries.map(([name, scriptName]) =>
64
+ ensureScript(path.join(ctx.paths.binDir, name), packageScriptPath(scriptName)));
65
+ const stamp = `${RUNTIME_VERSION}\n`;
66
+ const stampPath = ctx.paths.runtimeVersionFile;
67
+ let cur = null;
68
+ try {
69
+ cur = fs.readFileSync(stampPath, 'utf8');
70
+ } catch { cur = null; }
71
+ if (cur !== stamp) {
72
+ const tmp = `${stampPath}.tmp-${process.pid}`;
73
+ fs.writeFileSync(tmp, stamp, { mode: 0o644 });
74
+ fs.renameSync(tmp, stampPath);
75
+ }
76
+ return r;
77
+ }
78
+
79
+ /**
80
+ * 运行时脚本体检(status 用)。
81
+ * @param {string} dstPath
82
+ * @param {string} srcPath
83
+ * @returns {'ok'|'missing'|'stale'}
84
+ */
85
+ export function auditScript(dstPath, srcPath) {
86
+ let cur;
87
+ try {
88
+ cur = fs.readFileSync(dstPath);
89
+ } catch (err) {
90
+ if (!err || err.code !== 'ENOENT') throw err;
91
+ return 'missing';
92
+ }
93
+ return cur.equals(fs.readFileSync(srcPath)) ? 'ok' : 'stale';
94
+ }
95
+
96
+ /**
97
+ * 读运行时版本戳;缺失/为空返回 null。
98
+ * @param {{runtimeVersionFile:string}} paths
99
+ * @returns {string | null}
100
+ */
101
+ export function readRuntimeVersion(paths) {
102
+ try {
103
+ const v = fs.readFileSync(paths.runtimeVersionFile, 'utf8').trim();
104
+ return v.length > 0 ? v : null;
105
+ } catch {
106
+ return null;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * 包版本与运行时戳的对账结果;一致返回 null,否则给 status 的问题文案。
112
+ * @param {{runtimeVersionFile:string}} paths
113
+ * @returns {string | null}
114
+ */
115
+ export function runtimeVersionIssue(paths) {
116
+ const v = readRuntimeVersion(paths);
117
+ if (v === null) return '隧道组件缺版本信息——跑一次 ssh-net install 修复';
118
+ if (v !== RUNTIME_VERSION)
119
+ return `程序已升级到 ${RUNTIME_VERSION},隧道组件还是 ${v}——跑一次 ssh-net install 同步`;
120
+ return null;
121
+ }
@@ -7,7 +7,7 @@ set -u
7
7
  LC_ALL=C
8
8
  export LC_ALL
9
9
  SSH=${SSH:-/usr/bin/ssh}
10
- STATE_DIR=${SSH_NET_STATE_DIR:-$HOME/.local/state/ssh-net}
10
+ STATE_DIR=${SSH_NET_STATE_DIR:-$HOME/.ssh/ssh-net/state}
11
11
  BIN_DIR=${SSH_NET_BIN_DIR:-$HOME/.ssh/ssh-net/bin}
12
12
  RELAY_TTL=${SSH_NET_RELAY_TTL:-600} # relay 态寿命,到期回循环重估
13
13
  PEER_WINDOW=${SSH_NET_PEER_WINDOW:-8} # 回拨建立窗口(秒)
@@ -9,7 +9,7 @@ export LC_ALL
9
9
  SSH=${SSH:-/usr/bin/ssh}
10
10
  LAUNCHCTL=${LAUNCHCTL:-/bin/launchctl}
11
11
  ID=${ID:-/usr/bin/id}
12
- STATE_DIR=${SSH_NET_STATE_DIR:-$HOME/.local/state/ssh-net}
12
+ STATE_DIR=${SSH_NET_STATE_DIR:-$HOME/.ssh/ssh-net/state}
13
13
  CLEAR_TTL=${SSH_NET_CLEAR_TTL:-30} # 持续存活满 30s 清零失败计数
14
14
  FAIL_LIMIT=${SSH_NET_FAIL_LIMIT:-6}
15
15
  RETRY_SLEEP=${SSH_NET_RETRY_SLEEP:-30}
@@ -64,15 +64,15 @@ while :; do
64
64
  exit 0
65
65
  fi
66
66
 
67
+ # host key 走默认 known_hosts + accept-new(2026-09-29 弃专用信任本;
68
+ # 对面不是本尊时 user key 认证处即失败,行为与 pinning 失败一致)
67
69
  "$SSH" -N -R "10022:127.0.0.1:22" \
68
70
  -i "$HOME/.ssh/id_ed25519" \
69
71
  -o ExitOnForwardFailure=yes -o BatchMode=yes -o IdentitiesOnly=yes \
70
72
  -o ControlMaster=no -o ControlPath=none \
71
73
  -o ServerAliveInterval=35 -o ServerAliveCountMax=3 \
72
74
  -o ConnectTimeout=15 \
73
- -o StrictHostKeyChecking=yes \
74
- -o UserKnownHostsFile="$HOME/.ssh/ssh-net/known-hosts" \
75
- -o HostKeyAlias="$alias_name" \
75
+ -o StrictHostKeyChecking=accept-new \
76
76
  "$user@$v6" &
77
77
  ssh_pid=$!
78
78
  start_clear_timer
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ssh-net",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "type": "module",
5
5
  "description": "个人 SSH 组网:v6 直连优先、relay 兜底、关机有界重试后静默",
6
6
  "bin": {
@@ -1,61 +0,0 @@
1
- // bin/ 软链的对账(install/checkin/status 三方共享,design §2.3)。
2
- // install 幂等:目标正确不重建;checkin 首次报名建 uplink-edge 链;
3
- // status 逐条体检。目标是实体文件(非软链)时不擅自删,抛错让人处理。
4
- import fs from 'node:fs';
5
-
6
- /** 软链路径上已有非软链实体时抛此错。 */
7
- export class LinkOccupiedError extends Error {
8
- /** @param {string} linkPath */
9
- constructor(linkPath) {
10
- super(`软链位置被实体文件占用(不自动删除):${linkPath}`);
11
- this.name = 'LinkOccupiedError';
12
- this.linkPath = linkPath;
13
- }
14
- }
15
-
16
- /**
17
- * 幂等建链。
18
- * @param {string} linkPath
19
- * @param {string} target 期望目标(绝对路径)
20
- * @returns {'created'|'unchanged'|'replaced'}
21
- */
22
- export function ensureLink(linkPath, target) {
23
- let existing;
24
- try {
25
- existing = fs.lstatSync(linkPath);
26
- } catch (err) {
27
- if (!err || err.code !== 'ENOENT') throw err;
28
- fs.symlinkSync(target, linkPath);
29
- return 'created';
30
- }
31
- if (!existing.isSymbolicLink()) throw new LinkOccupiedError(linkPath);
32
- if (fs.readlinkSync(linkPath) === target) return 'unchanged';
33
- fs.unlinkSync(linkPath);
34
- fs.symlinkSync(target, linkPath);
35
- return 'replaced';
36
- }
37
-
38
- /**
39
- * 软链体检(status 用)。
40
- * @param {string} linkPath
41
- * @param {string} expectedTarget
42
- * @returns {'ok'|'missing'|'dangling'|'foreign'}
43
- */
44
- export function auditLink(linkPath, expectedTarget) {
45
- let st;
46
- try {
47
- st = fs.lstatSync(linkPath);
48
- } catch (err) {
49
- if (!err || err.code !== 'ENOENT') throw err;
50
- return 'missing';
51
- }
52
- if (!st.isSymbolicLink()) return 'foreign';
53
- if (fs.readlinkSync(linkPath) !== expectedTarget) return 'foreign';
54
- try {
55
- fs.statSync(linkPath); // 跟随符号链,失败=悬空
56
- } catch (err) {
57
- if (!err || err.code !== 'ENOENT') throw err;
58
- return 'dangling';
59
- }
60
- return 'ok';
61
- }