ssh-net 26.10.33 → 26.10.35

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.
@@ -1,7 +1,7 @@
1
1
  // 渲染唯一来源(design §2.3、§4.2、§6.1、§6.2):
2
2
  // - plist/systemd unit:每机差异只以位置参数出现(端口、别名、user、转发列表)
3
- // - conf.d 片段:routes(edge 选路 Match)、vscode-mark(edge 上 VS Code 连接打标)
4
- // 与 edge-<别名>(core 上的 edge 入口)
3
+ // - conf.d 片段:routes(edge 选路 Match + 尾部 VS Code 打标块)与
4
+ // edge-<别名>(core 上的 edge 入口)
5
5
  // 纯字符串函数;渲染快照测试钉死输出;结构性断言(XML 闭合、只绑环回)在测试侧另查。
6
6
  import { CALLBACK_PORT } from './constants.mjs';
7
7
 
@@ -75,6 +75,22 @@ const ROUTES_HEADER = `# 本文件由 \`ssh-net install\` 从 ~/.ssh/ssh-net/top
75
75
  # relay 兜底。User 不写——由主 config 的 Host 块补。
76
76
  `;
77
77
 
78
+ /**
79
+ * sn-route 的冻结位置参数(design §2.3 argv 契约):
80
+ * <self> <core> <relay> <core 注册口> <core 用户> <show|quiet>
81
+ * routes 渲染与 doctor 喂参的唯一生产点,两边改一处即可。
82
+ * @param {import('./config.mjs').Topology} topo
83
+ * @param {string} selfAlias 本机 edge 规范别名(sn-route 报名 RPC 的自称)
84
+ * @param {'show'|'quiet'} ui
85
+ * @returns {string[]}
86
+ */
87
+ export function snRouteArgv(topo, selfAlias, ui) {
88
+ return [
89
+ selfAlias, topo.core.alias, topo.relay.alias,
90
+ String(topo.core.relayPort), topo.core.user, ui,
91
+ ];
92
+ }
93
+
78
94
  /**
79
95
  * edge 选路片段 conf.d/routes 的唯一渲染来源。值全部来自 topology + 冻结常量,
80
96
  * 不出现任何真实 IP(环回口 + relay 别名)。
@@ -89,11 +105,25 @@ export function renderRoutes(topo, selfAlias) {
89
105
  const blocks = [];
90
106
 
91
107
  // sn-route argv 直接渲染进 Match(无配置文件中转);peer 块 show(终端可见
92
- // 进度)、relay 块 quiet(第二次调用零输出)
93
- const routeArgs = (ui) =>
94
- `${snRoute} ${selfAlias} ${topo.core.alias} ${topo.relay.alias} '${topo.core.relayPort}' ${topo.core.user} ${ui}`;
108
+ // 进度)、relay 块 quiet(第二次调用零输出)。端口加引号是 shell 渲染层,
109
+ // argv 契约本身在 snRouteArgv
110
+ const routeArgs = (ui) => {
111
+ const argv = snRouteArgv(topo, selfAlias, ui);
112
+ argv[3] = `'${argv[3]}'`;
113
+ return `${snRoute} ${argv.join(' ')}`;
114
+ };
95
115
  const match = (alias, cond) =>
96
116
  `Match originalhost ${alias} exec "test -e ${state}/RELAY_ON${cond}"`;
117
+ // 经 relay 的兜底 Host 块(core 失败兜底与 node 常态同构):环回口 + 注册口
118
+ // + ProxyJump,差异只在注释与 Match 条件
119
+ const relayBlock = (alias, port, comment, cond) => [
120
+ `# ${alias}:${comment}`,
121
+ match(alias, cond),
122
+ ' HostName 127.0.0.1',
123
+ ` Port ${port}`,
124
+ ` ProxyJump ${topo.relay.alias}`,
125
+ ` HostKeyAlias ${alias}`,
126
+ ].join('\n');
97
127
 
98
128
  // core:peer 一跳(sn-route 按需确保成功:回拨落在本机 [::1]:10022)
99
129
  blocks.push([
@@ -104,26 +134,15 @@ export function renderRoutes(topo, selfAlias) {
104
134
  ` HostKeyAlias ${topo.core.alias}`,
105
135
  ].join('\n'));
106
136
  // core:relay 兜底(与上块互斥:sn-route 失败本块才成立)
107
- blocks.push([
108
- `# ${topo.core.alias}:relay 兜底(无 v6/确保失败/预算超时)`,
109
- match(topo.core.alias, ` && ! ${routeArgs('quiet')}`),
110
- ' HostName 127.0.0.1',
111
- ` Port ${topo.core.relayPort}`,
112
- ` ProxyJump ${topo.relay.alias}`,
113
- ` HostKeyAlias ${topo.core.alias}`,
114
- ].join('\n'));
137
+ blocks.push(relayBlock(
138
+ topo.core.alias, topo.core.relayPort,
139
+ 'relay 兜底(无 v6/确保失败/预算超时)',
140
+ ` && ! ${routeArgs('quiet')}`,
141
+ ));
115
142
 
116
143
  // node:只有 relay(无公网入站)
117
- for (const n of topo.nodes) {
118
- blocks.push([
119
- `# ${n.alias}:relay(node 无公网入站)`,
120
- match(n.alias, ''),
121
- ' HostName 127.0.0.1',
122
- ` Port ${n.relayPort}`,
123
- ` ProxyJump ${topo.relay.alias}`,
124
- ` HostKeyAlias ${n.alias}`,
125
- ].join('\n'));
126
- }
144
+ for (const n of topo.nodes)
145
+ blocks.push(relayBlock(n.alias, n.relayPort, 'relay(node 无公网入站)', ''));
127
146
 
128
147
  // VS Code 打标块(与目标无关,对所有 VS Code 发起的连接生效):扩展宿主
129
148
  // 进程有 VSCODE_IPC_HOOK;集成终端里手动 ssh 只有 VSCODE_IPC_HOOK_CLI、
@@ -143,20 +162,56 @@ export function renderRoutes(topo, selfAlias) {
143
162
  * core 上的 edge 在线入口片段 conf.d/edge-<规范别名>。Host 模式给全部别名:
144
163
  * 规范名(ssh-net 内部用,如 edge1)在前,给人用的短名(如 e1)在后,
145
164
  * `ssh edge1` 与 `ssh e1` 等价;文件/state/job 命名只用规范名。
146
- * @param {{alias:string, aliases?:string[], user:string, v6:string}} opts
165
+ * @param {{alias:string, aliases:string[], user:string, v6:string}} opts
147
166
  * @returns {string}
148
167
  */
149
168
  export function renderEdgeHost({ alias, aliases, user, v6 }) {
150
- const patterns = aliases && aliases.length > 0 ? aliases.join(' ') : alias;
151
169
  return `# 本文件由 ssh-net 维护:core 收到 ${alias} 的报名时写入,回拨 job 休眠
152
170
  # (edge 关机/不可达,六连败)或 uninstall 时删除。存在即 edge 当前在线、
153
171
  # 其上报 v6 可拨;勿手改(改了下次报名也会被覆盖)。
154
- Host ${patterns}
172
+ Host ${aliases.join(' ')}
155
173
  User ${user}
156
174
  HostName ${v6}
157
175
  `;
158
176
  }
159
177
 
178
+ // ---- 经 relay 拨 core 环回口的 ssh argv(报名 RPC 与 status 探测共用)----
179
+
180
+ /**
181
+ * 命令行显式 -J 经 relay 拨 core 注册口的公共 argv(design §4.3):字面目标
182
+ * 127.0.0.1 不命中 Match 选路、跳板地址/用户仍读 ssh config 的 Host 块、
183
+ * HostKeyAlias 保证多路径同一条 known_hosts。两个调用方只在分歧项上显式传参:
184
+ * 报名无人值守首连要 accept-new(探测侧不接受新 host key)、各自超时与远端命令。
185
+ * @param {import('./config.mjs').Topology} topo
186
+ * @param {object} [opts]
187
+ * @param {number} [opts.connectTimeout=5]
188
+ * @param {boolean} [opts.acceptHost=false] 加 StrictHostKeyChecking=accept-new
189
+ * @param {string} [opts.remoteCommand] 给了就追加为远端命令
190
+ * @param {readonly string[]} [opts.extraOpts] 追加的额外 -o 选项(成对追加)
191
+ * @returns {string[]}
192
+ */
193
+ export function coreViaRelayArgs(topo, {
194
+ connectTimeout = 5,
195
+ acceptHost = false,
196
+ remoteCommand,
197
+ extraOpts = [],
198
+ } = {}) {
199
+ const args = [
200
+ '-J', topo.relay.alias,
201
+ '-p', String(topo.core.relayPort),
202
+ '-o', `HostKeyAlias=${topo.core.alias}`,
203
+ '-o', 'BatchMode=yes',
204
+ '-o', `ConnectTimeout=${connectTimeout}`,
205
+ '-o', 'ControlMaster=no', '-o', 'ControlPath=none',
206
+ '-o', 'IdentitiesOnly=yes',
207
+ ];
208
+ if (acceptHost) args.push('-o', 'StrictHostKeyChecking=accept-new');
209
+ args.push(...extraOpts);
210
+ args.push(`${topo.core.user}@127.0.0.1`);
211
+ if (remoteCommand !== undefined) args.push(remoteCommand);
212
+ return args;
213
+ }
214
+
160
215
  // ---- 三种 LaunchAgent plist ----
161
216
 
162
217
  // link job 的 launchd 重连间隔(2026-10-02):纯 ssh 形态下 ssh 退出即 job
@@ -10,6 +10,7 @@
10
10
  import fs from 'node:fs';
11
11
  import path from 'node:path';
12
12
  import { packageScriptPath } from './paths.mjs';
13
+ import { readFileOrNull, writeFileAtomic } from './fsutil.mjs';
13
14
  import pkg from '../../package.json' with { type: 'json' };
14
15
 
15
16
  export const RUNTIME_VERSION = pkg.version;
@@ -22,12 +23,7 @@ export const RUNTIME_VERSION = pkg.version;
22
23
  */
23
24
  export function ensureScript(dstPath, srcPath) {
24
25
  const src = fs.readFileSync(srcPath);
25
- let cur = null;
26
- try {
27
- cur = fs.readFileSync(dstPath);
28
- } catch (err) {
29
- if (err.code !== 'ENOENT') throw err;
30
- }
26
+ const cur = readFileOrNull(dstPath, null);
31
27
  if (cur !== null && cur.equals(src)) {
32
28
  // 内容对但可执行位丢了(cp/同步工具吃掉 mode):补上
33
29
  if (fs.statSync(dstPath).mode & 0o111) return 'unchanged';
@@ -35,10 +31,7 @@ export function ensureScript(dstPath, srcPath) {
35
31
  return 'repaired';
36
32
  }
37
33
  // 缺失或旧内容:tmp+rename 原子换(rename 直接替换目录项)
38
- const tmp = `${dstPath}.tmp-${process.pid}`;
39
- fs.writeFileSync(tmp, src, { mode: 0o755 });
40
- fs.renameSync(tmp, dstPath);
41
- fs.chmodSync(dstPath, 0o755);
34
+ writeFileAtomic(dstPath, src, { mode: 0o755 });
42
35
  return cur !== null ? 'updated' : 'created';
43
36
  }
44
37
 
@@ -100,17 +93,9 @@ export function ensureRuntime(ctx, entries, links = []) {
100
93
 
101
94
  /** 刷新版本戳(ensureRuntime 尾部) */
102
95
  function refreshStamp(ctx) {
103
- const stamp = `${RUNTIME_VERSION}\n`;
104
96
  const stampPath = ctx.paths.runtimeVersionFile;
105
- let cur = null;
106
- try {
107
- cur = fs.readFileSync(stampPath, 'utf8');
108
- } catch { cur = null; }
109
- if (cur !== stamp) {
110
- const tmp = `${stampPath}.tmp-${process.pid}`;
111
- fs.writeFileSync(tmp, stamp, { mode: 0o644 });
112
- fs.renameSync(tmp, stampPath);
113
- }
97
+ if (readFileOrNull(stampPath) !== `${RUNTIME_VERSION}\n`)
98
+ writeFileAtomic(stampPath, `${RUNTIME_VERSION}\n`);
114
99
  }
115
100
 
116
101
  /**
@@ -162,12 +147,10 @@ export function auditLink(linkPath, entityName) {
162
147
  * @returns {string | null}
163
148
  */
164
149
  export function readRuntimeVersion(paths) {
165
- try {
166
- const v = fs.readFileSync(paths.runtimeVersionFile, 'utf8').trim();
167
- return v.length > 0 ? v : null;
168
- } catch {
169
- return null;
170
- }
150
+ const v = readFileOrNull(paths.runtimeVersionFile);
151
+ if (v === null) return null;
152
+ const trimmed = v.trim();
153
+ return trimmed.length > 0 ? trimmed : null;
171
154
  }
172
155
 
173
156
  /**
@@ -13,7 +13,6 @@
13
13
  /**
14
14
  * @typedef {Object} StaticHost
15
15
  * @property {string} [hostname] HostName;缺省时 ssh 以别名为地址
16
- * @property {string} [user] User
17
16
  */
18
17
 
19
18
  const GLOB_CHARS = new Set(['*', '?', '!']);
@@ -35,10 +34,6 @@ export function parseStaticHosts(text) {
35
34
  let currentPatterns = [];
36
35
  let inMatch = false;
37
36
 
38
- const putFirst = (host, key, value) => {
39
- if (host[key] === undefined) host[key] = value;
40
- };
41
-
42
37
  for (const raw of text.split('\n')) {
43
38
  const line = raw.trim();
44
39
  if (line.length === 0 || line.startsWith('#')) continue;
@@ -53,7 +48,7 @@ export function parseStaticHosts(text) {
53
48
  if (keyword === 'host') {
54
49
  inMatch = false;
55
50
  // 精确模式入表(多模式逐个);同一别名多个 Host 块时 ssh 取首次值——
56
- // 已存在的记录对象继续沿用,putFirst 保证不被后块覆盖
51
+ // 已存在的记录对象继续沿用,首次值写入不被后块覆盖
57
52
  currentPatterns = cols.slice(1).filter(isExactPattern);
58
53
  for (const p of currentPatterns) {
59
54
  if (!table.has(p)) table.set(p, {});
@@ -61,11 +56,13 @@ export function parseStaticHosts(text) {
61
56
  continue;
62
57
  }
63
58
  if (inMatch || currentPatterns.length === 0) continue;
64
- if (keyword === 'hostname' || keyword === 'user') {
59
+ if (keyword === 'hostname') {
65
60
  const value = cols.slice(1).join(' ');
66
61
  if (value) {
67
- for (const p of currentPatterns)
68
- putFirst(table.get(p), keyword === 'hostname' ? 'hostname' : 'user', value);
62
+ for (const p of currentPatterns) {
63
+ const host = table.get(p);
64
+ if (host.hostname === undefined) host.hostname = value;
65
+ }
69
66
  }
70
67
  }
71
68
  }
@@ -6,6 +6,7 @@
6
6
  // 目录 0700、文件 0600,写 v6 走 tmp+rename 防报名写入与 uplink-edge 读到半截。
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
+ import { readFileOrNull, writeFileAtomic } from './fsutil.mjs';
9
10
 
10
11
  const SWITCH_NAMES = ['relay', 'peer'];
11
12
 
@@ -18,7 +19,6 @@ const SWITCH_NAMES = ['relay', 'peer'];
18
19
  * @property {(alias: string) => string | null} readEdgeV6
19
20
  * @property {(alias: string, v6: string) => void} writeEdgeV6
20
21
  * @property {(alias: string) => void} removeEdgeV6 不存在时静默
21
- * @property {() => void} removeAllEdges
22
22
  */
23
23
 
24
24
  /**
@@ -29,8 +29,6 @@ const SWITCH_NAMES = ['relay', 'peer'];
29
29
  * @returns {StateStore}
30
30
  */
31
31
  export function createStateStore({ stateDir, switchFiles, edgesDir }) {
32
- const files = switchFiles;
33
-
34
32
  const ensureState = () => {
35
33
  fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
36
34
  };
@@ -43,7 +41,7 @@ export function createStateStore({ stateDir, switchFiles, edgesDir }) {
43
41
  return {
44
42
  isOn(name) {
45
43
  assertNames([name]);
46
- return fs.existsSync(files[name]);
44
+ return fs.existsSync(switchFiles[name]);
47
45
  },
48
46
 
49
47
  setOn(names) {
@@ -51,9 +49,9 @@ export function createStateStore({ stateDir, switchFiles, edgesDir }) {
51
49
  ensureState();
52
50
  for (const n of names) {
53
51
  // 'a':不截断、已存在不报错(touch 语义)
54
- const fd = fs.openSync(files[n], 'a');
52
+ const fd = fs.openSync(switchFiles[n], 'a');
55
53
  fs.closeSync(fd);
56
- fs.chmodSync(files[n], 0o600);
54
+ fs.chmodSync(switchFiles[n], 0o600);
57
55
  }
58
56
  },
59
57
 
@@ -61,7 +59,7 @@ export function createStateStore({ stateDir, switchFiles, edgesDir }) {
61
59
  assertNames(names);
62
60
  for (const n of names) {
63
61
  try {
64
- fs.unlinkSync(files[n]);
62
+ fs.unlinkSync(switchFiles[n]);
65
63
  } catch (err) {
66
64
  if (err && err.code === 'ENOENT') continue;
67
65
  throw err;
@@ -71,29 +69,22 @@ export function createStateStore({ stateDir, switchFiles, edgesDir }) {
71
69
 
72
70
  readSwitches() {
73
71
  return {
74
- relay: fs.existsSync(files.relay),
75
- peer: fs.existsSync(files.peer),
72
+ relay: fs.existsSync(switchFiles.relay),
73
+ peer: fs.existsSync(switchFiles.peer),
76
74
  };
77
75
  },
78
76
 
79
77
  readEdgeV6(alias) {
80
- try {
81
- const v6 = fs.readFileSync(path.join(edgesDir, alias), 'utf8').trim();
82
- return v6.length > 0 ? v6 : null;
83
- } catch (err) {
84
- if (err && err.code === 'ENOENT') return null;
85
- throw err;
86
- }
78
+ const v6 = readFileOrNull(path.join(edgesDir, alias));
79
+ if (v6 === null) return null;
80
+ const trimmed = v6.trim();
81
+ return trimmed.length > 0 ? trimmed : null;
87
82
  },
88
83
 
89
84
  writeEdgeV6(alias, v6) {
90
85
  ensureState();
91
86
  fs.mkdirSync(edgesDir, { recursive: true, mode: 0o700 });
92
- const final = path.join(edgesDir, alias);
93
- const tmp = path.join(edgesDir, `.${alias}.tmp-${process.pid}`);
94
- fs.writeFileSync(tmp, `${v6}\n`, { mode: 0o600 });
95
- fs.renameSync(tmp, final);
96
- fs.chmodSync(final, 0o600);
87
+ writeFileAtomic(path.join(edgesDir, alias), `${v6}\n`, { mode: 0o600 });
97
88
  },
98
89
 
99
90
  removeEdgeV6(alias) {
@@ -104,9 +95,5 @@ export function createStateStore({ stateDir, switchFiles, edgesDir }) {
104
95
  throw err;
105
96
  }
106
97
  },
107
-
108
- removeAllEdges() {
109
- fs.rmSync(edgesDir, { recursive: true, force: true });
110
- },
111
98
  };
112
99
  }
@@ -1,6 +1,9 @@
1
1
  // node 机 systemd 编排。node 登录为 root(migration 实测前提),直接
2
2
  // systemctl、直接写 /etc/systemd/system,不包 sudo;非 root 调用由命令层拒绝。
3
3
  // Restart=always/RestartSec/StartLimitIntervalSec 在渲染的 unit 里定死。
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { readFileOrNull, writeFileAtomic } from './fsutil.mjs';
4
7
 
5
8
  /** @param {import('./exec.mjs').Runner} runner @param {string} unit 含 .service */
6
9
  const sc = (runner, args) => runner.run('systemctl', args);
@@ -28,3 +31,48 @@ export function verifyUnit(runner, unitPath) {
28
31
  // verify 对只告警也可能非零;这里把非零视为失败,命令层打印 stderr
29
32
  return { ok: r.code === 0, stdout: r.stdout, stderr: r.stderr };
30
33
  }
34
+
35
+ /**
36
+ * 停一个 unit:未加载(未装/已卸)的 not-loaded 失败放行,其余抛出。
37
+ * stop 与 uninstall 共用这条规则——真失败必须报,否则「已关闭」是谎报、
38
+ * 删了 unit 文件还会留下在跑的 ghost 进程。
39
+ * @param {import('./exec.mjs').Runner} runner
40
+ * @param {string} unit
41
+ */
42
+ export function stopIfLoaded(runner, unit) {
43
+ const r = stopUnit(runner, unit);
44
+ if (r.code !== 0 && !/not loaded/.test(r.stderr))
45
+ throw new Error(`systemctl stop 失败:${r.stderr.trim()}`);
46
+ }
47
+
48
+ /**
49
+ * 对账一个 unit 到磁盘并确保服务在跑(与 mac 侧 syncPlist 同构、对齐 design §5
50
+ * 「install 幂等不断连」):字节相同只 enable+start,不重写不 restart;内容
51
+ * 变了才 verify → 原子落盘 → daemon-reload → enable → restart。
52
+ * @param {import('./exec.mjs').Runner} runner
53
+ * @param {{unitPath:string, unitName:string, content:string}} job
54
+ * @returns {'unchanged'|'deployed'}
55
+ */
56
+ export function syncUnit(runner, { unitPath, unitName, content }) {
57
+ fs.mkdirSync(path.dirname(unitPath), { recursive: true });
58
+
59
+ if (readFileOrNull(unitPath) === content) {
60
+ for (const r of [enableUnit(runner, unitName), startUnit(runner, unitName)]) {
61
+ if (r.code !== 0) throw new Error(`systemctl 失败:${r.stderr.trim()}`);
62
+ }
63
+ return 'unchanged';
64
+ }
65
+
66
+ writeFileAtomic(unitPath, content, { mode: 0o644 });
67
+ const verify = verifyUnit(runner, unitPath);
68
+ if (!verify.ok && !verify.skipped)
69
+ throw new Error(`systemd-analyze verify 失败:\n${verify.stderr}`);
70
+ for (const r of [
71
+ daemonReload(runner),
72
+ enableUnit(runner, unitName),
73
+ restartUnit(runner, unitName),
74
+ ]) {
75
+ if (r.code !== 0) throw new Error(`systemctl 失败:${r.stderr.trim()}`);
76
+ }
77
+ return 'deployed';
78
+ }
package/libexec/sn-route CHANGED
@@ -55,8 +55,9 @@ peer_user=$5
55
55
  ui=$6
56
56
  case "$ui" in show|quiet) ;; *) exit 1 ;; esac
57
57
 
58
- start=$("$DATE" +%s)
59
- deadline=$((start + DEADLINE))
58
+ # 预算计时用 bash 内建 $SECONDS(整秒精度与 date +%s 相同,但轮询每 tick
59
+ # 不生进程);写进印记/锁的时间仍取 date epoch——那是跨进程/跨语言的契约
60
+ deadline=$((SECONDS + DEADLINE))
60
61
 
61
62
  # 进度只在 show 且 stderr 是终端时输出:VS Code/Remote-SSH 的 stderr 是管道,
62
63
  # scp、脚本调用同样自动静默。恒返回 0,输出不影响判决
@@ -64,16 +65,18 @@ say() {
64
65
  [ "$ui" = show ] && [ -t 2 ] && printf '%s\n' "$*" >&2
65
66
  return 0
66
67
  }
67
- time_left() { [ "$("$DATE" +%s)" -lt "$deadline" ]; }
68
+ time_left() { [ "$SECONDS" -lt "$deadline" ]; }
68
69
 
69
- # 印记/锁新鲜判定:$1=文件 $2=TTL;内容为 epoch,空/非数/超龄=不新鲜
70
+ # 印记/锁新鲜判定:$1=文件 $2=TTL,$3=可选当前 epoch(轮询里两处判定
71
+ # 共用一次 date);内容为 epoch,空/非数/超龄=不新鲜
70
72
  stamp_fresh() {
71
- local v
73
+ local v now
72
74
  # 不用 $(<file) 2>/dev/null:bash 3.2 下赋值后尾随重定向会让读取优化
73
75
  # 失效、把 file 当命令执行(实测)
74
76
  v=$("$CAT" "$1" 2>/dev/null) || return 1
75
77
  case "$v" in ''|*[!0-9]*) return 1 ;; esac
76
- [ $(( $("$DATE" +%s) - v )) -le "$2" ]
78
+ now=${3:-$("$DATE" +%s)}
79
+ [ $(( now - v )) -le "$2" ]
77
80
  }
78
81
 
79
82
  # banner probe 在子 shell 里做:stderr 重定向只在子内生效(主 shell 的 stderr
@@ -95,8 +98,9 @@ mark_fail() {
95
98
  local t
96
99
  t=$("$DATE" +%s) || return 0
97
100
  ( umask 077; printf '%s\n' "$t" >"$STATE_DIR/PROBE_FAIL.tmp.$$" ) 2>/dev/null || return 0
98
- "$MV" -f "$STATE_DIR/PROBE_FAIL.tmp.$$" "$STATE_DIR/PROBE_FAIL" 2>/dev/null
99
- "$RM" -f "$STATE_DIR/PROBE_FAIL.tmp.$$" 2>/dev/null
101
+ # rename 成功 tmp 即不存在,不再白 rm;rename 失败才清 tmp
102
+ "$MV" -f "$STATE_DIR/PROBE_FAIL.tmp.$$" "$STATE_DIR/PROBE_FAIL" 2>/dev/null \
103
+ || "$RM" -f "$STATE_DIR/PROBE_FAIL.tmp.$$" 2>/dev/null
100
104
  }
101
105
 
102
106
  # ── 层 1
@@ -148,10 +152,16 @@ announce_now() {
148
152
  ann_pid=$!
149
153
  }
150
154
 
155
+ # 抢锁写当前 epoch:umask 077 + set -C 保证不覆盖在干活的锁;成功返回 0。
156
+ # leader 首抢与 follower 陈旧接管同一咒语
157
+ trylock() {
158
+ ( umask 077; set -C; printf '%s\n' "$("$DATE" +%s)" >"$lock" ) 2>/dev/null
159
+ }
160
+
151
161
  # 获取锁:0=leader(创建成功),1=follower(新鲜锁);陈旧/损坏删锁重抢
152
162
  acquire() {
153
163
  while time_left; do
154
- if ( umask 077; set -C; printf '%s\n' "$("$DATE" +%s)" >"$lock" ) 2>/dev/null; then
164
+ if trylock; then
155
165
  return 0
156
166
  fi
157
167
  if stamp_fresh "$lock" "$LOCK_STALE"; then
@@ -162,9 +172,6 @@ acquire() {
162
172
  return 1
163
173
  }
164
174
 
165
- # 收尾:只有 leader 杀报名 ssh 并删锁(follower 删锁会毁掉在干活的互斥)。
166
- # kill -9 的残留由下一任的 LOCK_STALE 判定接管
167
-
168
175
  # 回拨建立后的本地副作用(仅 leader 在「本次报名换回新回拨」时调一次,
169
176
  # 见下方轮询;层 2 旧回拨直接命中不调,避免每次 ssh 都弹/都踢):
170
177
  # ① 桌面通知「直连已就绪」——terminal-notifier 优先,缺它 osascript 兜底;
@@ -193,6 +200,8 @@ peer_ready() {
193
200
  fi
194
201
  }
195
202
 
203
+ # 收尾:只有 leader 杀报名 ssh 并删锁(follower 删锁会毁掉在干活的互斥)。
204
+ # kill -9 的残留由下一任的 LOCK_STALE 判定接管
196
205
  cleanup() {
197
206
  trap - EXIT TERM INT
198
207
  if [ "$role" = leader ]; then
@@ -233,14 +242,16 @@ while time_left; do
233
242
  fi
234
243
  fi
235
244
  else
236
- if stamp_fresh "$STATE_DIR/PROBE_FAIL" "$FAIL_TTL"; then
245
+ # follower 每 tick 只取一次 epoch:失败印记与锁陈旧两处新鲜判定共用
246
+ now=$("$DATE" +%s)
247
+ if stamp_fresh "$STATE_DIR/PROBE_FAIL" "$FAIL_TTL" "$now"; then
237
248
  say "经中继连接 $peer"
238
249
  exit 1
239
250
  fi
240
251
  # leader 被 kill/卡死留下陈旧锁 → 用剩余预算接管
241
- if ! stamp_fresh "$lock" "$LOCK_STALE"; then
252
+ if ! stamp_fresh "$lock" "$LOCK_STALE" "$now"; then
242
253
  "$RM" -f "$lock" 2>/dev/null
243
- if ( umask 077; set -C; printf '%s\n' "$("$DATE" +%s)" >"$lock" ) 2>/dev/null; then
254
+ if trylock; then
244
255
  role=leader
245
256
  announce_now
246
257
  fi
@@ -23,6 +23,7 @@ RETRY_SLEEP=${SSH_NET_RETRY_SLEEP:-30}
23
23
  alias_name=$1
24
24
  user=$2
25
25
  label="local.ssh-net-uplink-edge-$alias_name"
26
+ gui_target="gui/$("$ID" -u)/$label"
26
27
  state_file="$STATE_DIR/edges/$alias_name"
27
28
 
28
29
  # 事件日志:一行一事件(design §6.2)。ssh 自身 stderr 照旧落同一文件但无
@@ -63,6 +64,15 @@ rounds=0
63
64
  # 与 _register 的写有竞态(本删晚于报名的写):报名 RPC 无条件两处同写,
64
65
  # 下一次报名即补回片段(窗口只影响人主动 ssh,不影响隧道)
65
66
  retire_host_fragment() { "$RM" -f "$CONF_DIR/edge-$alias_name" 2>/dev/null || true; }
67
+
68
+ # 休眠 = edge 当前不在线:删入口片段 + disable + exit 0(launchd 见自愿退出
69
+ # 不重拉)。state 无 v6 与六连败两条路径同构,收在这一处
70
+ hibernate() {
71
+ log "$1"
72
+ retire_host_fragment
73
+ "$LAUNCHCTL" disable "$gui_target"
74
+ exit 0
75
+ }
66
76
  while :; do
67
77
  if [ -n "${SSH_NET_MAX_ROUNDS:-}" ]; then
68
78
  rounds=$((rounds + 1))
@@ -78,10 +88,7 @@ while :; do
78
88
  # 文件缺失只可能是人工误删(休眠不删 state):disable 休眠等下次报名,
79
89
  # 不空转拨号;conf.d 入口片段照删(与休眠同款收尸,v6 都没了它必是假入口)
80
90
  if [ -z "$v6" ]; then
81
- log "state 无 v6(人工误删?)→ disable 休眠,等下次报名唤醒"
82
- retire_host_fragment
83
- "$LAUNCHCTL" disable "gui/$("$ID" -u)/$label"
84
- exit 0
91
+ hibernate "state 无 v6(人工误删?)→ disable 休眠,等下次报名唤醒"
85
92
  fi
86
93
 
87
94
  # host key 走默认 known_hosts + accept-new(2026-09-29 弃专用信任本;
@@ -116,10 +123,7 @@ while :; do
116
123
  if [ "$fails" -ge "$FAIL_LIMIT" ]; then
117
124
  # 当下零重拉靠本 exit 0(SuccessfulExit=false 只在非自愿退出时重拉);
118
125
  # disable 管加载期拦截与跨登录持久(实测矩阵见 notes)
119
- log "$FAIL_LIMIT 次快速失败 → disable 休眠(正常路径:edge 关机/合盖/不可达;等下次报名唤醒)"
120
- retire_host_fragment
121
- "$LAUNCHCTL" disable "gui/$("$ID" -u)/$label"
122
- exit 0
126
+ hibernate "$FAIL_LIMIT 次快速失败 → disable 休眠(正常路径:edge 关机/合盖/不可达;等下次报名唤醒)"
123
127
  fi
124
128
  # 后台 + wait(不是前台 sleep):wait 可被 trap 打断,前台命令要跑完
125
129
  # 才处理 TERM——30s 会把 launchd 的停 job 扣到超时被 SIGKILL(收尾逻辑
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ssh-net",
3
- "version": "26.10.33",
3
+ "version": "26.10.35",
4
4
  "type": "module",
5
5
  "description": "个人 SSH 组网:v6 直连优先、relay 兜底、关机有界重试后静默",
6
6
  "bin": {