mihomo-cli 3.8.1 → 3.9.1
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 +43 -0
- package/README.md +28 -24
- package/dist/index.js +596 -516
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -17,9 +17,9 @@ var colors = {
|
|
|
17
17
|
|
|
18
18
|
// src/config.ts
|
|
19
19
|
import { spawnSync } from "child_process";
|
|
20
|
-
import
|
|
20
|
+
import fs5 from "fs";
|
|
21
21
|
|
|
22
|
-
// node_modules/js-yaml/dist/js-yaml.mjs
|
|
22
|
+
// ../../../node_modules/js-yaml/dist/js-yaml.mjs
|
|
23
23
|
var NOT_RESOLVED = /* @__PURE__ */ Symbol("NOT_RESOLVED");
|
|
24
24
|
function defineScalarTag(tagName, options) {
|
|
25
25
|
return {
|
|
@@ -3183,10 +3183,10 @@ var DIRS = {
|
|
|
3183
3183
|
logs: path.join(USER_DATA_DIR, "logs"),
|
|
3184
3184
|
data: path.join(USER_DATA_DIR, "data"),
|
|
3185
3185
|
runtime: path.join(USER_DATA_DIR, "runtime"),
|
|
3186
|
-
// 隧道运行态。刻意独立于 runtime/:clearRuntime() 会在 stop() 成功路径 rmrf 整个
|
|
3186
|
+
// ssh 隧道运行态。刻意独立于 runtime/:clearRuntime() 会在 stop() 成功路径 rmrf 整个
|
|
3187
3187
|
// runtime 目录,隧道状态放那里会被 `mihomo stop` 连同 config.yaml 一起抹掉,
|
|
3188
3188
|
// 于是「谁起的」标记丢失、手动起的隧道再也无法被识别
|
|
3189
|
-
|
|
3189
|
+
ssh: path.join(USER_DATA_DIR, "ssh")
|
|
3190
3190
|
};
|
|
3191
3191
|
var PATHS = {
|
|
3192
3192
|
mihomoBinary: path.join(DIRS.kernel, "mihomo"),
|
|
@@ -3198,6 +3198,9 @@ var PATHS = {
|
|
|
3198
3198
|
configStage1Subscription: path.join(DIRS.runtime, "1.subscription.yaml"),
|
|
3199
3199
|
configStage2Overwrite: path.join(DIRS.runtime, "2.overwrite.yaml"),
|
|
3200
3200
|
configStage3System: path.join(DIRS.runtime, "3.system.yaml"),
|
|
3201
|
+
// ssh 单列一个 stage:它不受 overwrite 开关约束,混进 2.overwrite.yaml 会让
|
|
3202
|
+
// `ow off` 时的调试输出自相矛盾(覆写已禁用,文件里却有内容)
|
|
3203
|
+
configStage4Ssh: path.join(DIRS.runtime, "4.ssh.yaml"),
|
|
3201
3204
|
// launchd LaunchDaemon plist 位于系统级 /Library/LaunchDaemons/,root:wheel 拥有,与 homedir / MIHOMO_CLI_DIR 无关
|
|
3202
3205
|
launchDaemonPlist: path.join("/Library/LaunchDaemons", `${LAUNCH_DAEMON_LABEL}.plist`)
|
|
3203
3206
|
};
|
|
@@ -3432,6 +3435,22 @@ function getSubscriptionsWithCache() {
|
|
|
3432
3435
|
}));
|
|
3433
3436
|
}
|
|
3434
3437
|
var SAFE_NAME_RE = /^[\w\-\p{Unified_Ideograph}]{1,64}$/u;
|
|
3438
|
+
function getSshTunnels() {
|
|
3439
|
+
const settings = readSettings();
|
|
3440
|
+
const tunnels = settings.ssh;
|
|
3441
|
+
if (!Array.isArray(tunnels)) {
|
|
3442
|
+
if (tunnels !== void 0) {
|
|
3443
|
+
console.warn("\u8B66\u544A: settings.json \u7684 ssh \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08\u53EF\u7528 mihomo ssh add \u91CD\u65B0\u6DFB\u52A0\uFF09");
|
|
3444
|
+
}
|
|
3445
|
+
return [];
|
|
3446
|
+
}
|
|
3447
|
+
return tunnels.filter((t) => t != null && typeof t === "object" && typeof t.name === "string" && typeof t.host === "string" && Number.isInteger(t.port));
|
|
3448
|
+
}
|
|
3449
|
+
function validateSshName(name) {
|
|
3450
|
+
if (!name || !SAFE_NAME_RE.test(name)) {
|
|
3451
|
+
throw new CliError(`\u96A7\u9053\u540D\u79F0\u65E0\u6548: "${name}"\uFF0C\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\u548C\u4E2D\u6587\uFF08\u6700\u957F 64 \u5B57\u7B26\uFF09`);
|
|
3452
|
+
}
|
|
3453
|
+
}
|
|
3435
3454
|
function validateSubscriptionName(name) {
|
|
3436
3455
|
if (!name || !SAFE_NAME_RE.test(name)) {
|
|
3437
3456
|
throw new CliError(`\u8BA2\u9605\u540D\u79F0\u65E0\u6548: "${name}"\uFF0C\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\u548C\u4E2D\u6587\uFF08\u6700\u957F 64 \u5B57\u7B26\uFF09`);
|
|
@@ -3767,6 +3786,103 @@ function listOverwriteFile() {
|
|
|
3767
3786
|
};
|
|
3768
3787
|
}
|
|
3769
3788
|
|
|
3789
|
+
// src/ssh-config.ts
|
|
3790
|
+
import fs4 from "fs";
|
|
3791
|
+
import path4 from "path";
|
|
3792
|
+
var SSH_FILENAME_RE = /^ssh\.(.+)\.ya?ml$/;
|
|
3793
|
+
function isSshFilename(filename) {
|
|
3794
|
+
return SSH_FILENAME_RE.test(filename);
|
|
3795
|
+
}
|
|
3796
|
+
function getSshConfigPath(name) {
|
|
3797
|
+
validateSshName(name);
|
|
3798
|
+
return path4.join(USER_DATA_DIR, `ssh.${name}.yaml`);
|
|
3799
|
+
}
|
|
3800
|
+
function capitalize(name) {
|
|
3801
|
+
return name.charAt(0).toUpperCase() + name.slice(1);
|
|
3802
|
+
}
|
|
3803
|
+
function getSshProxyName(name) {
|
|
3804
|
+
return `SSH-${capitalize(name)}-Host`;
|
|
3805
|
+
}
|
|
3806
|
+
function getSshGroupName(name) {
|
|
3807
|
+
return `SSH-${capitalize(name)}`;
|
|
3808
|
+
}
|
|
3809
|
+
function renderSshProxy(tunnel) {
|
|
3810
|
+
return {
|
|
3811
|
+
name: getSshProxyName(tunnel.name),
|
|
3812
|
+
type: "socks5",
|
|
3813
|
+
server: "127.0.0.1",
|
|
3814
|
+
port: tunnel.port
|
|
3815
|
+
};
|
|
3816
|
+
}
|
|
3817
|
+
function collectSshProxyNames(tunnels) {
|
|
3818
|
+
return tunnels.map((t) => getSshProxyName(t.name));
|
|
3819
|
+
}
|
|
3820
|
+
function loadSshConfigFiles() {
|
|
3821
|
+
if (!fs4.existsSync(USER_DATA_DIR)) return [];
|
|
3822
|
+
const files = fs4.readdirSync(USER_DATA_DIR).filter(isSshFilename).sort();
|
|
3823
|
+
const results = [];
|
|
3824
|
+
for (const file of files) {
|
|
3825
|
+
const filePath = path4.join(USER_DATA_DIR, file);
|
|
3826
|
+
try {
|
|
3827
|
+
const parsed = load(fs4.readFileSync(filePath, "utf8"), { maxAliases: 200 });
|
|
3828
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
3829
|
+
if ("match" in parsed) {
|
|
3830
|
+
console.warn(`\u8B66\u544A: ssh \u914D\u7F6E "${file}" \u7684 match \u5757\u4E0D\u751F\u6548\uFF08ssh \u96A7\u9053\u6052\u5168\u5C40\uFF09\uFF0C\u5DF2\u5FFD\u7565`);
|
|
3831
|
+
delete parsed.match;
|
|
3832
|
+
}
|
|
3833
|
+
results.push({ name: file, path: filePath, config: parsed });
|
|
3834
|
+
} else if (parsed !== null) {
|
|
3835
|
+
console.warn(`\u8B66\u544A: ssh \u914D\u7F6E "${file}" \u9876\u5C42\u5FC5\u987B\u662F\u5BF9\u8C61\uFF0C\u5DF2\u8DF3\u8FC7`);
|
|
3836
|
+
}
|
|
3837
|
+
} catch (e) {
|
|
3838
|
+
console.warn(`\u8B66\u544A: ssh \u914D\u7F6E "${file}" \u89E3\u6790\u5931\u8D25: ${e.message}`);
|
|
3839
|
+
}
|
|
3840
|
+
}
|
|
3841
|
+
return results;
|
|
3842
|
+
}
|
|
3843
|
+
function applySshConfig(baseConfig, sshFiles, tunnels) {
|
|
3844
|
+
let result = { ...baseConfig };
|
|
3845
|
+
for (const file of sshFiles) {
|
|
3846
|
+
result = deepMergeWithOverrides(result, file.config);
|
|
3847
|
+
}
|
|
3848
|
+
if (tunnels.length > 0) {
|
|
3849
|
+
result = deepMergeWithOverrides(result, { "~proxies": tunnels.map(renderSshProxy) });
|
|
3850
|
+
}
|
|
3851
|
+
return result;
|
|
3852
|
+
}
|
|
3853
|
+
function renderSshConfigTemplate(tunnel) {
|
|
3854
|
+
const proxyName = getSshProxyName(tunnel.name);
|
|
3855
|
+
const groupName = getSshGroupName(tunnel.name);
|
|
3856
|
+
return `# mihomo-cli ssh \u96A7\u9053\u914D\u7F6E\uFF08ssh: ${tunnel.name}\uFF09
|
|
3857
|
+
# \u672C\u6587\u4EF6\u7531 mihomo-cli \u9996\u6B21\u521B\u5EFA\uFF0C\u4E4B\u540E\u5B8C\u5168\u7531\u4F60\u7EF4\u62A4\u2014\u2014CLI \u4E0D\u4F1A\u518D\u6539\u5199\u6216\u5220\u9664\u5B83\u3002
|
|
3858
|
+
#
|
|
3859
|
+
# \u8282\u70B9 ${proxyName} \u7531 CLI \u4F9D\u636E settings \u91CC\u7684 host/port \u81EA\u52A8\u6CE8\u5165\uFF0C
|
|
3860
|
+
# \u65E0\u9700\u4E5F\u4E0D\u8981\u5728\u6B64\u58F0\u660E\uFF1A\u7AEF\u53E3\u4EE5 \`mihomo ssh\` \u663E\u793A\u7684\u4E3A\u51C6\uFF0C\u6539\u7AEF\u53E3\u7528 \`mihomo ssh add\`\u3002
|
|
3861
|
+
#
|
|
3862
|
+
# \u672C\u6587\u4EF6\u4E0D\u53D7 \`mihomo ow off\` \u5F71\u54CD\uFF08ssh \u5206\u6D41\u662F\u521A\u9700\uFF0C\u8986\u5199\u662F\u53EF\u9009\u8C03\u4F18\uFF09\u3002
|
|
3863
|
+
# ~ \u662F\u300C\u6309 name \u5C31\u5730\u5408\u5E76\u300D\u8BED\u4E49\uFF0C\u4E0D\u4F9D\u8D56\u6587\u4EF6\u52A0\u8F7D\u987A\u5E8F\u3002
|
|
3864
|
+
|
|
3865
|
+
~proxy-groups:
|
|
3866
|
+
- name: ${groupName}
|
|
3867
|
+
type: select
|
|
3868
|
+
proxies:
|
|
3869
|
+
- ${proxyName}
|
|
3870
|
+
- DIRECT
|
|
3871
|
+
|
|
3872
|
+
# \u53D6\u6D88\u6CE8\u91CA\u5E76\u586B\u5165\u9700\u8981\u8D70\u96A7\u9053\u7684\u5185\u7F51\u57DF\u540D/\u7F51\u6BB5\uFF08CLI \u65E0\u4ECE\u77E5\u9053\u4F60\u7684\u5185\u7F51\u5730\u5740\uFF09\uFF1A
|
|
3873
|
+
# +rules:
|
|
3874
|
+
# - DOMAIN-SUFFIX,example.internal,${groupName}
|
|
3875
|
+
# - IP-CIDR,10.0.0.0/8,${groupName}
|
|
3876
|
+
`;
|
|
3877
|
+
}
|
|
3878
|
+
function ensureSshConfigFile(tunnel) {
|
|
3879
|
+
const filePath = getSshConfigPath(tunnel.name);
|
|
3880
|
+
if (fs4.existsSync(filePath)) return false;
|
|
3881
|
+
fs4.mkdirSync(USER_DATA_DIR, { recursive: true, mode: 448 });
|
|
3882
|
+
fs4.writeFileSync(filePath, renderSshConfigTemplate(tunnel), { mode: 384 });
|
|
3883
|
+
return true;
|
|
3884
|
+
}
|
|
3885
|
+
|
|
3770
3886
|
// src/utils.ts
|
|
3771
3887
|
var sleepBuf = new Int32Array(new SharedArrayBuffer(4));
|
|
3772
3888
|
function sleepSync(ms) {
|
|
@@ -3875,7 +3991,7 @@ var VALUE_FLAGS = /* @__PURE__ */ new Set([
|
|
|
3875
3991
|
]);
|
|
3876
3992
|
function extractStartOptions(args) {
|
|
3877
3993
|
if (!args) return [];
|
|
3878
|
-
const BOOL_FLAGS = /* @__PURE__ */ new Set(["-s", "--no-update", "--no-clean", "--no-
|
|
3994
|
+
const BOOL_FLAGS = /* @__PURE__ */ new Set(["-s", "--no-update", "--no-clean", "--no-ssh"]);
|
|
3879
3995
|
const out = [];
|
|
3880
3996
|
for (let i = 0; i < args.length; i++) {
|
|
3881
3997
|
const a = args[i];
|
|
@@ -4021,8 +4137,8 @@ function collectOverwriteProxyNames(overwriteFiles) {
|
|
|
4021
4137
|
}
|
|
4022
4138
|
return names;
|
|
4023
4139
|
}
|
|
4024
|
-
function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles) {
|
|
4025
|
-
const injectedNames = collectOverwriteProxyNames(overwriteFiles);
|
|
4140
|
+
function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles, extraNames = []) {
|
|
4141
|
+
const injectedNames = [...collectOverwriteProxyNames(overwriteFiles), ...extraNames];
|
|
4026
4142
|
if (injectedNames.length === 0) return;
|
|
4027
4143
|
const groups = config["proxy-groups"];
|
|
4028
4144
|
if (!groups) return;
|
|
@@ -4206,31 +4322,35 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4206
4322
|
const allFiles = overwriteEnabled ? loadOverwriteFile() : [];
|
|
4207
4323
|
const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
|
|
4208
4324
|
const withOverwrites = applyOverwrite(subscriptionConfig, overwriteFiles);
|
|
4209
|
-
|
|
4210
|
-
|
|
4325
|
+
const sshTunnels = getSshTunnels();
|
|
4326
|
+
const sshFiles = sshTunnels.length > 0 ? loadSshConfigFiles() : [];
|
|
4327
|
+
const withSsh = applySshConfig(withOverwrites, sshFiles, sshTunnels);
|
|
4328
|
+
const sshProxyNames = collectSshProxyNames(sshTunnels);
|
|
4329
|
+
if (overwriteFiles.length > 0 || sshProxyNames.length > 0) {
|
|
4330
|
+
excludeOverwriteProxiesFromIncludeAll(withSsh, overwriteFiles, sshProxyNames);
|
|
4211
4331
|
}
|
|
4212
4332
|
const systemConfig = {};
|
|
4213
4333
|
for (const [key, value] of Object.entries(BASE_CONFIG)) {
|
|
4214
|
-
if (!(key in
|
|
4334
|
+
if (!(key in withSsh)) {
|
|
4215
4335
|
systemConfig[key] = value;
|
|
4216
4336
|
}
|
|
4217
4337
|
}
|
|
4218
4338
|
systemConfig["external-controller"] = BASE_CONFIG["external-controller"];
|
|
4219
4339
|
systemConfig["mixed-port"] = BASE_CONFIG["mixed-port"];
|
|
4220
|
-
delete
|
|
4221
|
-
delete
|
|
4222
|
-
delete
|
|
4223
|
-
delete
|
|
4224
|
-
delete
|
|
4225
|
-
delete
|
|
4226
|
-
delete
|
|
4340
|
+
delete withSsh["mixed-port"];
|
|
4341
|
+
delete withSsh.port;
|
|
4342
|
+
delete withSsh["socks-port"];
|
|
4343
|
+
delete withSsh["external-ui"];
|
|
4344
|
+
delete withSsh["external-ui-name"];
|
|
4345
|
+
delete withSsh["external-ui-url"];
|
|
4346
|
+
delete withSsh.secret;
|
|
4227
4347
|
const controllerSecret = readSettings().controller_secret;
|
|
4228
4348
|
if (controllerSecret) {
|
|
4229
4349
|
systemConfig.secret = controllerSecret;
|
|
4230
4350
|
}
|
|
4231
4351
|
if (mode === "tun") {
|
|
4232
4352
|
systemConfig.tun = TUN_CONFIG.tun;
|
|
4233
|
-
const subDns =
|
|
4353
|
+
const subDns = withSsh.dns || {};
|
|
4234
4354
|
const dns = {};
|
|
4235
4355
|
if (!("enable" in subDns)) dns.enable = true;
|
|
4236
4356
|
if (!("enhanced-mode" in subDns)) dns["enhanced-mode"] = "fake-ip";
|
|
@@ -4239,14 +4359,14 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4239
4359
|
systemConfig.dns = dns;
|
|
4240
4360
|
}
|
|
4241
4361
|
} else {
|
|
4242
|
-
delete
|
|
4362
|
+
delete withSsh.tun;
|
|
4243
4363
|
}
|
|
4244
|
-
const merged = { ...
|
|
4364
|
+
const merged = { ...withSsh, ...systemConfig };
|
|
4245
4365
|
if (systemConfig.dns) {
|
|
4246
|
-
merged.dns = { ...
|
|
4366
|
+
merged.dns = { ...withSsh.dns || {}, ...systemConfig.dns };
|
|
4247
4367
|
}
|
|
4248
4368
|
const mergedDns = merged.dns || {};
|
|
4249
|
-
if (mergedDns["enhanced-mode"] === "fake-ip" && !("sniffer" in
|
|
4369
|
+
if (mergedDns["enhanced-mode"] === "fake-ip" && !("sniffer" in withSsh)) {
|
|
4250
4370
|
merged.sniffer = {
|
|
4251
4371
|
enable: true,
|
|
4252
4372
|
sniff: {
|
|
@@ -4258,7 +4378,7 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4258
4378
|
};
|
|
4259
4379
|
}
|
|
4260
4380
|
const warnings = validateConfig(merged);
|
|
4261
|
-
return { config: merged, subscriptionConfig, overwriteFiles, systemConfig, warnings };
|
|
4381
|
+
return { config: merged, subscriptionConfig, overwriteFiles, sshFiles, systemConfig, warnings };
|
|
4262
4382
|
}
|
|
4263
4383
|
function writeMihomoConfig(configObj) {
|
|
4264
4384
|
ensureDirs();
|
|
@@ -4267,22 +4387,32 @@ function writeMihomoConfig(configObj) {
|
|
|
4267
4387
|
}
|
|
4268
4388
|
function writeDebugConfig(buildResult) {
|
|
4269
4389
|
ensureDirs();
|
|
4270
|
-
|
|
4390
|
+
fs5.writeFileSync(PATHS.configStage1Subscription, dumpYaml(buildResult.subscriptionConfig), { mode: 384 });
|
|
4271
4391
|
const overwriteMerged = {};
|
|
4272
4392
|
for (const f of buildResult.overwriteFiles) {
|
|
4273
4393
|
Object.assign(overwriteMerged, f.config);
|
|
4274
4394
|
}
|
|
4275
4395
|
const overwriteContent = buildResult.overwriteFiles.length > 0 ? dumpYaml(overwriteMerged) : "# overwrite \u5DF2\u7981\u7528\u6216\u65E0\u8986\u5199\u6587\u4EF6\n";
|
|
4276
|
-
|
|
4277
|
-
|
|
4396
|
+
fs5.writeFileSync(PATHS.configStage2Overwrite, overwriteContent, { mode: 384 });
|
|
4397
|
+
fs5.writeFileSync(PATHS.configStage3System, dumpYaml(buildResult.systemConfig), { mode: 384 });
|
|
4398
|
+
const sshMerged = {};
|
|
4399
|
+
for (const f of buildResult.sshFiles) {
|
|
4400
|
+
Object.assign(sshMerged, f.config);
|
|
4401
|
+
}
|
|
4402
|
+
const sshTunnels = getSshTunnels();
|
|
4403
|
+
if (sshTunnels.length > 0) {
|
|
4404
|
+
sshMerged["~proxies"] = sshTunnels.map(renderSshProxy);
|
|
4405
|
+
}
|
|
4406
|
+
const sshContent = Object.keys(sshMerged).length > 0 ? dumpYaml(sshMerged) : "# \u672A\u914D\u7F6E ssh \u96A7\u9053\n";
|
|
4407
|
+
fs5.writeFileSync(PATHS.configStage4Ssh, sshContent, { mode: 384 });
|
|
4278
4408
|
}
|
|
4279
4409
|
function hasConfig() {
|
|
4280
|
-
return
|
|
4410
|
+
return fs5.existsSync(PATHS.configFile);
|
|
4281
4411
|
}
|
|
4282
4412
|
function getConfigInfo() {
|
|
4283
4413
|
if (!hasConfig()) return null;
|
|
4284
4414
|
try {
|
|
4285
|
-
const content =
|
|
4415
|
+
const content = fs5.readFileSync(PATHS.configFile, "utf8");
|
|
4286
4416
|
const cfg = loadYamlSafe(content);
|
|
4287
4417
|
if (!cfg) return null;
|
|
4288
4418
|
const proxies = cfg.proxies;
|
|
@@ -4302,7 +4432,7 @@ function getConfigInfo() {
|
|
|
4302
4432
|
}
|
|
4303
4433
|
}
|
|
4304
4434
|
function hasKernel() {
|
|
4305
|
-
return
|
|
4435
|
+
return fs5.existsSync(PATHS.mihomoBinary);
|
|
4306
4436
|
}
|
|
4307
4437
|
var kernelVersionCache = null;
|
|
4308
4438
|
var kernelVersionCached = false;
|
|
@@ -4378,13 +4508,13 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\
|
|
|
4378
4508
|
" mihomo start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
|
|
4379
4509
|
" mihomo start -u 30000 # \u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 30 \u79D2 (\u9ED8\u8BA4 10s)",
|
|
4380
4510
|
" mihomo daemon on # \u5F00\u542F\u4FDD\u6D3B\uFF08\u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F\uFF09",
|
|
4381
|
-
" mihomo
|
|
4511
|
+
" mihomo ssh add work --host m4 --port 1080 # \u52A0 ssh \u96A7\u9053\u51FA\u53E3",
|
|
4382
4512
|
" mihomo sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
|
|
4383
4513
|
" mihomo ui # \u6253\u5F00 Web UI",
|
|
4384
4514
|
"",
|
|
4385
4515
|
`${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
|
|
4386
4516
|
" tun = start tun use = sub use on/off = ow on/off open = dir open",
|
|
4387
|
-
" up = start down = stop upd/upgrade = update
|
|
4517
|
+
" up = start down = stop upd/upgrade = update",
|
|
4388
4518
|
"",
|
|
4389
4519
|
`${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
|
|
4390
4520
|
" mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)",
|
|
@@ -4410,13 +4540,13 @@ function printVersion() {
|
|
|
4410
4540
|
|
|
4411
4541
|
// src/daemon.ts
|
|
4412
4542
|
import { spawnSync as spawnSync3 } from "child_process";
|
|
4413
|
-
import
|
|
4414
|
-
import
|
|
4543
|
+
import fs7 from "fs";
|
|
4544
|
+
import path6 from "path";
|
|
4415
4545
|
|
|
4416
4546
|
// src/process.ts
|
|
4417
4547
|
import { spawn, spawnSync as spawnSync2 } from "child_process";
|
|
4418
|
-
import
|
|
4419
|
-
import
|
|
4548
|
+
import fs6 from "fs";
|
|
4549
|
+
import path5 from "path";
|
|
4420
4550
|
|
|
4421
4551
|
// src/lifecycle.ts
|
|
4422
4552
|
var cleanupFns = /* @__PURE__ */ new Set();
|
|
@@ -4481,15 +4611,15 @@ function isProcessRoot(pid) {
|
|
|
4481
4611
|
}
|
|
4482
4612
|
var MAIN_INSTANCE_PATTERN = `${escapeRegExp(PATHS.mihomoBinary)}.*${escapeRegExp(PATHS.configFile)}`;
|
|
4483
4613
|
function clearRuntime() {
|
|
4484
|
-
if (
|
|
4614
|
+
if (fs6.existsSync(DIRS.runtime)) {
|
|
4485
4615
|
rmrf(DIRS.runtime);
|
|
4486
4616
|
}
|
|
4487
4617
|
ensureDirs();
|
|
4488
4618
|
}
|
|
4489
4619
|
function getPid() {
|
|
4490
|
-
if (!
|
|
4620
|
+
if (!fs6.existsSync(PATHS.pidFile)) return null;
|
|
4491
4621
|
try {
|
|
4492
|
-
const pid = parseInt(
|
|
4622
|
+
const pid = parseInt(fs6.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
|
|
4493
4623
|
return pid > 0 ? pid : null;
|
|
4494
4624
|
} catch {
|
|
4495
4625
|
return null;
|
|
@@ -4511,9 +4641,9 @@ function getMihomoPids() {
|
|
|
4511
4641
|
}
|
|
4512
4642
|
}
|
|
4513
4643
|
function isPidFileOwnedByRoot() {
|
|
4514
|
-
if (!
|
|
4644
|
+
if (!fs6.existsSync(PATHS.pidFile)) return false;
|
|
4515
4645
|
try {
|
|
4516
|
-
const stat =
|
|
4646
|
+
const stat = fs6.statSync(PATHS.pidFile);
|
|
4517
4647
|
return stat.uid === 0;
|
|
4518
4648
|
} catch {
|
|
4519
4649
|
return false;
|
|
@@ -4536,10 +4666,10 @@ function hasRootResidue() {
|
|
|
4536
4666
|
}
|
|
4537
4667
|
function savePid(pid) {
|
|
4538
4668
|
ensureDirs();
|
|
4539
|
-
|
|
4669
|
+
fs6.writeFileSync(PATHS.pidFile, pid.toString(), { mode: 384 });
|
|
4540
4670
|
}
|
|
4541
4671
|
function clearPid() {
|
|
4542
|
-
if (!
|
|
4672
|
+
if (!fs6.existsSync(PATHS.pidFile)) return;
|
|
4543
4673
|
if (isPidFileOwnedByRoot()) {
|
|
4544
4674
|
try {
|
|
4545
4675
|
spawnSync2("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
|
|
@@ -4547,7 +4677,7 @@ function clearPid() {
|
|
|
4547
4677
|
}
|
|
4548
4678
|
} else {
|
|
4549
4679
|
try {
|
|
4550
|
-
|
|
4680
|
+
fs6.unlinkSync(PATHS.pidFile);
|
|
4551
4681
|
} catch {
|
|
4552
4682
|
}
|
|
4553
4683
|
}
|
|
@@ -4661,9 +4791,9 @@ echo "--- \u65E5\u5FD7 ---"
|
|
|
4661
4791
|
tail -25 "\${LOG_FILE}" 2>/dev/null
|
|
4662
4792
|
exit 2
|
|
4663
4793
|
`;
|
|
4664
|
-
const scriptPath =
|
|
4665
|
-
|
|
4666
|
-
|
|
4794
|
+
const scriptPath = path5.join(DIRS.runtime, "launch-tun.sh");
|
|
4795
|
+
fs6.writeFileSync(scriptPath, scriptContent, { mode: 448 });
|
|
4796
|
+
fs6.chmodSync(scriptPath, 448);
|
|
4667
4797
|
return scriptPath;
|
|
4668
4798
|
}
|
|
4669
4799
|
function getProcessInfo(pid) {
|
|
@@ -4701,11 +4831,11 @@ async function start(mode = "mixed") {
|
|
|
4701
4831
|
ensureDirs();
|
|
4702
4832
|
rotateAndCleanupLogs();
|
|
4703
4833
|
const binary = PATHS.mihomoBinary;
|
|
4704
|
-
if (!
|
|
4834
|
+
if (!fs6.existsSync(binary)) {
|
|
4705
4835
|
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
|
|
4706
4836
|
}
|
|
4707
4837
|
const configFile = PATHS.configFile;
|
|
4708
|
-
if (!
|
|
4838
|
+
if (!fs6.existsSync(configFile)) {
|
|
4709
4839
|
throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
|
|
4710
4840
|
}
|
|
4711
4841
|
const staleState = checkStaleState();
|
|
@@ -4734,24 +4864,24 @@ async function startMixedMode(staleState) {
|
|
|
4734
4864
|
const configFile = PATHS.configFile;
|
|
4735
4865
|
const logFile = PATHS.logFile;
|
|
4736
4866
|
const args = ["-d", DIRS.data, "-f", configFile];
|
|
4737
|
-
if (
|
|
4867
|
+
if (fs6.existsSync(logFile)) {
|
|
4738
4868
|
try {
|
|
4739
|
-
|
|
4869
|
+
fs6.accessSync(logFile, fs6.constants.W_OK);
|
|
4740
4870
|
} catch {
|
|
4741
4871
|
try {
|
|
4742
|
-
|
|
4872
|
+
fs6.unlinkSync(logFile);
|
|
4743
4873
|
} catch {
|
|
4744
4874
|
}
|
|
4745
4875
|
}
|
|
4746
4876
|
}
|
|
4747
|
-
const logFd =
|
|
4877
|
+
const logFd = fs6.openSync(logFile, "a");
|
|
4748
4878
|
const child = spawn(PATHS.mihomoBinary, args, {
|
|
4749
4879
|
detached: true,
|
|
4750
4880
|
stdio: ["ignore", logFd, logFd]
|
|
4751
4881
|
});
|
|
4752
4882
|
child.on("error", () => {
|
|
4753
4883
|
});
|
|
4754
|
-
|
|
4884
|
+
fs6.closeSync(logFd);
|
|
4755
4885
|
child.unref();
|
|
4756
4886
|
const pid = child.pid;
|
|
4757
4887
|
if (!pid) {
|
|
@@ -4763,9 +4893,9 @@ async function startMixedMode(staleState) {
|
|
|
4763
4893
|
if (!isRunning()) {
|
|
4764
4894
|
clearPid();
|
|
4765
4895
|
let errorMsg = "\u542F\u52A8\u5931\u8D25";
|
|
4766
|
-
if (
|
|
4896
|
+
if (fs6.existsSync(logFile)) {
|
|
4767
4897
|
try {
|
|
4768
|
-
const logs =
|
|
4898
|
+
const logs = fs6.readFileSync(logFile, "utf8").slice(-3e3);
|
|
4769
4899
|
if (logs.trim()) {
|
|
4770
4900
|
errorMsg += "\n\u6700\u8FD1\u7684\u65E5\u5FD7:\n" + logs.split("\n").map((l) => ` ${l}`).join("\n");
|
|
4771
4901
|
}
|
|
@@ -4792,7 +4922,7 @@ async function startTunMode(staleState) {
|
|
|
4792
4922
|
}
|
|
4793
4923
|
} catch (e) {
|
|
4794
4924
|
try {
|
|
4795
|
-
|
|
4925
|
+
fs6.unlinkSync(launchScript);
|
|
4796
4926
|
} catch {
|
|
4797
4927
|
}
|
|
4798
4928
|
if (e.status === 1) {
|
|
@@ -4804,7 +4934,7 @@ async function startTunMode(staleState) {
|
|
|
4804
4934
|
throw new Error(e.message);
|
|
4805
4935
|
}
|
|
4806
4936
|
try {
|
|
4807
|
-
|
|
4937
|
+
fs6.unlinkSync(launchScript);
|
|
4808
4938
|
} catch {
|
|
4809
4939
|
}
|
|
4810
4940
|
await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
|
|
@@ -4843,18 +4973,18 @@ function getLogPath() {
|
|
|
4843
4973
|
}
|
|
4844
4974
|
function rotateLog() {
|
|
4845
4975
|
const logFile = PATHS.logFile;
|
|
4846
|
-
if (!
|
|
4847
|
-
const stat =
|
|
4976
|
+
if (!fs6.existsSync(logFile)) return null;
|
|
4977
|
+
const stat = fs6.statSync(logFile);
|
|
4848
4978
|
if (stat.size === 0) return null;
|
|
4849
4979
|
const rotatedName = `mihomo.${formatLocalTimestamp()}.log`;
|
|
4850
|
-
const rotatedPath =
|
|
4851
|
-
|
|
4980
|
+
const rotatedPath = path5.join(DIRS.logs, rotatedName);
|
|
4981
|
+
fs6.renameSync(logFile, rotatedPath);
|
|
4852
4982
|
return rotatedPath;
|
|
4853
4983
|
}
|
|
4854
4984
|
function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
|
|
4855
4985
|
const logsDir = DIRS.logs;
|
|
4856
|
-
if (!
|
|
4857
|
-
const files =
|
|
4986
|
+
if (!fs6.existsSync(logsDir)) return { deleted: 0, errors: 0 };
|
|
4987
|
+
const files = fs6.readdirSync(logsDir);
|
|
4858
4988
|
const now = Date.now();
|
|
4859
4989
|
const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
|
|
4860
4990
|
let deleted = 0;
|
|
@@ -4862,10 +4992,10 @@ function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
|
|
|
4862
4992
|
for (const file of files) {
|
|
4863
4993
|
if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.log$/)) continue;
|
|
4864
4994
|
try {
|
|
4865
|
-
const filePath =
|
|
4866
|
-
const stat =
|
|
4995
|
+
const filePath = path5.join(logsDir, file);
|
|
4996
|
+
const stat = fs6.statSync(filePath);
|
|
4867
4997
|
if (now - stat.mtimeMs > maxAgeMs) {
|
|
4868
|
-
|
|
4998
|
+
fs6.unlinkSync(filePath);
|
|
4869
4999
|
deleted++;
|
|
4870
5000
|
}
|
|
4871
5001
|
} catch {
|
|
@@ -4877,8 +5007,8 @@ function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
|
|
|
4877
5007
|
function listLogs() {
|
|
4878
5008
|
const logsDir = DIRS.logs;
|
|
4879
5009
|
const result = { current: null, archives: [] };
|
|
4880
|
-
if (
|
|
4881
|
-
const stat =
|
|
5010
|
+
if (fs6.existsSync(PATHS.logFile)) {
|
|
5011
|
+
const stat = fs6.statSync(PATHS.logFile);
|
|
4882
5012
|
result.current = {
|
|
4883
5013
|
name: "mihomo.log (\u5F53\u524D)",
|
|
4884
5014
|
path: PATHS.logFile,
|
|
@@ -4887,14 +5017,14 @@ function listLogs() {
|
|
|
4887
5017
|
isCurrent: true
|
|
4888
5018
|
};
|
|
4889
5019
|
}
|
|
4890
|
-
if (!
|
|
4891
|
-
const files =
|
|
5020
|
+
if (!fs6.existsSync(logsDir)) return result;
|
|
5021
|
+
const files = fs6.readdirSync(logsDir);
|
|
4892
5022
|
for (const file of files) {
|
|
4893
5023
|
const match = file.match(/^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})\.log$/);
|
|
4894
5024
|
if (!match) continue;
|
|
4895
5025
|
try {
|
|
4896
|
-
const filePath =
|
|
4897
|
-
const stat =
|
|
5026
|
+
const filePath = path5.join(logsDir, file);
|
|
5027
|
+
const stat = fs6.statSync(filePath);
|
|
4898
5028
|
result.archives.push({
|
|
4899
5029
|
name: file,
|
|
4900
5030
|
path: filePath,
|
|
@@ -4909,22 +5039,22 @@ function listLogs() {
|
|
|
4909
5039
|
return result;
|
|
4910
5040
|
}
|
|
4911
5041
|
function isPathUnderDir(filePath, baseDir) {
|
|
4912
|
-
const resolvedPath =
|
|
4913
|
-
const resolvedBase =
|
|
4914
|
-
return resolvedPath === resolvedBase || resolvedPath.startsWith(resolvedBase +
|
|
5042
|
+
const resolvedPath = path5.resolve(filePath);
|
|
5043
|
+
const resolvedBase = path5.resolve(baseDir);
|
|
5044
|
+
return resolvedPath === resolvedBase || resolvedPath.startsWith(resolvedBase + path5.sep);
|
|
4915
5045
|
}
|
|
4916
5046
|
function getLogPathByName(name) {
|
|
4917
5047
|
const logsDir = DIRS.logs;
|
|
4918
5048
|
let targetName = name;
|
|
4919
5049
|
if (!name.endsWith(".log")) targetName = `mihomo.${name}.log`;
|
|
4920
5050
|
if (!targetName.startsWith("mihomo.")) targetName = `mihomo.${targetName}`;
|
|
4921
|
-
const filePath =
|
|
4922
|
-
if (
|
|
4923
|
-
if (
|
|
4924
|
-
const files =
|
|
5051
|
+
const filePath = path5.join(logsDir, targetName);
|
|
5052
|
+
if (fs6.existsSync(filePath) && isPathUnderDir(filePath, logsDir)) return filePath;
|
|
5053
|
+
if (fs6.existsSync(logsDir)) {
|
|
5054
|
+
const files = fs6.readdirSync(logsDir);
|
|
4925
5055
|
for (const file of files) {
|
|
4926
5056
|
if (file.includes(name)) {
|
|
4927
|
-
const candidatePath =
|
|
5057
|
+
const candidatePath = path5.join(logsDir, file);
|
|
4928
5058
|
if (isPathUnderDir(candidatePath, logsDir)) return candidatePath;
|
|
4929
5059
|
}
|
|
4930
5060
|
}
|
|
@@ -4991,7 +5121,7 @@ var DAEMON_BOOT_WAIT_MS = 500;
|
|
|
4991
5121
|
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
4992
5122
|
function logOversized() {
|
|
4993
5123
|
try {
|
|
4994
|
-
return
|
|
5124
|
+
return fs7.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
4995
5125
|
} catch {
|
|
4996
5126
|
return false;
|
|
4997
5127
|
}
|
|
@@ -5031,9 +5161,9 @@ function runSudoScript(scriptBody, opts) {
|
|
|
5031
5161
|
throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
|
|
5032
5162
|
}
|
|
5033
5163
|
ensureDirs();
|
|
5034
|
-
const scriptPath =
|
|
5035
|
-
|
|
5036
|
-
|
|
5164
|
+
const scriptPath = path6.join(DIRS.runtime, opts.file);
|
|
5165
|
+
fs7.writeFileSync(scriptPath, scriptBody, { mode: 448 });
|
|
5166
|
+
fs7.chmodSync(scriptPath, 448);
|
|
5037
5167
|
try {
|
|
5038
5168
|
const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
5039
5169
|
if (result.error) throw result.error;
|
|
@@ -5049,13 +5179,13 @@ function runSudoScript(scriptBody, opts) {
|
|
|
5049
5179
|
}
|
|
5050
5180
|
} finally {
|
|
5051
5181
|
try {
|
|
5052
|
-
|
|
5182
|
+
fs7.unlinkSync(scriptPath);
|
|
5053
5183
|
} catch {
|
|
5054
5184
|
}
|
|
5055
5185
|
}
|
|
5056
5186
|
}
|
|
5057
5187
|
function isDaemonEnabled() {
|
|
5058
|
-
return
|
|
5188
|
+
return fs7.existsSync(PATHS.launchDaemonPlist);
|
|
5059
5189
|
}
|
|
5060
5190
|
function getDaemonStatus() {
|
|
5061
5191
|
if (!isDaemonEnabled()) {
|
|
@@ -5069,14 +5199,14 @@ function isDaemonRunning(status) {
|
|
|
5069
5199
|
}
|
|
5070
5200
|
function enableDaemon() {
|
|
5071
5201
|
assertDaemonLabelSafe();
|
|
5072
|
-
if (!
|
|
5202
|
+
if (!fs7.existsSync(PATHS.mihomoBinary)) {
|
|
5073
5203
|
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
|
|
5074
5204
|
}
|
|
5075
|
-
if (!
|
|
5205
|
+
if (!fs7.existsSync(PATHS.configFile)) {
|
|
5076
5206
|
throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
|
|
5077
5207
|
}
|
|
5078
5208
|
ensureDirs();
|
|
5079
|
-
const stagePath =
|
|
5209
|
+
const stagePath = path6.join(DIRS.runtime, "daemon.plist.stage");
|
|
5080
5210
|
atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
|
|
5081
5211
|
const target = shellQuote(SERVICE_TARGET);
|
|
5082
5212
|
const plistDest = shellQuote(PATHS.launchDaemonPlist);
|
|
@@ -5108,7 +5238,7 @@ function enableDaemon() {
|
|
|
5108
5238
|
});
|
|
5109
5239
|
} finally {
|
|
5110
5240
|
try {
|
|
5111
|
-
|
|
5241
|
+
fs7.unlinkSync(stagePath);
|
|
5112
5242
|
} catch {
|
|
5113
5243
|
}
|
|
5114
5244
|
}
|
|
@@ -5169,14 +5299,14 @@ async function tryHotReload() {
|
|
|
5169
5299
|
}
|
|
5170
5300
|
}
|
|
5171
5301
|
async function restartDaemon() {
|
|
5172
|
-
if (!
|
|
5302
|
+
if (!fs7.existsSync(PATHS.launchDaemonPlist)) {
|
|
5173
5303
|
throw new CliError("\u4FDD\u6D3B\u672A\u542F\u7528\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u542F\u7528\u4FDD\u6D3B: mihomo daemon on" });
|
|
5174
5304
|
}
|
|
5175
5305
|
if (!logOversized() && await tryHotReload()) return;
|
|
5176
5306
|
const target = shellQuote(SERVICE_TARGET);
|
|
5177
5307
|
const plistDest = shellQuote(PATHS.launchDaemonPlist);
|
|
5178
5308
|
const logFile = shellQuote(PATHS.logFile);
|
|
5179
|
-
const archiveFile = shellQuote(
|
|
5309
|
+
const archiveFile = shellQuote(path6.join(DIRS.logs, `mihomo.${formatLocalTimestamp()}.log`));
|
|
5180
5310
|
const script = [
|
|
5181
5311
|
"#!/bin/bash",
|
|
5182
5312
|
`if [ -f ${logFile} ] && [ "$(stat -f%z ${logFile} 2>/dev/null || echo 0)" -gt ${LOG_ROTATE_MAX_BYTES} ]; then`,
|
|
@@ -5904,11 +6034,11 @@ function formatTestSummary(summary) {
|
|
|
5904
6034
|
return `\u7ED3\u679C: ${colors.green(`${summary.alive} \u5B58\u6D3B`)} / ${colors.red(`${summary.dead} \u5931\u8D25`)} / ${summary.total} \u603B\u8BA1`;
|
|
5905
6035
|
}
|
|
5906
6036
|
|
|
5907
|
-
// src/
|
|
6037
|
+
// src/ssh.ts
|
|
5908
6038
|
import { spawn as spawn2 } from "child_process";
|
|
5909
|
-
import
|
|
6039
|
+
import fs8 from "fs";
|
|
5910
6040
|
import net from "net";
|
|
5911
|
-
import
|
|
6041
|
+
import path7 from "path";
|
|
5912
6042
|
var PORT_PROBE_TIMEOUT_MS = 300;
|
|
5913
6043
|
var STOP_WAIT_ATTEMPTS = 20;
|
|
5914
6044
|
var STOP_WAIT_INTERVAL = 100;
|
|
@@ -5925,15 +6055,10 @@ function getReservedPorts() {
|
|
|
5925
6055
|
if (Number.isInteger(testController)) reserved.set(testController, "\u6D4B\u901F\u5B9E\u4F8B\u63A7\u5236\u5668\u7AEF\u53E3");
|
|
5926
6056
|
return reserved;
|
|
5927
6057
|
}
|
|
5928
|
-
function validateTunnelName(name) {
|
|
5929
|
-
if (!name || !SAFE_NAME_RE.test(name)) {
|
|
5930
|
-
throw new CliError(`\u96A7\u9053\u540D\u79F0\u65E0\u6548: "${name}"\uFF0C\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\u548C\u4E2D\u6587\uFF08\u6700\u957F 64 \u5B57\u7B26\uFF09`);
|
|
5931
|
-
}
|
|
5932
|
-
}
|
|
5933
6058
|
var SAFE_HOST_RE = /^[A-Za-z0-9][A-Za-z0-9._@-]*$/;
|
|
5934
|
-
function
|
|
6059
|
+
function validateSshHost(host) {
|
|
5935
6060
|
if (!host) {
|
|
5936
|
-
throw new CliError("\u7F3A\u5C11 --host", { hint: ["\u4F8B\u5982: mihomo
|
|
6061
|
+
throw new CliError("\u7F3A\u5C11 --host", { hint: ["\u4F8B\u5982: mihomo ssh add work --host m4 --port 1080"] });
|
|
5937
6062
|
}
|
|
5938
6063
|
if (host.startsWith("-")) {
|
|
5939
6064
|
throw new CliError(`\u4E3B\u673A\u540D\u65E0\u6548: "${host}"`, {
|
|
@@ -5948,7 +6073,7 @@ function validateTunnelHost(host) {
|
|
|
5948
6073
|
});
|
|
5949
6074
|
}
|
|
5950
6075
|
}
|
|
5951
|
-
function
|
|
6076
|
+
function validateSshPort(port, exclude) {
|
|
5952
6077
|
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
5953
6078
|
throw new CliError(`\u7AEF\u53E3\u65E0\u6548: ${port}\uFF0C\u9700\u4E3A 1-65535 \u7684\u6574\u6570`);
|
|
5954
6079
|
}
|
|
@@ -5959,64 +6084,53 @@ function validateTunnelPort(port, exclude) {
|
|
|
5959
6084
|
hint: ["\u8BF7\u6362\u4E00\u4E2A\u7AEF\u53E3\uFF0C\u4F8B\u5982 1080\u3002"]
|
|
5960
6085
|
});
|
|
5961
6086
|
}
|
|
5962
|
-
const conflict =
|
|
6087
|
+
const conflict = getSshTunnels().find((t) => t.port === port && t.name !== exclude);
|
|
5963
6088
|
if (conflict) {
|
|
5964
6089
|
throw new CliError(`\u7AEF\u53E3 ${port} \u5DF2\u88AB\u96A7\u9053 "${conflict.name}" \u4F7F\u7528`, { label: "\u7AEF\u53E3\u51B2\u7A81" });
|
|
5965
6090
|
}
|
|
5966
6091
|
}
|
|
5967
|
-
function
|
|
5968
|
-
|
|
5969
|
-
const tunnels = settings.tunnels;
|
|
5970
|
-
if (!Array.isArray(tunnels)) {
|
|
5971
|
-
if (tunnels !== void 0) {
|
|
5972
|
-
console.warn("\u8B66\u544A: settings.json \u7684 tunnels \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08\u53EF\u7528 mihomo tunnel add \u91CD\u65B0\u6DFB\u52A0\uFF09");
|
|
5973
|
-
}
|
|
5974
|
-
return [];
|
|
5975
|
-
}
|
|
5976
|
-
return tunnels.filter((t) => t != null && typeof t === "object" && typeof t.name === "string" && typeof t.host === "string" && Number.isInteger(t.port));
|
|
5977
|
-
}
|
|
5978
|
-
function findTunnel(name) {
|
|
5979
|
-
return getTunnels().find((t) => t.name === name);
|
|
6092
|
+
function findSshTunnel(name) {
|
|
6093
|
+
return getSshTunnels().find((t) => t.name === name);
|
|
5980
6094
|
}
|
|
5981
|
-
function
|
|
5982
|
-
|
|
5983
|
-
|
|
5984
|
-
|
|
6095
|
+
function addSshTunnel(config) {
|
|
6096
|
+
validateSshName(config.name);
|
|
6097
|
+
validateSshHost(config.host);
|
|
6098
|
+
validateSshPort(config.port);
|
|
5985
6099
|
let duplicate = false;
|
|
5986
6100
|
updateSettings(() => {
|
|
5987
|
-
const tunnels = [...
|
|
6101
|
+
const tunnels = [...getSshTunnels()];
|
|
5988
6102
|
if (tunnels.some((t) => t.name === config.name)) {
|
|
5989
6103
|
duplicate = true;
|
|
5990
6104
|
return {};
|
|
5991
6105
|
}
|
|
5992
6106
|
tunnels.push(config);
|
|
5993
|
-
return { tunnels };
|
|
6107
|
+
return { ssh: tunnels };
|
|
5994
6108
|
});
|
|
5995
6109
|
if (duplicate) {
|
|
5996
|
-
throw new CliError(`\u96A7\u9053 "${config.name}" \u5DF2\u5B58\u5728\uFF0C\u8BF7\u6362\u4E2A\u540D\u79F0\uFF0C\u6216\u5148\u5220\u9664\uFF08mihomo
|
|
6110
|
+
throw new CliError(`\u96A7\u9053 "${config.name}" \u5DF2\u5B58\u5728\uFF0C\u8BF7\u6362\u4E2A\u540D\u79F0\uFF0C\u6216\u5148\u5220\u9664\uFF08mihomo ssh rm ${config.name}\uFF09`);
|
|
5997
6111
|
}
|
|
5998
6112
|
}
|
|
5999
|
-
function
|
|
6113
|
+
function removeSshTunnel(name) {
|
|
6000
6114
|
let found = false;
|
|
6001
6115
|
updateSettings(() => {
|
|
6002
|
-
const tunnels = [...
|
|
6116
|
+
const tunnels = [...getSshTunnels()];
|
|
6003
6117
|
const idx = tunnels.findIndex((t) => t.name === name);
|
|
6004
6118
|
if (idx < 0) return {};
|
|
6005
6119
|
found = true;
|
|
6006
6120
|
tunnels.splice(idx, 1);
|
|
6007
|
-
return { tunnels };
|
|
6121
|
+
return { ssh: tunnels };
|
|
6008
6122
|
});
|
|
6009
6123
|
if (!found) return false;
|
|
6010
|
-
|
|
6124
|
+
clearSshRuntime(name);
|
|
6011
6125
|
return true;
|
|
6012
6126
|
}
|
|
6013
|
-
function
|
|
6014
|
-
|
|
6015
|
-
return
|
|
6127
|
+
function getSshRuntimePath(name) {
|
|
6128
|
+
validateSshName(name);
|
|
6129
|
+
return path7.join(DIRS.ssh, `${name}.json`);
|
|
6016
6130
|
}
|
|
6017
|
-
function
|
|
6131
|
+
function readSshRuntime(name) {
|
|
6018
6132
|
try {
|
|
6019
|
-
const raw =
|
|
6133
|
+
const raw = fs8.readFileSync(getSshRuntimePath(name), "utf8");
|
|
6020
6134
|
const parsed = JSON.parse(raw);
|
|
6021
6135
|
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
6022
6136
|
const r = parsed;
|
|
@@ -6031,13 +6145,13 @@ function readTunnelRuntime(name) {
|
|
|
6031
6145
|
return null;
|
|
6032
6146
|
}
|
|
6033
6147
|
}
|
|
6034
|
-
function
|
|
6148
|
+
function writeSshRuntime(name, runtime) {
|
|
6035
6149
|
ensureDirs();
|
|
6036
|
-
atomicWriteFileSync(
|
|
6150
|
+
atomicWriteFileSync(getSshRuntimePath(name), JSON.stringify(runtime, null, 2), { mode: 384 });
|
|
6037
6151
|
}
|
|
6038
|
-
function
|
|
6152
|
+
function clearSshRuntime(name) {
|
|
6039
6153
|
try {
|
|
6040
|
-
|
|
6154
|
+
fs8.rmSync(getSshRuntimePath(name), { force: true });
|
|
6041
6155
|
} catch {
|
|
6042
6156
|
}
|
|
6043
6157
|
}
|
|
@@ -6062,11 +6176,11 @@ function buildSshArgs(tunnel) {
|
|
|
6062
6176
|
function commandNeedle(port) {
|
|
6063
6177
|
return `-D 127.0.0.1:${port}`;
|
|
6064
6178
|
}
|
|
6065
|
-
function
|
|
6066
|
-
|
|
6067
|
-
return
|
|
6179
|
+
function getSshLogPath(name) {
|
|
6180
|
+
validateSshName(name);
|
|
6181
|
+
return path7.join(DIRS.logs, `ssh-${name}.log`);
|
|
6068
6182
|
}
|
|
6069
|
-
function
|
|
6183
|
+
function isSshProcessAlive(pid, port) {
|
|
6070
6184
|
return isProcessRunning(pid) && isProcessCommandMatching(pid, commandNeedle(port));
|
|
6071
6185
|
}
|
|
6072
6186
|
function isPortListening(port, timeoutMs = PORT_PROBE_TIMEOUT_MS) {
|
|
@@ -6086,9 +6200,9 @@ function isPortListening(port, timeoutMs = PORT_PROBE_TIMEOUT_MS) {
|
|
|
6086
6200
|
socket.connect(port, "127.0.0.1");
|
|
6087
6201
|
});
|
|
6088
6202
|
}
|
|
6089
|
-
async function
|
|
6090
|
-
const runtime =
|
|
6091
|
-
const alive = runtime !== null &&
|
|
6203
|
+
async function getSshStatus(config) {
|
|
6204
|
+
const runtime = readSshRuntime(config.name);
|
|
6205
|
+
const alive = runtime !== null && isSshProcessAlive(runtime.pid, runtime.port || config.port);
|
|
6092
6206
|
if (!alive) {
|
|
6093
6207
|
return { config, state: "stopped", pid: null, started_by: null, started_at: null };
|
|
6094
6208
|
}
|
|
@@ -6101,22 +6215,22 @@ async function getTunnelStatus(config) {
|
|
|
6101
6215
|
started_at: runtime.started_at || null
|
|
6102
6216
|
};
|
|
6103
6217
|
}
|
|
6104
|
-
async function
|
|
6105
|
-
return Promise.all(
|
|
6218
|
+
async function getAllSshStatus() {
|
|
6219
|
+
return Promise.all(getSshTunnels().map(getSshStatus));
|
|
6106
6220
|
}
|
|
6107
|
-
async function
|
|
6108
|
-
const config =
|
|
6221
|
+
async function startSshTunnel(name, options) {
|
|
6222
|
+
const config = findSshTunnel(name);
|
|
6109
6223
|
if (!config) {
|
|
6110
|
-
throw new CliError(`\u672A\u627E\u5230\u96A7\u9053 "${name}"`, { hint: ["\u67E5\u770B\u5168\u90E8\u96A7\u9053: mihomo
|
|
6224
|
+
throw new CliError(`\u672A\u627E\u5230\u96A7\u9053 "${name}"`, { hint: ["\u67E5\u770B\u5168\u90E8\u96A7\u9053: mihomo ssh"] });
|
|
6111
6225
|
}
|
|
6112
|
-
const existing =
|
|
6113
|
-
if (existing &&
|
|
6226
|
+
const existing = readSshRuntime(name);
|
|
6227
|
+
if (existing && isSshProcessAlive(existing.pid, existing.port || config.port)) {
|
|
6114
6228
|
if (options.startedBy === "manual" && existing.started_by === "auto") {
|
|
6115
|
-
|
|
6229
|
+
writeSshRuntime(name, { ...existing, started_by: "manual" });
|
|
6116
6230
|
}
|
|
6117
6231
|
return { alreadyRunning: true, pid: existing.pid };
|
|
6118
6232
|
}
|
|
6119
|
-
if (existing)
|
|
6233
|
+
if (existing) clearSshRuntime(name);
|
|
6120
6234
|
if (await isPortListening(config.port)) {
|
|
6121
6235
|
throw new CliError(`\u7AEF\u53E3 ${config.port} \u5DF2\u88AB\u5360\u7528`, {
|
|
6122
6236
|
label: "\u65E0\u6CD5\u542F\u52A8\u96A7\u9053",
|
|
@@ -6124,21 +6238,21 @@ async function startTunnel(name, options) {
|
|
|
6124
6238
|
});
|
|
6125
6239
|
}
|
|
6126
6240
|
ensureDirs();
|
|
6127
|
-
const logPath =
|
|
6128
|
-
const logFd =
|
|
6241
|
+
const logPath = getSshLogPath(name);
|
|
6242
|
+
const logFd = fs8.openSync(logPath, "w");
|
|
6129
6243
|
const child = spawn2("ssh", buildSshArgs(config), {
|
|
6130
6244
|
detached: true,
|
|
6131
6245
|
stdio: ["ignore", logFd, logFd]
|
|
6132
6246
|
});
|
|
6133
6247
|
child.on("error", () => {
|
|
6134
6248
|
});
|
|
6135
|
-
|
|
6249
|
+
fs8.closeSync(logFd);
|
|
6136
6250
|
child.unref();
|
|
6137
6251
|
const pid = child.pid;
|
|
6138
6252
|
if (!pid) {
|
|
6139
6253
|
throw new CliError("\u65E0\u6CD5\u521B\u5EFA ssh \u8FDB\u7A0B", { label: "\u542F\u52A8\u96A7\u9053\u5931\u8D25", hint: ["\u8BF7\u786E\u8BA4\u5DF2\u5B89\u88C5 ssh \u5BA2\u6237\u7AEF\u3002"] });
|
|
6140
6254
|
}
|
|
6141
|
-
|
|
6255
|
+
writeSshRuntime(name, {
|
|
6142
6256
|
pid,
|
|
6143
6257
|
started_by: options.startedBy,
|
|
6144
6258
|
started_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -6149,7 +6263,7 @@ async function startTunnel(name, options) {
|
|
|
6149
6263
|
process.kill(pid, "SIGKILL");
|
|
6150
6264
|
} catch {
|
|
6151
6265
|
}
|
|
6152
|
-
|
|
6266
|
+
clearSshRuntime(name);
|
|
6153
6267
|
});
|
|
6154
6268
|
try {
|
|
6155
6269
|
for (let i = 0; i < START_WAIT_ATTEMPTS; i++) {
|
|
@@ -6163,7 +6277,7 @@ async function startTunnel(name, options) {
|
|
|
6163
6277
|
} finally {
|
|
6164
6278
|
unregisterCleanup();
|
|
6165
6279
|
}
|
|
6166
|
-
|
|
6280
|
+
clearSshRuntime(name);
|
|
6167
6281
|
if (isProcessRunning(pid)) {
|
|
6168
6282
|
try {
|
|
6169
6283
|
process.kill(pid, "SIGKILL");
|
|
@@ -6177,24 +6291,24 @@ async function startTunnel(name, options) {
|
|
|
6177
6291
|
}
|
|
6178
6292
|
function readLogTail(logPath, maxLines = 5) {
|
|
6179
6293
|
try {
|
|
6180
|
-
const content =
|
|
6294
|
+
const content = fs8.readFileSync(logPath, "utf8").trim();
|
|
6181
6295
|
if (!content) return [];
|
|
6182
6296
|
return content.split("\n").slice(-maxLines).map((line) => ` ${line.trim()}`);
|
|
6183
6297
|
} catch {
|
|
6184
6298
|
return [];
|
|
6185
6299
|
}
|
|
6186
6300
|
}
|
|
6187
|
-
function
|
|
6188
|
-
const config =
|
|
6189
|
-
const runtime =
|
|
6301
|
+
function stopSshTunnel(name) {
|
|
6302
|
+
const config = findSshTunnel(name);
|
|
6303
|
+
const runtime = readSshRuntime(name);
|
|
6190
6304
|
if (!runtime) {
|
|
6191
|
-
|
|
6305
|
+
clearSshRuntime(name);
|
|
6192
6306
|
return { notRunning: true, pid: null };
|
|
6193
6307
|
}
|
|
6194
6308
|
const port = runtime.port || config?.port || 0;
|
|
6195
6309
|
const { pid } = runtime;
|
|
6196
|
-
if (!
|
|
6197
|
-
|
|
6310
|
+
if (!isSshProcessAlive(pid, port)) {
|
|
6311
|
+
clearSshRuntime(name);
|
|
6198
6312
|
return { notRunning: true, pid: null };
|
|
6199
6313
|
}
|
|
6200
6314
|
try {
|
|
@@ -6215,15 +6329,15 @@ function stopTunnel(name) {
|
|
|
6215
6329
|
sleepSync(STOP_WAIT_INTERVAL);
|
|
6216
6330
|
}
|
|
6217
6331
|
}
|
|
6218
|
-
|
|
6332
|
+
clearSshRuntime(name);
|
|
6219
6333
|
return { notRunning: false, pid };
|
|
6220
6334
|
}
|
|
6221
|
-
async function
|
|
6335
|
+
async function startAutoSshTunnels() {
|
|
6222
6336
|
const outcomes = [];
|
|
6223
|
-
for (const tunnel of
|
|
6337
|
+
for (const tunnel of getSshTunnels()) {
|
|
6224
6338
|
if (!tunnel.auto) continue;
|
|
6225
6339
|
try {
|
|
6226
|
-
const result = await
|
|
6340
|
+
const result = await startSshTunnel(tunnel.name, { startedBy: "auto" });
|
|
6227
6341
|
outcomes.push({ name: tunnel.name, ok: true, alreadyRunning: result.alreadyRunning });
|
|
6228
6342
|
} catch (e) {
|
|
6229
6343
|
outcomes.push({
|
|
@@ -6235,63 +6349,24 @@ async function startAutoTunnels() {
|
|
|
6235
6349
|
}
|
|
6236
6350
|
return outcomes;
|
|
6237
6351
|
}
|
|
6238
|
-
function
|
|
6352
|
+
function stopAutoSshTunnels() {
|
|
6239
6353
|
const stopped = [];
|
|
6240
|
-
for (const tunnel of
|
|
6241
|
-
const runtime =
|
|
6354
|
+
for (const tunnel of getSshTunnels()) {
|
|
6355
|
+
const runtime = readSshRuntime(tunnel.name);
|
|
6242
6356
|
if (runtime?.started_by !== "auto") continue;
|
|
6243
|
-
const result =
|
|
6357
|
+
const result = stopSshTunnel(tunnel.name);
|
|
6244
6358
|
if (!result.notRunning) stopped.push(tunnel.name);
|
|
6245
6359
|
}
|
|
6246
6360
|
return stopped;
|
|
6247
6361
|
}
|
|
6248
|
-
function
|
|
6362
|
+
function stopAllSshTunnels() {
|
|
6249
6363
|
const stopped = [];
|
|
6250
|
-
for (const tunnel of
|
|
6251
|
-
const result =
|
|
6364
|
+
for (const tunnel of getSshTunnels()) {
|
|
6365
|
+
const result = stopSshTunnel(tunnel.name);
|
|
6252
6366
|
if (!result.notRunning) stopped.push(tunnel.name);
|
|
6253
6367
|
}
|
|
6254
6368
|
return stopped;
|
|
6255
6369
|
}
|
|
6256
|
-
function getTunnelOverwritePath(name) {
|
|
6257
|
-
validateTunnelName(name);
|
|
6258
|
-
return path6.join(USER_DATA_DIR, `overwrite.tunnel-${name}.yaml`);
|
|
6259
|
-
}
|
|
6260
|
-
function renderTunnelOverwrite(tunnel) {
|
|
6261
|
-
const proxyName = `Tunnel-${tunnel.name}-Host`;
|
|
6262
|
-
const groupName = `Tunnel-${tunnel.name}`;
|
|
6263
|
-
return `# mihomo-cli \u96A7\u9053\u8986\u5199\uFF08tunnel: ${tunnel.name}\uFF09
|
|
6264
|
-
# \u672C\u6587\u4EF6\u7531 mihomo-cli \u9996\u6B21\u521B\u5EFA\uFF0C\u4E4B\u540E\u5B8C\u5168\u7531\u4F60\u7EF4\u62A4\u2014\u2014CLI \u4E0D\u4F1A\u518D\u6539\u5199\u6216\u5220\u9664\u5B83\u3002
|
|
6265
|
-
#
|
|
6266
|
-
# ~ \u662F\u300C\u6309 name \u5C31\u5730\u5408\u5E76\u300D\u8BED\u4E49\uFF1A\u4E0E\u5176\u4ED6\u8986\u5199\u6587\u4EF6\u4E2D\u7684\u540C\u540D\u8282\u70B9/\u5206\u7EC4\u5408\u5E76\uFF0C
|
|
6267
|
-
# \u4E0D\u4F9D\u8D56\u6587\u4EF6\u52A0\u8F7D\u987A\u5E8F\uFF08+proxies \u5219\u4F9D\u8D56\u5B57\u6BCD\u5E8F\uFF0C\u4F1A\u88AB\u540E\u6765\u7684\u6587\u4EF6\u538B\u8FC7\u53BB\uFF09\u3002
|
|
6268
|
-
|
|
6269
|
-
~proxies:
|
|
6270
|
-
- name: ${proxyName}
|
|
6271
|
-
type: socks5
|
|
6272
|
-
server: 127.0.0.1
|
|
6273
|
-
port: ${tunnel.port}
|
|
6274
|
-
|
|
6275
|
-
~proxy-groups:
|
|
6276
|
-
- name: ${groupName}
|
|
6277
|
-
type: select
|
|
6278
|
-
proxies:
|
|
6279
|
-
- ${proxyName}
|
|
6280
|
-
- DIRECT
|
|
6281
|
-
|
|
6282
|
-
# \u53D6\u6D88\u6CE8\u91CA\u5E76\u586B\u5165\u9700\u8981\u8D70\u96A7\u9053\u7684\u5185\u7F51\u57DF\u540D/\u7F51\u6BB5\uFF08CLI \u65E0\u4ECE\u77E5\u9053\u4F60\u7684\u5185\u7F51\u5730\u5740\uFF09\uFF1A
|
|
6283
|
-
# +rules:
|
|
6284
|
-
# - DOMAIN-SUFFIX,example.internal,${groupName}
|
|
6285
|
-
# - IP-CIDR,10.0.0.0/8,${groupName}
|
|
6286
|
-
`;
|
|
6287
|
-
}
|
|
6288
|
-
function ensureTunnelOverwriteFile(tunnel) {
|
|
6289
|
-
const filePath = getTunnelOverwritePath(tunnel.name);
|
|
6290
|
-
if (fs7.existsSync(filePath)) return false;
|
|
6291
|
-
ensureDirs();
|
|
6292
|
-
atomicWriteFileSync(filePath, renderTunnelOverwrite(tunnel), { mode: 384 });
|
|
6293
|
-
return true;
|
|
6294
|
-
}
|
|
6295
6370
|
|
|
6296
6371
|
// src/commands/status.ts
|
|
6297
6372
|
async function printStatus() {
|
|
@@ -6361,9 +6436,9 @@ async function printStatus() {
|
|
|
6361
6436
|
if (isDaemonEnabled()) {
|
|
6362
6437
|
console.log(`${colors.gray("\u4FDD\u6D3B: ")}${colors.green("\u5DF2\u542F\u7528")} ${colors.gray("(\u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F)")}`);
|
|
6363
6438
|
}
|
|
6364
|
-
const tunnels =
|
|
6439
|
+
const tunnels = getSshTunnels();
|
|
6365
6440
|
if (tunnels.length > 0) {
|
|
6366
|
-
const statuses = await
|
|
6441
|
+
const statuses = await getAllSshStatus();
|
|
6367
6442
|
const parts = statuses.map((s) => {
|
|
6368
6443
|
const label = `${s.config.name}:${s.config.port}`;
|
|
6369
6444
|
if (s.state === "running") return colors.green(label);
|
|
@@ -6381,8 +6456,8 @@ function handleStopResult(result) {
|
|
|
6381
6456
|
throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint: "\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo" });
|
|
6382
6457
|
}
|
|
6383
6458
|
}
|
|
6384
|
-
function
|
|
6385
|
-
const stopped =
|
|
6459
|
+
function stopAutoSshTunnelsWithLog() {
|
|
6460
|
+
const stopped = stopAutoSshTunnels();
|
|
6386
6461
|
if (stopped.length > 0) {
|
|
6387
6462
|
console.log(`${colors.green("\u5DF2\u505C\u6B62\u96A7\u9053")}: ${stopped.join(", ")}`);
|
|
6388
6463
|
}
|
|
@@ -6393,22 +6468,22 @@ async function cmdStop(args) {
|
|
|
6393
6468
|
console.log("\u76F4\u63A5\u505C\u6B62\u4F1A\u88AB\u81EA\u52A8\u91CD\u65B0\u62C9\u8D77\uFF0C\u8BF7\u7528: mihomo daemon off");
|
|
6394
6469
|
return;
|
|
6395
6470
|
}
|
|
6396
|
-
const
|
|
6471
|
+
const skipSsh = hasFlag(args, "--no-ssh");
|
|
6397
6472
|
const pids = getMihomoPids();
|
|
6398
6473
|
if (pids.length === 0) {
|
|
6399
6474
|
console.log(colors.yellow("\u4E0D\u5728\u8FD0\u884C"));
|
|
6400
|
-
if (!
|
|
6475
|
+
if (!skipSsh) stopAutoSshTunnelsWithLog();
|
|
6401
6476
|
return;
|
|
6402
6477
|
}
|
|
6403
6478
|
console.log(`\u505C\u6B62 ${pids.length} \u4E2A\u8FDB\u7A0B...`);
|
|
6404
6479
|
handleStopResult(stop());
|
|
6405
6480
|
console.log(colors.green("\u5DF2\u505C\u6B62\u8FDB\u7A0B"));
|
|
6406
|
-
if (!
|
|
6481
|
+
if (!skipSsh) stopAutoSshTunnelsWithLog();
|
|
6407
6482
|
}
|
|
6408
6483
|
|
|
6409
6484
|
// src/commands/start.ts
|
|
6410
|
-
async function
|
|
6411
|
-
const outcomes = await
|
|
6485
|
+
async function startAutoSshTunnelsWithWarning() {
|
|
6486
|
+
const outcomes = await startAutoSshTunnels();
|
|
6412
6487
|
if (outcomes.length === 0) return;
|
|
6413
6488
|
const started = outcomes.filter((o) => o.ok && !o.alreadyRunning);
|
|
6414
6489
|
if (started.length > 0) {
|
|
@@ -6422,7 +6497,7 @@ async function startAutoTunnelsWithWarning() {
|
|
|
6422
6497
|
if (line.trim()) console.log(colors.gray(line.startsWith(" ") ? line : ` ${line}`));
|
|
6423
6498
|
}
|
|
6424
6499
|
console.log(colors.gray(" \u5185\u7F51\u5206\u6D41\u89C4\u5219\u5C06\u4E0D\u53EF\u7528\uFF0C\u5176\u4F59\u6D41\u91CF\u6B63\u5E38"));
|
|
6425
|
-
console.log(colors.gray(` \u6392\u67E5: mihomo
|
|
6500
|
+
console.log(colors.gray(` \u6392\u67E5: mihomo ssh status ${failed.name}`));
|
|
6426
6501
|
console.log("");
|
|
6427
6502
|
}
|
|
6428
6503
|
}
|
|
@@ -6444,7 +6519,7 @@ async function cmdStart(args) {
|
|
|
6444
6519
|
const concurrency = parseIntArg(args, "-j", "--concurrency", DEFAULT_TEST_CONCURRENCY);
|
|
6445
6520
|
const skipUpdate = hasFlag(args, "-s", "--no-update");
|
|
6446
6521
|
const skipClean = hasFlag(args, "--no-clean");
|
|
6447
|
-
const
|
|
6522
|
+
const skipSsh = hasFlag(args, "--no-ssh");
|
|
6448
6523
|
const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
|
|
6449
6524
|
const sub = requireActiveSubscription("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
|
|
6450
6525
|
if (!skipUpdate) {
|
|
@@ -6486,8 +6561,8 @@ async function cmdStart(args) {
|
|
|
6486
6561
|
const lines = e.message.split("\n");
|
|
6487
6562
|
throw new CliError(lines[0], { label: "\u542F\u52A8\u5931\u8D25", hint: lines.slice(1) });
|
|
6488
6563
|
}
|
|
6489
|
-
if (!
|
|
6490
|
-
await
|
|
6564
|
+
if (!skipSsh) {
|
|
6565
|
+
await startAutoSshTunnelsWithWarning();
|
|
6491
6566
|
}
|
|
6492
6567
|
const cleanThreshold = isGithubUrl(sub.url) ? AUTO_CLEAN_THRESHOLD_GITHUB : AUTO_CLEAN_THRESHOLD;
|
|
6493
6568
|
if (!skipClean && configInfo.proxies > cleanThreshold) {
|
|
@@ -6736,10 +6811,10 @@ async function cmdDirectory(args) {
|
|
|
6736
6811
|
|
|
6737
6812
|
// src/kernel.ts
|
|
6738
6813
|
import { spawnSync as spawnSync4 } from "child_process";
|
|
6739
|
-
import
|
|
6740
|
-
import
|
|
6814
|
+
import fs9 from "fs";
|
|
6815
|
+
import path8 from "path";
|
|
6741
6816
|
|
|
6742
|
-
// node_modules/compare-versions/lib/esm/utils.js
|
|
6817
|
+
// ../../../node_modules/compare-versions/lib/esm/utils.js
|
|
6743
6818
|
var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
|
|
6744
6819
|
var validateAndParse = (version) => {
|
|
6745
6820
|
if (typeof version !== "string") {
|
|
@@ -6777,7 +6852,7 @@ var compareSegments = (a, b) => {
|
|
|
6777
6852
|
return 0;
|
|
6778
6853
|
};
|
|
6779
6854
|
|
|
6780
|
-
// node_modules/compare-versions/lib/esm/compareVersions.js
|
|
6855
|
+
// ../../../node_modules/compare-versions/lib/esm/compareVersions.js
|
|
6781
6856
|
var compareVersions = (v1, v2) => {
|
|
6782
6857
|
const n1 = validateAndParse(v1);
|
|
6783
6858
|
const n2 = validateAndParse(v2);
|
|
@@ -6880,10 +6955,10 @@ async function checkUpdate(mirror) {
|
|
|
6880
6955
|
}
|
|
6881
6956
|
function findBinaryInDir(dir, maxDepth = 4) {
|
|
6882
6957
|
if (maxDepth <= 0) return null;
|
|
6883
|
-
const files =
|
|
6958
|
+
const files = fs9.readdirSync(dir);
|
|
6884
6959
|
for (const f of files) {
|
|
6885
|
-
const fullPath =
|
|
6886
|
-
const stat =
|
|
6960
|
+
const fullPath = path8.join(dir, f);
|
|
6961
|
+
const stat = fs9.lstatSync(fullPath);
|
|
6887
6962
|
if (stat.isDirectory()) {
|
|
6888
6963
|
const found = findBinaryInDir(fullPath, maxDepth - 1);
|
|
6889
6964
|
if (found) return found;
|
|
@@ -6911,7 +6986,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6911
6986
|
}
|
|
6912
6987
|
assertTrustedAssetUrl(asset.browser_download_url);
|
|
6913
6988
|
const downloadUrl = withMirror(asset.browser_download_url, mirror);
|
|
6914
|
-
const tempPath =
|
|
6989
|
+
const tempPath = path8.join(DIRS.kernel, path8.basename(asset.name));
|
|
6915
6990
|
const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
|
|
6916
6991
|
if (mirror && progressCallback) {
|
|
6917
6992
|
progressCallback("\u63D0\u793A: \u7ECF\u7B2C\u4E09\u65B9\u955C\u50CF\u4E2D\u8F6C\u4E0B\u8F7D\uFF0C\u65E0\u6CD5\u9A8C\u8BC1\u6765\u6E90\u5B8C\u6574\u6027\uFF0C\u5EFA\u8BAE\u76F4\u8FDE\u6216\u81EA\u884C\u6821\u9A8C\u4EA7\u7269");
|
|
@@ -6949,19 +7024,19 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6949
7024
|
}
|
|
6950
7025
|
if (curlResult.status !== 0) {
|
|
6951
7026
|
try {
|
|
6952
|
-
|
|
7027
|
+
fs9.unlinkSync(tempPath);
|
|
6953
7028
|
} catch {
|
|
6954
7029
|
}
|
|
6955
7030
|
throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
|
|
6956
7031
|
}
|
|
6957
|
-
if (!
|
|
7032
|
+
if (!fs9.existsSync(tempPath)) {
|
|
6958
7033
|
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
6959
7034
|
}
|
|
6960
7035
|
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
6961
|
-
const actual =
|
|
7036
|
+
const actual = fs9.statSync(tempPath).size;
|
|
6962
7037
|
if (actual !== asset.size) {
|
|
6963
7038
|
try {
|
|
6964
|
-
|
|
7039
|
+
fs9.unlinkSync(tempPath);
|
|
6965
7040
|
} catch {
|
|
6966
7041
|
}
|
|
6967
7042
|
throw new Error(
|
|
@@ -7001,17 +7076,17 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
7001
7076
|
if (tarResult.error) throw tarResult.error;
|
|
7002
7077
|
if (tarResult.status !== 0) throw new Error(`tar \u9000\u51FA\u7801 ${tarResult.status}`);
|
|
7003
7078
|
} else if (tempPath.endsWith(".gz")) {
|
|
7004
|
-
const baseName =
|
|
7005
|
-
const outputPath =
|
|
7079
|
+
const baseName = path8.basename(tempPath, ".gz");
|
|
7080
|
+
const outputPath = path8.join(extractPath, baseName);
|
|
7006
7081
|
const gzipResult = spawnSync4("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
|
|
7007
7082
|
if (gzipResult.error) throw gzipResult.error;
|
|
7008
7083
|
if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
|
|
7009
|
-
|
|
7084
|
+
fs9.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
|
|
7010
7085
|
extractedBinary = outputPath;
|
|
7011
7086
|
}
|
|
7012
7087
|
} catch (e) {
|
|
7013
7088
|
try {
|
|
7014
|
-
|
|
7089
|
+
fs9.unlinkSync(tempPath);
|
|
7015
7090
|
} catch {
|
|
7016
7091
|
}
|
|
7017
7092
|
throw new Error(`\u89E3\u538B\u5931\u8D25: ${e.message}`);
|
|
@@ -7019,23 +7094,23 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
7019
7094
|
const foundBinary = extractedBinary || findBinaryInDir(extractPath);
|
|
7020
7095
|
if (!foundBinary) {
|
|
7021
7096
|
try {
|
|
7022
|
-
|
|
7097
|
+
fs9.unlinkSync(tempPath);
|
|
7023
7098
|
} catch {
|
|
7024
7099
|
}
|
|
7025
7100
|
throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
|
|
7026
7101
|
}
|
|
7027
7102
|
const targetPath = PATHS.mihomoBinary;
|
|
7028
7103
|
if (foundBinary !== targetPath) {
|
|
7029
|
-
if (
|
|
7030
|
-
|
|
7104
|
+
if (fs9.existsSync(targetPath)) {
|
|
7105
|
+
fs9.chmodSync(targetPath, 493);
|
|
7031
7106
|
try {
|
|
7032
|
-
|
|
7107
|
+
fs9.unlinkSync(targetPath);
|
|
7033
7108
|
} catch {
|
|
7034
7109
|
}
|
|
7035
7110
|
}
|
|
7036
|
-
|
|
7111
|
+
fs9.renameSync(foundBinary, targetPath);
|
|
7037
7112
|
}
|
|
7038
|
-
|
|
7113
|
+
fs9.chmodSync(targetPath, 493);
|
|
7039
7114
|
if (progressCallback) {
|
|
7040
7115
|
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
7041
7116
|
}
|
|
@@ -7043,11 +7118,11 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
7043
7118
|
const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
|
|
7044
7119
|
if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
|
|
7045
7120
|
try {
|
|
7046
|
-
|
|
7121
|
+
fs9.unlinkSync(targetPath);
|
|
7047
7122
|
} catch {
|
|
7048
7123
|
}
|
|
7049
7124
|
try {
|
|
7050
|
-
|
|
7125
|
+
fs9.unlinkSync(tempPath);
|
|
7051
7126
|
} catch {
|
|
7052
7127
|
}
|
|
7053
7128
|
throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u5DF2\u5220\u9664
|
|
@@ -7055,7 +7130,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
7055
7130
|
\u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
|
|
7056
7131
|
}
|
|
7057
7132
|
try {
|
|
7058
|
-
|
|
7133
|
+
fs9.unlinkSync(tempPath);
|
|
7059
7134
|
} catch {
|
|
7060
7135
|
}
|
|
7061
7136
|
clearKernelVersionCache();
|
|
@@ -7190,7 +7265,7 @@ function cmdLogs(args) {
|
|
|
7190
7265
|
}
|
|
7191
7266
|
|
|
7192
7267
|
// src/commands/overwrite.ts
|
|
7193
|
-
import
|
|
7268
|
+
import path9 from "path";
|
|
7194
7269
|
function printOverwriteList() {
|
|
7195
7270
|
const info = listOverwriteFile();
|
|
7196
7271
|
const statusText = info.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
|
|
@@ -7200,8 +7275,8 @@ function printOverwriteList() {
|
|
|
7200
7275
|
if (info.files.length === 0) {
|
|
7201
7276
|
console.log("\u6682\u65E0\u8986\u5199\u6587\u4EF6");
|
|
7202
7277
|
console.log("");
|
|
7203
|
-
console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${
|
|
7204
|
-
console.log(` \u6216 ${
|
|
7278
|
+
console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path9.join(info.dir, "overwrite.yaml")}`);
|
|
7279
|
+
console.log(` \u6216 ${path9.join(info.dir, "overwrite.dns.yaml")}`);
|
|
7205
7280
|
console.log("");
|
|
7206
7281
|
} else {
|
|
7207
7282
|
console.log(`${colors.cyan("\u8986\u5199\u6587\u4EF6")} (${info.files.length} \u4E2A\uFF0C\u6309\u987A\u5E8F\u52A0\u8F7D):`);
|
|
@@ -7265,7 +7340,7 @@ async function cmdOverwrite(args) {
|
|
|
7265
7340
|
}
|
|
7266
7341
|
|
|
7267
7342
|
// src/commands/reset.ts
|
|
7268
|
-
import
|
|
7343
|
+
import fs10 from "fs";
|
|
7269
7344
|
var RESET_TARGETS = [
|
|
7270
7345
|
{
|
|
7271
7346
|
id: "subs",
|
|
@@ -7303,15 +7378,20 @@ var RESET_TARGETS = [
|
|
|
7303
7378
|
// 它们会继续占着端口跑下去,且 CLI 无任何路径能停掉。
|
|
7304
7379
|
// **必须排在 settings 之前**:onAfter 会 writeSettings 重建 settings.json,
|
|
7305
7380
|
// 排在 settings 之后会让 `reset --full` 留下一个 {}(同 subs 的处理,见执行顺序注释)
|
|
7306
|
-
id: "
|
|
7307
|
-
aliases: ["
|
|
7381
|
+
id: "ssh",
|
|
7382
|
+
aliases: ["ssh"],
|
|
7308
7383
|
label: "\u96A7\u9053",
|
|
7309
|
-
|
|
7384
|
+
// 连 ssh.*.yaml 一并删:它们既不匹配 isOverwriteFilename(不归 overwrites 目标),
|
|
7385
|
+
// 本目标又只管运行态的话,`reset --full` 会留下配置文件,与「删全部」的承诺不符。
|
|
7386
|
+
// 单条 `ssh rm` 则刻意不删该文件(用户手写的分流规则不可恢复),两者语义不同
|
|
7387
|
+
paths: () => {
|
|
7388
|
+
const files = fs10.existsSync(USER_DATA_DIR) ? fs10.readdirSync(USER_DATA_DIR).filter(isSshFilename).map((f) => `${USER_DATA_DIR}/${f}`) : [];
|
|
7389
|
+
return [DIRS.ssh, ...files];
|
|
7390
|
+
},
|
|
7310
7391
|
needsStop: false,
|
|
7311
|
-
onBefore: () =>
|
|
7312
|
-
// 同步清空 settings
|
|
7313
|
-
|
|
7314
|
-
onAfter: () => writeSettings({ tunnels: void 0 })
|
|
7392
|
+
onBefore: () => stopAllSshTunnels(),
|
|
7393
|
+
// 同步清空 settings 里的隧道列表:只删运行态会留下「列表在但状态没了」的半重置状态
|
|
7394
|
+
onAfter: () => writeSettings({ ssh: void 0 })
|
|
7315
7395
|
},
|
|
7316
7396
|
{
|
|
7317
7397
|
id: "settings",
|
|
@@ -7340,8 +7420,8 @@ var RESET_TARGETS = [
|
|
|
7340
7420
|
label: "\u8986\u5199",
|
|
7341
7421
|
paths: () => {
|
|
7342
7422
|
const dir = USER_DATA_DIR;
|
|
7343
|
-
if (!
|
|
7344
|
-
return
|
|
7423
|
+
if (!fs10.existsSync(dir)) return [];
|
|
7424
|
+
return fs10.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
|
|
7345
7425
|
},
|
|
7346
7426
|
needsStop: false
|
|
7347
7427
|
},
|
|
@@ -7404,7 +7484,7 @@ async function cmdReset(args) {
|
|
|
7404
7484
|
}
|
|
7405
7485
|
targets = matched;
|
|
7406
7486
|
} else {
|
|
7407
|
-
targets = RESET_TARGETS.filter((t) => !["settings", "kernel", "overwrites", "daemon", "
|
|
7487
|
+
targets = RESET_TARGETS.filter((t) => !["settings", "kernel", "overwrites", "daemon", "ssh"].includes(t.id));
|
|
7408
7488
|
}
|
|
7409
7489
|
for (const t of targets) {
|
|
7410
7490
|
if (t.checkEmpty?.()) {
|
|
@@ -7466,7 +7546,7 @@ async function cmdReset(args) {
|
|
|
7466
7546
|
for (const t of targets) {
|
|
7467
7547
|
t.onBefore?.();
|
|
7468
7548
|
for (const p of t.paths()) {
|
|
7469
|
-
if (
|
|
7549
|
+
if (fs10.existsSync(p)) {
|
|
7470
7550
|
try {
|
|
7471
7551
|
rmrf(p);
|
|
7472
7552
|
} catch (e) {
|
|
@@ -7483,10 +7563,227 @@ async function cmdReset(args) {
|
|
|
7483
7563
|
console.log(colors.green(`\u5DF2\u91CD\u7F6E: ${targets.map((t) => t.label).join("\u3001")}`));
|
|
7484
7564
|
}
|
|
7485
7565
|
|
|
7566
|
+
// src/commands/ssh.ts
|
|
7567
|
+
function formatState(status) {
|
|
7568
|
+
switch (status.state) {
|
|
7569
|
+
case "running":
|
|
7570
|
+
return colors.green(`\u8FD0\u884C\u4E2D (PID ${status.pid})`);
|
|
7571
|
+
case "dead-port":
|
|
7572
|
+
return colors.yellow(`\u5047\u6D3B (PID ${status.pid}\uFF0C\u7AEF\u53E3 ${status.config.port} \u4E0D\u901A)`);
|
|
7573
|
+
default:
|
|
7574
|
+
return colors.yellow("\u672A\u8FD0\u884C");
|
|
7575
|
+
}
|
|
7576
|
+
}
|
|
7577
|
+
function getSshNameArg(args) {
|
|
7578
|
+
return getNonFlagArg(args, 2);
|
|
7579
|
+
}
|
|
7580
|
+
function requireSshNameArg(args, usage) {
|
|
7581
|
+
const name = getSshNameArg(args);
|
|
7582
|
+
if (!name) {
|
|
7583
|
+
const tunnels = getSshTunnels();
|
|
7584
|
+
throw new CliError("\u8BF7\u6307\u5B9A\u96A7\u9053\u540D\u79F0", {
|
|
7585
|
+
hint: [usage, ...tunnels.length > 0 ? ["", "\u53EF\u7528\u96A7\u9053:", ...tunnels.map((t) => ` ${t.name}`)] : []]
|
|
7586
|
+
});
|
|
7587
|
+
}
|
|
7588
|
+
return name;
|
|
7589
|
+
}
|
|
7590
|
+
async function printSshList() {
|
|
7591
|
+
const tunnels = getSshTunnels();
|
|
7592
|
+
console.log("");
|
|
7593
|
+
if (tunnels.length === 0) {
|
|
7594
|
+
console.log("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053");
|
|
7595
|
+
console.log("");
|
|
7596
|
+
console.log("\u6DFB\u52A0\u96A7\u9053: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>");
|
|
7597
|
+
console.log(colors.gray(" \u4F8B\u5982: mihomo ssh add work --host m4 --port 1080"));
|
|
7598
|
+
console.log(colors.gray(" \u96A7\u9053\u628A\u5185\u7F51\u51FA\u53E3\u66B4\u9732\u4E3A\u672C\u5730 SOCKS5\uFF0C\u914D\u5408 ssh.<\u540D\u5B57>.yaml \u5206\u6D41\u5185\u7F51\u57DF\u540D"));
|
|
7599
|
+
console.log("");
|
|
7600
|
+
return;
|
|
7601
|
+
}
|
|
7602
|
+
const statuses = await getAllSshStatus();
|
|
7603
|
+
console.log(colors.cyan("\u96A7\u9053\u5217\u8868:"));
|
|
7604
|
+
console.log("");
|
|
7605
|
+
for (const status of statuses) {
|
|
7606
|
+
const { config } = status;
|
|
7607
|
+
const autoLabel = config.auto ? colors.gray(" [auto]") : "";
|
|
7608
|
+
console.log(` ${colors.bold(config.name)}${autoLabel}`);
|
|
7609
|
+
console.log(` ${colors.gray("\u51FA\u53E3: ")}${config.host} \u2192 127.0.0.1:${config.port}`);
|
|
7610
|
+
console.log(` ${colors.gray("\u72B6\u6001: ")}${formatState(status)}`);
|
|
7611
|
+
console.log(` ${colors.gray("\u914D\u7F6E: ")}${getSshConfigPath(config.name)}`);
|
|
7612
|
+
if (status.started_by) {
|
|
7613
|
+
console.log(` ${colors.gray("\u6765\u6E90: ")}${status.started_by === "auto" ? "\u968F start \u62C9\u8D77" : "\u624B\u52A8\u542F\u52A8"}`);
|
|
7614
|
+
}
|
|
7615
|
+
}
|
|
7616
|
+
console.log("");
|
|
7617
|
+
console.log("\u542F\u52A8: mihomo ssh up [\u540D\u5B57] \u505C\u6B62: mihomo ssh down [\u540D\u5B57]");
|
|
7618
|
+
console.log("\u72B6\u6001: mihomo ssh status \u5220\u9664: mihomo ssh rm <\u540D\u5B57>");
|
|
7619
|
+
console.log("");
|
|
7620
|
+
}
|
|
7621
|
+
async function sshAdd(args) {
|
|
7622
|
+
const name = requireSshNameArg(args, "\u7528\u6CD5: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]");
|
|
7623
|
+
const host = parseStringArg(args, "--host");
|
|
7624
|
+
if (!host) {
|
|
7625
|
+
throw new CliError("\u7F3A\u5C11 --host", {
|
|
7626
|
+
hint: ["\u7528\u6CD5: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>", "", "\u4E3B\u673A\u53EF\u7528 ~/.ssh/config \u91CC\u7684\u522B\u540D\uFF0C\u4F8B\u5982 --host m4"]
|
|
7627
|
+
});
|
|
7628
|
+
}
|
|
7629
|
+
const portRaw = parseStringArg(args, "--port");
|
|
7630
|
+
if (!portRaw) {
|
|
7631
|
+
throw new CliError("\u7F3A\u5C11 --port", { hint: ["\u7528\u6CD5: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"] });
|
|
7632
|
+
}
|
|
7633
|
+
if (!/^\d+$/.test(portRaw.trim())) {
|
|
7634
|
+
throw new CliError(`\u7AEF\u53E3\u65E0\u6548: "${portRaw}"\uFF0C\u9700\u4E3A 1-65535 \u7684\u6574\u6570`);
|
|
7635
|
+
}
|
|
7636
|
+
const port = Number(portRaw.trim());
|
|
7637
|
+
const auto = !hasFlag(args, "--no-auto");
|
|
7638
|
+
const config = { name, host, port, auto };
|
|
7639
|
+
addSshTunnel(config);
|
|
7640
|
+
const created = ensureSshConfigFile(config);
|
|
7641
|
+
const configPath = getSshConfigPath(name);
|
|
7642
|
+
console.log(`${colors.green("\u5DF2\u6DFB\u52A0\u96A7\u9053")} ${name} \xB7 ${host} \u2192 127.0.0.1:${port}${auto ? " \xB7 auto" : ""}`);
|
|
7643
|
+
console.log("");
|
|
7644
|
+
if (created) {
|
|
7645
|
+
console.log(`\u5DF2\u751F\u6210\u914D\u7F6E\u6A21\u677F: ${configPath}`);
|
|
7646
|
+
console.log(colors.gray(" socks5 \u8282\u70B9\u7531 CLI \u81EA\u52A8\u6CE8\u5165\uFF0C\u6A21\u677F\u53EA\u5EFA\u597D\u5206\u7EC4\uFF0C\u5206\u6D41\u89C4\u5219\u9700\u4F60\u586B\u5199\uFF08CLI \u65E0\u4ECE\u77E5\u9053\u4F60\u7684\u5185\u7F51\u57DF\u540D\uFF09"));
|
|
7647
|
+
console.log(colors.gray(" \u7F16\u8F91\u540E\u6267\u884C mihomo start \u751F\u6548"));
|
|
7648
|
+
} else {
|
|
7649
|
+
console.log(`\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728\uFF0C\u672A\u6539\u52A8: ${configPath}`);
|
|
7650
|
+
}
|
|
7651
|
+
console.log("");
|
|
7652
|
+
console.log(`\u542F\u52A8\u96A7\u9053: mihomo ssh up ${name}`);
|
|
7653
|
+
await restartToApply(args);
|
|
7654
|
+
}
|
|
7655
|
+
async function sshUp(args) {
|
|
7656
|
+
const name = getSshNameArg(args);
|
|
7657
|
+
const targets = name ? [resolveSshTunnel(name)] : getSshTunnels();
|
|
7658
|
+
if (targets.length === 0) {
|
|
7659
|
+
throw new CliError("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053", { hint: ["\u6DFB\u52A0\u96A7\u9053: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"] });
|
|
7660
|
+
}
|
|
7661
|
+
for (const config of targets) {
|
|
7662
|
+
if (ensureSshConfigFile(config)) {
|
|
7663
|
+
console.log(colors.gray(`\u5DF2\u8865\u5EFA\u914D\u7F6E\u6A21\u677F: ${getSshConfigPath(config.name)}`));
|
|
7664
|
+
}
|
|
7665
|
+
const result = await startSshTunnel(config.name, { startedBy: "manual" });
|
|
7666
|
+
if (result.alreadyRunning) {
|
|
7667
|
+
console.log(`${colors.gray("\u5DF2\u5728\u8FD0\u884C")} ${config.name} (PID ${result.pid})`);
|
|
7668
|
+
} else {
|
|
7669
|
+
console.log(`${colors.green("\u5DF2\u542F\u52A8\u96A7\u9053")} ${config.name} \xB7 ${config.host} \u2192 127.0.0.1:${config.port} (PID ${result.pid})`);
|
|
7670
|
+
}
|
|
7671
|
+
}
|
|
7672
|
+
}
|
|
7673
|
+
function sshDown(args) {
|
|
7674
|
+
const name = getSshNameArg(args);
|
|
7675
|
+
const targets = name ? [resolveSshTunnel(name)] : getSshTunnels();
|
|
7676
|
+
if (targets.length === 0) {
|
|
7677
|
+
throw new CliError("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053");
|
|
7678
|
+
}
|
|
7679
|
+
let stopped = 0;
|
|
7680
|
+
for (const config of targets) {
|
|
7681
|
+
const result = stopSshTunnel(config.name);
|
|
7682
|
+
if (result.notRunning) {
|
|
7683
|
+
console.log(`${colors.yellow("\u4E0D\u5728\u8FD0\u884C")} ${config.name}`);
|
|
7684
|
+
} else {
|
|
7685
|
+
console.log(`${colors.green("\u5DF2\u505C\u6B62\u96A7\u9053")} ${config.name} (PID ${result.pid})`);
|
|
7686
|
+
stopped++;
|
|
7687
|
+
}
|
|
7688
|
+
}
|
|
7689
|
+
if (stopped > 0) {
|
|
7690
|
+
console.log("");
|
|
7691
|
+
console.log(colors.gray("\u6CE8\u610F: \u914D\u7F6E\u91CC\u7684\u96A7\u9053\u8282\u70B9\u4ECD\u5728\uFF0C\u73B0\u5728\u6307\u5411\u672A\u76D1\u542C\u7684\u7AEF\u53E3"));
|
|
7692
|
+
}
|
|
7693
|
+
}
|
|
7694
|
+
async function sshStatus(args) {
|
|
7695
|
+
const name = getSshNameArg(args);
|
|
7696
|
+
if (!name) {
|
|
7697
|
+
await printSshList();
|
|
7698
|
+
return;
|
|
7699
|
+
}
|
|
7700
|
+
const config = resolveSshTunnel(name);
|
|
7701
|
+
const status = await getSshStatus(config);
|
|
7702
|
+
console.log("");
|
|
7703
|
+
console.log(`${colors.gray("\u96A7\u9053: ")}${config.name}${config.auto ? colors.gray(" [auto]") : ""}`);
|
|
7704
|
+
console.log(`${colors.gray("\u51FA\u53E3: ")}${config.host} \u2192 127.0.0.1:${config.port}`);
|
|
7705
|
+
console.log(`${colors.gray("\u72B6\u6001: ")}${formatState(status)}`);
|
|
7706
|
+
if (status.started_by) {
|
|
7707
|
+
console.log(`${colors.gray("\u6765\u6E90: ")}${status.started_by === "auto" ? "\u968F start \u62C9\u8D77" : "\u624B\u52A8\u542F\u52A8"}`);
|
|
7708
|
+
}
|
|
7709
|
+
console.log("");
|
|
7710
|
+
if (status.state === "dead-port") {
|
|
7711
|
+
console.log(colors.yellow("ssh \u8FDB\u7A0B\u8FD8\u5728\uFF0C\u4F46\u7AEF\u53E3\u6CA1\u6709\u76D1\u542C\u2014\u2014\u5185\u7F51\u5206\u6D41\u5F53\u524D\u4E0D\u53EF\u7528"));
|
|
7712
|
+
console.log(`\u91CD\u542F\u96A7\u9053: mihomo ssh down ${config.name} && mihomo ssh up ${config.name}`);
|
|
7713
|
+
console.log(colors.gray(` \u65E5\u5FD7: ${getSshLogPath(config.name)}`));
|
|
7714
|
+
console.log("");
|
|
7715
|
+
} else if (status.state === "stopped") {
|
|
7716
|
+
console.log(`\u542F\u52A8\u96A7\u9053: mihomo ssh up ${config.name}`);
|
|
7717
|
+
console.log("");
|
|
7718
|
+
}
|
|
7719
|
+
}
|
|
7720
|
+
async function sshRemove(args) {
|
|
7721
|
+
const name = requireSshNameArg(args, "\u7528\u6CD5: mihomo ssh rm <\u540D\u5B57> [-y]");
|
|
7722
|
+
const config = resolveSshTunnel(name);
|
|
7723
|
+
const skipConfirm = hasFlag(args, "-y", "--yes");
|
|
7724
|
+
if (!skipConfirm) {
|
|
7725
|
+
if (!process.stdin.isTTY) {
|
|
7726
|
+
throw new CliError("\u5220\u9664\u96A7\u9053\u9700\u8981\u786E\u8BA4", {
|
|
7727
|
+
label: "\u5DF2\u53D6\u6D88",
|
|
7728
|
+
hint: [`\u8DF3\u8FC7\u786E\u8BA4: mihomo ssh rm ${config.name} -y`]
|
|
7729
|
+
});
|
|
7730
|
+
}
|
|
7731
|
+
const confirmed = await confirmPrompt(`\u786E\u8BA4\u5220\u9664\u96A7\u9053 "${config.name}"?`);
|
|
7732
|
+
if (!confirmed) {
|
|
7733
|
+
console.log("\u5DF2\u53D6\u6D88");
|
|
7734
|
+
return;
|
|
7735
|
+
}
|
|
7736
|
+
}
|
|
7737
|
+
stopSshTunnel(config.name);
|
|
7738
|
+
removeSshTunnel(config.name);
|
|
7739
|
+
console.log(`${colors.green("\u5DF2\u5220\u9664\u96A7\u9053")} ${config.name}`);
|
|
7740
|
+
console.log("");
|
|
7741
|
+
console.log(`\u914D\u7F6E\u6587\u4EF6\u672A\u5220\u9664: ${getSshConfigPath(config.name)}`);
|
|
7742
|
+
console.log(colors.gray(" \u5176\u4E2D\u7684\u5206\u7EC4\u5DF2\u5F15\u7528\u4E0D\u5230\u8282\u70B9\uFF0C\u4E0B\u6B21 start \u4F1A\u88AB\u81EA\u52A8\u79FB\u9664\uFF0C\u5982\u4E0D\u518D\u9700\u8981\u8BF7\u81EA\u884C\u5220\u9664\u8BE5\u6587\u4EF6"));
|
|
7743
|
+
}
|
|
7744
|
+
function resolveSshTunnel(name) {
|
|
7745
|
+
const config = findSshTunnel(name);
|
|
7746
|
+
if (!config) {
|
|
7747
|
+
const tunnels = getSshTunnels();
|
|
7748
|
+
const suggestion = suggestSimilar(
|
|
7749
|
+
name,
|
|
7750
|
+
tunnels.map((t) => t.name)
|
|
7751
|
+
);
|
|
7752
|
+
throw new CliError(`\u672A\u627E\u5230\u96A7\u9053 "${name}"`, {
|
|
7753
|
+
hint: [
|
|
7754
|
+
...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
|
|
7755
|
+
...tunnels.length > 0 ? ["", "\u53EF\u7528\u96A7\u9053:", ...tunnels.map((t) => ` ${t.name}`)] : ["", "\u6DFB\u52A0\u96A7\u9053: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"]
|
|
7756
|
+
]
|
|
7757
|
+
});
|
|
7758
|
+
}
|
|
7759
|
+
return config;
|
|
7760
|
+
}
|
|
7761
|
+
var SUBCOMMANDS4 = [
|
|
7762
|
+
{ name: "list", handler: printSshList },
|
|
7763
|
+
{ name: "add", handler: sshAdd },
|
|
7764
|
+
{ name: "up", aliases: ["start"], handler: sshUp },
|
|
7765
|
+
{ name: "down", aliases: ["stop"], handler: sshDown },
|
|
7766
|
+
{ name: "status", handler: sshStatus },
|
|
7767
|
+
{ name: "remove", aliases: ["rm", "delete"], handler: sshRemove }
|
|
7768
|
+
];
|
|
7769
|
+
async function cmdSsh(args) {
|
|
7770
|
+
await dispatchSubcommand(args, SUBCOMMANDS4, {
|
|
7771
|
+
// 无 action → 列表;未知 action → 报错(不静默回落,否则 `ssh upp` 会看似成功)
|
|
7772
|
+
fallback: printSshList,
|
|
7773
|
+
onUnknown: (action) => {
|
|
7774
|
+
const names = SUBCOMMANDS4.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
7775
|
+
const suggestion = suggestSimilar(action, names);
|
|
7776
|
+
throw new CliError(`\u672A\u77E5\u7684 ssh \u5B50\u547D\u4EE4: ${action}`, {
|
|
7777
|
+
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: list, add, up, down, status, rm"]
|
|
7778
|
+
});
|
|
7779
|
+
}
|
|
7780
|
+
});
|
|
7781
|
+
}
|
|
7782
|
+
|
|
7486
7783
|
// src/test-instance.ts
|
|
7487
7784
|
import { spawn as spawn3 } from "child_process";
|
|
7488
|
-
import
|
|
7489
|
-
import
|
|
7785
|
+
import fs11 from "fs";
|
|
7786
|
+
import path10 from "path";
|
|
7490
7787
|
function isProxyValid(proxy) {
|
|
7491
7788
|
if (proxy === null || typeof proxy !== "object") return false;
|
|
7492
7789
|
if (!proxy.name || !proxy.server || !proxy.port) return false;
|
|
@@ -7497,20 +7794,20 @@ function isProxyValid(proxy) {
|
|
|
7497
7794
|
}
|
|
7498
7795
|
return true;
|
|
7499
7796
|
}
|
|
7500
|
-
var TEST_DIR =
|
|
7797
|
+
var TEST_DIR = path10.join(USER_DATA_DIR, "test");
|
|
7501
7798
|
var TEST_DIRS = {
|
|
7502
|
-
data:
|
|
7503
|
-
runtime:
|
|
7799
|
+
data: path10.join(TEST_DIR, "data"),
|
|
7800
|
+
runtime: path10.join(TEST_DIR, "runtime")
|
|
7504
7801
|
};
|
|
7505
7802
|
var TEST_PATHS = {
|
|
7506
|
-
configFile:
|
|
7507
|
-
pidFile:
|
|
7508
|
-
logFile:
|
|
7803
|
+
configFile: path10.join(TEST_DIRS.runtime, "config.yaml"),
|
|
7804
|
+
pidFile: path10.join(TEST_DIRS.runtime, "pid"),
|
|
7805
|
+
logFile: path10.join(TEST_DIR, "test.log")
|
|
7509
7806
|
};
|
|
7510
7807
|
var TEST_API = `http://${TEST_CONFIG["external-controller"]}`;
|
|
7511
7808
|
function ensureTestDirs() {
|
|
7512
7809
|
for (const dir of Object.values(TEST_DIRS)) {
|
|
7513
|
-
|
|
7810
|
+
fs11.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
7514
7811
|
}
|
|
7515
7812
|
}
|
|
7516
7813
|
function cleanupTestDir() {
|
|
@@ -7548,25 +7845,25 @@ function buildTestConfig(subName) {
|
|
|
7548
7845
|
rules: ["MATCH,PROXY"]
|
|
7549
7846
|
};
|
|
7550
7847
|
const content = dumpYaml(config);
|
|
7551
|
-
|
|
7848
|
+
fs11.writeFileSync(TEST_PATHS.configFile, content, { mode: 384 });
|
|
7552
7849
|
}
|
|
7553
7850
|
async function startTestInstance() {
|
|
7554
7851
|
const binary = PATHS.mihomoBinary;
|
|
7555
|
-
if (!
|
|
7852
|
+
if (!fs11.existsSync(binary)) throw new CliError('\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u8FD0\u884C "mihomo kernel" \u4E0B\u8F7D');
|
|
7556
7853
|
stopTestInstance();
|
|
7557
|
-
const logFd =
|
|
7854
|
+
const logFd = fs11.openSync(TEST_PATHS.logFile, "a");
|
|
7558
7855
|
const child = spawn3(binary, ["-d", TEST_DIRS.data, "-f", TEST_PATHS.configFile], {
|
|
7559
7856
|
detached: true,
|
|
7560
7857
|
stdio: ["ignore", logFd, logFd]
|
|
7561
7858
|
});
|
|
7562
7859
|
child.on("error", () => {
|
|
7563
7860
|
});
|
|
7564
|
-
|
|
7861
|
+
fs11.closeSync(logFd);
|
|
7565
7862
|
child.unref();
|
|
7566
7863
|
const pid = child.pid;
|
|
7567
7864
|
if (!pid) throw new CliError("\u6D4B\u8BD5\u5B9E\u4F8B\u542F\u52A8\u5931\u8D25\uFF1A\u65E0\u6CD5\u521B\u5EFA\u8FDB\u7A0B\uFF08\u5185\u6838\u4E8C\u8FDB\u5236\u53EF\u80FD\u4E0D\u53EF\u6267\u884C\uFF09");
|
|
7568
7865
|
spawnedTestPid = pid;
|
|
7569
|
-
|
|
7866
|
+
fs11.writeFileSync(TEST_PATHS.pidFile, pid.toString(), { mode: 384 });
|
|
7570
7867
|
const client = createHttpClient({ timeout: 2e3 });
|
|
7571
7868
|
let ready = false;
|
|
7572
7869
|
for (let i = 0; i < 60; i++) {
|
|
@@ -7582,7 +7879,7 @@ async function startTestInstance() {
|
|
|
7582
7879
|
if (!isProcessRunning(pid)) {
|
|
7583
7880
|
let errorDetail = "";
|
|
7584
7881
|
try {
|
|
7585
|
-
errorDetail =
|
|
7882
|
+
errorDetail = fs11.readFileSync(TEST_PATHS.logFile, "utf8").slice(-1e3);
|
|
7586
7883
|
} catch {
|
|
7587
7884
|
}
|
|
7588
7885
|
throw new CliError(`\u6D4B\u8BD5\u5B9E\u4F8B\u542F\u52A8\u5931\u8D25${errorDetail ? `
|
|
@@ -7596,7 +7893,7 @@ var spawnedTestPid = null;
|
|
|
7596
7893
|
function stopTestInstance() {
|
|
7597
7894
|
let pid = null;
|
|
7598
7895
|
try {
|
|
7599
|
-
const fromFile = parseInt(
|
|
7896
|
+
const fromFile = parseInt(fs11.readFileSync(TEST_PATHS.pidFile, "utf8").trim(), 10);
|
|
7600
7897
|
if (fromFile > 0) pid = fromFile;
|
|
7601
7898
|
} catch {
|
|
7602
7899
|
}
|
|
@@ -7611,7 +7908,7 @@ function stopTestInstance() {
|
|
|
7611
7908
|
}
|
|
7612
7909
|
spawnedTestPid = null;
|
|
7613
7910
|
try {
|
|
7614
|
-
|
|
7911
|
+
fs11.unlinkSync(TEST_PATHS.pidFile);
|
|
7615
7912
|
} catch {
|
|
7616
7913
|
}
|
|
7617
7914
|
}
|
|
@@ -7931,7 +8228,7 @@ async function subTest(args) {
|
|
|
7931
8228
|
progress.finish();
|
|
7932
8229
|
console.log(formatTestSummary(summary));
|
|
7933
8230
|
}
|
|
7934
|
-
var
|
|
8231
|
+
var SUBCOMMANDS5 = [
|
|
7935
8232
|
{ name: "list", handler: printSubscriptionList },
|
|
7936
8233
|
{ name: "add", handler: subAdd },
|
|
7937
8234
|
{ name: "update", handler: subUpdate },
|
|
@@ -7942,11 +8239,11 @@ var SUBCOMMANDS4 = [
|
|
|
7942
8239
|
{ name: "test", handler: subTest }
|
|
7943
8240
|
];
|
|
7944
8241
|
async function cmdSubscription(args) {
|
|
7945
|
-
await dispatchSubcommand(args,
|
|
8242
|
+
await dispatchSubcommand(args, SUBCOMMANDS5, {
|
|
7946
8243
|
// 无子命令 → 列表;未知子命令 → 报错
|
|
7947
8244
|
fallback: printSubscriptionList,
|
|
7948
8245
|
onUnknown: (action) => {
|
|
7949
|
-
const names =
|
|
8246
|
+
const names = SUBCOMMANDS5.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
7950
8247
|
const suggestion = suggestSimilar(action, names);
|
|
7951
8248
|
throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
|
|
7952
8249
|
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "\u7528\u6CD5: mihomo sub [list|use|add|update|remove|web|test|clean]"]
|
|
@@ -8021,224 +8318,6 @@ async function cmdClean(args) {
|
|
|
8021
8318
|
}
|
|
8022
8319
|
}
|
|
8023
8320
|
|
|
8024
|
-
// src/commands/tunnel.ts
|
|
8025
|
-
function formatState(status) {
|
|
8026
|
-
switch (status.state) {
|
|
8027
|
-
case "running":
|
|
8028
|
-
return colors.green(`\u8FD0\u884C\u4E2D (PID ${status.pid})`);
|
|
8029
|
-
case "dead-port":
|
|
8030
|
-
return colors.yellow(`\u5047\u6D3B (PID ${status.pid}\uFF0C\u7AEF\u53E3 ${status.config.port} \u4E0D\u901A)`);
|
|
8031
|
-
default:
|
|
8032
|
-
return colors.yellow("\u672A\u8FD0\u884C");
|
|
8033
|
-
}
|
|
8034
|
-
}
|
|
8035
|
-
function getTunnelNameArg(args) {
|
|
8036
|
-
return getNonFlagArg(args, 2);
|
|
8037
|
-
}
|
|
8038
|
-
function requireTunnelNameArg(args, usage) {
|
|
8039
|
-
const name = getTunnelNameArg(args);
|
|
8040
|
-
if (!name) {
|
|
8041
|
-
const tunnels = getTunnels();
|
|
8042
|
-
throw new CliError("\u8BF7\u6307\u5B9A\u96A7\u9053\u540D\u79F0", {
|
|
8043
|
-
hint: [usage, ...tunnels.length > 0 ? ["", "\u53EF\u7528\u96A7\u9053:", ...tunnels.map((t) => ` ${t.name}`)] : []]
|
|
8044
|
-
});
|
|
8045
|
-
}
|
|
8046
|
-
return name;
|
|
8047
|
-
}
|
|
8048
|
-
async function printTunnelList() {
|
|
8049
|
-
const tunnels = getTunnels();
|
|
8050
|
-
console.log("");
|
|
8051
|
-
if (tunnels.length === 0) {
|
|
8052
|
-
console.log("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053");
|
|
8053
|
-
console.log("");
|
|
8054
|
-
console.log("\u6DFB\u52A0\u96A7\u9053: mihomo tunnel add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>");
|
|
8055
|
-
console.log(colors.gray(" \u4F8B\u5982: mihomo tunnel add work --host m4 --port 1080"));
|
|
8056
|
-
console.log(colors.gray(" \u96A7\u9053\u628A\u5185\u7F51\u51FA\u53E3\u66B4\u9732\u4E3A\u672C\u5730 SOCKS5\uFF0C\u914D\u5408\u8986\u5199\u6587\u4EF6\u5206\u6D41\u5185\u7F51\u57DF\u540D"));
|
|
8057
|
-
console.log("");
|
|
8058
|
-
return;
|
|
8059
|
-
}
|
|
8060
|
-
const statuses = await getAllTunnelStatus();
|
|
8061
|
-
console.log(colors.cyan("\u96A7\u9053\u5217\u8868:"));
|
|
8062
|
-
console.log("");
|
|
8063
|
-
for (const status of statuses) {
|
|
8064
|
-
const { config } = status;
|
|
8065
|
-
const autoLabel = config.auto ? colors.gray(" [auto]") : "";
|
|
8066
|
-
console.log(` ${colors.bold(config.name)}${autoLabel}`);
|
|
8067
|
-
console.log(` ${colors.gray("\u51FA\u53E3: ")}${config.host} \u2192 127.0.0.1:${config.port}`);
|
|
8068
|
-
console.log(` ${colors.gray("\u72B6\u6001: ")}${formatState(status)}`);
|
|
8069
|
-
if (status.started_by) {
|
|
8070
|
-
console.log(` ${colors.gray("\u6765\u6E90: ")}${status.started_by === "auto" ? "\u968F start \u62C9\u8D77" : "\u624B\u52A8\u542F\u52A8"}`);
|
|
8071
|
-
}
|
|
8072
|
-
}
|
|
8073
|
-
console.log("");
|
|
8074
|
-
console.log("\u542F\u52A8: mihomo tunnel up [\u540D\u5B57] \u505C\u6B62: mihomo tunnel down [\u540D\u5B57]");
|
|
8075
|
-
console.log("\u72B6\u6001: mihomo tunnel status \u5220\u9664: mihomo tunnel rm <\u540D\u5B57>");
|
|
8076
|
-
console.log("");
|
|
8077
|
-
}
|
|
8078
|
-
async function tunnelAdd(args) {
|
|
8079
|
-
const name = requireTunnelNameArg(args, "\u7528\u6CD5: mihomo tunnel add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]");
|
|
8080
|
-
const host = parseStringArg(args, "--host");
|
|
8081
|
-
if (!host) {
|
|
8082
|
-
throw new CliError("\u7F3A\u5C11 --host", {
|
|
8083
|
-
hint: ["\u7528\u6CD5: mihomo tunnel add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>", "", "\u4E3B\u673A\u53EF\u7528 ~/.ssh/config \u91CC\u7684\u522B\u540D\uFF0C\u4F8B\u5982 --host m4"]
|
|
8084
|
-
});
|
|
8085
|
-
}
|
|
8086
|
-
const portRaw = parseStringArg(args, "--port");
|
|
8087
|
-
if (!portRaw) {
|
|
8088
|
-
throw new CliError("\u7F3A\u5C11 --port", { hint: ["\u7528\u6CD5: mihomo tunnel add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"] });
|
|
8089
|
-
}
|
|
8090
|
-
if (!/^\d+$/.test(portRaw.trim())) {
|
|
8091
|
-
throw new CliError(`\u7AEF\u53E3\u65E0\u6548: "${portRaw}"\uFF0C\u9700\u4E3A 1-65535 \u7684\u6574\u6570`);
|
|
8092
|
-
}
|
|
8093
|
-
const port = Number(portRaw.trim());
|
|
8094
|
-
const auto = !hasFlag(args, "--no-auto");
|
|
8095
|
-
const config = { name, host, port, auto };
|
|
8096
|
-
addTunnel(config);
|
|
8097
|
-
const created = ensureTunnelOverwriteFile(config);
|
|
8098
|
-
const overwritePath = getTunnelOverwritePath(name);
|
|
8099
|
-
console.log(`${colors.green("\u5DF2\u6DFB\u52A0\u96A7\u9053")} ${name} \xB7 ${host} \u2192 127.0.0.1:${port}${auto ? " \xB7 auto" : ""}`);
|
|
8100
|
-
console.log("");
|
|
8101
|
-
if (created) {
|
|
8102
|
-
console.log(`\u5DF2\u751F\u6210\u8986\u5199\u6A21\u677F: ${overwritePath}`);
|
|
8103
|
-
console.log(colors.gray(" \u6A21\u677F\u53EA\u5EFA\u597D socks5 \u8282\u70B9\u4E0E\u5206\u7EC4\uFF0C\u5206\u6D41\u89C4\u5219\u9700\u4F60\u586B\u5199\uFF08CLI \u65E0\u4ECE\u77E5\u9053\u4F60\u7684\u5185\u7F51\u57DF\u540D\uFF09"));
|
|
8104
|
-
console.log(colors.gray(" \u7F16\u8F91\u540E\u6267\u884C mihomo start \u751F\u6548"));
|
|
8105
|
-
} else {
|
|
8106
|
-
console.log(`\u8986\u5199\u6587\u4EF6\u5DF2\u5B58\u5728\uFF0C\u672A\u6539\u52A8: ${overwritePath}`);
|
|
8107
|
-
}
|
|
8108
|
-
console.log("");
|
|
8109
|
-
console.log(`\u542F\u52A8\u96A7\u9053: mihomo tunnel up ${name}`);
|
|
8110
|
-
if (created) {
|
|
8111
|
-
await restartToApply(args);
|
|
8112
|
-
}
|
|
8113
|
-
}
|
|
8114
|
-
async function tunnelUp(args) {
|
|
8115
|
-
const name = getTunnelNameArg(args);
|
|
8116
|
-
const targets = name ? [resolveTunnel(name)] : getTunnels();
|
|
8117
|
-
if (targets.length === 0) {
|
|
8118
|
-
throw new CliError("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053", { hint: ["\u6DFB\u52A0\u96A7\u9053: mihomo tunnel add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"] });
|
|
8119
|
-
}
|
|
8120
|
-
for (const config of targets) {
|
|
8121
|
-
if (ensureTunnelOverwriteFile(config)) {
|
|
8122
|
-
console.log(colors.gray(`\u5DF2\u8865\u5EFA\u8986\u5199\u6A21\u677F: ${getTunnelOverwritePath(config.name)}`));
|
|
8123
|
-
}
|
|
8124
|
-
const result = await startTunnel(config.name, { startedBy: "manual" });
|
|
8125
|
-
if (result.alreadyRunning) {
|
|
8126
|
-
console.log(`${colors.gray("\u5DF2\u5728\u8FD0\u884C")} ${config.name} (PID ${result.pid})`);
|
|
8127
|
-
} else {
|
|
8128
|
-
console.log(`${colors.green("\u5DF2\u542F\u52A8\u96A7\u9053")} ${config.name} \xB7 ${config.host} \u2192 127.0.0.1:${config.port} (PID ${result.pid})`);
|
|
8129
|
-
}
|
|
8130
|
-
}
|
|
8131
|
-
}
|
|
8132
|
-
function tunnelDown(args) {
|
|
8133
|
-
const name = getTunnelNameArg(args);
|
|
8134
|
-
const targets = name ? [resolveTunnel(name)] : getTunnels();
|
|
8135
|
-
if (targets.length === 0) {
|
|
8136
|
-
throw new CliError("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053");
|
|
8137
|
-
}
|
|
8138
|
-
let stopped = 0;
|
|
8139
|
-
for (const config of targets) {
|
|
8140
|
-
const result = stopTunnel(config.name);
|
|
8141
|
-
if (result.notRunning) {
|
|
8142
|
-
console.log(`${colors.yellow("\u4E0D\u5728\u8FD0\u884C")} ${config.name}`);
|
|
8143
|
-
} else {
|
|
8144
|
-
console.log(`${colors.green("\u5DF2\u505C\u6B62\u96A7\u9053")} ${config.name} (PID ${result.pid})`);
|
|
8145
|
-
stopped++;
|
|
8146
|
-
}
|
|
8147
|
-
}
|
|
8148
|
-
if (stopped > 0) {
|
|
8149
|
-
console.log("");
|
|
8150
|
-
console.log(colors.gray("\u6CE8\u610F: \u8986\u5199\u6587\u4EF6\u4ECD\u5728\uFF0C\u914D\u7F6E\u91CC\u7684\u96A7\u9053\u8282\u70B9\u73B0\u5728\u6307\u5411\u672A\u76D1\u542C\u7684\u7AEF\u53E3"));
|
|
8151
|
-
}
|
|
8152
|
-
}
|
|
8153
|
-
async function tunnelStatus(args) {
|
|
8154
|
-
const name = getTunnelNameArg(args);
|
|
8155
|
-
if (!name) {
|
|
8156
|
-
await printTunnelList();
|
|
8157
|
-
return;
|
|
8158
|
-
}
|
|
8159
|
-
const config = resolveTunnel(name);
|
|
8160
|
-
const status = await getTunnelStatus(config);
|
|
8161
|
-
console.log("");
|
|
8162
|
-
console.log(`${colors.gray("\u96A7\u9053: ")}${config.name}${config.auto ? colors.gray(" [auto]") : ""}`);
|
|
8163
|
-
console.log(`${colors.gray("\u51FA\u53E3: ")}${config.host} \u2192 127.0.0.1:${config.port}`);
|
|
8164
|
-
console.log(`${colors.gray("\u72B6\u6001: ")}${formatState(status)}`);
|
|
8165
|
-
if (status.started_by) {
|
|
8166
|
-
console.log(`${colors.gray("\u6765\u6E90: ")}${status.started_by === "auto" ? "\u968F start \u62C9\u8D77" : "\u624B\u52A8\u542F\u52A8"}`);
|
|
8167
|
-
}
|
|
8168
|
-
console.log("");
|
|
8169
|
-
if (status.state === "dead-port") {
|
|
8170
|
-
console.log(colors.yellow("ssh \u8FDB\u7A0B\u8FD8\u5728\uFF0C\u4F46\u7AEF\u53E3\u6CA1\u6709\u76D1\u542C\u2014\u2014\u5185\u7F51\u5206\u6D41\u5F53\u524D\u4E0D\u53EF\u7528"));
|
|
8171
|
-
console.log(`\u91CD\u542F\u96A7\u9053: mihomo tunnel down ${config.name} && mihomo tunnel up ${config.name}`);
|
|
8172
|
-
console.log(colors.gray(` \u65E5\u5FD7: ${getTunnelLogPath(config.name)}`));
|
|
8173
|
-
console.log("");
|
|
8174
|
-
} else if (status.state === "stopped") {
|
|
8175
|
-
console.log(`\u542F\u52A8\u96A7\u9053: mihomo tunnel up ${config.name}`);
|
|
8176
|
-
console.log("");
|
|
8177
|
-
}
|
|
8178
|
-
}
|
|
8179
|
-
async function tunnelRemove(args) {
|
|
8180
|
-
const name = requireTunnelNameArg(args, "\u7528\u6CD5: mihomo tunnel rm <\u540D\u5B57> [-y]");
|
|
8181
|
-
const config = resolveTunnel(name);
|
|
8182
|
-
const skipConfirm = hasFlag(args, "-y", "--yes");
|
|
8183
|
-
if (!skipConfirm) {
|
|
8184
|
-
if (!process.stdin.isTTY) {
|
|
8185
|
-
throw new CliError("\u5220\u9664\u96A7\u9053\u9700\u8981\u786E\u8BA4", {
|
|
8186
|
-
label: "\u5DF2\u53D6\u6D88",
|
|
8187
|
-
hint: [`\u8DF3\u8FC7\u786E\u8BA4: mihomo tunnel rm ${config.name} -y`]
|
|
8188
|
-
});
|
|
8189
|
-
}
|
|
8190
|
-
const confirmed = await confirmPrompt(`\u786E\u8BA4\u5220\u9664\u96A7\u9053 "${config.name}"?`);
|
|
8191
|
-
if (!confirmed) {
|
|
8192
|
-
console.log("\u5DF2\u53D6\u6D88");
|
|
8193
|
-
return;
|
|
8194
|
-
}
|
|
8195
|
-
}
|
|
8196
|
-
stopTunnel(config.name);
|
|
8197
|
-
removeTunnel(config.name);
|
|
8198
|
-
console.log(`${colors.green("\u5DF2\u5220\u9664\u96A7\u9053")} ${config.name}`);
|
|
8199
|
-
console.log("");
|
|
8200
|
-
console.log(`\u8986\u5199\u6587\u4EF6\u672A\u5220\u9664: ${getTunnelOverwritePath(config.name)}`);
|
|
8201
|
-
console.log(colors.gray(" \u5B83\u4ECD\u4F1A\u5411\u914D\u7F6E\u6CE8\u5165\u6307\u5411\u8BE5\u7AEF\u53E3\u7684\u8282\u70B9\uFF0C\u5982\u4E0D\u518D\u9700\u8981\u8BF7\u81EA\u884C\u5220\u9664"));
|
|
8202
|
-
}
|
|
8203
|
-
function resolveTunnel(name) {
|
|
8204
|
-
const config = findTunnel(name);
|
|
8205
|
-
if (!config) {
|
|
8206
|
-
const tunnels = getTunnels();
|
|
8207
|
-
const suggestion = suggestSimilar(
|
|
8208
|
-
name,
|
|
8209
|
-
tunnels.map((t) => t.name)
|
|
8210
|
-
);
|
|
8211
|
-
throw new CliError(`\u672A\u627E\u5230\u96A7\u9053 "${name}"`, {
|
|
8212
|
-
hint: [
|
|
8213
|
-
...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
|
|
8214
|
-
...tunnels.length > 0 ? ["", "\u53EF\u7528\u96A7\u9053:", ...tunnels.map((t) => ` ${t.name}`)] : ["", "\u6DFB\u52A0\u96A7\u9053: mihomo tunnel add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"]
|
|
8215
|
-
]
|
|
8216
|
-
});
|
|
8217
|
-
}
|
|
8218
|
-
return config;
|
|
8219
|
-
}
|
|
8220
|
-
var SUBCOMMANDS5 = [
|
|
8221
|
-
{ name: "list", handler: printTunnelList },
|
|
8222
|
-
{ name: "add", handler: tunnelAdd },
|
|
8223
|
-
{ name: "up", aliases: ["start"], handler: tunnelUp },
|
|
8224
|
-
{ name: "down", aliases: ["stop"], handler: tunnelDown },
|
|
8225
|
-
{ name: "status", handler: tunnelStatus },
|
|
8226
|
-
{ name: "remove", aliases: ["rm", "delete"], handler: tunnelRemove }
|
|
8227
|
-
];
|
|
8228
|
-
async function cmdTunnel(args) {
|
|
8229
|
-
await dispatchSubcommand(args, SUBCOMMANDS5, {
|
|
8230
|
-
// 无 action → 列表;未知 action → 报错(不静默回落,否则 `tunnel upp` 会看似成功)
|
|
8231
|
-
fallback: printTunnelList,
|
|
8232
|
-
onUnknown: (action) => {
|
|
8233
|
-
const names = SUBCOMMANDS5.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
8234
|
-
const suggestion = suggestSimilar(action, names);
|
|
8235
|
-
throw new CliError(`\u672A\u77E5\u7684 tunnel \u5B50\u547D\u4EE4: ${action}`, {
|
|
8236
|
-
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: list, add, up, down, status, rm"]
|
|
8237
|
-
});
|
|
8238
|
-
}
|
|
8239
|
-
});
|
|
8240
|
-
}
|
|
8241
|
-
|
|
8242
8321
|
// src/commands/ui.ts
|
|
8243
8322
|
function cmdUI(args) {
|
|
8244
8323
|
const uiName = args[1] || "zash";
|
|
@@ -8471,17 +8550,18 @@ var COMMANDS = [
|
|
|
8471
8550
|
usage: ["daemon on|off \u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F\uFF08\u4EC5 Mixed\uFF0C\u9700\u7BA1\u7406\u5458\u5BC6\u7801\uFF09", "daemon status \u67E5\u770B\u4FDD\u6D3B\u72B6\u6001"]
|
|
8472
8551
|
},
|
|
8473
8552
|
{
|
|
8474
|
-
//
|
|
8475
|
-
|
|
8476
|
-
|
|
8477
|
-
|
|
8553
|
+
// 无别名:`tun` 被 TUN 模式快捷命令占用,`ssh` 本身已够短。
|
|
8554
|
+
// (注册表重复 token 会在模块加载期直接抛错)
|
|
8555
|
+
name: "ssh",
|
|
8556
|
+
aliases: [],
|
|
8557
|
+
handler: cmdSsh,
|
|
8478
8558
|
group: "system",
|
|
8479
8559
|
usage: [
|
|
8480
|
-
"
|
|
8481
|
-
"
|
|
8482
|
-
"
|
|
8483
|
-
"
|
|
8484
|
-
"
|
|
8560
|
+
"ssh \u5217\u51FA ssh \u96A7\u9053",
|
|
8561
|
+
"ssh add <\u540D\u5B57> --host <\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]",
|
|
8562
|
+
"ssh up|down [\u540D\u5B57] \u542F\u52A8/\u505C\u6B62\u96A7\u9053\uFF08\u65E0\u53C2\u5373\u5168\u90E8\uFF09",
|
|
8563
|
+
"ssh status [\u540D\u5B57] \u67E5\u770B\u96A7\u9053\u72B6\u6001\uFF08\u771F\u5B9E\u63A2\u6D4B\u7AEF\u53E3\uFF09",
|
|
8564
|
+
"ssh rm <\u540D\u5B57> [-y] \u5220\u9664\u96A7\u9053\uFF08\u4E0D\u5220\u914D\u7F6E\u6587\u4EF6\uFF09"
|
|
8485
8565
|
]
|
|
8486
8566
|
},
|
|
8487
8567
|
{
|