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.
@@ -7,6 +7,8 @@ import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import * as launchd from '../lib/launchd.mjs';
9
9
  import * as systemd from '../lib/systemd.mjs';
10
+ import { ensureLoaded } from '../lib/manage.mjs';
11
+ import { assertUnitSwitchArgs } from '../lib/cliargs.mjs';
10
12
  import { relayLabel, relayUnitName, plistFileName } from '../lib/render.mjs';
11
13
  import { enablePeer } from './register.mjs';
12
14
 
@@ -26,22 +28,12 @@ function startCore(ctx) {
26
28
  const label = relayLabel(ctx.topo.relay.alias);
27
29
  const plist = path.join(ctx.paths.launchAgentsDir, plistFileName(label));
28
30
  if (!fs.existsSync(plist)) throw new Error(`尚未安装(缺 ${plist}),先跑 ssh-net install`);
29
- const st = launchd.inspect(ctx.runner, ctx.uid, label);
30
- if (!st.registered) {
31
- const en = launchd.enable(ctx.runner, ctx.uid, label);
32
- if (en.code !== 0) throw new Error(`enable 失败:${en.stderr.trim()}`);
33
- const r = launchd.bootstrap(ctx.runner, ctx.uid, plist);
34
- if (r.code !== 0) throw new Error(`启动失败:${r.stderr.trim()}`);
35
- return 'relay 已开启';
36
- }
37
- if (!st.running) {
38
- // kickstartEnabled:kickstart 对 disabled job 被拒(stop 中途失败/手工
39
- // disable 的残留态),先幂等 enable
40
- const r = launchd.kickstartEnabled(ctx.runner, ctx.uid, label);
41
- if (r.code !== 0) throw new Error(`启动失败:${r.stderr.trim()}`);
42
- return 'relay 已重新拉起';
43
- }
44
- if (st.disabled) launchd.enable(ctx.runner, ctx.uid, label); // 在跑但 override 残留:清掉防退出后不重拉
31
+ // start 语义:在册但停着要踢活;在跑但 disabled 只清 override、不闪断
32
+ const action = ensureLoaded(ctx, { label, plistPath: plist }, {
33
+ kickWhenStopped: true,
34
+ });
35
+ if (action === 'bootstrapped') return 'relay 已开启';
36
+ if (action === 'kickstarted') return 'relay 已重新拉起';
45
37
  return 'relay 已在运行';
46
38
  }
47
39
 
@@ -51,18 +43,15 @@ export function run(ctx, args = []) {
51
43
  const targets = parseTargets(args); // ['relay','peer'] 或 ['relay'];link 抛错
52
44
 
53
45
  if (targets.includes('peer')) {
54
- // 默认/-a/peer:enablePeer 置两开关(幂等)+ 立即报名
55
- const msg = enablePeer(ctx);
56
- return before.relay && before.peer
57
- ? msg.replace('peer 已开启', '隧道已是开启状态')
58
- : msg;
46
+ // 默认/-a/peer:enablePeer 置两开关(幂等)+ 立即报名。开关此前已
47
+ // 全开时措辞由 enablePeer 内部一处选词
48
+ return enablePeer(ctx, before.relay && before.peer);
59
49
  }
60
50
  ctx.state.setOn(['relay']);
61
51
  return `relay ${before.relay ? '已是开启状态' : '已开启'}(隧道基础,不报名——要被 core 连到再 ssh-net start peer)`;
62
52
  }
63
53
  // core/node 是单总开关(等同 --all):显式 -a/--all 收下,其余参数拒绝
64
- if (args.length && !(args.length === 1 && (args[0] === '-a' || args[0] === '--all')))
65
- throw new Error('本机是单总开关,start 不带参数(-a/--all 亦可,等同缺省)');
54
+ assertUnitSwitchArgs(args, 'start');
66
55
  if (ctx.role === 'core') return startCore(ctx);
67
56
  if (ctx.role === 'node') {
68
57
  const r = systemd.startUnit(ctx.runner, relayUnitName(ctx.topo.relay.alias));
@@ -9,15 +9,19 @@
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import {
12
- auditScript, auditLink, readRuntimeVersion, runtimeVersionIssue,
12
+ auditScript, auditLink, runtimeVersionIssue,
13
13
  } from '../lib/runtime.mjs';
14
14
  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,44 +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 };
60
- }
61
-
62
- /** 版本对账问题(各角色共用);版本值不单列展示,不一致才说话。 */
63
- function versionInfo(ctx) {
64
- const issue = runtimeVersionIssue(ctx.paths);
65
- return { issue, runtimeVersion: readRuntimeVersion(ctx.paths) };
57
+ return { issues, entityAudits };
66
58
  }
67
59
 
68
60
  /** forward 的人话标签:写出目标(loopback 是落地机环回)。 */
@@ -73,6 +65,15 @@ function forwardLabel(f) {
73
65
  return `端口转发 127.0.0.1:${f.listenPort} → ${target}`;
74
66
  }
75
67
 
68
+ /** relay 口没在监听时的 issue(core/node 同款文案):不可达与没监听分开报——
69
+ * 把 relay 不可达断言成「没在监听」会把故障点错指向本机转发,排障方向
70
+ * 完全不同。 */
71
+ function relayPortIssue(relayAlias, port, r) {
72
+ return r.reachable === false
73
+ ? `连不上 ${relayAlias}(${r.detail || 'ssh 探测失败'}),入口 ${port} 状态未知——查 ${relayAlias} 可达性或本机网络`
74
+ : `${relayAlias} 入口 ${port} 没在监听:在外面暂时进不来(断线会自动重连;持续出现请查 ${relayAlias} 或本机网络)`;
75
+ }
76
+
76
77
  async function relayPortListening(ctx, port) {
77
78
  // relay 别名的 User/HostName 由 ssh config Host 块提供;
78
79
  // BatchMode 防换机器/换钥匙时在终端闪密码提示;IdentitiesOnly 防 agent
@@ -89,54 +90,42 @@ async function relayPortListening(ctx, port) {
89
90
  }
90
91
 
91
92
  /** edge 的 relay 线路实测:命令行显式 -J 经 relay 跑一条真 ssh(报名/中继同
92
- * 信道;字面 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)。 */
93
96
  async function relayPathOk(ctx) {
94
- const r = await ctx.runner.runAsync('ssh', [
95
- '-J', ctx.topo.relay.alias,
96
- '-p', String(ctx.topo.core.relayPort),
97
- '-o', `HostKeyAlias=${ctx.topo.core.alias}`,
98
- '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5',
99
- '-o', 'IdentitiesOnly=yes',
100
- '-o', 'ControlMaster=no', '-o', 'ControlPath=none',
101
- `${ctx.topo.core.user}@127.0.0.1`, 'true',
102
- ], { timeout: 8000 });
97
+ const r = await ctx.runner.runAsync(
98
+ 'ssh',
99
+ coreViaRelayArgs(ctx.topo, { connectTimeout: 5, remoteCommand: 'true' }),
100
+ { timeout: 8000 },
101
+ );
103
102
  return r.code === 0;
104
103
  }
105
104
 
106
105
  async function collectEdge(ctx) {
107
106
  const { topo, paths, state } = ctx;
108
107
  const issues = [];
109
- const { issue: vIssue, runtimeVersion } = versionInfo(ctx);
108
+ const vIssue = runtimeVersionIssue(ctx.paths);
110
109
  if (vIssue) issues.push(vIssue);
111
- // link 附加件以 marker 为准:默认只有 5 实体、无服务软链;装了才加
110
+ // link 附加件以 marker 为准:默认只有 3 实体、无服务软链;装了才加
112
111
  // link-core(转发口只取决于装没装,不是运行时开关)
113
112
  const linkInstalled = fs.existsSync(paths.linkEnabledFile);
114
- /** @type {[string,string][]} */
115
- const entities = [
116
- ['sn-probe', 'sn-probe'],
117
- ['sn-route', 'sn-route'],
118
- ['sn-ipv6', 'sn-ipv6'],
119
- ];
120
- /** @type {[string,string][]} */
121
- const serviceLinks = [];
122
- if (linkInstalled) {
123
- entities.push(['ssh-net-link-core', 'ssh-net-link-core']);
124
- serviceLinks.push([linkLinkName(topo.core.alias), 'ssh-net-link-core']);
125
- }
126
- const { issues: rtIssues, links } = runtimeIssues(ctx, { entities, serviceLinks });
113
+ const plan = edgeRuntimePlan(topo, linkInstalled);
114
+ const { issues: rtIssues, entityAudits } = runtimeIssues(ctx, plan);
127
115
  issues.push(...rtIssues);
128
116
 
129
117
  // routes 体检(sn-route 实体在才查:没装时 rtIssues 已报「尚未安装」):
130
118
  // routes 被手删/过期会让 ssh 静默退回 lan 直连,是故障、进 issues。文件尾部
131
119
  // 的 VS Code 打标块同属这份内容,逐字节对账一并覆盖,不用单独体检
132
- if (links.find((l) => l.link === 'sn-route')?.audit === 'ok') {
120
+ if (entityAudits.some((a) => a.name === 'sn-route' && a.audit === 'ok')) {
133
121
  const routeAudit = auditConfFragment(paths.routesFile, renderRoutes(topo, ctx.self.alias));
134
122
  if (routeAudit !== 'ok')
135
123
  issues.push(`选路片段 conf.d/routes ${routeAudit === 'missing' ? '缺失' : '与 topology 不一致'}——跑一次 ssh-net install 刷新`);
136
124
  }
137
125
 
126
+ // 显示只消费 registered/running:轻量 print 即可,不跑全域 print-disabled
138
127
  const label = linkLabel(topo.core.alias);
139
- const job = launchd.inspect(ctx.runner, ctx.uid, label);
128
+ const job = launchd.printState(ctx.runner, ctx.uid, label);
140
129
  const switches = state.readSwitches();
141
130
 
142
131
  // 非法组合:peer 依赖 relay。开关是「文件即接口」——手 touch/rm state 里
@@ -145,6 +134,16 @@ async function collectEdge(ctx) {
145
134
  if (switches.peer && !switches.relay)
146
135
  issues.push('开关组合异常:peer 开但 relay 关(peer 依赖 relay,多半是 state 里的开关被手动改动)——跑一次 ssh-net stop 后再按需要 start');
147
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
+
148
147
  // 就绪实测并发(On 是意图、ready 是事实;开关关的线路不探测=null)。
149
148
  // 转发口只有装了 link 才可能存在——默认形态不探
150
149
  const relayOk = ctx.relayOk ?? relayPathOk; // 测试可注入
@@ -161,7 +160,7 @@ async function collectEdge(ctx) {
161
160
  const coreLanIp = ctx.hostTable.get(topo.core.alias)?.hostname;
162
161
  const lanIdx = switches.relay && coreLanIp ? probes.length : -1;
163
162
  if (lanIdx >= 0) probes.push(openTcp(coreLanIp, 22, 1200));
164
- const got = await Promise.all(probes);
163
+ const [got, v6Probe] = await Promise.all([Promise.all(probes), v6P]);
165
164
  const relayReady = got[0];
166
165
  const peerReady = got[1];
167
166
  const ports = {};
@@ -169,6 +168,13 @@ async function collectEdge(ctx) {
169
168
  topo.forwards.forEach((f, i) => { ports[f.listenPort] = got[2 + i]; });
170
169
  const lanReachable = lanIdx >= 0 ? got[lanIdx] : false;
171
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
+
172
178
  if (lanReachable)
173
179
  issues.push(`检测到 ${topo.core.alias}(${coreLanIp})局域网直连可达——隧道可能在空转绕中继;人在办公室可 ssh-net stop`);
174
180
 
@@ -185,58 +191,47 @@ async function collectEdge(ctx) {
185
191
  if (f.targetAlias === 'loopback' && !ports[f.listenPort])
186
192
  issues.push(`${forwardLabel(f)} 未就绪:edge 侧正常时多半是 core 上的出口代理(microsocks)没跑——到 core 上查 local.microsocks`);
187
193
 
188
- // v6 只是诊断线索不是判决:探测没跑成(超时被杀/非零退出/实体缺失)时
189
- // 不能谎称「没有 IPv6」——那个结论只在 sn-ipv6 正常跑完且无输出时才成立
190
- //(与 doctor 的 probeOk 同判据;sn-ipv6 自身退出码恒 0,code!==0 只会是
191
- // 超时或崩溃)。全关(在办公室)时 render 早返回不显示 v6 行,不白跑
192
- let v6 = '';
193
- let v6ProbeOk = false;
194
- if ((switches.relay || switches.peer)
195
- && links.find((l) => l.link === 'sn-ipv6')?.audit === 'ok') {
196
- const probe = ctx.runner.runRaw(path.join(paths.binDir, 'sn-ipv6'), [], { timeout: 5000 });
197
- v6 = probe.stdout.trim();
198
- v6ProbeOk = !probe.error && probe.code === 0;
199
- }
200
-
201
194
  const forwardViews = linkInstalled
202
195
  ? topo.forwards.map((f) => [forwardLabel(f), ports[f.listenPort]])
203
196
  : [];
204
197
  return {
205
198
  role: 'edge', alias: ctx.self.alias, switches, relayReady, peerReady,
206
- linkInstalled, job, links, ports, forwardViews,
199
+ linkInstalled, job, ports, forwardViews,
207
200
  coreAlias: topo.core.alias, relayAlias: topo.relay.alias,
208
- v6, v6ProbeOk, runtimeVersion, issues,
201
+ v6, v6ProbeOk, issues,
209
202
  };
210
203
  }
211
204
 
212
205
  async function collectCore(ctx) {
213
206
  const { topo, paths } = ctx;
214
207
  const issues = [];
215
- const { issue: vIssue, runtimeVersion } = versionInfo(ctx);
208
+ const vIssue = runtimeVersionIssue(ctx.paths);
216
209
  if (vIssue) issues.push(vIssue);
217
- const { issues: rtIssues } = runtimeIssues(ctx, {
218
- entities: [['ssh-net-uplink-relay', 'ssh-net-uplink-relay']],
219
- serviceLinks: [[relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay']],
220
- });
210
+ const { issues: rtIssues } = runtimeIssues(ctx, relayRuntimePlan(topo));
221
211
  issues.push(...rtIssues);
222
212
 
213
+ // disabled override 是整域同一份字典:relay job 与各 edge job 共用一次拉取
214
+ const dmap = launchd.disabledMap(ctx.runner, ctx.uid);
223
215
  const relayLabelName = relayLabel(topo.relay.alias);
224
- const relayJob = launchd.inspect(ctx.runner, ctx.uid, relayLabelName);
216
+ const relayJob = launchd.inspectWith(ctx.runner, ctx.uid, relayLabelName, dmap);
225
217
  // relay 口实测是 8s 超时的真 ssh:先发起来,边等边做下面的注册态体检
226
218
  const relayPortP = relayPortListening(ctx, topo.core.relayPort);
227
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
+
228
226
  const edges = [];
229
227
  for (const e of topo.edges) {
230
228
  const label = edgeLabel(e.alias);
231
- const st = launchd.inspect(ctx.runner, ctx.uid, label);
229
+ const st = launchd.inspectWith(ctx.runner, ctx.uid, label, dmap);
232
230
  // 已连接过的随身机,回拨组件一并体检:回拨脚本/软链只有 _register
233
231
  // (报名)这条刷新通道,漏刷会拿旧脚本拨号
234
232
  if (st.registered) {
235
233
  const bad = [];
236
- if (auditScript(
237
- path.join(paths.binDir, 'ssh-net-uplink-edge'),
238
- packageScriptPath('ssh-net-uplink-edge'),
239
- ) !== 'ok') bad.push('回拨脚本');
234
+ if (callbackEntityAudit !== 'ok') bad.push('回拨脚本');
240
235
  const linkState = auditLink(
241
236
  path.join(paths.binDir, edgeLinkName(e.alias)),
242
237
  'ssh-net-uplink-edge',
@@ -254,11 +249,8 @@ async function collectCore(ctx) {
254
249
  // install)都会让 `ssh <别名>` 失败或解析错。休眠(disabled)时片段
255
250
  // 本就该删(六连败收尸),不报;未注册无 v6 也不报
256
251
  let fragmentAudit = null;
257
- if (st.registered && !st.disabled && v6) {
258
- fragmentAudit = auditConfFragment(
259
- paths.edgeHostFile(e.alias),
260
- renderEdgeHost({ alias: e.alias, aliases: e.aliases, user: e.user, v6 }),
261
- );
252
+ if (edgeFragmentShouldExist(st, v6)) {
253
+ fragmentAudit = auditConfFragment(paths.edgeHostFile(e.alias), edgeFragmentContent(e, v6));
262
254
  if (fragmentAudit !== 'ok')
263
255
  issues.push(`${e.alias} 的 ssh 入口片段${fragmentAudit === 'missing' ? '缺失' : '过期'}(state 有 v6、job 未休眠)——跑一次 ssh-net install 重建`);
264
256
  }
@@ -275,30 +267,20 @@ async function collectCore(ctx) {
275
267
 
276
268
  const relayPort = await relayPortP;
277
269
  if (!relayJob.running) issues.push('relay 未在运行——ssh-net start 可拉起');
278
- if (!relayPort.listening) {
279
- // 连不上 relay 时入口状态未知,别断言成「没在监听」——那是把故障点
280
- // 指向本机转发,实际更可能是 relay 不可达(排障方向完全不同)
281
- if (relayPort.reachable === false)
282
- issues.push(`连不上 ${topo.relay.alias}(${relayPort.detail || 'ssh 探测失败'}),入口 ${topo.core.relayPort} 状态未知——查 ${topo.relay.alias} 可达性或本机网络`);
283
- else
284
- issues.push(`${topo.relay.alias} 入口 ${topo.core.relayPort} 没在监听:在外面暂时进不来(断线会自动重连;持续出现请查 ${topo.relay.alias} 或本机网络)`);
285
- }
270
+ if (!relayPort.listening)
271
+ issues.push(relayPortIssue(topo.relay.alias, topo.core.relayPort, relayPort));
286
272
 
287
273
  // topology 已删(edge 改名/退役)但磁盘上还有回拨 job:不渲染成 edges 行
288
274
  //(state/conf.d 都按新别名走),单独点破。残留无害——六连败后自休眠、
289
275
  // 端口争抢由胜者持有且监听功能等价——但不可见会让改名现场少一条线索
290
276
  const knownAliases = new Set(topo.edges.map((e) => e.alias));
291
- try {
292
- for (const f of fs.readdirSync(paths.launchAgentsDir)) {
293
- if (!f.startsWith('local.ssh-net-uplink-edge-') || !f.endsWith('.plist')) continue;
294
- const alias = f.slice('local.ssh-net-uplink-edge-'.length, -'.plist'.length);
295
- if (!knownAliases.has(alias))
296
- issues.push(`${alias} 的回拨 job 还在但 topology 已没有这个 edge(改名/退役残留,无害)——清理:launchctl bootout gui/${ctx.uid}/${f.replace(/\.plist$/, '')} 后删该 plist;或无视(它六连败后会自休眠)`);
297
- }
298
- } catch { /* LaunchAgents 目录不存在(未装) */ }
277
+ for (const alias of launchd.edgeAliasesOnDisk(paths.launchAgentsDir)) {
278
+ if (!knownAliases.has(alias))
279
+ issues.push(`${alias} 的回拨 job 还在但 topology 已没有这个 edge(改名/退役残留,无害)——清理:launchctl bootout gui/${ctx.uid}/${edgeLabel(alias)} 后删该 plist;或无视(它六连败后会自休眠)`);
280
+ }
299
281
 
300
282
  return {
301
- role: 'core', alias: ctx.self.alias, runtimeVersion,
283
+ role: 'core', alias: ctx.self.alias,
302
284
  relayAlias: topo.relay.alias, relayJob, relayPort, edges, issues,
303
285
  };
304
286
  }
@@ -306,12 +288,9 @@ async function collectCore(ctx) {
306
288
  async function collectNode(ctx) {
307
289
  const { topo } = ctx;
308
290
  const issues = [];
309
- const { issue: vIssue, runtimeVersion } = versionInfo(ctx);
291
+ const vIssue = runtimeVersionIssue(ctx.paths);
310
292
  if (vIssue) issues.push(vIssue);
311
- const { issues: rtIssues } = runtimeIssues(ctx, {
312
- entities: [['ssh-net-uplink-relay', 'ssh-net-uplink-relay']],
313
- serviceLinks: [[relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay']],
314
- });
293
+ const { issues: rtIssues } = runtimeIssues(ctx, relayRuntimePlan(topo));
315
294
  issues.push(...rtIssues);
316
295
 
317
296
  const unit = relayUnitName(topo.relay.alias);
@@ -319,16 +298,11 @@ async function collectNode(ctx) {
319
298
  const relayPort = await relayPortListening(ctx, ctx.self.relayPort);
320
299
  if (active !== 'active')
321
300
  issues.push(`系统服务 ${unit} 状态 ${active}——systemctl status ${unit} 查看`);
322
- if (!relayPort.listening) {
323
- // 与 core 侧同款区分:relay 不可达 ≠ 入口没在监听,排障方向不同
324
- if (relayPort.reachable === false)
325
- issues.push(`连不上 ${topo.relay.alias}(${relayPort.detail || 'ssh 探测失败'}),入口 ${ctx.self.relayPort} 状态未知——查 ${topo.relay.alias} 可达性或本机网络`);
326
- else
327
- issues.push(`${ctx.topo.relay.alias} 入口 ${ctx.self.relayPort} 没在监听:在外面暂时进不来(断线会自动重连;持续出现请查 ${ctx.topo.relay.alias} 或本机网络)`);
328
- }
301
+ if (!relayPort.listening)
302
+ issues.push(relayPortIssue(topo.relay.alias, ctx.self.relayPort, relayPort));
329
303
 
330
304
  return {
331
- role: 'node', alias: ctx.self.alias, runtimeVersion,
305
+ role: 'node', alias: ctx.self.alias,
332
306
  relayAlias: topo.relay.alias, unit, active, relayPort, issues,
333
307
  };
334
308
  }
@@ -360,6 +334,13 @@ function profileOf(sw, linkInstalled) {
360
334
  return '仅中继信道(待命:不报名、无本地转发口)';
361
335
  }
362
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
+
363
344
  export function renderText(s) {
364
345
  const lines = [];
365
346
  lines.push(`ssh-net ${s.role} ${s.alias}`);
@@ -403,9 +384,7 @@ export function renderText(s) {
403
384
  }
404
385
  lines.push(` 后台任务: ${!s.job.registered ? `未装 link(默认零常驻)` : s.job.running ? 'link 运行中' : 'link 已停止'}`);
405
386
  } else if (s.role === 'core') {
406
- lines.push(s.relayPort.listening
407
- ? ` relay: ✓ 开着(在外面经 ${s.relayAlias} 进入 ${s.alias} · 入口 ${s.relayPort.port})`
408
- : ` relay: ✗ ${s.relayPort.reachable === false ? `连不上 ${s.relayAlias},入口状态未知` : `入口 ${s.relayPort.port} 没在监听`}`);
387
+ lines.push(relayStatusLine(s));
409
388
  lines.push(` relay 进程: ${s.relayJob.running ? `运行中${exitNote(s.relayJob.lastExitCode)}` : '未运行'}`);
410
389
  lines.push(' edge:');
411
390
  for (const e of s.edges) {
@@ -424,9 +403,7 @@ export function renderText(s) {
424
403
  lines.push(` ${e.alias} ${state}${frag}`);
425
404
  }
426
405
  } else {
427
- lines.push(s.relayPort.listening
428
- ? ` relay: ✓ 开着(在外面经 ${s.relayAlias} 进入 ${s.alias} · 入口 ${s.relayPort.port})`
429
- : ` relay: ✗ ${s.relayPort.reachable === false ? `连不上 ${s.relayAlias},入口状态未知` : `入口 ${s.relayPort.port} 没在监听`}`);
406
+ lines.push(relayStatusLine(s));
430
407
  lines.push(` relay 进程: ${s.active === 'active' ? '运行中(systemd)' : `${s.active}(systemd)`}`);
431
408
  }
432
409
 
@@ -439,5 +416,5 @@ export function renderText(s) {
439
416
 
440
417
  export async function run(ctx) {
441
418
  const s = await collect(ctx);
442
- return { text: renderText(s), issues: s.issues, status: s };
419
+ return { text: renderText(s), issues: s.issues };
443
420
  }
@@ -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 已关闭(重启后保持关闭)';
@@ -4,6 +4,7 @@
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { removeJob } from '../lib/manage.mjs';
7
+ import * as launchd from '../lib/launchd.mjs';
7
8
  import * as systemd from '../lib/systemd.mjs';
8
9
  import {
9
10
  linkLabel, plistFileName,
@@ -12,17 +13,6 @@ import {
12
13
 
13
14
  const rm = (p) => fs.rmSync(p, { recursive: true, force: true });
14
15
 
15
- /** 列出磁盘上全部 uplink-edge plist(topology 已删的机器只能靠 glob 发现)。 */
16
- function edgePlistFiles(ctx) {
17
- let files = [];
18
- try {
19
- files = fs
20
- .readdirSync(ctx.paths.launchAgentsDir)
21
- .filter((f) => f.startsWith('local.ssh-net-uplink-edge-') && f.endsWith('.plist'));
22
- } catch { /* 目录不存在 */ }
23
- return files;
24
- }
25
-
26
16
  function uninstallEdge(ctx) {
27
17
  const label = linkLabel(ctx.topo.core.alias);
28
18
  removeJob(ctx, label, path.join(
@@ -41,8 +31,9 @@ function uninstallCore(ctx) {
41
31
  const dir = ctx.paths.launchAgentsDir;
42
32
  // label → plist 路径:磁盘 glob(topology 已删的残留)∪ topology 在册 edge
43
33
  const edgeJobs = new Map();
44
- for (const f of edgePlistFiles(ctx)) {
45
- edgeJobs.set(f.replace(/\.plist$/, ''), path.join(dir, f));
34
+ for (const alias of launchd.edgeAliasesOnDisk(dir)) {
35
+ const label = edgeLabel(alias);
36
+ edgeJobs.set(label, path.join(dir, plistFileName(label)));
46
37
  }
47
38
  for (const e of ctx.topo.edges) {
48
39
  const label = edgeLabel(e.alias);
@@ -67,11 +58,9 @@ function uninstallNode(ctx) {
67
58
  if (ctx.uid !== 0)
68
59
  throw new Error('node 卸载写 /etc/systemd/system 需要 root,请以 root 运行');
69
60
  const unit = relayUnitName(ctx.topo.relay.alias);
70
- const s = systemd.stopUnit(ctx.runner, unit);
71
- // unit 不存在(未装/已卸)的无害失败放行;真失败必须报——否则删了 unit
72
- // 文件、systemd 里留下 ghost 态的在跑进程
73
- if (s.code !== 0 && !/not loaded/.test(s.stderr))
74
- throw new Error(`systemctl stop 失败:${s.stderr.trim()}`);
61
+ // not-loaded(未装/已卸)无害,真失败必须报——否则删了 unit 文件、
62
+ // systemd 里留下 ghost 态的在跑进程
63
+ systemd.stopIfLoaded(ctx.runner, unit);
75
64
  systemd.disableUnit(ctx.runner, unit); // 已禁无害
76
65
  rm(path.join(ctx.paths.systemdUnitDir, unit));
77
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
  }