mihomo-cli 3.8.1 → 3.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/README.md +28 -24
- package/dist/index.js +593 -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,100 @@ 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 getSshProxyName(name) {
|
|
3801
|
+
return `Ssh-${name}-Host`;
|
|
3802
|
+
}
|
|
3803
|
+
function getSshGroupName(name) {
|
|
3804
|
+
return `Ssh-${name}`;
|
|
3805
|
+
}
|
|
3806
|
+
function renderSshProxy(tunnel) {
|
|
3807
|
+
return {
|
|
3808
|
+
name: getSshProxyName(tunnel.name),
|
|
3809
|
+
type: "socks5",
|
|
3810
|
+
server: "127.0.0.1",
|
|
3811
|
+
port: tunnel.port
|
|
3812
|
+
};
|
|
3813
|
+
}
|
|
3814
|
+
function collectSshProxyNames(tunnels) {
|
|
3815
|
+
return tunnels.map((t) => getSshProxyName(t.name));
|
|
3816
|
+
}
|
|
3817
|
+
function loadSshConfigFiles() {
|
|
3818
|
+
if (!fs4.existsSync(USER_DATA_DIR)) return [];
|
|
3819
|
+
const files = fs4.readdirSync(USER_DATA_DIR).filter(isSshFilename).sort();
|
|
3820
|
+
const results = [];
|
|
3821
|
+
for (const file of files) {
|
|
3822
|
+
const filePath = path4.join(USER_DATA_DIR, file);
|
|
3823
|
+
try {
|
|
3824
|
+
const parsed = load(fs4.readFileSync(filePath, "utf8"), { maxAliases: 200 });
|
|
3825
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
3826
|
+
if ("match" in parsed) {
|
|
3827
|
+
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`);
|
|
3828
|
+
delete parsed.match;
|
|
3829
|
+
}
|
|
3830
|
+
results.push({ name: file, path: filePath, config: parsed });
|
|
3831
|
+
} else if (parsed !== null) {
|
|
3832
|
+
console.warn(`\u8B66\u544A: ssh \u914D\u7F6E "${file}" \u9876\u5C42\u5FC5\u987B\u662F\u5BF9\u8C61\uFF0C\u5DF2\u8DF3\u8FC7`);
|
|
3833
|
+
}
|
|
3834
|
+
} catch (e) {
|
|
3835
|
+
console.warn(`\u8B66\u544A: ssh \u914D\u7F6E "${file}" \u89E3\u6790\u5931\u8D25: ${e.message}`);
|
|
3836
|
+
}
|
|
3837
|
+
}
|
|
3838
|
+
return results;
|
|
3839
|
+
}
|
|
3840
|
+
function applySshConfig(baseConfig, sshFiles, tunnels) {
|
|
3841
|
+
let result = { ...baseConfig };
|
|
3842
|
+
for (const file of sshFiles) {
|
|
3843
|
+
result = deepMergeWithOverrides(result, file.config);
|
|
3844
|
+
}
|
|
3845
|
+
if (tunnels.length > 0) {
|
|
3846
|
+
result = deepMergeWithOverrides(result, { "~proxies": tunnels.map(renderSshProxy) });
|
|
3847
|
+
}
|
|
3848
|
+
return result;
|
|
3849
|
+
}
|
|
3850
|
+
function renderSshConfigTemplate(tunnel) {
|
|
3851
|
+
const proxyName = getSshProxyName(tunnel.name);
|
|
3852
|
+
const groupName = getSshGroupName(tunnel.name);
|
|
3853
|
+
return `# mihomo-cli ssh \u96A7\u9053\u914D\u7F6E\uFF08ssh: ${tunnel.name}\uFF09
|
|
3854
|
+
# \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
|
|
3855
|
+
#
|
|
3856
|
+
# \u8282\u70B9 ${proxyName} \u7531 CLI \u4F9D\u636E settings \u91CC\u7684 host/port \u81EA\u52A8\u6CE8\u5165\uFF0C
|
|
3857
|
+
# \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
|
|
3858
|
+
#
|
|
3859
|
+
# \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
|
|
3860
|
+
# ~ \u662F\u300C\u6309 name \u5C31\u5730\u5408\u5E76\u300D\u8BED\u4E49\uFF0C\u4E0D\u4F9D\u8D56\u6587\u4EF6\u52A0\u8F7D\u987A\u5E8F\u3002
|
|
3861
|
+
|
|
3862
|
+
~proxy-groups:
|
|
3863
|
+
- name: ${groupName}
|
|
3864
|
+
type: select
|
|
3865
|
+
proxies:
|
|
3866
|
+
- ${proxyName}
|
|
3867
|
+
- DIRECT
|
|
3868
|
+
|
|
3869
|
+
# \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
|
|
3870
|
+
# +rules:
|
|
3871
|
+
# - DOMAIN-SUFFIX,example.internal,${groupName}
|
|
3872
|
+
# - IP-CIDR,10.0.0.0/8,${groupName}
|
|
3873
|
+
`;
|
|
3874
|
+
}
|
|
3875
|
+
function ensureSshConfigFile(tunnel) {
|
|
3876
|
+
const filePath = getSshConfigPath(tunnel.name);
|
|
3877
|
+
if (fs4.existsSync(filePath)) return false;
|
|
3878
|
+
fs4.mkdirSync(USER_DATA_DIR, { recursive: true, mode: 448 });
|
|
3879
|
+
fs4.writeFileSync(filePath, renderSshConfigTemplate(tunnel), { mode: 384 });
|
|
3880
|
+
return true;
|
|
3881
|
+
}
|
|
3882
|
+
|
|
3770
3883
|
// src/utils.ts
|
|
3771
3884
|
var sleepBuf = new Int32Array(new SharedArrayBuffer(4));
|
|
3772
3885
|
function sleepSync(ms) {
|
|
@@ -3875,7 +3988,7 @@ var VALUE_FLAGS = /* @__PURE__ */ new Set([
|
|
|
3875
3988
|
]);
|
|
3876
3989
|
function extractStartOptions(args) {
|
|
3877
3990
|
if (!args) return [];
|
|
3878
|
-
const BOOL_FLAGS = /* @__PURE__ */ new Set(["-s", "--no-update", "--no-clean", "--no-
|
|
3991
|
+
const BOOL_FLAGS = /* @__PURE__ */ new Set(["-s", "--no-update", "--no-clean", "--no-ssh"]);
|
|
3879
3992
|
const out = [];
|
|
3880
3993
|
for (let i = 0; i < args.length; i++) {
|
|
3881
3994
|
const a = args[i];
|
|
@@ -4021,8 +4134,8 @@ function collectOverwriteProxyNames(overwriteFiles) {
|
|
|
4021
4134
|
}
|
|
4022
4135
|
return names;
|
|
4023
4136
|
}
|
|
4024
|
-
function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles) {
|
|
4025
|
-
const injectedNames = collectOverwriteProxyNames(overwriteFiles);
|
|
4137
|
+
function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles, extraNames = []) {
|
|
4138
|
+
const injectedNames = [...collectOverwriteProxyNames(overwriteFiles), ...extraNames];
|
|
4026
4139
|
if (injectedNames.length === 0) return;
|
|
4027
4140
|
const groups = config["proxy-groups"];
|
|
4028
4141
|
if (!groups) return;
|
|
@@ -4206,31 +4319,35 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4206
4319
|
const allFiles = overwriteEnabled ? loadOverwriteFile() : [];
|
|
4207
4320
|
const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
|
|
4208
4321
|
const withOverwrites = applyOverwrite(subscriptionConfig, overwriteFiles);
|
|
4209
|
-
|
|
4210
|
-
|
|
4322
|
+
const sshTunnels = getSshTunnels();
|
|
4323
|
+
const sshFiles = sshTunnels.length > 0 ? loadSshConfigFiles() : [];
|
|
4324
|
+
const withSsh = applySshConfig(withOverwrites, sshFiles, sshTunnels);
|
|
4325
|
+
const sshProxyNames = collectSshProxyNames(sshTunnels);
|
|
4326
|
+
if (overwriteFiles.length > 0 || sshProxyNames.length > 0) {
|
|
4327
|
+
excludeOverwriteProxiesFromIncludeAll(withSsh, overwriteFiles, sshProxyNames);
|
|
4211
4328
|
}
|
|
4212
4329
|
const systemConfig = {};
|
|
4213
4330
|
for (const [key, value] of Object.entries(BASE_CONFIG)) {
|
|
4214
|
-
if (!(key in
|
|
4331
|
+
if (!(key in withSsh)) {
|
|
4215
4332
|
systemConfig[key] = value;
|
|
4216
4333
|
}
|
|
4217
4334
|
}
|
|
4218
4335
|
systemConfig["external-controller"] = BASE_CONFIG["external-controller"];
|
|
4219
4336
|
systemConfig["mixed-port"] = BASE_CONFIG["mixed-port"];
|
|
4220
|
-
delete
|
|
4221
|
-
delete
|
|
4222
|
-
delete
|
|
4223
|
-
delete
|
|
4224
|
-
delete
|
|
4225
|
-
delete
|
|
4226
|
-
delete
|
|
4337
|
+
delete withSsh["mixed-port"];
|
|
4338
|
+
delete withSsh.port;
|
|
4339
|
+
delete withSsh["socks-port"];
|
|
4340
|
+
delete withSsh["external-ui"];
|
|
4341
|
+
delete withSsh["external-ui-name"];
|
|
4342
|
+
delete withSsh["external-ui-url"];
|
|
4343
|
+
delete withSsh.secret;
|
|
4227
4344
|
const controllerSecret = readSettings().controller_secret;
|
|
4228
4345
|
if (controllerSecret) {
|
|
4229
4346
|
systemConfig.secret = controllerSecret;
|
|
4230
4347
|
}
|
|
4231
4348
|
if (mode === "tun") {
|
|
4232
4349
|
systemConfig.tun = TUN_CONFIG.tun;
|
|
4233
|
-
const subDns =
|
|
4350
|
+
const subDns = withSsh.dns || {};
|
|
4234
4351
|
const dns = {};
|
|
4235
4352
|
if (!("enable" in subDns)) dns.enable = true;
|
|
4236
4353
|
if (!("enhanced-mode" in subDns)) dns["enhanced-mode"] = "fake-ip";
|
|
@@ -4239,14 +4356,14 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4239
4356
|
systemConfig.dns = dns;
|
|
4240
4357
|
}
|
|
4241
4358
|
} else {
|
|
4242
|
-
delete
|
|
4359
|
+
delete withSsh.tun;
|
|
4243
4360
|
}
|
|
4244
|
-
const merged = { ...
|
|
4361
|
+
const merged = { ...withSsh, ...systemConfig };
|
|
4245
4362
|
if (systemConfig.dns) {
|
|
4246
|
-
merged.dns = { ...
|
|
4363
|
+
merged.dns = { ...withSsh.dns || {}, ...systemConfig.dns };
|
|
4247
4364
|
}
|
|
4248
4365
|
const mergedDns = merged.dns || {};
|
|
4249
|
-
if (mergedDns["enhanced-mode"] === "fake-ip" && !("sniffer" in
|
|
4366
|
+
if (mergedDns["enhanced-mode"] === "fake-ip" && !("sniffer" in withSsh)) {
|
|
4250
4367
|
merged.sniffer = {
|
|
4251
4368
|
enable: true,
|
|
4252
4369
|
sniff: {
|
|
@@ -4258,7 +4375,7 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4258
4375
|
};
|
|
4259
4376
|
}
|
|
4260
4377
|
const warnings = validateConfig(merged);
|
|
4261
|
-
return { config: merged, subscriptionConfig, overwriteFiles, systemConfig, warnings };
|
|
4378
|
+
return { config: merged, subscriptionConfig, overwriteFiles, sshFiles, systemConfig, warnings };
|
|
4262
4379
|
}
|
|
4263
4380
|
function writeMihomoConfig(configObj) {
|
|
4264
4381
|
ensureDirs();
|
|
@@ -4267,22 +4384,32 @@ function writeMihomoConfig(configObj) {
|
|
|
4267
4384
|
}
|
|
4268
4385
|
function writeDebugConfig(buildResult) {
|
|
4269
4386
|
ensureDirs();
|
|
4270
|
-
|
|
4387
|
+
fs5.writeFileSync(PATHS.configStage1Subscription, dumpYaml(buildResult.subscriptionConfig), { mode: 384 });
|
|
4271
4388
|
const overwriteMerged = {};
|
|
4272
4389
|
for (const f of buildResult.overwriteFiles) {
|
|
4273
4390
|
Object.assign(overwriteMerged, f.config);
|
|
4274
4391
|
}
|
|
4275
4392
|
const overwriteContent = buildResult.overwriteFiles.length > 0 ? dumpYaml(overwriteMerged) : "# overwrite \u5DF2\u7981\u7528\u6216\u65E0\u8986\u5199\u6587\u4EF6\n";
|
|
4276
|
-
|
|
4277
|
-
|
|
4393
|
+
fs5.writeFileSync(PATHS.configStage2Overwrite, overwriteContent, { mode: 384 });
|
|
4394
|
+
fs5.writeFileSync(PATHS.configStage3System, dumpYaml(buildResult.systemConfig), { mode: 384 });
|
|
4395
|
+
const sshMerged = {};
|
|
4396
|
+
for (const f of buildResult.sshFiles) {
|
|
4397
|
+
Object.assign(sshMerged, f.config);
|
|
4398
|
+
}
|
|
4399
|
+
const sshTunnels = getSshTunnels();
|
|
4400
|
+
if (sshTunnels.length > 0) {
|
|
4401
|
+
sshMerged["~proxies"] = sshTunnels.map(renderSshProxy);
|
|
4402
|
+
}
|
|
4403
|
+
const sshContent = Object.keys(sshMerged).length > 0 ? dumpYaml(sshMerged) : "# \u672A\u914D\u7F6E ssh \u96A7\u9053\n";
|
|
4404
|
+
fs5.writeFileSync(PATHS.configStage4Ssh, sshContent, { mode: 384 });
|
|
4278
4405
|
}
|
|
4279
4406
|
function hasConfig() {
|
|
4280
|
-
return
|
|
4407
|
+
return fs5.existsSync(PATHS.configFile);
|
|
4281
4408
|
}
|
|
4282
4409
|
function getConfigInfo() {
|
|
4283
4410
|
if (!hasConfig()) return null;
|
|
4284
4411
|
try {
|
|
4285
|
-
const content =
|
|
4412
|
+
const content = fs5.readFileSync(PATHS.configFile, "utf8");
|
|
4286
4413
|
const cfg = loadYamlSafe(content);
|
|
4287
4414
|
if (!cfg) return null;
|
|
4288
4415
|
const proxies = cfg.proxies;
|
|
@@ -4302,7 +4429,7 @@ function getConfigInfo() {
|
|
|
4302
4429
|
}
|
|
4303
4430
|
}
|
|
4304
4431
|
function hasKernel() {
|
|
4305
|
-
return
|
|
4432
|
+
return fs5.existsSync(PATHS.mihomoBinary);
|
|
4306
4433
|
}
|
|
4307
4434
|
var kernelVersionCache = null;
|
|
4308
4435
|
var kernelVersionCached = false;
|
|
@@ -4378,13 +4505,13 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\
|
|
|
4378
4505
|
" mihomo start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
|
|
4379
4506
|
" mihomo start -u 30000 # \u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 30 \u79D2 (\u9ED8\u8BA4 10s)",
|
|
4380
4507
|
" mihomo daemon on # \u5F00\u542F\u4FDD\u6D3B\uFF08\u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F\uFF09",
|
|
4381
|
-
" mihomo
|
|
4508
|
+
" mihomo ssh add work --host m4 --port 1080 # \u52A0 ssh \u96A7\u9053\u51FA\u53E3",
|
|
4382
4509
|
" mihomo sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
|
|
4383
4510
|
" mihomo ui # \u6253\u5F00 Web UI",
|
|
4384
4511
|
"",
|
|
4385
4512
|
`${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
|
|
4386
4513
|
" tun = start tun use = sub use on/off = ow on/off open = dir open",
|
|
4387
|
-
" up = start down = stop upd/upgrade = update
|
|
4514
|
+
" up = start down = stop upd/upgrade = update",
|
|
4388
4515
|
"",
|
|
4389
4516
|
`${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
|
|
4390
4517
|
" mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)",
|
|
@@ -4410,13 +4537,13 @@ function printVersion() {
|
|
|
4410
4537
|
|
|
4411
4538
|
// src/daemon.ts
|
|
4412
4539
|
import { spawnSync as spawnSync3 } from "child_process";
|
|
4413
|
-
import
|
|
4414
|
-
import
|
|
4540
|
+
import fs7 from "fs";
|
|
4541
|
+
import path6 from "path";
|
|
4415
4542
|
|
|
4416
4543
|
// src/process.ts
|
|
4417
4544
|
import { spawn, spawnSync as spawnSync2 } from "child_process";
|
|
4418
|
-
import
|
|
4419
|
-
import
|
|
4545
|
+
import fs6 from "fs";
|
|
4546
|
+
import path5 from "path";
|
|
4420
4547
|
|
|
4421
4548
|
// src/lifecycle.ts
|
|
4422
4549
|
var cleanupFns = /* @__PURE__ */ new Set();
|
|
@@ -4481,15 +4608,15 @@ function isProcessRoot(pid) {
|
|
|
4481
4608
|
}
|
|
4482
4609
|
var MAIN_INSTANCE_PATTERN = `${escapeRegExp(PATHS.mihomoBinary)}.*${escapeRegExp(PATHS.configFile)}`;
|
|
4483
4610
|
function clearRuntime() {
|
|
4484
|
-
if (
|
|
4611
|
+
if (fs6.existsSync(DIRS.runtime)) {
|
|
4485
4612
|
rmrf(DIRS.runtime);
|
|
4486
4613
|
}
|
|
4487
4614
|
ensureDirs();
|
|
4488
4615
|
}
|
|
4489
4616
|
function getPid() {
|
|
4490
|
-
if (!
|
|
4617
|
+
if (!fs6.existsSync(PATHS.pidFile)) return null;
|
|
4491
4618
|
try {
|
|
4492
|
-
const pid = parseInt(
|
|
4619
|
+
const pid = parseInt(fs6.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
|
|
4493
4620
|
return pid > 0 ? pid : null;
|
|
4494
4621
|
} catch {
|
|
4495
4622
|
return null;
|
|
@@ -4511,9 +4638,9 @@ function getMihomoPids() {
|
|
|
4511
4638
|
}
|
|
4512
4639
|
}
|
|
4513
4640
|
function isPidFileOwnedByRoot() {
|
|
4514
|
-
if (!
|
|
4641
|
+
if (!fs6.existsSync(PATHS.pidFile)) return false;
|
|
4515
4642
|
try {
|
|
4516
|
-
const stat =
|
|
4643
|
+
const stat = fs6.statSync(PATHS.pidFile);
|
|
4517
4644
|
return stat.uid === 0;
|
|
4518
4645
|
} catch {
|
|
4519
4646
|
return false;
|
|
@@ -4536,10 +4663,10 @@ function hasRootResidue() {
|
|
|
4536
4663
|
}
|
|
4537
4664
|
function savePid(pid) {
|
|
4538
4665
|
ensureDirs();
|
|
4539
|
-
|
|
4666
|
+
fs6.writeFileSync(PATHS.pidFile, pid.toString(), { mode: 384 });
|
|
4540
4667
|
}
|
|
4541
4668
|
function clearPid() {
|
|
4542
|
-
if (!
|
|
4669
|
+
if (!fs6.existsSync(PATHS.pidFile)) return;
|
|
4543
4670
|
if (isPidFileOwnedByRoot()) {
|
|
4544
4671
|
try {
|
|
4545
4672
|
spawnSync2("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
|
|
@@ -4547,7 +4674,7 @@ function clearPid() {
|
|
|
4547
4674
|
}
|
|
4548
4675
|
} else {
|
|
4549
4676
|
try {
|
|
4550
|
-
|
|
4677
|
+
fs6.unlinkSync(PATHS.pidFile);
|
|
4551
4678
|
} catch {
|
|
4552
4679
|
}
|
|
4553
4680
|
}
|
|
@@ -4661,9 +4788,9 @@ echo "--- \u65E5\u5FD7 ---"
|
|
|
4661
4788
|
tail -25 "\${LOG_FILE}" 2>/dev/null
|
|
4662
4789
|
exit 2
|
|
4663
4790
|
`;
|
|
4664
|
-
const scriptPath =
|
|
4665
|
-
|
|
4666
|
-
|
|
4791
|
+
const scriptPath = path5.join(DIRS.runtime, "launch-tun.sh");
|
|
4792
|
+
fs6.writeFileSync(scriptPath, scriptContent, { mode: 448 });
|
|
4793
|
+
fs6.chmodSync(scriptPath, 448);
|
|
4667
4794
|
return scriptPath;
|
|
4668
4795
|
}
|
|
4669
4796
|
function getProcessInfo(pid) {
|
|
@@ -4701,11 +4828,11 @@ async function start(mode = "mixed") {
|
|
|
4701
4828
|
ensureDirs();
|
|
4702
4829
|
rotateAndCleanupLogs();
|
|
4703
4830
|
const binary = PATHS.mihomoBinary;
|
|
4704
|
-
if (!
|
|
4831
|
+
if (!fs6.existsSync(binary)) {
|
|
4705
4832
|
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
|
|
4706
4833
|
}
|
|
4707
4834
|
const configFile = PATHS.configFile;
|
|
4708
|
-
if (!
|
|
4835
|
+
if (!fs6.existsSync(configFile)) {
|
|
4709
4836
|
throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
|
|
4710
4837
|
}
|
|
4711
4838
|
const staleState = checkStaleState();
|
|
@@ -4734,24 +4861,24 @@ async function startMixedMode(staleState) {
|
|
|
4734
4861
|
const configFile = PATHS.configFile;
|
|
4735
4862
|
const logFile = PATHS.logFile;
|
|
4736
4863
|
const args = ["-d", DIRS.data, "-f", configFile];
|
|
4737
|
-
if (
|
|
4864
|
+
if (fs6.existsSync(logFile)) {
|
|
4738
4865
|
try {
|
|
4739
|
-
|
|
4866
|
+
fs6.accessSync(logFile, fs6.constants.W_OK);
|
|
4740
4867
|
} catch {
|
|
4741
4868
|
try {
|
|
4742
|
-
|
|
4869
|
+
fs6.unlinkSync(logFile);
|
|
4743
4870
|
} catch {
|
|
4744
4871
|
}
|
|
4745
4872
|
}
|
|
4746
4873
|
}
|
|
4747
|
-
const logFd =
|
|
4874
|
+
const logFd = fs6.openSync(logFile, "a");
|
|
4748
4875
|
const child = spawn(PATHS.mihomoBinary, args, {
|
|
4749
4876
|
detached: true,
|
|
4750
4877
|
stdio: ["ignore", logFd, logFd]
|
|
4751
4878
|
});
|
|
4752
4879
|
child.on("error", () => {
|
|
4753
4880
|
});
|
|
4754
|
-
|
|
4881
|
+
fs6.closeSync(logFd);
|
|
4755
4882
|
child.unref();
|
|
4756
4883
|
const pid = child.pid;
|
|
4757
4884
|
if (!pid) {
|
|
@@ -4763,9 +4890,9 @@ async function startMixedMode(staleState) {
|
|
|
4763
4890
|
if (!isRunning()) {
|
|
4764
4891
|
clearPid();
|
|
4765
4892
|
let errorMsg = "\u542F\u52A8\u5931\u8D25";
|
|
4766
|
-
if (
|
|
4893
|
+
if (fs6.existsSync(logFile)) {
|
|
4767
4894
|
try {
|
|
4768
|
-
const logs =
|
|
4895
|
+
const logs = fs6.readFileSync(logFile, "utf8").slice(-3e3);
|
|
4769
4896
|
if (logs.trim()) {
|
|
4770
4897
|
errorMsg += "\n\u6700\u8FD1\u7684\u65E5\u5FD7:\n" + logs.split("\n").map((l) => ` ${l}`).join("\n");
|
|
4771
4898
|
}
|
|
@@ -4792,7 +4919,7 @@ async function startTunMode(staleState) {
|
|
|
4792
4919
|
}
|
|
4793
4920
|
} catch (e) {
|
|
4794
4921
|
try {
|
|
4795
|
-
|
|
4922
|
+
fs6.unlinkSync(launchScript);
|
|
4796
4923
|
} catch {
|
|
4797
4924
|
}
|
|
4798
4925
|
if (e.status === 1) {
|
|
@@ -4804,7 +4931,7 @@ async function startTunMode(staleState) {
|
|
|
4804
4931
|
throw new Error(e.message);
|
|
4805
4932
|
}
|
|
4806
4933
|
try {
|
|
4807
|
-
|
|
4934
|
+
fs6.unlinkSync(launchScript);
|
|
4808
4935
|
} catch {
|
|
4809
4936
|
}
|
|
4810
4937
|
await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
|
|
@@ -4843,18 +4970,18 @@ function getLogPath() {
|
|
|
4843
4970
|
}
|
|
4844
4971
|
function rotateLog() {
|
|
4845
4972
|
const logFile = PATHS.logFile;
|
|
4846
|
-
if (!
|
|
4847
|
-
const stat =
|
|
4973
|
+
if (!fs6.existsSync(logFile)) return null;
|
|
4974
|
+
const stat = fs6.statSync(logFile);
|
|
4848
4975
|
if (stat.size === 0) return null;
|
|
4849
4976
|
const rotatedName = `mihomo.${formatLocalTimestamp()}.log`;
|
|
4850
|
-
const rotatedPath =
|
|
4851
|
-
|
|
4977
|
+
const rotatedPath = path5.join(DIRS.logs, rotatedName);
|
|
4978
|
+
fs6.renameSync(logFile, rotatedPath);
|
|
4852
4979
|
return rotatedPath;
|
|
4853
4980
|
}
|
|
4854
4981
|
function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
|
|
4855
4982
|
const logsDir = DIRS.logs;
|
|
4856
|
-
if (!
|
|
4857
|
-
const files =
|
|
4983
|
+
if (!fs6.existsSync(logsDir)) return { deleted: 0, errors: 0 };
|
|
4984
|
+
const files = fs6.readdirSync(logsDir);
|
|
4858
4985
|
const now = Date.now();
|
|
4859
4986
|
const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
|
|
4860
4987
|
let deleted = 0;
|
|
@@ -4862,10 +4989,10 @@ function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
|
|
|
4862
4989
|
for (const file of files) {
|
|
4863
4990
|
if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.log$/)) continue;
|
|
4864
4991
|
try {
|
|
4865
|
-
const filePath =
|
|
4866
|
-
const stat =
|
|
4992
|
+
const filePath = path5.join(logsDir, file);
|
|
4993
|
+
const stat = fs6.statSync(filePath);
|
|
4867
4994
|
if (now - stat.mtimeMs > maxAgeMs) {
|
|
4868
|
-
|
|
4995
|
+
fs6.unlinkSync(filePath);
|
|
4869
4996
|
deleted++;
|
|
4870
4997
|
}
|
|
4871
4998
|
} catch {
|
|
@@ -4877,8 +5004,8 @@ function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
|
|
|
4877
5004
|
function listLogs() {
|
|
4878
5005
|
const logsDir = DIRS.logs;
|
|
4879
5006
|
const result = { current: null, archives: [] };
|
|
4880
|
-
if (
|
|
4881
|
-
const stat =
|
|
5007
|
+
if (fs6.existsSync(PATHS.logFile)) {
|
|
5008
|
+
const stat = fs6.statSync(PATHS.logFile);
|
|
4882
5009
|
result.current = {
|
|
4883
5010
|
name: "mihomo.log (\u5F53\u524D)",
|
|
4884
5011
|
path: PATHS.logFile,
|
|
@@ -4887,14 +5014,14 @@ function listLogs() {
|
|
|
4887
5014
|
isCurrent: true
|
|
4888
5015
|
};
|
|
4889
5016
|
}
|
|
4890
|
-
if (!
|
|
4891
|
-
const files =
|
|
5017
|
+
if (!fs6.existsSync(logsDir)) return result;
|
|
5018
|
+
const files = fs6.readdirSync(logsDir);
|
|
4892
5019
|
for (const file of files) {
|
|
4893
5020
|
const match = file.match(/^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})\.log$/);
|
|
4894
5021
|
if (!match) continue;
|
|
4895
5022
|
try {
|
|
4896
|
-
const filePath =
|
|
4897
|
-
const stat =
|
|
5023
|
+
const filePath = path5.join(logsDir, file);
|
|
5024
|
+
const stat = fs6.statSync(filePath);
|
|
4898
5025
|
result.archives.push({
|
|
4899
5026
|
name: file,
|
|
4900
5027
|
path: filePath,
|
|
@@ -4909,22 +5036,22 @@ function listLogs() {
|
|
|
4909
5036
|
return result;
|
|
4910
5037
|
}
|
|
4911
5038
|
function isPathUnderDir(filePath, baseDir) {
|
|
4912
|
-
const resolvedPath =
|
|
4913
|
-
const resolvedBase =
|
|
4914
|
-
return resolvedPath === resolvedBase || resolvedPath.startsWith(resolvedBase +
|
|
5039
|
+
const resolvedPath = path5.resolve(filePath);
|
|
5040
|
+
const resolvedBase = path5.resolve(baseDir);
|
|
5041
|
+
return resolvedPath === resolvedBase || resolvedPath.startsWith(resolvedBase + path5.sep);
|
|
4915
5042
|
}
|
|
4916
5043
|
function getLogPathByName(name) {
|
|
4917
5044
|
const logsDir = DIRS.logs;
|
|
4918
5045
|
let targetName = name;
|
|
4919
5046
|
if (!name.endsWith(".log")) targetName = `mihomo.${name}.log`;
|
|
4920
5047
|
if (!targetName.startsWith("mihomo.")) targetName = `mihomo.${targetName}`;
|
|
4921
|
-
const filePath =
|
|
4922
|
-
if (
|
|
4923
|
-
if (
|
|
4924
|
-
const files =
|
|
5048
|
+
const filePath = path5.join(logsDir, targetName);
|
|
5049
|
+
if (fs6.existsSync(filePath) && isPathUnderDir(filePath, logsDir)) return filePath;
|
|
5050
|
+
if (fs6.existsSync(logsDir)) {
|
|
5051
|
+
const files = fs6.readdirSync(logsDir);
|
|
4925
5052
|
for (const file of files) {
|
|
4926
5053
|
if (file.includes(name)) {
|
|
4927
|
-
const candidatePath =
|
|
5054
|
+
const candidatePath = path5.join(logsDir, file);
|
|
4928
5055
|
if (isPathUnderDir(candidatePath, logsDir)) return candidatePath;
|
|
4929
5056
|
}
|
|
4930
5057
|
}
|
|
@@ -4991,7 +5118,7 @@ var DAEMON_BOOT_WAIT_MS = 500;
|
|
|
4991
5118
|
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
4992
5119
|
function logOversized() {
|
|
4993
5120
|
try {
|
|
4994
|
-
return
|
|
5121
|
+
return fs7.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
4995
5122
|
} catch {
|
|
4996
5123
|
return false;
|
|
4997
5124
|
}
|
|
@@ -5031,9 +5158,9 @@ function runSudoScript(scriptBody, opts) {
|
|
|
5031
5158
|
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
5159
|
}
|
|
5033
5160
|
ensureDirs();
|
|
5034
|
-
const scriptPath =
|
|
5035
|
-
|
|
5036
|
-
|
|
5161
|
+
const scriptPath = path6.join(DIRS.runtime, opts.file);
|
|
5162
|
+
fs7.writeFileSync(scriptPath, scriptBody, { mode: 448 });
|
|
5163
|
+
fs7.chmodSync(scriptPath, 448);
|
|
5037
5164
|
try {
|
|
5038
5165
|
const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
5039
5166
|
if (result.error) throw result.error;
|
|
@@ -5049,13 +5176,13 @@ function runSudoScript(scriptBody, opts) {
|
|
|
5049
5176
|
}
|
|
5050
5177
|
} finally {
|
|
5051
5178
|
try {
|
|
5052
|
-
|
|
5179
|
+
fs7.unlinkSync(scriptPath);
|
|
5053
5180
|
} catch {
|
|
5054
5181
|
}
|
|
5055
5182
|
}
|
|
5056
5183
|
}
|
|
5057
5184
|
function isDaemonEnabled() {
|
|
5058
|
-
return
|
|
5185
|
+
return fs7.existsSync(PATHS.launchDaemonPlist);
|
|
5059
5186
|
}
|
|
5060
5187
|
function getDaemonStatus() {
|
|
5061
5188
|
if (!isDaemonEnabled()) {
|
|
@@ -5069,14 +5196,14 @@ function isDaemonRunning(status) {
|
|
|
5069
5196
|
}
|
|
5070
5197
|
function enableDaemon() {
|
|
5071
5198
|
assertDaemonLabelSafe();
|
|
5072
|
-
if (!
|
|
5199
|
+
if (!fs7.existsSync(PATHS.mihomoBinary)) {
|
|
5073
5200
|
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
|
|
5074
5201
|
}
|
|
5075
|
-
if (!
|
|
5202
|
+
if (!fs7.existsSync(PATHS.configFile)) {
|
|
5076
5203
|
throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
|
|
5077
5204
|
}
|
|
5078
5205
|
ensureDirs();
|
|
5079
|
-
const stagePath =
|
|
5206
|
+
const stagePath = path6.join(DIRS.runtime, "daemon.plist.stage");
|
|
5080
5207
|
atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
|
|
5081
5208
|
const target = shellQuote(SERVICE_TARGET);
|
|
5082
5209
|
const plistDest = shellQuote(PATHS.launchDaemonPlist);
|
|
@@ -5108,7 +5235,7 @@ function enableDaemon() {
|
|
|
5108
5235
|
});
|
|
5109
5236
|
} finally {
|
|
5110
5237
|
try {
|
|
5111
|
-
|
|
5238
|
+
fs7.unlinkSync(stagePath);
|
|
5112
5239
|
} catch {
|
|
5113
5240
|
}
|
|
5114
5241
|
}
|
|
@@ -5169,14 +5296,14 @@ async function tryHotReload() {
|
|
|
5169
5296
|
}
|
|
5170
5297
|
}
|
|
5171
5298
|
async function restartDaemon() {
|
|
5172
|
-
if (!
|
|
5299
|
+
if (!fs7.existsSync(PATHS.launchDaemonPlist)) {
|
|
5173
5300
|
throw new CliError("\u4FDD\u6D3B\u672A\u542F\u7528\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u542F\u7528\u4FDD\u6D3B: mihomo daemon on" });
|
|
5174
5301
|
}
|
|
5175
5302
|
if (!logOversized() && await tryHotReload()) return;
|
|
5176
5303
|
const target = shellQuote(SERVICE_TARGET);
|
|
5177
5304
|
const plistDest = shellQuote(PATHS.launchDaemonPlist);
|
|
5178
5305
|
const logFile = shellQuote(PATHS.logFile);
|
|
5179
|
-
const archiveFile = shellQuote(
|
|
5306
|
+
const archiveFile = shellQuote(path6.join(DIRS.logs, `mihomo.${formatLocalTimestamp()}.log`));
|
|
5180
5307
|
const script = [
|
|
5181
5308
|
"#!/bin/bash",
|
|
5182
5309
|
`if [ -f ${logFile} ] && [ "$(stat -f%z ${logFile} 2>/dev/null || echo 0)" -gt ${LOG_ROTATE_MAX_BYTES} ]; then`,
|
|
@@ -5904,11 +6031,11 @@ function formatTestSummary(summary) {
|
|
|
5904
6031
|
return `\u7ED3\u679C: ${colors.green(`${summary.alive} \u5B58\u6D3B`)} / ${colors.red(`${summary.dead} \u5931\u8D25`)} / ${summary.total} \u603B\u8BA1`;
|
|
5905
6032
|
}
|
|
5906
6033
|
|
|
5907
|
-
// src/
|
|
6034
|
+
// src/ssh.ts
|
|
5908
6035
|
import { spawn as spawn2 } from "child_process";
|
|
5909
|
-
import
|
|
6036
|
+
import fs8 from "fs";
|
|
5910
6037
|
import net from "net";
|
|
5911
|
-
import
|
|
6038
|
+
import path7 from "path";
|
|
5912
6039
|
var PORT_PROBE_TIMEOUT_MS = 300;
|
|
5913
6040
|
var STOP_WAIT_ATTEMPTS = 20;
|
|
5914
6041
|
var STOP_WAIT_INTERVAL = 100;
|
|
@@ -5925,15 +6052,10 @@ function getReservedPorts() {
|
|
|
5925
6052
|
if (Number.isInteger(testController)) reserved.set(testController, "\u6D4B\u901F\u5B9E\u4F8B\u63A7\u5236\u5668\u7AEF\u53E3");
|
|
5926
6053
|
return reserved;
|
|
5927
6054
|
}
|
|
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
6055
|
var SAFE_HOST_RE = /^[A-Za-z0-9][A-Za-z0-9._@-]*$/;
|
|
5934
|
-
function
|
|
6056
|
+
function validateSshHost(host) {
|
|
5935
6057
|
if (!host) {
|
|
5936
|
-
throw new CliError("\u7F3A\u5C11 --host", { hint: ["\u4F8B\u5982: mihomo
|
|
6058
|
+
throw new CliError("\u7F3A\u5C11 --host", { hint: ["\u4F8B\u5982: mihomo ssh add work --host m4 --port 1080"] });
|
|
5937
6059
|
}
|
|
5938
6060
|
if (host.startsWith("-")) {
|
|
5939
6061
|
throw new CliError(`\u4E3B\u673A\u540D\u65E0\u6548: "${host}"`, {
|
|
@@ -5948,7 +6070,7 @@ function validateTunnelHost(host) {
|
|
|
5948
6070
|
});
|
|
5949
6071
|
}
|
|
5950
6072
|
}
|
|
5951
|
-
function
|
|
6073
|
+
function validateSshPort(port, exclude) {
|
|
5952
6074
|
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
5953
6075
|
throw new CliError(`\u7AEF\u53E3\u65E0\u6548: ${port}\uFF0C\u9700\u4E3A 1-65535 \u7684\u6574\u6570`);
|
|
5954
6076
|
}
|
|
@@ -5959,64 +6081,53 @@ function validateTunnelPort(port, exclude) {
|
|
|
5959
6081
|
hint: ["\u8BF7\u6362\u4E00\u4E2A\u7AEF\u53E3\uFF0C\u4F8B\u5982 1080\u3002"]
|
|
5960
6082
|
});
|
|
5961
6083
|
}
|
|
5962
|
-
const conflict =
|
|
6084
|
+
const conflict = getSshTunnels().find((t) => t.port === port && t.name !== exclude);
|
|
5963
6085
|
if (conflict) {
|
|
5964
6086
|
throw new CliError(`\u7AEF\u53E3 ${port} \u5DF2\u88AB\u96A7\u9053 "${conflict.name}" \u4F7F\u7528`, { label: "\u7AEF\u53E3\u51B2\u7A81" });
|
|
5965
6087
|
}
|
|
5966
6088
|
}
|
|
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);
|
|
6089
|
+
function findSshTunnel(name) {
|
|
6090
|
+
return getSshTunnels().find((t) => t.name === name);
|
|
5980
6091
|
}
|
|
5981
|
-
function
|
|
5982
|
-
|
|
5983
|
-
|
|
5984
|
-
|
|
6092
|
+
function addSshTunnel(config) {
|
|
6093
|
+
validateSshName(config.name);
|
|
6094
|
+
validateSshHost(config.host);
|
|
6095
|
+
validateSshPort(config.port);
|
|
5985
6096
|
let duplicate = false;
|
|
5986
6097
|
updateSettings(() => {
|
|
5987
|
-
const tunnels = [...
|
|
6098
|
+
const tunnels = [...getSshTunnels()];
|
|
5988
6099
|
if (tunnels.some((t) => t.name === config.name)) {
|
|
5989
6100
|
duplicate = true;
|
|
5990
6101
|
return {};
|
|
5991
6102
|
}
|
|
5992
6103
|
tunnels.push(config);
|
|
5993
|
-
return { tunnels };
|
|
6104
|
+
return { ssh: tunnels };
|
|
5994
6105
|
});
|
|
5995
6106
|
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
|
|
6107
|
+
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
6108
|
}
|
|
5998
6109
|
}
|
|
5999
|
-
function
|
|
6110
|
+
function removeSshTunnel(name) {
|
|
6000
6111
|
let found = false;
|
|
6001
6112
|
updateSettings(() => {
|
|
6002
|
-
const tunnels = [...
|
|
6113
|
+
const tunnels = [...getSshTunnels()];
|
|
6003
6114
|
const idx = tunnels.findIndex((t) => t.name === name);
|
|
6004
6115
|
if (idx < 0) return {};
|
|
6005
6116
|
found = true;
|
|
6006
6117
|
tunnels.splice(idx, 1);
|
|
6007
|
-
return { tunnels };
|
|
6118
|
+
return { ssh: tunnels };
|
|
6008
6119
|
});
|
|
6009
6120
|
if (!found) return false;
|
|
6010
|
-
|
|
6121
|
+
clearSshRuntime(name);
|
|
6011
6122
|
return true;
|
|
6012
6123
|
}
|
|
6013
|
-
function
|
|
6014
|
-
|
|
6015
|
-
return
|
|
6124
|
+
function getSshRuntimePath(name) {
|
|
6125
|
+
validateSshName(name);
|
|
6126
|
+
return path7.join(DIRS.ssh, `${name}.json`);
|
|
6016
6127
|
}
|
|
6017
|
-
function
|
|
6128
|
+
function readSshRuntime(name) {
|
|
6018
6129
|
try {
|
|
6019
|
-
const raw =
|
|
6130
|
+
const raw = fs8.readFileSync(getSshRuntimePath(name), "utf8");
|
|
6020
6131
|
const parsed = JSON.parse(raw);
|
|
6021
6132
|
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
6022
6133
|
const r = parsed;
|
|
@@ -6031,13 +6142,13 @@ function readTunnelRuntime(name) {
|
|
|
6031
6142
|
return null;
|
|
6032
6143
|
}
|
|
6033
6144
|
}
|
|
6034
|
-
function
|
|
6145
|
+
function writeSshRuntime(name, runtime) {
|
|
6035
6146
|
ensureDirs();
|
|
6036
|
-
atomicWriteFileSync(
|
|
6147
|
+
atomicWriteFileSync(getSshRuntimePath(name), JSON.stringify(runtime, null, 2), { mode: 384 });
|
|
6037
6148
|
}
|
|
6038
|
-
function
|
|
6149
|
+
function clearSshRuntime(name) {
|
|
6039
6150
|
try {
|
|
6040
|
-
|
|
6151
|
+
fs8.rmSync(getSshRuntimePath(name), { force: true });
|
|
6041
6152
|
} catch {
|
|
6042
6153
|
}
|
|
6043
6154
|
}
|
|
@@ -6062,11 +6173,11 @@ function buildSshArgs(tunnel) {
|
|
|
6062
6173
|
function commandNeedle(port) {
|
|
6063
6174
|
return `-D 127.0.0.1:${port}`;
|
|
6064
6175
|
}
|
|
6065
|
-
function
|
|
6066
|
-
|
|
6067
|
-
return
|
|
6176
|
+
function getSshLogPath(name) {
|
|
6177
|
+
validateSshName(name);
|
|
6178
|
+
return path7.join(DIRS.logs, `ssh-${name}.log`);
|
|
6068
6179
|
}
|
|
6069
|
-
function
|
|
6180
|
+
function isSshProcessAlive(pid, port) {
|
|
6070
6181
|
return isProcessRunning(pid) && isProcessCommandMatching(pid, commandNeedle(port));
|
|
6071
6182
|
}
|
|
6072
6183
|
function isPortListening(port, timeoutMs = PORT_PROBE_TIMEOUT_MS) {
|
|
@@ -6086,9 +6197,9 @@ function isPortListening(port, timeoutMs = PORT_PROBE_TIMEOUT_MS) {
|
|
|
6086
6197
|
socket.connect(port, "127.0.0.1");
|
|
6087
6198
|
});
|
|
6088
6199
|
}
|
|
6089
|
-
async function
|
|
6090
|
-
const runtime =
|
|
6091
|
-
const alive = runtime !== null &&
|
|
6200
|
+
async function getSshStatus(config) {
|
|
6201
|
+
const runtime = readSshRuntime(config.name);
|
|
6202
|
+
const alive = runtime !== null && isSshProcessAlive(runtime.pid, runtime.port || config.port);
|
|
6092
6203
|
if (!alive) {
|
|
6093
6204
|
return { config, state: "stopped", pid: null, started_by: null, started_at: null };
|
|
6094
6205
|
}
|
|
@@ -6101,22 +6212,22 @@ async function getTunnelStatus(config) {
|
|
|
6101
6212
|
started_at: runtime.started_at || null
|
|
6102
6213
|
};
|
|
6103
6214
|
}
|
|
6104
|
-
async function
|
|
6105
|
-
return Promise.all(
|
|
6215
|
+
async function getAllSshStatus() {
|
|
6216
|
+
return Promise.all(getSshTunnels().map(getSshStatus));
|
|
6106
6217
|
}
|
|
6107
|
-
async function
|
|
6108
|
-
const config =
|
|
6218
|
+
async function startSshTunnel(name, options) {
|
|
6219
|
+
const config = findSshTunnel(name);
|
|
6109
6220
|
if (!config) {
|
|
6110
|
-
throw new CliError(`\u672A\u627E\u5230\u96A7\u9053 "${name}"`, { hint: ["\u67E5\u770B\u5168\u90E8\u96A7\u9053: mihomo
|
|
6221
|
+
throw new CliError(`\u672A\u627E\u5230\u96A7\u9053 "${name}"`, { hint: ["\u67E5\u770B\u5168\u90E8\u96A7\u9053: mihomo ssh"] });
|
|
6111
6222
|
}
|
|
6112
|
-
const existing =
|
|
6113
|
-
if (existing &&
|
|
6223
|
+
const existing = readSshRuntime(name);
|
|
6224
|
+
if (existing && isSshProcessAlive(existing.pid, existing.port || config.port)) {
|
|
6114
6225
|
if (options.startedBy === "manual" && existing.started_by === "auto") {
|
|
6115
|
-
|
|
6226
|
+
writeSshRuntime(name, { ...existing, started_by: "manual" });
|
|
6116
6227
|
}
|
|
6117
6228
|
return { alreadyRunning: true, pid: existing.pid };
|
|
6118
6229
|
}
|
|
6119
|
-
if (existing)
|
|
6230
|
+
if (existing) clearSshRuntime(name);
|
|
6120
6231
|
if (await isPortListening(config.port)) {
|
|
6121
6232
|
throw new CliError(`\u7AEF\u53E3 ${config.port} \u5DF2\u88AB\u5360\u7528`, {
|
|
6122
6233
|
label: "\u65E0\u6CD5\u542F\u52A8\u96A7\u9053",
|
|
@@ -6124,21 +6235,21 @@ async function startTunnel(name, options) {
|
|
|
6124
6235
|
});
|
|
6125
6236
|
}
|
|
6126
6237
|
ensureDirs();
|
|
6127
|
-
const logPath =
|
|
6128
|
-
const logFd =
|
|
6238
|
+
const logPath = getSshLogPath(name);
|
|
6239
|
+
const logFd = fs8.openSync(logPath, "w");
|
|
6129
6240
|
const child = spawn2("ssh", buildSshArgs(config), {
|
|
6130
6241
|
detached: true,
|
|
6131
6242
|
stdio: ["ignore", logFd, logFd]
|
|
6132
6243
|
});
|
|
6133
6244
|
child.on("error", () => {
|
|
6134
6245
|
});
|
|
6135
|
-
|
|
6246
|
+
fs8.closeSync(logFd);
|
|
6136
6247
|
child.unref();
|
|
6137
6248
|
const pid = child.pid;
|
|
6138
6249
|
if (!pid) {
|
|
6139
6250
|
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
6251
|
}
|
|
6141
|
-
|
|
6252
|
+
writeSshRuntime(name, {
|
|
6142
6253
|
pid,
|
|
6143
6254
|
started_by: options.startedBy,
|
|
6144
6255
|
started_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -6149,7 +6260,7 @@ async function startTunnel(name, options) {
|
|
|
6149
6260
|
process.kill(pid, "SIGKILL");
|
|
6150
6261
|
} catch {
|
|
6151
6262
|
}
|
|
6152
|
-
|
|
6263
|
+
clearSshRuntime(name);
|
|
6153
6264
|
});
|
|
6154
6265
|
try {
|
|
6155
6266
|
for (let i = 0; i < START_WAIT_ATTEMPTS; i++) {
|
|
@@ -6163,7 +6274,7 @@ async function startTunnel(name, options) {
|
|
|
6163
6274
|
} finally {
|
|
6164
6275
|
unregisterCleanup();
|
|
6165
6276
|
}
|
|
6166
|
-
|
|
6277
|
+
clearSshRuntime(name);
|
|
6167
6278
|
if (isProcessRunning(pid)) {
|
|
6168
6279
|
try {
|
|
6169
6280
|
process.kill(pid, "SIGKILL");
|
|
@@ -6177,24 +6288,24 @@ async function startTunnel(name, options) {
|
|
|
6177
6288
|
}
|
|
6178
6289
|
function readLogTail(logPath, maxLines = 5) {
|
|
6179
6290
|
try {
|
|
6180
|
-
const content =
|
|
6291
|
+
const content = fs8.readFileSync(logPath, "utf8").trim();
|
|
6181
6292
|
if (!content) return [];
|
|
6182
6293
|
return content.split("\n").slice(-maxLines).map((line) => ` ${line.trim()}`);
|
|
6183
6294
|
} catch {
|
|
6184
6295
|
return [];
|
|
6185
6296
|
}
|
|
6186
6297
|
}
|
|
6187
|
-
function
|
|
6188
|
-
const config =
|
|
6189
|
-
const runtime =
|
|
6298
|
+
function stopSshTunnel(name) {
|
|
6299
|
+
const config = findSshTunnel(name);
|
|
6300
|
+
const runtime = readSshRuntime(name);
|
|
6190
6301
|
if (!runtime) {
|
|
6191
|
-
|
|
6302
|
+
clearSshRuntime(name);
|
|
6192
6303
|
return { notRunning: true, pid: null };
|
|
6193
6304
|
}
|
|
6194
6305
|
const port = runtime.port || config?.port || 0;
|
|
6195
6306
|
const { pid } = runtime;
|
|
6196
|
-
if (!
|
|
6197
|
-
|
|
6307
|
+
if (!isSshProcessAlive(pid, port)) {
|
|
6308
|
+
clearSshRuntime(name);
|
|
6198
6309
|
return { notRunning: true, pid: null };
|
|
6199
6310
|
}
|
|
6200
6311
|
try {
|
|
@@ -6215,15 +6326,15 @@ function stopTunnel(name) {
|
|
|
6215
6326
|
sleepSync(STOP_WAIT_INTERVAL);
|
|
6216
6327
|
}
|
|
6217
6328
|
}
|
|
6218
|
-
|
|
6329
|
+
clearSshRuntime(name);
|
|
6219
6330
|
return { notRunning: false, pid };
|
|
6220
6331
|
}
|
|
6221
|
-
async function
|
|
6332
|
+
async function startAutoSshTunnels() {
|
|
6222
6333
|
const outcomes = [];
|
|
6223
|
-
for (const tunnel of
|
|
6334
|
+
for (const tunnel of getSshTunnels()) {
|
|
6224
6335
|
if (!tunnel.auto) continue;
|
|
6225
6336
|
try {
|
|
6226
|
-
const result = await
|
|
6337
|
+
const result = await startSshTunnel(tunnel.name, { startedBy: "auto" });
|
|
6227
6338
|
outcomes.push({ name: tunnel.name, ok: true, alreadyRunning: result.alreadyRunning });
|
|
6228
6339
|
} catch (e) {
|
|
6229
6340
|
outcomes.push({
|
|
@@ -6235,63 +6346,24 @@ async function startAutoTunnels() {
|
|
|
6235
6346
|
}
|
|
6236
6347
|
return outcomes;
|
|
6237
6348
|
}
|
|
6238
|
-
function
|
|
6349
|
+
function stopAutoSshTunnels() {
|
|
6239
6350
|
const stopped = [];
|
|
6240
|
-
for (const tunnel of
|
|
6241
|
-
const runtime =
|
|
6351
|
+
for (const tunnel of getSshTunnels()) {
|
|
6352
|
+
const runtime = readSshRuntime(tunnel.name);
|
|
6242
6353
|
if (runtime?.started_by !== "auto") continue;
|
|
6243
|
-
const result =
|
|
6354
|
+
const result = stopSshTunnel(tunnel.name);
|
|
6244
6355
|
if (!result.notRunning) stopped.push(tunnel.name);
|
|
6245
6356
|
}
|
|
6246
6357
|
return stopped;
|
|
6247
6358
|
}
|
|
6248
|
-
function
|
|
6359
|
+
function stopAllSshTunnels() {
|
|
6249
6360
|
const stopped = [];
|
|
6250
|
-
for (const tunnel of
|
|
6251
|
-
const result =
|
|
6361
|
+
for (const tunnel of getSshTunnels()) {
|
|
6362
|
+
const result = stopSshTunnel(tunnel.name);
|
|
6252
6363
|
if (!result.notRunning) stopped.push(tunnel.name);
|
|
6253
6364
|
}
|
|
6254
6365
|
return stopped;
|
|
6255
6366
|
}
|
|
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
6367
|
|
|
6296
6368
|
// src/commands/status.ts
|
|
6297
6369
|
async function printStatus() {
|
|
@@ -6361,9 +6433,9 @@ async function printStatus() {
|
|
|
6361
6433
|
if (isDaemonEnabled()) {
|
|
6362
6434
|
console.log(`${colors.gray("\u4FDD\u6D3B: ")}${colors.green("\u5DF2\u542F\u7528")} ${colors.gray("(\u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F)")}`);
|
|
6363
6435
|
}
|
|
6364
|
-
const tunnels =
|
|
6436
|
+
const tunnels = getSshTunnels();
|
|
6365
6437
|
if (tunnels.length > 0) {
|
|
6366
|
-
const statuses = await
|
|
6438
|
+
const statuses = await getAllSshStatus();
|
|
6367
6439
|
const parts = statuses.map((s) => {
|
|
6368
6440
|
const label = `${s.config.name}:${s.config.port}`;
|
|
6369
6441
|
if (s.state === "running") return colors.green(label);
|
|
@@ -6381,8 +6453,8 @@ function handleStopResult(result) {
|
|
|
6381
6453
|
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
6454
|
}
|
|
6383
6455
|
}
|
|
6384
|
-
function
|
|
6385
|
-
const stopped =
|
|
6456
|
+
function stopAutoSshTunnelsWithLog() {
|
|
6457
|
+
const stopped = stopAutoSshTunnels();
|
|
6386
6458
|
if (stopped.length > 0) {
|
|
6387
6459
|
console.log(`${colors.green("\u5DF2\u505C\u6B62\u96A7\u9053")}: ${stopped.join(", ")}`);
|
|
6388
6460
|
}
|
|
@@ -6393,22 +6465,22 @@ async function cmdStop(args) {
|
|
|
6393
6465
|
console.log("\u76F4\u63A5\u505C\u6B62\u4F1A\u88AB\u81EA\u52A8\u91CD\u65B0\u62C9\u8D77\uFF0C\u8BF7\u7528: mihomo daemon off");
|
|
6394
6466
|
return;
|
|
6395
6467
|
}
|
|
6396
|
-
const
|
|
6468
|
+
const skipSsh = hasFlag(args, "--no-ssh");
|
|
6397
6469
|
const pids = getMihomoPids();
|
|
6398
6470
|
if (pids.length === 0) {
|
|
6399
6471
|
console.log(colors.yellow("\u4E0D\u5728\u8FD0\u884C"));
|
|
6400
|
-
if (!
|
|
6472
|
+
if (!skipSsh) stopAutoSshTunnelsWithLog();
|
|
6401
6473
|
return;
|
|
6402
6474
|
}
|
|
6403
6475
|
console.log(`\u505C\u6B62 ${pids.length} \u4E2A\u8FDB\u7A0B...`);
|
|
6404
6476
|
handleStopResult(stop());
|
|
6405
6477
|
console.log(colors.green("\u5DF2\u505C\u6B62\u8FDB\u7A0B"));
|
|
6406
|
-
if (!
|
|
6478
|
+
if (!skipSsh) stopAutoSshTunnelsWithLog();
|
|
6407
6479
|
}
|
|
6408
6480
|
|
|
6409
6481
|
// src/commands/start.ts
|
|
6410
|
-
async function
|
|
6411
|
-
const outcomes = await
|
|
6482
|
+
async function startAutoSshTunnelsWithWarning() {
|
|
6483
|
+
const outcomes = await startAutoSshTunnels();
|
|
6412
6484
|
if (outcomes.length === 0) return;
|
|
6413
6485
|
const started = outcomes.filter((o) => o.ok && !o.alreadyRunning);
|
|
6414
6486
|
if (started.length > 0) {
|
|
@@ -6422,7 +6494,7 @@ async function startAutoTunnelsWithWarning() {
|
|
|
6422
6494
|
if (line.trim()) console.log(colors.gray(line.startsWith(" ") ? line : ` ${line}`));
|
|
6423
6495
|
}
|
|
6424
6496
|
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
|
|
6497
|
+
console.log(colors.gray(` \u6392\u67E5: mihomo ssh status ${failed.name}`));
|
|
6426
6498
|
console.log("");
|
|
6427
6499
|
}
|
|
6428
6500
|
}
|
|
@@ -6444,7 +6516,7 @@ async function cmdStart(args) {
|
|
|
6444
6516
|
const concurrency = parseIntArg(args, "-j", "--concurrency", DEFAULT_TEST_CONCURRENCY);
|
|
6445
6517
|
const skipUpdate = hasFlag(args, "-s", "--no-update");
|
|
6446
6518
|
const skipClean = hasFlag(args, "--no-clean");
|
|
6447
|
-
const
|
|
6519
|
+
const skipSsh = hasFlag(args, "--no-ssh");
|
|
6448
6520
|
const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
|
|
6449
6521
|
const sub = requireActiveSubscription("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
|
|
6450
6522
|
if (!skipUpdate) {
|
|
@@ -6486,8 +6558,8 @@ async function cmdStart(args) {
|
|
|
6486
6558
|
const lines = e.message.split("\n");
|
|
6487
6559
|
throw new CliError(lines[0], { label: "\u542F\u52A8\u5931\u8D25", hint: lines.slice(1) });
|
|
6488
6560
|
}
|
|
6489
|
-
if (!
|
|
6490
|
-
await
|
|
6561
|
+
if (!skipSsh) {
|
|
6562
|
+
await startAutoSshTunnelsWithWarning();
|
|
6491
6563
|
}
|
|
6492
6564
|
const cleanThreshold = isGithubUrl(sub.url) ? AUTO_CLEAN_THRESHOLD_GITHUB : AUTO_CLEAN_THRESHOLD;
|
|
6493
6565
|
if (!skipClean && configInfo.proxies > cleanThreshold) {
|
|
@@ -6736,10 +6808,10 @@ async function cmdDirectory(args) {
|
|
|
6736
6808
|
|
|
6737
6809
|
// src/kernel.ts
|
|
6738
6810
|
import { spawnSync as spawnSync4 } from "child_process";
|
|
6739
|
-
import
|
|
6740
|
-
import
|
|
6811
|
+
import fs9 from "fs";
|
|
6812
|
+
import path8 from "path";
|
|
6741
6813
|
|
|
6742
|
-
// node_modules/compare-versions/lib/esm/utils.js
|
|
6814
|
+
// ../../../node_modules/compare-versions/lib/esm/utils.js
|
|
6743
6815
|
var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
|
|
6744
6816
|
var validateAndParse = (version) => {
|
|
6745
6817
|
if (typeof version !== "string") {
|
|
@@ -6777,7 +6849,7 @@ var compareSegments = (a, b) => {
|
|
|
6777
6849
|
return 0;
|
|
6778
6850
|
};
|
|
6779
6851
|
|
|
6780
|
-
// node_modules/compare-versions/lib/esm/compareVersions.js
|
|
6852
|
+
// ../../../node_modules/compare-versions/lib/esm/compareVersions.js
|
|
6781
6853
|
var compareVersions = (v1, v2) => {
|
|
6782
6854
|
const n1 = validateAndParse(v1);
|
|
6783
6855
|
const n2 = validateAndParse(v2);
|
|
@@ -6880,10 +6952,10 @@ async function checkUpdate(mirror) {
|
|
|
6880
6952
|
}
|
|
6881
6953
|
function findBinaryInDir(dir, maxDepth = 4) {
|
|
6882
6954
|
if (maxDepth <= 0) return null;
|
|
6883
|
-
const files =
|
|
6955
|
+
const files = fs9.readdirSync(dir);
|
|
6884
6956
|
for (const f of files) {
|
|
6885
|
-
const fullPath =
|
|
6886
|
-
const stat =
|
|
6957
|
+
const fullPath = path8.join(dir, f);
|
|
6958
|
+
const stat = fs9.lstatSync(fullPath);
|
|
6887
6959
|
if (stat.isDirectory()) {
|
|
6888
6960
|
const found = findBinaryInDir(fullPath, maxDepth - 1);
|
|
6889
6961
|
if (found) return found;
|
|
@@ -6911,7 +6983,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6911
6983
|
}
|
|
6912
6984
|
assertTrustedAssetUrl(asset.browser_download_url);
|
|
6913
6985
|
const downloadUrl = withMirror(asset.browser_download_url, mirror);
|
|
6914
|
-
const tempPath =
|
|
6986
|
+
const tempPath = path8.join(DIRS.kernel, path8.basename(asset.name));
|
|
6915
6987
|
const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
|
|
6916
6988
|
if (mirror && progressCallback) {
|
|
6917
6989
|
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 +7021,19 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6949
7021
|
}
|
|
6950
7022
|
if (curlResult.status !== 0) {
|
|
6951
7023
|
try {
|
|
6952
|
-
|
|
7024
|
+
fs9.unlinkSync(tempPath);
|
|
6953
7025
|
} catch {
|
|
6954
7026
|
}
|
|
6955
7027
|
throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
|
|
6956
7028
|
}
|
|
6957
|
-
if (!
|
|
7029
|
+
if (!fs9.existsSync(tempPath)) {
|
|
6958
7030
|
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
6959
7031
|
}
|
|
6960
7032
|
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
6961
|
-
const actual =
|
|
7033
|
+
const actual = fs9.statSync(tempPath).size;
|
|
6962
7034
|
if (actual !== asset.size) {
|
|
6963
7035
|
try {
|
|
6964
|
-
|
|
7036
|
+
fs9.unlinkSync(tempPath);
|
|
6965
7037
|
} catch {
|
|
6966
7038
|
}
|
|
6967
7039
|
throw new Error(
|
|
@@ -7001,17 +7073,17 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
7001
7073
|
if (tarResult.error) throw tarResult.error;
|
|
7002
7074
|
if (tarResult.status !== 0) throw new Error(`tar \u9000\u51FA\u7801 ${tarResult.status}`);
|
|
7003
7075
|
} else if (tempPath.endsWith(".gz")) {
|
|
7004
|
-
const baseName =
|
|
7005
|
-
const outputPath =
|
|
7076
|
+
const baseName = path8.basename(tempPath, ".gz");
|
|
7077
|
+
const outputPath = path8.join(extractPath, baseName);
|
|
7006
7078
|
const gzipResult = spawnSync4("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
|
|
7007
7079
|
if (gzipResult.error) throw gzipResult.error;
|
|
7008
7080
|
if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
|
|
7009
|
-
|
|
7081
|
+
fs9.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
|
|
7010
7082
|
extractedBinary = outputPath;
|
|
7011
7083
|
}
|
|
7012
7084
|
} catch (e) {
|
|
7013
7085
|
try {
|
|
7014
|
-
|
|
7086
|
+
fs9.unlinkSync(tempPath);
|
|
7015
7087
|
} catch {
|
|
7016
7088
|
}
|
|
7017
7089
|
throw new Error(`\u89E3\u538B\u5931\u8D25: ${e.message}`);
|
|
@@ -7019,23 +7091,23 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
7019
7091
|
const foundBinary = extractedBinary || findBinaryInDir(extractPath);
|
|
7020
7092
|
if (!foundBinary) {
|
|
7021
7093
|
try {
|
|
7022
|
-
|
|
7094
|
+
fs9.unlinkSync(tempPath);
|
|
7023
7095
|
} catch {
|
|
7024
7096
|
}
|
|
7025
7097
|
throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
|
|
7026
7098
|
}
|
|
7027
7099
|
const targetPath = PATHS.mihomoBinary;
|
|
7028
7100
|
if (foundBinary !== targetPath) {
|
|
7029
|
-
if (
|
|
7030
|
-
|
|
7101
|
+
if (fs9.existsSync(targetPath)) {
|
|
7102
|
+
fs9.chmodSync(targetPath, 493);
|
|
7031
7103
|
try {
|
|
7032
|
-
|
|
7104
|
+
fs9.unlinkSync(targetPath);
|
|
7033
7105
|
} catch {
|
|
7034
7106
|
}
|
|
7035
7107
|
}
|
|
7036
|
-
|
|
7108
|
+
fs9.renameSync(foundBinary, targetPath);
|
|
7037
7109
|
}
|
|
7038
|
-
|
|
7110
|
+
fs9.chmodSync(targetPath, 493);
|
|
7039
7111
|
if (progressCallback) {
|
|
7040
7112
|
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
7041
7113
|
}
|
|
@@ -7043,11 +7115,11 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
7043
7115
|
const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
|
|
7044
7116
|
if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
|
|
7045
7117
|
try {
|
|
7046
|
-
|
|
7118
|
+
fs9.unlinkSync(targetPath);
|
|
7047
7119
|
} catch {
|
|
7048
7120
|
}
|
|
7049
7121
|
try {
|
|
7050
|
-
|
|
7122
|
+
fs9.unlinkSync(tempPath);
|
|
7051
7123
|
} catch {
|
|
7052
7124
|
}
|
|
7053
7125
|
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 +7127,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
7055
7127
|
\u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
|
|
7056
7128
|
}
|
|
7057
7129
|
try {
|
|
7058
|
-
|
|
7130
|
+
fs9.unlinkSync(tempPath);
|
|
7059
7131
|
} catch {
|
|
7060
7132
|
}
|
|
7061
7133
|
clearKernelVersionCache();
|
|
@@ -7190,7 +7262,7 @@ function cmdLogs(args) {
|
|
|
7190
7262
|
}
|
|
7191
7263
|
|
|
7192
7264
|
// src/commands/overwrite.ts
|
|
7193
|
-
import
|
|
7265
|
+
import path9 from "path";
|
|
7194
7266
|
function printOverwriteList() {
|
|
7195
7267
|
const info = listOverwriteFile();
|
|
7196
7268
|
const statusText = info.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
|
|
@@ -7200,8 +7272,8 @@ function printOverwriteList() {
|
|
|
7200
7272
|
if (info.files.length === 0) {
|
|
7201
7273
|
console.log("\u6682\u65E0\u8986\u5199\u6587\u4EF6");
|
|
7202
7274
|
console.log("");
|
|
7203
|
-
console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${
|
|
7204
|
-
console.log(` \u6216 ${
|
|
7275
|
+
console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path9.join(info.dir, "overwrite.yaml")}`);
|
|
7276
|
+
console.log(` \u6216 ${path9.join(info.dir, "overwrite.dns.yaml")}`);
|
|
7205
7277
|
console.log("");
|
|
7206
7278
|
} else {
|
|
7207
7279
|
console.log(`${colors.cyan("\u8986\u5199\u6587\u4EF6")} (${info.files.length} \u4E2A\uFF0C\u6309\u987A\u5E8F\u52A0\u8F7D):`);
|
|
@@ -7265,7 +7337,7 @@ async function cmdOverwrite(args) {
|
|
|
7265
7337
|
}
|
|
7266
7338
|
|
|
7267
7339
|
// src/commands/reset.ts
|
|
7268
|
-
import
|
|
7340
|
+
import fs10 from "fs";
|
|
7269
7341
|
var RESET_TARGETS = [
|
|
7270
7342
|
{
|
|
7271
7343
|
id: "subs",
|
|
@@ -7303,15 +7375,20 @@ var RESET_TARGETS = [
|
|
|
7303
7375
|
// 它们会继续占着端口跑下去,且 CLI 无任何路径能停掉。
|
|
7304
7376
|
// **必须排在 settings 之前**:onAfter 会 writeSettings 重建 settings.json,
|
|
7305
7377
|
// 排在 settings 之后会让 `reset --full` 留下一个 {}(同 subs 的处理,见执行顺序注释)
|
|
7306
|
-
id: "
|
|
7307
|
-
aliases: ["
|
|
7378
|
+
id: "ssh",
|
|
7379
|
+
aliases: ["ssh"],
|
|
7308
7380
|
label: "\u96A7\u9053",
|
|
7309
|
-
|
|
7381
|
+
// 连 ssh.*.yaml 一并删:它们既不匹配 isOverwriteFilename(不归 overwrites 目标),
|
|
7382
|
+
// 本目标又只管运行态的话,`reset --full` 会留下配置文件,与「删全部」的承诺不符。
|
|
7383
|
+
// 单条 `ssh rm` 则刻意不删该文件(用户手写的分流规则不可恢复),两者语义不同
|
|
7384
|
+
paths: () => {
|
|
7385
|
+
const files = fs10.existsSync(USER_DATA_DIR) ? fs10.readdirSync(USER_DATA_DIR).filter(isSshFilename).map((f) => `${USER_DATA_DIR}/${f}`) : [];
|
|
7386
|
+
return [DIRS.ssh, ...files];
|
|
7387
|
+
},
|
|
7310
7388
|
needsStop: false,
|
|
7311
|
-
onBefore: () =>
|
|
7312
|
-
// 同步清空 settings
|
|
7313
|
-
|
|
7314
|
-
onAfter: () => writeSettings({ tunnels: void 0 })
|
|
7389
|
+
onBefore: () => stopAllSshTunnels(),
|
|
7390
|
+
// 同步清空 settings 里的隧道列表:只删运行态会留下「列表在但状态没了」的半重置状态
|
|
7391
|
+
onAfter: () => writeSettings({ ssh: void 0 })
|
|
7315
7392
|
},
|
|
7316
7393
|
{
|
|
7317
7394
|
id: "settings",
|
|
@@ -7340,8 +7417,8 @@ var RESET_TARGETS = [
|
|
|
7340
7417
|
label: "\u8986\u5199",
|
|
7341
7418
|
paths: () => {
|
|
7342
7419
|
const dir = USER_DATA_DIR;
|
|
7343
|
-
if (!
|
|
7344
|
-
return
|
|
7420
|
+
if (!fs10.existsSync(dir)) return [];
|
|
7421
|
+
return fs10.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
|
|
7345
7422
|
},
|
|
7346
7423
|
needsStop: false
|
|
7347
7424
|
},
|
|
@@ -7404,7 +7481,7 @@ async function cmdReset(args) {
|
|
|
7404
7481
|
}
|
|
7405
7482
|
targets = matched;
|
|
7406
7483
|
} else {
|
|
7407
|
-
targets = RESET_TARGETS.filter((t) => !["settings", "kernel", "overwrites", "daemon", "
|
|
7484
|
+
targets = RESET_TARGETS.filter((t) => !["settings", "kernel", "overwrites", "daemon", "ssh"].includes(t.id));
|
|
7408
7485
|
}
|
|
7409
7486
|
for (const t of targets) {
|
|
7410
7487
|
if (t.checkEmpty?.()) {
|
|
@@ -7466,7 +7543,7 @@ async function cmdReset(args) {
|
|
|
7466
7543
|
for (const t of targets) {
|
|
7467
7544
|
t.onBefore?.();
|
|
7468
7545
|
for (const p of t.paths()) {
|
|
7469
|
-
if (
|
|
7546
|
+
if (fs10.existsSync(p)) {
|
|
7470
7547
|
try {
|
|
7471
7548
|
rmrf(p);
|
|
7472
7549
|
} catch (e) {
|
|
@@ -7483,10 +7560,227 @@ async function cmdReset(args) {
|
|
|
7483
7560
|
console.log(colors.green(`\u5DF2\u91CD\u7F6E: ${targets.map((t) => t.label).join("\u3001")}`));
|
|
7484
7561
|
}
|
|
7485
7562
|
|
|
7563
|
+
// src/commands/ssh.ts
|
|
7564
|
+
function formatState(status) {
|
|
7565
|
+
switch (status.state) {
|
|
7566
|
+
case "running":
|
|
7567
|
+
return colors.green(`\u8FD0\u884C\u4E2D (PID ${status.pid})`);
|
|
7568
|
+
case "dead-port":
|
|
7569
|
+
return colors.yellow(`\u5047\u6D3B (PID ${status.pid}\uFF0C\u7AEF\u53E3 ${status.config.port} \u4E0D\u901A)`);
|
|
7570
|
+
default:
|
|
7571
|
+
return colors.yellow("\u672A\u8FD0\u884C");
|
|
7572
|
+
}
|
|
7573
|
+
}
|
|
7574
|
+
function getSshNameArg(args) {
|
|
7575
|
+
return getNonFlagArg(args, 2);
|
|
7576
|
+
}
|
|
7577
|
+
function requireSshNameArg(args, usage) {
|
|
7578
|
+
const name = getSshNameArg(args);
|
|
7579
|
+
if (!name) {
|
|
7580
|
+
const tunnels = getSshTunnels();
|
|
7581
|
+
throw new CliError("\u8BF7\u6307\u5B9A\u96A7\u9053\u540D\u79F0", {
|
|
7582
|
+
hint: [usage, ...tunnels.length > 0 ? ["", "\u53EF\u7528\u96A7\u9053:", ...tunnels.map((t) => ` ${t.name}`)] : []]
|
|
7583
|
+
});
|
|
7584
|
+
}
|
|
7585
|
+
return name;
|
|
7586
|
+
}
|
|
7587
|
+
async function printSshList() {
|
|
7588
|
+
const tunnels = getSshTunnels();
|
|
7589
|
+
console.log("");
|
|
7590
|
+
if (tunnels.length === 0) {
|
|
7591
|
+
console.log("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053");
|
|
7592
|
+
console.log("");
|
|
7593
|
+
console.log("\u6DFB\u52A0\u96A7\u9053: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>");
|
|
7594
|
+
console.log(colors.gray(" \u4F8B\u5982: mihomo ssh add work --host m4 --port 1080"));
|
|
7595
|
+
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"));
|
|
7596
|
+
console.log("");
|
|
7597
|
+
return;
|
|
7598
|
+
}
|
|
7599
|
+
const statuses = await getAllSshStatus();
|
|
7600
|
+
console.log(colors.cyan("\u96A7\u9053\u5217\u8868:"));
|
|
7601
|
+
console.log("");
|
|
7602
|
+
for (const status of statuses) {
|
|
7603
|
+
const { config } = status;
|
|
7604
|
+
const autoLabel = config.auto ? colors.gray(" [auto]") : "";
|
|
7605
|
+
console.log(` ${colors.bold(config.name)}${autoLabel}`);
|
|
7606
|
+
console.log(` ${colors.gray("\u51FA\u53E3: ")}${config.host} \u2192 127.0.0.1:${config.port}`);
|
|
7607
|
+
console.log(` ${colors.gray("\u72B6\u6001: ")}${formatState(status)}`);
|
|
7608
|
+
console.log(` ${colors.gray("\u914D\u7F6E: ")}${getSshConfigPath(config.name)}`);
|
|
7609
|
+
if (status.started_by) {
|
|
7610
|
+
console.log(` ${colors.gray("\u6765\u6E90: ")}${status.started_by === "auto" ? "\u968F start \u62C9\u8D77" : "\u624B\u52A8\u542F\u52A8"}`);
|
|
7611
|
+
}
|
|
7612
|
+
}
|
|
7613
|
+
console.log("");
|
|
7614
|
+
console.log("\u542F\u52A8: mihomo ssh up [\u540D\u5B57] \u505C\u6B62: mihomo ssh down [\u540D\u5B57]");
|
|
7615
|
+
console.log("\u72B6\u6001: mihomo ssh status \u5220\u9664: mihomo ssh rm <\u540D\u5B57>");
|
|
7616
|
+
console.log("");
|
|
7617
|
+
}
|
|
7618
|
+
async function sshAdd(args) {
|
|
7619
|
+
const name = requireSshNameArg(args, "\u7528\u6CD5: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]");
|
|
7620
|
+
const host = parseStringArg(args, "--host");
|
|
7621
|
+
if (!host) {
|
|
7622
|
+
throw new CliError("\u7F3A\u5C11 --host", {
|
|
7623
|
+
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"]
|
|
7624
|
+
});
|
|
7625
|
+
}
|
|
7626
|
+
const portRaw = parseStringArg(args, "--port");
|
|
7627
|
+
if (!portRaw) {
|
|
7628
|
+
throw new CliError("\u7F3A\u5C11 --port", { hint: ["\u7528\u6CD5: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"] });
|
|
7629
|
+
}
|
|
7630
|
+
if (!/^\d+$/.test(portRaw.trim())) {
|
|
7631
|
+
throw new CliError(`\u7AEF\u53E3\u65E0\u6548: "${portRaw}"\uFF0C\u9700\u4E3A 1-65535 \u7684\u6574\u6570`);
|
|
7632
|
+
}
|
|
7633
|
+
const port = Number(portRaw.trim());
|
|
7634
|
+
const auto = !hasFlag(args, "--no-auto");
|
|
7635
|
+
const config = { name, host, port, auto };
|
|
7636
|
+
addSshTunnel(config);
|
|
7637
|
+
const created = ensureSshConfigFile(config);
|
|
7638
|
+
const configPath = getSshConfigPath(name);
|
|
7639
|
+
console.log(`${colors.green("\u5DF2\u6DFB\u52A0\u96A7\u9053")} ${name} \xB7 ${host} \u2192 127.0.0.1:${port}${auto ? " \xB7 auto" : ""}`);
|
|
7640
|
+
console.log("");
|
|
7641
|
+
if (created) {
|
|
7642
|
+
console.log(`\u5DF2\u751F\u6210\u914D\u7F6E\u6A21\u677F: ${configPath}`);
|
|
7643
|
+
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"));
|
|
7644
|
+
console.log(colors.gray(" \u7F16\u8F91\u540E\u6267\u884C mihomo start \u751F\u6548"));
|
|
7645
|
+
} else {
|
|
7646
|
+
console.log(`\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728\uFF0C\u672A\u6539\u52A8: ${configPath}`);
|
|
7647
|
+
}
|
|
7648
|
+
console.log("");
|
|
7649
|
+
console.log(`\u542F\u52A8\u96A7\u9053: mihomo ssh up ${name}`);
|
|
7650
|
+
await restartToApply(args);
|
|
7651
|
+
}
|
|
7652
|
+
async function sshUp(args) {
|
|
7653
|
+
const name = getSshNameArg(args);
|
|
7654
|
+
const targets = name ? [resolveSshTunnel(name)] : getSshTunnels();
|
|
7655
|
+
if (targets.length === 0) {
|
|
7656
|
+
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>"] });
|
|
7657
|
+
}
|
|
7658
|
+
for (const config of targets) {
|
|
7659
|
+
if (ensureSshConfigFile(config)) {
|
|
7660
|
+
console.log(colors.gray(`\u5DF2\u8865\u5EFA\u914D\u7F6E\u6A21\u677F: ${getSshConfigPath(config.name)}`));
|
|
7661
|
+
}
|
|
7662
|
+
const result = await startSshTunnel(config.name, { startedBy: "manual" });
|
|
7663
|
+
if (result.alreadyRunning) {
|
|
7664
|
+
console.log(`${colors.gray("\u5DF2\u5728\u8FD0\u884C")} ${config.name} (PID ${result.pid})`);
|
|
7665
|
+
} else {
|
|
7666
|
+
console.log(`${colors.green("\u5DF2\u542F\u52A8\u96A7\u9053")} ${config.name} \xB7 ${config.host} \u2192 127.0.0.1:${config.port} (PID ${result.pid})`);
|
|
7667
|
+
}
|
|
7668
|
+
}
|
|
7669
|
+
}
|
|
7670
|
+
function sshDown(args) {
|
|
7671
|
+
const name = getSshNameArg(args);
|
|
7672
|
+
const targets = name ? [resolveSshTunnel(name)] : getSshTunnels();
|
|
7673
|
+
if (targets.length === 0) {
|
|
7674
|
+
throw new CliError("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053");
|
|
7675
|
+
}
|
|
7676
|
+
let stopped = 0;
|
|
7677
|
+
for (const config of targets) {
|
|
7678
|
+
const result = stopSshTunnel(config.name);
|
|
7679
|
+
if (result.notRunning) {
|
|
7680
|
+
console.log(`${colors.yellow("\u4E0D\u5728\u8FD0\u884C")} ${config.name}`);
|
|
7681
|
+
} else {
|
|
7682
|
+
console.log(`${colors.green("\u5DF2\u505C\u6B62\u96A7\u9053")} ${config.name} (PID ${result.pid})`);
|
|
7683
|
+
stopped++;
|
|
7684
|
+
}
|
|
7685
|
+
}
|
|
7686
|
+
if (stopped > 0) {
|
|
7687
|
+
console.log("");
|
|
7688
|
+
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"));
|
|
7689
|
+
}
|
|
7690
|
+
}
|
|
7691
|
+
async function sshStatus(args) {
|
|
7692
|
+
const name = getSshNameArg(args);
|
|
7693
|
+
if (!name) {
|
|
7694
|
+
await printSshList();
|
|
7695
|
+
return;
|
|
7696
|
+
}
|
|
7697
|
+
const config = resolveSshTunnel(name);
|
|
7698
|
+
const status = await getSshStatus(config);
|
|
7699
|
+
console.log("");
|
|
7700
|
+
console.log(`${colors.gray("\u96A7\u9053: ")}${config.name}${config.auto ? colors.gray(" [auto]") : ""}`);
|
|
7701
|
+
console.log(`${colors.gray("\u51FA\u53E3: ")}${config.host} \u2192 127.0.0.1:${config.port}`);
|
|
7702
|
+
console.log(`${colors.gray("\u72B6\u6001: ")}${formatState(status)}`);
|
|
7703
|
+
if (status.started_by) {
|
|
7704
|
+
console.log(`${colors.gray("\u6765\u6E90: ")}${status.started_by === "auto" ? "\u968F start \u62C9\u8D77" : "\u624B\u52A8\u542F\u52A8"}`);
|
|
7705
|
+
}
|
|
7706
|
+
console.log("");
|
|
7707
|
+
if (status.state === "dead-port") {
|
|
7708
|
+
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"));
|
|
7709
|
+
console.log(`\u91CD\u542F\u96A7\u9053: mihomo ssh down ${config.name} && mihomo ssh up ${config.name}`);
|
|
7710
|
+
console.log(colors.gray(` \u65E5\u5FD7: ${getSshLogPath(config.name)}`));
|
|
7711
|
+
console.log("");
|
|
7712
|
+
} else if (status.state === "stopped") {
|
|
7713
|
+
console.log(`\u542F\u52A8\u96A7\u9053: mihomo ssh up ${config.name}`);
|
|
7714
|
+
console.log("");
|
|
7715
|
+
}
|
|
7716
|
+
}
|
|
7717
|
+
async function sshRemove(args) {
|
|
7718
|
+
const name = requireSshNameArg(args, "\u7528\u6CD5: mihomo ssh rm <\u540D\u5B57> [-y]");
|
|
7719
|
+
const config = resolveSshTunnel(name);
|
|
7720
|
+
const skipConfirm = hasFlag(args, "-y", "--yes");
|
|
7721
|
+
if (!skipConfirm) {
|
|
7722
|
+
if (!process.stdin.isTTY) {
|
|
7723
|
+
throw new CliError("\u5220\u9664\u96A7\u9053\u9700\u8981\u786E\u8BA4", {
|
|
7724
|
+
label: "\u5DF2\u53D6\u6D88",
|
|
7725
|
+
hint: [`\u8DF3\u8FC7\u786E\u8BA4: mihomo ssh rm ${config.name} -y`]
|
|
7726
|
+
});
|
|
7727
|
+
}
|
|
7728
|
+
const confirmed = await confirmPrompt(`\u786E\u8BA4\u5220\u9664\u96A7\u9053 "${config.name}"?`);
|
|
7729
|
+
if (!confirmed) {
|
|
7730
|
+
console.log("\u5DF2\u53D6\u6D88");
|
|
7731
|
+
return;
|
|
7732
|
+
}
|
|
7733
|
+
}
|
|
7734
|
+
stopSshTunnel(config.name);
|
|
7735
|
+
removeSshTunnel(config.name);
|
|
7736
|
+
console.log(`${colors.green("\u5DF2\u5220\u9664\u96A7\u9053")} ${config.name}`);
|
|
7737
|
+
console.log("");
|
|
7738
|
+
console.log(`\u914D\u7F6E\u6587\u4EF6\u672A\u5220\u9664: ${getSshConfigPath(config.name)}`);
|
|
7739
|
+
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"));
|
|
7740
|
+
}
|
|
7741
|
+
function resolveSshTunnel(name) {
|
|
7742
|
+
const config = findSshTunnel(name);
|
|
7743
|
+
if (!config) {
|
|
7744
|
+
const tunnels = getSshTunnels();
|
|
7745
|
+
const suggestion = suggestSimilar(
|
|
7746
|
+
name,
|
|
7747
|
+
tunnels.map((t) => t.name)
|
|
7748
|
+
);
|
|
7749
|
+
throw new CliError(`\u672A\u627E\u5230\u96A7\u9053 "${name}"`, {
|
|
7750
|
+
hint: [
|
|
7751
|
+
...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
|
|
7752
|
+
...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>"]
|
|
7753
|
+
]
|
|
7754
|
+
});
|
|
7755
|
+
}
|
|
7756
|
+
return config;
|
|
7757
|
+
}
|
|
7758
|
+
var SUBCOMMANDS4 = [
|
|
7759
|
+
{ name: "list", handler: printSshList },
|
|
7760
|
+
{ name: "add", handler: sshAdd },
|
|
7761
|
+
{ name: "up", aliases: ["start"], handler: sshUp },
|
|
7762
|
+
{ name: "down", aliases: ["stop"], handler: sshDown },
|
|
7763
|
+
{ name: "status", handler: sshStatus },
|
|
7764
|
+
{ name: "remove", aliases: ["rm", "delete"], handler: sshRemove }
|
|
7765
|
+
];
|
|
7766
|
+
async function cmdSsh(args) {
|
|
7767
|
+
await dispatchSubcommand(args, SUBCOMMANDS4, {
|
|
7768
|
+
// 无 action → 列表;未知 action → 报错(不静默回落,否则 `ssh upp` 会看似成功)
|
|
7769
|
+
fallback: printSshList,
|
|
7770
|
+
onUnknown: (action) => {
|
|
7771
|
+
const names = SUBCOMMANDS4.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
7772
|
+
const suggestion = suggestSimilar(action, names);
|
|
7773
|
+
throw new CliError(`\u672A\u77E5\u7684 ssh \u5B50\u547D\u4EE4: ${action}`, {
|
|
7774
|
+
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: list, add, up, down, status, rm"]
|
|
7775
|
+
});
|
|
7776
|
+
}
|
|
7777
|
+
});
|
|
7778
|
+
}
|
|
7779
|
+
|
|
7486
7780
|
// src/test-instance.ts
|
|
7487
7781
|
import { spawn as spawn3 } from "child_process";
|
|
7488
|
-
import
|
|
7489
|
-
import
|
|
7782
|
+
import fs11 from "fs";
|
|
7783
|
+
import path10 from "path";
|
|
7490
7784
|
function isProxyValid(proxy) {
|
|
7491
7785
|
if (proxy === null || typeof proxy !== "object") return false;
|
|
7492
7786
|
if (!proxy.name || !proxy.server || !proxy.port) return false;
|
|
@@ -7497,20 +7791,20 @@ function isProxyValid(proxy) {
|
|
|
7497
7791
|
}
|
|
7498
7792
|
return true;
|
|
7499
7793
|
}
|
|
7500
|
-
var TEST_DIR =
|
|
7794
|
+
var TEST_DIR = path10.join(USER_DATA_DIR, "test");
|
|
7501
7795
|
var TEST_DIRS = {
|
|
7502
|
-
data:
|
|
7503
|
-
runtime:
|
|
7796
|
+
data: path10.join(TEST_DIR, "data"),
|
|
7797
|
+
runtime: path10.join(TEST_DIR, "runtime")
|
|
7504
7798
|
};
|
|
7505
7799
|
var TEST_PATHS = {
|
|
7506
|
-
configFile:
|
|
7507
|
-
pidFile:
|
|
7508
|
-
logFile:
|
|
7800
|
+
configFile: path10.join(TEST_DIRS.runtime, "config.yaml"),
|
|
7801
|
+
pidFile: path10.join(TEST_DIRS.runtime, "pid"),
|
|
7802
|
+
logFile: path10.join(TEST_DIR, "test.log")
|
|
7509
7803
|
};
|
|
7510
7804
|
var TEST_API = `http://${TEST_CONFIG["external-controller"]}`;
|
|
7511
7805
|
function ensureTestDirs() {
|
|
7512
7806
|
for (const dir of Object.values(TEST_DIRS)) {
|
|
7513
|
-
|
|
7807
|
+
fs11.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
7514
7808
|
}
|
|
7515
7809
|
}
|
|
7516
7810
|
function cleanupTestDir() {
|
|
@@ -7548,25 +7842,25 @@ function buildTestConfig(subName) {
|
|
|
7548
7842
|
rules: ["MATCH,PROXY"]
|
|
7549
7843
|
};
|
|
7550
7844
|
const content = dumpYaml(config);
|
|
7551
|
-
|
|
7845
|
+
fs11.writeFileSync(TEST_PATHS.configFile, content, { mode: 384 });
|
|
7552
7846
|
}
|
|
7553
7847
|
async function startTestInstance() {
|
|
7554
7848
|
const binary = PATHS.mihomoBinary;
|
|
7555
|
-
if (!
|
|
7849
|
+
if (!fs11.existsSync(binary)) throw new CliError('\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u8FD0\u884C "mihomo kernel" \u4E0B\u8F7D');
|
|
7556
7850
|
stopTestInstance();
|
|
7557
|
-
const logFd =
|
|
7851
|
+
const logFd = fs11.openSync(TEST_PATHS.logFile, "a");
|
|
7558
7852
|
const child = spawn3(binary, ["-d", TEST_DIRS.data, "-f", TEST_PATHS.configFile], {
|
|
7559
7853
|
detached: true,
|
|
7560
7854
|
stdio: ["ignore", logFd, logFd]
|
|
7561
7855
|
});
|
|
7562
7856
|
child.on("error", () => {
|
|
7563
7857
|
});
|
|
7564
|
-
|
|
7858
|
+
fs11.closeSync(logFd);
|
|
7565
7859
|
child.unref();
|
|
7566
7860
|
const pid = child.pid;
|
|
7567
7861
|
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
7862
|
spawnedTestPid = pid;
|
|
7569
|
-
|
|
7863
|
+
fs11.writeFileSync(TEST_PATHS.pidFile, pid.toString(), { mode: 384 });
|
|
7570
7864
|
const client = createHttpClient({ timeout: 2e3 });
|
|
7571
7865
|
let ready = false;
|
|
7572
7866
|
for (let i = 0; i < 60; i++) {
|
|
@@ -7582,7 +7876,7 @@ async function startTestInstance() {
|
|
|
7582
7876
|
if (!isProcessRunning(pid)) {
|
|
7583
7877
|
let errorDetail = "";
|
|
7584
7878
|
try {
|
|
7585
|
-
errorDetail =
|
|
7879
|
+
errorDetail = fs11.readFileSync(TEST_PATHS.logFile, "utf8").slice(-1e3);
|
|
7586
7880
|
} catch {
|
|
7587
7881
|
}
|
|
7588
7882
|
throw new CliError(`\u6D4B\u8BD5\u5B9E\u4F8B\u542F\u52A8\u5931\u8D25${errorDetail ? `
|
|
@@ -7596,7 +7890,7 @@ var spawnedTestPid = null;
|
|
|
7596
7890
|
function stopTestInstance() {
|
|
7597
7891
|
let pid = null;
|
|
7598
7892
|
try {
|
|
7599
|
-
const fromFile = parseInt(
|
|
7893
|
+
const fromFile = parseInt(fs11.readFileSync(TEST_PATHS.pidFile, "utf8").trim(), 10);
|
|
7600
7894
|
if (fromFile > 0) pid = fromFile;
|
|
7601
7895
|
} catch {
|
|
7602
7896
|
}
|
|
@@ -7611,7 +7905,7 @@ function stopTestInstance() {
|
|
|
7611
7905
|
}
|
|
7612
7906
|
spawnedTestPid = null;
|
|
7613
7907
|
try {
|
|
7614
|
-
|
|
7908
|
+
fs11.unlinkSync(TEST_PATHS.pidFile);
|
|
7615
7909
|
} catch {
|
|
7616
7910
|
}
|
|
7617
7911
|
}
|
|
@@ -7931,7 +8225,7 @@ async function subTest(args) {
|
|
|
7931
8225
|
progress.finish();
|
|
7932
8226
|
console.log(formatTestSummary(summary));
|
|
7933
8227
|
}
|
|
7934
|
-
var
|
|
8228
|
+
var SUBCOMMANDS5 = [
|
|
7935
8229
|
{ name: "list", handler: printSubscriptionList },
|
|
7936
8230
|
{ name: "add", handler: subAdd },
|
|
7937
8231
|
{ name: "update", handler: subUpdate },
|
|
@@ -7942,11 +8236,11 @@ var SUBCOMMANDS4 = [
|
|
|
7942
8236
|
{ name: "test", handler: subTest }
|
|
7943
8237
|
];
|
|
7944
8238
|
async function cmdSubscription(args) {
|
|
7945
|
-
await dispatchSubcommand(args,
|
|
8239
|
+
await dispatchSubcommand(args, SUBCOMMANDS5, {
|
|
7946
8240
|
// 无子命令 → 列表;未知子命令 → 报错
|
|
7947
8241
|
fallback: printSubscriptionList,
|
|
7948
8242
|
onUnknown: (action) => {
|
|
7949
|
-
const names =
|
|
8243
|
+
const names = SUBCOMMANDS5.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
7950
8244
|
const suggestion = suggestSimilar(action, names);
|
|
7951
8245
|
throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
|
|
7952
8246
|
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 +8315,6 @@ async function cmdClean(args) {
|
|
|
8021
8315
|
}
|
|
8022
8316
|
}
|
|
8023
8317
|
|
|
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
8318
|
// src/commands/ui.ts
|
|
8243
8319
|
function cmdUI(args) {
|
|
8244
8320
|
const uiName = args[1] || "zash";
|
|
@@ -8471,17 +8547,18 @@ var COMMANDS = [
|
|
|
8471
8547
|
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
8548
|
},
|
|
8473
8549
|
{
|
|
8474
|
-
//
|
|
8475
|
-
|
|
8476
|
-
|
|
8477
|
-
|
|
8550
|
+
// 无别名:`tun` 被 TUN 模式快捷命令占用,`ssh` 本身已够短。
|
|
8551
|
+
// (注册表重复 token 会在模块加载期直接抛错)
|
|
8552
|
+
name: "ssh",
|
|
8553
|
+
aliases: [],
|
|
8554
|
+
handler: cmdSsh,
|
|
8478
8555
|
group: "system",
|
|
8479
8556
|
usage: [
|
|
8480
|
-
"
|
|
8481
|
-
"
|
|
8482
|
-
"
|
|
8483
|
-
"
|
|
8484
|
-
"
|
|
8557
|
+
"ssh \u5217\u51FA ssh \u96A7\u9053",
|
|
8558
|
+
"ssh add <\u540D\u5B57> --host <\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]",
|
|
8559
|
+
"ssh up|down [\u540D\u5B57] \u542F\u52A8/\u505C\u6B62\u96A7\u9053\uFF08\u65E0\u53C2\u5373\u5168\u90E8\uFF09",
|
|
8560
|
+
"ssh status [\u540D\u5B57] \u67E5\u770B\u96A7\u9053\u72B6\u6001\uFF08\u771F\u5B9E\u63A2\u6D4B\u7AEF\u53E3\uFF09",
|
|
8561
|
+
"ssh rm <\u540D\u5B57> [-y] \u5220\u9664\u96A7\u9053\uFF08\u4E0D\u5220\u914D\u7F6E\u6587\u4EF6\uFF09"
|
|
8485
8562
|
]
|
|
8486
8563
|
},
|
|
8487
8564
|
{
|