ssh-net 26.10.34 → 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.
@@ -15,9 +15,13 @@ import { packageScriptPath } from '../lib/paths.mjs';
15
15
  import * as launchd from '../lib/launchd.mjs';
16
16
  import * as systemd from '../lib/systemd.mjs';
17
17
  import { peerProbeOk, tcpOpen } from '../lib/probe.mjs';
18
+ import { readFileOrNull } from '../lib/fsutil.mjs';
19
+ import { edgeRuntimePlan, relayRuntimePlan } from '../lib/manifest.mjs';
20
+ import { edgeFragmentContent, edgeFragmentShouldExist } from '../lib/registration.mjs';
18
21
  import {
19
- linkLabel, linkLinkName, relayLabel, relayLinkName, relayUnitName,
20
- edgeLabel, edgeLinkName, renderRoutes, renderEdgeHost,
22
+ linkLabel, relayLabel, relayUnitName,
23
+ edgeLabel, edgeLinkName,
24
+ renderRoutes, coreViaRelayArgs,
21
25
  } from '../lib/render.mjs';
22
26
 
23
27
  /**
@@ -25,38 +29,32 @@ import {
25
29
  * @returns {'ok'|'stale'|'missing'}
26
30
  */
27
31
  function auditConfFragment(file, expected) {
28
- let text = null;
29
- try {
30
- text = fs.readFileSync(file, 'utf8');
31
- } catch { return 'missing'; }
32
+ const text = readFileOrNull(file);
33
+ if (text === null) return 'missing';
32
34
  return text === expected ? 'ok' : 'stale';
33
35
  }
34
36
 
35
- /** 实体脚本体检列表。 */
36
- function auditRequired(ctx, entries) {
37
- return entries.map(([name, script]) => ({
38
- link: name,
39
- audit: auditScript(path.join(ctx.paths.binDir, name), packageScriptPath(script)),
40
- }));
41
- }
42
-
43
37
  /** 各角色共用的实体+软链体检,返回人话问题列表(空=健康)。 */
44
- function runtimeIssues(ctx, { entities, serviceLinks }) {
38
+ function runtimeIssues(ctx, { entities, links }) {
45
39
  const issues = [];
46
- const links = auditRequired(ctx, entities);
47
- if (links.some((l) => l.audit === 'stale'))
40
+ // 实体逐字节比对(name 是 bin 实体名,不是软链)
41
+ const entityAudits = entities.map(([name, script]) => ({
42
+ name,
43
+ audit: auditScript(path.join(ctx.paths.binDir, name), packageScriptPath(script)),
44
+ }));
45
+ if (entityAudits.some((a) => a.audit === 'stale'))
48
46
  issues.push('隧道组件与所装版本不一致——跑一次 ssh-net install 刷新');
49
- if (links.every((l) => l.audit === 'missing'))
47
+ if (entityAudits.every((a) => a.audit === 'missing'))
50
48
  issues.push('尚未安装(先跑 ssh-net install)');
51
- else if (links.some((l) => l.audit === 'missing'))
49
+ else if (entityAudits.some((a) => a.audit === 'missing'))
52
50
  // 部分缺失:探针丢了会让开着的隧道恒判中继,不能只显示不报
53
- issues.push(`隧道组件不完整(缺 ${links.filter((l) => l.audit === 'missing').map((l) => l.link).join('、')})——跑一次 ssh-net install 修复`);
54
- for (const [linkName, entityName] of serviceLinks) {
51
+ issues.push(`隧道组件不完整(缺 ${entityAudits.filter((a) => a.audit === 'missing').map((a) => a.name).join('、')})——跑一次 ssh-net install 修复`);
52
+ for (const [linkName, entityName] of links) {
55
53
  const r = auditLink(path.join(ctx.paths.binDir, linkName), entityName);
56
54
  if (r !== 'ok')
57
55
  issues.push(`隧道组件异常(${linkName}:${r})——跑一次 ssh-net install 修复`);
58
56
  }
59
- return { issues, links };
57
+ return { issues, entityAudits };
60
58
  }
61
59
 
62
60
  /** forward 的人话标签:写出目标(loopback 是落地机环回)。 */
@@ -92,17 +90,15 @@ async function relayPortListening(ctx, port) {
92
90
  }
93
91
 
94
92
  /** edge 的 relay 线路实测:命令行显式 -J 经 relay 跑一条真 ssh(报名/中继同
95
- * 信道;字面 127.0.0.1 不命中 Match,绕开自动选路,design §6.7)。 */
93
+ * 信道;字面 127.0.0.1 不命中 Match,绕开自动选路,design §6.7)。
94
+ * 探测不接受新 host key(acceptHost 缺省 false)——与无人值守报名的
95
+ * accept-new 是刻意分级(design §4.3)。 */
96
96
  async function relayPathOk(ctx) {
97
- const r = await ctx.runner.runAsync('ssh', [
98
- '-J', ctx.topo.relay.alias,
99
- '-p', String(ctx.topo.core.relayPort),
100
- '-o', `HostKeyAlias=${ctx.topo.core.alias}`,
101
- '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5',
102
- '-o', 'IdentitiesOnly=yes',
103
- '-o', 'ControlMaster=no', '-o', 'ControlPath=none',
104
- `${ctx.topo.core.user}@127.0.0.1`, 'true',
105
- ], { timeout: 8000 });
97
+ const r = await ctx.runner.runAsync(
98
+ 'ssh',
99
+ coreViaRelayArgs(ctx.topo, { connectTimeout: 5, remoteCommand: 'true' }),
100
+ { timeout: 8000 },
101
+ );
106
102
  return r.code === 0;
107
103
  }
108
104
 
@@ -111,35 +107,25 @@ async function collectEdge(ctx) {
111
107
  const issues = [];
112
108
  const vIssue = runtimeVersionIssue(ctx.paths);
113
109
  if (vIssue) issues.push(vIssue);
114
- // link 附加件以 marker 为准:默认只有 5 实体、无服务软链;装了才加
110
+ // link 附加件以 marker 为准:默认只有 3 实体、无服务软链;装了才加
115
111
  // link-core(转发口只取决于装没装,不是运行时开关)
116
112
  const linkInstalled = fs.existsSync(paths.linkEnabledFile);
117
- /** @type {[string,string][]} */
118
- const entities = [
119
- ['sn-probe', 'sn-probe'],
120
- ['sn-route', 'sn-route'],
121
- ['sn-ipv6', 'sn-ipv6'],
122
- ];
123
- /** @type {[string,string][]} */
124
- const serviceLinks = [];
125
- if (linkInstalled) {
126
- entities.push(['ssh-net-link-core', 'ssh-net-link-core']);
127
- serviceLinks.push([linkLinkName(topo.core.alias), 'ssh-net-link-core']);
128
- }
129
- const { issues: rtIssues, links } = runtimeIssues(ctx, { entities, serviceLinks });
113
+ const plan = edgeRuntimePlan(topo, linkInstalled);
114
+ const { issues: rtIssues, entityAudits } = runtimeIssues(ctx, plan);
130
115
  issues.push(...rtIssues);
131
116
 
132
117
  // routes 体检(sn-route 实体在才查:没装时 rtIssues 已报「尚未安装」):
133
118
  // routes 被手删/过期会让 ssh 静默退回 lan 直连,是故障、进 issues。文件尾部
134
119
  // 的 VS Code 打标块同属这份内容,逐字节对账一并覆盖,不用单独体检
135
- if (links.find((l) => l.link === 'sn-route')?.audit === 'ok') {
120
+ if (entityAudits.some((a) => a.name === 'sn-route' && a.audit === 'ok')) {
136
121
  const routeAudit = auditConfFragment(paths.routesFile, renderRoutes(topo, ctx.self.alias));
137
122
  if (routeAudit !== 'ok')
138
123
  issues.push(`选路片段 conf.d/routes ${routeAudit === 'missing' ? '缺失' : '与 topology 不一致'}——跑一次 ssh-net install 刷新`);
139
124
  }
140
125
 
126
+ // 显示只消费 registered/running:轻量 print 即可,不跑全域 print-disabled
141
127
  const label = linkLabel(topo.core.alias);
142
- const job = launchd.inspect(ctx.runner, ctx.uid, label);
128
+ const job = launchd.printState(ctx.runner, ctx.uid, label);
143
129
  const switches = state.readSwitches();
144
130
 
145
131
  // 非法组合:peer 依赖 relay。开关是「文件即接口」——手 touch/rm state 里
@@ -148,6 +134,16 @@ async function collectEdge(ctx) {
148
134
  if (switches.peer && !switches.relay)
149
135
  issues.push('开关组合异常:peer 开但 relay 关(peer 依赖 relay,多半是 state 里的开关被手动改动)——跑一次 ssh-net stop 后再按需要 start');
150
136
 
137
+ // v6 探测与下面的就绪实测互不依赖:同一批并发(5s sn-ipv6 不再串行白等在
138
+ // 8s relay 探测之后)。全关(在办公室)时不跑。v6 只是诊断线索不是判决:
139
+ // 探测没跑成(超时/非零退出/实体缺失)时不能谎称「没有 IPv6」——那个
140
+ // 结论只在 sn-ipv6 正常跑完且无输出时才成立
141
+ const needV6 = (switches.relay || switches.peer)
142
+ && entityAudits.some((a) => a.name === 'sn-ipv6' && a.audit === 'ok');
143
+ const v6P = needV6
144
+ ? ctx.runner.runRawAsync(path.join(paths.binDir, 'sn-ipv6'), [], { timeout: 5000 })
145
+ : Promise.resolve(null);
146
+
151
147
  // 就绪实测并发(On 是意图、ready 是事实;开关关的线路不探测=null)。
152
148
  // 转发口只有装了 link 才可能存在——默认形态不探
153
149
  const relayOk = ctx.relayOk ?? relayPathOk; // 测试可注入
@@ -164,7 +160,7 @@ async function collectEdge(ctx) {
164
160
  const coreLanIp = ctx.hostTable.get(topo.core.alias)?.hostname;
165
161
  const lanIdx = switches.relay && coreLanIp ? probes.length : -1;
166
162
  if (lanIdx >= 0) probes.push(openTcp(coreLanIp, 22, 1200));
167
- const got = await Promise.all(probes);
163
+ const [got, v6Probe] = await Promise.all([Promise.all(probes), v6P]);
168
164
  const relayReady = got[0];
169
165
  const peerReady = got[1];
170
166
  const ports = {};
@@ -172,6 +168,13 @@ async function collectEdge(ctx) {
172
168
  topo.forwards.forEach((f, i) => { ports[f.listenPort] = got[2 + i]; });
173
169
  const lanReachable = lanIdx >= 0 ? got[lanIdx] : false;
174
170
 
171
+ let v6 = '';
172
+ let v6ProbeOk = false;
173
+ if (v6Probe) {
174
+ v6 = v6Probe.stdout.trim();
175
+ v6ProbeOk = !v6Probe.error && v6Probe.code === 0;
176
+ }
177
+
175
178
  if (lanReachable)
176
179
  issues.push(`检测到 ${topo.core.alias}(${coreLanIp})局域网直连可达——隧道可能在空转绕中继;人在办公室可 ssh-net stop`);
177
180
 
@@ -188,19 +191,6 @@ async function collectEdge(ctx) {
188
191
  if (f.targetAlias === 'loopback' && !ports[f.listenPort])
189
192
  issues.push(`${forwardLabel(f)} 未就绪:edge 侧正常时多半是 core 上的出口代理(microsocks)没跑——到 core 上查 local.microsocks`);
190
193
 
191
- // v6 只是诊断线索不是判决:探测没跑成(超时被杀/非零退出/实体缺失)时
192
- // 不能谎称「没有 IPv6」——那个结论只在 sn-ipv6 正常跑完且无输出时才成立
193
- //(与 doctor 的 probeOk 同判据;sn-ipv6 自身退出码恒 0,code!==0 只会是
194
- // 超时或崩溃)。全关(在办公室)时 render 早返回不显示 v6 行,不白跑
195
- let v6 = '';
196
- let v6ProbeOk = false;
197
- if ((switches.relay || switches.peer)
198
- && links.find((l) => l.link === 'sn-ipv6')?.audit === 'ok') {
199
- const probe = ctx.runner.runRaw(path.join(paths.binDir, 'sn-ipv6'), [], { timeout: 5000 });
200
- v6 = probe.stdout.trim();
201
- v6ProbeOk = !probe.error && probe.code === 0;
202
- }
203
-
204
194
  const forwardViews = linkInstalled
205
195
  ? topo.forwards.map((f) => [forwardLabel(f), ports[f.listenPort]])
206
196
  : [];
@@ -217,29 +207,31 @@ async function collectCore(ctx) {
217
207
  const issues = [];
218
208
  const vIssue = runtimeVersionIssue(ctx.paths);
219
209
  if (vIssue) issues.push(vIssue);
220
- const { issues: rtIssues } = runtimeIssues(ctx, {
221
- entities: [['ssh-net-uplink-relay', 'ssh-net-uplink-relay']],
222
- serviceLinks: [[relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay']],
223
- });
210
+ const { issues: rtIssues } = runtimeIssues(ctx, relayRuntimePlan(topo));
224
211
  issues.push(...rtIssues);
225
212
 
213
+ // disabled override 是整域同一份字典:relay job 与各 edge job 共用一次拉取
214
+ const dmap = launchd.disabledMap(ctx.runner, ctx.uid);
226
215
  const relayLabelName = relayLabel(topo.relay.alias);
227
- const relayJob = launchd.inspect(ctx.runner, ctx.uid, relayLabelName);
216
+ const relayJob = launchd.inspectWith(ctx.runner, ctx.uid, relayLabelName, dmap);
228
217
  // relay 口实测是 8s 超时的真 ssh:先发起来,边等边做下面的注册态体检
229
218
  const relayPortP = relayPortListening(ctx, topo.core.relayPort);
230
219
 
220
+ // 回拨实体与 edge 别名无关:循环外体检一次,各 edge 只检各自的软链
221
+ const callbackEntityAudit = auditScript(
222
+ path.join(paths.binDir, 'ssh-net-uplink-edge'),
223
+ packageScriptPath('ssh-net-uplink-edge'),
224
+ );
225
+
231
226
  const edges = [];
232
227
  for (const e of topo.edges) {
233
228
  const label = edgeLabel(e.alias);
234
- const st = launchd.inspect(ctx.runner, ctx.uid, label);
229
+ const st = launchd.inspectWith(ctx.runner, ctx.uid, label, dmap);
235
230
  // 已连接过的随身机,回拨组件一并体检:回拨脚本/软链只有 _register
236
231
  // (报名)这条刷新通道,漏刷会拿旧脚本拨号
237
232
  if (st.registered) {
238
233
  const bad = [];
239
- if (auditScript(
240
- path.join(paths.binDir, 'ssh-net-uplink-edge'),
241
- packageScriptPath('ssh-net-uplink-edge'),
242
- ) !== 'ok') bad.push('回拨脚本');
234
+ if (callbackEntityAudit !== 'ok') bad.push('回拨脚本');
243
235
  const linkState = auditLink(
244
236
  path.join(paths.binDir, edgeLinkName(e.alias)),
245
237
  'ssh-net-uplink-edge',
@@ -257,11 +249,8 @@ async function collectCore(ctx) {
257
249
  // install)都会让 `ssh <别名>` 失败或解析错。休眠(disabled)时片段
258
250
  // 本就该删(六连败收尸),不报;未注册无 v6 也不报
259
251
  let fragmentAudit = null;
260
- if (st.registered && !st.disabled && v6) {
261
- fragmentAudit = auditConfFragment(
262
- paths.edgeHostFile(e.alias),
263
- renderEdgeHost({ alias: e.alias, aliases: e.aliases, user: e.user, v6 }),
264
- );
252
+ if (edgeFragmentShouldExist(st, v6)) {
253
+ fragmentAudit = auditConfFragment(paths.edgeHostFile(e.alias), edgeFragmentContent(e, v6));
265
254
  if (fragmentAudit !== 'ok')
266
255
  issues.push(`${e.alias} 的 ssh 入口片段${fragmentAudit === 'missing' ? '缺失' : '过期'}(state 有 v6、job 未休眠)——跑一次 ssh-net install 重建`);
267
256
  }
@@ -301,10 +290,7 @@ async function collectNode(ctx) {
301
290
  const issues = [];
302
291
  const vIssue = runtimeVersionIssue(ctx.paths);
303
292
  if (vIssue) issues.push(vIssue);
304
- const { issues: rtIssues } = runtimeIssues(ctx, {
305
- entities: [['ssh-net-uplink-relay', 'ssh-net-uplink-relay']],
306
- serviceLinks: [[relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay']],
307
- });
293
+ const { issues: rtIssues } = runtimeIssues(ctx, relayRuntimePlan(topo));
308
294
  issues.push(...rtIssues);
309
295
 
310
296
  const unit = relayUnitName(topo.relay.alias);
@@ -348,6 +334,13 @@ function profileOf(sw, linkInstalled) {
348
334
  return '仅中继信道(待命:不报名、无本地转发口)';
349
335
  }
350
336
 
337
+ /** core/node 共用的 relay 状态行。 */
338
+ function relayStatusLine(s) {
339
+ return s.relayPort.listening
340
+ ? ` relay: ✓ 开着(在外面经 ${s.relayAlias} 进入 ${s.alias} · 入口 ${s.relayPort.port})`
341
+ : ` relay: ✗ ${s.relayPort.reachable === false ? `连不上 ${s.relayAlias},入口状态未知` : `入口 ${s.relayPort.port} 没在监听`}`;
342
+ }
343
+
351
344
  export function renderText(s) {
352
345
  const lines = [];
353
346
  lines.push(`ssh-net ${s.role} ${s.alias}`);
@@ -391,9 +384,7 @@ export function renderText(s) {
391
384
  }
392
385
  lines.push(` 后台任务: ${!s.job.registered ? `未装 link(默认零常驻)` : s.job.running ? 'link 运行中' : 'link 已停止'}`);
393
386
  } else if (s.role === 'core') {
394
- lines.push(s.relayPort.listening
395
- ? ` relay: ✓ 开着(在外面经 ${s.relayAlias} 进入 ${s.alias} · 入口 ${s.relayPort.port})`
396
- : ` relay: ✗ ${s.relayPort.reachable === false ? `连不上 ${s.relayAlias},入口状态未知` : `入口 ${s.relayPort.port} 没在监听`}`);
387
+ lines.push(relayStatusLine(s));
397
388
  lines.push(` relay 进程: ${s.relayJob.running ? `运行中${exitNote(s.relayJob.lastExitCode)}` : '未运行'}`);
398
389
  lines.push(' edge:');
399
390
  for (const e of s.edges) {
@@ -412,9 +403,7 @@ export function renderText(s) {
412
403
  lines.push(` ${e.alias} ${state}${frag}`);
413
404
  }
414
405
  } else {
415
- lines.push(s.relayPort.listening
416
- ? ` relay: ✓ 开着(在外面经 ${s.relayAlias} 进入 ${s.alias} · 入口 ${s.relayPort.port})`
417
- : ` relay: ✗ ${s.relayPort.reachable === false ? `连不上 ${s.relayAlias},入口状态未知` : `入口 ${s.relayPort.port} 没在监听`}`);
406
+ lines.push(relayStatusLine(s));
418
407
  lines.push(` relay 进程: ${s.active === 'active' ? '运行中(systemd)' : `${s.active}(systemd)`}`);
419
408
  }
420
409
 
@@ -7,6 +7,7 @@
7
7
  import * as launchd from '../lib/launchd.mjs';
8
8
  import * as systemd from '../lib/systemd.mjs';
9
9
  import { stopEdgeLink } from '../lib/jobctl.mjs';
10
+ import { assertUnitSwitchArgs } from '../lib/cliargs.mjs';
10
11
  import { relayLabel, relayUnitName } from '../lib/render.mjs';
11
12
 
12
13
  const TARGETS = ['relay', 'peer'];
@@ -61,16 +62,11 @@ export function run(ctx, args = []) {
61
62
  : 'relay 已关闭(peer 一并关闭——它依赖 relay)。几分钟后 core 侧会停止回拨并静默';
62
63
  }
63
64
  // core/node 是单总开关(等同 --all):显式 -a/--all 收下,其余参数拒绝
64
- if (args.length && !(args.length === 1 && (args[0] === '-a' || args[0] === '--all')))
65
- throw new Error('本机是单总开关,stop 不带参数(-a/--all 亦可,等同缺省)');
65
+ assertUnitSwitchArgs(args, 'stop');
66
66
  if (ctx.role === 'core') return stopCore(ctx);
67
67
  if (ctx.role === 'node') {
68
68
  const unit = relayUnitName(ctx.topo.relay.alias);
69
- const s = systemd.stopUnit(ctx.runner, unit);
70
- // 与 uninstallNode 同规则:unit 未加载(未装/已卸)的无害失败放行;
71
- // 真失败必须报——否则「已关闭」是谎报,在跑进程仍在外面监听
72
- if (s.code !== 0 && !/not loaded/.test(s.stderr))
73
- throw new Error(`systemctl stop 失败:${s.stderr.trim()}`);
69
+ systemd.stopIfLoaded(ctx.runner, unit); // not-loaded(未装/已卸)无害,真失败抛出
74
70
  const d = systemd.disableUnit(ctx.runner, unit);
75
71
  if (d.code !== 0) throw new Error(`systemctl disable 失败:${d.stderr.trim()}`);
76
72
  return 'relay 已关闭(重启后保持关闭)';
@@ -58,11 +58,9 @@ function uninstallNode(ctx) {
58
58
  if (ctx.uid !== 0)
59
59
  throw new Error('node 卸载写 /etc/systemd/system 需要 root,请以 root 运行');
60
60
  const unit = relayUnitName(ctx.topo.relay.alias);
61
- const s = systemd.stopUnit(ctx.runner, unit);
62
- // unit 不存在(未装/已卸)的无害失败放行;真失败必须报——否则删了 unit
63
- // 文件、systemd 里留下 ghost 态的在跑进程
64
- if (s.code !== 0 && !/not loaded/.test(s.stderr))
65
- throw new Error(`systemctl stop 失败:${s.stderr.trim()}`);
61
+ // not-loaded(未装/已卸)无害,真失败必须报——否则删了 unit 文件、
62
+ // systemd 里留下 ghost 态的在跑进程
63
+ systemd.stopIfLoaded(ctx.runner, unit);
66
64
  systemd.disableUnit(ctx.runner, unit); // 已禁无害
67
65
  rm(path.join(ctx.paths.systemdUnitDir, unit));
68
66
  systemd.daemonReload(ctx.runner);
@@ -0,0 +1,12 @@
1
+ // start/stop 共用的命令行参数小助手(edge 的 relay/peer 解析两命令返回
2
+ // 语义不同,各自保留;只收逐字相同的部分)。
3
+
4
+ /**
5
+ * core/node 是单总开关:无参或显式 -a/--all 收下(等同缺省),其余参数拒绝。
6
+ * @param {string[]} args
7
+ * @param {'start'|'stop'} verb
8
+ */
9
+ export function assertUnitSwitchArgs(args, verb) {
10
+ if (args.length && !(args.length === 1 && (args[0] === '-a' || args[0] === '--all')))
11
+ throw new Error(`本机是单总开关,${verb} 不带参数(-a/--all 亦可,等同缺省)`);
12
+ }
@@ -6,6 +6,7 @@
6
6
  // - sync 幂等:内容字节相同不动盘(routes 每次 install 调,不产生无意义变更)
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
  /** 确保 conf.d 存在且 0700(~/.ssh/ssh-net 已由 state 侧建为 0700)。 */
11
12
  function ensureConfDir(confDir) {
@@ -20,21 +21,12 @@ function ensureConfDir(confDir) {
20
21
  * @returns {boolean} 是否实际重写
21
22
  */
22
23
  export function syncConfFile(file, content) {
23
- let existing = null;
24
- try {
25
- existing = fs.readFileSync(file, 'utf8');
26
- } catch {
27
- existing = null;
28
- }
29
- if (existing === content) return false;
24
+ if (readFileOrNull(file) === content) return false;
30
25
 
31
26
  const dir = path.dirname(file);
32
27
  ensureConfDir(dir);
33
28
  // tmp 落 conf.d 的**上级**目录:glob conf.d/* 扫不到它
34
- const tmp = path.join(path.dirname(dir), `.${path.basename(file)}.tmp-${process.pid}`);
35
- fs.writeFileSync(tmp, content, { mode: 0o600 });
36
- fs.renameSync(tmp, file);
37
- fs.chmodSync(file, 0o600);
29
+ writeFileAtomic(file, content, { mode: 0o600, tmpDir: path.dirname(dir) });
38
30
  return true;
39
31
  }
40
32
 
@@ -35,7 +35,6 @@ const BIND = '127.0.0.1'; // 所有转发强制只绑环回(design §6.5)
35
35
  * @property {string} user
36
36
  *
37
37
  * @typedef {Object} Forward
38
- * @property {string} bind 恒 127.0.0.1
39
38
  * @property {number} listenPort
40
39
  * @property {string} targetAlias 目标别名:'loopback'=落地机 v4 环回、
41
40
  * 'loopback6'=v6 环回(固定 [::1]),其余=主机别名(渲染时查
@@ -211,7 +210,7 @@ export function parseTopology(text) {
211
210
  if (target.role === 'edge')
212
211
  throw new ConfigError(line, `forward local 目标 ${targetAlias} 是 edge(edge 无注册地址,不能做转发目标)`);
213
212
  }
214
- forwards.push({ bind: BIND, listenPort, targetAlias, targetPort });
213
+ forwards.push({ listenPort, targetAlias, targetPort });
215
214
  }
216
215
 
217
216
  return Object.freeze({
@@ -282,7 +281,7 @@ export function renderForwardArgs(forwards, hostTable) {
282
281
  throw new Error(`forward local 目标 ${f.targetAlias} 在 ~/.ssh/config 缺 Host 块或 HostName`);
283
282
  target = host.hostname;
284
283
  }
285
- args.push('-L', `127.0.0.1:${f.listenPort}:${target}:${f.targetPort}`);
284
+ args.push('-L', `${BIND}:${f.listenPort}:${target}:${f.targetPort}`);
286
285
  }
287
286
  return args;
288
287
  }
@@ -0,0 +1,34 @@
1
+ // 文件系统小原语:原子落盘与「缺失即 null」读取。manage/state/runtime/conf
2
+ // 等所有落盘方共用这一份,不各自抄 tmp+rename+chmod。
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ /**
7
+ * 读文件;不存在返回 null(仅吞 ENOENT,其余错误照抛)。
8
+ * @param {string} file
9
+ * @param {BufferEncoding|null} [encoding] 缺省 utf8;传 null 读 Buffer
10
+ * @returns {string|Buffer|null}
11
+ */
12
+ export function readFileOrNull(file, encoding = 'utf8') {
13
+ try {
14
+ return fs.readFileSync(file, encoding === null ? undefined : encoding);
15
+ } catch (err) {
16
+ if (err && err.code === 'ENOENT') return null;
17
+ throw err;
18
+ }
19
+ }
20
+
21
+ /**
22
+ * 原子落盘:tmp 写好再 rename 落定,落定后 chmod 兜底(怪 umask/拷贝工具
23
+ * 吃位都修正到 mode)。
24
+ * @param {string} file
25
+ * @param {string|Buffer} content
26
+ * @param {{mode?: number, tmpDir?: string}} [opts] tmpDir 给 Include 片段用:
27
+ * tmp 必须写在 glob 目录之外(conf.d/* 会被 ssh 扫到)
28
+ */
29
+ export function writeFileAtomic(file, content, { mode = 0o644, tmpDir = path.dirname(file) } = {}) {
30
+ const tmp = path.join(tmpDir, `.${path.basename(file)}.tmp-${process.pid}`);
31
+ fs.writeFileSync(tmp, content, { mode });
32
+ fs.renameSync(tmp, file);
33
+ fs.chmodSync(file, mode);
34
+ }
@@ -8,20 +8,21 @@
8
8
  import net from 'node:net';
9
9
 
10
10
  /**
11
- * 取首 hextet 数值;不是「无 scope、非内嵌 v4 的合法 IPv6 字面值」返回 null。
11
+ * 分类一个候选 v6:合法(无 scope、非内嵌 v4 的 IPv6 字面值)给首 hextet
12
+ * 数值;否则给中文拒收原因。isDialableV6 与 explainV6Error 的唯一共同来源,
13
+ * 拒收规则不抄第二份。
12
14
  * @param {unknown} value
13
- * @returns {number | null}
15
+ * @returns {{g0:number}|{reason:string}}
14
16
  */
15
- function firstHextetOf(value) {
16
- if (typeof value !== 'string') return null;
17
- if (value.length === 0 || value.includes('%')) return null; // 无 scope id
18
- if (net.isIP(value) !== 6) return null;
17
+ function classifyV6(value) {
18
+ if (typeof value !== 'string' || value.length === 0) return { reason: 'v6 为空' };
19
+ if (value.includes('%')) return { reason: 'v6 带 scope id,拒绝' };
20
+ if (net.isIP(value) !== 6) return { reason: '不是合法 IPv6 字面值' };
19
21
  // 任何内嵌 v4 形态(末段含点,如 ::ffff:192.0.2.1)一律拒
20
- const tail = value.slice(value.lastIndexOf(':') + 1);
21
- if (tail.includes('.')) return null;
22
+ if (value.slice(value.lastIndexOf(':') + 1).includes('.'))
23
+ return { reason: '拒绝内嵌 v4(含 ::ffff: v4-mapped)' };
22
24
  const firstGroup = value.split(':')[0];
23
- const g0 = firstGroup === '' ? 0 : Number.parseInt(firstGroup, 16);
24
- return Number.isInteger(g0) ? g0 : null;
25
+ return { g0: firstGroup === '' ? 0 : Number.parseInt(firstGroup, 16) };
25
26
  }
26
27
 
27
28
  /**
@@ -30,23 +31,19 @@ function firstHextetOf(value) {
30
31
  * @returns {boolean}
31
32
  */
32
33
  export function isDialableV6(value) {
33
- const g0 = firstHextetOf(value);
34
- return g0 !== null
35
- && ((g0 >= 0x2000 && g0 <= 0x3fff) || (g0 >= 0xfc00 && g0 <= 0xfdff));
34
+ const c = classifyV6(value);
35
+ return 'g0' in c
36
+ && ((c.g0 >= 0x2000 && c.g0 <= 0x3fff) || (c.g0 >= 0xfc00 && c.g0 <= 0xfdff));
36
37
  }
37
38
 
38
39
  /**
39
- * 给报名 RPC 报错用的中文原因;合法返回 null。
40
+ * 给报名 RPC 报错用的中文原因;合法可拨号返回 null。
40
41
  * @param {unknown} value
41
42
  * @returns {string | null}
42
43
  */
43
44
  export function explainV6Error(value) {
44
- if (typeof value !== 'string' || value.length === 0) return 'v6 为空';
45
- if (value.includes('%')) return 'v6 带 scope id,拒绝';
46
- if (net.isIP(value) !== 6) return '不是合法 IPv6 字面值';
47
- if (value.slice(value.lastIndexOf(':') + 1).includes('.'))
48
- return '拒绝内嵌 v4(含 ::ffff: v4-mapped)';
49
- // 可拨号判定单一来源是 isDialableV6,别在这抄第二份
45
+ const c = classifyV6(value);
46
+ if ('reason' in c) return c.reason;
50
47
  if (!isDialableV6(value))
51
48
  return '不是可拨号 v6(收 2000::/3 公网单播与 fc00::/7 ULA,拒 link-local/组播/保留段)';
52
49
  return null;
@@ -5,7 +5,8 @@
5
5
  import * as launchd from './launchd.mjs';
6
6
  import { linkLabel } from './render.mjs';
7
7
 
8
- const TERM_BUDGET_MS = 40_000; // 覆盖 TERM 落在 start peer 前台报名 ssh 的最坏 ~35s
8
+ const TERM_ROUNDS = 2; // 每轮最多等 20s,两轮共覆盖最坏 ~35s 的前台报名 ssh
9
+ const ROUND_MS = 20_000;
9
10
  const POLL_MS = 500;
10
11
 
11
12
  function sleepMs(ms) {
@@ -14,7 +15,8 @@ function sleepMs(ms) {
14
15
  }
15
16
 
16
17
  function isGone(ctx, label) {
17
- const st = launchd.inspect(ctx.runner, ctx.uid, label);
18
+ // 只要 print 的注册/运行/pid:轮询每 500ms 一次,不跑全域 print-disabled
19
+ const st = launchd.printState(ctx.runner, ctx.uid, label);
18
20
  return !st.registered || (!st.running && st.pid === null);
19
21
  }
20
22
 
@@ -27,17 +29,16 @@ export function stopEdgeLink(ctx) {
27
29
  // 删两开关(peer 依赖 relay,见 design §5)。PathState:rm RELAY_ON 不杀
28
30
  // 进程,但阻止退出后重拉
29
31
  ctx.state.removeOn(['relay', 'peer']);
30
- if (!launchd.inspect(ctx.runner, ctx.uid, label).registered) return { gone: true, label };
32
+ if (!launchd.printState(ctx.runner, ctx.uid, label).registered)
33
+ return { gone: true, label };
31
34
 
32
- let remaining = TERM_BUDGET_MS;
33
- for (let attempt = 0; attempt < 2; attempt += 1) {
35
+ for (let attempt = 0; attempt < TERM_ROUNDS; attempt += 1) {
34
36
  launchd.killJob(ctx.runner, ctx.uid, label, 'TERM');
35
- const end = Date.now() + Math.min(20_000, remaining);
37
+ const end = Date.now() + ROUND_MS;
36
38
  while (Date.now() < end) {
37
39
  if (isGone(ctx, label)) return { gone: true, label };
38
40
  sleepMs(POLL_MS);
39
41
  }
40
- remaining -= 20_000;
41
42
  }
42
43
  return { gone: isGone(ctx, label), label };
43
44
  }
@@ -82,22 +82,62 @@ export function parseDisabled(stdout) {
82
82
  */
83
83
 
84
84
  /**
85
- * print + print-disabled 合成四态所需的全部事实。
85
+ * 整个 gui 域的 disabled override 字典(一次 print-disabled)。同一域多个
86
+ * label 体检时循环外取一次、inspectWith 共用——全域 dump 与查哪个 label 无关。
87
+ * @param {import('./exec.mjs').Runner} runner
88
+ * @param {number} uid
89
+ * @returns {Map<string, boolean>}
90
+ */
91
+ export function disabledMap(runner, uid) {
92
+ return parseDisabled(
93
+ runner.run('launchctl', ['print-disabled', guiDomain(uid)]).stdout,
94
+ );
95
+ }
96
+
97
+ /**
98
+ * print + 预取字典合成四态(inspect 的 map 注入版;字典由调用方循环外取一次
99
+ * 共用)。print 先行:未注册不碰传入 map。
100
+ * @param {import('./exec.mjs').Runner} runner
101
+ * @param {number} uid
102
+ * @param {string} label
103
+ * @param {Map<string, boolean>} map disabledMap 的产物
104
+ * @returns {JobState}
105
+ */
106
+ export function inspectWith(runner, uid, label, map) {
107
+ const printed = printState(runner, uid, label);
108
+ if (!printed.registered) {
109
+ return { registered: false, disabled: false, running: false, pid: null, runs: null, lastExitCode: null };
110
+ }
111
+ return { ...printed, disabled: map.get(label) === true };
112
+ }
113
+
114
+ /**
115
+ * print + print-disabled 合成四态所需的全部事实(单 label 便捷封装)。
116
+ * print 在前、未注册即返回(不白跑全域 dump)。
86
117
  * @param {import('./exec.mjs').Runner} runner
87
118
  * @param {number} uid
88
119
  * @param {string} label
89
120
  * @returns {JobState}
90
121
  */
91
122
  export function inspect(runner, uid, label) {
92
- const domain = guiDomain(uid);
93
- const printed = parsePrint(runner.run('launchctl', ['print', `${domain}/${label}`]));
123
+ const printed = printState(runner, uid, label);
94
124
  if (!printed.registered) {
95
125
  return { registered: false, disabled: false, running: false, pid: null, runs: null, lastExitCode: null };
96
126
  }
97
- const disabledMap = parseDisabled(
98
- runner.run('launchctl', ['print-disabled', domain]).stdout,
127
+ return { ...printed, disabled: disabledMap(runner, uid).get(label) === true };
128
+ }
129
+
130
+ /**
131
+ * 只要注册/运行/pid 事实(stop 轮询专用):不跑全域 print-disabled。
132
+ * @param {import('./exec.mjs').Runner} runner
133
+ * @param {number} uid
134
+ * @param {string} label
135
+ * @returns {ReturnType<typeof parsePrint>}
136
+ */
137
+ export function printState(runner, uid, label) {
138
+ return parsePrint(
139
+ runner.run('launchctl', ['print', `${guiDomain(uid)}/${label}`]),
99
140
  );
100
- return { ...printed, disabled: disabledMap.get(label) === true };
101
141
  }
102
142
 
103
143
  /** 以下均返回原始 RunResult,由命令层判 code(编排顺序是冻结行为,勿在此吞错)。 */
@@ -109,6 +149,20 @@ export const bootstrap = (runner, uid, plistPath) =>
109
149
  runner.run('launchctl', ['bootstrap', guiDomain(uid), plistPath]);
110
150
  export const kickstart = (runner, uid, label) =>
111
151
  runner.run('launchctl', ['kickstart', '-k', `${guiDomain(uid)}/${label}`]);
152
+ /**
153
+ * enable + bootstrap 连发(未注册 job 的加载序列)。任一步失败抛错——
154
+ * enable 失败若吞掉,只会以 bootstrap error 5 的间接形式浮出,排障被带偏。
155
+ * @param {import('./exec.mjs').Runner} runner
156
+ * @param {number} uid
157
+ * @param {string} label
158
+ * @param {string} plistPath
159
+ */
160
+ export function enableBootstrap(runner, uid, label, plistPath) {
161
+ const en = enable(runner, uid, label);
162
+ if (en.code !== 0) throw new Error(`enable 失败(${label}):${en.stderr.trim()}`);
163
+ const b = bootstrap(runner, uid, plistPath);
164
+ if (b.code !== 0) throw new Error(`bootstrap 失败(${label}):${b.stderr.trim()}`);
165
+ }
112
166
  /** kickstart 对 disabled job 被拒(实测矩阵),kickstart 前一律幂等 enable。
113
167
  * enable 失败要报(本文件宣言「勿在此吞错」):否则以 kickstart 被拒的
114
168
  * 间接形式浮出,排障方向被带偏。 */