ssh-net 26.11.2 → 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.
@@ -1,118 +1,89 @@
1
- // install:对账到 topology 描述的稳态。幂等:运行时脚本内容相同不重写、
2
- // plist/unit 字节相同不 bootout(不断连)。edge 只注册 PathState job(RELAY_ON
3
- // 不在不启动);core/node 会恢复 stop 的中继服务;core 不预建 uplink-edge
4
- //(首次报名才生成),node 写 unit 并 enable --now。
1
+ // install 对账本机组件。edge 注册本地转发任务,是否启动由 RELAY_ON 决定;
2
+ // core/node 恢复中继服务,core 到 edge 的回拨任务仍在首次报名时才创建
5
3
  import fs from 'node:fs';
6
4
  import path from 'node:path';
7
5
  import {
8
6
  CALLBACK_PORT, TERMINAL_NOTIFIER_PATHS, OSASCRIPT_PATH,
9
7
  } from '../lib/constants.mjs';
10
- import { syncPlist, removeJob } from '../lib/manage.mjs';
8
+ import { removeJobs, syncPlist } from '../lib/manage.mjs';
11
9
  import { syncConfFile } from '../lib/conf.mjs';
12
10
  import { ensureRuntime } from '../lib/runtime.mjs';
13
11
  import { edgeLinkJob, coreRelayJob, nodeRelayJob } from '../lib/jobs.mjs';
12
+ import { requireNodeHome } from '../lib/identity.mjs';
14
13
  import * as launchd from '../lib/launchd.mjs';
15
14
  import * as systemd from '../lib/systemd.mjs';
16
15
  import {
17
- classifyLocalPort, lsofListen, v6LoopbackPids, peerProbeOk,
16
+ forwardListenerPids, hasRouteTimeout, lsofListen, v6ListenerScope, peerProbeOk,
18
17
  } from '../lib/probe.mjs';
19
- import { readDirOrEmpty, writeFileAtomic } from '../lib/fsutil.mjs';
18
+ import { isExecutableFile, readDirOrEmpty, removeObsoleteNames } from '../lib/fsutil.mjs';
20
19
  import { packageScriptPath } from '../lib/paths.mjs';
21
20
  import {
22
21
  SN_PROBE, RESIDENT_SCRIPTS, edgeRuntimePlan, coreNodeRuntimePlan,
23
- edgeCallbacksPlan, linkAddonPlan, mergePlans,
24
22
  } from '../lib/manifest.mjs';
25
- import { linkLabel, renderEdgeHost, renderRoutes } from '../lib/render.mjs';
23
+ import {
24
+ edgeLabel, linkLabel, linkLinkName, relayLabel, relayLinkName, renderEdgeHost, renderRoutes,
25
+ } from '../lib/render.mjs';
26
26
 
27
- /** 对账只汇总有无变化;具体差异看文件与 launchd/systemd,不维护逐态文案。 */
28
- function compNote(results, entities) {
27
+ /** 只有常驻脚本本身发生变化,才提示要等进程重连 */
28
+ function syncRuntime(ctx, { entities, links }) {
29
+ const results = ensureRuntime(ctx, entities, links);
29
30
  if (!results.some(Boolean)) return '';
30
- const residentUpdated = entities.some(([name], i) =>
31
- results[i] && RESIDENT_SCRIPTS.includes(name));
32
- return residentUpdated
31
+ return entities.some((name, i) => results[i] && RESIDENT_SCRIPTS.includes(name))
33
32
  ? '后台脚本已同步,常驻进程将在下次重连后使用新版'
34
33
  : '后台脚本已同步';
35
34
  }
36
35
 
37
- /** 安装结果文案:组件刷新/配置更新若干条 note 合并进一对括号(''=零附加信息)。 */
38
36
  function notesPart(...notes) {
39
37
  const parts = notes.filter(Boolean);
40
38
  return parts.length ? `(${parts.join(';')})` : '';
41
39
  }
42
40
 
43
- /** plist/unit 的同构部署结果统一变成用户可读的任务变化。 */
44
41
  function deploymentNote(r, task, config) {
45
42
  if (!r.changed) return '';
46
43
  return r.restarted ? `${config}已更新,可能断开当前连接` : `${task}已同步`;
47
44
  }
48
45
 
49
- function coreNodeInstallMsg(comp, entryChanged, result, relayLine) {
46
+ function coreNodeInstallMsg(ctx, comp, entryChanged, result, removed) {
47
+ const relayLine = `${ctx.topo.relay.alias} 入口 ${ctx.self.relayPort}`;
50
48
  const note = notesPart(
51
49
  comp,
52
50
  entryChanged ? 'edge 入口已更新' : '',
53
51
  deploymentNote(result, '中继任务', '中继服务配置'),
52
+ removed ? '旧中继组件已移除' : '',
54
53
  );
55
54
  if (!note)
56
55
  return `已安装,服务配置无需改动;中继通道已开启(${relayLine})`;
57
56
  return `安装完成${note},中继通道已开启(${relayLine})`;
58
57
  }
59
58
 
60
- /** edge 端口预检(纯读 + banner 判定),冲突抛错并报持有者。转发口只在
61
- * link 附加件本次会装时才查:默认零常驻不绑这些口,他进程(如 VS Code
62
- * 自动转发到本机的端口)占用与本服务无关。 */
63
- async function precheckEdgePorts(ctx, linkOn) {
64
-
65
- const { runner, uid, topo } = ctx;
66
- const forwardPorts = topo.forwards.map((f) => f.listenPort);
67
- if (linkOn && forwardPorts.length > 0) {
68
- // 只要 pid 判持口者归属(link-core 是 exec ssh,job pid 即持口者)
69
- const jobPid = launchd.printState(runner, uid, linkLabel(topo.core.alias), true).pid;
70
- for (const port of forwardPorts) {
71
- const c = classifyLocalPort(runner, port, jobPid);
72
- if (c.kind === 'foreign') {
73
- throw new Error(`端口 ${port} 被别的程序占用(pid ${c.pids.join(',')}):\n${lsofListen(runner, port)}`);
74
- }
59
+ /** 端口冲突时在写任何产物前退出。转发端口由 link 的 ssh 进程持有,回拨端口则由 sshd 持有 */
60
+ async function precheckEdgePorts({ runner, uid, topo }, labels) {
61
+ const jobPids = () => new Set(labels.map((label) => launchd.printState(runner, uid, label).pid));
62
+ let owned = jobPids();
63
+ for (const { listenPort: port } of topo.forwards) {
64
+ const listeners = await forwardListenerPids(runner, port);
65
+ if (listeners.every((pid) => owned.has(pid))) continue;
66
+ // launchd 可能恰好在查端口期间重连,按最新的任务 PID 确认归属
67
+ owned = jobPids();
68
+ const foreign = listeners.filter((pid) => !owned.has(pid));
69
+ if (foreign.length) {
70
+ throw new Error(`端口 ${port} 被别的程序占用(pid ${foreign.join(',')}):\n${lsofListen(runner, port)}`);
75
71
  }
76
72
  }
77
73
 
78
- // 10022 持口者永远是本机 sshd,无法按 pid 溯源:读到 SSH banner 才认。
79
- // 只盯 [::1](本服务的监听面);127.0.0.1:10022 的持有者如 VS Code 本地
80
- // 转发与本服务不同地址族、可共存,不判冲突。
81
- // 一次 lsof 同时拿持有者 pid 与报错展示文本。预检执行包内探针:
82
- // 不能用待修复的 bin/sn-probe,否则探针损坏会把 install 自己的修复入口堵住
74
+ // 检查覆盖 [::1] 的 IPv6 监听;同号的纯 IPv4 监听可以共存。
75
+ // 用包内探针读 SSH 标识,不能让磁盘上待修复的探针堵住 install
83
76
  const listeners = lsofListen(runner, CALLBACK_PORT);
84
- if (
85
- v6LoopbackPids(listeners, CALLBACK_PORT).length > 0
86
- && !(await peerProbeOk(runner, path.dirname(packageScriptPath(SN_PROBE))))
87
- ) {
77
+ const scope = v6ListenerScope(listeners, CALLBACK_PORT);
78
+ if (scope === 'wildcard')
79
+ throw new Error(`端口 ${CALLBACK_PORT} 的 IPv6 通配监听占用了回拨地址 [::1]:\n${listeners}`);
80
+ if (scope === 'loopback' && !(await peerProbeOk(runner, path.dirname(packageScriptPath(SN_PROBE))))) {
88
81
  throw new Error(
89
82
  `端口 ${CALLBACK_PORT} 有程序在监听但没有响应(多半是断线残留,或被别的程序占用):\n${listeners}`,
90
83
  );
91
84
  }
92
85
  }
93
86
 
94
- /** 解析 edge install 的 link 意图:true=--with-link、false=--without-link、
95
- * undefined=无 flag;两 flag 同现或夹带未知参数即用法错误 */
96
- function parseLinkFlag(args) {
97
- /** @type {boolean|undefined} */
98
- let flag;
99
- for (const a of args) {
100
- if (a === '--with-link' || a === '--without-link') {
101
- if (flag !== undefined)
102
- throw new Error('--with-link 与 --without-link 不能同时使用');
103
- flag = a === '--with-link';
104
- } else {
105
- throw new Error(`未知参数:${a}——edge install 只接受 --with-link / --without-link`);
106
- }
107
- }
108
- return flag;
109
- }
110
-
111
- // 回连桌面通知的可选依赖:sn-route 的 peer_ready 优先 terminal-notifier、
112
- // 缺它走系统 osascript(默认路径单源在 constants,与 bash 侧的一致性靠
113
- // constants.test 锚);两个都没有(Linux)则直连恢复时无通知。装的时候
114
- // 说清楚,别等第一次用时疑惑
115
-
116
87
  /** 通知依赖提示('\n' 前缀的独立行;terminal-notifier 齐备返回 '')。 */
117
88
  export function notifyDepNote({ hasTerminalNotifier, hasOsascript }) {
118
89
  if (hasTerminalNotifier) return '';
@@ -121,154 +92,113 @@ export function notifyDepNote({ hasTerminalNotifier, hasOsascript }) {
121
92
  return '\n提示:此机没有桌面通知工具,直连恢复时不会弹通知(不影响连接功能)';
122
93
  }
123
94
 
124
- /** 本机真实检测(分档文案由 notifyDepNote 纯函数测试锚定)。 */
125
95
  function localNotifyDepNote() {
126
- const execOk = (p) => {
127
- try { fs.accessSync(p, fs.constants.X_OK); return true; } catch { return false; }
128
- };
129
96
  return notifyDepNote({
130
- hasTerminalNotifier: TERMINAL_NOTIFIER_PATHS.some(execOk),
131
- hasOsascript: execOk(OSASCRIPT_PATH),
97
+ hasTerminalNotifier: TERMINAL_NOTIFIER_PATHS.some(isExecutableFile),
98
+ hasOsascript: isExecutableFile(OSASCRIPT_PATH),
132
99
  });
133
100
  }
134
101
 
135
- async function installEdge(ctx, args) {
136
- const { topo, paths } = ctx;
137
- const flag = parseLinkFlag(args);
138
- // 本次 install 后 link 在不在:显式 flag 说了算,无 flag 按 marker
139
- const linkOn = flag === true
140
- || (flag !== false && fs.existsSync(paths.linkEnabledFile));
141
- // 预检纯读且在落任何产物之前:被拒时 bin/ 一个都不建
142
- await precheckEdgePorts(ctx, linkOn);
143
-
144
- // 先记下加装意图,失败后无参 install 也能继续;移除则等任务和脚本清理成功
145
- if (flag === true) {
146
- fs.mkdirSync(paths.sshNetDir, { recursive: true });
147
- writeFileAtomic(paths.linkEnabledFile, '1\n', { mode: 0o600 });
148
- }
102
+ /** 只收回指定前缀下不再使用的文件;即使对应任务早已移除,也能清掉残留 */
103
+ function removeObsoleteFiles(dir, prefix, keep) {
104
+ const obsolete = readDirOrEmpty(dir).filter((name) => name.startsWith(prefix) && !keep.includes(name));
105
+ return removeObsoleteNames(dir, obsolete, keep);
106
+ }
149
107
 
150
- // 实体/软链清单唯一来源在 manifest:基础 3 实体,linkOn 才加第 4 实体与
151
- // 带机器名软链。回拨通知与 link 秒切由 sn-route 成功点在本地执行
152
- const plan = edgeRuntimePlan(topo, linkOn);
153
- const comp = compNote(ensureRuntime(ctx, plan.entities, plan.links), plan.entities);
154
- let linkChanged = false;
108
+ async function installEdge(ctx) {
109
+ const { topo, paths } = ctx;
110
+ const link = edgeLinkJob(ctx);
111
+ const diskLabels = launchd.labelsOnDisk(paths.launchAgentsDir, linkLabel(''));
112
+ const obsolete = diskLabels.filter((label) => label !== link?.label);
113
+ await precheckEdgePorts(ctx, link ? [link.label, ...obsolete] : []);
114
+ const comp = syncRuntime(ctx, edgeRuntimePlan(topo));
115
+ // link 可能在 bootstrap 内立即连接;新旧任务各自启动前都要读到配套的 routes
116
+ let routesChanged = false;
117
+ let restoreRoutes;
118
+ const routes = {
119
+ apply() {
120
+ routesChanged = syncConfFile(paths.routesFile, renderRoutes(topo, ctx.self.alias), restore => { restoreRoutes = restore; });
121
+ },
122
+ restore() { restoreRoutes?.(); },
123
+ };
155
124
  let linkNote = '';
156
-
157
- if (linkOn) {
158
- // 附加件:渲染纯 ssh plist 并对账(RELAY_ON 在 syncPlist 按 stopped 语义
159
- // 首发,不在注册待命);转发参数是最终 -L argv
160
- const r = syncPlist(ctx, edgeLinkJob(ctx));
161
- if (r.lintError) throw new Error(`link plist 校验失败:${r.lintError}`);
162
- linkChanged = r.changed;
163
- linkNote = deploymentNote(r, '本地转发任务', '本地转发配置');
125
+ if (link) {
126
+ const job = syncPlist(ctx, link, obsolete, routes);
127
+ if (job.lintError) throw new Error(`link plist 校验失败:${job.lintError}`);
128
+ linkNote = deploymentNote(job, '本地转发任务', '本地转发配置');
164
129
  } else {
165
- // 默认零常驻:清掉加装过的 link 全部产物。plist 必须先 bootout,否则
166
- // 删了实体后 launchd 每 ThrottleInterval 刷 ENOENT
167
- const label = linkLabel(topo.core.alias);
168
- const plistPath = paths.plistFile(label);
169
- const jobRemoved = removeJob(ctx, label, plistPath);
170
- const addon = linkAddonPlan(topo);
171
- const addonPaths = [...addon.entities, ...addon.links].map(([name]) => paths.binScript(name));
172
- const addonRemoved = addonPaths.some((p) =>
173
- fs.lstatSync(p, { throwIfNoEntry: false }) !== undefined);
174
- for (const p of addonPaths) fs.rmSync(p, { force: true });
175
- if (flag === false) fs.rmSync(paths.linkEnabledFile, { force: true });
176
- linkChanged = jobRemoved || addonRemoved;
177
- if (linkChanged) linkNote = '本地转发任务与组件已移除';
130
+ removeJobs(ctx, obsolete);
131
+ routes.apply();
178
132
  }
179
-
180
- // conf.d 片段(design §4.2):edge 是 routes 的唯一安装角色——routes 含
181
- // 选路 Match 与尾部本机别名打标块
182
- const routesChanged = syncConfFile(paths.routesFile, renderRoutes(topo, ctx.self.alias));
183
- const depNote = localNotifyDepNote();
184
- const head = linkOn ? '安装完成(含本地端口转发)' : '安装完成';
185
- const base = (!comp && !linkChanged && !routesChanged && flag === undefined)
186
- ? '已安装,配置无需改动'
187
- : `${head}${notesPart(comp, linkNote, routesChanged ? 'ssh 配置片段已更新' : '')}`;
188
- const startNote = ctx.state.isOn('relay')
189
- ? ''
190
- : '\n当前为关闭状态;开启自动选路和 IPv6 直连:ssh-net start';
191
- return `${base}${startNote}${depNote}`;
133
+ removeObsoleteFiles(paths.binDir, linkLinkName(''), [linkLinkName(topo.core.alias)]);
134
+ fs.rmSync(paths.legacyLinkEnabledFile, { force: true });
135
+
136
+ const note = notesPart(comp, linkNote, obsolete.length ? '旧转发任务已移除' : '',
137
+ routesChanged ? 'ssh 配置片段已更新' : '');
138
+ const base = note ? `安装完成${note}` : '已安装,配置无需改动';
139
+ const startNote = ctx.state.isOn('relay') ? '' : '\n当前为关闭状态;开启自动选路和 IPv6 直连:ssh-net start';
140
+ return `${base}${startNote}${localNotifyDepNote()}`;
192
141
  }
193
142
 
194
- /**
195
- * core/node:按 topology 渲染每台 edge 的入口片段 conf.d/edge-<别名>(内容只随
196
- * topology 变,地址在 Include 的 state/addr 文件里),并删掉 topology 已没有的
197
- * 旧片段——conf.d/edge-* 全由本函数管。
198
- * @returns {boolean} 有无改动
199
- */
143
+ /** core/node 按 topology 写各 edge 的入口,并移除已经不在 topology 里的旧片段 */
200
144
  function syncEdgeEntries(ctx) {
201
145
  const { topo, paths } = ctx;
202
146
  let changed = false;
203
- const keep = new Set();
147
+ const keep = [];
204
148
  for (const e of topo.edges) {
205
149
  const file = paths.edgeHostFile(e.alias);
206
- keep.add(path.basename(file));
150
+ keep.push(path.basename(file));
207
151
  if (syncConfFile(file, renderEdgeHost(e))) changed = true;
208
152
  }
209
- const existing = readDirOrEmpty(paths.confDir);
210
- // 片段名公式唯一来源是 edgeHostFile(含 '' 即前缀),不抄 'edge-' 字面量
211
- const edgePrefix = path.basename(paths.edgeHostFile(''));
212
- for (const f of existing) {
213
- if (f.startsWith(edgePrefix) && !keep.has(f)) {
214
- fs.rmSync(path.join(paths.confDir, f), { force: true });
215
- changed = true;
216
- }
217
- }
218
- return changed;
153
+ const removed = removeObsoleteFiles(paths.confDir, path.basename(paths.edgeHostFile('')), keep);
154
+ return changed || removed;
219
155
  }
220
156
 
221
157
  function installCore(ctx) {
222
158
  const { topo, paths } = ctx;
159
+ const job = coreRelayJob(ctx);
160
+ const labels = launchd.labelsOnDisk(paths.launchAgentsDir);
161
+ const relayPrefix = relayLabel('');
162
+ const obsolete = labels.filter((label) => label.startsWith(relayPrefix) && label !== job.label);
223
163
  const entryChanged = syncEdgeEntries(ctx);
224
- // 磁盘在册 edge 的回拨组件在 install 时一并对账:否则 update 后 core
225
- // status 要对每台未联系的 edge 报组件异常,直到它下次报名才自愈
226
- const edges = launchd.edgeAliasesOnDisk(paths.launchAgentsDir);
227
- // relay 基础形态 + 磁盘在册 edge 的回拨组件(清单与报名/status 体检同源)
228
- const plan = mergePlans(coreNodeRuntimePlan(topo), edgeCallbacksPlan(edges));
229
- const comp = compNote(ensureRuntime(ctx, plan.entities, plan.links), plan.entities);
230
- const r = syncPlist(ctx, coreRelayJob(ctx));
231
- // lint 失败不能静默报「安装完成」:syncPlist 以返回值交错误(register 同判)
164
+ // 同一份磁盘清单里,旧中继要撤掉,已经登记的回拨只刷新脚本
165
+ const edgePrefix = edgeLabel('');
166
+ const edges = labels.filter((label) => label.startsWith(edgePrefix))
167
+ .map((label) => label.slice(edgePrefix.length));
168
+ const comp = syncRuntime(ctx, coreNodeRuntimePlan(topo, edges));
169
+ const r = syncPlist(ctx, job, obsolete);
232
170
  if (r.lintError) throw new Error(`relay plist 校验失败:${r.lintError}`);
233
- return coreNodeInstallMsg(comp, entryChanged, r,
234
- `${topo.relay.alias} 入口 ${topo.core.relayPort}`);
171
+ const removedLinks = removeObsoleteFiles(paths.binDir, relayLinkName(''), [relayLinkName(topo.relay.alias)]);
172
+ return coreNodeInstallMsg(ctx, comp, entryChanged, r, obsolete.length || removedLinks);
235
173
  }
236
174
 
237
- function installNode(ctx) {
175
+ function installNode(ctx, home) {
238
176
  const { topo, paths, runner } = ctx;
239
- if (ctx.uid !== 0)
240
- throw new Error('node 安装写 /etc/systemd/system 需要 root,请运行 sudo -i ssh-net install');
241
- const { home, ...job } = nodeRelayJob(ctx);
242
- if (ctx.env.HOME !== home)
243
- throw new Error('HOME 与 root 账户的家目录不一致,请运行 sudo -i ssh-net install');
244
- // ExecStart 按空白分词,HOME 含空白会拆断脚本路径
245
- if (/\s/.test(home))
246
- throw new Error(`node 的 HOME(${home})含空白字符:systemd ExecStart 无法转义,拒绝安装`);
177
+ const job = nodeRelayJob(ctx, home);
178
+ const obsolete = systemd.unitNamesOnDisk(paths.systemdUnitDir, relayLinkName(''))
179
+ .filter((unit) => unit !== job.unitName);
247
180
  const entryChanged = syncEdgeEntries(ctx);
248
- const plan = coreNodeRuntimePlan(topo);
249
- const comp = compNote(ensureRuntime(ctx, plan.entities, plan.links), plan.entities);
250
- const r = systemd.syncUnit(runner, job);
251
- return coreNodeInstallMsg(comp, entryChanged, r,
252
- `${ctx.topo.relay.alias} 入口 ${ctx.self.relayPort}`);
181
+ const comp = syncRuntime(ctx, coreNodeRuntimePlan(topo));
182
+ const r = systemd.syncUnit(runner, job, obsolete);
183
+ const removedLinks = removeObsoleteFiles(paths.binDir, relayLinkName(''), [relayLinkName(topo.relay.alias)]);
184
+ return coreNodeInstallMsg(ctx, comp, entryChanged, r, obsolete.length || removedLinks);
253
185
  }
254
186
 
255
- /**
256
- * @param {object} ctx
257
- * @param {string[]} [args] edge 可带 --with-link/--without-link
258
- */
187
+ /** @param {object} ctx @param {string[]} [args] */
259
188
  export async function run(ctx, args = []) {
260
- let result;
261
- switch (ctx.role) {
262
- case 'edge': result = await installEdge(ctx, args); break;
263
- case 'core':
264
- case 'node':
265
- // --with-link 是 edge 附加件:core/node 上静默吞掉会让错打的 flag
266
- // 看起来被接受了
267
- if (args.length)
268
- throw new Error(`本机是 ${ctx.role},install 不接受参数(--with-link/--without-link 是 edge 上本地转发的开关)`);
269
- result = ctx.role === 'core' ? installCore(ctx) : installNode(ctx);
270
- break;
271
- default: throw new Error(`未知角色:${ctx.role}`);
272
- }
273
- return result;
189
+ if (args.length) throw new Error('用法:ssh-net install 不带参数');
190
+ if (ctx.role === 'core') return installCore(ctx);
191
+ if (!['edge', 'node'].includes(ctx.role)) throw new Error(`未知角色:${ctx.role}`);
192
+ if (ctx.role === 'edge' && !hasRouteTimeout(ctx.env))
193
+ throw new Error('缺少可执行的 timeout,未安装 edge 组件。请在这台机器上运行 brew install coreutils,再重跑 ssh-net install');
194
+ const home = ctx.role === 'node' ? requireNodeHome(ctx, 'install') : null;
195
+ // routes 和 systemd 恢复记录都跨多步更新。同一账户的两次安装不能替对方回滚
196
+ const fd = fs.openSync(ctx.paths.sshDir, 'r');
197
+ try {
198
+ const mac = (ctx.platform ?? process.platform) === 'darwin';
199
+ const lock = ctx.runner.run(mac ? 'lockf' : 'flock', mac ? ['-s', '-t', '0', '3'] : ['-n', '3'],
200
+ { stdio: ['ignore', 'pipe', 'pipe', fd] });
201
+ if (lock.code !== 0) throw new Error(`无法取得安装锁:${lock.error?.message || lock.stderr.trim() || '有其他安装正在运行,请稍后重试'}`);
202
+ return ctx.role === 'node' ? installNode(ctx, home) : await installEdge(ctx);
203
+ } finally { fs.closeSync(fd); }
274
204
  }
@@ -41,8 +41,6 @@ export function runRegister(ctx, args = []) {
41
41
  binDir: ctx.paths.binDir, edgeAlias: alias, user: edge.user,
42
42
  logsDir: ctx.paths.logsDir,
43
43
  });
44
- const st = launchd.inspect(ctx.runner, ctx.uid, label);
45
-
46
44
  const plan = edgeCallbacksPlan([alias]);
47
45
  ensureRuntime(ctx, plan.entities, plan.links);
48
46
  ctx.state.writeEdgeV6(alias, v6);
@@ -50,6 +48,7 @@ export function runRegister(ctx, args = []) {
50
48
 
51
49
  // 未注册(首次报名)或 plist 与 topology 渲染不符(user 等变了):
52
50
  // 重新部署,syncPlist 的 bootstrap 即首发
51
+ const st = launchd.inspect(ctx.runner, ctx.uid, label);
53
52
  if (!st.registered || readFileOrNull(plistPath) !== content) {
54
53
  const r = syncPlist(ctx, { label, plistPath, content });
55
54
  if (r.lintError) throw new Error(`uplink-edge plist 校验失败:${r.lintError}`);
@@ -1,30 +1,26 @@
1
1
  // start:edge 两开关(缺省或 -a/--all=relay+peer,peer 自动补 relay);
2
- // core 重新 enable+bootstrap uplink-relay;node systemctl。link 不是
3
- // 运行时开关(转发口只取决于装没装附加件)。peer 路径复用 sn-route 做
4
- // 人工强制恢复,不在控制面另维护一套报名实现。
2
+ // core 重新启用中继,node 走 systemctl。edge 的本地转发随 relay 启停。
3
+ // 人工恢复 peer 复用 sn-route,不在控制面另维护一套报名实现
5
4
  import fs from 'node:fs';
5
+ import path from 'node:path';
6
6
  import * as systemd from '../lib/systemd.mjs';
7
7
  import { ensureLoaded } from '../lib/manage.mjs';
8
8
  import { SWITCH_NAMES } from '../lib/state.mjs';
9
9
  import { SN_ROUTE } from '../lib/manifest.mjs';
10
+ import { edgeLinkJob } from '../lib/jobs.mjs';
10
11
  import { relayLabel, relayUnitName, snRouteArgv } from '../lib/render.mjs';
11
12
 
12
- function parseTargets(args) {
13
+ function parseEdgeTarget(args) {
13
14
  if (args.length === 0 || (args.length === 1 && (args[0] === '-a' || args[0] === '--all')))
14
- return ['relay', 'peer'];
15
+ return 'peer';
15
16
  if (args.length === 1 && SWITCH_NAMES.includes(args[0]))
16
- return [args[0]];
17
- if (args.length === 1 && args[0] === 'link')
18
- throw new Error('link 不是运行时开关:本地转发口只取决于装没装 link 组件——启用 ssh-net install --with-link,移除 ssh-net install --without-link');
17
+ return args[0];
19
18
  throw new Error('用法:start [-a|--all|relay|peer](不带参数或 -a=relay+peer)');
20
19
  }
21
20
 
22
21
  /** 先保存开关,再沿日常 ssh 的选路路径强制确保一次;未就绪不撤销用户意图。 */
23
22
  function startEdgePeer(ctx) {
24
23
  const route = ctx.paths.binScript(SN_ROUTE);
25
- if (!fs.existsSync(route))
26
- throw new Error('未安装(缺 sn-route)——先跑 ssh-net install');
27
-
28
24
  const prefix = 'relay 和 peer 开关已开启';
29
25
  ctx.state.setOn(['relay', 'peer']);
30
26
  // FORCE 只跳过新鲜失败印记;probe、ENSURE 与等待预算都和普通 ssh 相同。
@@ -51,18 +47,24 @@ function startCore(ctx) {
51
47
  const plist = ctx.paths.plistFile(label);
52
48
  if (!fs.existsSync(plist)) throw new Error(`尚未安装(缺 ${plist}),先跑 ssh-net install`);
53
49
  // start 语义:在册但停着要踢活;在跑但 disabled 只清 override、不闪断
54
- ensureLoaded(ctx, { label, plistPath: plist }, { kickWhenStopped: true });
50
+ ensureLoaded(ctx, { label, plistPath: plist });
55
51
  return '中继通道已开启';
56
52
  }
57
53
 
58
54
  export function run(ctx, args = []) {
59
55
  if (ctx.role === 'edge') {
60
- const before = ctx.state.readSwitches();
61
- const targets = parseTargets(args); // ['relay','peer'] 或 ['relay']
62
-
63
- if (targets.includes('peer')) return startEdgePeer(ctx);
56
+ const target = parseEdgeTarget(args);
57
+ const peerWasOn = target === 'relay' && ctx.state.isOn('peer');
58
+ if (!fs.existsSync(ctx.paths.binScript(SN_ROUTE)) || !fs.existsSync(ctx.paths.routesFile))
59
+ throw new Error('未安装完整(缺 sn-route 或选路配置)——先跑 ssh-net install');
60
+ const link = edgeLinkJob(ctx);
61
+ if (link) {
62
+ if (!fs.existsSync(link.plistPath)) throw new Error('缺本地转发任务——先跑 ssh-net install');
63
+ ensureLoaded(ctx, link);
64
+ }
65
+ if (target === 'peer') return startEdgePeer(ctx);
64
66
  ctx.state.setOn(['relay']);
65
- const peerNote = before.peer
67
+ const peerNote = peerWasOn
66
68
  ? 'peer 保持开启,仍会主动恢复 IPv6 直连'
67
69
  : 'peer 仍关闭;需要自动恢复时运行 ssh-net start peer';
68
70
  return `relay 已开启(${peerNote})`;
@@ -72,7 +74,12 @@ export function run(ctx, args = []) {
72
74
  throw new Error('本机是单总开关,start 不带参数(-a/--all 亦可,等同缺省)');
73
75
  if (ctx.role === 'core') return startCore(ctx);
74
76
  if (ctx.role === 'node') {
75
- systemd.enableStart(ctx.runner, relayUnitName(ctx.topo.relay.alias));
77
+ const unit = relayUnitName(ctx.topo.relay.alias);
78
+ systemd.enableStart(ctx.runner, unit);
79
+ if (systemd.hasPendingUpdate(path.join(ctx.paths.systemdUnitDir, unit))) {
80
+ const text = '中继服务已启动,配置更新尚未完成——跑一次 ssh-net install 完成更新';
81
+ return { text, issues: [text] };
82
+ }
76
83
  return '中继通道已开启';
77
84
  }
78
85
  throw new Error(`未知角色:${ctx.role}`);