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.
- package/CHANGELOG.md +24 -0
- package/LICENSE +21 -0
- package/README.md +81 -0
- package/libexec/cli.mjs +114 -0
- package/libexec/commands/checkin.mjs +86 -0
- package/libexec/commands/install.mjs +129 -0
- package/libexec/commands/restart.mjs +30 -0
- package/libexec/commands/start.mjs +46 -0
- package/libexec/commands/status.mjs +187 -0
- package/libexec/commands/stop.mjs +37 -0
- package/libexec/commands/uninstall.mjs +85 -0
- package/libexec/lib/config.mjs +227 -0
- package/libexec/lib/constants.mjs +6 -0
- package/libexec/lib/exec.mjs +67 -0
- package/libexec/lib/identity.mjs +34 -0
- package/libexec/lib/ipv6.mjs +39 -0
- package/libexec/lib/jobctl.mjs +40 -0
- package/libexec/lib/launchd.mjs +106 -0
- package/libexec/lib/links.mjs +61 -0
- package/libexec/lib/manage.mjs +108 -0
- package/libexec/lib/paths.mjs +76 -0
- package/libexec/lib/probe.mjs +116 -0
- package/libexec/lib/render.mjs +157 -0
- package/libexec/lib/state.mjs +76 -0
- package/libexec/lib/systemd.mjs +30 -0
- package/libexec/peer-probe +20 -0
- package/libexec/ssh-net-link-core +94 -0
- package/libexec/ssh-net-uplink-edge +97 -0
- package/libexec/ssh-net-uplink-relay +15 -0
- package/libexec/v6-address +59 -0
- package/package.json +38 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// edge stop 的进程收束(design §5):rm on 后 launchctl kill TERM,轮询校验
|
|
2
|
+
// wrapper 真退出(TERM 转发给 ssh 与寿命定时器)。预算内补发一次 TERM,
|
|
3
|
+
// 仍在则报错给手工排障命令,绝不自动 KILL。同步 CLI 用 Atomics.wait 节流。
|
|
4
|
+
import * as launchd from './launchd.mjs';
|
|
5
|
+
import { linkLabel } from './render.mjs';
|
|
6
|
+
|
|
7
|
+
const TERM_BUDGET_MS = 40_000; // 覆盖 TERM 落在 checkin 前台 ssh 的最坏 ~35s
|
|
8
|
+
const POLL_MS = 500;
|
|
9
|
+
|
|
10
|
+
function sleepMs(ms) {
|
|
11
|
+
const buf = new Int32Array(new SharedArrayBuffer(4));
|
|
12
|
+
Atomics.wait(buf, 0, 0, ms);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function isGone(ctx, label) {
|
|
16
|
+
const st = launchd.inspect(ctx.runner, ctx.uid, label);
|
|
17
|
+
return !st.registered || (!st.running && st.pid === null);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {object} ctx
|
|
22
|
+
* @returns {{gone:boolean, label:string}}
|
|
23
|
+
*/
|
|
24
|
+
export function stopEdgeLink(ctx) {
|
|
25
|
+
const label = linkLabel(ctx.topo.core.alias);
|
|
26
|
+
ctx.state.removeOn(); // PathState:rm 不杀进程,但阻止退出后重拉
|
|
27
|
+
if (!launchd.inspect(ctx.runner, ctx.uid, label).registered) return { gone: true, label };
|
|
28
|
+
|
|
29
|
+
let remaining = TERM_BUDGET_MS;
|
|
30
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
31
|
+
launchd.killJob(ctx.runner, ctx.uid, label, 'TERM');
|
|
32
|
+
const end = Date.now() + Math.min(20_000, remaining);
|
|
33
|
+
while (Date.now() < end) {
|
|
34
|
+
if (isGone(ctx, label)) return { gone: true, label };
|
|
35
|
+
sleepMs(POLL_MS);
|
|
36
|
+
}
|
|
37
|
+
remaining -= 20_000;
|
|
38
|
+
}
|
|
39
|
+
return { gone: isGone(ctx, label), label };
|
|
40
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// mac gui 域 launchctl 编排。行为矩阵全部经 2026-09-28 m4 macOS 27 实测
|
|
2
|
+
// (notes「launchctl gui 域实测矩阵」):
|
|
3
|
+
// - 未注册 print exit 113 + “Could not find service”
|
|
4
|
+
// - 休眠判据只用 print-disabled 字典(print 正文无稳定字段)
|
|
5
|
+
// - 任何 bootstrap 前无条件先 enable(override 残留时 bootstrap error 5)
|
|
6
|
+
// - enable 本身不触发首发,唤醒必须 kickstart -k
|
|
7
|
+
/** @param {number} uid */
|
|
8
|
+
export const guiDomain = (uid) => `gui/${uid}`;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* print 正文解析。
|
|
12
|
+
* @param {{code:number|null, stderr:string, stdout:string}} result
|
|
13
|
+
* @returns {{registered:boolean, running:boolean, pid:number|null,
|
|
14
|
+
* runs:number|null, lastExitCode:string|null}}
|
|
15
|
+
*/
|
|
16
|
+
export function parsePrint(result) {
|
|
17
|
+
// 0 才是在册:113 之外的非零(域缺失/launchd 异常)一律按未注册处理,
|
|
18
|
+
// 误判成「已注册」会让 syncPlist 报 unchanged 却没在跑;按未注册走
|
|
19
|
+
// enable+bootstrap 会以真实报错浮出(2026-09-29 真机确认 113 语义)
|
|
20
|
+
const registered =
|
|
21
|
+
result.code === 0 && !/Could not find service/.test(result.stderr ?? '');
|
|
22
|
+
if (!registered) {
|
|
23
|
+
return { registered: false, running: false, pid: null, runs: null, lastExitCode: null };
|
|
24
|
+
}
|
|
25
|
+
const out = result.stdout ?? '';
|
|
26
|
+
const pidMatch = out.match(/^\s*pid\s*=\s*(\d+)/m);
|
|
27
|
+
const runsMatch = out.match(/^\s*runs\s*=\s*(\d+)/m);
|
|
28
|
+
const exitMatch = out.match(/^\s*last exit code\s*=\s*(.+)$/m);
|
|
29
|
+
return {
|
|
30
|
+
registered: true,
|
|
31
|
+
running: /^\s*state\s*=\s*running/m.test(out),
|
|
32
|
+
pid: pidMatch ? Number(pidMatch[1]) : null,
|
|
33
|
+
runs: runsMatch ? Number(runsMatch[1]) : null,
|
|
34
|
+
lastExitCode: exitMatch ? exitMatch[1].trim() : null,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* print-disabled 输出解析为 label → 是否 disabled。
|
|
40
|
+
* @param {string} stdout
|
|
41
|
+
* @returns {Map<string, boolean>}
|
|
42
|
+
*/
|
|
43
|
+
export function parseDisabled(stdout) {
|
|
44
|
+
const map = new Map();
|
|
45
|
+
for (const m of stdout.matchAll(/"([^"]+)"\s*=>\s*(enabled|disabled)/g)) {
|
|
46
|
+
map.set(m[1], m[2] === 'disabled');
|
|
47
|
+
}
|
|
48
|
+
return map;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @typedef {Object} JobState
|
|
53
|
+
* @property {boolean} registered
|
|
54
|
+
* @property {boolean} disabled
|
|
55
|
+
* @property {boolean} running
|
|
56
|
+
* @property {number|null} pid
|
|
57
|
+
* @property {number|null} runs
|
|
58
|
+
* @property {string|null} lastExitCode
|
|
59
|
+
*/
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* print + print-disabled 合成四态所需的全部事实。
|
|
63
|
+
* @param {import('./exec.mjs').Runner} runner
|
|
64
|
+
* @param {number} uid
|
|
65
|
+
* @param {string} label
|
|
66
|
+
* @returns {JobState}
|
|
67
|
+
*/
|
|
68
|
+
export function inspect(runner, uid, label) {
|
|
69
|
+
const domain = guiDomain(uid);
|
|
70
|
+
const printed = parsePrint(runner.run('launchctl', ['print', `${domain}/${label}`]));
|
|
71
|
+
if (!printed.registered) {
|
|
72
|
+
return { registered: false, disabled: false, running: false, pid: null, runs: null, lastExitCode: null };
|
|
73
|
+
}
|
|
74
|
+
const disabledMap = parseDisabled(
|
|
75
|
+
runner.run('launchctl', ['print-disabled', domain]).stdout,
|
|
76
|
+
);
|
|
77
|
+
return { ...printed, disabled: disabledMap.get(label) === true };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 以下均返回原始 RunResult,由命令层判 code(编排顺序是冻结行为,勿在此吞错)。 */
|
|
81
|
+
export const enable = (runner, uid, label) =>
|
|
82
|
+
runner.run('launchctl', ['enable', `${guiDomain(uid)}/${label}`]);
|
|
83
|
+
export const disable = (runner, uid, label) =>
|
|
84
|
+
runner.run('launchctl', ['disable', `${guiDomain(uid)}/${label}`]);
|
|
85
|
+
export const bootstrap = (runner, uid, plistPath) =>
|
|
86
|
+
runner.run('launchctl', ['bootstrap', guiDomain(uid), plistPath]);
|
|
87
|
+
export const kickstart = (runner, uid, label) =>
|
|
88
|
+
runner.run('launchctl', ['kickstart', '-k', `${guiDomain(uid)}/${label}`]);
|
|
89
|
+
/** kickstart 对 disabled job 被拒(实测矩阵),kickstart 前一律幂等 enable。 */
|
|
90
|
+
export const kickstartEnabled = (runner, uid, label) => {
|
|
91
|
+
enable(runner, uid, label);
|
|
92
|
+
return kickstart(runner, uid, label);
|
|
93
|
+
};
|
|
94
|
+
export const killJob = (runner, uid, label, signal = 'TERM') =>
|
|
95
|
+
runner.run('launchctl', ['kill', signal, `${guiDomain(uid)}/${label}`]);
|
|
96
|
+
export const bootout = (runner, uid, label) =>
|
|
97
|
+
runner.run('launchctl', ['bootout', `${guiDomain(uid)}/${label}`]);
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* plist 语法校验(lint 过不代表能 bootstrap,但能挡住明显手误)。
|
|
101
|
+
* @param {import('./exec.mjs').Runner} runner
|
|
102
|
+
* @param {string} plistPath
|
|
103
|
+
*/
|
|
104
|
+
export function lintPlist(runner, plistPath) {
|
|
105
|
+
return runner.run('plutil', ['-lint', plistPath]);
|
|
106
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// bin/ 软链的对账(install/checkin/status 三方共享,design §2.3)。
|
|
2
|
+
// install 幂等:目标正确不重建;checkin 首次报名建 uplink-edge 链;
|
|
3
|
+
// status 逐条体检。目标是实体文件(非软链)时不擅自删,抛错让人处理。
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
|
|
6
|
+
/** 软链路径上已有非软链实体时抛此错。 */
|
|
7
|
+
export class LinkOccupiedError extends Error {
|
|
8
|
+
/** @param {string} linkPath */
|
|
9
|
+
constructor(linkPath) {
|
|
10
|
+
super(`软链位置被实体文件占用(不自动删除):${linkPath}`);
|
|
11
|
+
this.name = 'LinkOccupiedError';
|
|
12
|
+
this.linkPath = linkPath;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 幂等建链。
|
|
18
|
+
* @param {string} linkPath
|
|
19
|
+
* @param {string} target 期望目标(绝对路径)
|
|
20
|
+
* @returns {'created'|'unchanged'|'replaced'}
|
|
21
|
+
*/
|
|
22
|
+
export function ensureLink(linkPath, target) {
|
|
23
|
+
let existing;
|
|
24
|
+
try {
|
|
25
|
+
existing = fs.lstatSync(linkPath);
|
|
26
|
+
} catch (err) {
|
|
27
|
+
if (!err || err.code !== 'ENOENT') throw err;
|
|
28
|
+
fs.symlinkSync(target, linkPath);
|
|
29
|
+
return 'created';
|
|
30
|
+
}
|
|
31
|
+
if (!existing.isSymbolicLink()) throw new LinkOccupiedError(linkPath);
|
|
32
|
+
if (fs.readlinkSync(linkPath) === target) return 'unchanged';
|
|
33
|
+
fs.unlinkSync(linkPath);
|
|
34
|
+
fs.symlinkSync(target, linkPath);
|
|
35
|
+
return 'replaced';
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 软链体检(status 用)。
|
|
40
|
+
* @param {string} linkPath
|
|
41
|
+
* @param {string} expectedTarget
|
|
42
|
+
* @returns {'ok'|'missing'|'dangling'|'foreign'}
|
|
43
|
+
*/
|
|
44
|
+
export function auditLink(linkPath, expectedTarget) {
|
|
45
|
+
let st;
|
|
46
|
+
try {
|
|
47
|
+
st = fs.lstatSync(linkPath);
|
|
48
|
+
} catch (err) {
|
|
49
|
+
if (!err || err.code !== 'ENOENT') throw err;
|
|
50
|
+
return 'missing';
|
|
51
|
+
}
|
|
52
|
+
if (!st.isSymbolicLink()) return 'foreign';
|
|
53
|
+
if (fs.readlinkSync(linkPath) !== expectedTarget) return 'foreign';
|
|
54
|
+
try {
|
|
55
|
+
fs.statSync(linkPath); // 跟随符号链,失败=悬空
|
|
56
|
+
} catch (err) {
|
|
57
|
+
if (!err || err.code !== 'ENOENT') throw err;
|
|
58
|
+
return 'dangling';
|
|
59
|
+
}
|
|
60
|
+
return 'ok';
|
|
61
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// install 与 checkin 共享的落地原语:bin 软链幂等、plist 原子落盘 +
|
|
2
|
+
// launchctl 注册态同步。核心承诺(design §5):渲染结果与现文件字节相同则
|
|
3
|
+
// 不 bootout——install 幂等不断连。
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { ensureLink } from './links.mjs';
|
|
7
|
+
import { packageScriptTarget } from './paths.mjs';
|
|
8
|
+
import * as launchd from './launchd.mjs';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 幂等对账 bin/ 软链(带机器名 → 包脚本)。
|
|
12
|
+
* @param {object} ctx
|
|
13
|
+
* @param {readonly (readonly [string, string])[]} entries [软链名, 包脚本名]
|
|
14
|
+
* @returns {('created'|'unchanged'|'replaced')[]}
|
|
15
|
+
*/
|
|
16
|
+
export function ensureBinLinks(ctx, entries) {
|
|
17
|
+
fs.mkdirSync(ctx.paths.binDir, { recursive: true });
|
|
18
|
+
return entries.map(([linkName, scriptName]) =>
|
|
19
|
+
ensureLink(
|
|
20
|
+
path.join(ctx.paths.binDir, linkName),
|
|
21
|
+
packageScriptTarget(scriptName, ctx.env),
|
|
22
|
+
));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 同目录 tmp + rename 原子落盘。 */
|
|
26
|
+
export function writeFileAtomic(file, content, mode = 0o644) {
|
|
27
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
28
|
+
fs.writeFileSync(tmp, content, { mode });
|
|
29
|
+
fs.renameSync(tmp, file);
|
|
30
|
+
fs.chmodSync(file, mode);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 同步一个 plist 到磁盘并按需注册(幂等、不断连)。
|
|
35
|
+
* @param {object} ctx
|
|
36
|
+
* @param {{label:string, plistPath:string, content:string}} job
|
|
37
|
+
* @returns {{unchanged?:boolean, registered?:boolean, revived?:boolean,
|
|
38
|
+
* deployed?:boolean, lintError?:string}}
|
|
39
|
+
*/
|
|
40
|
+
export function syncPlist(ctx, { label, plistPath, content }) {
|
|
41
|
+
const { runner, uid, paths } = ctx;
|
|
42
|
+
fs.mkdirSync(paths.launchAgentsDir, { recursive: true });
|
|
43
|
+
fs.mkdirSync(paths.logsDir, { recursive: true });
|
|
44
|
+
|
|
45
|
+
let existing = null;
|
|
46
|
+
try {
|
|
47
|
+
existing = fs.readFileSync(plistPath, 'utf8');
|
|
48
|
+
} catch {
|
|
49
|
+
existing = null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (existing === content) {
|
|
53
|
+
const st = launchd.inspect(runner, uid, label);
|
|
54
|
+
// registered+disabled(stop 中途失败/手工 disable)不是「已部署」:
|
|
55
|
+
// enable 后拉起,否则 install 报 unchanged 却没在跑、start 的 kickstart 被拒
|
|
56
|
+
if (st.registered && !st.disabled) return { unchanged: true };
|
|
57
|
+
launchd.enable(runner, uid, label);
|
|
58
|
+
if (!st.registered) {
|
|
59
|
+
const b = launchd.bootstrap(runner, uid, plistPath);
|
|
60
|
+
if (b.code !== 0) throw new Error(`bootstrap 失败(${label}):${b.stderr.trim()}`);
|
|
61
|
+
return { registered: true };
|
|
62
|
+
}
|
|
63
|
+
const k = launchd.kickstart(runner, uid, label);
|
|
64
|
+
if (k.code !== 0) throw new Error(`kickstart 失败(${label}):${k.stderr.trim()}`);
|
|
65
|
+
return { revived: true };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// 内容变化(或首次):先 lint tmp,过了再动现文件
|
|
69
|
+
const tmp = `${plistPath}.tmp-${process.pid}`;
|
|
70
|
+
fs.writeFileSync(tmp, content, { mode: 0o644 });
|
|
71
|
+
const lint = launchd.lintPlist(runner, tmp);
|
|
72
|
+
if (lint.code !== 0) {
|
|
73
|
+
fs.rmSync(tmp, { force: true });
|
|
74
|
+
return { lintError: lint.stderr.trim() || `plutil exit ${lint.code}` };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const st = launchd.inspect(runner, uid, label);
|
|
78
|
+
if (st.registered) {
|
|
79
|
+
const bo = launchd.bootout(runner, uid, label);
|
|
80
|
+
if (bo.code !== 0 && bo.code !== 113)
|
|
81
|
+
throw new Error(`bootout 失败(${label}):${bo.stderr.trim()}`);
|
|
82
|
+
}
|
|
83
|
+
fs.renameSync(tmp, plistPath);
|
|
84
|
+
fs.chmodSync(plistPath, 0o644);
|
|
85
|
+
launchd.enable(runner, uid, label); // 无条件先 enable(override 残留时 bootstrap error 5)
|
|
86
|
+
const b = launchd.bootstrap(runner, uid, plistPath);
|
|
87
|
+
if (b.code !== 0) throw new Error(`bootstrap 失败(${label}):${b.stderr.trim()}`);
|
|
88
|
+
return { deployed: true };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 卸载一个 job:在册才 bootout(忽略未注册),再删 plist。
|
|
93
|
+
* @param {object} ctx
|
|
94
|
+
* @param {string} label
|
|
95
|
+
* @param {string} plistPath
|
|
96
|
+
*/
|
|
97
|
+
export function removeJob(ctx, label, plistPath) {
|
|
98
|
+
const { runner, uid } = ctx;
|
|
99
|
+
const st = launchd.inspect(runner, uid, label);
|
|
100
|
+
if (st.registered) {
|
|
101
|
+
const bo = launchd.bootout(runner, uid, label);
|
|
102
|
+
// 113 = 未注册(竞态下消失),其余失败必须报:job 还在注册表里,删了
|
|
103
|
+
// plist 会留下内存态孤儿
|
|
104
|
+
if (bo.code !== 0 && bo.code !== 113)
|
|
105
|
+
throw new Error(`bootout 失败(${label}):${bo.stderr.trim()}`);
|
|
106
|
+
}
|
|
107
|
+
fs.rmSync(plistPath, { force: true });
|
|
108
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// 路径与软链目标规范化。纯函数 + 少量环境派生常量;需要注入的场景(测试)
|
|
2
|
+
// 一律走参数,不读模块级可变状态。
|
|
3
|
+
//
|
|
4
|
+
// 软链规则(design §2.3,唯一真相):cli/lib 经 import.meta.url(Node 默认
|
|
5
|
+
// realpath 符号链)落在 fnm 的具体版本目录
|
|
6
|
+
// `$FNM_DIR/node-versions/<ver>/installation/lib/node_modules/ssh-net/...`,
|
|
7
|
+
// 建链前把该前缀替换为稳定的 `$FNM_DIR/aliases/default/`;npm link 开发态
|
|
8
|
+
// realpath 在 ~/space/ssh-net,不匹配前缀,原样指仓实体。
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* fnm 根目录。
|
|
15
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
16
|
+
* @returns {string}
|
|
17
|
+
*/
|
|
18
|
+
export function fnmDir(env = process.env) {
|
|
19
|
+
return env.FNM_DIR && env.FNM_DIR.length > 0
|
|
20
|
+
? env.FNM_DIR
|
|
21
|
+
: path.join(env.HOME ?? '', '.local', 'share', 'fnm');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 把包内实体的真实路径规范化为 fnm aliases/default 形态;非 fnm 版本目录
|
|
26
|
+
* (npm link 开发态等)原样返回。
|
|
27
|
+
* @param {string} realPath 经 realpath 解析后的绝对路径
|
|
28
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
29
|
+
* @returns {string}
|
|
30
|
+
*/
|
|
31
|
+
export function normalizeScriptTarget(realPath, env = process.env) {
|
|
32
|
+
const versionsRoot = path.join(fnmDir(env), 'node-versions');
|
|
33
|
+
if (!realPath.startsWith(versionsRoot + path.sep)) return realPath;
|
|
34
|
+
const rel = path.relative(versionsRoot, realPath).split(path.sep);
|
|
35
|
+
// rel = [<ver>, 'installation', 'lib', 'node_modules', ...]
|
|
36
|
+
if (rel.length < 3 || rel[1] !== 'installation') return realPath;
|
|
37
|
+
return path.join(fnmDir(env), 'aliases', 'default', ...rel.slice(2));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 包内 libexec 实体所在的真实目录(本文件经 realpath 后位于 libexec/lib)。 */
|
|
41
|
+
const LIB_REAL = fs.realpathSync(fileURLToPath(import.meta.url));
|
|
42
|
+
const LIBEXEC_REAL = path.dirname(path.dirname(LIB_REAL));
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 包脚本经 fnm alias 规范化后的目标路径(install/checkin 软链指向它)。
|
|
46
|
+
* @param {string} scriptName libexec 下脚本名,如 ssh-net-link-core
|
|
47
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
48
|
+
* @returns {string}
|
|
49
|
+
*/
|
|
50
|
+
export function packageScriptTarget(scriptName, env = process.env) {
|
|
51
|
+
return normalizeScriptTarget(path.join(LIBEXEC_REAL, scriptName), env);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 本机全部产物与配置路径。config/known-hosts 在 dotfiles,state/bin 是本工具产物。
|
|
56
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
57
|
+
*/
|
|
58
|
+
export function machinePaths(env = process.env) {
|
|
59
|
+
const home = env.HOME ?? '';
|
|
60
|
+
const sshNetDir = path.join(home, '.ssh', 'ssh-net');
|
|
61
|
+
const stateDir = path.join(home, '.local', 'state', 'ssh-net');
|
|
62
|
+
return Object.freeze({
|
|
63
|
+
home,
|
|
64
|
+
sshDir: path.join(home, '.ssh'),
|
|
65
|
+
sshNetDir,
|
|
66
|
+
configFile: path.join(sshNetDir, 'config'),
|
|
67
|
+
knownHostsFile: path.join(sshNetDir, 'known-hosts'),
|
|
68
|
+
binDir: path.join(sshNetDir, 'bin'),
|
|
69
|
+
stateDir,
|
|
70
|
+
onFile: path.join(stateDir, 'on'),
|
|
71
|
+
edgesDir: path.join(stateDir, 'edges'),
|
|
72
|
+
launchAgentsDir: path.join(home, 'Library', 'LaunchAgents'),
|
|
73
|
+
logsDir: path.join(home, 'Library', 'Logs'),
|
|
74
|
+
systemdUnitDir: '/etc/systemd/system',
|
|
75
|
+
});
|
|
76
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// 真实探测,不信声明(design §5 端口预检、§6.7 status)。
|
|
2
|
+
// - 1080/15900 的持口者是 link bash 的 ssh 子进程,要用 ps 父子表判后代
|
|
3
|
+
// - 10022 的持口者永远是本机 sshd(-R 服务端持口),无法按 pid 溯源,
|
|
4
|
+
// 只能以 peer-probe 是否读到 SSH banner 认定是不是本服务
|
|
5
|
+
import net from 'node:net';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* TCP 能否在超时内连上(status 用,mjs 侧不依赖 nc)。
|
|
10
|
+
* @param {string} host
|
|
11
|
+
* @param {number} port
|
|
12
|
+
* @param {number} [timeoutMs]
|
|
13
|
+
* @returns {Promise<boolean>}
|
|
14
|
+
*/
|
|
15
|
+
export function tcpOpen(host, port, timeoutMs = 300) {
|
|
16
|
+
return new Promise((resolve) => {
|
|
17
|
+
const sock = net.createConnection({ host, port });
|
|
18
|
+
let done = false;
|
|
19
|
+
const finish = (ok) => {
|
|
20
|
+
if (done) return;
|
|
21
|
+
done = true;
|
|
22
|
+
sock.destroy();
|
|
23
|
+
resolve(ok);
|
|
24
|
+
};
|
|
25
|
+
sock.setTimeout(timeoutMs);
|
|
26
|
+
sock.on('connect', () => finish(true));
|
|
27
|
+
sock.on('timeout', () => finish(false));
|
|
28
|
+
sock.on('error', () => finish(false));
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 环回某端口当前的监听 pid 列表(无监听空数组)。
|
|
34
|
+
* @param {import('./exec.mjs').Runner} runner
|
|
35
|
+
* @param {number} port
|
|
36
|
+
* @returns {number[]}
|
|
37
|
+
*/
|
|
38
|
+
export function listListeners(runner, port) {
|
|
39
|
+
const r = runner.run('lsof', ['-tnP', `-iTCP:${port}`, '-sTCP:LISTEN']);
|
|
40
|
+
if (r.code !== 0) return []; // lsof 无持有者时 exit 1
|
|
41
|
+
return r.stdout
|
|
42
|
+
.trim()
|
|
43
|
+
.split(/\s+/)
|
|
44
|
+
.filter(Boolean)
|
|
45
|
+
.map(Number)
|
|
46
|
+
.filter((n) => Number.isInteger(n));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 全机 pid→ppid 表。
|
|
51
|
+
* @param {import('./exec.mjs').Runner} runner
|
|
52
|
+
* @returns {Map<number, number>}
|
|
53
|
+
*/
|
|
54
|
+
export function processTree(runner) {
|
|
55
|
+
const r = runner.run('ps', ['-axo', 'pid=,ppid=']);
|
|
56
|
+
const tree = new Map();
|
|
57
|
+
for (const line of r.stdout.split('\n')) {
|
|
58
|
+
const m = line.trim().match(/^(\d+)\s+(\d+)$/);
|
|
59
|
+
if (m) tree.set(Number(m[1]), Number(m[2]));
|
|
60
|
+
}
|
|
61
|
+
return tree;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @param {Map<number,number>} tree
|
|
66
|
+
* @param {number} root
|
|
67
|
+
* @returns {Set<number>} root 的全部后代(不含 root)
|
|
68
|
+
*/
|
|
69
|
+
export function descendantsOf(tree, root) {
|
|
70
|
+
const children = new Map();
|
|
71
|
+
for (const [pid, ppid] of tree) {
|
|
72
|
+
if (!children.has(ppid)) children.set(ppid, []);
|
|
73
|
+
children.get(ppid).push(pid);
|
|
74
|
+
}
|
|
75
|
+
const out = new Set();
|
|
76
|
+
const stack = [root];
|
|
77
|
+
while (stack.length) {
|
|
78
|
+
const cur = stack.pop();
|
|
79
|
+
for (const child of children.get(cur) ?? []) {
|
|
80
|
+
if (!out.has(child)) {
|
|
81
|
+
out.add(child);
|
|
82
|
+
stack.push(child);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 1080/15900 预检:无监听=空闲;持口者全是 job 后代=本服务;否则冲突。
|
|
91
|
+
* @param {import('./exec.mjs').Runner} runner
|
|
92
|
+
* @param {number} port
|
|
93
|
+
* @param {number|null} jobPid link job 的 pid(未注册给 null)
|
|
94
|
+
* @returns {{kind:'free'|'ours'|'foreign', pids:number[]}}
|
|
95
|
+
*/
|
|
96
|
+
export function classifyLocalPort(runner, port, jobPid) {
|
|
97
|
+
const pids = listListeners(runner, port);
|
|
98
|
+
if (pids.length === 0) return { kind: 'free', pids: [] };
|
|
99
|
+
if (jobPid === null) return { kind: 'foreign', pids };
|
|
100
|
+
const ok = new Set([jobPid, ...descendantsOf(processTree(runner), jobPid)]);
|
|
101
|
+
return pids.every((p) => ok.has(p))
|
|
102
|
+
? { kind: 'ours', pids }
|
|
103
|
+
: { kind: 'foreign', pids };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 跑 bin/peer-probe(install 预检与 status 共用同一实现)。
|
|
108
|
+
* @param {import('./exec.mjs').Runner} runner
|
|
109
|
+
* @param {string} binDir
|
|
110
|
+
* @param {number} [timeoutMs]
|
|
111
|
+
* @returns {boolean}
|
|
112
|
+
*/
|
|
113
|
+
export function peerProbeOk(runner, binDir, timeoutMs = 5000) {
|
|
114
|
+
const r = runner.runRaw(path.join(binDir, 'peer-probe'), [], { timeout: timeoutMs });
|
|
115
|
+
return r.code === 0;
|
|
116
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// plist/systemd unit 的唯一渲染来源(design §2.3、§6.1、§6.2)。
|
|
2
|
+
// 纯字符串函数:每机差异只以位置参数出现(端口、别名、user、转发列表)。
|
|
3
|
+
// 渲染快照测试钉死输出;结构性断言(XML 闭合、只绑环回)在测试侧另查。
|
|
4
|
+
|
|
5
|
+
export const THROTTLE = 30; // launchd ThrottleInterval / 对应 systemd RestartSec
|
|
6
|
+
|
|
7
|
+
/** @param {string} s */
|
|
8
|
+
function xmlEscape(s) {
|
|
9
|
+
return s.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const XML_HEAD = `<?xml version="1.0" encoding="UTF-8"?>
|
|
13
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
14
|
+
<plist version="1.0">
|
|
15
|
+
<dict>
|
|
16
|
+
`;
|
|
17
|
+
const XML_TAIL = `</dict>
|
|
18
|
+
</plist>
|
|
19
|
+
`;
|
|
20
|
+
|
|
21
|
+
/** @param {readonly string[]} argv */
|
|
22
|
+
function programArguments(argv) {
|
|
23
|
+
const body = argv.map((a) => ` <string>${xmlEscape(a)}</string>`).join('\n');
|
|
24
|
+
return ` <key>ProgramArguments</key>
|
|
25
|
+
<array>
|
|
26
|
+
${body}
|
|
27
|
+
</array>
|
|
28
|
+
`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** @param {{label:string, logsDir:string}} opts */
|
|
32
|
+
function logPaths({ label, logsDir }) {
|
|
33
|
+
return ` <key>StandardOutPath</key>
|
|
34
|
+
<string>${xmlEscape(`${logsDir}/${label}.log`)}</string>
|
|
35
|
+
<key>StandardErrorPath</key>
|
|
36
|
+
<string>${xmlEscape(`${logsDir}/${label}.log`)}</string>
|
|
37
|
+
`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// ---- 命名(design §2.3 公式 ssh-net-<link|uplink>-<对端角色>-<对端别名>)----
|
|
41
|
+
|
|
42
|
+
/** @param {string} coreAlias */
|
|
43
|
+
export const linkLinkName = (coreAlias) => `ssh-net-link-core-${coreAlias}`;
|
|
44
|
+
/** @param {string} coreAlias */
|
|
45
|
+
export const linkLabel = (coreAlias) => `local.${linkLinkName(coreAlias)}`;
|
|
46
|
+
|
|
47
|
+
/** @param {string} relayAlias */
|
|
48
|
+
export const relayLinkName = (relayAlias) => `ssh-net-uplink-relay-${relayAlias}`;
|
|
49
|
+
/** @param {string} relayAlias */
|
|
50
|
+
export const relayLabel = (relayAlias) => `local.${relayLinkName(relayAlias)}`;
|
|
51
|
+
/** @param {string} relayAlias */
|
|
52
|
+
export const relayUnitName = (relayAlias) => `${relayLinkName(relayAlias)}.service`;
|
|
53
|
+
|
|
54
|
+
/** @param {string} edgeAlias */
|
|
55
|
+
export const edgeLinkName = (edgeAlias) => `ssh-net-uplink-edge-${edgeAlias}`;
|
|
56
|
+
/** @param {string} edgeAlias */
|
|
57
|
+
export const edgeLabel = (edgeAlias) => `local.${edgeLinkName(edgeAlias)}`;
|
|
58
|
+
|
|
59
|
+
/** @param {string} label */
|
|
60
|
+
export const plistFileName = (label) => `${label}.plist`;
|
|
61
|
+
|
|
62
|
+
// ---- 三种 LaunchAgent plist ----
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* edge link job:PathState on 期间常驻,不写 RunAtLoad。
|
|
66
|
+
* @param {{binDir:string, coreAlias:string, selfAlias:string,
|
|
67
|
+
* forwardArgs:readonly string[], onFile:string, logsDir:string}} opts
|
|
68
|
+
*/
|
|
69
|
+
export function renderEdgeLinkPlist(opts) {
|
|
70
|
+
const { binDir, coreAlias, selfAlias, forwardArgs, onFile, logsDir } = opts;
|
|
71
|
+
const label = linkLabel(coreAlias);
|
|
72
|
+
const argv = [`${binDir}/${linkLinkName(coreAlias)}`, selfAlias, coreAlias, ...forwardArgs];
|
|
73
|
+
return `${XML_HEAD} <key>Label</key>
|
|
74
|
+
<string>${label}</string>
|
|
75
|
+
${programArguments(argv)} <key>ProcessType</key>
|
|
76
|
+
<string>Background</string>
|
|
77
|
+
<key>KeepAlive</key>
|
|
78
|
+
<dict>
|
|
79
|
+
<key>PathState</key>
|
|
80
|
+
<dict>
|
|
81
|
+
<key>${xmlEscape(onFile)}</key>
|
|
82
|
+
<true/>
|
|
83
|
+
</dict>
|
|
84
|
+
</dict>
|
|
85
|
+
<key>ThrottleInterval</key>
|
|
86
|
+
<integer>${THROTTLE}</integer>
|
|
87
|
+
${logPaths({ label, logsDir })}${XML_TAIL}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* core 常驻 uplink-relay:装完即启、无条件 KeepAlive。
|
|
92
|
+
* @param {{binDir:string, relayAlias:string, relayPort:number, logsDir:string}} opts
|
|
93
|
+
*/
|
|
94
|
+
export function renderRelayPlist(opts) {
|
|
95
|
+
const { binDir, relayAlias, relayPort, logsDir } = opts;
|
|
96
|
+
const label = relayLabel(relayAlias);
|
|
97
|
+
const argv = [`${binDir}/${relayLinkName(relayAlias)}`, String(relayPort), relayAlias];
|
|
98
|
+
return `${XML_HEAD} <key>Label</key>
|
|
99
|
+
<string>${label}</string>
|
|
100
|
+
${programArguments(argv)} <key>ProcessType</key>
|
|
101
|
+
<string>Background</string>
|
|
102
|
+
<key>RunAtLoad</key>
|
|
103
|
+
<true/>
|
|
104
|
+
<key>KeepAlive</key>
|
|
105
|
+
<true/>
|
|
106
|
+
<key>ThrottleInterval</key>
|
|
107
|
+
<integer>${THROTTLE}</integer>
|
|
108
|
+
${logPaths({ label, logsDir })}${XML_TAIL}`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* core 回拨 edge:失败计数与休眠在脚本里,launchd 只在非自愿退出时重拉。
|
|
113
|
+
* 无 RunAtLoad;6 连败由脚本 disable + exit 0。
|
|
114
|
+
* @param {{binDir:string, edgeAlias:string, user:string, logsDir:string}} opts
|
|
115
|
+
*/
|
|
116
|
+
export function renderUplinkEdgePlist(opts) {
|
|
117
|
+
const { binDir, edgeAlias, user, logsDir } = opts;
|
|
118
|
+
const label = edgeLabel(edgeAlias);
|
|
119
|
+
const argv = [`${binDir}/${edgeLinkName(edgeAlias)}`, edgeAlias, user];
|
|
120
|
+
return `${XML_HEAD} <key>Label</key>
|
|
121
|
+
<string>${label}</string>
|
|
122
|
+
${programArguments(argv)} <key>ProcessType</key>
|
|
123
|
+
<string>Background</string>
|
|
124
|
+
<key>KeepAlive</key>
|
|
125
|
+
<dict>
|
|
126
|
+
<key>SuccessfulExit</key>
|
|
127
|
+
<false/>
|
|
128
|
+
</dict>
|
|
129
|
+
<key>ThrottleInterval</key>
|
|
130
|
+
<integer>${THROTTLE}</integer>
|
|
131
|
+
${logPaths({ label, logsDir })}${XML_TAIL}`;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// ---- node 的 systemd unit(与 relay plist 同构,Restart=always)----
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* @param {{binDir:string, relayAlias:string, relayPort:number, home:string}} opts
|
|
138
|
+
* @returns {string}
|
|
139
|
+
*/
|
|
140
|
+
export function renderRelayUnit(opts) {
|
|
141
|
+
const { binDir, relayAlias, relayPort, home } = opts;
|
|
142
|
+
const execStart = `${binDir}/${relayLinkName(relayAlias)} ${relayPort} ${relayAlias}`;
|
|
143
|
+
return `[Unit]
|
|
144
|
+
Description=ssh-net uplink relay (${relayAlias})
|
|
145
|
+
StartLimitIntervalSec=0
|
|
146
|
+
|
|
147
|
+
[Service]
|
|
148
|
+
Type=simple
|
|
149
|
+
Environment="HOME=${home}"
|
|
150
|
+
ExecStart=${execStart}
|
|
151
|
+
Restart=always
|
|
152
|
+
RestartSec=${THROTTLE}
|
|
153
|
+
|
|
154
|
+
[Install]
|
|
155
|
+
WantedBy=multi-user.target
|
|
156
|
+
`;
|
|
157
|
+
}
|