ssh-net 26.10.59 → 26.10.61
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.
- package/CHANGELOG.md +29 -1
- package/libexec/cli.mjs +2 -2
- package/libexec/commands/install.mjs +11 -45
- package/libexec/commands/status.mjs +39 -20
- package/libexec/commands/uninstall.mjs +8 -9
- package/libexec/commands/update.mjs +13 -3
- package/libexec/lib/conf.mjs +14 -4
- package/libexec/lib/fsutil.mjs +42 -4
- package/libexec/lib/jobctl.mjs +4 -1
- package/libexec/lib/jobs.mjs +62 -0
- package/libexec/lib/launchd.mjs +4 -11
- package/libexec/lib/manage.mjs +23 -24
- package/libexec/lib/probe.mjs +16 -3
- package/libexec/lib/render.mjs +28 -11
- package/libexec/lib/runtime.mjs +6 -18
- package/libexec/lib/sshconfig.mjs +7 -4
- package/libexec/lib/state.mjs +2 -0
- package/libexec/lib/systemd.mjs +11 -16
- package/libexec/sn-route +17 -17
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,7 +4,35 @@
|
|
|
4
4
|
跨月从 1 开始;历史跳号不补、不另维护累计发包数。发布 = 改版本号 +
|
|
5
5
|
CHANGELOG + 发 GitHub Release,Actions 跑测试后 npm publish。
|
|
6
6
|
|
|
7
|
-
## [
|
|
7
|
+
## [26.10.61] - 2026-10-25
|
|
8
|
+
|
|
9
|
+
### 修复
|
|
10
|
+
|
|
11
|
+
- status 不再把 link 任务未运行、launchctl 查询失败或 core relay 的 disabled
|
|
12
|
+
override 当作健康;停止 link 时保留 launchctl kill 的真实错误
|
|
13
|
+
- 端口预检在 lsof/launchctl 结果未知时中止;install 不再忽略 conf.d 读取
|
|
14
|
+
失败,并修复既有 Include 片段与 state 目录权限
|
|
15
|
+
- node 卸载在 daemon-reload 失败后重跑仍会补做重载;plist 与原子写失败时
|
|
16
|
+
清理临时文件
|
|
17
|
+
- ssh config 解析支持 OpenSSH 等号分隔语法;Match exec 统一处理 shell 与
|
|
18
|
+
ssh_config 引用,HOME 含空白时选路与地址门控仍可用
|
|
19
|
+
- CLI 等待 stdout/stderr 刷新后退出,避免慢管道下输出截断
|
|
20
|
+
|
|
21
|
+
### 简化与效率
|
|
22
|
+
|
|
23
|
+
- 收敛目录读取、临时文件、systemd 重载与测试子进程回收的重复实现;测试
|
|
24
|
+
复用现有 fixture、路径与调用记录 helper
|
|
25
|
+
- sn-route 的 lsof 正常结束立即继续,只由独立 watchdog 负责超时,不再白等
|
|
26
|
+
连接恢复的轮询周期
|
|
27
|
+
|
|
28
|
+
## [26.10.60] - 2026-10-25
|
|
29
|
+
|
|
30
|
+
### 修复
|
|
31
|
+
|
|
32
|
+
- Linux 卸载仅在存在中继 unit 时要求 root,修复零 unit 的非 root 清理被误拒
|
|
33
|
+
- update 在收尾前核对 PATH 选中的 ssh-net 版本,避免旧 bin 执行 install 后假报升级成功
|
|
34
|
+
- status 直接比对 install 管理的 plist/unit,只改服务模板的未完成升级也会提示修复
|
|
35
|
+
- 发布流程要求 push CI 成功后再发 GitHub Release,不再只凭 publish 结果判断全平台测试
|
|
8
36
|
|
|
9
37
|
## [26.10.59] - 2026-10-25
|
|
10
38
|
|
package/libexec/cli.mjs
CHANGED
|
@@ -130,8 +130,8 @@ async function main() {
|
|
|
130
130
|
}
|
|
131
131
|
|
|
132
132
|
main()
|
|
133
|
-
.then((code) => process.
|
|
133
|
+
.then((code) => { process.exitCode = code; })
|
|
134
134
|
.catch((err) => {
|
|
135
135
|
process.stderr.write(`ssh-net: ${err.message}\n`);
|
|
136
|
-
process.
|
|
136
|
+
process.exitCode = 1;
|
|
137
137
|
});
|
|
@@ -3,30 +3,26 @@
|
|
|
3
3
|
// 不在不启动);core/node 会恢复 stop 的中继服务;core 不预建 uplink-edge
|
|
4
4
|
//(首次报名才生成),node 写 unit 并 enable --now。
|
|
5
5
|
import fs from 'node:fs';
|
|
6
|
-
import os from 'node:os';
|
|
7
6
|
import path from 'node:path';
|
|
8
|
-
import { renderForwardArgs } from '../lib/config.mjs';
|
|
9
7
|
import {
|
|
10
8
|
CALLBACK_PORT, TERMINAL_NOTIFIER_PATHS, OSASCRIPT_PATH,
|
|
11
9
|
} from '../lib/constants.mjs';
|
|
12
10
|
import { syncPlist, removeJob } from '../lib/manage.mjs';
|
|
13
11
|
import { syncConfFile } from '../lib/conf.mjs';
|
|
14
12
|
import { ensureRuntime } from '../lib/runtime.mjs';
|
|
13
|
+
import { edgeLinkJob, coreRelayJob, nodeRelayJob } from '../lib/jobs.mjs';
|
|
15
14
|
import * as launchd from '../lib/launchd.mjs';
|
|
16
15
|
import * as systemd from '../lib/systemd.mjs';
|
|
17
16
|
import {
|
|
18
17
|
classifyLocalPort, lsofListen, v6LoopbackPids, peerProbeOk,
|
|
19
18
|
} from '../lib/probe.mjs';
|
|
20
|
-
import { writeFileAtomic } from '../lib/fsutil.mjs';
|
|
19
|
+
import { readDirOrEmpty, writeFileAtomic } from '../lib/fsutil.mjs';
|
|
21
20
|
import { packageScriptPath } from '../lib/paths.mjs';
|
|
22
21
|
import {
|
|
23
22
|
SN_PROBE, RESIDENT_SCRIPTS, edgeRuntimePlan, coreNodeRuntimePlan,
|
|
24
23
|
edgeCallbacksPlan, linkAddonPlan, mergePlans,
|
|
25
24
|
} from '../lib/manifest.mjs';
|
|
26
|
-
import {
|
|
27
|
-
linkLabel, relayLabel, relayUnitName,
|
|
28
|
-
renderEdgeHost, renderEdgeLinkPlist, renderRelayPlist, renderRelayUnit, renderRoutes,
|
|
29
|
-
} from '../lib/render.mjs';
|
|
25
|
+
import { linkLabel, renderEdgeHost, renderRoutes } from '../lib/render.mjs';
|
|
30
26
|
|
|
31
27
|
/** 对账只汇总有无变化;具体差异看文件与 launchd/systemd,不维护逐态文案。 */
|
|
32
28
|
function compNote(results, entities) {
|
|
@@ -70,7 +66,7 @@ async function precheckEdgePorts(ctx, linkOn) {
|
|
|
70
66
|
const forwardPorts = topo.forwards.map((f) => f.listenPort);
|
|
71
67
|
if (linkOn && forwardPorts.length > 0) {
|
|
72
68
|
// 只要 pid 判持口者归属(link-core 是 exec ssh,job pid 即持口者)
|
|
73
|
-
const jobPid = launchd.printState(runner, uid, linkLabel(topo.core.alias)).pid;
|
|
69
|
+
const jobPid = launchd.printState(runner, uid, linkLabel(topo.core.alias), true).pid;
|
|
74
70
|
for (const port of forwardPorts) {
|
|
75
71
|
const c = classifyLocalPort(runner, port, jobPid);
|
|
76
72
|
if (c.kind === 'foreign') {
|
|
@@ -145,9 +141,6 @@ async function installEdge(ctx, args) {
|
|
|
145
141
|
// 预检纯读且在落任何产物之前:被拒时 bin/ 一个都不建
|
|
146
142
|
await precheckEdgePorts(ctx, linkOn);
|
|
147
143
|
|
|
148
|
-
const label = linkLabel(topo.core.alias);
|
|
149
|
-
const plistPath = paths.plistFile(label);
|
|
150
|
-
|
|
151
144
|
// 显式意图先落/删 marker;无参 install(含 update 内置)不触碰它
|
|
152
145
|
if (flag === true) {
|
|
153
146
|
fs.mkdirSync(paths.sshNetDir, { recursive: true });
|
|
@@ -165,20 +158,15 @@ async function installEdge(ctx, args) {
|
|
|
165
158
|
if (linkOn) {
|
|
166
159
|
// 附加件:渲染纯 ssh plist 并对账(RELAY_ON 在 syncPlist 按 stopped 语义
|
|
167
160
|
// 首发,不在注册待命);转发参数是最终 -L argv
|
|
168
|
-
const
|
|
169
|
-
binDir: paths.binDir,
|
|
170
|
-
coreAlias: topo.core.alias,
|
|
171
|
-
forwardArgs: renderForwardArgs(topo.forwards, ctx.hostTable),
|
|
172
|
-
relayOnFile: paths.switchFiles.relay,
|
|
173
|
-
logsDir: paths.logsDir,
|
|
174
|
-
});
|
|
175
|
-
const r = syncPlist(ctx, { label, plistPath, content });
|
|
161
|
+
const r = syncPlist(ctx, edgeLinkJob(ctx));
|
|
176
162
|
if (r.lintError) throw new Error(`link plist 校验失败:${r.lintError}`);
|
|
177
163
|
linkChanged = r.changed;
|
|
178
164
|
linkNote = deploymentNote(r, '本地转发任务', '本地转发配置');
|
|
179
165
|
} else {
|
|
180
166
|
// 默认零常驻:清掉加装过的 link 全部产物。plist 必须先 bootout,否则
|
|
181
167
|
// 删了实体后 launchd 每 ThrottleInterval 刷 ENOENT
|
|
168
|
+
const label = linkLabel(topo.core.alias);
|
|
169
|
+
const plistPath = paths.plistFile(label);
|
|
182
170
|
const jobRemoved = removeJob(ctx, label, plistPath);
|
|
183
171
|
const addon = linkAddonPlan(topo);
|
|
184
172
|
const addonPaths = [...addon.entities, ...addon.links].map(([name]) => paths.binScript(name));
|
|
@@ -218,8 +206,7 @@ function syncEdgeEntries(ctx) {
|
|
|
218
206
|
keep.add(path.basename(file));
|
|
219
207
|
if (syncConfFile(file, renderEdgeHost(e))) changed = true;
|
|
220
208
|
}
|
|
221
|
-
|
|
222
|
-
try { existing = fs.readdirSync(paths.confDir); } catch { /* 目录不在即无旧片段 */ }
|
|
209
|
+
const existing = readDirOrEmpty(paths.confDir);
|
|
223
210
|
// 片段名公式唯一来源是 edgeHostFile(含 '' 即前缀),不抄 'edge-' 字面量
|
|
224
211
|
const edgePrefix = path.basename(paths.edgeHostFile(''));
|
|
225
212
|
for (const f of existing) {
|
|
@@ -240,14 +227,7 @@ function installCore(ctx) {
|
|
|
240
227
|
// relay 基础形态 + 磁盘在册 edge 的回拨组件(清单与报名/status 体检同源)
|
|
241
228
|
const plan = mergePlans(coreNodeRuntimePlan(topo), edgeCallbacksPlan(edges));
|
|
242
229
|
const comp = compNote(ensureRuntime(ctx, plan.entities, plan.links), plan.entities);
|
|
243
|
-
const
|
|
244
|
-
const content = renderRelayPlist({
|
|
245
|
-
binDir: paths.binDir,
|
|
246
|
-
relayAlias: topo.relay.alias,
|
|
247
|
-
relayPort: topo.core.relayPort,
|
|
248
|
-
logsDir: paths.logsDir,
|
|
249
|
-
});
|
|
250
|
-
const r = syncPlist(ctx, { label, plistPath: paths.plistFile(label), content });
|
|
230
|
+
const r = syncPlist(ctx, coreRelayJob(ctx));
|
|
251
231
|
// lint 失败不能静默报「安装完成」:syncPlist 以返回值交错误(register 同判)
|
|
252
232
|
if (r.lintError) throw new Error(`relay plist 校验失败:${r.lintError}`);
|
|
253
233
|
return coreNodeInstallMsg(comp, entryChanged, r,
|
|
@@ -261,26 +241,12 @@ function installNode(ctx) {
|
|
|
261
241
|
const entryChanged = syncEdgeEntries(ctx);
|
|
262
242
|
const plan = coreNodeRuntimePlan(topo);
|
|
263
243
|
const comp = compNote(ensureRuntime(ctx, plan.entities, plan.links), plan.entities);
|
|
264
|
-
const
|
|
265
|
-
// HOME 用 root 的真实家目录(getpwuid),不取 $HOME:sudo 保留 HOME 的环境
|
|
266
|
-
// (sudo -E,或部分发行版的默认值)会把调用者的家目录写进 unit——root
|
|
267
|
-
// 运行的 ssh 将去读别人的 ~/.ssh/config,relay 别名解析错配且无声
|
|
268
|
-
const home = ctx.nodeHome ?? os.userInfo().homedir;
|
|
244
|
+
const { home, ...job } = nodeRelayJob(ctx);
|
|
269
245
|
// ExecStart 按空白分词、无 shell 引号转义通路,HOME 含空白会拆断 bin 路径
|
|
270
246
|
// (plist 侧是 XML 数组无此问题)——当场拒绝比装出一个起不来的 unit 诚实
|
|
271
247
|
if (/\s/.test(home))
|
|
272
248
|
throw new Error(`node 的 HOME(${home})含空白字符:systemd ExecStart 无法转义,拒绝安装`);
|
|
273
|
-
const
|
|
274
|
-
const r = systemd.syncUnit(runner, {
|
|
275
|
-
unitPath,
|
|
276
|
-
unitName,
|
|
277
|
-
content: renderRelayUnit({
|
|
278
|
-
binDir: paths.binDir,
|
|
279
|
-
relayAlias: topo.relay.alias,
|
|
280
|
-
relayPort: ctx.self.relayPort,
|
|
281
|
-
home,
|
|
282
|
-
}),
|
|
283
|
-
});
|
|
249
|
+
const r = systemd.syncUnit(runner, job);
|
|
284
250
|
return coreNodeInstallMsg(comp, entryChanged, r,
|
|
285
251
|
`${ctx.topo.relay.alias} 入口 ${ctx.self.relayPort}`);
|
|
286
252
|
}
|
|
@@ -15,9 +15,9 @@ import {
|
|
|
15
15
|
SN_ROUTE, SN_IPV6, UPLINK_EDGE,
|
|
16
16
|
edgeRuntimePlan, coreNodeRuntimePlan, edgeCallbacksPlan,
|
|
17
17
|
} from '../lib/manifest.mjs';
|
|
18
|
+
import { edgeLinkJob, coreRelayJob, nodeRelayJob } from '../lib/jobs.mjs';
|
|
18
19
|
import {
|
|
19
|
-
|
|
20
|
-
renderEdgeHost, renderRoutes, coreViaRelayArgs, probeSshOpts,
|
|
20
|
+
edgeLabel, renderEdgeHost, renderRoutes, coreViaRelayArgs, probeSshOpts,
|
|
21
21
|
} from '../lib/render.mjs';
|
|
22
22
|
|
|
23
23
|
/**
|
|
@@ -48,20 +48,19 @@ function runtimeIssues(ctx, { entities, links }) {
|
|
|
48
48
|
return { issues, entityAudits };
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
/**
|
|
52
|
-
|
|
53
|
-
function confFragmentIssue(file, expected, label) {
|
|
51
|
+
/** install 生成物与期望内容比对,返回问题文案(''=健康)。 */
|
|
52
|
+
function configFileIssue(file, expected, label, staleText = '与 topology 不一致') {
|
|
54
53
|
const text = readFileOrNull(file);
|
|
55
54
|
return text === expected
|
|
56
55
|
? ''
|
|
57
|
-
: `${label}${text === null ? '缺失' :
|
|
56
|
+
: `${label}${text === null ? '缺失' : staleText}——跑一次 ssh-net install 刷新`;
|
|
58
57
|
}
|
|
59
58
|
|
|
60
59
|
/** core/node:各 edge 入口片段与渲染期望比对(install 的产物),并取当前入口
|
|
61
60
|
* 地址。缺失/过期会让 `ssh <别名>` 解析失败或用错 user,引导跑 install。 */
|
|
62
61
|
function edgeEntries(ctx, issues) {
|
|
63
62
|
return ctx.topo.edges.map((e) => {
|
|
64
|
-
const issue =
|
|
63
|
+
const issue = configFileIssue(
|
|
65
64
|
ctx.paths.edgeHostFile(e.alias), renderEdgeHost(e), `${e.alias} 的 ssh 入口配置`,
|
|
66
65
|
);
|
|
67
66
|
if (issue) issues.push(issue);
|
|
@@ -134,11 +133,18 @@ async function collectEdge(ctx, probe) {
|
|
|
134
133
|
const linkInstalled = fs.existsSync(paths.linkEnabledFile);
|
|
135
134
|
const plan = edgeRuntimePlan(topo, linkInstalled);
|
|
136
135
|
const { issues, entityAudits } = runtimeIssues(ctx, plan);
|
|
136
|
+
const linkDeployment = linkInstalled ? edgeLinkJob(ctx) : null;
|
|
137
|
+
if (linkDeployment) {
|
|
138
|
+
const issue = configFileIssue(
|
|
139
|
+
linkDeployment.plistPath, linkDeployment.content, '本地转发配置', '需要更新',
|
|
140
|
+
);
|
|
141
|
+
if (issue) issues.push(issue);
|
|
142
|
+
}
|
|
137
143
|
|
|
138
144
|
// routes 被手删/过期会让 ssh 静默退回 lan 直连,是故障。sn-route 没装时
|
|
139
145
|
// 上面已报「尚未安装」,不重复
|
|
140
146
|
if (entityAudits.some((a) => a.name === SN_ROUTE && a.audit === 'ok')) {
|
|
141
|
-
const issue =
|
|
147
|
+
const issue = configFileIssue(
|
|
142
148
|
paths.routesFile, renderRoutes(topo, ctx.self.alias), 'ssh 自动选路配置',
|
|
143
149
|
);
|
|
144
150
|
if (issue) issues.push(issue);
|
|
@@ -147,9 +153,11 @@ async function collectEdge(ctx, probe) {
|
|
|
147
153
|
// link 未装时 job 无消费者(渲染走「未安装」分支)——默认零常驻形态不为它
|
|
148
154
|
// 白跑一次 launchctl print
|
|
149
155
|
const job = linkInstalled
|
|
150
|
-
? launchd.printState(ctx.runner, ctx.uid,
|
|
156
|
+
? launchd.printState(ctx.runner, ctx.uid, linkDeployment.label, true)
|
|
151
157
|
: null;
|
|
152
158
|
const switches = state.readSwitches();
|
|
159
|
+
if (linkInstalled && switches.relay && !job.running)
|
|
160
|
+
issues.push('本地转发任务未在运行——先 stop 再按原开关 start,或跑 ssh-net install 修复');
|
|
153
161
|
|
|
154
162
|
// v6 只是诊断线索不是判决,与就绪实测并发。探测没跑成时不能谎称「没有
|
|
155
163
|
// IPv6」——那个结论只在 sn-ipv6 正常跑完且无输出时才成立
|
|
@@ -201,7 +209,12 @@ async function collectCore(ctx, probe) {
|
|
|
201
209
|
|
|
202
210
|
// disabled override 是整域同一份字典:relay job 与各 edge job 共用一次拉取
|
|
203
211
|
const dmap = launchd.disabledMap(ctx.runner, ctx.uid);
|
|
204
|
-
const
|
|
212
|
+
const relayDeployment = coreRelayJob(ctx);
|
|
213
|
+
const configIssue = configFileIssue(
|
|
214
|
+
relayDeployment.plistPath, relayDeployment.content, '中继服务配置', '需要更新',
|
|
215
|
+
);
|
|
216
|
+
if (configIssue) issues.push(configIssue);
|
|
217
|
+
const relayJob = launchd.inspectWith(ctx.runner, ctx.uid, relayDeployment.label, dmap);
|
|
205
218
|
// 实测时先发起来,边等边做注册态体检;默认快查不发起 ssh
|
|
206
219
|
const relayPortP = probe
|
|
207
220
|
? relayPortListening(ctx, topo.core.relayPort)
|
|
@@ -212,34 +225,35 @@ async function collectCore(ctx, probe) {
|
|
|
212
225
|
? auditScript(paths.binScript(UPLINK_EDGE), packageScriptPath(UPLINK_EDGE))
|
|
213
226
|
: null;
|
|
214
227
|
|
|
215
|
-
|
|
216
|
-
// 函数的迭代顺序里
|
|
217
|
-
const entryByAlias = new Map(edgeEntries(ctx, issues).map((en) => [en.alias, en]));
|
|
228
|
+
const entries = edgeEntries(ctx, issues);
|
|
218
229
|
const edges = [];
|
|
219
|
-
for (const
|
|
220
|
-
const
|
|
230
|
+
for (const entry of entries) {
|
|
231
|
+
const { alias } = entry;
|
|
232
|
+
const st = launchd.inspectWith(ctx.runner, ctx.uid, edgeLabel(alias), dmap);
|
|
221
233
|
// 已连接过的 edge 体检回拨脚本/软链:漏刷会拿旧脚本拨号
|
|
222
234
|
if (st.registered) {
|
|
223
|
-
const [linkName, entityName] = edgeCallbacksPlan([
|
|
235
|
+
const [linkName, entityName] = edgeCallbacksPlan([alias]).links[0];
|
|
224
236
|
const bad = [];
|
|
225
237
|
if (callbackEntityAudit !== 'ok')
|
|
226
238
|
bad.push(`连接脚本${callbackEntityAudit === 'missing' ? '缺失' : '过期'}`);
|
|
227
239
|
if (!auditLink(paths.binScript(linkName), entityName)) bad.push('服务软链异常');
|
|
228
240
|
if (bad.length)
|
|
229
|
-
issues.push(`${
|
|
241
|
+
issues.push(`${alias} 的自动连接脚本异常(${bad.join('、')})——它下次连过来时会自动刷新(或跑一次 ssh-net install 手动修复)`);
|
|
230
242
|
}
|
|
231
243
|
edges.push({
|
|
232
|
-
alias
|
|
244
|
+
alias,
|
|
233
245
|
registered: st.registered,
|
|
234
246
|
disabled: st.disabled,
|
|
235
247
|
running: st.running,
|
|
236
248
|
lastExitCode: st.lastExitCode,
|
|
237
|
-
entry
|
|
249
|
+
entry,
|
|
238
250
|
});
|
|
239
251
|
}
|
|
240
252
|
|
|
241
253
|
const relayPort = await relayPortP;
|
|
242
254
|
if (!relayJob.running) issues.push('relay 未在运行——ssh-net start 可拉起');
|
|
255
|
+
if (relayJob.registered && relayJob.disabled)
|
|
256
|
+
issues.push('relay 已禁用,后续加载可能被拦截——ssh-net start 可重新启用');
|
|
243
257
|
if (relayPort && !relayPort.listening)
|
|
244
258
|
issues.push(relayPortIssue(topo.relay.alias, topo.core.relayPort, relayPort));
|
|
245
259
|
|
|
@@ -254,7 +268,12 @@ async function collectNode(ctx, probe) {
|
|
|
254
268
|
const { issues } = runtimeIssues(ctx, coreNodeRuntimePlan(topo));
|
|
255
269
|
const entries = edgeEntries(ctx, issues);
|
|
256
270
|
|
|
257
|
-
const
|
|
271
|
+
const deployment = nodeRelayJob(ctx);
|
|
272
|
+
const configIssue = configFileIssue(
|
|
273
|
+
deployment.unitPath, deployment.content, '中继服务配置', '需要更新',
|
|
274
|
+
);
|
|
275
|
+
if (configIssue) issues.push(configIssue);
|
|
276
|
+
const unit = deployment.unitName;
|
|
258
277
|
const active = systemd.isActive(ctx.runner, unit);
|
|
259
278
|
const relayPort = probe ? await relayPortListening(ctx, ctx.self.relayPort) : null;
|
|
260
279
|
if (active !== 'active')
|
|
@@ -9,6 +9,7 @@ import * as systemd from '../lib/systemd.mjs';
|
|
|
9
9
|
import {
|
|
10
10
|
linkLabel, relayLabel, relayLinkName, edgeLabel,
|
|
11
11
|
} from '../lib/render.mjs';
|
|
12
|
+
import { readDirOrEmpty } from '../lib/fsutil.mjs';
|
|
12
13
|
|
|
13
14
|
const rm = (p) => fs.rmSync(p, { recursive: true, force: true });
|
|
14
15
|
|
|
@@ -21,11 +22,7 @@ function removeArtifacts(ctx) {
|
|
|
21
22
|
}
|
|
22
23
|
|
|
23
24
|
function removeSshNetLogs(ctx) {
|
|
24
|
-
|
|
25
|
-
try { files = fs.readdirSync(ctx.paths.logsDir); } catch (err) {
|
|
26
|
-
if (err.code !== 'ENOENT') throw err;
|
|
27
|
-
}
|
|
28
|
-
for (const file of files) {
|
|
25
|
+
for (const file of readDirOrEmpty(ctx.paths.logsDir)) {
|
|
29
26
|
if (file.startsWith('local.ssh-net-') && file.endsWith('.log'))
|
|
30
27
|
rm(path.join(ctx.paths.logsDir, file));
|
|
31
28
|
}
|
|
@@ -45,8 +42,7 @@ function removeNodeUnits(ctx, units) {
|
|
|
45
42
|
}
|
|
46
43
|
// daemon-reload 失败不能吞:systemd 仍持有已删 unit,Restart=always 会
|
|
47
44
|
// 留着/重拉 ghost 进程
|
|
48
|
-
|
|
49
|
-
if (dr.code !== 0) throw new Error(`systemctl daemon-reload 失败:${dr.stderr.trim()}`);
|
|
45
|
+
systemd.daemonReload(ctx.runner);
|
|
50
46
|
}
|
|
51
47
|
|
|
52
48
|
export function run(ctx, args = []) {
|
|
@@ -54,10 +50,13 @@ export function run(ctx, args = []) {
|
|
|
54
50
|
throw new Error('用法:uninstall 不带参数');
|
|
55
51
|
|
|
56
52
|
if ((ctx.platform ?? process.platform) === 'linux') {
|
|
57
|
-
if (ctx.uid !== 0)
|
|
58
|
-
throw new Error('node 卸载写 /etc/systemd/system 需要 root,请运行 sudo -i ssh-net uninstall');
|
|
59
53
|
const units = systemd.unitNamesOnDisk(ctx.paths.systemdUnitDir, relayLinkName(''));
|
|
54
|
+
if (units.length > 0 && ctx.uid !== 0)
|
|
55
|
+
throw new Error('node 卸载写 /etc/systemd/system 需要 root,请运行 sudo -i ssh-net uninstall');
|
|
60
56
|
if (units.length > 0) removeNodeUnits(ctx, units);
|
|
57
|
+
// 上次可能已在删完 unit 后、daemon-reload 失败处中断;磁盘为空也必须补做,
|
|
58
|
+
// 否则第二次卸载会留下 manager 内的旧定义却报成功。非 root 零产物仍纯本地清理。
|
|
59
|
+
else if (ctx.uid === 0) systemd.daemonReload(ctx.runner);
|
|
61
60
|
removeArtifacts(ctx);
|
|
62
61
|
return '已卸载。最后一步:npm uninstall -g ssh-net';
|
|
63
62
|
}
|
|
@@ -21,6 +21,7 @@ const INSTALL_TIMEOUT = 120_000;
|
|
|
21
21
|
|
|
22
22
|
const ARG_HINT = 'update 只接受一个可选的三段数字版本号';
|
|
23
23
|
const NPM_NOT_FOUND = 'PATH 上找不到 npm——检查 ~/.zshenv(mac)或 .bashrc(Linux)里 node 的 PATH 配置后重试';
|
|
24
|
+
const BIN_NOT_FOUND = 'npm 换装后 PATH 上找不到 ssh-net(全局 bin 未生效)——新开一个 shell 或手动跑一次 ssh-net install;若反复出现,检查 fnm 的 global 包路径';
|
|
24
25
|
|
|
25
26
|
/** 失败详情:stderr 优先;被信号杀(code null,典型是超时)别说成 exit null */
|
|
26
27
|
const failWhy = (r) => r.stderr.trim()
|
|
@@ -82,11 +83,20 @@ export async function run(ctx, args = []) {
|
|
|
82
83
|
if (r.code !== 0)
|
|
83
84
|
throw new Error(`npm 安装 ${resolved} 失败:${failWhy(r)}(已装的版本不受影响;网络或 registry 问题稍后重试,知道目标版号可直接 ssh-net update <版本号>)`);
|
|
84
85
|
|
|
85
|
-
// 版号地址 code 0
|
|
86
|
+
// 版号地址 code 0 即装上该版;先核对 PATH 选中的 bin,再让它跑 install。
|
|
87
|
+
// 多全局安装时,npm 更新的目录不一定排在 PATH 首位;旧 bin 成功退出也不代表
|
|
88
|
+
// 目标版本的组件已经同步。这里只核对进程版本,不恢复持久版本戳
|
|
86
89
|
progress('正在同步本机组件…');
|
|
90
|
+
const ver = runner.run('ssh-net', ['--version'], { timeout: INSTALL_TIMEOUT });
|
|
91
|
+
if (ver.error && ver.error.code === 'ENOENT') throw new Error(BIN_NOT_FOUND);
|
|
92
|
+
if (ver.code !== 0)
|
|
93
|
+
throw new Error(`npm 包已切换,但 ssh-net --version 失败:${failWhy(ver)}——检查 PATH 后手动跑一次 ssh-net install`);
|
|
94
|
+
const actual = ver.stdout.trim();
|
|
95
|
+
if (actual !== resolved)
|
|
96
|
+
throw new Error(`npm 包已切换到 ${resolved},但 PATH 上的 ssh-net 版本是 ${actual || '未知'},已停止收尾——用 which -a ssh-net 检查 PATH,再手动运行 ssh-net install`);
|
|
97
|
+
|
|
87
98
|
const inst = runner.run('ssh-net', ['install'], { timeout: INSTALL_TIMEOUT });
|
|
88
|
-
if (inst.error && inst.error.code === 'ENOENT')
|
|
89
|
-
throw new Error('npm 换装后 PATH 上找不到 ssh-net(全局 bin 未生效)——新开一个 shell 或手动跑一次 ssh-net install;若反复出现,检查 fnm 的 global 包路径');
|
|
99
|
+
if (inst.error && inst.error.code === 'ENOENT') throw new Error(BIN_NOT_FOUND);
|
|
90
100
|
if (inst.code !== 0)
|
|
91
101
|
throw new Error(`npm 包已切换,但 install 刷新没成功:${failWhy(inst)}——手动跑一次 ssh-net install 修复`);
|
|
92
102
|
|
package/libexec/lib/conf.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// - tmp 文件绝不写在 conf.d/ 内(写入中的半截文件会被某次 ssh 扫到)——
|
|
4
4
|
// 写在上级目录 ~/.ssh/ssh-net/.<名>.tmp-<pid> 再原子 rename 进来
|
|
5
5
|
// - 目录 0700、片段 0600(与 ~/.ssh 权限纪律一致)
|
|
6
|
-
// - sync
|
|
6
|
+
// - sync 幂等:内容、权限与文件类型都正确就不动盘(不产生无意义变更)
|
|
7
7
|
import fs from 'node:fs';
|
|
8
8
|
import path from 'node:path';
|
|
9
9
|
import { readFileOrNull, writeFileAtomic } from './fsutil.mjs';
|
|
@@ -18,13 +18,23 @@ function ensureConfDir(confDir) {
|
|
|
18
18
|
* 原子同步一个 Include 片段。
|
|
19
19
|
* @param {string} file 片段绝对路径(在 conf.d 内)
|
|
20
20
|
* @param {string} content 完整内容
|
|
21
|
-
* @returns {boolean}
|
|
21
|
+
* @returns {boolean} 是否有变更(重写、权限或文件类型修复)
|
|
22
22
|
*/
|
|
23
23
|
export function syncConfFile(file, content) {
|
|
24
|
-
if (readFileOrNull(file) === content) return false;
|
|
25
|
-
|
|
26
24
|
const dir = path.dirname(file);
|
|
27
25
|
ensureConfDir(dir);
|
|
26
|
+
const st = fs.lstatSync(file, { throwIfNoEntry: false }) ?? null;
|
|
27
|
+
|
|
28
|
+
let changed = false;
|
|
29
|
+
if (st?.isFile() && (st.mode & 0o7777) !== 0o600) {
|
|
30
|
+
// 先修权限再读:000 的片段也不能把修复入口自己挡住。
|
|
31
|
+
fs.chmodSync(file, 0o600);
|
|
32
|
+
changed = true;
|
|
33
|
+
}
|
|
34
|
+
const existing = st === null || st.isFile() ? readFileOrNull(file) : null;
|
|
35
|
+
if (existing === content && st?.isFile()) return changed;
|
|
36
|
+
// 同内容软链不是受管实体,落下原子替换为普通文件。
|
|
37
|
+
|
|
28
38
|
// tmp 落 conf.d 的**上级**目录:glob conf.d/* 扫不到它
|
|
29
39
|
writeFileAtomic(file, content, { mode: 0o600, tmpDir: path.dirname(dir) });
|
|
30
40
|
return true;
|
package/libexec/lib/fsutil.mjs
CHANGED
|
@@ -18,6 +18,21 @@ export function readFileOrNull(file, encoding = 'utf8') {
|
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
/**
|
|
22
|
+
* 读目录;不存在返回 [](仅吞 ENOENT,其余错误照抛)。发现/清理入口共用,
|
|
23
|
+
* 权限或 IO 错误不能冒充空清单。
|
|
24
|
+
* @param {string} dir
|
|
25
|
+
* @returns {string[]}
|
|
26
|
+
*/
|
|
27
|
+
export function readDirOrEmpty(dir) {
|
|
28
|
+
try {
|
|
29
|
+
return fs.readdirSync(dir);
|
|
30
|
+
} catch (err) {
|
|
31
|
+
if (err && err.code === 'ENOENT') return [];
|
|
32
|
+
throw err;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
21
36
|
/**
|
|
22
37
|
* 读文本并 trim:不存在或只剩空白返回 null(「文件里得有值才算数」,
|
|
23
38
|
* state 的 edges v6 与 runtime 的版本戳共用)。
|
|
@@ -31,6 +46,28 @@ export function readTrimmedOrNull(file) {
|
|
|
31
46
|
return trimmed.length > 0 ? trimmed : null;
|
|
32
47
|
}
|
|
33
48
|
|
|
49
|
+
/**
|
|
50
|
+
* 在目标旁建立唯一临时路径并交给 fn,返回后一律清理。fn 可在此完成校验、
|
|
51
|
+
* rename 等提交动作;原操作失败时清理失败不覆盖原始错误。
|
|
52
|
+
* @template T
|
|
53
|
+
* @param {string} file
|
|
54
|
+
* @param {{tmpDir?: string}} [opts]
|
|
55
|
+
* @param {(tmp: string) => T} fn
|
|
56
|
+
* @returns {T}
|
|
57
|
+
*/
|
|
58
|
+
export function withTempFile(file, { tmpDir = path.dirname(file) } = {}, fn) {
|
|
59
|
+
const tmp = path.join(tmpDir, `.${path.basename(file)}.tmp-${process.pid}`);
|
|
60
|
+
let result;
|
|
61
|
+
try {
|
|
62
|
+
result = fn(tmp);
|
|
63
|
+
} catch (err) {
|
|
64
|
+
try { fs.rmSync(tmp, { force: true }); } catch { /* 保留原始操作错误 */ }
|
|
65
|
+
throw err;
|
|
66
|
+
}
|
|
67
|
+
fs.rmSync(tmp, { force: true });
|
|
68
|
+
return result;
|
|
69
|
+
}
|
|
70
|
+
|
|
34
71
|
/**
|
|
35
72
|
* 原子落盘:tmp 写好再 rename 落定,落定后 chmod 兜底(怪 umask/拷贝工具
|
|
36
73
|
* 吃位都修正到 mode)。
|
|
@@ -40,8 +77,9 @@ export function readTrimmedOrNull(file) {
|
|
|
40
77
|
* tmp 必须写在 glob 目录之外(conf.d/* 会被 ssh 扫到)
|
|
41
78
|
*/
|
|
42
79
|
export function writeFileAtomic(file, content, { mode = 0o644, tmpDir = path.dirname(file) } = {}) {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
80
|
+
return withTempFile(file, { tmpDir }, (tmp) => {
|
|
81
|
+
fs.writeFileSync(tmp, content, { mode });
|
|
82
|
+
fs.renameSync(tmp, file);
|
|
83
|
+
fs.chmodSync(file, mode);
|
|
84
|
+
});
|
|
47
85
|
}
|
package/libexec/lib/jobctl.mjs
CHANGED
|
@@ -27,7 +27,10 @@ export function reapEdgeLink(ctx, label) {
|
|
|
27
27
|
if (!launchd.printState(ctx.runner, ctx.uid, label, true).registered)
|
|
28
28
|
return { gone: true, label };
|
|
29
29
|
|
|
30
|
-
launchd.killJob(ctx.runner, ctx.uid, label, 'TERM');
|
|
30
|
+
const killed = launchd.killJob(ctx.runner, ctx.uid, label, 'TERM');
|
|
31
|
+
if (killed.code !== 0 && killed.code !== 113
|
|
32
|
+
&& !/Could not find service/.test(killed.stderr ?? ''))
|
|
33
|
+
throw new Error(`launchctl kill 失败(${label}):${killed.stderr.trim() || `exit ${killed.code}`}`);
|
|
31
34
|
const end = Date.now() + WAIT_MS;
|
|
32
35
|
while (Date.now() < end) {
|
|
33
36
|
if (isGone(ctx, label)) return { gone: true, label };
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// install 管理的服务配置装配:写盘与 status 体检共用同一份渲染输入,
|
|
2
|
+
// 避免只改 plist/unit 模板时,status 因运行时脚本未变而漏报未同步升级。
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { renderForwardArgs } from './config.mjs';
|
|
6
|
+
import {
|
|
7
|
+
linkLabel, relayLabel, relayUnitName,
|
|
8
|
+
renderEdgeLinkPlist, renderRelayPlist, renderRelayUnit,
|
|
9
|
+
} from './render.mjs';
|
|
10
|
+
|
|
11
|
+
/** edge 本地转发 LaunchAgent。 */
|
|
12
|
+
export function edgeLinkJob(ctx) {
|
|
13
|
+
const { topo, paths } = ctx;
|
|
14
|
+
const label = linkLabel(topo.core.alias);
|
|
15
|
+
return {
|
|
16
|
+
label,
|
|
17
|
+
plistPath: paths.plistFile(label),
|
|
18
|
+
content: renderEdgeLinkPlist({
|
|
19
|
+
binDir: paths.binDir,
|
|
20
|
+
coreAlias: topo.core.alias,
|
|
21
|
+
forwardArgs: renderForwardArgs(topo.forwards, ctx.hostTable),
|
|
22
|
+
relayOnFile: paths.switchFiles.relay,
|
|
23
|
+
logsDir: paths.logsDir,
|
|
24
|
+
}),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** core 中继 LaunchAgent。 */
|
|
29
|
+
export function coreRelayJob(ctx) {
|
|
30
|
+
const { topo, paths } = ctx;
|
|
31
|
+
const label = relayLabel(topo.relay.alias);
|
|
32
|
+
return {
|
|
33
|
+
label,
|
|
34
|
+
plistPath: paths.plistFile(label),
|
|
35
|
+
content: renderRelayPlist({
|
|
36
|
+
binDir: paths.binDir,
|
|
37
|
+
relayAlias: topo.relay.alias,
|
|
38
|
+
relayPort: topo.core.relayPort,
|
|
39
|
+
logsDir: paths.logsDir,
|
|
40
|
+
}),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** node 中继 systemd unit;home 一并返回供 install 校验 ExecStart 边界。 */
|
|
45
|
+
export function nodeRelayJob(ctx) {
|
|
46
|
+
const { topo, paths } = ctx;
|
|
47
|
+
const unitName = relayUnitName(topo.relay.alias);
|
|
48
|
+
// HOME 用 root 的真实家目录(getpwuid),不取 $HOME:sudo 保留 HOME 会把
|
|
49
|
+
// 调用者的家目录写进 unit,root 的 ssh 随之读错 config
|
|
50
|
+
const home = ctx.nodeHome ?? os.userInfo().homedir;
|
|
51
|
+
return {
|
|
52
|
+
unitName,
|
|
53
|
+
unitPath: path.join(paths.systemdUnitDir, unitName),
|
|
54
|
+
home,
|
|
55
|
+
content: renderRelayUnit({
|
|
56
|
+
binDir: paths.binDir,
|
|
57
|
+
relayAlias: topo.relay.alias,
|
|
58
|
+
relayPort: ctx.self.relayPort,
|
|
59
|
+
home,
|
|
60
|
+
}),
|
|
61
|
+
};
|
|
62
|
+
}
|
package/libexec/lib/launchd.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// - 休眠判据只用 print-disabled 字典(print 正文无稳定字段)
|
|
5
5
|
// - 任何 bootstrap 前无条件先 enable(override 残留时 bootstrap error 5)
|
|
6
6
|
// - enable 本身不触发首发,唤醒必须 kickstart -k
|
|
7
|
-
import
|
|
7
|
+
import { readDirOrEmpty } from './fsutil.mjs';
|
|
8
8
|
import { edgeLabel } from './render.mjs';
|
|
9
9
|
|
|
10
10
|
/** @param {number} uid */
|
|
@@ -25,16 +25,9 @@ const NOT_REGISTERED = Object.freeze({ disabled: false, ...NOT_REGISTERED_PRINT
|
|
|
25
25
|
* @returns {string[]}
|
|
26
26
|
*/
|
|
27
27
|
export function labelsOnDisk(launchAgentsDir, prefix) {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
.filter((f) => f.startsWith(prefix) && f.endsWith('.plist'))
|
|
32
|
-
.map((f) => f.slice(0, -'.plist'.length));
|
|
33
|
-
} catch (err) {
|
|
34
|
-
// 只有目录不存在才是空清单;权限/IO 错误若吞掉,恢复卸载会漏掉在册任务
|
|
35
|
-
if (err.code === 'ENOENT') return [];
|
|
36
|
-
throw err;
|
|
37
|
-
}
|
|
28
|
+
return readDirOrEmpty(launchAgentsDir)
|
|
29
|
+
.filter((f) => f.startsWith(prefix) && f.endsWith('.plist'))
|
|
30
|
+
.map((f) => f.slice(0, -'.plist'.length));
|
|
38
31
|
}
|
|
39
32
|
|
|
40
33
|
/**
|
package/libexec/lib/manage.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// 渲染结果与现文件字节相同则不 bootout——install 幂等不断连。
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import * as launchd from './launchd.mjs';
|
|
6
|
-
import { readFileOrNull } from './fsutil.mjs';
|
|
6
|
+
import { readFileOrNull, withTempFile } from './fsutil.mjs';
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* 确保一个在册 job 已加载可用(launchctl 四态状态机的唯一实现,实测矩阵见
|
|
@@ -69,30 +69,29 @@ export function syncPlist(ctx, { label, plistPath, content }) {
|
|
|
69
69
|
return { changed: false };
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
-
// 内容变化(或首次):先 lint tmp
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
return { changed: false, lintError: lint.stderr.trim() || `plutil exit ${lint.code}` };
|
|
79
|
-
}
|
|
72
|
+
// 内容变化(或首次):先 lint tmp,过了再动现文件;tmp 生命周期与原子写共用
|
|
73
|
+
return withTempFile(plistPath, {}, (tmp) => {
|
|
74
|
+
fs.writeFileSync(tmp, content, { mode: 0o644 });
|
|
75
|
+
const lint = launchd.lintPlist(runner, tmp);
|
|
76
|
+
if (lint.code !== 0)
|
|
77
|
+
return { changed: false, lintError: lint.stderr.trim() || `plutil exit ${lint.code}` };
|
|
80
78
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
79
|
+
// 只要 registered 一个事实:printState 即可,不跑全域 print-disabled
|
|
80
|
+
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
|
+
}
|
|
86
|
+
fs.renameSync(tmp, plistPath);
|
|
87
|
+
fs.chmodSync(plistPath, 0o644);
|
|
88
|
+
// 无条件先 enable(override 残留时 bootstrap error 5;launchd.mjs 宣言
|
|
89
|
+
// 「勿在此吞错」)。取舍:此处 job 已 bootout、enable 失败即不 bootstrap
|
|
90
|
+
//(停机态)——真失败(override 数据库损坏)下 bootstrap 也过不去(error 5),
|
|
91
|
+
// 可见性优先于「也许 bootstrap 能侥幸成功」
|
|
92
|
+
launchd.enableBootstrap(runner, uid, label, plistPath);
|
|
93
|
+
return { changed: true, restarted: st.registered };
|
|
94
|
+
});
|
|
96
95
|
}
|
|
97
96
|
|
|
98
97
|
/**
|
package/libexec/lib/probe.mjs
CHANGED
|
@@ -31,6 +31,19 @@ export function tcpOpen(host, port, timeoutMs = 300) {
|
|
|
31
31
|
});
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
+
/**
|
|
35
|
+
* lsof 无匹配是 exit 1 且 stderr 为空;启动失败、权限错误等不能冒充「无监听」。
|
|
36
|
+
* @param {import('./exec.mjs').Runner} runner
|
|
37
|
+
* @param {string[]} args
|
|
38
|
+
* @param {number} port
|
|
39
|
+
*/
|
|
40
|
+
function runLsof(runner, args, port) {
|
|
41
|
+
const r = runner.run('lsof', args);
|
|
42
|
+
if (r.code === 0 || (r.code === 1 && r.stderr.trim() === '')) return r;
|
|
43
|
+
const detail = r.stderr.trim() || r.error?.message || `exit ${r.code ?? r.signal ?? '未知'}`;
|
|
44
|
+
throw new Error(`lsof 查询端口 ${port} 失败:${detail}`);
|
|
45
|
+
}
|
|
46
|
+
|
|
34
47
|
/**
|
|
35
48
|
* 环回某端口当前的监听 pid 列表(无监听空数组)。
|
|
36
49
|
* @param {import('./exec.mjs').Runner} runner
|
|
@@ -38,8 +51,8 @@ export function tcpOpen(host, port, timeoutMs = 300) {
|
|
|
38
51
|
* @returns {number[]}
|
|
39
52
|
*/
|
|
40
53
|
export function listListeners(runner, port) {
|
|
41
|
-
const r = runner
|
|
42
|
-
if (r.code !== 0) return [];
|
|
54
|
+
const r = runLsof(runner, ['-tnP', `-iTCP:${port}`, '-sTCP:LISTEN'], port);
|
|
55
|
+
if (r.code !== 0) return [];
|
|
43
56
|
return r.stdout
|
|
44
57
|
.trim()
|
|
45
58
|
.split(/\s+/)
|
|
@@ -56,7 +69,7 @@ export function listListeners(runner, port) {
|
|
|
56
69
|
* @returns {string}
|
|
57
70
|
*/
|
|
58
71
|
export function lsofListen(runner, port) {
|
|
59
|
-
const r = runner
|
|
72
|
+
const r = runLsof(runner, ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN'], port);
|
|
60
73
|
return r.code === 0 ? r.stdout.trim() : '';
|
|
61
74
|
}
|
|
62
75
|
|
package/libexec/lib/render.mjs
CHANGED
|
@@ -91,6 +91,20 @@ const ROUTES_HEADER = `# 本文件由 \`ssh-net install\` 从 ~/.ssh/ssh-net/top
|
|
|
91
91
|
# 入站,只有 relay 兜底。User 不写——由主 config 的 Host 块补。
|
|
92
92
|
`;
|
|
93
93
|
|
|
94
|
+
// Match exec 有两层语法:shellWord 保护 shell 参数,matchExec 再转义
|
|
95
|
+
// ssh_config 的外层双引号。输入均已由 topology 校验或来自内部常量;保留 $
|
|
96
|
+
// 是为了让 $HOME 与 VS Code 参数展开在实际连接时发生。
|
|
97
|
+
/** @param {string|number} value */
|
|
98
|
+
function shellWord(value) {
|
|
99
|
+
return `"${String(value).replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** @param {string} pattern @param {string} command */
|
|
103
|
+
function matchExec(pattern, command) {
|
|
104
|
+
const escaped = command.replaceAll('\\', '\\\\').replaceAll('"', '\\"');
|
|
105
|
+
return `Match originalhost ${pattern} exec "${escaped}"`;
|
|
106
|
+
}
|
|
107
|
+
|
|
94
108
|
/**
|
|
95
109
|
* sn-route 的冻结位置参数(design §2.3 argv 契约):
|
|
96
110
|
* <self> <core> <relay> <core 注册口> <core 用户>
|
|
@@ -120,12 +134,10 @@ export function renderRoutes(topo, selfAlias) {
|
|
|
120
134
|
const blocks = [];
|
|
121
135
|
|
|
122
136
|
// sn-route argv 直接渲染进 Match(无配置文件中转)。进度只进 stderr 且
|
|
123
|
-
// 仅终端显示(VS Code/Remote-SSH、scp
|
|
124
|
-
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
const match = (alias, cond) =>
|
|
128
|
-
`Match originalhost ${alias} exec "test -e ${state}/RELAY_ON${cond}"`;
|
|
137
|
+
// 仅终端显示(VS Code/Remote-SSH、scp、脚本下自动静默)
|
|
138
|
+
const routeCommand = [snRoute, ...snRouteArgv(topo, selfAlias)].map(shellWord).join(' ');
|
|
139
|
+
const match = (alias, cond = '') =>
|
|
140
|
+
matchExec(alias, `test -e ${shellWord(`${state}/RELAY_ON`)}${cond}`);
|
|
129
141
|
// core 判决块与兜底块共用一个发射器:first-wins 逐 keyword 取首值,
|
|
130
142
|
// 「块命中」不是整体替换——判决块必须占住兜底块设的每一个 keyword
|
|
131
143
|
// (ProxyJump none 不是装饰,漏了后块的 ProxyJump 就漏进直连路径,
|
|
@@ -142,7 +154,7 @@ export function renderRoutes(topo, selfAlias) {
|
|
|
142
154
|
|
|
143
155
|
// core:peer 一跳(sn-route 现场确保成功:对端连到本机 [::1]:10022)
|
|
144
156
|
blocks.push(routeBlock(
|
|
145
|
-
topo.core.alias, ` && ${
|
|
157
|
+
topo.core.alias, ` && ${routeCommand}`,
|
|
146
158
|
'::1', CALLBACK_PORT, 'none',
|
|
147
159
|
`peer(对方经 v6 连到本机 [::1]:${CALLBACK_PORT},全 v6 环回)`,
|
|
148
160
|
));
|
|
@@ -174,12 +186,13 @@ export function renderRoutes(topo, selfAlias) {
|
|
|
174
186
|
const peerList = [topo.core.alias, ...topo.nodes.map((n) => n.alias)];
|
|
175
187
|
const peers = peerList.join(',');
|
|
176
188
|
const nonPeers = `*,${peerList.map((a) => `!${a}`).join(',')}`;
|
|
177
|
-
const vscode =
|
|
189
|
+
const vscode = (pattern) =>
|
|
190
|
+
matchExec(pattern, `test -n ${shellWord('${VSCODE_IPC_HOOK:-}')}`);
|
|
178
191
|
blocks.push([
|
|
179
192
|
'# 连接打标:对端 ~/.ssh/rc 读 LC_VSCODE_SSH 维护 dot.via、把本机别名交给 sn-register-lan 登记内网地址',
|
|
180
|
-
|
|
193
|
+
vscode(peers),
|
|
181
194
|
` SetEnv LC_VSCODE_SSH=1 ${idEnv}`,
|
|
182
|
-
|
|
195
|
+
vscode(nonPeers),
|
|
183
196
|
' SetEnv LC_VSCODE_SSH=1',
|
|
184
197
|
`Match originalhost ${peers}`,
|
|
185
198
|
` SetEnv ${idEnv}`,
|
|
@@ -206,6 +219,10 @@ export function renderRoutes(topo, selfAlias) {
|
|
|
206
219
|
*/
|
|
207
220
|
export function renderEdgeHost({ alias, aliases, user }) {
|
|
208
221
|
const addr = edgeAddrFileRel(alias);
|
|
222
|
+
const freshnessGate = matchExec(
|
|
223
|
+
aliases.join(','),
|
|
224
|
+
`find ${shellWord(`$HOME/${addr}`)} -mmin -${EDGE_ADDR_TTL_MIN} 2>/dev/null | read -r _`,
|
|
225
|
+
);
|
|
209
226
|
// 门控管道用内建 read 收尾而不是 grep -q:Match exec 每条连接都跑,少 fork
|
|
210
227
|
// 一个外部进程(find 有输出 read 退出 0、EOF 退出 1,三态与 grep -q 等价)
|
|
211
228
|
return `# 本文件由 \`ssh-net install\` 从 topology 渲染,勿手改。地址在 Include 的文件
|
|
@@ -215,7 +232,7 @@ Host ${aliases.join(' ')}
|
|
|
215
232
|
User ${user}
|
|
216
233
|
HostKeyAlias ${alias}
|
|
217
234
|
ConnectTimeout 5
|
|
218
|
-
|
|
235
|
+
${freshnessGate}
|
|
219
236
|
Include ~/${addr}
|
|
220
237
|
`;
|
|
221
238
|
}
|
package/libexec/lib/runtime.mjs
CHANGED
|
@@ -6,7 +6,6 @@
|
|
|
6
6
|
// - 运行时零 npm/fnm 依赖;包升级后重跑 install 刷新(core 侧 uplink-edge
|
|
7
7
|
// 由每次报名自动对账),status 直接比对包内脚本与磁盘产物
|
|
8
8
|
import fs from 'node:fs';
|
|
9
|
-
import path from 'node:path';
|
|
10
9
|
import { packageScriptPath } from './paths.mjs';
|
|
11
10
|
import { readFileOrNull, writeFileAtomic } from './fsutil.mjs';
|
|
12
11
|
|
|
@@ -39,13 +38,8 @@ export function ensureScript(dstPath, srcPath) {
|
|
|
39
38
|
* @returns {boolean} 是否发生变更
|
|
40
39
|
*/
|
|
41
40
|
export function ensureLink(linkPath, entityName) {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
st = fs.lstatSync(linkPath);
|
|
45
|
-
} catch (err) {
|
|
46
|
-
if (err.code !== 'ENOENT') throw err;
|
|
47
|
-
}
|
|
48
|
-
if (st !== null && st.isSymbolicLink() && fs.readlinkSync(linkPath) === entityName)
|
|
41
|
+
const st = fs.lstatSync(linkPath, { throwIfNoEntry: false }) ?? null;
|
|
42
|
+
if (st?.isSymbolicLink() && fs.readlinkSync(linkPath) === entityName)
|
|
49
43
|
return false;
|
|
50
44
|
// 缺失无需处理;错链或实体占位都删掉后统一建链
|
|
51
45
|
if (st !== null) fs.rmSync(linkPath);
|
|
@@ -65,9 +59,9 @@ export function ensureLink(linkPath, entityName) {
|
|
|
65
59
|
export function ensureRuntime(ctx, entries, links = []) {
|
|
66
60
|
fs.mkdirSync(ctx.paths.binDir, { recursive: true });
|
|
67
61
|
const results = entries.map(([name, scriptName]) =>
|
|
68
|
-
ensureScript(
|
|
62
|
+
ensureScript(ctx.paths.binScript(name), packageScriptPath(scriptName)));
|
|
69
63
|
for (const [name, entityName] of links) {
|
|
70
|
-
results.push(ensureLink(
|
|
64
|
+
results.push(ensureLink(ctx.paths.binScript(name), entityName));
|
|
71
65
|
}
|
|
72
66
|
// 旧版本戳(26.10.59 退役)只作迁移清理,保留约一个月后随版本删除
|
|
73
67
|
fs.rmSync(ctx.paths.legacyRuntimeVersionFile, { force: true });
|
|
@@ -105,14 +99,8 @@ export function auditScript(dstPath, srcPath) {
|
|
|
105
99
|
* @returns {boolean}
|
|
106
100
|
*/
|
|
107
101
|
export function auditLink(linkPath, entityName) {
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
st = fs.lstatSync(linkPath);
|
|
111
|
-
} catch (err) {
|
|
112
|
-
if (err && err.code === 'ENOENT') return false;
|
|
113
|
-
throw err;
|
|
114
|
-
}
|
|
115
|
-
if (!st.isSymbolicLink()) return false;
|
|
102
|
+
const st = fs.lstatSync(linkPath, { throwIfNoEntry: false });
|
|
103
|
+
if (!st?.isSymbolicLink()) return false;
|
|
116
104
|
if (fs.readlinkSync(linkPath) !== entityName) return false;
|
|
117
105
|
try {
|
|
118
106
|
return Boolean(fs.statSync(linkPath).mode & 0o111);
|
|
@@ -37,8 +37,11 @@ export function parseStaticHosts(text) {
|
|
|
37
37
|
for (const raw of text.split('\n')) {
|
|
38
38
|
const line = raw.trim();
|
|
39
39
|
if (line.length === 0 || line.startsWith('#')) continue;
|
|
40
|
-
|
|
41
|
-
const
|
|
40
|
+
// ssh_config 允许 `Keyword value`、`Keyword=value` 与 `Keyword = value`。
|
|
41
|
+
const parsed = line.match(/^([^\s=]+)\s*(?:=\s*|\s+)(.*)$/);
|
|
42
|
+
if (!parsed) continue;
|
|
43
|
+
const keyword = parsed[1].toLowerCase();
|
|
44
|
+
const cols = parsed[2] ? parsed[2].split(/\s+/) : [];
|
|
42
45
|
|
|
43
46
|
if (keyword === 'match') {
|
|
44
47
|
inMatch = true;
|
|
@@ -49,7 +52,7 @@ export function parseStaticHosts(text) {
|
|
|
49
52
|
inMatch = false;
|
|
50
53
|
// 精确模式入表(多模式逐个);同一别名多个 Host 块时 ssh 取首次值——
|
|
51
54
|
// 已存在的记录对象继续沿用,首次值写入不被后块覆盖
|
|
52
|
-
currentPatterns = cols.
|
|
55
|
+
currentPatterns = cols.filter(isExactPattern);
|
|
53
56
|
for (const p of currentPatterns) {
|
|
54
57
|
if (!table.has(p)) table.set(p, {});
|
|
55
58
|
}
|
|
@@ -57,7 +60,7 @@ export function parseStaticHosts(text) {
|
|
|
57
60
|
}
|
|
58
61
|
if (inMatch || currentPatterns.length === 0) continue;
|
|
59
62
|
if (keyword === 'hostname') {
|
|
60
|
-
const value = cols.
|
|
63
|
+
const value = cols.join(' ');
|
|
61
64
|
if (value) {
|
|
62
65
|
for (const p of currentPatterns) {
|
|
63
66
|
const host = table.get(p);
|
package/libexec/lib/state.mjs
CHANGED
|
@@ -36,6 +36,7 @@ export const SWITCH_NAMES = ['relay', 'peer'];
|
|
|
36
36
|
export function createStateStore({ stateDir, switchFiles, edgesDir, addrDir }) {
|
|
37
37
|
const ensureState = () => {
|
|
38
38
|
fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
|
39
|
+
fs.chmodSync(stateDir, 0o700);
|
|
39
40
|
};
|
|
40
41
|
|
|
41
42
|
const assertNames = (names) => {
|
|
@@ -48,6 +49,7 @@ export function createStateStore({ stateDir, switchFiles, edgesDir, addrDir }) {
|
|
|
48
49
|
const writeStateLine = (dir, alias, line) => {
|
|
49
50
|
ensureState();
|
|
50
51
|
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
52
|
+
fs.chmodSync(dir, 0o700);
|
|
51
53
|
writeFileAtomic(path.join(dir, alias), line, { mode: 0o600 });
|
|
52
54
|
};
|
|
53
55
|
|
package/libexec/lib/systemd.mjs
CHANGED
|
@@ -4,12 +4,17 @@
|
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import os from 'node:os';
|
|
6
6
|
import path from 'node:path';
|
|
7
|
-
import { readFileOrNull, writeFileAtomic } from './fsutil.mjs';
|
|
7
|
+
import { readDirOrEmpty, readFileOrNull, writeFileAtomic } from './fsutil.mjs';
|
|
8
8
|
|
|
9
9
|
/** @param {import('./exec.mjs').Runner} runner @param {string} unit 含 .service */
|
|
10
10
|
const sc = (runner, args) => runner.run('systemctl', args);
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
/** 所有 reload 路径都把真失败抛出;恢复路径可给错误加「恢复后」前缀。 */
|
|
13
|
+
export function daemonReload(runner, errorPrefix = '') {
|
|
14
|
+
const r = sc(runner, ['daemon-reload']);
|
|
15
|
+
if (r.code !== 0)
|
|
16
|
+
throw new Error(`${errorPrefix}systemctl daemon-reload 失败:${r.stderr.trim()}`);
|
|
17
|
+
}
|
|
13
18
|
export const enableUnit = (runner, unit) => sc(runner, ['enable', unit]);
|
|
14
19
|
const disableUnit = (runner, unit) => sc(runner, ['disable', unit]);
|
|
15
20
|
export const startUnit = (runner, unit) => sc(runner, ['start', unit]);
|
|
@@ -23,14 +28,8 @@ export const restartUnit = (runner, unit) => sc(runner, ['restart', unit]);
|
|
|
23
28
|
* @returns {string[]}
|
|
24
29
|
*/
|
|
25
30
|
export function unitNamesOnDisk(unitDir, prefix) {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
.filter((f) => f.startsWith(prefix) && f.endsWith('.service'));
|
|
29
|
-
} catch (err) {
|
|
30
|
-
// 恢复卸载依赖完整清单;目录不存在才是空,其余错误不能静默吞掉
|
|
31
|
-
if (err.code === 'ENOENT') return [];
|
|
32
|
-
throw err;
|
|
33
|
-
}
|
|
31
|
+
return readDirOrEmpty(unitDir)
|
|
32
|
+
.filter((f) => f.startsWith(prefix) && f.endsWith('.service'));
|
|
34
33
|
}
|
|
35
34
|
|
|
36
35
|
/** 没装/已卸的 unit 放行(stop 的 not-loaded 与 disable 的 does not exist
|
|
@@ -128,9 +127,7 @@ export function syncUnit(runner, { unitPath, unitName, content }) {
|
|
|
128
127
|
throw new Error(`systemd-analyze verify 失败(未写入 ${unitPath}):\n${verify.stderr}`);
|
|
129
128
|
writeFileAtomic(unitPath, content, { mode: 0o644 });
|
|
130
129
|
try {
|
|
131
|
-
|
|
132
|
-
if (reload.code !== 0)
|
|
133
|
-
throw new Error(`systemctl daemon-reload 失败:${reload.stderr.trim()}`);
|
|
130
|
+
daemonReload(runner);
|
|
134
131
|
enableRestart(runner, unitName);
|
|
135
132
|
} catch (err) {
|
|
136
133
|
// 文件相同只能表示部署完成:失败时恢复旧文件并重载 manager;首装撤掉
|
|
@@ -145,9 +142,7 @@ export function syncUnit(runner, { unitPath, unitName, content }) {
|
|
|
145
142
|
} else {
|
|
146
143
|
writeFileAtomic(unitPath, previous, { mode: 0o644 });
|
|
147
144
|
}
|
|
148
|
-
|
|
149
|
-
if (reload.code !== 0)
|
|
150
|
-
throw new Error(`恢复后 systemctl daemon-reload 失败:${reload.stderr.trim()}`);
|
|
145
|
+
daemonReload(runner, '恢复后 ');
|
|
151
146
|
if (previous !== null) enableRestart(runner, unitName);
|
|
152
147
|
} catch (rollbackError) {
|
|
153
148
|
throw new AggregateError([err, rollbackError], `${err.message};恢复 systemd 状态失败:${rollbackError.message}`);
|
package/libexec/sn-route
CHANGED
|
@@ -166,28 +166,27 @@ fail_relay() {
|
|
|
166
166
|
# 本次报名也会立刻重建回拨。任何意外(lsof 缺失/失败、无持有者、comm 不符)
|
|
167
167
|
# 静默:等 sshd 90s 自行回收,之后下一条连接(受 15s 印记节流)再报名唤醒
|
|
168
168
|
reap_zombie() {
|
|
169
|
-
local pid= line comm= hit6= lsof_pid rc room expired=
|
|
169
|
+
local pid= line comm= hit6= lsof_pid watchdog_pid rc room expired=
|
|
170
170
|
local out="$STATE_DIR/LSOF.tmp.$$"
|
|
171
171
|
room=$((deadline - SECONDS - 1))
|
|
172
172
|
[ "$room" -ge 1 ] || return 1
|
|
173
|
-
# lsof
|
|
174
|
-
#
|
|
173
|
+
# lsof 正常结束就立刻 wait 返回,不白睡连接恢复用的 POLL;watchdog 只负责
|
|
174
|
+
# 到点留印记并 kill。半截输出绝不用于杀进程;正常失败仍静默跳过清尸。
|
|
175
175
|
"$LSOF" -F pcn -nP -i "TCP:$PORT" -sTCP:LISTEN >"$out" 2>/dev/null &
|
|
176
176
|
lsof_pid=$!
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
break
|
|
184
|
-
fi
|
|
185
|
-
"$SLEEP" "$POLL" 2>/dev/null || true
|
|
186
|
-
done
|
|
177
|
+
(
|
|
178
|
+
"$SLEEP" "$room" 2>/dev/null
|
|
179
|
+
: >"$out.expired"
|
|
180
|
+
kill "$lsof_pid" 2>/dev/null
|
|
181
|
+
) &
|
|
182
|
+
watchdog_pid=$!
|
|
187
183
|
wait "$lsof_pid" 2>/dev/null
|
|
188
184
|
rc=$?
|
|
185
|
+
kill "$watchdog_pid" 2>/dev/null
|
|
186
|
+
wait "$watchdog_pid" 2>/dev/null
|
|
187
|
+
[ -e "$out.expired" ] && expired=1
|
|
189
188
|
if [ -n "$expired" ]; then
|
|
190
|
-
"$RM" -f "$out" 2>/dev/null
|
|
189
|
+
"$RM" -f "$out" "$out.expired" 2>/dev/null
|
|
191
190
|
return 1
|
|
192
191
|
fi
|
|
193
192
|
# 一个进程块收尾:只有「本进程真有一条 [::1]:$PORT 的 LISTEN」且
|
|
@@ -209,13 +208,14 @@ reap_zombie() {
|
|
|
209
208
|
done <"$out"
|
|
210
209
|
flush
|
|
211
210
|
fi
|
|
212
|
-
"$RM" -f "$out" 2>/dev/null
|
|
211
|
+
"$RM" -f "$out" "$out.expired" 2>/dev/null
|
|
213
212
|
return 0
|
|
214
213
|
}
|
|
215
214
|
|
|
216
215
|
# ── 层 1
|
|
217
|
-
# 层 5 的 lsof 是后台进程:进入层 6 的 cleanup 前,TERM/INT
|
|
218
|
-
|
|
216
|
+
# 层 5 的 lsof 与 watchdog 是后台进程:进入层 6 的 cleanup 前,TERM/INT
|
|
217
|
+
# 也要收掉它们和临时文件
|
|
218
|
+
trap '[ -n "${lsof_pid:-}" ] && kill "$lsof_pid" 2>/dev/null; [ -n "${watchdog_pid:-}" ] && kill "$watchdog_pid" 2>/dev/null; [ -n "${out:-}" ] && "$RM" -f "$out" "$out.expired" 2>/dev/null; exit 1' TERM INT
|
|
219
219
|
[ -e "$STATE_DIR/RELAY_ON" ] || exit 1
|
|
220
220
|
|
|
221
221
|
peer_on=0
|