ssh-net 0.1.0 → 0.2.0

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,32 @@
2
2
 
3
3
  本项目版本号与发布节奏仿 mihomo-cli:npm 公共分发,版本即升级动作。
4
4
 
5
+ ## [0.2.0] - 2026-09-29
6
+
7
+ ### 变更(产物布局变化:升级后各机需重跑 `ssh-net install`)
8
+
9
+ - **运行时分发改实体拷贝**:install 把五个包脚本拷贝成
10
+ `~/.ssh/ssh-net/bin/` 下实体文件(0755;0.1.x 的 aliases/default 软链
11
+ 原位替换),运行时零 npm/fnm 依赖——npm 误卸载、fnm 切版本不再影响
12
+ 常驻服务。`runtime-version` 戳记录安装时包版本,status 对账,包升级后
13
+ 重跑 install 刷新(core 侧 uplink-edge 脚本由下次 checkin 自动刷新)
14
+ - **状态目录搬进 `~/.ssh/ssh-net/state/`**(原 `~/.local/state/ssh-net/`),
15
+ 配置/运行时/状态一棵树;旧目录由 cleanup 清
16
+ - **弃 `ssh-net/known-hosts` 信任本**:uplink-edge 回拨改默认 known_hosts +
17
+ `accept-new`(user key 认证兜底;edge host key 轮换零人工恢复)
18
+ - 新增 `ssh-net cleanup`(迁移期工具):清旧 ssh-socks / ssh-reverse 全部
19
+ 产物、11022 试验隧道与 0.1.x 遗留;system 域/root 项打印现成命令不自作主张
20
+
21
+ ## [0.1.1] - 2026-09-29
22
+
23
+ ### 新增
24
+
25
+ - `v6-address` 新增 `SSH_NET_V6_ALLOW_ULA=1`:额外接受 fc00::/7 ULA,用于
26
+ 办公室内网彩排 peer 路径与纯内网部署;默认仍只选 2000::/3 公网单播。
27
+ - checkin 的 v6 校验放宽为「可拨号段」(2000::/3 公网单播或 fc00::/7 ULA):
28
+ 选取的严格性在 edge 侧 v6-address,core 只校验可拨性;link-local、组播、
29
+ 内嵌 v4、带 scope id 照拒。
30
+
5
31
  ## [0.1.0] - 2026-09-29
6
32
 
7
33
  首个可发布版本(迁移 Phase 1 软件交付,未做各机部署)。
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,5 +78,7 @@ npm link # 开发机:全局 ssh-net 指向本仓,改脚本即时
77
78
 
78
79
  ## 状态
79
80
 
80
- 0.1.0 软件就绪、测试全绿(2026-09-29);尚未 publish,各机部署按
81
- docs/migration.md 的 Phase 2 起执行(Phase 0 现场项仍待真机闸门)。
81
+ 0.2.0 已发布 npm(2026-09-29:运行时改实体拷贝 + runtime-version 戳、
82
+ 状态并入 `~/.ssh/ssh-net/`、弃 known-hosts 信任本、新增迁移期 `cleanup`)。
83
+ 部署:m4/n007/n061 上线,mb5 已装并彩排 peer 全链路通过(办公室 ULA);
84
+ Phase 4/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'],
@@ -70,7 +70,7 @@ function installEdge(ctx) {
70
70
 
71
71
  function installCore(ctx) {
72
72
  const { topo, paths } = ctx;
73
- ensureBinLinks(ctx, [
73
+ ensureRuntime(ctx, [
74
74
  [relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay'],
75
75
  ]);
76
76
  const label = relayLabel(topo.relay.alias);
@@ -92,7 +92,7 @@ function installNode(ctx) {
92
92
  const { topo, paths, runner } = ctx;
93
93
  if (ctx.uid !== 0)
94
94
  throw new Error('node 安装写 /etc/systemd/system 需要 root,请以 root 运行');
95
- ensureBinLinks(ctx, [
95
+ ensureRuntime(ctx, [
96
96
  [relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay'],
97
97
  ]);
98
98
  const unitName = relayUnitName(topo.relay.alias);
@@ -1,10 +1,10 @@
1
1
  // status(design §6.7):只报本机角色,判据是 banner/端口/注册态真实探测。
2
2
  // collect 返回结构化对象(测试断言对象,不锁文本);renderText 给人看。
3
- // 退出码:健康(含 edge off)0;有可行动问题(悬空链/该听没听/软链缺失)1。
3
+ // 退出码:健康(含 edge off)0;有可行动问题(脚本过期/版本不齐/该听没听)1。
4
4
  // on 在但 probe 不通不算问题:可能只是回拨尚未建立(relay 同期可用)。
5
5
  import path from 'node:path';
6
- import { auditLink } from '../lib/links.mjs';
7
- import { packageScriptTarget } from '../lib/paths.mjs';
6
+ import { auditScript, readRuntimeVersion, runtimeVersionIssue } from '../lib/runtime.mjs';
7
+ import { packageScriptPath } from '../lib/paths.mjs';
8
8
  import * as launchd from '../lib/launchd.mjs';
9
9
  import * as systemd from '../lib/systemd.mjs';
10
10
  import { peerProbeOk, tcpOpen } from '../lib/probe.mjs';
@@ -14,13 +14,16 @@ import {
14
14
  } from '../lib/render.mjs';
15
15
 
16
16
  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
- });
17
+ return entries.map(([name, script]) => ({
18
+ link: name,
19
+ audit: auditScript(path.join(ctx.paths.binDir, name), packageScriptPath(script)),
20
+ }));
21
+ }
22
+
23
+ /** 版本对账问题(各角色共用);runtimeVersion 一并带回给展示层。 */
24
+ function versionInfo(ctx) {
25
+ const issue = runtimeVersionIssue(ctx.paths);
26
+ return { issue, runtimeVersion: readRuntimeVersion(ctx.paths) };
24
27
  }
25
28
 
26
29
  function relayPortListening(ctx, port) {
@@ -37,18 +40,20 @@ function relayPortListening(ctx, port) {
37
40
  async function collectEdge(ctx) {
38
41
  const { topo, paths, state } = ctx;
39
42
  const issues = [];
43
+ const { issue: vIssue, runtimeVersion } = versionInfo(ctx);
44
+ if (vIssue) issues.push(vIssue);
40
45
  const links = auditRequired(ctx, [
41
46
  [linkLinkName(topo.core.alias), 'ssh-net-link-core'],
42
47
  ['peer-probe', 'peer-probe'],
43
48
  ['v6-address', 'v6-address'],
44
49
  ]);
45
- if (links.some((l) => l.audit === 'dangling' || l.audit === 'foreign'))
46
- issues.push('运行时链异常(悬空或指向不符):npm i -g ssh-net 后恢复,或重新 install');
50
+ if (links.some((l) => l.audit === 'stale'))
51
+ issues.push('运行时脚本与包内不一致(npm i -g 后未重跑 install?):重跑 ssh-net install 刷新');
47
52
  if (links.every((l) => l.audit === 'missing'))
48
53
  issues.push('运行时未安装(ssh-net install)');
49
54
  else if (links.some((l) => l.audit === 'missing'))
50
55
  // 部分缺失:peer-probe 丢了会让 on 态恒判 relay,不能只显示不报
51
- issues.push('部分运行时软链缺失:重新 ssh-net install 恢复');
56
+ issues.push('部分运行时脚本缺失:重新 ssh-net install 恢复');
52
57
 
53
58
  const label = linkLabel(topo.core.alias);
54
59
  const job = launchd.inspect(ctx.runner, ctx.uid, label);
@@ -74,17 +79,19 @@ async function collectEdge(ctx) {
74
79
  if (links.find((l) => l.link === 'v6-address')?.audit === 'ok')
75
80
  v6 = ctx.runner.runRaw(path.join(paths.binDir, 'v6-address'), [], { timeout: 5000 }).stdout.trim();
76
81
 
77
- return { role: 'edge', alias: ctx.self.alias, on, route, peer, job, links, ports, v6, issues };
82
+ return { role: 'edge', alias: ctx.self.alias, on, route, peer, job, links, ports, v6, runtimeVersion, issues };
78
83
  }
79
84
 
80
85
  async function collectCore(ctx) {
81
86
  const { topo, paths } = ctx;
82
87
  const issues = [];
88
+ const { issue: vIssue, runtimeVersion } = versionInfo(ctx);
89
+ if (vIssue) issues.push(vIssue);
83
90
  const links = auditRequired(ctx, [
84
91
  [relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay'],
85
92
  ]);
86
- if (links.some((l) => l.audit === 'dangling' || l.audit === 'foreign'))
87
- issues.push('uplink-relay 软链悬空或指向不符:npm i -g ssh-net 后恢复');
93
+ if (links.some((l) => l.audit === 'stale'))
94
+ issues.push('uplink-relay 脚本与包内不一致:重跑 ssh-net install 刷新');
88
95
  if (links.every((l) => l.audit === 'missing'))
89
96
  issues.push('运行时未安装(ssh-net install)');
90
97
 
@@ -96,15 +103,15 @@ async function collectCore(ctx) {
96
103
  for (const e of topo.edges) {
97
104
  const label = edgeLabel(e.alias);
98
105
  const st = launchd.inspect(ctx.runner, ctx.uid, label);
99
- // 已注册(= 报过名、checkin 建过链)的 edge 链一并体检:与 relay 链
100
- // 同一故障面(fnm 切版本悬空、手工误删),悬空只看 last exit 不显眼
106
+ // 已注册(= 报过名、checkin 建过链)的 edge 脚本一并体检:包升级后
107
+ // uplink-edge 只有 checkin/install 两条刷新通道,漏刷会拿旧脚本拨号
101
108
  if (st.registered) {
102
- const a = auditLink(
109
+ const a = auditScript(
103
110
  path.join(paths.binDir, edgeLinkName(e.alias)),
104
- packageScriptTarget('ssh-net-uplink-edge', ctx.env),
111
+ packageScriptPath('ssh-net-uplink-edge'),
105
112
  );
106
113
  if (a !== 'ok')
107
- issues.push(`edge ${e.alias} 运行时软链异常(${a}):npm i -g ssh-net 后恢复,或等下次 checkin 对账`);
114
+ issues.push(`edge ${e.alias} 运行时脚本异常(${a}):重跑 ssh-net install,或等下次 checkin 对账`);
108
115
  }
109
116
  edges.push({
110
117
  alias: e.alias,
@@ -119,17 +126,19 @@ async function collectCore(ctx) {
119
126
  if (!relayJob.running) issues.push('uplink-relay 未在运行');
120
127
  if (!relayPort.listening) issues.push(`s100 环回口 ${topo.core.relayPort} 未在监听`);
121
128
 
122
- return { role: 'core', alias: ctx.self.alias, links, relayJob, relayPort, edges, issues };
129
+ return { role: 'core', alias: ctx.self.alias, links, runtimeVersion, relayJob, relayPort, edges, issues };
123
130
  }
124
131
 
125
132
  function collectNode(ctx) {
126
133
  const { topo } = ctx;
127
134
  const issues = [];
135
+ const { issue: vIssue, runtimeVersion } = versionInfo(ctx);
136
+ if (vIssue) issues.push(vIssue);
128
137
  const links = auditRequired(ctx, [
129
138
  [relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay'],
130
139
  ]);
131
- if (links.some((l) => l.audit === 'dangling' || l.audit === 'foreign'))
132
- issues.push('uplink-relay 软链悬空或指向不符:npm i -g ssh-net 后恢复');
140
+ if (links.some((l) => l.audit === 'stale'))
141
+ issues.push('uplink-relay 脚本与包内不一致:重跑 ssh-net install 刷新');
133
142
  if (links.every((l) => l.audit === 'missing'))
134
143
  issues.push('运行时未安装(ssh-net install)');
135
144
 
@@ -139,7 +148,7 @@ function collectNode(ctx) {
139
148
  if (active !== 'active') issues.push(`unit ${unit} 非 active(${active})`);
140
149
  if (!relayPort.listening) issues.push(`s100 环回口 ${ctx.self.relayPort} 未在监听`);
141
150
 
142
- return { role: 'node', alias: ctx.self.alias, links, unit, active, relayPort, issues };
151
+ return { role: 'node', alias: ctx.self.alias, links, runtimeVersion, unit, active, relayPort, issues };
143
152
  }
144
153
 
145
154
  export async function collect(ctx) {
@@ -152,8 +161,9 @@ export async function collect(ctx) {
152
161
  export function renderText(s) {
153
162
  const lines = [];
154
163
  lines.push(`ssh-net ${s.role} ${s.alias}`);
164
+ lines.push(` 运行时: ${s.runtimeVersion ?? '无版本戳'}`);
155
165
  for (const l of s.links)
156
- lines.push(` 链 ${l.link}: ${l.audit}`);
166
+ lines.push(` 脚本 ${l.link}: ${l.audit}`);
157
167
 
158
168
  if (s.role === 'edge') {
159
169
  lines.push(` on: ${s.on ? '在' : '不在(LAN 直连)'}`);
@@ -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 'edge 作业、运行时与状态已清除';
35
36
  }
36
37
 
37
38
  function uninstallCore(ctx) {
@@ -53,6 +54,7 @@ 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
60
  return `core 作业已清除(relay + ${edgeJobs.size} 个 uplink-edge)`;
@@ -72,6 +74,7 @@ function uninstallNode(ctx) {
72
74
  systemd.daemonReload(ctx.runner);
73
75
  rm(ctx.paths.binDir);
74
76
  rm(ctx.paths.stateDir);
77
+ rm(ctx.paths.runtimeVersionFile);
75
78
  return `node unit ${unit} 已停用并删除(journald 日志保留)`;
76
79
  }
77
80
 
@@ -1,24 +1,47 @@
1
- // checkin v6 入参的严格校验。唯一外部输入面(design §6.3):
2
- // 合法 IPv6 字面值 + 落在 2000::/3 全局单播段;拒绝 scope id、内嵌 v4
3
- // (含 ::ffff: v4-mapped)、ULA、link-local、unspecified、保留段等一切非 2000::/3。
4
- // 依赖 net.isIP 做字面值合法性,首 hextet 判段——2000::/3 即首组 0x2000–0x3fff,
5
- // 其余该拒的段(fc/fd、fe80、ff、::1、::)本就不在此区间,无需逐段分类。
1
+ // checkin v6 入参校验(design §6.3)。唯一外部输入面:合法 IPv6 字面值 +
2
+ // 可拨号段——2000::/3 公网单播,或 fc00::/7 ULA(2026-09-29 起收 ULA:
3
+ // 办公室内网彩排 peer 路径 / 纯内网部署场景。「报不报 ULA」的严格性在
4
+ // edge 侧 v6-address 的选取,checkin 只管「这个地址能不能拨」)。
5
+ // 仍拒绝 scope id、内嵌 v4(含 ::ffff: v4-mapped)、link-local、unspecified、
6
+ // 组播等。依赖 net.isIP 做字面值合法性,首 hextet 判段。
6
7
  import net from 'node:net';
7
8
 
8
9
  /**
10
+ * 取首 hextet 数值;不是「无 scope、非内嵌 v4 的合法 IPv6 字面值」返回 null。
9
11
  * @param {unknown} value
10
- * @returns {boolean}
12
+ * @returns {number | null}
11
13
  */
12
- export function isGlobalUnicastV6(value) {
13
- if (typeof value !== 'string') return false;
14
- if (value.length === 0 || value.includes('%')) return false; // 无 scope id
15
- if (net.isIP(value) !== 6) return false;
14
+ function firstHextetOf(value) {
15
+ if (typeof value !== 'string') return null;
16
+ if (value.length === 0 || value.includes('%')) return null; // 无 scope id
17
+ if (net.isIP(value) !== 6) return null;
16
18
  // 任何内嵌 v4 形态(末段含点,如 ::ffff:192.0.2.1)一律拒
17
19
  const tail = value.slice(value.lastIndexOf(':') + 1);
18
- if (tail.includes('.')) return false;
20
+ if (tail.includes('.')) return null;
19
21
  const firstGroup = value.split(':')[0];
20
22
  const g0 = firstGroup === '' ? 0 : Number.parseInt(firstGroup, 16);
21
- return Number.isInteger(g0) && g0 >= 0x2000 && g0 <= 0x3fff;
23
+ return Number.isInteger(g0) ? g0 : null;
24
+ }
25
+
26
+ /**
27
+ * 2000::/3 全局单播(首组 0x2000–0x3fff)。
28
+ * @param {unknown} value
29
+ * @returns {boolean}
30
+ */
31
+ export function isGlobalUnicastV6(value) {
32
+ const g0 = firstHextetOf(value);
33
+ return g0 !== null && g0 >= 0x2000 && g0 <= 0x3fff;
34
+ }
35
+
36
+ /**
37
+ * 可拨号段:2000::/3 公网单播或 fc00::/7 ULA(首组 0xfc00–0xfdff)。
38
+ * @param {unknown} value
39
+ * @returns {boolean}
40
+ */
41
+ export function isDialableV6(value) {
42
+ const g0 = firstHextetOf(value);
43
+ return g0 !== null
44
+ && ((g0 >= 0x2000 && g0 <= 0x3fff) || (g0 >= 0xfc00 && g0 <= 0xfdff));
22
45
  }
23
46
 
24
47
  /**
@@ -32,8 +55,8 @@ export function explainV6Error(value) {
32
55
  if (net.isIP(value) !== 6) return '不是合法 IPv6 字面值';
33
56
  if (value.slice(value.lastIndexOf(':') + 1).includes('.'))
34
57
  return '拒绝内嵌 v4(含 ::ffff: v4-mapped)';
35
- // 2000::/3 判定单一来源是 isGlobalUnicastV6,别在这抄第二份
36
- if (!isGlobalUnicastV6(value))
37
- return '不是 2000::/3 全局单播地址(拒绝 ULA/link-local/保留段)';
58
+ // 可拨号判定单一来源是 isDialableV6,别在这抄第二份
59
+ if (!isDialableV6(value))
60
+ return '不是可拨号 v6(收 2000::/3 公网单播与 fc00::/7 ULA,拒 link-local/组播/保留段)';
38
61
  return null;
39
62
  }
@@ -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 'runtime-version 戳缺失(重跑 ssh-net install)';
118
+ if (v !== RUNTIME_VERSION)
119
+ return `运行时 ${v} ≠ 包 ${RUNTIME_VERSION}:重跑 ssh-net install 刷新 bin/ 脚本`;
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
@@ -2,6 +2,8 @@
2
2
  # v6-address:选取本机可注册的公网 v6——默认路由网卡上 2000::/3 全局单播、
3
3
  # autoconf secured、非 deprecated/temporary 的第一个地址(design §6.4)。
4
4
  # 无输出 = 没有可注册 v6(v4-only/咖啡厅场景),退出码恒 0。
5
+ # SSH_NET_V6_ALLOW_ULA=1 额外收 fc00::/7 ULA(办公室内网彩排 peer 路径 /
6
+ # 纯内网部署;默认公网行为不变)。
5
7
  # 除 route/ifconfig 不引外部命令;ROUTE/IFCONFIG/SSH_NET_DEFAULT_IF 仅测试注入。
6
8
  set -u
7
9
  LC_ALL=C
@@ -9,16 +11,21 @@ export LC_ALL
9
11
  ROUTE=${ROUTE:-/sbin/route}
10
12
  IFCONFIG=${IFCONFIG:-/sbin/ifconfig}
11
13
 
12
- # 首 hextet ∈ [0x2000,0x3fff] 即 2000::/3。合法地址首段直接取首个冒号前,
14
+ # 首 hextet 判段:默认 [0x2000,0x3fff](2000::/3);SSH_NET_V6_ALLOW_ULA=1
15
+ # 时额外收 [0xfc00,0xfdff](fc00::/7 ULA)。合法地址首段直接取首个冒号前,
13
16
  # 不需展开 ::;拒内嵌点(v4/v4-mapped)与非十六进制。
14
- in_global_unicast() {
17
+ in_allowed_range() {
15
18
  local a=$1 g v
16
19
  case "$a" in *.*) return 1 ;; esac
17
20
  g=${a%%:*}
18
21
  [ -n "$g" ] || return 1
19
22
  case "$g" in *[!0-9a-fA-F]*) return 1 ;; esac
20
23
  v=$((16#$g))
21
- [ "$v" -ge $((16#2000)) ] && [ "$v" -le $((16#3fff)) ]
24
+ if [ "$v" -ge $((16#2000)) ] && [ "$v" -le $((16#3fff)) ]; then return 0; fi
25
+ if [ "${SSH_NET_V6_ALLOW_ULA:-}" = 1 ]; then
26
+ [ "$v" -ge $((16#fc00)) ] && [ "$v" -le $((16#fdff)) ] && return 0
27
+ fi
28
+ return 1
22
29
  }
23
30
 
24
31
  # 默认路由网卡(route 输出 "interface: en0"),纯内建解析
@@ -50,7 +57,7 @@ while IFS= read -r line; do
50
57
  case "$line" in *autoconf*secured*) ;; *) continue ;; esac
51
58
  case "$line" in *deprecated*|*temporary*) continue ;; esac
52
59
  addr=${2%%%*} # 去可能的 scope
53
- if in_global_unicast "$addr"; then
60
+ if in_allowed_range "$addr"; then
54
61
  printf '%s\n' "$addr"
55
62
  exit 0
56
63
  fi
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ssh-net",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
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
- }