ssh-net 0.1.0

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.
@@ -0,0 +1,187 @@
1
+ // status(design §6.7):只报本机角色,判据是 banner/端口/注册态真实探测。
2
+ // collect 返回结构化对象(测试断言对象,不锁文本);renderText 给人看。
3
+ // 退出码:健康(含 edge off)0;有可行动问题(悬空链/该听没听/软链缺失)1。
4
+ // on 在但 probe 不通不算问题:可能只是回拨尚未建立(relay 同期可用)。
5
+ import path from 'node:path';
6
+ import { auditLink } from '../lib/links.mjs';
7
+ import { packageScriptTarget } from '../lib/paths.mjs';
8
+ import * as launchd from '../lib/launchd.mjs';
9
+ import * as systemd from '../lib/systemd.mjs';
10
+ import { peerProbeOk, tcpOpen } from '../lib/probe.mjs';
11
+ import {
12
+ linkLabel, linkLinkName, relayLabel, relayLinkName, relayUnitName,
13
+ edgeLabel, edgeLinkName,
14
+ } from '../lib/render.mjs';
15
+
16
+ function auditRequired(ctx, entries) {
17
+ return entries.map(([name, script]) => {
18
+ const expected = packageScriptTarget(script, ctx.env);
19
+ return {
20
+ link: name,
21
+ audit: auditLink(path.join(ctx.paths.binDir, name), expected),
22
+ };
23
+ });
24
+ }
25
+
26
+ function relayPortListening(ctx, port) {
27
+ // relay 别名的 User/HostName 由 ssh config Host 块提供;
28
+ // BatchMode 防换机器/换钥匙时在终端闪密码提示(与运行时五个 ssh 同约定)
29
+ const r = ctx.runner.run('ssh', [
30
+ '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5',
31
+ ctx.topo.relay.alias, 'ss', '-tlnH',
32
+ ], { timeout: 8000 });
33
+ if (r.code !== 0) return { reachable: false, listening: false, detail: r.stderr.trim() };
34
+ return { reachable: true, listening: new RegExp(`127\\.0\\.0\\.1[:.]${port}\\b`).test(r.stdout) };
35
+ }
36
+
37
+ async function collectEdge(ctx) {
38
+ const { topo, paths, state } = ctx;
39
+ const issues = [];
40
+ const links = auditRequired(ctx, [
41
+ [linkLinkName(topo.core.alias), 'ssh-net-link-core'],
42
+ ['peer-probe', 'peer-probe'],
43
+ ['v6-address', 'v6-address'],
44
+ ]);
45
+ if (links.some((l) => l.audit === 'dangling' || l.audit === 'foreign'))
46
+ issues.push('运行时链异常(悬空或指向不符):npm i -g ssh-net 后恢复,或重新 install');
47
+ if (links.every((l) => l.audit === 'missing'))
48
+ issues.push('运行时未安装(ssh-net install)');
49
+ else if (links.some((l) => l.audit === 'missing'))
50
+ // 部分缺失:peer-probe 丢了会让 on 态恒判 relay,不能只显示不报
51
+ issues.push('部分运行时软链缺失:重新 ssh-net install 恢复');
52
+
53
+ const label = linkLabel(topo.core.alias);
54
+ const job = launchd.inspect(ctx.runner, ctx.uid, label);
55
+ const on = state.isOn();
56
+
57
+ let route = 'lan';
58
+ let peer = null;
59
+ const ports = {};
60
+ if (on) {
61
+ peer = peerProbeOk(ctx.runner, paths.binDir);
62
+ route = peer ? 'peer' : 'relay';
63
+ // on 但 probe 不通可能只是回拨尚未建立;不当作问题(relay 同期可用)
64
+ }
65
+ const openTcp = ctx.openTcp ?? tcpOpen; // 测试可注入,避免连真端口
66
+ for (const f of topo.forwards) ports[f.listenPort] = await openTcp('127.0.0.1', f.listenPort);
67
+
68
+ // off 时转发口仍在听=孤儿进程
69
+ if (!on)
70
+ for (const [p, listening] of Object.entries(ports))
71
+ if (listening) issues.push(`on 不在但端口 ${p} 仍在监听(孤儿转发进程?)`);
72
+
73
+ let v6 = '';
74
+ if (links.find((l) => l.link === 'v6-address')?.audit === 'ok')
75
+ v6 = ctx.runner.runRaw(path.join(paths.binDir, 'v6-address'), [], { timeout: 5000 }).stdout.trim();
76
+
77
+ return { role: 'edge', alias: ctx.self.alias, on, route, peer, job, links, ports, v6, issues };
78
+ }
79
+
80
+ async function collectCore(ctx) {
81
+ const { topo, paths } = ctx;
82
+ const issues = [];
83
+ const links = auditRequired(ctx, [
84
+ [relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay'],
85
+ ]);
86
+ if (links.some((l) => l.audit === 'dangling' || l.audit === 'foreign'))
87
+ issues.push('uplink-relay 软链悬空或指向不符:npm i -g ssh-net 后恢复');
88
+ if (links.every((l) => l.audit === 'missing'))
89
+ issues.push('运行时未安装(ssh-net install)');
90
+
91
+ const relayLabelName = relayLabel(topo.relay.alias);
92
+ const relayJob = launchd.inspect(ctx.runner, ctx.uid, relayLabelName);
93
+ const relayPort = relayPortListening(ctx, topo.core.relayPort);
94
+
95
+ const edges = [];
96
+ for (const e of topo.edges) {
97
+ const label = edgeLabel(e.alias);
98
+ const st = launchd.inspect(ctx.runner, ctx.uid, label);
99
+ // 已注册(= 报过名、checkin 建过链)的 edge 链一并体检:与 relay 链
100
+ // 同一故障面(fnm 切版本悬空、手工误删),悬空只看 last exit 不显眼
101
+ if (st.registered) {
102
+ const a = auditLink(
103
+ path.join(paths.binDir, edgeLinkName(e.alias)),
104
+ packageScriptTarget('ssh-net-uplink-edge', ctx.env),
105
+ );
106
+ if (a !== 'ok')
107
+ issues.push(`edge ${e.alias} 运行时软链异常(${a}):npm i -g ssh-net 后恢复,或等下次 checkin 对账`);
108
+ }
109
+ edges.push({
110
+ alias: e.alias,
111
+ registered: st.registered,
112
+ disabled: st.disabled,
113
+ running: st.running,
114
+ lastExitCode: st.lastExitCode,
115
+ v6: ctx.state.readEdgeV6(e.alias),
116
+ });
117
+ }
118
+
119
+ if (!relayJob.running) issues.push('uplink-relay 未在运行');
120
+ if (!relayPort.listening) issues.push(`s100 环回口 ${topo.core.relayPort} 未在监听`);
121
+
122
+ return { role: 'core', alias: ctx.self.alias, links, relayJob, relayPort, edges, issues };
123
+ }
124
+
125
+ function collectNode(ctx) {
126
+ const { topo } = ctx;
127
+ const issues = [];
128
+ const links = auditRequired(ctx, [
129
+ [relayLinkName(topo.relay.alias), 'ssh-net-uplink-relay'],
130
+ ]);
131
+ if (links.some((l) => l.audit === 'dangling' || l.audit === 'foreign'))
132
+ issues.push('uplink-relay 软链悬空或指向不符:npm i -g ssh-net 后恢复');
133
+ if (links.every((l) => l.audit === 'missing'))
134
+ issues.push('运行时未安装(ssh-net install)');
135
+
136
+ const unit = relayUnitName(topo.relay.alias);
137
+ const active = systemd.isActive(ctx.runner, unit);
138
+ const relayPort = relayPortListening(ctx, ctx.self.relayPort);
139
+ if (active !== 'active') issues.push(`unit ${unit} 非 active(${active})`);
140
+ if (!relayPort.listening) issues.push(`s100 环回口 ${ctx.self.relayPort} 未在监听`);
141
+
142
+ return { role: 'node', alias: ctx.self.alias, links, unit, active, relayPort, issues };
143
+ }
144
+
145
+ export async function collect(ctx) {
146
+ if (ctx.role === 'edge') return collectEdge(ctx);
147
+ if (ctx.role === 'core') return collectCore(ctx);
148
+ if (ctx.role === 'node') return collectNode(ctx);
149
+ throw new Error(`未知角色:${ctx.role}`);
150
+ }
151
+
152
+ export function renderText(s) {
153
+ const lines = [];
154
+ lines.push(`ssh-net ${s.role} ${s.alias}`);
155
+ for (const l of s.links)
156
+ lines.push(` 链 ${l.link}: ${l.audit}`);
157
+
158
+ if (s.role === 'edge') {
159
+ lines.push(` on: ${s.on ? '在' : '不在(LAN 直连)'}`);
160
+ if (s.on) lines.push(` 路径: ${s.route}(peer-probe ${s.peer ? '见 banner' : '未见 banner'})`);
161
+ if (s.v6 !== '') lines.push(` v6: ${s.v6}`);
162
+ lines.push(` link job: ${s.job.registered ? (s.job.running ? 'running' : 'not running') : '未注册'}`);
163
+ for (const [p, ok] of Object.entries(s.ports))
164
+ lines.push(` 端口 ${p}: ${ok ? '在听' : '未听'}`);
165
+ } else if (s.role === 'core') {
166
+ lines.push(` uplink-relay: ${s.relayJob.running ? 'running' : 'not running'}(last exit ${s.relayJob.lastExitCode})`);
167
+ lines.push(` s100 注册口: ${s.relayPort.listening ? '在听' : `未听${s.relayPort.reachable === false ? '(s100 不可达)' : ''}`}`);
168
+ for (const e of s.edges) {
169
+ const state = !e.registered ? '未注册' : e.disabled ? 'disabled(休眠,等 checkin 唤醒)' : e.running ? 'running' : 'enabled/未运行';
170
+ lines.push(` edge ${e.alias}: ${state}${e.v6 ? ` v6=${e.v6}` : ''}${e.registered ? ` last=${e.lastExitCode}` : ''}`);
171
+ }
172
+ } else {
173
+ lines.push(` unit ${s.unit}: ${s.active}`);
174
+ lines.push(` s100 注册口: ${s.relayPort.listening ? '在听' : '未听'}`);
175
+ }
176
+
177
+ if (s.issues.length) {
178
+ lines.push('问题:');
179
+ for (const i of s.issues) lines.push(` - ${i}`);
180
+ }
181
+ return lines.join('\n');
182
+ }
183
+
184
+ export async function run(ctx) {
185
+ const s = await collect(ctx);
186
+ return { text: renderText(s), issues: s.issues, status: s };
187
+ }
@@ -0,0 +1,37 @@
1
+ // stop(design §5):edge rm on + TERM 并校验真退出;core disable+bootout
2
+ // uplink-relay(不动 uplink-edge);node stop+disable。
3
+ import * as launchd from '../lib/launchd.mjs';
4
+ import * as systemd from '../lib/systemd.mjs';
5
+ import { stopEdgeLink } from '../lib/jobctl.mjs';
6
+ import { relayLabel, relayUnitName } from '../lib/render.mjs';
7
+
8
+ function stopCore(ctx) {
9
+ const label = relayLabel(ctx.topo.relay.alias);
10
+ const d = launchd.disable(ctx.runner, ctx.uid, label);
11
+ if (d.code !== 0) throw new Error(`disable 失败:${d.stderr.trim()}`);
12
+ const bo = launchd.bootout(ctx.runner, ctx.uid, label);
13
+ // 113 = 未注册(竞态下消失);其余失败必须报,否则 stop 谎报成功、隧道还活着
14
+ if (bo.code !== 0 && bo.code !== 113)
15
+ throw new Error(`bootout 失败(job 仍在注册表):${bo.stderr.trim()}`);
16
+ return 'core uplink-relay 已 disable 并 bootout(uplink-edge 不受影响)';
17
+ }
18
+
19
+ export function run(ctx) {
20
+ if (ctx.role === 'edge') {
21
+ const { gone, label } = stopEdgeLink(ctx);
22
+ if (!gone)
23
+ throw new Error(
24
+ `${label} 仍在运行(TERM 已发两次)。手工排查:launchctl print gui/${ctx.uid}/${label}`,
25
+ );
26
+ return 'on 已删,link 已退出(core 侧回拨 job 将自行休眠)';
27
+ }
28
+ if (ctx.role === 'core') return stopCore(ctx);
29
+ if (ctx.role === 'node') {
30
+ const unit = relayUnitName(ctx.topo.relay.alias);
31
+ systemd.stopUnit(ctx.runner, unit);
32
+ const d = systemd.disableUnit(ctx.runner, unit);
33
+ if (d.code !== 0) throw new Error(`systemctl disable 失败:${d.stderr.trim()}`);
34
+ return `node ${unit} 已停止并 disable`;
35
+ }
36
+ throw new Error(`未知角色:${ctx.role}`);
37
+ }
@@ -0,0 +1,85 @@
1
+ // uninstall(design §5):先 bootout 全部 job(TERM trap 转发,不留孤儿 ssh),
2
+ // 再删 plist/软链/状态/日志。不发 RPC、不手动 disable(override root 持有,
3
+ // 重装时 install 的 enable-first 兜底)。
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { removeJob } from '../lib/manage.mjs';
7
+ import * as systemd from '../lib/systemd.mjs';
8
+ import {
9
+ linkLabel, plistFileName,
10
+ relayLabel, relayUnitName, edgeLabel,
11
+ } from '../lib/render.mjs';
12
+
13
+ const rm = (p) => fs.rmSync(p, { recursive: true, force: true });
14
+
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
+ function uninstallEdge(ctx) {
27
+ const label = linkLabel(ctx.topo.core.alias);
28
+ removeJob(ctx, label, path.join(
29
+ ctx.paths.launchAgentsDir, plistFileName(label),
30
+ ));
31
+ rm(ctx.paths.binDir);
32
+ rm(ctx.paths.stateDir);
33
+ rm(path.join(ctx.paths.logsDir, `${label}.log`));
34
+ return 'edge 作业、软链与状态已清除';
35
+ }
36
+
37
+ function uninstallCore(ctx) {
38
+ const dir = ctx.paths.launchAgentsDir;
39
+ // label → plist 路径:磁盘 glob(topology 已删的残留)∪ topology 在册 edge
40
+ const edgeJobs = new Map();
41
+ for (const f of edgePlistFiles(ctx)) {
42
+ edgeJobs.set(f.replace(/\.plist$/, ''), path.join(dir, f));
43
+ }
44
+ for (const e of ctx.topo.edges) {
45
+ const label = edgeLabel(e.alias);
46
+ if (!edgeJobs.has(label))
47
+ edgeJobs.set(label, path.join(dir, plistFileName(label)));
48
+ }
49
+ for (const [label, p] of edgeJobs) removeJob(ctx, label, p);
50
+
51
+ const relay = relayLabel(ctx.topo.relay.alias);
52
+ removeJob(ctx, relay, path.join(dir, plistFileName(relay)));
53
+
54
+ rm(ctx.paths.binDir);
55
+ rm(ctx.paths.stateDir);
56
+ for (const label of [...edgeJobs.keys(), relay])
57
+ rm(path.join(ctx.paths.logsDir, `${label}.log`));
58
+ return `core 作业已清除(relay + ${edgeJobs.size} 个 uplink-edge)`;
59
+ }
60
+
61
+ function uninstallNode(ctx) {
62
+ if (ctx.uid !== 0)
63
+ throw new Error('node 卸载写 /etc/systemd/system 需要 root,请以 root 运行');
64
+ const unit = relayUnitName(ctx.topo.relay.alias);
65
+ const s = systemd.stopUnit(ctx.runner, unit);
66
+ // unit 不存在(未装/已卸)的无害失败放行;真失败必须报——否则删了 unit
67
+ // 文件、systemd 里留下 ghost 态的在跑进程
68
+ if (s.code !== 0 && !/not loaded/.test(s.stderr))
69
+ throw new Error(`systemctl stop 失败:${s.stderr.trim()}`);
70
+ systemd.disableUnit(ctx.runner, unit); // 已禁无害
71
+ rm(path.join(ctx.paths.systemdUnitDir, unit));
72
+ systemd.daemonReload(ctx.runner);
73
+ rm(ctx.paths.binDir);
74
+ rm(ctx.paths.stateDir);
75
+ return `node unit ${unit} 已停用并删除(journald 日志保留)`;
76
+ }
77
+
78
+ export function run(ctx) {
79
+ switch (ctx.role) {
80
+ case 'edge': return uninstallEdge(ctx);
81
+ case 'core': return uninstallCore(ctx);
82
+ case 'node': return uninstallNode(ctx);
83
+ default: throw new Error(`未知角色:${ctx.role}`);
84
+ }
85
+ }
@@ -0,0 +1,227 @@
1
+ // topology 配置(~/.ssh/ssh-net/config,dotfiles 托管)的解析与严格校验。
2
+ // 格式见 design §4.1:空格分隔、`#` 注释、空行忽略、无项填 `-`。
3
+ // 解析期反规范化(forward local 的目标别名当场翻成 LAN IP),下游零查找。
4
+ // 只登记控制面真正消费的事实:relay 的地址/用户在 ssh config Host 块
5
+ // (dotfiles 同管),不在此重复登记。
6
+
7
+ import net from 'node:net';
8
+
9
+ export class ConfigError extends Error {
10
+ /**
11
+ * @param {number} line 1 起行号;0 表示文件级错误
12
+ * @param {string} message
13
+ */
14
+ constructor(line, message) {
15
+ super(line > 0 ? `config 第 ${line} 行:${message}` : message);
16
+ this.name = 'ConfigError';
17
+ this.line = line;
18
+ }
19
+ }
20
+
21
+ const ALIAS_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
22
+ const ROLES = new Set(['core', 'edge', 'node']);
23
+ const BIND = '127.0.0.1'; // 所有转发强制只绑环回(design §6.5)
24
+
25
+ /**
26
+ * @typedef {Object} RelayRow
27
+ * @property {string} alias
28
+ *
29
+ * @typedef {Object} HostRow
30
+ * @property {'core'|'edge'|'node'} role
31
+ * @property {string} hostname DOT_HOST 短主机名
32
+ * @property {string} alias
33
+ * @property {string|null} lanIp
34
+ * @property {number|null} relayPort
35
+ * @property {string} user
36
+ *
37
+ * @typedef {Object} Forward
38
+ * @property {'dynamic'|'local'} kind
39
+ * @property {string} bind 恒 127.0.0.1
40
+ * @property {number} listenPort
41
+ * @property {string} [targetAlias]
42
+ * @property {string} [targetIp]
43
+ * @property {number} [targetPort]
44
+ *
45
+ * @typedef {Object} Topology
46
+ * @property {RelayRow} relay
47
+ * @property {HostRow} core
48
+ * @property {HostRow[]} edges
49
+ * @property {HostRow[]} nodes
50
+ * @property {Map<string, HostRow>} byAlias
51
+ * @property {Map<string, HostRow>} byHostname
52
+ * @property {Forward[]} forwards
53
+ */
54
+
55
+ /** @param {string} tok */
56
+ function parsePort(tok) {
57
+ if (!/^\d+$/.test(tok)) return NaN;
58
+ return Number(tok);
59
+ }
60
+
61
+ /**
62
+ * @param {string} text
63
+ * @returns {Topology}
64
+ */
65
+ export function parseTopology(text) {
66
+ if (typeof text !== 'string' || text.trim().length === 0)
67
+ throw new ConfigError(0, 'config 为空');
68
+
69
+ /** @type {RelayRow|null} */
70
+ let relay = null;
71
+ /** @type {HostRow[]} */
72
+ const hosts = [];
73
+ /** @type {{kind:'dynamic'|'local', cols:string[], line:number}[]} */
74
+ const rawForwards = [];
75
+
76
+ const lines = text.split('\n');
77
+ lines.forEach((rawLine, idx) => {
78
+ const lineNo = idx + 1;
79
+ const line = rawLine.replace(/\r$/, '').trim();
80
+ if (line.length === 0 || line.startsWith('#')) return;
81
+ const cols = line.split(/\s+/);
82
+ const head = cols[0];
83
+
84
+ if (head === 'relay') {
85
+ if (cols.length !== 2)
86
+ throw new ConfigError(lineNo, 'relay 需要 2 列:relay <别名>');
87
+ const [, alias] = cols;
88
+ if (!ALIAS_RE.test(alias)) throw new ConfigError(lineNo, `别名非法:${alias}`);
89
+ if (relay) throw new ConfigError(lineNo, 'relay 只能有一行');
90
+ relay = { alias };
91
+ return;
92
+ }
93
+
94
+ if (head === 'host') {
95
+ if (cols.length !== 7)
96
+ throw new ConfigError(
97
+ lineNo,
98
+ 'host 需要 7 列:host <角色> <主机名> <别名> <LAN_IP|-> <relay端口|-> <用户>',
99
+ );
100
+ const [, role, hostname, alias, ipTok, portTok, user] = cols;
101
+ if (!ROLES.has(role)) throw new ConfigError(lineNo, `未知角色:${role}(只允许 core/edge/node)`);
102
+ if (!ALIAS_RE.test(hostname)) throw new ConfigError(lineNo, `主机名非法:${hostname}`);
103
+ if (!ALIAS_RE.test(alias)) throw new ConfigError(lineNo, `别名非法:${alias}`);
104
+ if (!user || user === '-') throw new ConfigError(lineNo, '用户不能为空');
105
+ /** @type {string|null} */
106
+ let lanIp = null;
107
+ /** @type {number|null} */
108
+ let relayPort = null;
109
+ if (role === 'edge') {
110
+ if (ipTok !== '-' || portTok !== '-')
111
+ throw new ConfigError(lineNo, 'edge 行的 LAN_IP 与 relay 端口必须填 -');
112
+ } else {
113
+ if (ipTok === '-' || !ipTok)
114
+ throw new ConfigError(lineNo, `${role} 行必须有 LAN_IP`);
115
+ if (net.isIP(ipTok) === 0)
116
+ throw new ConfigError(lineNo, `LAN_IP 不是 IP 字面值:${ipTok}`);
117
+ const p = parsePort(portTok);
118
+ if (!Number.isInteger(p) || p < 1 || p > 65535)
119
+ throw new ConfigError(lineNo, `relay 端口非法:${portTok}`);
120
+ lanIp = ipTok;
121
+ relayPort = p;
122
+ }
123
+ hosts.push({ role, hostname, alias, lanIp, relayPort, user });
124
+ return;
125
+ }
126
+
127
+ if (head === 'forward') {
128
+ const kind = cols[1];
129
+ if (kind !== 'dynamic' && kind !== 'local')
130
+ throw new ConfigError(lineNo, `forward 类型只允许 dynamic/local:${kind ?? '(缺)'} `);
131
+ if (kind === 'dynamic' && cols.length !== 3)
132
+ throw new ConfigError(lineNo, 'forward dynamic 需要 3 列:forward dynamic <本地端口>');
133
+ if (kind === 'local' && cols.length !== 5)
134
+ throw new ConfigError(lineNo, 'forward local 需要 5 列:forward local <本地端口> <目标别名> <目标端口>');
135
+ rawForwards.push({ kind, cols, line: lineNo });
136
+ return;
137
+ }
138
+
139
+ throw new ConfigError(lineNo, `未知行首:${head}(只允许 relay/host/forward/注释)`);
140
+ });
141
+
142
+ if (!relay) throw new ConfigError(0, '缺 relay 行');
143
+
144
+ const byAlias = new Map();
145
+ const byHostname = new Map();
146
+ // relay 别名、各 host 的别名与主机名同处一个命名空间(ssh Host/HostKeyAlias
147
+ // 共用),任一重复都报错。
148
+ const names = new Set([relay.alias]);
149
+ for (const h of hosts) {
150
+ for (const [name, what] of [
151
+ [h.alias, '别名'],
152
+ [h.hostname, '主机名'],
153
+ ]) {
154
+ if (names.has(name)) throw new ConfigError(0, `${what}重复:${name}`);
155
+ names.add(name);
156
+ }
157
+ byAlias.set(h.alias, h);
158
+ byHostname.set(h.hostname, h);
159
+ }
160
+
161
+ const core = hosts.filter((h) => h.role === 'core');
162
+ if (core.length !== 1)
163
+ throw new ConfigError(0, `core 必须恰好一台,当前 ${core.length} 台`);
164
+
165
+ /** @type {Forward[]} */
166
+ const forwards = [];
167
+ /** @type {Set<number>} */
168
+ const listenPorts = new Set();
169
+ for (const { kind, cols, line } of rawForwards) {
170
+ const listenPort = parsePort(cols[2]);
171
+ if (!Number.isInteger(listenPort) || listenPort < 1 || listenPort > 65535)
172
+ throw new ConfigError(line, `本地端口非法:${cols[2]}`);
173
+ if (listenPorts.has(listenPort))
174
+ throw new ConfigError(line, `转发本地端口重复:${listenPort}`);
175
+ listenPorts.add(listenPort);
176
+
177
+ if (kind === 'dynamic') {
178
+ forwards.push({ kind, bind: BIND, listenPort });
179
+ } else {
180
+ const targetAlias = cols[3];
181
+ const targetPort = parsePort(cols[4]);
182
+ if (!Number.isInteger(targetPort) || targetPort < 1 || targetPort > 65535)
183
+ throw new ConfigError(line, `目标端口非法:${cols[4]}`);
184
+ const target = byAlias.get(targetAlias);
185
+ if (!target)
186
+ throw new ConfigError(line, `forward local 指向未知别名:${targetAlias}`);
187
+ if (target.lanIp === null)
188
+ throw new ConfigError(line, `forward local 目标 ${targetAlias} 没有 LAN_IP(不能指向 edge)`);
189
+ forwards.push({
190
+ kind,
191
+ bind: BIND,
192
+ listenPort,
193
+ targetAlias,
194
+ targetIp: target.lanIp,
195
+ targetPort,
196
+ });
197
+ }
198
+ }
199
+
200
+ return Object.freeze({
201
+ relay,
202
+ core: core[0],
203
+ edges: Object.freeze(hosts.filter((h) => h.role === 'edge')),
204
+ nodes: Object.freeze(hosts.filter((h) => h.role === 'node')),
205
+ byAlias,
206
+ byHostname,
207
+ forwards: Object.freeze(forwards),
208
+ });
209
+ }
210
+
211
+ /**
212
+ * 转发渲染成 ssh argv 片段(-D/-L,目标 LAN IP 已在解析期翻译好)。
213
+ * @param {readonly Forward[]} forwards
214
+ * @returns {string[]}
215
+ */
216
+ export function buildForwardArgs(forwards) {
217
+ /** @type {string[]} */
218
+ const args = [];
219
+ for (const f of forwards) {
220
+ if (f.kind === 'dynamic') {
221
+ args.push('-D', `${f.bind}:${f.listenPort}`);
222
+ } else {
223
+ args.push('-L', `${f.bind}:${f.listenPort}:${f.targetIp}:${f.targetPort}`);
224
+ }
225
+ }
226
+ return args;
227
+ }
@@ -0,0 +1,6 @@
1
+ // 协议/代码常量(design §3)。CALLBACK_PORT 是 core 回拨在 edge 环回的监听口,
2
+ // 两台 edge 必须同值,写死不进 topology;relay 上各机自己的注册口因机而异,
3
+ // 在 topology 里。
4
+
5
+ /** core 经 -R 回拨、edge 环回上的监听端口。 */
6
+ export const CALLBACK_PORT = 10022;
@@ -0,0 +1,67 @@
1
+ // 唯一 import child_process 的模块:外部命令绝对路径 + 同步执行封装。
2
+ // launchd/systemd/probe 只构造 argv 与解释输出,经注入的 Runner 执行,
3
+ // 测试用环境变量 SSH_NET_<KEY> 把命令换成 fake(与 shell 脚本同一接缝风格)。
4
+ import { spawnSync } from 'node:child_process';
5
+
6
+ /** 命令默认绝对路径(launchd 最小环境没有交互 PATH)。 */
7
+ const DEFAULTS = {
8
+ ssh: '/usr/bin/ssh',
9
+ launchctl: '/bin/launchctl',
10
+ systemctl: '/usr/bin/systemctl',
11
+ systemdAnalyze: '/usr/bin/systemd-analyze',
12
+ lsof: '/usr/sbin/lsof',
13
+ plutil: '/usr/bin/plutil',
14
+ ps: '/bin/ps',
15
+ };
16
+
17
+ /**
18
+ * @param {string} key
19
+ * @param {NodeJS.ProcessEnv} [env]
20
+ * @returns {string}
21
+ */
22
+ export function commandPath(key, env = process.env) {
23
+ const override = env[`SSH_NET_${key.replaceAll(/([a-z])(?=[A-Z])/g, '$1_').toUpperCase()}`];
24
+ return override || DEFAULTS[key] || key;
25
+ }
26
+
27
+ /**
28
+ * @typedef {Object} RunResult
29
+ * @property {number|null} code 退出码(被信号杀时为 null)
30
+ * @property {string|null} signal
31
+ * @property {string} stdout
32
+ * @property {string} stderr
33
+ * @property {NodeJS.ErrnoException|null} error ENOENT 等启动失败
34
+ */
35
+
36
+ /**
37
+ * @typedef {Object} Runner
38
+ * @property {(key: string) => string} path
39
+ * @property {(key: string, args?: string[], opts?: object) => RunResult} run
40
+ * @property {(file: string, args?: string[], opts?: object) => RunResult} runRaw
41
+ */
42
+
43
+ /**
44
+ * @param {NodeJS.ProcessEnv} [env]
45
+ * @returns {Runner}
46
+ */
47
+ export function createRunner(env = process.env) {
48
+ const doSpawn = (file, args = [], opts = {}) => {
49
+ const r = spawnSync(file, args, {
50
+ encoding: 'utf8',
51
+ ...opts,
52
+ env: { ...env, ...(opts.env ?? {}) },
53
+ });
54
+ return {
55
+ code: r.status,
56
+ signal: r.signal,
57
+ stdout: r.stdout ?? '',
58
+ stderr: r.stderr ?? '',
59
+ error: r.error ?? null,
60
+ };
61
+ };
62
+ return {
63
+ path: (key) => commandPath(key, env),
64
+ run: (key, args, opts) => doSpawn(commandPath(key, env), args, opts),
65
+ runRaw: (file, args, opts) => doSpawn(file, args, opts),
66
+ };
67
+ }
@@ -0,0 +1,34 @@
1
+ // 本机身份自取(design §5):os.hostname() 砍掉首个 `.` 及后缀,
2
+ // 与 dotfiles lib/host.sh 的 DOT_HOST 同一算法,再与 topology 主机名列精确匹配。
3
+ // 不读 DOT_HOST 环境变量——它只在交互 shell 链 export,checkin 这类非交互
4
+ // ssh 远程命令里不存在。
5
+ import os from 'node:os';
6
+
7
+ /**
8
+ * 短主机名(去掉首个点及域名后缀)。
9
+ * @param {string} [hostname] 可注入,默认 os.hostname()
10
+ * @returns {string}
11
+ */
12
+ export function localHostname(hostname = os.hostname()) {
13
+ return hostname.split('.')[0];
14
+ }
15
+
16
+ /**
17
+ * @typedef {Object} IdentityMatch
18
+ * @property {'core'|'edge'|'node'} role
19
+ * @property {string} hostname
20
+ * @property {string} alias
21
+ * @property {string} user
22
+ * @property {string|null} lanIp
23
+ * @property {number|null} relayPort
24
+ */
25
+
26
+ /**
27
+ * 在 topology 里按主机名精确(大小写敏感)匹配本机身份。
28
+ * @param {{byHostname: Map<string, IdentityMatch>}} topology
29
+ * @param {string} [hostname]
30
+ * @returns {IdentityMatch | null}
31
+ */
32
+ export function matchIdentity(topology, hostname = localHostname()) {
33
+ return topology.byHostname.get(hostname) ?? null;
34
+ }
@@ -0,0 +1,39 @@
1
+ // checkin v6 入参的严格校验。唯一外部输入面(design §6.3):
2
+ // 合法 IPv6 字面值 + 落在 2000::/3 全局单播段;拒绝 scope id、内嵌 v4
3
+ // (含 ::ffff: v4-mapped)、ULA、link-local、unspecified、保留段等一切非 2000::/3。
4
+ // 依赖 net.isIP 做字面值合法性,首 hextet 判段——2000::/3 即首组 0x2000–0x3fff,
5
+ // 其余该拒的段(fc/fd、fe80、ff、::1、::)本就不在此区间,无需逐段分类。
6
+ import net from 'node:net';
7
+
8
+ /**
9
+ * @param {unknown} value
10
+ * @returns {boolean}
11
+ */
12
+ export function isGlobalUnicastV6(value) {
13
+ if (typeof value !== 'string') return false;
14
+ if (value.length === 0 || value.includes('%')) return false; // 无 scope id
15
+ if (net.isIP(value) !== 6) return false;
16
+ // 任何内嵌 v4 形态(末段含点,如 ::ffff:192.0.2.1)一律拒
17
+ const tail = value.slice(value.lastIndexOf(':') + 1);
18
+ if (tail.includes('.')) return false;
19
+ const firstGroup = value.split(':')[0];
20
+ const g0 = firstGroup === '' ? 0 : Number.parseInt(firstGroup, 16);
21
+ return Number.isInteger(g0) && g0 >= 0x2000 && g0 <= 0x3fff;
22
+ }
23
+
24
+ /**
25
+ * 给 checkin 报错用的中文原因;合法返回 null。
26
+ * @param {unknown} value
27
+ * @returns {string | null}
28
+ */
29
+ export function explainV6Error(value) {
30
+ if (typeof value !== 'string' || value.length === 0) return 'v6 为空';
31
+ if (value.includes('%')) return 'v6 带 scope id,拒绝';
32
+ if (net.isIP(value) !== 6) return '不是合法 IPv6 字面值';
33
+ if (value.slice(value.lastIndexOf(':') + 1).includes('.'))
34
+ return '拒绝内嵌 v4(含 ::ffff: v4-mapped)';
35
+ // 2000::/3 判定单一来源是 isGlobalUnicastV6,别在这抄第二份
36
+ if (!isGlobalUnicastV6(value))
37
+ return '不是 2000::/3 全局单播地址(拒绝 ULA/link-local/保留段)';
38
+ return null;
39
+ }