ssh-net 26.11.3 → 26.11.66

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,18 +5,20 @@
5
5
  // 退回 @latest:标签与 view 看同一份 registry 元数据,先装再 ls 无法阻止降级。
6
6
  // 只做一轮、不轮询等待;知道目标版号时直接 update <版号>。
7
7
  //
8
- // 刻意「换装后重新 exec 新 bin」而不是在当前进程里直接调 installRun:
9
- // 当前进程加载的是旧包代码与包内路径,只有新进程才能保证 install 与刚装
10
- // 上的版本一致。
8
+ // 安装前确认 npm 会覆盖正在运行的这份包,避免切换 fnm 环境后装出第二份。
9
+ // 当前进程加载的是旧代码,换装后由新进程核对版本并运行 install。
11
10
  //
12
- // 边界:node 角色需要 root(install 写 /etc/systemd/system),先检查再动
13
- // npm,避免「包装上了、install 被拒」的半截态;core 侧已注册 edge 的
11
+ // 边界:node 先按 install 的要求核对 root 身份与 HOME,再动 npm,避免
12
+ // 「包装上了、install 被拒」的半截态;core 侧已注册 edge 的
14
13
  // uplink-edge 实体随 install 刷新,job 参数仍等各 edge 下次报名对账。
14
+ import { lstatSync, readFileSync, realpathSync } from 'node:fs';
15
+ import path from 'node:path';
16
+ import { requireNodeHome } from '../lib/identity.mjs';
15
17
  import { cmpVersion, VERSION_RE } from '../lib/version.mjs';
16
18
  import pkg from '../../package.json' with { type: 'json' };
17
19
 
18
20
  const NPM_TIMEOUT = 180_000; // 慢网络下全局装包的余量
19
- const QUERY_TIMEOUT = 60_000; // view 只读查询
21
+ const QUERY_TIMEOUT = 60_000; // npm 只读查询
20
22
  const INSTALL_TIMEOUT = 120_000;
21
23
 
22
24
  const ARG_HINT = 'update 只接受一个可选的三段数字版本号';
@@ -24,7 +26,7 @@ const NPM_NOT_FOUND = 'PATH 上找不到 npm——检查 ~/.zshenv(mac)或 .
24
26
  const BIN_NOT_FOUND = 'npm 换装后 PATH 上找不到 ssh-net(全局 bin 未生效)——新开一个 shell 或手动跑一次 ssh-net install;若反复出现,检查 fnm 的 global 包路径';
25
27
 
26
28
  /** 失败详情:stderr 优先;被信号杀(code null,典型是超时)别说成 exit null */
27
- const failWhy = (r) => r.stderr.trim()
29
+ const failWhy = (r) => r.stderr.trim() || (!r.signal && r.error?.message)
28
30
  || (r.code !== null ? `exit ${r.code}` : `被信号杀死(${r.signal ?? '未知'},多半是超时)`);
29
31
 
30
32
  /** 参数:零个或一个版号;返回 null(无参)或版号字符串 */
@@ -42,23 +44,44 @@ function parseArgs(args) {
42
44
  return version;
43
45
  }
44
46
 
45
- /** ref 为具体版号;统一带 --prefer-online 跳过缓存元数据 */
46
- const npmInstall = (runner, ref) =>
47
- runner.run('npm', ['install', '-g', `ssh-net@${ref}`, '--prefer-online'], { timeout: NPM_TIMEOUT });
47
+ function runNpm(runner, args, timeout = QUERY_TIMEOUT) {
48
+ const r = runner.run('npm', args, { timeout });
49
+ if (r.error?.code === 'ENOENT') throw new Error(NPM_NOT_FOUND);
50
+ return r;
51
+ }
48
52
 
49
53
  /** 问 registry 当前最新版号;查不到或输出不合法返回 null(调用方停止升级) */
50
54
  const npmLatest = (runner) => {
51
- const r = runner.run('npm', ['view', 'ssh-net', 'version', '--prefer-online'], { timeout: QUERY_TIMEOUT });
52
- if (r.error && r.error.code === 'ENOENT')
53
- throw new Error(NPM_NOT_FOUND);
55
+ const r = runNpm(runner, ['view', 'ssh-net', 'version', '--prefer-online']);
54
56
  const v = r.code === 0 ? r.stdout.trim() : '';
55
57
  return VERSION_RE.test(v) ? v : null;
56
58
  };
57
59
 
60
+ function checkNpmTarget({ runner, packageDir = new URL('../../', import.meta.url) }) {
61
+ const r = runNpm(runner, ['root', '-g']);
62
+ if (r.code !== 0)
63
+ throw new Error(`npm root -g 查询失败,未执行安装:${failWhy(r)}`);
64
+ const root = r.stdout.trim();
65
+ if (!path.isAbsolute(root))
66
+ throw new Error('npm root -g 未返回全局目录的绝对路径,未执行安装');
67
+
68
+ const target = path.join(root, pkg.name);
69
+ const current = realpathSync.native(packageDir);
70
+ const mismatch = `npm 安装目标 ${target} 与当前运行的 ssh-net 目录 ${current} 不一致,未执行安装——请切换到安装这份 ssh-net 的 Node.js 环境后重试`;
71
+ // macOS 与 Linux 的全局目录都是 <prefix>/lib/node_modules。固定 fnm 当前指向的真实 prefix,
72
+ // 检查与安装都使用它,避免两次 npm 调用之间切版本而换错包
73
+ if (!path.resolve(root).endsWith('/lib/node_modules') || !lstatSync(target, { throwIfNoEntry: false }))
74
+ throw new Error(mismatch);
75
+ const prefix = realpathSync.native(path.resolve(root, '../..'));
76
+ const pinned = path.join(prefix, 'lib', 'node_modules', pkg.name);
77
+ if (!lstatSync(pinned, { throwIfNoEntry: false })?.isDirectory() || realpathSync.native(pinned) !== current)
78
+ throw new Error(mismatch);
79
+ return prefix;
80
+ }
81
+
58
82
  export async function run(ctx, args = []) {
59
83
  const target = parseArgs(args);
60
- if (ctx.role === 'node' && ctx.uid !== 0)
61
- throw new Error('node 上升级需要 root(install 要写 /etc/systemd/system),请运行 sudo -i ssh-net update');
84
+ if (ctx.role === 'node') requireNodeHome(ctx, 'update');
62
85
 
63
86
  const { runner, progress } = ctx;
64
87
 
@@ -76,12 +99,11 @@ export async function run(ctx, args = []) {
76
99
  resolved = latest;
77
100
  }
78
101
 
102
+ const prefix = checkNpmTarget(ctx);
79
103
  progress(`正在安装 ssh-net@${resolved}…`);
80
- const r = npmInstall(runner, resolved);
81
- if (r.error && r.error.code === 'ENOENT')
82
- throw new Error(NPM_NOT_FOUND);
104
+ const r = runNpm(runner, ['install', '-g', `ssh-net@${resolved}`, '--prefer-online', '--prefix', prefix], NPM_TIMEOUT);
83
105
  if (r.code !== 0)
84
- throw new Error(`npm 安装 ${resolved} 失败:${failWhy(r)}(已装的版本不受影响;网络或 registry 问题稍后重试,知道目标版号可直接 ssh-net update <版本号>)`);
106
+ throw new Error(`npm 安装 ${resolved} 失败:${failWhy(r)}(请用 ssh-net --version 核对当前安装,网络或 registry 恢复后可重试同一版本)`);
85
107
 
86
108
  // 版号地址 code 0 即装上该版;先核对 PATH 选中的 bin,再让它跑 install。
87
109
  // 多全局安装时,npm 更新的目录不一定排在 PATH 首位;旧 bin 成功退出也不代表
@@ -95,8 +117,14 @@ export async function run(ctx, args = []) {
95
117
  if (actual !== resolved)
96
118
  throw new Error(`npm 包已切换到 ${resolved},但 PATH 上的 ssh-net 版本是 ${actual || '未知'},已停止收尾——用 which -a ssh-net 检查 PATH,再手动运行 ssh-net install`);
97
119
 
98
- const inst = runner.run('ssh-net', ['install'], { timeout: INSTALL_TIMEOUT });
99
- if (inst.error && inst.error.code === 'ENOENT') throw new Error(BIN_NOT_FOUND);
120
+ // PATH 上另一份同版包(例如 npm link 的源码)也能通过版号检查。收尾必须使用刚写入的 bin
121
+ const dir = path.join(prefix, 'lib', 'node_modules', pkg.name);
122
+ const installed = JSON.parse(readFileSync(path.join(dir, 'package.json'), 'utf8'));
123
+ if (installed.version !== resolved)
124
+ throw new Error(`npm 安装目录里的版本是 ${installed.version},与目标 ${resolved} 不一致,已停止收尾`);
125
+ const bin = typeof installed.bin === 'string' ? installed.bin : installed.bin?.[pkg.name];
126
+ if (!bin) throw new Error(`ssh-net@${resolved} 缺少命令入口,无法运行 install`);
127
+ const inst = runner.runRaw(path.resolve(dir, bin), ['install'], { timeout: INSTALL_TIMEOUT });
100
128
  if (inst.code !== 0)
101
129
  throw new Error(`npm 包已切换,但 install 刷新没成功:${failWhy(inst)}——手动跑一次 ssh-net install 修复`);
102
130
 
@@ -6,7 +6,7 @@
6
6
  // - sync 幂等:内容、权限与文件类型都正确就不动盘(不产生无意义变更)
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
- import { readFileOrNull, writeFileAtomic } from './fsutil.mjs';
9
+ import { readFileOrNull, withTempFile, writeFileAtomic } from './fsutil.mjs';
10
10
 
11
11
  /** 确保 conf.d 存在且 0700(~/.ssh/ssh-net 已由 state 侧建为 0700)。 */
12
12
  function ensureConfDir(confDir) {
@@ -18,9 +18,10 @@ function ensureConfDir(confDir) {
18
18
  * 原子同步一个 Include 片段。
19
19
  * @param {string} file 片段绝对路径(在 conf.d 内)
20
20
  * @param {string} content 完整内容
21
+ * @param {(restore:() => void) => void} [onReplace] 关联服务部署失败时恢复原来的目录项
21
22
  * @returns {boolean} 是否有变更(重写、权限或文件类型修复)
22
23
  */
23
- export function syncConfFile(file, content) {
24
+ export function syncConfFile(file, content, onReplace) {
24
25
  const dir = path.dirname(file);
25
26
  ensureConfDir(dir);
26
27
  const st = fs.lstatSync(file, { throwIfNoEntry: false }) ?? null;
@@ -36,6 +37,16 @@ export function syncConfFile(file, content) {
36
37
  // 同内容软链不是受管实体,落下原子替换为普通文件。
37
38
 
38
39
  // tmp 落 conf.d 的**上级**目录:glob conf.d/* 扫不到它
39
- writeFileAtomic(file, content, { mode: 0o600, tmpDir: path.dirname(dir) });
40
+ const tmpDir = path.dirname(dir);
41
+ const link = onReplace && st?.isSymbolicLink() ? fs.readlinkSync(file) : null;
42
+ writeFileAtomic(file, content, { mode: 0o600, tmpDir });
43
+ onReplace?.(() => {
44
+ if (link !== null) withTempFile(file, { tmpDir }, tmp => {
45
+ fs.symlinkSync(link, tmp);
46
+ fs.renameSync(tmp, file);
47
+ });
48
+ else if (existing !== null) syncConfFile(file, existing);
49
+ else fs.rmSync(file, { force: true });
50
+ });
40
51
  return true;
41
52
  }
@@ -251,19 +251,9 @@ export function parseTopology(text) {
251
251
  * @param {Map<string, {hostname?: string}>} hostTable parseStaticHosts 的产物
252
252
  */
253
253
  export function validateHostContract(topo, hostTable) {
254
- /** @type {string[]} */
255
- const missing = [];
256
- const check = (alias) => {
257
- const host = hostTable.get(alias);
258
- if (!host || !host.hostname) missing.push(alias);
259
- };
260
- check(topo.relay.alias);
261
- check(topo.core.alias);
262
- for (const n of topo.nodes) check(n.alias);
263
- for (const f of topo.forwards) {
264
- const a = f.targetAlias;
265
- if (a && a !== 'loopback' && a !== 'loopback6') check(a);
266
- }
254
+ const missing = [topo.relay, topo.core, ...topo.nodes]
255
+ .map((host) => host.alias)
256
+ .filter((alias) => !hostTable.get(alias)?.hostname);
267
257
  if (missing.length > 0)
268
258
  throw new ConfigError(
269
259
  0,
@@ -5,6 +5,9 @@
5
5
  /** core 经 -R 回拨、edge 环回上的监听端口。 */
6
6
  export const CALLBACK_PORT = 10022;
7
7
 
8
+ // edge 报名优先用系统 timeout,其次用两种默认 Homebrew 安装位置,不依赖交互 shell 的 PATH
9
+ export const TIMEOUT_SEARCH_PATH = '/usr/bin:/opt/homebrew/opt/coreutils/libexec/gnubin:/usr/local/opt/coreutils/libexec/gnubin';
10
+
8
11
  // 回连桌面通知后端(sn-route 的 peer_ready 优先 terminal-notifier、缺它走
9
12
  // osascript)。install 的可选依赖提示与 sn-route 的实际探测共用这组默认
10
13
  // 路径;shell 读不到本文件,一致性靠 constants.test 锚
@@ -12,6 +12,8 @@ const DEFAULTS = {
12
12
  systemdAnalyze: '/usr/bin/systemd-analyze',
13
13
  lsof: '/usr/sbin/lsof',
14
14
  plutil: '/usr/bin/plutil',
15
+ lockf: '/usr/bin/lockf',
16
+ flock: '/usr/bin/flock',
15
17
  ps: '/bin/ps',
16
18
  };
17
19
 
@@ -3,6 +3,13 @@
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
 
6
+ export function isExecutableFile(file) {
7
+ try {
8
+ fs.accessSync(file, fs.constants.X_OK);
9
+ return fs.statSync(file).isFile();
10
+ } catch { return false; }
11
+ }
12
+
6
13
  /**
7
14
  * 读取 UTF-8 文本,文件不存在时返回 null,其他错误照常抛出
8
15
  * @param {string} file
@@ -32,6 +39,26 @@ export function readDirOrEmpty(dir) {
32
39
  }
33
40
  }
34
41
 
42
+ /** 清理改名前的目录项。大小写不敏感的卷上,旧拼写有时仍是新服务使用的同一项 */
43
+ export function removeObsoleteNames(dir, obsolete, keep) {
44
+ if (!obsolete.length) return false;
45
+ const names = new Set(readDirOrEmpty(dir));
46
+ let changed = false;
47
+ for (const old of obsolete) {
48
+ if (!names.has(old) || keep.includes(old)) continue;
49
+ const file = path.join(dir, old);
50
+ const spelling = keep.find((name) => name.toLowerCase() === old.toLowerCase() && !names.has(name));
51
+ if (spelling && fs.lstatSync(path.join(dir, spelling), { throwIfNoEntry: false })) {
52
+ fs.renameSync(file, path.join(dir, spelling));
53
+ names.add(spelling);
54
+ } else {
55
+ fs.rmSync(file, { force: true });
56
+ }
57
+ changed = true;
58
+ }
59
+ return changed;
60
+ }
61
+
35
62
  /**
36
63
  * 读文本并 trim:不存在或只剩空白返回 null(「文件里得有值才算数」,
37
64
  * state 的 edges v6 与 runtime 的版本戳共用)。
@@ -68,8 +95,7 @@ export function withTempFile(file, { tmpDir = path.dirname(file) } = {}, fn) {
68
95
  }
69
96
 
70
97
  /**
71
- * 原子落盘:tmp 写好再 rename 落定,落定后 chmod 兜底(怪 umask/拷贝工具
72
- * 吃位都修正到 mode)。
98
+ * 原子落盘:先在临时文件上修正 umask 影响,内容和权限都准备好再替换目标
73
99
  * @param {string} file
74
100
  * @param {string|Buffer} content
75
101
  * @param {{mode?: number, tmpDir?: string}} [opts] tmpDir 给 Include 片段用:
@@ -78,7 +104,7 @@ export function withTempFile(file, { tmpDir = path.dirname(file) } = {}, fn) {
78
104
  export function writeFileAtomic(file, content, { mode = 0o644, tmpDir = path.dirname(file) } = {}) {
79
105
  return withTempFile(file, { tmpDir }, (tmp) => {
80
106
  fs.writeFileSync(tmp, content, { mode });
107
+ fs.chmodSync(tmp, mode);
81
108
  fs.renameSync(tmp, file);
82
- fs.chmodSync(file, mode);
83
109
  });
84
110
  }
@@ -31,3 +31,19 @@ export function localHostname(hostname = os.hostname()) {
31
31
  export function matchIdentity(topology, hostname = localHostname()) {
32
32
  return topology.byHostname.get(hostname) ?? null;
33
33
  }
34
+
35
+ // os.userInfo() 从系统账户记录取家目录,不受 sudo 保留的 HOME 影响
36
+ export const nodeAccountHome = (ctx) => ctx.nodeHome ?? os.userInfo().homedir;
37
+
38
+ /** 写入 node 的安装或服务前核对账户,不依赖 topology */
39
+ export function requireNodeHome(ctx, command) {
40
+ const retry = `sudo -i ssh-net ${command}`;
41
+ if (ctx.uid !== 0)
42
+ throw new Error(`操作 node 的系统服务需要 root,请运行 ${retry}`);
43
+ const home = nodeAccountHome(ctx);
44
+ if (!ctx.env.HOME || ctx.env.HOME.replace(/\/+$/, '') !== home.replace(/\/+$/, ''))
45
+ throw new Error(`HOME 与 root 账户的家目录不一致,请运行 ${retry}`);
46
+ if (['install', 'update'].includes(command) && /\s/.test(home))
47
+ throw new Error(`node 的 HOME(${home})含空白字符,当前 systemd ExecStart 无法转义,拒绝${command === 'install' ? '安装' : '升级'}`);
48
+ return home;
49
+ }
@@ -1,8 +1,8 @@
1
1
  // install 管理的服务配置装配:写盘与 status 体检共用同一份渲染输入,
2
2
  // 避免只改 plist/unit 模板时,status 因运行时脚本未变而漏报未同步升级。
3
- import os from 'node:os';
4
3
  import path from 'node:path';
5
4
  import { renderForwardArgs } from './config.mjs';
5
+ import { nodeAccountHome } from './identity.mjs';
6
6
  import {
7
7
  linkLabel, relayLabel, relayUnitName,
8
8
  renderEdgeLinkPlist, renderRelayPlist, renderRelayUnit,
@@ -45,17 +45,13 @@ export function coreRelayJob(ctx) {
45
45
  };
46
46
  }
47
47
 
48
- /** node 中继 systemd unit;home 一并返回供 install 校验 ExecStart 边界。 */
49
- export function nodeRelayJob(ctx) {
48
+ /** node 中继 systemd unit。status 只读取预期配置,不要求 root */
49
+ export function nodeRelayJob(ctx, home = nodeAccountHome(ctx)) {
50
50
  const { topo, paths } = ctx;
51
51
  const unitName = relayUnitName(topo.relay.alias);
52
- // HOME 用 root 的真实家目录(getpwuid),不取 $HOME:sudo 保留 HOME 会把
53
- // 调用者的家目录写进 unit,root 的 ssh 随之读错 config
54
- const home = ctx.nodeHome ?? os.userInfo().homedir;
55
52
  return {
56
53
  unitName,
57
54
  unitPath: path.join(paths.systemdUnitDir, unitName),
58
- home,
59
55
  content: renderRelayUnit({
60
56
  binDir: paths.binDir,
61
57
  relayAlias: topo.relay.alias,
@@ -5,42 +5,28 @@
5
5
  // - 任何 bootstrap 前无条件先 enable(override 残留时 bootstrap error 5)
6
6
  // - enable 本身不触发首发,唤醒必须 kickstart -k
7
7
  import { readDirOrEmpty } from './fsutil.mjs';
8
- import { edgeLabel } from './render.mjs';
9
8
 
10
9
  /** @param {number} uid */
11
10
  export const guiDomain = (uid) => `gui/${uid}`;
12
11
 
13
- const EDGE_PLIST_PREFIX = edgeLabel(''); // 'local.ssh-net-uplink-edge-'
14
-
15
- /** 未注册状态的固定形状(parsePrint 与两个 inspect 的未注册返回共用)。 */
12
+ /** 未注册时的查询结果,只有 inspect 额外返回禁用状态 */
16
13
  const NOT_REGISTERED_PRINT = Object.freeze(
17
14
  { registered: false, running: false, pid: null, lastExitCode: null },
18
15
  );
19
16
  const NOT_REGISTERED = Object.freeze({ disabled: false, ...NOT_REGISTERED_PRINT });
20
17
 
21
18
  /**
22
- * 磁盘 LaunchAgents 里指定前缀的 job label(卸载用;目录不存在时空)。
19
+ * 磁盘上的 job label,可按前缀筛选;目录不存在时返回空清单
23
20
  * @param {string} launchAgentsDir
24
- * @param {string} prefix
21
+ * @param {string} [prefix]
25
22
  * @returns {string[]}
26
23
  */
27
- export function labelsOnDisk(launchAgentsDir, prefix) {
24
+ export function labelsOnDisk(launchAgentsDir, prefix = '') {
28
25
  return readDirOrEmpty(launchAgentsDir)
29
26
  .filter((f) => f.startsWith(prefix) && f.endsWith('.plist'))
30
27
  .map((f) => f.slice(0, -'.plist'.length));
31
28
  }
32
29
 
33
- /**
34
- * 磁盘 LaunchAgents 里 uplink-edge job plist 的别名清单(install/status/
35
- * uninstall 共用;topology 已删的机器只能靠这个 glob 兜底发现)。
36
- * @param {string} launchAgentsDir
37
- * @returns {string[]}
38
- */
39
- export function edgeAliasesOnDisk(launchAgentsDir) {
40
- return labelsOnDisk(launchAgentsDir, EDGE_PLIST_PREFIX)
41
- .map((label) => label.slice(EDGE_PLIST_PREFIX.length));
42
- }
43
-
44
30
  /**
45
31
  * print 正文解析。
46
32
  * @param {{code:number|null, stderr:string, stdout:string}} result
@@ -92,7 +78,7 @@ export function parseDisabled(stdout) {
92
78
 
93
79
  /**
94
80
  * 整个 gui 域的 disabled override 字典(一次 print-disabled)。同一域多个
95
- * label 体检时循环外取一次、inspectWith 共用——全域 dump 与查哪个 label 无关。
81
+ * label 体检时可在循环外取一次,交给各次 inspect 共用
96
82
  * @param {import('./exec.mjs').Runner} runner
97
83
  * @param {number} uid
98
84
  * @returns {Map<string, boolean>}
@@ -108,32 +94,17 @@ export function disabledMap(runner, uid) {
108
94
  }
109
95
 
110
96
  /**
111
- * print + 预取字典合成四态(inspect 的 map 注入版;字典由调用方循环外取一次
112
- * 共用)。print 先行:未注册不碰传入 map。
113
- * @param {import('./exec.mjs').Runner} runner
114
- * @param {number} uid
115
- * @param {string} label
116
- * @param {Map<string, boolean>} map disabledMap 的产物
117
- * @returns {JobState}
118
- */
119
- export function inspectWith(runner, uid, label, map) {
120
- const printed = printState(runner, uid, label, false);
121
- if (!printed.registered) return NOT_REGISTERED;
122
- return { ...printed, disabled: map.get(label) === true };
123
- }
124
-
125
- /**
126
- * print + print-disabled 合成四态所需的全部事实(单 label 便捷封装)。
127
- * print 在前、未注册即返回(不白跑全域 dump)。
97
+ * 查询一个任务的注册、运行与禁用状态。批量查询可共用同一份禁用字典
128
98
  * @param {import('./exec.mjs').Runner} runner
129
99
  * @param {number} uid
130
100
  * @param {string} label
101
+ * @param {Map<string, boolean>} [map] disabledMap 的结果
131
102
  * @returns {JobState}
132
103
  */
133
- export function inspect(runner, uid, label) {
104
+ export function inspect(runner, uid, label, map) {
134
105
  const printed = printState(runner, uid, label);
135
106
  if (!printed.registered) return NOT_REGISTERED;
136
- return { ...printed, disabled: disabledMap(runner, uid).get(label) === true };
107
+ return { ...printed, disabled: (map ?? disabledMap(runner, uid)).get(label) === true };
137
108
  }
138
109
 
139
110
  /**
@@ -141,12 +112,11 @@ export function inspect(runner, uid, label) {
141
112
  * @param {import('./exec.mjs').Runner} runner
142
113
  * @param {number} uid
143
114
  * @param {string} label
144
- * @param {boolean} [strict=true] 只有批量展示任务状态时沿用宽松解析
145
115
  * @returns {ReturnType<typeof parsePrint>}
146
116
  */
147
- export function printState(runner, uid, label, strict = true) {
117
+ export function printState(runner, uid, label) {
148
118
  const result = runner.run('launchctl', ['print', `${guiDomain(uid)}/${label}`]);
149
- if (strict && result.code !== 0 && result.code !== 113
119
+ if (result.code !== 0 && result.code !== 113
150
120
  && !/Could not find service/.test(result.stderr ?? ''))
151
121
  throw new Error(`launchctl print 失败(${label}):${result.stderr.trim() || `exit ${result.code}`}`);
152
122
  return parsePrint(result);
@@ -3,7 +3,8 @@
3
3
  // 渲染结果与现文件字节相同则不 bootout——install 幂等不断连。
4
4
  import fs from 'node:fs';
5
5
  import * as launchd from './launchd.mjs';
6
- import { readFileOrNull, withTempFile } from './fsutil.mjs';
6
+ import path from 'node:path';
7
+ import { readFileOrNull, removeObsoleteNames, withTempFile, writeFileAtomic } from './fsutil.mjs';
7
8
 
8
9
  /**
9
10
  * install 与 start 共用的任务恢复逻辑。带 PathState 的任务由 launchd 按文件状态启动
@@ -14,9 +15,19 @@ export function ensureLoaded({ runner, uid }, { label, plistPath, pathStateFile
14
15
  const st = launchd.inspect(runner, uid, label);
15
16
  // enable 本身不会首发。重新注册让 launchd 按当下开关决定,避免与 stop 抢启动
16
17
  const reloadPathState = pathStateFile && st.disabled && !st.running && fs.existsSync(pathStateFile);
17
- if (reloadPathState) bootoutJob(runner, uid, label);
18
18
  if (!st.registered || reloadPathState) {
19
- launchd.enableBootstrap(runner, uid, label, plistPath);
19
+ const wasDisabled = st.disabled || launchd.disabledMap(runner, uid).get(label) === true;
20
+ if (reloadPathState) bootoutJob(runner, uid, label);
21
+ try {
22
+ launchd.enableBootstrap(runner, uid, label, plistPath);
23
+ } catch (err) {
24
+ // enable 成功、bootstrap 失败时,下一次登录也要继续服从之前的禁用标记
25
+ if (wasDisabled && !launchd.printState(runner, uid, label).registered) {
26
+ const r = launchd.disable(runner, uid, label);
27
+ if (r.code !== 0) throw new Error(`${err.message};恢复 ${label} 的禁用状态失败:${r.stderr.trim()}`, { cause: err });
28
+ }
29
+ throw err;
30
+ }
20
31
  return;
21
32
  }
22
33
  if (st.disabled) {
@@ -31,45 +42,100 @@ export function ensureLoaded({ runner, uid }, { label, plistPath, pathStateFile
31
42
  }
32
43
 
33
44
  /**
34
- * 同步一个 plist 到磁盘并按需注册(幂等、不断连)。
45
+ * 同步一个 plist 到磁盘并按需注册。改名时等新配置就绪再撤旧任务,避免争用同一端口
35
46
  * @param {object} ctx
36
47
  * @param {{label:string, plistPath:string, content:string, pathStateFile?:string}} job
48
+ * @param {string[]} [obsolete] 本次安装要撤掉的旧任务名
49
+ * @param {{apply:Function, restore:Function}} [routes] edge 转发须与对应版本的选路片段一起启用
37
50
  * @returns {{changed:boolean, restarted?:boolean, lintError?:string}}
38
51
  * changed 只表示 plist 内容变化,服务恢复不计入;restarted 只在替换已注册
39
52
  * job 的配置时为真,用于提示可能断连
40
53
  */
41
- export function syncPlist(ctx, job) {
54
+ export function syncPlist(ctx, job, obsolete = [], routes) {
42
55
  const { label, plistPath, content } = job;
43
56
  const { runner, uid, paths } = ctx;
44
57
  fs.mkdirSync(paths.launchAgentsDir, { recursive: true });
45
58
  fs.mkdirSync(paths.logsDir, { recursive: true });
46
59
 
47
60
  const existing = readFileOrNull(plistPath);
61
+ const changed = existing !== content;
48
62
 
49
- if (existing === content) {
50
- ensureLoaded(ctx, job);
51
- return { changed: false };
52
- }
53
-
54
- // 内容变化(或首次):先 lint tmp,过了再动现文件;tmp 生命周期与原子写共用
55
- return withTempFile(plistPath, {}, (tmp) => {
56
- fs.writeFileSync(tmp, content, { mode: 0o644 });
57
- const lint = launchd.lintPlist(runner, tmp);
58
- if (lint.code !== 0)
59
- return { changed: false, lintError: lint.stderr.trim() || `plutil exit ${lint.code}` };
63
+ // plist 相同时也可能换了选路,加载失败要走同一条恢复路径
64
+ function deploy(tmp) {
65
+ if (changed) {
66
+ fs.writeFileSync(tmp, content, { mode: 0o644 });
67
+ fs.chmodSync(tmp, 0o644);
68
+ const lint = launchd.lintPlist(runner, tmp);
69
+ if (lint.code !== 0)
70
+ return { changed: false, lintError: lint.stderr.trim() || `plutil exit ${lint.code}` };
71
+ }
60
72
 
61
- // 只要 registered 一个事实:printState 即可,不跑全域 print-disabled
62
- const st = launchd.printState(runner, uid, label);
63
- if (st.registered) bootoutJob(runner, uid, label);
64
- fs.renameSync(tmp, plistPath);
65
- fs.chmodSync(plistPath, 0o644);
66
- // 无条件先 enable(override 残留时 bootstrap error 5;launchd.mjs 宣言
67
- // 「勿在此吞错」)。取舍:此处 job 已 bootout、enable 失败即不 bootstrap
68
- //(停机态)——真失败(override 数据库损坏)下 bootstrap 也过不去(error 5),
69
- // 可见性优先于「也许 bootstrap 能侥幸成功」
70
- launchd.enableBootstrap(runner, uid, label, plistPath);
71
- return { changed: true, restarted: st.registered };
72
- });
73
+ // 只改大小写时,新旧路径在默认 macOS 卷上是同一项;回滚要还原磁盘上的旧拼写
74
+ const diskNames = obsolete.length && existing !== null ? fs.readdirSync(paths.launchAgentsDir) : [];
75
+ const oldSpelling = !diskNames.includes(path.basename(plistPath)) && obsolete.find((old) =>
76
+ old.toLowerCase() === label.toLowerCase() && diskNames.includes(path.basename(paths.plistFile(old))));
77
+ const existingPath = oldSpelling ? paths.plistFile(oldSpelling) : plistPath;
78
+ const stopped = [];
79
+ let replaced = false;
80
+ let candidate;
81
+ let targetWasDisabled = false;
82
+ try {
83
+ for (const old of changed ? [...obsolete, label] : obsolete) {
84
+ const st = launchd.inspect(runner, uid, old);
85
+ if (!st.registered) {
86
+ if (old === label) targetWasDisabled = launchd.disabledMap(runner, uid).get(label) === true;
87
+ continue;
88
+ }
89
+ if (bootoutJob(runner, uid, old)) stopped.push({ label: old, disabled: st.disabled });
90
+ }
91
+ routes?.apply();
92
+ if (changed) {
93
+ candidate = fs.statSync(tmp);
94
+ fs.renameSync(tmp, plistPath);
95
+ replaced = true;
96
+ launchd.enableBootstrap(runner, uid, label, plistPath);
97
+ } else {
98
+ ensureLoaded(ctx, job);
99
+ }
100
+ } catch (err) {
101
+ // 另一条安装或报名可能已经替换文件或注册任务,失败的调用不能再撤销对方的部署
102
+ if (replaced) {
103
+ const disk = fs.lstatSync(plistPath, { throwIfNoEntry: false });
104
+ let registered;
105
+ try { registered = launchd.printState(runner, uid, label).registered; } catch (query) {
106
+ throw new AggregateError([err, query], `${err.message};回滚前查询任务失败:${query.message}`);
107
+ }
108
+ if (!disk || disk.ino !== candidate.ino || disk.dev !== candidate.dev || registered)
109
+ throw new Error(`${err.message};部署期间任务状态已改变,请用 ssh-net status 核对`, { cause: err });
110
+ }
111
+ const failures = [];
112
+ try { routes?.restore(); } catch (restore) { failures.push(restore); }
113
+ // 在册任务的 plist 可能曾被手删;这时刚校验过的新文件是唯一可用于恢复的定义
114
+ let fileReady = true;
115
+ try {
116
+ if (replaced && existing !== null) writeFileAtomic(existingPath, existing);
117
+ else if (replaced && !stopped.some(old => old.label === label)) fs.rmSync(plistPath, { force: true });
118
+ } catch (restore) { fileReady = false; failures.push(restore); }
119
+ for (const old of stopped) {
120
+ if (!fileReady && (old.label === label || old.label === oldSpelling)) continue;
121
+ try {
122
+ launchd.enableBootstrap(runner, uid, old.label, paths.plistFile(old.label));
123
+ } catch (restore) { failures.push(restore); }
124
+ }
125
+ const disabled = stopped.filter(old => old.disabled).map(old => old.label);
126
+ if (replaced && targetWasDisabled) disabled.push(label);
127
+ for (const name of disabled) {
128
+ const r = launchd.disable(runner, uid, name);
129
+ if (r.code !== 0) failures.push(new Error(`disable 失败(${name}):${r.stderr.trim()}`));
130
+ }
131
+ if (failures.length)
132
+ throw new AggregateError([err, ...failures], `${err.message};恢复旧任务失败:${failures.map(e => e.message).join(';')}`);
133
+ throw err;
134
+ }
135
+ removeObsoleteNames(paths.launchAgentsDir, obsolete.map((old) => path.basename(paths.plistFile(old))), [path.basename(plistPath)]);
136
+ return { changed, restarted: stopped.some((old) => old.label === label) };
137
+ }
138
+ return changed ? withTempFile(plistPath, {}, deploy) : deploy();
73
139
  }
74
140
 
75
141
  /**
@@ -89,4 +155,5 @@ function bootoutJob(runner, uid, label) {
89
155
  const bo = launchd.bootout(runner, uid, label);
90
156
  if (bo.code !== 0 && bo.code !== 113)
91
157
  throw new Error(`bootout 失败(${label}):${bo.stderr.trim()}`);
158
+ return bo.code === 0;
92
159
  }
@@ -6,6 +6,14 @@
6
6
  import net from 'node:net';
7
7
  import path from 'node:path';
8
8
  import { SN_PROBE } from './manifest.mjs';
9
+ import { TIMEOUT_SEARCH_PATH } from './constants.mjs';
10
+ import { isExecutableFile } from './fsutil.mjs';
11
+
12
+ /** 检查安装和本地状态所需的回拨限时工具,不运行外部命令 */
13
+ export function hasRouteTimeout(env) {
14
+ const searchPath = env.SSH_NET_TIMEOUT_PATH || TIMEOUT_SEARCH_PATH;
15
+ return searchPath.split(':').some(dir => isExecutableFile(path.join(dir, 'timeout')));
16
+ }
9
17
 
10
18
  /**
11
19
  * TCP 能否在超时内连上(status 用,mjs 侧不依赖 nc)。
@@ -72,22 +80,17 @@ export function lsofListen(runner, port) {
72
80
  return r.code === 0 ? r.stdout.trim() : '';
73
81
  }
74
82
 
75
- /**
76
- * 从 lsof 全输出解析 v6 环回([::1])监听者 pid(lsof 的 -iTCP@ 过滤对 v6
77
- * 字面量支持不稳,按行过滤)。v4 环回(127.0.0.1)上的同名端口持有者——如
78
- * VS Code 本地转发——与本服务不同地址族、可共存,不算冲突。端口后必须是
79
- * 非数字边界,否则 10022 的子串会命中 100220/100221 等无关监听。
80
- * @param {string} text lsofListen 的输出
81
- * @param {number} port
82
- * @returns {number[]}
83
- */
84
- export function v6LoopbackPids(text, port) {
85
- const portRe = new RegExp(`\\[::1\\]:${port}(?!\\d)(?:\\s|$)`);
86
- return text
87
- .split('\n')
88
- .filter((l) => portRe.test(l))
89
- .map((l) => Number(l.match(/\s(\d+)\s/)?.[1]))
90
- .filter((n) => Number.isInteger(n));
83
+ /** 回拨只能绑定 [::1]。IPv6 通配即使提供 SSH 服务也会占用回拨地址 */
84
+ export function v6ListenerScope(text, port) {
85
+ let scope = null;
86
+ for (const line of text.split('\n')) {
87
+ const fields = line.trim().split(/\s+/);
88
+ if (fields[4] !== 'IPv6') continue;
89
+ const address = fields.at(-2);
90
+ if (address === `*:${port}` || address === `[::]:${port}`) return 'wildcard';
91
+ if (address === `[::1]:${port}`) scope = 'loopback';
92
+ }
93
+ return scope;
91
94
  }
92
95
 
93
96
  /**