ssh-net 26.11.1 → 26.11.3

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.
@@ -48,9 +48,7 @@ export function edgeAliasesOnDisk(launchAgentsDir) {
48
48
  * lastExitCode:string|null}}
49
49
  */
50
50
  export function parsePrint(result) {
51
- // 0 才是在册:113 之外的非零(域缺失/launchd 异常)一律按未注册处理,
52
- // 误判成「已注册」会让 syncPlist 报 unchanged 却没在跑;按未注册走
53
- // enable+bootstrap 会以真实报错浮出
51
+ // 只有成功的查询能确认任务在册。需要区分系统故障的调用方先由 printState 检查退出码
54
52
  const registered =
55
53
  result.code === 0 && !/Could not find service/.test(result.stderr ?? '');
56
54
  if (!registered) return NOT_REGISTERED_PRINT;
@@ -119,7 +117,7 @@ export function disabledMap(runner, uid) {
119
117
  * @returns {JobState}
120
118
  */
121
119
  export function inspectWith(runner, uid, label, map) {
122
- const printed = printState(runner, uid, label);
120
+ const printed = printState(runner, uid, label, false);
123
121
  if (!printed.registered) return NOT_REGISTERED;
124
122
  return { ...printed, disabled: map.get(label) === true };
125
123
  }
@@ -139,16 +137,14 @@ export function inspect(runner, uid, label) {
139
137
  }
140
138
 
141
139
  /**
142
- * 只要注册/运行/pid 事实(stop 轮询专用):不跑全域 print-disabled。
143
- * 删除路径必须传 strict:除明确的 113/not-found 外,查询失败都当场报错,
144
- * 不能把「不知道是否注册」当成「未注册」后继续删 plist。
140
+ * 单查注册状态、运行状态与 PID。除明确未注册外,系统查询失败即报错
145
141
  * @param {import('./exec.mjs').Runner} runner
146
142
  * @param {number} uid
147
143
  * @param {string} label
148
- * @param {boolean} [strict=false]
144
+ * @param {boolean} [strict=true] 只有批量展示任务状态时沿用宽松解析
149
145
  * @returns {ReturnType<typeof parsePrint>}
150
146
  */
151
- export function printState(runner, uid, label, strict = false) {
147
+ export function printState(runner, uid, label, strict = true) {
152
148
  const result = runner.run('launchctl', ['print', `${guiDomain(uid)}/${label}`]);
153
149
  if (strict && result.code !== 0 && result.code !== 113
154
150
  && !/Could not find service/.test(result.stderr ?? ''))
@@ -163,8 +159,9 @@ export const disable = (runner, uid, label) =>
163
159
  runner.run('launchctl', ['disable', `${guiDomain(uid)}/${label}`]);
164
160
  export const bootstrap = (runner, uid, plistPath) =>
165
161
  runner.run('launchctl', ['bootstrap', guiDomain(uid), plistPath]);
162
+ // 不加 -k:若查询后任务已自行启动,绝不能打断刚建好的连接
166
163
  export const kickstart = (runner, uid, label) =>
167
- runner.run('launchctl', ['kickstart', '-k', `${guiDomain(uid)}/${label}`]);
164
+ runner.run('launchctl', ['kickstart', `${guiDomain(uid)}/${label}`]);
168
165
  /**
169
166
  * enable + bootstrap 连发(未注册 job 的加载序列)。任一步失败抛错——
170
167
  * enable 失败若吞掉,只会以 bootstrap error 5 的间接形式浮出,排障被带偏。
@@ -185,7 +182,8 @@ export function enableBootstrap(runner, uid, label, plistPath) {
185
182
  export const kickstartEnabled = (runner, uid, label) => {
186
183
  const en = enable(runner, uid, label);
187
184
  if (en.code !== 0) throw new Error(`enable 失败(${label}):${en.stderr.trim()}`);
188
- return kickstart(runner, uid, label);
185
+ // 只有收到报名时才强制换掉旧回拨,使用 edge 刚上报的地址
186
+ return runner.run('launchctl', ['kickstart', '-k', `${guiDomain(uid)}/${label}`]);
189
187
  };
190
188
  export const killJob = (runner, uid, label, signal = 'TERM') =>
191
189
  runner.run('launchctl', ['kill', signal, `${guiDomain(uid)}/${label}`]);
@@ -6,54 +6,40 @@ import * as launchd from './launchd.mjs';
6
6
  import { readFileOrNull, withTempFile } from './fsutil.mjs';
7
7
 
8
8
  /**
9
- * 确保一个在册 job 已加载可用(launchctl 四态状态机的唯一实现,实测矩阵见
10
- * launchd.mjs 头注;syncPlist 的「文件没变」分支与 `start core` 共用)。
9
+ * install 与 start 共用的任务恢复逻辑。带 PathState 的任务由 launchd 按文件状态启动
11
10
  * @param {object} ctx
12
- * @param {{label:string, plistPath:string}} job
13
- * @param {object} [opts]
14
- * @param {boolean} [opts.kickWhenStopped=false] registered+enabled 但没在跑时
15
- * 是否踢活:install 对账不踢(不断连),start 要踢
16
- * @param {boolean} [opts.reviveRunningDisabled=false] registered+disabled 但
17
- * 还在跑时是否踢重启:install 要 revive,start 只清 override、不闪断
18
- * 只执行必要的加载/恢复动作;是否有配置变化由 syncPlist 另行判断
11
+ * @param {{label:string, plistPath:string, pathStateFile?:string}} job
19
12
  */
20
- export function ensureLoaded(ctx, { label, plistPath }, {
21
- kickWhenStopped = false,
22
- reviveRunningDisabled = false,
23
- } = {}) {
24
- const { runner, uid } = ctx;
13
+ export function ensureLoaded({ runner, uid }, { label, plistPath, pathStateFile }) {
25
14
  const st = launchd.inspect(runner, uid, label);
26
- if (!st.registered) {
15
+ // enable 本身不会首发。重新注册让 launchd 按当下开关决定,避免与 stop 抢启动
16
+ const reloadPathState = pathStateFile && st.disabled && !st.running && fs.existsSync(pathStateFile);
17
+ if (reloadPathState) bootoutJob(runner, uid, label);
18
+ if (!st.registered || reloadPathState) {
27
19
  launchd.enableBootstrap(runner, uid, label, plistPath);
28
20
  return;
29
21
  }
30
- if (st.disabled && (!st.running || reviveRunningDisabled)) {
31
- const k = launchd.kickstartEnabled(runner, uid, label);
32
- if (k.code !== 0) throw new Error(`kickstart 失败(${label}):${k.stderr.trim()}`);
33
- return;
34
- }
35
22
  if (st.disabled) {
36
- // 在跑但 override 残留:只 enable 清掉,防退出后不重拉,不打断现连接
23
+ // disable 不会停掉已在跑的进程;清除标记就够了,不必断开现有连接
37
24
  const en = launchd.enable(runner, uid, label);
38
25
  if (en.code !== 0) throw new Error(`enable 失败(${label}):${en.stderr.trim()}`);
39
- return;
40
26
  }
41
- if (kickWhenStopped && !st.running) {
27
+ if (!pathStateFile && !st.running) {
42
28
  const k = launchd.kickstart(runner, uid, label);
43
29
  if (k.code !== 0) throw new Error(`kickstart 失败(${label}):${k.stderr.trim()}`);
44
- return;
45
30
  }
46
31
  }
47
32
 
48
33
  /**
49
34
  * 同步一个 plist 到磁盘并按需注册(幂等、不断连)。
50
35
  * @param {object} ctx
51
- * @param {{label:string, plistPath:string, content:string}} job
36
+ * @param {{label:string, plistPath:string, content:string, pathStateFile?:string}} job
52
37
  * @returns {{changed:boolean, restarted?:boolean, lintError?:string}}
53
38
  * changed 只表示 plist 内容变化,服务恢复不计入;restarted 只在替换已注册
54
39
  * job 的配置时为真,用于提示可能断连
55
40
  */
56
- export function syncPlist(ctx, { label, plistPath, content }) {
41
+ export function syncPlist(ctx, job) {
42
+ const { label, plistPath, content } = job;
57
43
  const { runner, uid, paths } = ctx;
58
44
  fs.mkdirSync(paths.launchAgentsDir, { recursive: true });
59
45
  fs.mkdirSync(paths.logsDir, { recursive: true });
@@ -61,11 +47,7 @@ export function syncPlist(ctx, { label, plistPath, content }) {
61
47
  const existing = readFileOrNull(plistPath);
62
48
 
63
49
  if (existing === content) {
64
- // registered+disabled(stop 中途失败/手工 disable)不是「已部署」:
65
- // enable 后拉起,否则 install 报配置未变却没在跑、start 的 kickstart 被拒
66
- ensureLoaded(ctx, { label, plistPath }, {
67
- reviveRunningDisabled: true,
68
- });
50
+ ensureLoaded(ctx, job);
69
51
  return { changed: false };
70
52
  }
71
53
 
@@ -78,11 +60,7 @@ export function syncPlist(ctx, { label, plistPath, content }) {
78
60
 
79
61
  // 只要 registered 一个事实:printState 即可,不跑全域 print-disabled
80
62
  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
- }
63
+ if (st.registered) bootoutJob(runner, uid, label);
86
64
  fs.renameSync(tmp, plistPath);
87
65
  fs.chmodSync(plistPath, 0o644);
88
66
  // 无条件先 enable(override 残留时 bootstrap error 5;launchd.mjs 宣言
@@ -95,24 +73,20 @@ export function syncPlist(ctx, { label, plistPath, content }) {
95
73
  }
96
74
 
97
75
  /**
98
- * 卸载一个 job:在册才 bootout(忽略未注册),再删 plist。
76
+ * 逐个卸载磁盘任务,在册的先 bootout,再删 plist。查询失败时保留文件
99
77
  * @param {object} ctx
100
- * @param {string} label
101
- * @param {string} plistPath
102
- * @returns {boolean} 是否在册任务或磁盘 plist 确有清理
78
+ * @param {Iterable<string>} labels
103
79
  */
104
- export function removeJob(ctx, label, plistPath) {
105
- const { runner, uid } = ctx;
106
- const existed = fs.existsSync(plistPath);
107
- // 删除路径按查询失败中止,只有明确的未注册才允许直接删 plist
108
- const st = launchd.printState(runner, uid, label, true);
109
- if (st.registered) {
110
- const bo = launchd.bootout(runner, uid, label);
111
- // 113 = 未注册(竞态下消失),其余失败必须报:job 还在注册表里,删了
112
- // plist 会留下内存态孤儿
113
- if (bo.code !== 0 && bo.code !== 113)
114
- throw new Error(`bootout 失败(${label}):${bo.stderr.trim()}`);
80
+ export function removeJobs({ runner, uid, paths }, labels) {
81
+ for (const label of labels) {
82
+ const st = launchd.printState(runner, uid, label);
83
+ if (st.registered) bootoutJob(runner, uid, label);
84
+ fs.rmSync(paths.plistFile(label), { force: true });
115
85
  }
116
- fs.rmSync(plistPath, { force: true });
117
- return st.registered || existed;
86
+ }
87
+
88
+ function bootoutJob(runner, uid, label) {
89
+ const bo = launchd.bootout(runner, uid, label);
90
+ if (bo.code !== 0 && bo.code !== 113)
91
+ throw new Error(`bootout 失败(${label}):${bo.stderr.trim()}`);
118
92
  }
@@ -1,12 +1,7 @@
1
- // 运行时实体/服务软链清单的单一来源(install 对账、报名对账与 status 体检
2
- // 共用,design §2.3)。清单即契约:新增包脚本只改这里,漏装与假报「组件
3
- // 异常」不会再分叉。
4
- //
5
- // entities:[bin 名, 包脚本名]——原名实体;links:[带机器名软链, 实体名]。
1
+ // install、报名与 status 共用的运行时清单。实体按包内原名安装;只有服务软链
2
+ // 需要两列:[带机器名的链名, 实体名](design §2.3)
6
3
  import { edgeLinkName, linkLinkName, relayLinkName } from './render.mjs';
7
4
 
8
- // bin 脚本名:plan 清单与按名判断(status 体检、install/报名调用)共用,
9
- // 改名一处。跨模块消费的只有 SN_* 与 UPLINK_EDGE,另两个仅本文件 plan 用
10
5
  export const SN_PROBE = 'sn-probe';
11
6
  export const SN_ROUTE = 'sn-route';
12
7
  export const SN_IPV6 = 'sn-ipv6';
@@ -14,71 +9,33 @@ export const SN_REGISTER_LAN = 'sn-register-lan';
14
9
  const LINK_CORE = 'ssh-net-link-core';
15
10
  const UPLINK_RELAY = 'ssh-net-uplink-relay';
16
11
  export const UPLINK_EDGE = 'ssh-net-uplink-edge';
17
- // 可能被后台 job 长期持有的实体;软链按目标名归入同一组。sn-* 按需工具
18
- // 不影响 update 的重连提示
12
+ // 只有常驻脚本的更新需要提示「下次重连后生效」
19
13
  export const RESIDENT_SCRIPTS = Object.freeze([LINK_CORE, UPLINK_RELAY, UPLINK_EDGE]);
20
14
 
21
- /**
22
- * link 附加件专属产物:第 4 实体 + 带机器名软链。edgeRuntimePlan 装了 link
23
- * 时并入;install --without-link 按这份清单删。
24
- * @param {import('./config.mjs').Topology} topo
25
- */
26
- export function linkAddonPlan(topo) {
15
+ /** @param {import('./config.mjs').Topology} topo */
16
+ export function edgeRuntimePlan(topo) {
27
17
  return {
28
- entities: [[LINK_CORE, LINK_CORE]],
18
+ entities: [SN_PROBE, SN_ROUTE, SN_IPV6, LINK_CORE],
29
19
  links: [[linkLinkName(topo.core.alias), LINK_CORE]],
30
20
  };
31
21
  }
32
22
 
33
- /**
34
- * edge 形态:基础三件套恒装;装了 link 附加件才加第 4 实体与带机器名软链。
35
- * @param {import('./config.mjs').Topology} topo
36
- * @param {boolean} linkInstalled
37
- */
38
- export function edgeRuntimePlan(topo, linkInstalled) {
39
- /** @type {[string,string][]} */
40
- const entities = [
41
- [SN_PROBE, SN_PROBE],
42
- [SN_ROUTE, SN_ROUTE], // Match exec 按需选路 + 成功后本地通知/秒切(design §2.2)
43
- [SN_IPV6, SN_IPV6],
44
- ];
45
- return linkInstalled
46
- ? mergePlans({ entities, links: [] }, linkAddonPlan(topo))
47
- : { entities, links: [] };
48
- }
49
-
50
- /**
51
- * core/node 基础形态:常驻 relay 一件套 + sn-register-lan(rc 登录调起的
52
- * edge 内网地址登记,零常驻)。installCore 在其上并入在册 edge 的回拨组件。
23
+ /** core 安装时一并刷新已登记的回拨脚本;node 只有中继与内网地址登记脚本
53
24
  * @param {import('./config.mjs').Topology} topo
25
+ * @param {readonly string[]} [registeredEdges]
54
26
  */
55
- export function coreNodeRuntimePlan(topo) {
27
+ export function coreNodeRuntimePlan(topo, registeredEdges = []) {
28
+ const callbacks = edgeCallbacksPlan(registeredEdges);
56
29
  return {
57
- entities: [
58
- [UPLINK_RELAY, UPLINK_RELAY],
59
- [SN_REGISTER_LAN, SN_REGISTER_LAN],
60
- ],
61
- links: [[relayLinkName(topo.relay.alias), UPLINK_RELAY]],
30
+ entities: [UPLINK_RELAY, SN_REGISTER_LAN, ...callbacks.entities],
31
+ links: [[relayLinkName(topo.relay.alias), UPLINK_RELAY], ...callbacks.links],
62
32
  };
63
33
  }
64
34
 
65
- /**
66
- * core 侧在册 edge 的回拨组件并集:uplink-edge 全 core 一份实体,每台 edge
67
- * 一条带别名软链(install 按磁盘在册、_register 传单台、status 按 topology
68
- * 在册,三方同源)。
69
- * @param {readonly string[]} aliases
70
- */
35
+ /** core 上已登记的 edge 共用一份回拨脚本,每台各有一条软链。@param {readonly string[]} aliases */
71
36
  export function edgeCallbacksPlan(aliases) {
72
37
  return {
73
- entities: aliases.length ? [[UPLINK_EDGE, UPLINK_EDGE]] : [],
38
+ entities: aliases.length ? [UPLINK_EDGE] : [],
74
39
  links: aliases.map((alias) => [edgeLinkName(alias), UPLINK_EDGE]),
75
40
  };
76
41
  }
77
-
78
- /** 多份计划并集(顺序拼接;调用方保证各份之间实体/软链不重复)。 */
79
- export function mergePlans(...plans) {
80
- return {
81
- entities: plans.flatMap((p) => p.entities),
82
- links: plans.flatMap((p) => p.links),
83
- };
84
- }
@@ -5,7 +5,6 @@
5
5
  // topology dotfiles 托管的拓扑(名/角色/relay 口/用户)
6
6
  // bin/ 包脚本实体 + 服务软链(install/报名对账;运行时零 npm/fnm 依赖)
7
7
  // state/ 易变状态(两开关、edges v6、addr 入口地址、PROBE_FAIL、ENSURE)
8
- // link.enabled link 附加件的持久安装意图(树根,不放 state/)
9
8
  // conf.d/ 渲染给 ssh Include 的配置片段(生成物,不进 dotfiles):
10
9
  // routes edge:Match 选路块 + 尾部打标块(install 渲染)
11
10
  // edge-<别名> core/node:edge 入口(install 渲染,地址 Include state/addr)
@@ -72,9 +71,8 @@ export function machinePaths(env = process.env) {
72
71
  relay: path.join(stateDir, 'RELAY_ON'),
73
72
  peer: path.join(stateDir, 'PEER_ON'),
74
73
  }),
75
- // link 附加件的持久安装意图:存在=install 对账 link 实体/plist。放树根
76
- // 不放 state/——update 的无参 install 与任何 state 维护都不能误伤它
77
- linkEnabledFile: path.join(sshNetDir, 'link.enabled'),
74
+ // 旧版 edge 的选装标记(2026-11 退役),仅供安装与卸载清理,不再参与判断
75
+ legacyLinkEnabledFile: path.join(sshNetDir, 'link.enabled'),
78
76
  // PROBE_FAIL:sn-route 的失败印记(内容 epoch,15s TTL)。文件名是
79
77
  // paths ↔ sn-route 两处契约(constants.test 锚)
80
78
  probeFailFile: path.join(stateDir, 'PROBE_FAIL'),
@@ -44,21 +44,20 @@ function runLsof(runner, args, port) {
44
44
  throw new Error(`lsof 查询端口 ${port} 失败:${detail}`);
45
45
  }
46
46
 
47
- /**
48
- * 环回某端口当前的监听 pid 列表(无监听空数组)。
49
- * @param {import('./exec.mjs').Runner} runner
50
- * @param {number} port
51
- * @returns {number[]}
52
- */
53
- export function listListeners(runner, port) {
54
- const r = runLsof(runner, ['-tnP', `-iTCP:${port}`, '-sTCP:LISTEN'], port);
55
- if (r.code !== 0) return [];
56
- return r.stdout
57
- .trim()
58
- .split(/\s+/)
59
- .filter(Boolean)
60
- .map(Number)
61
- .filter((n) => Number.isInteger(n));
47
+ /** 只认覆盖 127.0.0.1 的监听。同号的 IPv6 通配监听可能只收 IPv6,单独探测 */
48
+ export async function forwardListenerPids(runner, port) {
49
+ const r = runLsof(runner, ['-nP', '-Fpftn', `-iTCP:${port}`, '-sTCP:LISTEN'], port);
50
+ const ipv4 = new Set();
51
+ const wildcard6 = new Set();
52
+ let pid, type;
53
+ for (const field of r.stdout.split('\n')) {
54
+ if (field.startsWith('p')) pid = Number(field.slice(1));
55
+ if (field.startsWith('t')) type = field.slice(1);
56
+ if (field === `n127.0.0.1:${port}` || field === `n[::ffff:127.0.0.1]:${port}`) ipv4.add(pid);
57
+ if (field === `n*:${port}`) (type === 'IPv6' ? wildcard6 : ipv4).add(pid);
58
+ }
59
+ if (ipv4.size === 0 && wildcard6.size && await tcpOpen('127.0.0.1', port)) return [...wildcard6];
60
+ return [...ipv4];
62
61
  }
63
62
 
64
63
  /**
@@ -91,21 +90,6 @@ export function v6LoopbackPids(text, port) {
91
90
  .filter((n) => Number.isInteger(n));
92
91
  }
93
92
 
94
- /**
95
- * 本地转发口预检:无监听=空闲;持口者全是 link job 进程本身=本服务;否则冲突。
96
- * @param {import('./exec.mjs').Runner} runner
97
- * @param {number} port
98
- * @param {number|null} jobPid link job 的 pid(未注册或没在跑给 null)
99
- * @returns {{kind:'free'|'ours'|'foreign', pids:number[]}}
100
- */
101
- export function classifyLocalPort(runner, port, jobPid) {
102
- const pids = listListeners(runner, port);
103
- if (pids.length === 0) return { kind: 'free', pids: [] };
104
- return jobPid !== null && pids.every((p) => p === jobPid)
105
- ? { kind: 'ours', pids }
106
- : { kind: 'foreign', pids };
107
- }
108
-
109
93
  /**
110
94
  * 跑 bin/sn-probe(install 预检与 status 共用同一实现)。异步:status 把
111
95
  * 它与 relay 实测、端口探测并发,避免串行累加超时。
@@ -2,12 +2,17 @@
2
2
  // - bin/ 只放包脚本的**原名实体**(0755),服务 job 经「带机器名软链」引用——
3
3
  // 程序永远只有一份(升级原子换一份、N 个 job 自动跟新),进程 argv[0] 第
4
4
  // 一列仍带机器名可辨识(ssh-net-uplink-edge-<别名> 等)
5
- // - 实体/软链都幂等:内容相同不重写(只补可执行位)、链指向正确不动
5
+ // - 实体的内容与 0755 权限都正确时保留原文件;软链目标正确时保留原链
6
6
  // - 运行时零 npm/fnm 依赖;包升级后重跑 install 刷新(core 侧 uplink-edge
7
7
  // 由每次报名自动对账),status 直接比对包内脚本与磁盘产物
8
8
  import fs from 'node:fs';
9
+ import path from 'node:path';
9
10
  import { packageScriptPath } from './paths.mjs';
10
- import { readFileOrNull, writeFileAtomic } from './fsutil.mjs';
11
+ import { withTempFile, writeFileAtomic } from './fsutil.mjs';
12
+
13
+ function isRuntimeFile(stat) {
14
+ return stat.isFile() && (stat.mode & 0o7777) === 0o755;
15
+ }
11
16
 
12
17
  /**
13
18
  * 拷贝单脚本到 bin/(实体)。
@@ -17,14 +22,7 @@ import { readFileOrNull, writeFileAtomic } from './fsutil.mjs';
17
22
  */
18
23
  export function ensureScript(dstPath, srcPath) {
19
24
  const src = fs.readFileSync(srcPath);
20
- const cur = readFileOrNull(dstPath, null);
21
- const st = cur === null ? null : fs.lstatSync(dstPath);
22
- if (st !== null && st.isFile() && cur.equals(src)) {
23
- // 内容对但可执行位丢了(cp/同步工具吃掉 mode):补上
24
- if (st.mode & 0o111) return false;
25
- fs.chmodSync(dstPath, 0o755);
26
- return true;
27
- }
25
+ if (auditScript(dstPath, src) === 'ok') return false;
28
26
  // 缺失、旧内容或软链:tmp+rename 原子换(rename 替换目录项本身,不跟随软链)
29
27
  writeFileAtomic(dstPath, src, { mode: 0o755 });
30
28
  return true;
@@ -41,25 +39,26 @@ export function ensureLink(linkPath, entityName) {
41
39
  const st = fs.lstatSync(linkPath, { throwIfNoEntry: false }) ?? null;
42
40
  if (st?.isSymbolicLink() && fs.readlinkSync(linkPath) === entityName)
43
41
  return false;
44
- // 缺失无需处理;错链或实体占位都删掉后统一建链
45
- if (st !== null) fs.rmSync(linkPath);
46
- fs.symlinkSync(entityName, linkPath);
42
+ // 原子替换,launchd 和并发报名始终可以打开已存在的服务入口
43
+ withTempFile(linkPath, {}, (tmp) => {
44
+ fs.symlinkSync(entityName, tmp);
45
+ fs.renameSync(tmp, linkPath);
46
+ });
47
47
  return true;
48
48
  }
49
49
 
50
50
  /**
51
51
  * 幂等对账 bin/:实体拷贝 + 服务软链。所有 install 路径都先经这里。
52
- * 顺序是 entries 先刷实体、links 后建链:软链位有实体残留时敢直接删掉换链,
53
- * 靠的就是实体已先行刷对。
52
+ * 先刷实体再建链,软链位即使有旧文件,也可以直接换成指向新实体的链接。
54
53
  * @param {object} ctx
55
- * @param {readonly (readonly [string, string])[]} entries [bin 名, 包脚本名] 实体
54
+ * @param {readonly string[]} entities 原名安装的包脚本
56
55
  * @param {readonly (readonly [string, string])[]} links [链名, 实体 bin 名]
57
56
  * @returns {boolean[]} 每项是否发生变更
58
57
  */
59
- export function ensureRuntime(ctx, entries, links = []) {
58
+ export function ensureRuntime(ctx, entities, links = []) {
60
59
  fs.mkdirSync(ctx.paths.binDir, { recursive: true });
61
- const results = entries.map(([name, scriptName]) =>
62
- ensureScript(ctx.paths.binScript(name), packageScriptPath(scriptName)));
60
+ const results = entities.map((name) =>
61
+ ensureScript(ctx.paths.binScript(name), packageScriptPath(name)));
63
62
  for (const [name, entityName] of links) {
64
63
  results.push(ensureLink(ctx.paths.binScript(name), entityName));
65
64
  }
@@ -69,26 +68,18 @@ export function ensureRuntime(ctx, entries, links = []) {
69
68
  }
70
69
 
71
70
  /**
72
- * 运行时脚本体检(status 用):实体必须是普通文件,与包内逐字节比对,并查
73
- * 可执行位。软链即使同内容也判 stale,ensureScript 会替成实体,避免运行时
74
- * 继续依赖包路径;位丢了时 Match exec 直接 EACCES,只报字节一致会让 status
75
- * 在选路静默落 relay 时误判健康。
71
+ * 实体须为权限 0755 的普通文件,且与包内脚本逐字节相同。先查类型,避免跟随
72
+ * 软链或读取命名管道。安装时直接复用即将写入的字节
76
73
  * @param {string} dstPath
77
- * @param {string} srcPath
74
+ * @param {string|Buffer} source 包内脚本的路径或已读内容
78
75
  * @returns {'ok'|'missing'|'stale'}
79
76
  */
80
- export function auditScript(dstPath, srcPath) {
81
- let cur;
82
- let st;
83
- try {
84
- [cur, st] = [fs.readFileSync(dstPath), fs.lstatSync(dstPath)];
85
- } catch (err) {
86
- if (err.code !== 'ENOENT') throw err;
87
- return 'missing';
88
- }
89
- if (!st.isFile() || !cur.equals(fs.readFileSync(srcPath)) || !(st.mode & 0o111))
90
- return 'stale';
91
- return 'ok';
77
+ export function auditScript(dstPath, source) {
78
+ const st = fs.lstatSync(dstPath, { throwIfNoEntry: false });
79
+ if (!st) return 'missing';
80
+ if (!isRuntimeFile(st)) return 'stale';
81
+ const expected = Buffer.isBuffer(source) ? source : fs.readFileSync(source);
82
+ return fs.readFileSync(dstPath).equals(expected) ? 'ok' : 'stale';
92
83
  }
93
84
 
94
85
  /**
@@ -103,7 +94,8 @@ export function auditLink(linkPath, entityName) {
103
94
  if (!st?.isSymbolicLink()) return false;
104
95
  if (fs.readlinkSync(linkPath) !== entityName) return false;
105
96
  try {
106
- return Boolean(fs.statSync(linkPath).mode & 0o111);
97
+ const target = fs.lstatSync(path.join(path.dirname(linkPath), entityName));
98
+ return isRuntimeFile(target);
107
99
  } catch {
108
100
  return false;
109
101
  }