ssh-net 26.10.60 → 26.10.61

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,27 @@
4
4
  跨月从 1 开始;历史跳号不补、不另维护累计发包数。发布 = 改版本号 +
5
5
  CHANGELOG + 发 GitHub Release,Actions 跑测试后 npm publish。
6
6
 
7
+ ## [26.10.61] - 2026-10-25
8
+
9
+ ### 修复
10
+
11
+ - status 不再把 link 任务未运行、launchctl 查询失败或 core relay 的 disabled
12
+ override 当作健康;停止 link 时保留 launchctl kill 的真实错误
13
+ - 端口预检在 lsof/launchctl 结果未知时中止;install 不再忽略 conf.d 读取
14
+ 失败,并修复既有 Include 片段与 state 目录权限
15
+ - node 卸载在 daemon-reload 失败后重跑仍会补做重载;plist 与原子写失败时
16
+ 清理临时文件
17
+ - ssh config 解析支持 OpenSSH 等号分隔语法;Match exec 统一处理 shell 与
18
+ ssh_config 引用,HOME 含空白时选路与地址门控仍可用
19
+ - CLI 等待 stdout/stderr 刷新后退出,避免慢管道下输出截断
20
+
21
+ ### 简化与效率
22
+
23
+ - 收敛目录读取、临时文件、systemd 重载与测试子进程回收的重复实现;测试
24
+ 复用现有 fixture、路径与调用记录 helper
25
+ - sn-route 的 lsof 正常结束立即继续,只由独立 watchdog 负责超时,不再白等
26
+ 连接恢复的轮询周期
27
+
7
28
  ## [26.10.60] - 2026-10-25
8
29
 
9
30
  ### 修复
package/libexec/cli.mjs CHANGED
@@ -130,8 +130,8 @@ async function main() {
130
130
  }
131
131
 
132
132
  main()
133
- .then((code) => process.exit(code))
133
+ .then((code) => { process.exitCode = code; })
134
134
  .catch((err) => {
135
135
  process.stderr.write(`ssh-net: ${err.message}\n`);
136
- process.exit(1);
136
+ process.exitCode = 1;
137
137
  });
@@ -16,7 +16,7 @@ import * as systemd from '../lib/systemd.mjs';
16
16
  import {
17
17
  classifyLocalPort, lsofListen, v6LoopbackPids, peerProbeOk,
18
18
  } from '../lib/probe.mjs';
19
- import { writeFileAtomic } from '../lib/fsutil.mjs';
19
+ import { readDirOrEmpty, writeFileAtomic } from '../lib/fsutil.mjs';
20
20
  import { packageScriptPath } from '../lib/paths.mjs';
21
21
  import {
22
22
  SN_PROBE, RESIDENT_SCRIPTS, edgeRuntimePlan, coreNodeRuntimePlan,
@@ -66,7 +66,7 @@ async function precheckEdgePorts(ctx, linkOn) {
66
66
  const forwardPorts = topo.forwards.map((f) => f.listenPort);
67
67
  if (linkOn && forwardPorts.length > 0) {
68
68
  // 只要 pid 判持口者归属(link-core 是 exec ssh,job pid 即持口者)
69
- const jobPid = launchd.printState(runner, uid, linkLabel(topo.core.alias)).pid;
69
+ const jobPid = launchd.printState(runner, uid, linkLabel(topo.core.alias), true).pid;
70
70
  for (const port of forwardPorts) {
71
71
  const c = classifyLocalPort(runner, port, jobPid);
72
72
  if (c.kind === 'foreign') {
@@ -206,8 +206,7 @@ function syncEdgeEntries(ctx) {
206
206
  keep.add(path.basename(file));
207
207
  if (syncConfFile(file, renderEdgeHost(e))) changed = true;
208
208
  }
209
- let existing = [];
210
- try { existing = fs.readdirSync(paths.confDir); } catch { /* 目录不在即无旧片段 */ }
209
+ const existing = readDirOrEmpty(paths.confDir);
211
210
  // 片段名公式唯一来源是 edgeHostFile(含 '' 即前缀),不抄 'edge-' 字面量
212
211
  const edgePrefix = path.basename(paths.edgeHostFile(''));
213
212
  for (const f of existing) {
@@ -153,9 +153,11 @@ async function collectEdge(ctx, probe) {
153
153
  // link 未装时 job 无消费者(渲染走「未安装」分支)——默认零常驻形态不为它
154
154
  // 白跑一次 launchctl print
155
155
  const job = linkInstalled
156
- ? launchd.printState(ctx.runner, ctx.uid, linkDeployment.label)
156
+ ? launchd.printState(ctx.runner, ctx.uid, linkDeployment.label, true)
157
157
  : null;
158
158
  const switches = state.readSwitches();
159
+ if (linkInstalled && switches.relay && !job.running)
160
+ issues.push('本地转发任务未在运行——先 stop 再按原开关 start,或跑 ssh-net install 修复');
159
161
 
160
162
  // v6 只是诊断线索不是判决,与就绪实测并发。探测没跑成时不能谎称「没有
161
163
  // IPv6」——那个结论只在 sn-ipv6 正常跑完且无输出时才成立
@@ -223,34 +225,35 @@ async function collectCore(ctx, probe) {
223
225
  ? auditScript(paths.binScript(UPLINK_EDGE), packageScriptPath(UPLINK_EDGE))
224
226
  : null;
225
227
 
226
- // 按别名关联入口(entry 自带 alias):位置对位会把对齐不变式藏在另一个
227
- // 函数的迭代顺序里
228
- const entryByAlias = new Map(edgeEntries(ctx, issues).map((en) => [en.alias, en]));
228
+ const entries = edgeEntries(ctx, issues);
229
229
  const edges = [];
230
- for (const e of topo.edges) {
231
- const st = launchd.inspectWith(ctx.runner, ctx.uid, edgeLabel(e.alias), dmap);
230
+ for (const entry of entries) {
231
+ const { alias } = entry;
232
+ const st = launchd.inspectWith(ctx.runner, ctx.uid, edgeLabel(alias), dmap);
232
233
  // 已连接过的 edge 体检回拨脚本/软链:漏刷会拿旧脚本拨号
233
234
  if (st.registered) {
234
- const [linkName, entityName] = edgeCallbacksPlan([e.alias]).links[0];
235
+ const [linkName, entityName] = edgeCallbacksPlan([alias]).links[0];
235
236
  const bad = [];
236
237
  if (callbackEntityAudit !== 'ok')
237
238
  bad.push(`连接脚本${callbackEntityAudit === 'missing' ? '缺失' : '过期'}`);
238
239
  if (!auditLink(paths.binScript(linkName), entityName)) bad.push('服务软链异常');
239
240
  if (bad.length)
240
- issues.push(`${e.alias} 的自动连接脚本异常(${bad.join('、')})——它下次连过来时会自动刷新(或跑一次 ssh-net install 手动修复)`);
241
+ issues.push(`${alias} 的自动连接脚本异常(${bad.join('、')})——它下次连过来时会自动刷新(或跑一次 ssh-net install 手动修复)`);
241
242
  }
242
243
  edges.push({
243
- alias: e.alias,
244
+ alias,
244
245
  registered: st.registered,
245
246
  disabled: st.disabled,
246
247
  running: st.running,
247
248
  lastExitCode: st.lastExitCode,
248
- entry: entryByAlias.get(e.alias),
249
+ entry,
249
250
  });
250
251
  }
251
252
 
252
253
  const relayPort = await relayPortP;
253
254
  if (!relayJob.running) issues.push('relay 未在运行——ssh-net start 可拉起');
255
+ if (relayJob.registered && relayJob.disabled)
256
+ issues.push('relay 已禁用,后续加载可能被拦截——ssh-net start 可重新启用');
254
257
  if (relayPort && !relayPort.listening)
255
258
  issues.push(relayPortIssue(topo.relay.alias, topo.core.relayPort, relayPort));
256
259
 
@@ -9,6 +9,7 @@ import * as systemd from '../lib/systemd.mjs';
9
9
  import {
10
10
  linkLabel, relayLabel, relayLinkName, edgeLabel,
11
11
  } from '../lib/render.mjs';
12
+ import { readDirOrEmpty } from '../lib/fsutil.mjs';
12
13
 
13
14
  const rm = (p) => fs.rmSync(p, { recursive: true, force: true });
14
15
 
@@ -21,11 +22,7 @@ function removeArtifacts(ctx) {
21
22
  }
22
23
 
23
24
  function removeSshNetLogs(ctx) {
24
- let files = [];
25
- try { files = fs.readdirSync(ctx.paths.logsDir); } catch (err) {
26
- if (err.code !== 'ENOENT') throw err;
27
- }
28
- for (const file of files) {
25
+ for (const file of readDirOrEmpty(ctx.paths.logsDir)) {
29
26
  if (file.startsWith('local.ssh-net-') && file.endsWith('.log'))
30
27
  rm(path.join(ctx.paths.logsDir, file));
31
28
  }
@@ -45,8 +42,7 @@ function removeNodeUnits(ctx, units) {
45
42
  }
46
43
  // daemon-reload 失败不能吞:systemd 仍持有已删 unit,Restart=always 会
47
44
  // 留着/重拉 ghost 进程
48
- const dr = systemd.daemonReload(ctx.runner);
49
- if (dr.code !== 0) throw new Error(`systemctl daemon-reload 失败:${dr.stderr.trim()}`);
45
+ systemd.daemonReload(ctx.runner);
50
46
  }
51
47
 
52
48
  export function run(ctx, args = []) {
@@ -58,6 +54,9 @@ export function run(ctx, args = []) {
58
54
  if (units.length > 0 && ctx.uid !== 0)
59
55
  throw new Error('node 卸载写 /etc/systemd/system 需要 root,请运行 sudo -i ssh-net uninstall');
60
56
  if (units.length > 0) removeNodeUnits(ctx, units);
57
+ // 上次可能已在删完 unit 后、daemon-reload 失败处中断;磁盘为空也必须补做,
58
+ // 否则第二次卸载会留下 manager 内的旧定义却报成功。非 root 零产物仍纯本地清理。
59
+ else if (ctx.uid === 0) systemd.daemonReload(ctx.runner);
61
60
  removeArtifacts(ctx);
62
61
  return '已卸载。最后一步:npm uninstall -g ssh-net';
63
62
  }
@@ -3,7 +3,7 @@
3
3
  // - tmp 文件绝不写在 conf.d/ 内(写入中的半截文件会被某次 ssh 扫到)——
4
4
  // 写在上级目录 ~/.ssh/ssh-net/.<名>.tmp-<pid> 再原子 rename 进来
5
5
  // - 目录 0700、片段 0600(与 ~/.ssh 权限纪律一致)
6
- // - sync 幂等:内容字节相同不动盘(routes 每次 install 调,不产生无意义变更)
6
+ // - sync 幂等:内容、权限与文件类型都正确就不动盘(不产生无意义变更)
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { readFileOrNull, writeFileAtomic } from './fsutil.mjs';
@@ -18,13 +18,23 @@ function ensureConfDir(confDir) {
18
18
  * 原子同步一个 Include 片段。
19
19
  * @param {string} file 片段绝对路径(在 conf.d 内)
20
20
  * @param {string} content 完整内容
21
- * @returns {boolean} 是否实际重写
21
+ * @returns {boolean} 是否有变更(重写、权限或文件类型修复)
22
22
  */
23
23
  export function syncConfFile(file, content) {
24
- if (readFileOrNull(file) === content) return false;
25
-
26
24
  const dir = path.dirname(file);
27
25
  ensureConfDir(dir);
26
+ const st = fs.lstatSync(file, { throwIfNoEntry: false }) ?? null;
27
+
28
+ let changed = false;
29
+ if (st?.isFile() && (st.mode & 0o7777) !== 0o600) {
30
+ // 先修权限再读:000 的片段也不能把修复入口自己挡住。
31
+ fs.chmodSync(file, 0o600);
32
+ changed = true;
33
+ }
34
+ const existing = st === null || st.isFile() ? readFileOrNull(file) : null;
35
+ if (existing === content && st?.isFile()) return changed;
36
+ // 同内容软链不是受管实体,落下原子替换为普通文件。
37
+
28
38
  // tmp 落 conf.d 的**上级**目录:glob conf.d/* 扫不到它
29
39
  writeFileAtomic(file, content, { mode: 0o600, tmpDir: path.dirname(dir) });
30
40
  return true;
@@ -18,6 +18,21 @@ export function readFileOrNull(file, encoding = 'utf8') {
18
18
  }
19
19
  }
20
20
 
21
+ /**
22
+ * 读目录;不存在返回 [](仅吞 ENOENT,其余错误照抛)。发现/清理入口共用,
23
+ * 权限或 IO 错误不能冒充空清单。
24
+ * @param {string} dir
25
+ * @returns {string[]}
26
+ */
27
+ export function readDirOrEmpty(dir) {
28
+ try {
29
+ return fs.readdirSync(dir);
30
+ } catch (err) {
31
+ if (err && err.code === 'ENOENT') return [];
32
+ throw err;
33
+ }
34
+ }
35
+
21
36
  /**
22
37
  * 读文本并 trim:不存在或只剩空白返回 null(「文件里得有值才算数」,
23
38
  * state 的 edges v6 与 runtime 的版本戳共用)。
@@ -31,6 +46,28 @@ export function readTrimmedOrNull(file) {
31
46
  return trimmed.length > 0 ? trimmed : null;
32
47
  }
33
48
 
49
+ /**
50
+ * 在目标旁建立唯一临时路径并交给 fn,返回后一律清理。fn 可在此完成校验、
51
+ * rename 等提交动作;原操作失败时清理失败不覆盖原始错误。
52
+ * @template T
53
+ * @param {string} file
54
+ * @param {{tmpDir?: string}} [opts]
55
+ * @param {(tmp: string) => T} fn
56
+ * @returns {T}
57
+ */
58
+ export function withTempFile(file, { tmpDir = path.dirname(file) } = {}, fn) {
59
+ const tmp = path.join(tmpDir, `.${path.basename(file)}.tmp-${process.pid}`);
60
+ let result;
61
+ try {
62
+ result = fn(tmp);
63
+ } catch (err) {
64
+ try { fs.rmSync(tmp, { force: true }); } catch { /* 保留原始操作错误 */ }
65
+ throw err;
66
+ }
67
+ fs.rmSync(tmp, { force: true });
68
+ return result;
69
+ }
70
+
34
71
  /**
35
72
  * 原子落盘:tmp 写好再 rename 落定,落定后 chmod 兜底(怪 umask/拷贝工具
36
73
  * 吃位都修正到 mode)。
@@ -40,8 +77,9 @@ export function readTrimmedOrNull(file) {
40
77
  * tmp 必须写在 glob 目录之外(conf.d/* 会被 ssh 扫到)
41
78
  */
42
79
  export function writeFileAtomic(file, content, { mode = 0o644, tmpDir = path.dirname(file) } = {}) {
43
- const tmp = path.join(tmpDir, `.${path.basename(file)}.tmp-${process.pid}`);
44
- fs.writeFileSync(tmp, content, { mode });
45
- fs.renameSync(tmp, file);
46
- fs.chmodSync(file, mode);
80
+ return withTempFile(file, { tmpDir }, (tmp) => {
81
+ fs.writeFileSync(tmp, content, { mode });
82
+ fs.renameSync(tmp, file);
83
+ fs.chmodSync(file, mode);
84
+ });
47
85
  }
@@ -27,7 +27,10 @@ export function reapEdgeLink(ctx, label) {
27
27
  if (!launchd.printState(ctx.runner, ctx.uid, label, true).registered)
28
28
  return { gone: true, label };
29
29
 
30
- launchd.killJob(ctx.runner, ctx.uid, label, 'TERM');
30
+ const killed = launchd.killJob(ctx.runner, ctx.uid, label, 'TERM');
31
+ if (killed.code !== 0 && killed.code !== 113
32
+ && !/Could not find service/.test(killed.stderr ?? ''))
33
+ throw new Error(`launchctl kill 失败(${label}):${killed.stderr.trim() || `exit ${killed.code}`}`);
31
34
  const end = Date.now() + WAIT_MS;
32
35
  while (Date.now() < end) {
33
36
  if (isGone(ctx, label)) return { gone: true, label };
@@ -4,7 +4,7 @@
4
4
  // - 休眠判据只用 print-disabled 字典(print 正文无稳定字段)
5
5
  // - 任何 bootstrap 前无条件先 enable(override 残留时 bootstrap error 5)
6
6
  // - enable 本身不触发首发,唤醒必须 kickstart -k
7
- import fs from 'node:fs';
7
+ import { readDirOrEmpty } from './fsutil.mjs';
8
8
  import { edgeLabel } from './render.mjs';
9
9
 
10
10
  /** @param {number} uid */
@@ -25,16 +25,9 @@ const NOT_REGISTERED = Object.freeze({ disabled: false, ...NOT_REGISTERED_PRINT
25
25
  * @returns {string[]}
26
26
  */
27
27
  export function labelsOnDisk(launchAgentsDir, prefix) {
28
- try {
29
- return fs
30
- .readdirSync(launchAgentsDir)
31
- .filter((f) => f.startsWith(prefix) && f.endsWith('.plist'))
32
- .map((f) => f.slice(0, -'.plist'.length));
33
- } catch (err) {
34
- // 只有目录不存在才是空清单;权限/IO 错误若吞掉,恢复卸载会漏掉在册任务
35
- if (err.code === 'ENOENT') return [];
36
- throw err;
37
- }
28
+ return readDirOrEmpty(launchAgentsDir)
29
+ .filter((f) => f.startsWith(prefix) && f.endsWith('.plist'))
30
+ .map((f) => f.slice(0, -'.plist'.length));
38
31
  }
39
32
 
40
33
  /**
@@ -3,7 +3,7 @@
3
3
  // 渲染结果与现文件字节相同则不 bootout——install 幂等不断连。
4
4
  import fs from 'node:fs';
5
5
  import * as launchd from './launchd.mjs';
6
- import { readFileOrNull } from './fsutil.mjs';
6
+ import { readFileOrNull, withTempFile } from './fsutil.mjs';
7
7
 
8
8
  /**
9
9
  * 确保一个在册 job 已加载可用(launchctl 四态状态机的唯一实现,实测矩阵见
@@ -69,30 +69,29 @@ export function syncPlist(ctx, { label, plistPath, content }) {
69
69
  return { changed: false };
70
70
  }
71
71
 
72
- // 内容变化(或首次):先 lint tmp,过了再动现文件
73
- const tmp = `${plistPath}.tmp-${process.pid}`;
74
- fs.writeFileSync(tmp, content, { mode: 0o644 });
75
- const lint = launchd.lintPlist(runner, tmp);
76
- if (lint.code !== 0) {
77
- fs.rmSync(tmp, { force: true });
78
- return { changed: false, lintError: lint.stderr.trim() || `plutil exit ${lint.code}` };
79
- }
72
+ // 内容变化(或首次):先 lint tmp,过了再动现文件;tmp 生命周期与原子写共用
73
+ return withTempFile(plistPath, {}, (tmp) => {
74
+ fs.writeFileSync(tmp, content, { mode: 0o644 });
75
+ const lint = launchd.lintPlist(runner, tmp);
76
+ if (lint.code !== 0)
77
+ return { changed: false, lintError: lint.stderr.trim() || `plutil exit ${lint.code}` };
80
78
 
81
- // 只要 registered 一个事实:printState 即可,不跑全域 print-disabled
82
- const st = launchd.printState(runner, uid, label);
83
- if (st.registered) {
84
- const bo = launchd.bootout(runner, uid, label);
85
- if (bo.code !== 0 && bo.code !== 113)
86
- throw new Error(`bootout 失败(${label}):${bo.stderr.trim()}`);
87
- }
88
- fs.renameSync(tmp, plistPath);
89
- fs.chmodSync(plistPath, 0o644);
90
- // 无条件先 enable(override 残留时 bootstrap error 5;launchd.mjs 宣言
91
- // 「勿在此吞错」)。取舍:此处 job 已 bootout、enable 失败即不 bootstrap
92
- //(停机态)——真失败(override 数据库损坏)下 bootstrap 也过不去(error 5),
93
- // 可见性优先于「也许 bootstrap 能侥幸成功」
94
- launchd.enableBootstrap(runner, uid, label, plistPath);
95
- return { changed: true, restarted: st.registered };
79
+ // 只要 registered 一个事实:printState 即可,不跑全域 print-disabled
80
+ const st = launchd.printState(runner, uid, label);
81
+ if (st.registered) {
82
+ const bo = launchd.bootout(runner, uid, label);
83
+ if (bo.code !== 0 && bo.code !== 113)
84
+ throw new Error(`bootout 失败(${label}):${bo.stderr.trim()}`);
85
+ }
86
+ fs.renameSync(tmp, plistPath);
87
+ fs.chmodSync(plistPath, 0o644);
88
+ // 无条件先 enable(override 残留时 bootstrap error 5;launchd.mjs 宣言
89
+ // 「勿在此吞错」)。取舍:此处 job 已 bootout、enable 失败即不 bootstrap
90
+ //(停机态)——真失败(override 数据库损坏)下 bootstrap 也过不去(error 5),
91
+ // 可见性优先于「也许 bootstrap 能侥幸成功」
92
+ launchd.enableBootstrap(runner, uid, label, plistPath);
93
+ return { changed: true, restarted: st.registered };
94
+ });
96
95
  }
97
96
 
98
97
  /**
@@ -31,6 +31,19 @@ export function tcpOpen(host, port, timeoutMs = 300) {
31
31
  });
32
32
  }
33
33
 
34
+ /**
35
+ * lsof 无匹配是 exit 1 且 stderr 为空;启动失败、权限错误等不能冒充「无监听」。
36
+ * @param {import('./exec.mjs').Runner} runner
37
+ * @param {string[]} args
38
+ * @param {number} port
39
+ */
40
+ function runLsof(runner, args, port) {
41
+ const r = runner.run('lsof', args);
42
+ if (r.code === 0 || (r.code === 1 && r.stderr.trim() === '')) return r;
43
+ const detail = r.stderr.trim() || r.error?.message || `exit ${r.code ?? r.signal ?? '未知'}`;
44
+ throw new Error(`lsof 查询端口 ${port} 失败:${detail}`);
45
+ }
46
+
34
47
  /**
35
48
  * 环回某端口当前的监听 pid 列表(无监听空数组)。
36
49
  * @param {import('./exec.mjs').Runner} runner
@@ -38,8 +51,8 @@ export function tcpOpen(host, port, timeoutMs = 300) {
38
51
  * @returns {number[]}
39
52
  */
40
53
  export function listListeners(runner, port) {
41
- const r = runner.run('lsof', ['-tnP', `-iTCP:${port}`, '-sTCP:LISTEN']);
42
- if (r.code !== 0) return []; // lsof 无持有者时 exit 1
54
+ const r = runLsof(runner, ['-tnP', `-iTCP:${port}`, '-sTCP:LISTEN'], port);
55
+ if (r.code !== 0) return [];
43
56
  return r.stdout
44
57
  .trim()
45
58
  .split(/\s+/)
@@ -56,7 +69,7 @@ export function listListeners(runner, port) {
56
69
  * @returns {string}
57
70
  */
58
71
  export function lsofListen(runner, port) {
59
- const r = runner.run('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN']);
72
+ const r = runLsof(runner, ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN'], port);
60
73
  return r.code === 0 ? r.stdout.trim() : '';
61
74
  }
62
75
 
@@ -91,6 +91,20 @@ const ROUTES_HEADER = `# 本文件由 \`ssh-net install\` 从 ~/.ssh/ssh-net/top
91
91
  # 入站,只有 relay 兜底。User 不写——由主 config 的 Host 块补。
92
92
  `;
93
93
 
94
+ // Match exec 有两层语法:shellWord 保护 shell 参数,matchExec 再转义
95
+ // ssh_config 的外层双引号。输入均已由 topology 校验或来自内部常量;保留 $
96
+ // 是为了让 $HOME 与 VS Code 参数展开在实际连接时发生。
97
+ /** @param {string|number} value */
98
+ function shellWord(value) {
99
+ return `"${String(value).replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`;
100
+ }
101
+
102
+ /** @param {string} pattern @param {string} command */
103
+ function matchExec(pattern, command) {
104
+ const escaped = command.replaceAll('\\', '\\\\').replaceAll('"', '\\"');
105
+ return `Match originalhost ${pattern} exec "${escaped}"`;
106
+ }
107
+
94
108
  /**
95
109
  * sn-route 的冻结位置参数(design §2.3 argv 契约):
96
110
  * <self> <core> <relay> <core 注册口> <core 用户>
@@ -120,12 +134,10 @@ export function renderRoutes(topo, selfAlias) {
120
134
  const blocks = [];
121
135
 
122
136
  // sn-route argv 直接渲染进 Match(无配置文件中转)。进度只进 stderr 且
123
- // 仅终端显示(VS Code/Remote-SSH、scp、脚本下自动静默)。端口加引号是
124
- // shell 渲染层,argv 契约本身在 snRouteArgv
125
- const routeArgs = snRouteArgv(topo, selfAlias);
126
- routeArgs[3] = `'${routeArgs[3]}'`;
127
- const match = (alias, cond) =>
128
- `Match originalhost ${alias} exec "test -e ${state}/RELAY_ON${cond}"`;
137
+ // 仅终端显示(VS Code/Remote-SSH、scp、脚本下自动静默)
138
+ const routeCommand = [snRoute, ...snRouteArgv(topo, selfAlias)].map(shellWord).join(' ');
139
+ const match = (alias, cond = '') =>
140
+ matchExec(alias, `test -e ${shellWord(`${state}/RELAY_ON`)}${cond}`);
129
141
  // core 判决块与兜底块共用一个发射器:first-wins 逐 keyword 取首值,
130
142
  // 「块命中」不是整体替换——判决块必须占住兜底块设的每一个 keyword
131
143
  // (ProxyJump none 不是装饰,漏了后块的 ProxyJump 就漏进直连路径,
@@ -142,7 +154,7 @@ export function renderRoutes(topo, selfAlias) {
142
154
 
143
155
  // core:peer 一跳(sn-route 现场确保成功:对端连到本机 [::1]:10022)
144
156
  blocks.push(routeBlock(
145
- topo.core.alias, ` && ${snRoute} ${routeArgs.join(' ')}`,
157
+ topo.core.alias, ` && ${routeCommand}`,
146
158
  '::1', CALLBACK_PORT, 'none',
147
159
  `peer(对方经 v6 连到本机 [::1]:${CALLBACK_PORT},全 v6 环回)`,
148
160
  ));
@@ -174,12 +186,13 @@ export function renderRoutes(topo, selfAlias) {
174
186
  const peerList = [topo.core.alias, ...topo.nodes.map((n) => n.alias)];
175
187
  const peers = peerList.join(',');
176
188
  const nonPeers = `*,${peerList.map((a) => `!${a}`).join(',')}`;
177
- const vscode = 'exec "test -n \\"${VSCODE_IPC_HOOK:-}\\""';
189
+ const vscode = (pattern) =>
190
+ matchExec(pattern, `test -n ${shellWord('${VSCODE_IPC_HOOK:-}')}`);
178
191
  blocks.push([
179
192
  '# 连接打标:对端 ~/.ssh/rc 读 LC_VSCODE_SSH 维护 dot.via、把本机别名交给 sn-register-lan 登记内网地址',
180
- `Match originalhost ${peers} ${vscode}`,
193
+ vscode(peers),
181
194
  ` SetEnv LC_VSCODE_SSH=1 ${idEnv}`,
182
- `Match originalhost ${nonPeers} ${vscode}`,
195
+ vscode(nonPeers),
183
196
  ' SetEnv LC_VSCODE_SSH=1',
184
197
  `Match originalhost ${peers}`,
185
198
  ` SetEnv ${idEnv}`,
@@ -206,6 +219,10 @@ export function renderRoutes(topo, selfAlias) {
206
219
  */
207
220
  export function renderEdgeHost({ alias, aliases, user }) {
208
221
  const addr = edgeAddrFileRel(alias);
222
+ const freshnessGate = matchExec(
223
+ aliases.join(','),
224
+ `find ${shellWord(`$HOME/${addr}`)} -mmin -${EDGE_ADDR_TTL_MIN} 2>/dev/null | read -r _`,
225
+ );
209
226
  // 门控管道用内建 read 收尾而不是 grep -q:Match exec 每条连接都跑,少 fork
210
227
  // 一个外部进程(find 有输出 read 退出 0、EOF 退出 1,三态与 grep -q 等价)
211
228
  return `# 本文件由 \`ssh-net install\` 从 topology 渲染,勿手改。地址在 Include 的文件
@@ -215,7 +232,7 @@ Host ${aliases.join(' ')}
215
232
  User ${user}
216
233
  HostKeyAlias ${alias}
217
234
  ConnectTimeout 5
218
- Match originalhost ${aliases.join(',')} exec "find $HOME/${addr} -mmin -${EDGE_ADDR_TTL_MIN} 2>/dev/null | read -r _"
235
+ ${freshnessGate}
219
236
  Include ~/${addr}
220
237
  `;
221
238
  }
@@ -6,7 +6,6 @@
6
6
  // - 运行时零 npm/fnm 依赖;包升级后重跑 install 刷新(core 侧 uplink-edge
7
7
  // 由每次报名自动对账),status 直接比对包内脚本与磁盘产物
8
8
  import fs from 'node:fs';
9
- import path from 'node:path';
10
9
  import { packageScriptPath } from './paths.mjs';
11
10
  import { readFileOrNull, writeFileAtomic } from './fsutil.mjs';
12
11
 
@@ -39,13 +38,8 @@ export function ensureScript(dstPath, srcPath) {
39
38
  * @returns {boolean} 是否发生变更
40
39
  */
41
40
  export function ensureLink(linkPath, entityName) {
42
- let st = null;
43
- try {
44
- st = fs.lstatSync(linkPath);
45
- } catch (err) {
46
- if (err.code !== 'ENOENT') throw err;
47
- }
48
- if (st !== null && st.isSymbolicLink() && fs.readlinkSync(linkPath) === entityName)
41
+ const st = fs.lstatSync(linkPath, { throwIfNoEntry: false }) ?? null;
42
+ if (st?.isSymbolicLink() && fs.readlinkSync(linkPath) === entityName)
49
43
  return false;
50
44
  // 缺失无需处理;错链或实体占位都删掉后统一建链
51
45
  if (st !== null) fs.rmSync(linkPath);
@@ -65,9 +59,9 @@ export function ensureLink(linkPath, entityName) {
65
59
  export function ensureRuntime(ctx, entries, links = []) {
66
60
  fs.mkdirSync(ctx.paths.binDir, { recursive: true });
67
61
  const results = entries.map(([name, scriptName]) =>
68
- ensureScript(path.join(ctx.paths.binDir, name), packageScriptPath(scriptName)));
62
+ ensureScript(ctx.paths.binScript(name), packageScriptPath(scriptName)));
69
63
  for (const [name, entityName] of links) {
70
- results.push(ensureLink(path.join(ctx.paths.binDir, name), entityName));
64
+ results.push(ensureLink(ctx.paths.binScript(name), entityName));
71
65
  }
72
66
  // 旧版本戳(26.10.59 退役)只作迁移清理,保留约一个月后随版本删除
73
67
  fs.rmSync(ctx.paths.legacyRuntimeVersionFile, { force: true });
@@ -105,14 +99,8 @@ export function auditScript(dstPath, srcPath) {
105
99
  * @returns {boolean}
106
100
  */
107
101
  export function auditLink(linkPath, entityName) {
108
- let st;
109
- try {
110
- st = fs.lstatSync(linkPath);
111
- } catch (err) {
112
- if (err && err.code === 'ENOENT') return false;
113
- throw err;
114
- }
115
- if (!st.isSymbolicLink()) return false;
102
+ const st = fs.lstatSync(linkPath, { throwIfNoEntry: false });
103
+ if (!st?.isSymbolicLink()) return false;
116
104
  if (fs.readlinkSync(linkPath) !== entityName) return false;
117
105
  try {
118
106
  return Boolean(fs.statSync(linkPath).mode & 0o111);
@@ -37,8 +37,11 @@ export function parseStaticHosts(text) {
37
37
  for (const raw of text.split('\n')) {
38
38
  const line = raw.trim();
39
39
  if (line.length === 0 || line.startsWith('#')) continue;
40
- const cols = line.split(/\s+/);
41
- const keyword = cols[0].toLowerCase();
40
+ // ssh_config 允许 `Keyword value`、`Keyword=value` 与 `Keyword = value`。
41
+ const parsed = line.match(/^([^\s=]+)\s*(?:=\s*|\s+)(.*)$/);
42
+ if (!parsed) continue;
43
+ const keyword = parsed[1].toLowerCase();
44
+ const cols = parsed[2] ? parsed[2].split(/\s+/) : [];
42
45
 
43
46
  if (keyword === 'match') {
44
47
  inMatch = true;
@@ -49,7 +52,7 @@ export function parseStaticHosts(text) {
49
52
  inMatch = false;
50
53
  // 精确模式入表(多模式逐个);同一别名多个 Host 块时 ssh 取首次值——
51
54
  // 已存在的记录对象继续沿用,首次值写入不被后块覆盖
52
- currentPatterns = cols.slice(1).filter(isExactPattern);
55
+ currentPatterns = cols.filter(isExactPattern);
53
56
  for (const p of currentPatterns) {
54
57
  if (!table.has(p)) table.set(p, {});
55
58
  }
@@ -57,7 +60,7 @@ export function parseStaticHosts(text) {
57
60
  }
58
61
  if (inMatch || currentPatterns.length === 0) continue;
59
62
  if (keyword === 'hostname') {
60
- const value = cols.slice(1).join(' ');
63
+ const value = cols.join(' ');
61
64
  if (value) {
62
65
  for (const p of currentPatterns) {
63
66
  const host = table.get(p);
@@ -36,6 +36,7 @@ export const SWITCH_NAMES = ['relay', 'peer'];
36
36
  export function createStateStore({ stateDir, switchFiles, edgesDir, addrDir }) {
37
37
  const ensureState = () => {
38
38
  fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
39
+ fs.chmodSync(stateDir, 0o700);
39
40
  };
40
41
 
41
42
  const assertNames = (names) => {
@@ -48,6 +49,7 @@ export function createStateStore({ stateDir, switchFiles, edgesDir, addrDir }) {
48
49
  const writeStateLine = (dir, alias, line) => {
49
50
  ensureState();
50
51
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
52
+ fs.chmodSync(dir, 0o700);
51
53
  writeFileAtomic(path.join(dir, alias), line, { mode: 0o600 });
52
54
  };
53
55
 
@@ -4,12 +4,17 @@
4
4
  import fs from 'node:fs';
5
5
  import os from 'node:os';
6
6
  import path from 'node:path';
7
- import { readFileOrNull, writeFileAtomic } from './fsutil.mjs';
7
+ import { readDirOrEmpty, readFileOrNull, writeFileAtomic } from './fsutil.mjs';
8
8
 
9
9
  /** @param {import('./exec.mjs').Runner} runner @param {string} unit 含 .service */
10
10
  const sc = (runner, args) => runner.run('systemctl', args);
11
11
 
12
- export const daemonReload = (runner) => sc(runner, ['daemon-reload']);
12
+ /** 所有 reload 路径都把真失败抛出;恢复路径可给错误加「恢复后」前缀。 */
13
+ export function daemonReload(runner, errorPrefix = '') {
14
+ const r = sc(runner, ['daemon-reload']);
15
+ if (r.code !== 0)
16
+ throw new Error(`${errorPrefix}systemctl daemon-reload 失败:${r.stderr.trim()}`);
17
+ }
13
18
  export const enableUnit = (runner, unit) => sc(runner, ['enable', unit]);
14
19
  const disableUnit = (runner, unit) => sc(runner, ['disable', unit]);
15
20
  export const startUnit = (runner, unit) => sc(runner, ['start', unit]);
@@ -23,14 +28,8 @@ export const restartUnit = (runner, unit) => sc(runner, ['restart', unit]);
23
28
  * @returns {string[]}
24
29
  */
25
30
  export function unitNamesOnDisk(unitDir, prefix) {
26
- try {
27
- return fs.readdirSync(unitDir)
28
- .filter((f) => f.startsWith(prefix) && f.endsWith('.service'));
29
- } catch (err) {
30
- // 恢复卸载依赖完整清单;目录不存在才是空,其余错误不能静默吞掉
31
- if (err.code === 'ENOENT') return [];
32
- throw err;
33
- }
31
+ return readDirOrEmpty(unitDir)
32
+ .filter((f) => f.startsWith(prefix) && f.endsWith('.service'));
34
33
  }
35
34
 
36
35
  /** 没装/已卸的 unit 放行(stop 的 not-loaded 与 disable 的 does not exist
@@ -128,9 +127,7 @@ export function syncUnit(runner, { unitPath, unitName, content }) {
128
127
  throw new Error(`systemd-analyze verify 失败(未写入 ${unitPath}):\n${verify.stderr}`);
129
128
  writeFileAtomic(unitPath, content, { mode: 0o644 });
130
129
  try {
131
- const reload = daemonReload(runner);
132
- if (reload.code !== 0)
133
- throw new Error(`systemctl daemon-reload 失败:${reload.stderr.trim()}`);
130
+ daemonReload(runner);
134
131
  enableRestart(runner, unitName);
135
132
  } catch (err) {
136
133
  // 文件相同只能表示部署完成:失败时恢复旧文件并重载 manager;首装撤掉
@@ -145,9 +142,7 @@ export function syncUnit(runner, { unitPath, unitName, content }) {
145
142
  } else {
146
143
  writeFileAtomic(unitPath, previous, { mode: 0o644 });
147
144
  }
148
- const reload = daemonReload(runner);
149
- if (reload.code !== 0)
150
- throw new Error(`恢复后 systemctl daemon-reload 失败:${reload.stderr.trim()}`);
145
+ daemonReload(runner, '恢复后 ');
151
146
  if (previous !== null) enableRestart(runner, unitName);
152
147
  } catch (rollbackError) {
153
148
  throw new AggregateError([err, rollbackError], `${err.message};恢复 systemd 状态失败:${rollbackError.message}`);
package/libexec/sn-route CHANGED
@@ -166,28 +166,27 @@ fail_relay() {
166
166
  # 本次报名也会立刻重建回拨。任何意外(lsof 缺失/失败、无持有者、comm 不符)
167
167
  # 静默:等 sshd 90s 自行回收,之后下一条连接(受 15s 印记节流)再报名唤醒
168
168
  reap_zombie() {
169
- local pid= line comm= hit6= lsof_pid rc room expired=
169
+ local pid= line comm= hit6= lsof_pid watchdog_pid rc room expired=
170
170
  local out="$STATE_DIR/LSOF.tmp.$$"
171
171
  room=$((deadline - SECONDS - 1))
172
172
  [ "$room" -ge 1 ] || return 1
173
- # lsof 是单一可执行文件:后台跑、父进程按预算轮询,超时直接 kill。
174
- # 半截输出绝不用于杀进程;正常失败仍按旧行为静默跳过清尸。
173
+ # lsof 正常结束就立刻 wait 返回,不白睡连接恢复用的 POLL;watchdog 只负责
174
+ # 到点留印记并 kill。半截输出绝不用于杀进程;正常失败仍静默跳过清尸。
175
175
  "$LSOF" -F pcn -nP -i "TCP:$PORT" -sTCP:LISTEN >"$out" 2>/dev/null &
176
176
  lsof_pid=$!
177
- # 这里只有 lsof 一个后台任务;jobs -r 不含已结束但尚未 wait 的僵尸项
178
- while [ -n "$(jobs -r -p)" ]; do
179
- room=$((deadline - SECONDS - 1))
180
- if [ "$room" -lt 1 ]; then
181
- expired=1
182
- kill "$lsof_pid" 2>/dev/null
183
- break
184
- fi
185
- "$SLEEP" "$POLL" 2>/dev/null || true
186
- done
177
+ (
178
+ "$SLEEP" "$room" 2>/dev/null
179
+ : >"$out.expired"
180
+ kill "$lsof_pid" 2>/dev/null
181
+ ) &
182
+ watchdog_pid=$!
187
183
  wait "$lsof_pid" 2>/dev/null
188
184
  rc=$?
185
+ kill "$watchdog_pid" 2>/dev/null
186
+ wait "$watchdog_pid" 2>/dev/null
187
+ [ -e "$out.expired" ] && expired=1
189
188
  if [ -n "$expired" ]; then
190
- "$RM" -f "$out" 2>/dev/null
189
+ "$RM" -f "$out" "$out.expired" 2>/dev/null
191
190
  return 1
192
191
  fi
193
192
  # 一个进程块收尾:只有「本进程真有一条 [::1]:$PORT 的 LISTEN」且
@@ -209,13 +208,14 @@ reap_zombie() {
209
208
  done <"$out"
210
209
  flush
211
210
  fi
212
- "$RM" -f "$out" 2>/dev/null
211
+ "$RM" -f "$out" "$out.expired" 2>/dev/null
213
212
  return 0
214
213
  }
215
214
 
216
215
  # ── 层 1
217
- # 层 5 的 lsof 是后台进程:进入层 6 的 cleanup 前,TERM/INT 也要收掉它和临时文件
218
- trap '[ -n "${lsof_pid:-}" ] && kill "$lsof_pid" 2>/dev/null; [ -n "${out:-}" ] && "$RM" -f "$out" 2>/dev/null; exit 1' TERM INT
216
+ # 层 5 的 lsof 与 watchdog 是后台进程:进入层 6 的 cleanup 前,TERM/INT
217
+ # 也要收掉它们和临时文件
218
+ trap '[ -n "${lsof_pid:-}" ] && kill "$lsof_pid" 2>/dev/null; [ -n "${watchdog_pid:-}" ] && kill "$watchdog_pid" 2>/dev/null; [ -n "${out:-}" ] && "$RM" -f "$out" "$out.expired" 2>/dev/null; exit 1' TERM INT
219
219
  [ -e "$STATE_DIR/RELAY_ON" ] || exit 1
220
220
 
221
221
  peer_on=0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ssh-net",
3
- "version": "26.10.60",
3
+ "version": "26.10.61",
4
4
  "type": "module",
5
5
  "description": "个人 SSH 组网:IPv6 直连优先,中继自动兜底,断开后有界重试、按需恢复",
6
6
  "bin": {