ssh-net 26.11.66 → 26.11.68

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.
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import {
6
6
  CALLBACK_PORT, TERMINAL_NOTIFIER_PATHS, OSASCRIPT_PATH,
7
7
  } from '../lib/constants.mjs';
8
- import { removeJobs, syncPlist } from '../lib/manage.mjs';
8
+ import { acquireSshLock, removeJobs, syncPlist } from '../lib/manage.mjs';
9
9
  import { syncConfFile } from '../lib/conf.mjs';
10
10
  import { ensureRuntime } from '../lib/runtime.mjs';
11
11
  import { edgeLinkJob, coreRelayJob, nodeRelayJob } from '../lib/jobs.mjs';
@@ -56,8 +56,8 @@ function coreNodeInstallMsg(ctx, comp, entryChanged, result, removed) {
56
56
  return `安装完成${note},中继通道已开启(${relayLine})`;
57
57
  }
58
58
 
59
- /** 端口冲突时在写任何产物前退出。转发端口由 link 的 ssh 进程持有,回拨端口则由 sshd 持有 */
60
- async function precheckEdgePorts({ runner, uid, topo }, labels) {
59
+ /** 转发端口被别的程序占用时,在写任何产物前退出:link 的 ssh 绑不上口,装了也起不来 */
60
+ async function assertForwardPortsFree({ runner, uid, topo }, labels) {
61
61
  const jobPids = () => new Set(labels.map((label) => launchd.printState(runner, uid, label).pid));
62
62
  let owned = jobPids();
63
63
  for (const { listenPort: port } of topo.forwards) {
@@ -70,18 +70,22 @@ async function precheckEdgePorts({ runner, uid, topo }, labels) {
70
70
  throw new Error(`端口 ${port} 被别的程序占用(pid ${foreign.join(',')}):\n${lsofListen(runner, port)}`);
71
71
  }
72
72
  }
73
+ }
73
74
 
74
- // 检查覆盖 [::1] 的 IPv6 监听;同号的纯 IPv4 监听可以共存。
75
+ /**
76
+ * 回拨端口被占时的提示('\n' 起头的独立行),没被占为 ''。它不影响安装产物,
77
+ * 开盖后旧回拨的残留监听又要等 sshd 保活回收,所以只提示,不挡 install 和 update
78
+ */
79
+ async function callbackPortNote(runner) {
80
+ // 只看覆盖 [::1] 的 IPv6 监听;同号的纯 IPv4 监听可以共存。
75
81
  // 用包内探针读 SSH 标识,不能让磁盘上待修复的探针堵住 install
76
82
  const listeners = lsofListen(runner, CALLBACK_PORT);
77
83
  const scope = v6ListenerScope(listeners, CALLBACK_PORT);
78
- if (scope === 'wildcard')
79
- throw new Error(`端口 ${CALLBACK_PORT} 的 IPv6 通配监听占用了回拨地址 [::1]:\n${listeners}`);
80
- if (scope === 'loopback' && !(await peerProbeOk(runner, path.dirname(packageScriptPath(SN_PROBE))))) {
81
- throw new Error(
82
- `端口 ${CALLBACK_PORT} 有程序在监听但没有响应(多半是断线残留,或被别的程序占用):\n${listeners}`,
83
- );
84
- }
84
+ const why = scope === 'wildcard' ? 'IPv6 通配监听占用了回拨地址 [::1]'
85
+ : scope === 'loopback' && !(await peerProbeOk(runner, path.dirname(packageScriptPath(SN_PROBE))))
86
+ ? '有程序在监听但没有响应(多半是断线残留,sshd 保活会回收;持续出现就是被别的程序占用)'
87
+ : '';
88
+ return why ? `\n提示:端口 ${CALLBACK_PORT} ${why},core 的回拨暂时绑不上这个口:\n${listeners}` : '';
85
89
  }
86
90
 
87
91
  /** 通知依赖提示('\n' 前缀的独立行;terminal-notifier 齐备返回 '')。 */
@@ -110,7 +114,7 @@ async function installEdge(ctx) {
110
114
  const link = edgeLinkJob(ctx);
111
115
  const diskLabels = launchd.labelsOnDisk(paths.launchAgentsDir, linkLabel(''));
112
116
  const obsolete = diskLabels.filter((label) => label !== link?.label);
113
- await precheckEdgePorts(ctx, link ? [link.label, ...obsolete] : []);
117
+ await assertForwardPortsFree(ctx, link ? [link.label, ...obsolete] : []);
114
118
  const comp = syncRuntime(ctx, edgeRuntimePlan(topo));
115
119
  // link 可能在 bootstrap 内立即连接;新旧任务各自启动前都要读到配套的 routes
116
120
  let routesChanged = false;
@@ -137,7 +141,7 @@ async function installEdge(ctx) {
137
141
  routesChanged ? 'ssh 配置片段已更新' : '');
138
142
  const base = note ? `安装完成${note}` : '已安装,配置无需改动';
139
143
  const startNote = ctx.state.isOn('relay') ? '' : '\n当前为关闭状态;开启自动选路和 IPv6 直连:ssh-net start';
140
- return `${base}${startNote}${localNotifyDepNote()}`;
144
+ return `${base}${startNote}${await callbackPortNote(ctx.runner)}${localNotifyDepNote()}`;
141
145
  }
142
146
 
143
147
  /** core/node 按 topology 写各 edge 的入口,并移除已经不在 topology 里的旧片段 */
@@ -187,18 +191,15 @@ function installNode(ctx, home) {
187
191
  /** @param {object} ctx @param {string[]} [args] */
188
192
  export async function run(ctx, args = []) {
189
193
  if (args.length) throw new Error('用法:ssh-net install 不带参数');
190
- if (ctx.role === 'core') return installCore(ctx);
191
- if (!['edge', 'node'].includes(ctx.role)) throw new Error(`未知角色:${ctx.role}`);
194
+ // 不认识的角色直接报错,不能落进 edge 分支去动它的任务
195
+ if (!['core', 'node', 'edge'].includes(ctx.role)) throw new Error(`未知角色:${ctx.role}`);
192
196
  if (ctx.role === 'edge' && !hasRouteTimeout(ctx.env))
193
197
  throw new Error('缺少可执行的 timeout,未安装 edge 组件。请在这台机器上运行 brew install coreutils,再重跑 ssh-net install');
194
198
  const home = ctx.role === 'node' ? requireNodeHome(ctx, 'install') : null;
195
- // routes 和 systemd 恢复记录都跨多步更新。同一账户的两次安装不能替对方回滚
196
- const fd = fs.openSync(ctx.paths.sshDir, 'r');
199
+ // 回滚按命令开头记下的旧状态还原;安装、core 报名和 mac 卸载共用同一把锁
200
+ const fd = acquireSshLock(ctx);
197
201
  try {
198
- const mac = (ctx.platform ?? process.platform) === 'darwin';
199
- const lock = ctx.runner.run(mac ? 'lockf' : 'flock', mac ? ['-s', '-t', '0', '3'] : ['-n', '3'],
200
- { stdio: ['ignore', 'pipe', 'pipe', fd] });
201
- if (lock.code !== 0) throw new Error(`无法取得安装锁:${lock.error?.message || lock.stderr.trim() || '有其他安装正在运行,请稍后重试'}`);
202
- return ctx.role === 'node' ? installNode(ctx, home) : await installEdge(ctx);
203
- } finally { fs.closeSync(fd); }
202
+ if (ctx.role === 'node') return installNode(ctx, home);
203
+ return ctx.role === 'core' ? installCore(ctx) : await installEdge(ctx);
204
+ } finally { if (fd !== null) fs.closeSync(fd); }
204
205
  }
@@ -1,9 +1,10 @@
1
1
  // core 侧报名 RPC:edge 的 sn-route 经 relay 调用,登记最近地址并建/唤回拨。
2
2
  // 人工 start peer 也复用 sn-route,edge 侧不另维护一套报名实现。
3
3
  // install 与报名都会刷新运行时脚本;job 参数由报名重新渲染。
4
+ import fs from 'node:fs';
4
5
  import { explainV6Error } from '../lib/ipv6.mjs';
5
6
  import * as launchd from '../lib/launchd.mjs';
6
- import { syncPlist } from '../lib/manage.mjs';
7
+ import { acquireSshLock, syncPlist } from '../lib/manage.mjs';
7
8
  import { ensureRuntime } from '../lib/runtime.mjs';
8
9
  import { readFileOrNull } from '../lib/fsutil.mjs';
9
10
  import { edgeCallbacksPlan } from '../lib/manifest.mjs';
@@ -35,28 +36,32 @@ export function runRegister(ctx, args = []) {
35
36
  const v6Err = explainV6Error(v6);
36
37
  if (v6Err) throw new Error(`v6 校验失败(${alias}):${v6Err}`);
37
38
 
38
- const label = edgeLabel(alias);
39
- const plistPath = ctx.paths.plistFile(label);
40
- const content = renderUplinkEdgePlist({
41
- binDir: ctx.paths.binDir, edgeAlias: alias, user: edge.user,
42
- logsDir: ctx.paths.logsDir,
43
- });
44
- const plan = edgeCallbacksPlan([alias]);
45
- ensureRuntime(ctx, plan.entities, plan.links);
46
- ctx.state.writeEdgeV6(alias, v6);
47
- ctx.state.writeEdgeAddr(alias, v6);
39
+ // 两台 edge 可同时报名;短等正常报名收尾,仍受 sn-route 的报名总时限约束
40
+ const fd = acquireSshLock(ctx, 1);
41
+ try {
42
+ const label = edgeLabel(alias);
43
+ const plistPath = ctx.paths.plistFile(label);
44
+ const content = renderUplinkEdgePlist({
45
+ binDir: ctx.paths.binDir, edgeAlias: alias, user: edge.user,
46
+ logsDir: ctx.paths.logsDir,
47
+ });
48
+ const plan = edgeCallbacksPlan([alias]);
49
+ ensureRuntime(ctx, plan.entities, plan.links);
50
+ ctx.state.writeEdgeV6(alias, v6);
51
+ ctx.state.writeEdgeAddr(alias, v6);
48
52
 
49
- // 未注册(首次报名)或 plist 与 topology 渲染不符(user 等变了):
50
- // 重新部署,syncPlist 的 bootstrap 即首发
51
- const st = launchd.inspect(ctx.runner, ctx.uid, label);
52
- if (!st.registered || readFileOrNull(plistPath) !== content) {
53
- const r = syncPlist(ctx, { label, plistPath, content });
54
- if (r.lintError) throw new Error(`uplink-edge plist 校验失败:${r.lintError}`);
55
- return st.registered ? `已更新登记 ${alias}` : `已登记 ${alias}`;
56
- }
53
+ // 未注册(首次报名)或 plist 与 topology 渲染不符(user 等变了):
54
+ // 重新部署,syncPlist 的 bootstrap 即首发
55
+ const st = launchd.inspect(ctx.runner, ctx.uid, label);
56
+ if (!st.registered || readFileOrNull(plistPath) !== content) {
57
+ const r = syncPlist(ctx, { label, plistPath, content });
58
+ if (r.lintError) throw new Error(`uplink-edge plist 校验失败:${r.lintError}`);
59
+ return st.registered ? `已更新登记 ${alias}` : `已登记 ${alias}`;
60
+ }
57
61
 
58
- // 已注册:休眠中要先 enable 清 override,enabled 时幂等;kickstart -k 杀旧起新
59
- const r = launchd.kickstartEnabled(ctx.runner, ctx.uid, label);
60
- if (r.code !== 0) throw new Error(`kickstart 失败:${r.stderr.trim()}`);
61
- return st.disabled ? `已唤醒 ${alias}` : `已开始拨号 ${alias}`;
62
+ // 已注册:休眠中要先 enable 清 override,enabled 时幂等;kickstart -k 杀旧起新
63
+ const r = launchd.kickstartEnabled(ctx.runner, ctx.uid, label);
64
+ if (r.code !== 0) throw new Error(`kickstart 失败:${r.stderr.trim()}`);
65
+ return st.disabled ? `已唤醒 ${alias}` : `已开始拨号 ${alias}`;
66
+ } finally { if (fd !== null) fs.closeSync(fd); }
62
67
  }
@@ -4,7 +4,7 @@
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import * as systemd from '../lib/systemd.mjs';
7
- import { ensureLoaded } from '../lib/manage.mjs';
7
+ import { acquireSshLock, ensureLoaded } from '../lib/manage.mjs';
8
8
  import { SWITCH_NAMES } from '../lib/state.mjs';
9
9
  import { SN_ROUTE } from '../lib/manifest.mjs';
10
10
  import { edgeLinkJob } from '../lib/jobs.mjs';
@@ -51,7 +51,7 @@ function startCore(ctx) {
51
51
  return '中继通道已开启';
52
52
  }
53
53
 
54
- export function run(ctx, args = []) {
54
+ function runUnlocked(ctx, args = []) {
55
55
  if (ctx.role === 'edge') {
56
56
  const target = parseEdgeTarget(args);
57
57
  const peerWasOn = target === 'relay' && ctx.state.isOn('peer');
@@ -84,3 +84,13 @@ export function run(ctx, args = []) {
84
84
  }
85
85
  throw new Error(`未知角色:${ctx.role}`);
86
86
  }
87
+
88
+ export function run(ctx, args = []) {
89
+ if (ctx.role === 'node' || (ctx.platform ?? process.platform) === 'linux')
90
+ return runUnlocked(ctx, args);
91
+ // start 可能在卸载的 bootout 后重新 bootstrap;共用锁,避免留下无 plist 的注册任务
92
+ const fd = acquireSshLock(ctx);
93
+ try {
94
+ return runUnlocked(ctx, args);
95
+ } finally { if (fd !== null) fs.closeSync(fd); }
96
+ }
@@ -140,7 +140,7 @@ async function probeForwardPorts(ctx, forwards, label, initialJob) {
140
140
  const job = initialJob && owners.some(pids => !pids.includes(firstPid))
141
141
  ? launchd.inspect(ctx.runner, ctx.uid, label) : initialJob;
142
142
  const forwardViews = await Promise.all(forwards.map(async (f, i) => {
143
- let ok = owners[i].some(pid => pid === firstPid || pid === job?.pid);
143
+ let ok = owners[i].includes(job?.pid);
144
144
  // 探测可能恰好落在两任进程之间。只为换了进程又没认领的端口再查一次
145
145
  if (!ok && job?.pid && job.pid !== firstPid) ok = (await listeners(f)).includes(job.pid);
146
146
  return [forwardLabel(f), ok];
@@ -296,10 +296,18 @@ async function collectNode(ctx, probe) {
296
296
  if (configIssue) issues.push(configIssue);
297
297
  if (systemd.hasPendingUpdate(deployment.unitPath)) issues.push('中继服务更新尚未完成——跑一次 ssh-net install 完成更新');
298
298
  const unit = deployment.unitName;
299
- const active = systemd.isActive(ctx.runner, unit);
299
+ const { activeState: active, fileState } = systemd.unitSnapshot(ctx.runner, unit);
300
300
  const relayPort = probe ? await relayPortListening(ctx, ctx.self.relayPort) : null;
301
301
  if (active !== 'active')
302
302
  issues.push(`系统服务 ${unit} 状态 ${active}——systemctl status ${unit} 查看`);
303
+ else if (fileState !== 'enabled') {
304
+ const repair = ['disabled', 'enabled-runtime'].includes(fileState)
305
+ ? 'ssh-net start 可重新启用'
306
+ : fileState.includes('masked')
307
+ ? '先用 systemctl unmask 取消屏蔽,再用 ssh-net start 恢复'
308
+ : '检查 unit 文件与 systemctl enable 状态';
309
+ issues.push(`系统服务 ${unit} 仍在运行,但开机自启为 ${fileState || 'unknown'}——${repair}`);
310
+ }
303
311
  if (relayPort && !relayPort.listening)
304
312
  issues.push(relayPortIssue(topo.relay.alias, ctx.self.relayPort, relayPort));
305
313
 
@@ -3,7 +3,7 @@
3
3
  // plist/unit、运行时脚本、状态与日志;topology 改名前的残留由 glob 覆盖。
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
- import { removeJobs } from '../lib/manage.mjs';
6
+ import { acquireSshLock, removeJobs } from '../lib/manage.mjs';
7
7
  import { requireNodeHome } from '../lib/identity.mjs';
8
8
  import * as launchd from '../lib/launchd.mjs';
9
9
  import * as systemd from '../lib/systemd.mjs';
@@ -46,13 +46,17 @@ export function run(ctx, args = []) {
46
46
  return '已卸载。最后一步:npm uninstall -g ssh-net';
47
47
  }
48
48
 
49
- const labels = new Set([
50
- ...launchd.labelsOnDisk(ctx.paths.launchAgentsDir, linkLabel('')),
51
- ...launchd.labelsOnDisk(ctx.paths.launchAgentsDir, relayLabel('')),
52
- ...launchd.labelsOnDisk(ctx.paths.launchAgentsDir, edgeLabel('')),
53
- ]);
54
- removeJobs(ctx, labels);
55
- removeArtifacts(ctx);
56
- removeSshNetLogs(ctx);
57
- return '已卸载。最后一步:npm uninstall -g ssh-net';
49
+ // 快照与删除必须和 core 报名互斥,否则新回拨会在快照后注册、再被删掉运行时
50
+ const fd = acquireSshLock(ctx);
51
+ try {
52
+ const labels = new Set([
53
+ ...launchd.labelsOnDisk(ctx.paths.launchAgentsDir, linkLabel('')),
54
+ ...launchd.labelsOnDisk(ctx.paths.launchAgentsDir, relayLabel('')),
55
+ ...launchd.labelsOnDisk(ctx.paths.launchAgentsDir, edgeLabel('')),
56
+ ]);
57
+ removeJobs(ctx, labels);
58
+ removeArtifacts(ctx);
59
+ removeSshNetLogs(ctx);
60
+ return '已卸载。最后一步:npm uninstall -g ssh-net';
61
+ } finally { if (fd !== null) fs.closeSync(fd); }
58
62
  }
@@ -6,6 +6,32 @@ import * as launchd from './launchd.mjs';
6
6
  import path from 'node:path';
7
7
  import { readFileOrNull, removeObsoleteNames, withTempFile, writeFileAtomic } from './fsutil.mjs';
8
8
 
9
+ /**
10
+ * 取得本账户 .ssh 目录的排他锁,调用方持有返回的 fd 直至操作结束。
11
+ * install、core 报名和 mac start/uninstall 共用,避免回滚或删除产物时互相交错。
12
+ * 没有 .ssh 说明没有可互斥的本地产物,供空 HOME 的卸载保持幂等。
13
+ * @param {object} ctx
14
+ * @param {number} [waitSeconds] 正常报名之间短等;安装、启动和卸载默认不等待
15
+ * @returns {number|null} 调用方负责 close;null 表示无需锁
16
+ */
17
+ export function acquireSshLock(ctx, waitSeconds = 0) {
18
+ if (!fs.existsSync(ctx.paths.sshDir)) return null;
19
+ const fd = fs.openSync(ctx.paths.sshDir, 'r');
20
+ try {
21
+ const mac = (ctx.platform ?? process.platform) === 'darwin';
22
+ const args = mac ? ['-s', '-t', String(waitSeconds), '3']
23
+ : waitSeconds ? ['-w', String(waitSeconds), '3'] : ['-n', '3'];
24
+ const lock = ctx.runner.run(mac ? 'lockf' : 'flock', args,
25
+ { stdio: ['ignore', 'pipe', 'pipe', fd] });
26
+ if (lock.code !== 0)
27
+ throw new Error(`无法取得安装锁:${lock.error?.message || lock.stderr.trim() || '有其他安装、报名或卸载正在运行,请稍后重试'}`);
28
+ return fd;
29
+ } catch (err) {
30
+ fs.closeSync(fd);
31
+ throw err;
32
+ }
33
+ }
34
+
9
35
  /**
10
36
  * install 与 start 共用的任务恢复逻辑。带 PathState 的任务由 launchd 按文件状态启动
11
37
  * @param {object} ctx
@@ -94,10 +94,9 @@ const ROUTES_HEADER = `# 本文件由 \`ssh-net install\` 从 ~/.ssh/ssh-net/top
94
94
  // Match exec 只保留 ssh_config 的外层双引号:OpenSSH 9.x 不能解析内嵌
95
95
  // 转义双引号。路径用 ~ 让 shell 展开(结果不受 HOME 空白分词影响),topology
96
96
  // 已拒绝 argv 的空白与 shell 元字符,不在此层做 shell 引号
97
- /** @param {string} pattern @param {string} command */
97
+ /** @param {string} pattern @param {string} command(不得含引号) */
98
98
  function matchExec(pattern, command) {
99
- const escaped = command.replaceAll('\\', '\\\\').replaceAll('"', '\\"');
100
- return `Match originalhost ${pattern} exec "${escaped}"`;
99
+ return `Match originalhost ${pattern} exec "${command}"`;
101
100
  }
102
101
 
103
102
  /**
@@ -64,16 +64,6 @@ function restart(runner, unit) {
64
64
  if (r.code !== 0) throw new Error(`systemctl restart 失败:${r.stderr.trim()}`);
65
65
  }
66
66
 
67
- /** @returns {string} active|inactive|failed|... */
68
- export function isActive(runner, unit) {
69
- const r = sc(runner, ['is-active', unit]);
70
- const state = r.stdout.trim();
71
- // inactive/failed 也有非零退出码;此时 stdout 仍有状态,与无法连接 manager 区分
72
- if (!state || ![0, 3, 4].includes(r.code))
73
- throw new Error(`systemctl is-active 失败(${unit}):${r.stderr.trim() || r.error?.message || `exit ${r.code}`}`);
74
- return state;
75
- }
76
-
77
67
  /**
78
68
  * unit 内容校验:写进私有临时目录、**文件名与正式 unit 相同**(verify 要求
79
69
  * .service 后缀,basename 参与模板/实例语义),过了才允许落 /etc——坏 unit
@@ -139,20 +129,28 @@ export function removeUnits(runner, unitDir, units) {
139
129
  }
140
130
  }
141
131
 
142
- function unitState(runner, unit, withInvocation = false) {
143
- const props = ['-p', 'ActiveState', '-p', 'UnitFileState'];
144
- if (withInvocation) props.push('-p', 'InvocationID');
145
- const state = sc(runner, ['show', ...props, unit]);
132
+ /** 一次只读快照;空 UnitFileState 留给调用方解释,属性行缺失仍是查询失败 */
133
+ export function unitSnapshot(runner, unit, withInvocation = false) {
134
+ const props = ['ActiveState', 'UnitFileState'];
135
+ if (withInvocation) props.push('InvocationID');
136
+ const state = sc(runner, ['show', ...props.flatMap((name) => ['-p', name]), unit]);
146
137
  if (state.code !== 0) throw new Error(`systemctl show 失败(${unit}):${state.stderr.trim()}`);
147
138
  const activeState = state.stdout.match(/^ActiveState=(\S+)$/m)?.[1];
148
139
  if (!activeState) throw new Error(`systemctl show 未返回 ${unit} 的运行状态`);
149
- const fileState = state.stdout.match(/^UnitFileState=(\S+)$/m)?.[1];
150
- if (!fileState) throw new Error(`systemctl show 未返回 ${unit} 的自启状态`);
151
- const active = ['active', 'activating', 'reloading', 'refreshing'].includes(activeState);
140
+ const fileState = state.stdout.match(/^UnitFileState=(.*)$/m)?.[1].trim();
141
+ if (fileState === undefined) throw new Error(`systemctl show 未返回 ${unit} 的自启状态`);
152
142
  const invocation = state.stdout.match(/^InvocationID=([0-9a-f]{32})$/m)?.[1];
153
- if (withInvocation && active && (!invocation || /^0+$/.test(invocation)))
143
+ return { activeState, fileState, invocation };
144
+ }
145
+
146
+ function unitState(runner, unit, withInvocation = false) {
147
+ const state = unitSnapshot(runner, unit, withInvocation);
148
+ // 安装和回滚必须知道真实自启状态;空值不能像 status 一样只归一为 unknown
149
+ if (!state.fileState) throw new Error(`systemctl show 未返回 ${unit} 的自启状态`);
150
+ const active = ['active', 'activating', 'reloading', 'refreshing'].includes(state.activeState);
151
+ if (withInvocation && active && (!state.invocation || /^0+$/.test(state.invocation)))
154
152
  throw new Error(`systemctl show 未返回 ${unit} 的运行实例 ID`);
155
- return { active, fileState, invocation: active ? invocation : null };
153
+ return { active, fileState: state.fileState, invocation: active ? state.invocation : null };
156
154
  }
157
155
 
158
156
  /** 各 unit 的运行和自启分别恢复,单步错误在尝试完其他服务后一起报告 */
package/libexec/sn-route CHANGED
@@ -15,9 +15,10 @@
15
15
  # 4. PROBE_FAIL 印记新鲜(15s) → 失败,不报名;SSH_NET_ROUTE_FORCE=1
16
16
  # 仅供 start 的 peer 恢复路径跳过这层短路,其他层序与锁纪律不变
17
17
  # 5. sn-ipv6 为空 → 失败,写印记
18
- # 6. 拿到 ENSURE 锁后再探。旧端口仍无 SSH 标识时,尝试结束持有它的 sshd 会话,
19
- # 再经 relay 报名。其他连接只跟随探测。清理和等待回拨共用 6s 预算。
20
- # 本次报名等到新回拨后,先让现存转发重连,再发一次桌面通知(peer_ready)
18
+ # 6. 拿到 ENSURE 锁后再探,自动连接直接经 relay 报名;只有 start peer 人工
19
+ # 恢复会在旧端口无 SSH 标识时尝试结束持口 sshd,再请求重拨。其他连接只跟随
20
+ # 探测。清理和等待回拨共用 6s 预算。本次报名等到新回拨后,其他连接发起的
21
+ # 恢复先让现存转发重连,转发自己发起则直接使用新连接,再发一次桌面通知
21
22
  # probe 永远在印记前面:失败印记物理上不可能压住一个真活着的 peer。成功不落盘
22
23
  # (成功缓存会在 core 硬重启后的僵尸窗口把连接挂死 banner 等待,OpenSSH 无
23
24
  # banner 超时);只有失败写印记,方向安全。
@@ -32,15 +33,6 @@ RM=${RM:-/bin/rm}
32
33
  SLEEP=${SLEEP:-/bin/sleep}
33
34
  LAUNCHCTL=${LAUNCHCTL:-/bin/launchctl}
34
35
  LSOF=${LSOF:-/usr/sbin/lsof}
35
- # edge 生产是 macOS lockf;同脚本在 Linux 跑时用 util-linux flock,接口差异
36
- # 收在 lock_try,不引第三方锁包。
37
- if [ -x /usr/bin/lockf ]; then
38
- LOCK_BACKEND=lockf
39
- elif [ -x /usr/bin/flock ]; then
40
- LOCK_BACKEND=flock
41
- else
42
- LOCK_BACKEND=none
43
- fi
44
36
  STATE_DIR=${SSH_NET_STATE_DIR:-$HOME/.ssh/ssh-net/state}
45
37
  SSH_NET_DIR=${SSH_NET_DIR:-$HOME/.ssh/ssh-net}
46
38
  BIN_DIR=${SSH_NET_BIN_DIR:-$SSH_NET_DIR/bin}
@@ -84,12 +76,12 @@ say() {
84
76
  [ -t 2 ] && printf '%s\n' "$*" >&2
85
77
  return 0
86
78
  }
79
+ # 锁后端:edge 生产是 macOS lockf,同脚本在 Linux 跑时用 util-linux flock,不引第三方
80
+ # 锁包。拿不到锁一律非 0(flock 不存在、执行失败时也一样):没有锁就不能报名。
81
+ # 报错进 /dev/null:非终端下 stderr 必须保持零输出
87
82
  lock_try() {
88
- case "$LOCK_BACKEND" in
89
- lockf) /usr/bin/lockf -s -t 0 9 ;;
90
- flock) /usr/bin/flock -n 9 ;;
91
- *) return 1 ;;
92
- esac
83
+ if [ -x /usr/bin/lockf ]; then /usr/bin/lockf -s -t 0 9
84
+ else /usr/bin/flock -n 9 2>/dev/null; fi
93
85
  }
94
86
 
95
87
  # 失败印记新鲜判定:$1=文件 $2=TTL;整份内容只许一个 epoch,空/非数/超龄=不新鲜
@@ -216,7 +208,12 @@ clear_stalled_listener() {
216
208
  callback_enabled || exit 1
217
209
  case $rc in
218
210
  0) ;;
219
- 124|137) fail_relay ;;
211
+ 124|137)
212
+ # 本机诊断超时不是对端失败:清掉 FORCE 越过的旧印记,下条自动连接可立即报名
213
+ "$RM" -f "$STATE_DIR/PROBE_FAIL" 2>/dev/null || true
214
+ say "本机监听查询超时,本次选择中继($peer)"
215
+ exit 1
216
+ ;;
220
217
  *) holders='' ;;
221
218
  esac
222
219
  # 查进程期间可能已有健康回拨接管了端口。复用它,避免断开刚恢复的连接
@@ -241,7 +238,7 @@ announce_now() {
241
238
  fi
242
239
  fail_relay
243
240
  fi
244
- if [ "$probe_result" = 2 ]; then clear_stalled_listener "$timeout"; fi
241
+ if [ "$probe_result" = 2 ] && [ "$ROUTE_FORCE" = 1 ]; then clear_stalled_listener "$timeout"; fi
245
242
  callback_enabled || exit 1
246
243
  update_budget || fail_relay
247
244
  say "直连暂不可用,正在经中继请 $peer 连过来…"
@@ -271,13 +268,14 @@ show_announce_error() {
271
268
  }
272
269
 
273
270
  # 回拨建立后的本地动作,仅由本次报名的 leader 在等到新回拨时执行一次:
274
- # ① 只向在跑的 link 发 TERM。launchd 的 PathState 按 RELAY_ON 决定是否重连,
275
- # 即使 stop 恰好在检查之后返回,这个动作也无法启动已停的转发
271
+ # ① 其他连接发起时才向在跑的 link 发 TERM。launchd 按 RELAY_ON 决定是否重连;
272
+ # link 自己发起时已有这条新连接可用,跳过多余重启。stop 后的检查与发信号
273
+ # 之间即使有竞态,RELAY_ON 不在也不会重新启动转发
276
274
  # ② 桌面通知「直连已就绪」——terminal-notifier 优先,缺它 osascript 兜底;
277
275
  # 纯本地调用、恒 0、绝不拖选路。非 tty(VS Code/scp)也弹,正是非交互
278
276
  # 场景唯一可见的反馈
279
277
  peer_ready() {
280
- if [ -e "$STATE_DIR/RELAY_ON" ]; then
278
+ if [ -e "$STATE_DIR/RELAY_ON" ] && [ "${SSH_NET_FROM_LINK:-}" != 1 ]; then
281
279
  "$LAUNCHCTL" kill TERM \
282
280
  "gui/$EUID/local.ssh-net-link-core-$peer" 2>/dev/null || true
283
281
  fi
@@ -331,13 +329,12 @@ while :; do
331
329
  probe_in_budget
332
330
  probe_rc=$?
333
331
  if [ "$probe_rc" = 0 ]; then
334
- # follower 只复用回拨,由报名的 leader 让 link 重连并发通知。
332
+ # follower 只复用回拨,由报名的 leader 切换旧 link 并发通知。
335
333
  # 副作用 detach 到子 shell 做:terminal-notifier 缺装
336
334
  # 走 osascript,它可能卡在 TCC 授权/通知中心挂起,|| true 只兜失败
337
335
  # 不兜挂起——选路已经判成功,绝不能让收尾外部程序拖住 Match exec;
338
- # peer_ready 内先通知旧转发退出,通知挂起也不会丢本次 link 秒切
336
+ # fd9 不带入,通知不会继承报名锁
339
337
  if [ "$role" = leader ]; then
340
- # 转发自己发起选路时,launchd 会随旧 SSH 一起清理同进程组的子进程
341
338
  ( trap - EXIT TERM INT; set -m; peer_ready & disown ) </dev/null >/dev/null 2>&1 9>&-
342
339
  fi
343
340
  say "直连已恢复"
@@ -2,11 +2,13 @@
2
2
  # edge 上的本地转发任务。plist 给齐 ssh 参数(-N、-L 转发口、选项、对端别名),
3
3
  # 直接 exec ssh,让停止任务的信号送到持有转发口的进程
4
4
  #
5
- # 报名不在这里做:ssh 建连命中 routes Match,判决块的 sn-route 已经按需报名;
6
- # ssh 退出后 launchd(PathState 盯 RELAY_ON)重拉时重新选路,peer 恢复后由
7
- # sn-route 通知旧转发退出,launchd 按同一开关重连。SSH 可注入只供测试。
5
+ # 报名不在这里做:ssh 建连命中 routes Match,判决块的 sn-route 已经按需报名。
6
+ # 其他连接恢复 peer 后由 sn-route 通知旧转发退出重连;本脚本自己发起时通过
7
+ # 本地标记跳过这次多余重启,新连接直接使用刚建好的回拨。SSH 可注入只供测试。
8
8
  set -u
9
9
  LC_ALL=C
10
10
  export LC_ALL
11
11
  SSH=${SSH:-/usr/bin/ssh}
12
+ SSH_NET_FROM_LINK=1
13
+ export SSH_NET_FROM_LINK
12
14
  exec "$SSH" "$@"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ssh-net",
3
- "version": "26.11.66",
3
+ "version": "26.11.68",
4
4
  "type": "module",
5
5
  "description": "个人 SSH 组网:IPv6 直连优先,中继自动兜底,断开后有界重试、按需恢复",
6
6
  "bin": {
@@ -8,6 +8,7 @@
8
8
  },
9
9
  "files": [
10
10
  "libexec",
11
+ "docs",
11
12
  "CHANGELOG.md"
12
13
  ],
13
14
  "scripts": {