mihomo-cli 4.5.0 → 4.7.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 +66 -0
- package/README.md +29 -25
- package/dist/index.js +493 -230
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -3060,8 +3060,13 @@ var require2 = createRequire(import.meta.url);
|
|
|
3060
3060
|
var pkg = require2("../package.json");
|
|
3061
3061
|
var VERSION = pkg.version;
|
|
3062
3062
|
var PKG_NAME = pkg.name;
|
|
3063
|
-
var AVAILABLE_MIRRORS = ["
|
|
3064
|
-
var
|
|
3063
|
+
var AVAILABLE_MIRRORS = ["gh-proxy.org", "v4.gh-proxy.org", "v6.gh-proxy.org", "cdn.gh-proxy.org", "axisnow.gh-proxy.org"];
|
|
3064
|
+
var MIRROR_ALIASES = {
|
|
3065
|
+
v4: "https://v4.gh-proxy.org/",
|
|
3066
|
+
v6: "https://v6.gh-proxy.org/",
|
|
3067
|
+
cdn: "https://cdn.gh-proxy.org/",
|
|
3068
|
+
axisnow: "https://axisnow.gh-proxy.org/"
|
|
3069
|
+
};
|
|
3065
3070
|
var UI_URLS = {
|
|
3066
3071
|
zash: "https://board.zash.run.place",
|
|
3067
3072
|
dash: "https://metacubex.github.io/metacubexd",
|
|
@@ -3185,6 +3190,8 @@ var PATHS = {
|
|
|
3185
3190
|
configFile: path.join(DIRS.runtime, "config.yaml"),
|
|
3186
3191
|
logFile: path.join(DIRS.logs, "mihomo.log"),
|
|
3187
3192
|
pidFile: path.join(DIRS.runtime, "pid"),
|
|
3193
|
+
/** 服务操作跨进程锁:start/stop/install/uninstall 的 enable/bootstrap/bootout/disable 串行化 */
|
|
3194
|
+
serviceLock: path.join(DIRS.runtime, "service.lock"),
|
|
3188
3195
|
configStage1Subscription: path.join(DIRS.runtime, "1.subscription.yaml"),
|
|
3189
3196
|
configStage2Overwrite: path.join(DIRS.runtime, "2.overwrite.yaml"),
|
|
3190
3197
|
configStage3System: path.join(DIRS.runtime, "3.system.yaml"),
|
|
@@ -3388,9 +3395,28 @@ function getPorts() {
|
|
|
3388
3395
|
function maskSingleUrl(url) {
|
|
3389
3396
|
try {
|
|
3390
3397
|
const parsed = new URL(url);
|
|
3391
|
-
const tokenKeys =
|
|
3392
|
-
|
|
3393
|
-
|
|
3398
|
+
const tokenKeys = /* @__PURE__ */ new Set([
|
|
3399
|
+
"token",
|
|
3400
|
+
"key",
|
|
3401
|
+
"secret",
|
|
3402
|
+
"pass",
|
|
3403
|
+
"password",
|
|
3404
|
+
"auth",
|
|
3405
|
+
"access_token",
|
|
3406
|
+
"api_key",
|
|
3407
|
+
"uuid",
|
|
3408
|
+
"sid",
|
|
3409
|
+
"id",
|
|
3410
|
+
"sub",
|
|
3411
|
+
"user",
|
|
3412
|
+
"email",
|
|
3413
|
+
"passwd",
|
|
3414
|
+
"apikey",
|
|
3415
|
+
"api_key",
|
|
3416
|
+
"access"
|
|
3417
|
+
]);
|
|
3418
|
+
for (const [key, value] of parsed.searchParams) {
|
|
3419
|
+
if (tokenKeys.has(key.toLowerCase()) || value.length >= 16) {
|
|
3394
3420
|
parsed.searchParams.set(key, "***");
|
|
3395
3421
|
}
|
|
3396
3422
|
}
|
|
@@ -3438,7 +3464,8 @@ function saveSubscriptionCache(subName, data) {
|
|
|
3438
3464
|
ensureDirs();
|
|
3439
3465
|
withFileLock(PATHS.subscriptionsCacheFile, () => {
|
|
3440
3466
|
const cache = readSubscriptionCache();
|
|
3441
|
-
|
|
3467
|
+
const old = cache[subName];
|
|
3468
|
+
cache[subName] = { ...old && typeof old === "object" && !Array.isArray(old) ? old : {}, ...data };
|
|
3442
3469
|
writeSubscriptionCache(cache);
|
|
3443
3470
|
});
|
|
3444
3471
|
}
|
|
@@ -3512,14 +3539,14 @@ function removeSubscription(name) {
|
|
|
3512
3539
|
switchedTo = subs.length > 0 ? subs[0].name : null;
|
|
3513
3540
|
updates.active_subscription = switchedTo ?? void 0;
|
|
3514
3541
|
}
|
|
3542
|
+
try {
|
|
3543
|
+
fs2.rmSync(getSubscriptionRawConfigPath(name), { force: true });
|
|
3544
|
+
} catch {
|
|
3545
|
+
}
|
|
3515
3546
|
return updates;
|
|
3516
3547
|
});
|
|
3517
3548
|
if (!found) return null;
|
|
3518
3549
|
deleteSubscriptionCache(name);
|
|
3519
|
-
try {
|
|
3520
|
-
fs2.rmSync(getSubscriptionRawConfigPath(name), { force: true });
|
|
3521
|
-
} catch {
|
|
3522
|
-
}
|
|
3523
3550
|
return switchedTo;
|
|
3524
3551
|
}
|
|
3525
3552
|
function setDefaultSubscription(name) {
|
|
@@ -3805,6 +3832,9 @@ function listOverwriteFile() {
|
|
|
3805
3832
|
};
|
|
3806
3833
|
}
|
|
3807
3834
|
|
|
3835
|
+
// src/utils.ts
|
|
3836
|
+
import os2 from "os";
|
|
3837
|
+
|
|
3808
3838
|
// src/flags.ts
|
|
3809
3839
|
var FLAGS = [
|
|
3810
3840
|
// === start 的选项(重启透传) ===
|
|
@@ -3826,6 +3856,11 @@ function sleep(ms) {
|
|
|
3826
3856
|
function escapeRegExp(s) {
|
|
3827
3857
|
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
3828
3858
|
}
|
|
3859
|
+
function sanitizeTerminal(s) {
|
|
3860
|
+
const ansiEscape = /\x1b\[[0-9;]*[a-zA-Z]/g;
|
|
3861
|
+
const controlChars = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g;
|
|
3862
|
+
return s.replace(ansiEscape, "").replace(controlChars, "");
|
|
3863
|
+
}
|
|
3829
3864
|
function shellQuote(s) {
|
|
3830
3865
|
return `'${s.replace(/'/g, "'\\''")}'`;
|
|
3831
3866
|
}
|
|
@@ -3922,6 +3957,21 @@ function subscriptionUrgency(entry, nowMs = Date.now()) {
|
|
|
3922
3957
|
function hasFlag(args, short, long) {
|
|
3923
3958
|
return !!args && (args.includes(short) || long !== void 0 && args.includes(long));
|
|
3924
3959
|
}
|
|
3960
|
+
function assertKnownFlags(args, known, command) {
|
|
3961
|
+
if (!args) return;
|
|
3962
|
+
const knownSet = new Set(known);
|
|
3963
|
+
for (const a of args) {
|
|
3964
|
+
if (!a.startsWith("-") || a === "-") continue;
|
|
3965
|
+
if (knownSet.has(a)) continue;
|
|
3966
|
+
const eqIdx = a.indexOf("=");
|
|
3967
|
+
if (eqIdx > 0 && knownSet.has(a.slice(0, eqIdx))) continue;
|
|
3968
|
+
if (a.length > 2 && a.startsWith("-") && !a.startsWith("--") && knownSet.has(a.slice(0, 2))) continue;
|
|
3969
|
+
throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${a}`, {
|
|
3970
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
3971
|
+
hint: [`\u53EF\u7528\u9009\u9879: ${known.join(", ")}`, "", `\u7528\u6CD5: mihomo ${command}`]
|
|
3972
|
+
});
|
|
3973
|
+
}
|
|
3974
|
+
}
|
|
3925
3975
|
function parseIntArg(args, short, long, defaultValue) {
|
|
3926
3976
|
if (!args) return defaultValue;
|
|
3927
3977
|
const parse = (raw, flag) => {
|
|
@@ -3944,6 +3994,9 @@ function parseIntArg(args, short, long, defaultValue) {
|
|
|
3944
3994
|
if (args[i].startsWith(`${long}=`)) {
|
|
3945
3995
|
return parse(args[i].slice(long.length + 1), long);
|
|
3946
3996
|
}
|
|
3997
|
+
if (args[i].startsWith(short) && args[i].length > short.length && /^\d+$/.test(args[i].slice(short.length))) {
|
|
3998
|
+
return parse(args[i].slice(short.length), short);
|
|
3999
|
+
}
|
|
3947
4000
|
}
|
|
3948
4001
|
return defaultValue;
|
|
3949
4002
|
}
|
|
@@ -4014,9 +4067,24 @@ function suggestSimilar(input, candidates) {
|
|
|
4014
4067
|
scored.sort((a, b) => a.score - b.score || a.lenDiff - b.lenDiff);
|
|
4015
4068
|
return scored.slice(0, 3).map((s) => s.name);
|
|
4016
4069
|
}
|
|
4070
|
+
function hasGlobalIpv6() {
|
|
4071
|
+
for (const addrs of Object.values(os2.networkInterfaces())) {
|
|
4072
|
+
for (const addr of addrs ?? []) {
|
|
4073
|
+
if (addr.family !== "IPv6" || addr.internal) continue;
|
|
4074
|
+
if (/^(fe80|f[c-d])/i.test(addr.address)) continue;
|
|
4075
|
+
return true;
|
|
4076
|
+
}
|
|
4077
|
+
}
|
|
4078
|
+
return false;
|
|
4079
|
+
}
|
|
4080
|
+
function getDefaultMirror() {
|
|
4081
|
+
return hasGlobalIpv6() ? MIRROR_ALIASES.v6 : "https://gh-proxy.org/";
|
|
4082
|
+
}
|
|
4017
4083
|
function normalizeMirrorUrl(val) {
|
|
4018
4084
|
if (!val) return null;
|
|
4019
|
-
if (val === "direct"
|
|
4085
|
+
if (val === "direct") return null;
|
|
4086
|
+
const alias = MIRROR_ALIASES[val.toLowerCase()];
|
|
4087
|
+
if (alias) return alias;
|
|
4020
4088
|
const withScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(val) ? val : `https://${val}`;
|
|
4021
4089
|
let parsed;
|
|
4022
4090
|
try {
|
|
@@ -4024,7 +4092,7 @@ function normalizeMirrorUrl(val) {
|
|
|
4024
4092
|
} catch {
|
|
4025
4093
|
throw new CliError(`\u955C\u50CF\u5730\u5740\u65E0\u6548: "${val}"`, {
|
|
4026
4094
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
4027
|
-
hint: ["\u683C\u5F0F\u5982: --mirror
|
|
4095
|
+
hint: ["\u683C\u5F0F\u5982: --mirror cdn\uFF08\u77ED\u522B\u540D\uFF09\u6216 --mirror gh-proxy.org \u6216 --mirror https://gh-proxy.org/", "\u4E0D\u4F7F\u7528\u955C\u50CF: --mirror direct"]
|
|
4028
4096
|
});
|
|
4029
4097
|
}
|
|
4030
4098
|
if (parsed.protocol !== "https:") {
|
|
@@ -4036,15 +4104,15 @@ function normalizeMirrorUrl(val) {
|
|
|
4036
4104
|
const url = parsed.toString();
|
|
4037
4105
|
return url.endsWith("/") ? url : `${url}/`;
|
|
4038
4106
|
}
|
|
4039
|
-
function parseMirrorArg(args
|
|
4107
|
+
function parseMirrorArg(args) {
|
|
4040
4108
|
if (!args || args.length < 2) {
|
|
4041
|
-
return
|
|
4109
|
+
return { mirror: null, isOverride: false };
|
|
4042
4110
|
}
|
|
4043
4111
|
if (args.some((a) => a === "--mirror-all" || a.startsWith("--mirror-all="))) {
|
|
4044
4112
|
throw new CliError("--mirror-all \u5DF2\u79FB\u9664\uFF08v3.10.0\uFF09", {
|
|
4045
4113
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
4046
4114
|
hint: [
|
|
4047
|
-
"\u7248\u672C\u67E5\u8BE2\uFF08GitHub API\uFF09\
|
|
4115
|
+
"\u7248\u672C\u67E5\u8BE2\uFF08GitHub API\uFF09\u7EDD\u4E0D\u7ECF\u8FC7\u955C\u50CF\uFF0C\u955C\u50CF\u53EA\u4F5C\u7528\u4E8E\u5185\u6838\u4EA7\u7269\u4E0B\u8F7D\u3002",
|
|
4048
4116
|
"API \u82E5\u8D70\u955C\u50CF\uFF0C\u4E0B\u8F7D\u5730\u5740\u5C31\u7531\u955C\u50CF\u8BF4\u4E86\u7B97\uFF0C\u800C\u5185\u6838\u968F\u540E\u4EE5 root \u8FD0\u884C\u3002",
|
|
4049
4117
|
"",
|
|
4050
4118
|
"\u6539\u7528: mihomo kernel --mirror [\u955C\u50CF]"
|
|
@@ -4052,7 +4120,10 @@ function parseMirrorArg(args, savedMirror) {
|
|
|
4052
4120
|
});
|
|
4053
4121
|
}
|
|
4054
4122
|
if (args.includes("--no-mirror") || args.includes("--direct")) {
|
|
4055
|
-
|
|
4123
|
+
throw new CliError("--no-mirror/--direct \u5DF2\u79FB\u9664\uFF08v4.7.0\uFF09", {
|
|
4124
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
4125
|
+
hint: ["\u5F3A\u5236\u76F4\u8FDE\u6539\u7528: mihomo kernel --mirror direct", "\u4E0D\u5E26\u9009\u9879\u65F6\u81EA\u52A8\u9009\u62E9\u901A\u9053: gh > \u672C\u673A\u4EE3\u7406 > \u955C\u50CF > \u76F4\u8FDE"]
|
|
4126
|
+
});
|
|
4056
4127
|
}
|
|
4057
4128
|
const mirrorEq = args.find((a) => a.startsWith("--mirror="));
|
|
4058
4129
|
const mirrorIdx = args.indexOf("--mirror");
|
|
@@ -4060,12 +4131,12 @@ function parseMirrorArg(args, savedMirror) {
|
|
|
4060
4131
|
const inline = mirrorEq?.slice("--mirror=".length);
|
|
4061
4132
|
const nextArg = inline ?? args[mirrorIdx + 1];
|
|
4062
4133
|
if (!nextArg || nextArg.startsWith("-")) {
|
|
4063
|
-
return { mirror:
|
|
4134
|
+
return { mirror: getDefaultMirror(), isOverride: true };
|
|
4064
4135
|
}
|
|
4065
4136
|
const normalized = normalizeMirrorUrl(nextArg);
|
|
4066
|
-
return
|
|
4137
|
+
return { mirror: normalized, isOverride: true };
|
|
4067
4138
|
}
|
|
4068
|
-
return
|
|
4139
|
+
return { mirror: null, isOverride: false };
|
|
4069
4140
|
}
|
|
4070
4141
|
|
|
4071
4142
|
// src/config.ts
|
|
@@ -4083,8 +4154,11 @@ function parseYamlOrJson(content, errorMsg) {
|
|
|
4083
4154
|
} catch {
|
|
4084
4155
|
}
|
|
4085
4156
|
try {
|
|
4086
|
-
|
|
4087
|
-
|
|
4157
|
+
const result = JSON.parse(content);
|
|
4158
|
+
if (result != null && typeof result === "object" && !Array.isArray(result)) return result;
|
|
4159
|
+
throw new Error(`${errorMsg || "\u5185\u5BB9"}\u4E0D\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61`);
|
|
4160
|
+
} catch (e) {
|
|
4161
|
+
if (e instanceof Error && e.message.includes("\u4E0D\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61")) throw e;
|
|
4088
4162
|
throw new Error(`${errorMsg || "\u5185\u5BB9"}\u683C\u5F0F\u9519\u8BEF\uFF0C\u65E0\u6CD5\u89E3\u6790\u4E3A YAML \u6216 JSON`);
|
|
4089
4163
|
}
|
|
4090
4164
|
}
|
|
@@ -4293,7 +4367,8 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4293
4367
|
const overwriteEnabled = isOverwriteEnabled();
|
|
4294
4368
|
const allFiles = overwriteEnabled ? loadOverwriteFile() : [];
|
|
4295
4369
|
const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
|
|
4296
|
-
const
|
|
4370
|
+
const working = structuredClone(subscriptionConfig);
|
|
4371
|
+
const withOverwrites = applyOverwrite(working, overwriteFiles);
|
|
4297
4372
|
if (overwriteFiles.length > 0) {
|
|
4298
4373
|
const baseProxies = Array.isArray(subscriptionConfig.proxies) ? subscriptionConfig.proxies : [];
|
|
4299
4374
|
const baseProxyNames = new Set(
|
|
@@ -4476,8 +4551,15 @@ function rotateLog() {
|
|
|
4476
4551
|
if (!fs5.existsSync(logFile)) return null;
|
|
4477
4552
|
const stat = fs5.statSync(logFile);
|
|
4478
4553
|
if (stat.size === 0) return null;
|
|
4479
|
-
const
|
|
4480
|
-
|
|
4554
|
+
const timestamp = formatLocalTimestamp();
|
|
4555
|
+
let rotatedName = `mihomo.${timestamp}.log`;
|
|
4556
|
+
let rotatedPath = path4.join(DIRS.logs, rotatedName);
|
|
4557
|
+
let seq = 1;
|
|
4558
|
+
while (fs5.existsSync(rotatedPath)) {
|
|
4559
|
+
rotatedName = `mihomo.${timestamp}.${seq}.log`;
|
|
4560
|
+
rotatedPath = path4.join(DIRS.logs, rotatedName);
|
|
4561
|
+
seq++;
|
|
4562
|
+
}
|
|
4481
4563
|
fs5.renameSync(logFile, rotatedPath);
|
|
4482
4564
|
return rotatedPath;
|
|
4483
4565
|
}
|
|
@@ -4490,7 +4572,7 @@ function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
|
|
|
4490
4572
|
let deleted = 0;
|
|
4491
4573
|
let errors = 0;
|
|
4492
4574
|
for (const file of files) {
|
|
4493
|
-
if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}
|
|
4575
|
+
if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(\.\d+)?\.log$/)) continue;
|
|
4494
4576
|
try {
|
|
4495
4577
|
const filePath = path4.join(logsDir, file);
|
|
4496
4578
|
const stat = fs5.statSync(filePath);
|
|
@@ -4927,8 +5009,10 @@ async function installService(wasRunning) {
|
|
|
4927
5009
|
fs8.copyFileSync(stagePath, PATHS.userAgentPlist);
|
|
4928
5010
|
fs8.chmodSync(PATHS.userAgentPlist, 420);
|
|
4929
5011
|
if (wasRunning) {
|
|
4930
|
-
|
|
4931
|
-
|
|
5012
|
+
withFileLock(PATHS.serviceLock, () => {
|
|
5013
|
+
runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
|
|
5014
|
+
runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u88C5\u8F7D\u670D\u52A1");
|
|
5015
|
+
});
|
|
4932
5016
|
}
|
|
4933
5017
|
} finally {
|
|
4934
5018
|
try {
|
|
@@ -4964,8 +5048,13 @@ async function startService() {
|
|
|
4964
5048
|
await bootoutService();
|
|
4965
5049
|
await waitUntilUnloaded();
|
|
4966
5050
|
rotateAndCleanupLogs();
|
|
4967
|
-
|
|
4968
|
-
|
|
5051
|
+
withFileLock(PATHS.serviceLock, () => {
|
|
5052
|
+
if (isServiceDisabledInLaunchd()) {
|
|
5053
|
+
return;
|
|
5054
|
+
}
|
|
5055
|
+
runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
|
|
5056
|
+
runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u542F\u52A8\u670D\u52A1");
|
|
5057
|
+
});
|
|
4969
5058
|
}
|
|
4970
5059
|
function disableServiceAutoStart() {
|
|
4971
5060
|
assertServiceLabelSafe();
|
|
@@ -4978,14 +5067,19 @@ function disableServiceAutoStart() {
|
|
|
4978
5067
|
}
|
|
4979
5068
|
async function stopService() {
|
|
4980
5069
|
assertServiceLabelSafe();
|
|
4981
|
-
await
|
|
5070
|
+
await withFileLock(PATHS.serviceLock, () => {
|
|
5071
|
+
bootoutService();
|
|
5072
|
+
disableServiceAutoStart();
|
|
5073
|
+
});
|
|
4982
5074
|
await waitUntilUnloaded();
|
|
4983
|
-
disableServiceAutoStart();
|
|
4984
5075
|
killResidualKernels();
|
|
4985
5076
|
}
|
|
4986
5077
|
async function uninstallService() {
|
|
4987
5078
|
assertServiceLabelSafe();
|
|
4988
|
-
await
|
|
5079
|
+
await withFileLock(PATHS.serviceLock, () => {
|
|
5080
|
+
bootoutService();
|
|
5081
|
+
disableServiceAutoStart();
|
|
5082
|
+
});
|
|
4989
5083
|
await waitUntilUnloaded();
|
|
4990
5084
|
try {
|
|
4991
5085
|
fs8.rmSync(PATHS.userAgentPlist, { force: true });
|
|
@@ -5003,7 +5097,14 @@ function cleanupLegacySystemInstall() {
|
|
|
5003
5097
|
assertServiceLabelSafe();
|
|
5004
5098
|
const script = [
|
|
5005
5099
|
"#!/bin/bash",
|
|
5006
|
-
|
|
5100
|
+
// bootout 退出码分级:113=未装载(daemon 已不在,正常),其余是真实失败。
|
|
5101
|
+
// 此前 || true 吞掉所有错误,daemon 仍在跑却继续 rm plist 并报「已清理」
|
|
5102
|
+
`bootout_code=0`,
|
|
5103
|
+
`launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || bootout_code=$?`,
|
|
5104
|
+
`if [ $bootout_code -ne 0 ] && [ $bootout_code -ne 113 ]; then`,
|
|
5105
|
+
` echo "launchctl bootout \u5931\u8D25\uFF08\u9000\u51FA\u7801 $bootout_code\uFF09" >&2`,
|
|
5106
|
+
` exit 1`,
|
|
5107
|
+
`fi`,
|
|
5007
5108
|
`rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
|
|
5008
5109
|
`chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
|
|
5009
5110
|
`chown -R "$SUDO_UID:$SUDO_GID" ${shellQuote(DIRS.data)} 2>/dev/null || true`,
|
|
@@ -5013,6 +5114,17 @@ function cleanupLegacySystemInstall() {
|
|
|
5013
5114
|
].join("\n");
|
|
5014
5115
|
runSudoScript(script, { action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1", file: "legacy-cleanup.sh" });
|
|
5015
5116
|
}
|
|
5117
|
+
function cleanupLegacyInstallOrThrow() {
|
|
5118
|
+
try {
|
|
5119
|
+
cleanupLegacySystemInstall();
|
|
5120
|
+
} catch (e) {
|
|
5121
|
+
if (e instanceof CliError) throw e;
|
|
5122
|
+
throw new CliError(e.message, {
|
|
5123
|
+
label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
|
|
5124
|
+
hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
|
|
5125
|
+
});
|
|
5126
|
+
}
|
|
5127
|
+
}
|
|
5016
5128
|
function logOversized() {
|
|
5017
5129
|
try {
|
|
5018
5130
|
return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
@@ -5034,6 +5146,11 @@ async function tryHotReload() {
|
|
|
5034
5146
|
if (!probe.ok) return false;
|
|
5035
5147
|
const info = await probe.json();
|
|
5036
5148
|
if (typeof info?.version !== "string") return false;
|
|
5149
|
+
const port = getPorts().controller;
|
|
5150
|
+
const lsofResult = spawnSync4("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
|
|
5151
|
+
if (lsofResult.status !== 0) return false;
|
|
5152
|
+
const listenerPid = Number.parseInt(lsofResult.stdout.trim(), 10);
|
|
5153
|
+
if (!Number.isFinite(listenerPid) || listenerPid !== status.pid) return false;
|
|
5037
5154
|
const res = await fetch(`${baseUrl}/configs?force=true`, {
|
|
5038
5155
|
method: "PUT",
|
|
5039
5156
|
headers,
|
|
@@ -5053,7 +5170,13 @@ async function restartService() {
|
|
|
5053
5170
|
}
|
|
5054
5171
|
if (!logOversized() && await tryHotReload()) return { hotReloaded: true };
|
|
5055
5172
|
if (logOversized()) {
|
|
5056
|
-
const
|
|
5173
|
+
const timestamp = formatLocalTimestamp();
|
|
5174
|
+
let archiveFile = path6.join(DIRS.logs, `mihomo.${timestamp}.log`);
|
|
5175
|
+
let seq = 1;
|
|
5176
|
+
while (fs8.existsSync(archiveFile)) {
|
|
5177
|
+
archiveFile = path6.join(DIRS.logs, `mihomo.${timestamp}.${seq}.log`);
|
|
5178
|
+
seq++;
|
|
5179
|
+
}
|
|
5057
5180
|
try {
|
|
5058
5181
|
fs8.copyFileSync(PATHS.logFile, archiveFile);
|
|
5059
5182
|
fs8.writeFileSync(PATHS.logFile, "");
|
|
@@ -5154,7 +5277,7 @@ function printVersion() {
|
|
|
5154
5277
|
|
|
5155
5278
|
// src/commands/completion.ts
|
|
5156
5279
|
import fs10 from "fs";
|
|
5157
|
-
import
|
|
5280
|
+
import os3 from "os";
|
|
5158
5281
|
import path8 from "path";
|
|
5159
5282
|
|
|
5160
5283
|
// src/open.ts
|
|
@@ -5303,7 +5426,11 @@ async function startTun() {
|
|
|
5303
5426
|
}
|
|
5304
5427
|
const staleState = checkStaleState();
|
|
5305
5428
|
if (staleState.needsCleanup) {
|
|
5306
|
-
|
|
5429
|
+
if (staleState.allPids.length > 0) {
|
|
5430
|
+
console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
|
|
5431
|
+
} else {
|
|
5432
|
+
console.log("\u6E05\u7406\u6B8B\u7559\u7684 root pid \u6587\u4EF6...");
|
|
5433
|
+
}
|
|
5307
5434
|
}
|
|
5308
5435
|
console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
|
|
5309
5436
|
runSudoScript(buildTunLaunchScript(), {
|
|
@@ -5386,6 +5513,9 @@ function createHttpClient(options = {}) {
|
|
|
5386
5513
|
signal,
|
|
5387
5514
|
headers: { "User-Agent": `mihomo-cli/${VERSION}` }
|
|
5388
5515
|
});
|
|
5516
|
+
if (url.startsWith("https://") && !response.url.startsWith("https://")) {
|
|
5517
|
+
throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${response.url}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
|
|
5518
|
+
}
|
|
5389
5519
|
if (!response.ok) {
|
|
5390
5520
|
const error = new Error(`HTTP ${response.status}`);
|
|
5391
5521
|
error.response = { status: response.status };
|
|
@@ -5511,8 +5641,9 @@ function extractSubscriptionMeta(headers) {
|
|
|
5511
5641
|
return {
|
|
5512
5642
|
userInfo: parseUserInfo(headers?.get("subscription-userinfo") ?? null),
|
|
5513
5643
|
updateInterval: parsePositiveInterval(headers?.get("profile-update-interval")),
|
|
5514
|
-
|
|
5515
|
-
|
|
5644
|
+
// 服务器返回的字符串可能含 ANSI 转义/控制字符,展示前消毒(防终端输出伪造)
|
|
5645
|
+
webPageUrl: sanitizeTerminal(headers?.get("profile-web-page-url") || "") || null,
|
|
5646
|
+
username: sanitizeTerminal(parseUsernameFromContentDisposition(headers?.get("content-disposition") ?? null) || "") || null
|
|
5516
5647
|
};
|
|
5517
5648
|
}
|
|
5518
5649
|
function saveSubscriptionMeta(subName, meta) {
|
|
@@ -5590,7 +5721,9 @@ function assertLooksLikeSubscription(parsed, maskedUrl) {
|
|
|
5590
5721
|
const providers = parsed["proxy-providers"];
|
|
5591
5722
|
const hasProviders = providers != null && typeof providers === "object" && Object.keys(providers).length > 0;
|
|
5592
5723
|
if (hasProxies || hasGroups || hasProviders) return;
|
|
5593
|
-
const serverMsg =
|
|
5724
|
+
const serverMsg = sanitizeTerminal(
|
|
5725
|
+
["error", "message", "msg", "info"].map((k) => parsed[k]).find((v) => typeof v === "string" && v.length > 0) ?? ""
|
|
5726
|
+
);
|
|
5594
5727
|
throw new CliError("\u8BA2\u9605\u5185\u5BB9\u4E0D\u542B\u4EFB\u4F55\u8282\u70B9\u6765\u6E90\uFF08proxies / proxy-groups / proxy-providers \u5747\u4E3A\u7A7A\uFF09", {
|
|
5595
5728
|
label: "\u8BA2\u9605\u65E0\u6548",
|
|
5596
5729
|
hint: [
|
|
@@ -5837,6 +5970,7 @@ function buildStatusJson(args) {
|
|
|
5837
5970
|
};
|
|
5838
5971
|
}
|
|
5839
5972
|
async function printStatus(args = []) {
|
|
5973
|
+
assertKnownFlags(args, ["-j", "--json", "--no-probe"], "status [--json] [--no-probe]");
|
|
5840
5974
|
const asJson = hasFlag(args, "-j", "--json");
|
|
5841
5975
|
const skipProbe = hasFlag(args, "--no-probe");
|
|
5842
5976
|
const service = getServiceStatus();
|
|
@@ -5987,7 +6121,7 @@ function resolveStartMode(args) {
|
|
|
5987
6121
|
return modeToken === "tun" ? "tun" : "mixed";
|
|
5988
6122
|
}
|
|
5989
6123
|
async function cmdStart(args) {
|
|
5990
|
-
|
|
6124
|
+
assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "start [tun|mixed]");
|
|
5991
6125
|
const targetMode = resolveStartMode(args);
|
|
5992
6126
|
if (!hasKernel()) {
|
|
5993
6127
|
throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
@@ -6087,17 +6221,6 @@ async function restartToApply(args) {
|
|
|
6087
6221
|
await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
|
|
6088
6222
|
return true;
|
|
6089
6223
|
}
|
|
6090
|
-
function cleanupLegacyInstallOrThrow() {
|
|
6091
|
-
try {
|
|
6092
|
-
cleanupLegacySystemInstall();
|
|
6093
|
-
} catch (e) {
|
|
6094
|
-
if (e instanceof CliError) throw e;
|
|
6095
|
-
throw new CliError(e.message, {
|
|
6096
|
-
label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
|
|
6097
|
-
hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
|
|
6098
|
-
});
|
|
6099
|
-
}
|
|
6100
|
-
}
|
|
6101
6224
|
|
|
6102
6225
|
// src/commands/directory.ts
|
|
6103
6226
|
function openDirectory(args) {
|
|
@@ -6209,6 +6332,7 @@ var SUBCOMMANDS2 = [
|
|
|
6209
6332
|
{ name: "off", aliases: ["disable"], description: "\u7981\u7528\u8986\u5199", handler: (args) => setOverwrite(false, args) }
|
|
6210
6333
|
];
|
|
6211
6334
|
async function cmdOverwrite(args) {
|
|
6335
|
+
assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "ow [on|off]");
|
|
6212
6336
|
await dispatchSubcommand(args, SUBCOMMANDS2, {
|
|
6213
6337
|
// 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
|
|
6214
6338
|
fallback: () => {
|
|
@@ -6328,10 +6452,11 @@ async function subAdd(args) {
|
|
|
6328
6452
|
throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25" });
|
|
6329
6453
|
}
|
|
6330
6454
|
console.log("");
|
|
6455
|
+
printRestartHintIfRunning();
|
|
6331
6456
|
printSubscriptionList();
|
|
6332
6457
|
}
|
|
6333
6458
|
async function subUpdate(args) {
|
|
6334
|
-
const name = args
|
|
6459
|
+
const name = getNonFlagArg(args, 2);
|
|
6335
6460
|
const subs = getSubscriptions();
|
|
6336
6461
|
if (subs.length === 0) {
|
|
6337
6462
|
throw new CliError("\u6CA1\u6709\u8BA2\u9605");
|
|
@@ -6362,7 +6487,7 @@ async function subUpdate(args) {
|
|
|
6362
6487
|
printSubscriptionList();
|
|
6363
6488
|
}
|
|
6364
6489
|
async function subUse(args) {
|
|
6365
|
-
const name = args
|
|
6490
|
+
const name = getNonFlagArg(args, 2);
|
|
6366
6491
|
const subs = getSubscriptions();
|
|
6367
6492
|
if (subs.length === 0) {
|
|
6368
6493
|
throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo sub add <url> [name]" });
|
|
@@ -6426,6 +6551,7 @@ var SUBCOMMANDS3 = [
|
|
|
6426
6551
|
{ name: "remove", aliases: ["rm", "delete"], description: "\u5220\u9664\u8BA2\u9605", handler: subRemove }
|
|
6427
6552
|
];
|
|
6428
6553
|
async function cmdSubscription(args) {
|
|
6554
|
+
assertKnownFlags(args, ["-y", "--yes", "-s", "--no-update", "-u", "--update-timeout"], "sub [add|update|use|remove]");
|
|
6429
6555
|
await dispatchSubcommand(args, SUBCOMMANDS3, {
|
|
6430
6556
|
// 无子命令 → 列表;未知子命令 → 报错
|
|
6431
6557
|
fallback: printSubscriptionList,
|
|
@@ -6441,7 +6567,7 @@ async function cmdSubscription(args) {
|
|
|
6441
6567
|
|
|
6442
6568
|
// src/commands/completion.ts
|
|
6443
6569
|
function commandWords(commands) {
|
|
6444
|
-
return commands.filter((c) => !c.hidden).
|
|
6570
|
+
return commands.filter((c) => !c.hidden).flatMap((c) => [{ word: c.name, desc: c.usage[0]?.description ?? "" }, ...c.aliases.map((a) => ({ word: a, desc: c.usage[0]?.description ?? "" }))]);
|
|
6445
6571
|
}
|
|
6446
6572
|
function subWords(subs) {
|
|
6447
6573
|
return subs.flatMap((s) => [{ word: s.name, desc: s.description ?? "" }, ...(s.aliases ?? []).map((a) => ({ word: a, desc: s.description ?? "" }))]);
|
|
@@ -6481,23 +6607,26 @@ function buildZsh(commands, groups) {
|
|
|
6481
6607
|
];
|
|
6482
6608
|
for (const group of groups) {
|
|
6483
6609
|
const aliases = group.tokens.join("|");
|
|
6610
|
+
const isDirectory = group.tokens.includes("directory");
|
|
6484
6611
|
lines.push(` ${aliases})`);
|
|
6485
6612
|
lines.push(" subcmds=(");
|
|
6486
6613
|
for (const s of group.words) lines.push(` '${s.word}:${s.desc.replace(/'/g, "''")}'`);
|
|
6487
6614
|
lines.push(" )");
|
|
6488
6615
|
lines.push(" if (( CURRENT == 2 )); then");
|
|
6489
6616
|
lines.push(" _describe 'subcommand' subcmds");
|
|
6490
|
-
|
|
6491
|
-
|
|
6617
|
+
if (isDirectory) {
|
|
6618
|
+
lines.push(" elif (( CURRENT == 3 )) && [[ ${words[2]} == open ]]; then");
|
|
6619
|
+
lines.push(` _values 'target' ${DIR_TARGETS.join(" ")}`);
|
|
6620
|
+
lines.push(" else");
|
|
6621
|
+
lines.push(" _files");
|
|
6622
|
+
} else {
|
|
6623
|
+
lines.push(" else");
|
|
6624
|
+
lines.push(" _files");
|
|
6625
|
+
}
|
|
6492
6626
|
lines.push(" fi");
|
|
6493
6627
|
lines.push(" ;;");
|
|
6494
6628
|
}
|
|
6495
6629
|
lines.push(
|
|
6496
|
-
" directory|dir|dirs|directories)",
|
|
6497
|
-
" if (( CURRENT == 3 )); then",
|
|
6498
|
-
` _values 'target' ${DIR_TARGETS.join(" ")}`,
|
|
6499
|
-
" fi",
|
|
6500
|
-
" ;;",
|
|
6501
6630
|
" logs)",
|
|
6502
6631
|
" _arguments '-f[\u5B9E\u65F6\u8DDF\u968F]' '-n[\u663E\u793A\u884C\u6570]:\u884C\u6570:' '-o[\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00]' '1::\u7F16\u53F7:'",
|
|
6503
6632
|
" ;;",
|
|
@@ -6505,7 +6634,7 @@ function buildZsh(commands, groups) {
|
|
|
6505
6634
|
` _values 'ui' ${UI_NAMES.join(" ")}`,
|
|
6506
6635
|
" ;;",
|
|
6507
6636
|
" kernel)",
|
|
6508
|
-
" _arguments '--mirror[\u8D70\u955C\u50CF\u4E0B\u8F7D]:\u955C\u50CF:
|
|
6637
|
+
" _arguments '--mirror[\u8D70\u955C\u50CF\u4E0B\u8F7D]:\u955C\u50CF:(cdn v4 v6 axisnow)'",
|
|
6509
6638
|
" ;;",
|
|
6510
6639
|
" reset)",
|
|
6511
6640
|
` _values 'target' subs logs data runtime settings kernel overwrites service`,
|
|
@@ -6513,7 +6642,7 @@ function buildZsh(commands, groups) {
|
|
|
6513
6642
|
" ;;",
|
|
6514
6643
|
" completion)",
|
|
6515
6644
|
" if (( CURRENT == 2 )); then",
|
|
6516
|
-
|
|
6645
|
+
` _values 'action' install ${SHELLS.join(" ")}`,
|
|
6517
6646
|
" elif (( CURRENT == 3 )) && [[ ${words[2]} == install ]]; then",
|
|
6518
6647
|
` _values 'shell' ${SHELLS.join(" ")}`,
|
|
6519
6648
|
" fi",
|
|
@@ -6566,20 +6695,20 @@ _mihomo_completions() {
|
|
|
6566
6695
|
case "\${COMP_WORDS[1]}" in
|
|
6567
6696
|
${subCase}
|
|
6568
6697
|
logs)
|
|
6569
|
-
COMPREPLY=( $(compgen -W "-f -n -o --
|
|
6698
|
+
COMPREPLY=( $(compgen -W "-f -n -o --lines --follow --open" -- "\${cur}") )
|
|
6570
6699
|
;;
|
|
6571
6700
|
ui)
|
|
6572
6701
|
COMPREPLY=( $(compgen -W "${UI_NAMES.join(" ")}" -- "\${cur}") )
|
|
6573
6702
|
;;
|
|
6574
6703
|
kernel)
|
|
6575
|
-
COMPREPLY=( $(compgen -W "--mirror
|
|
6704
|
+
COMPREPLY=( $(compgen -W "--mirror" -- "\${cur}") )
|
|
6576
6705
|
;;
|
|
6577
6706
|
reset)
|
|
6578
6707
|
COMPREPLY=( $(compgen -W "subs logs data runtime settings kernel overwrites service --full -y" -- "\${cur}") )
|
|
6579
6708
|
;;
|
|
6580
6709
|
completion)
|
|
6581
6710
|
if [[ \${COMP_CWORD} -eq 2 ]]; then
|
|
6582
|
-
COMPREPLY=( $(compgen -W "install" -- "\${cur}") )
|
|
6711
|
+
COMPREPLY=( $(compgen -W "install ${SHELLS.join(" ")}" -- "\${cur}") )
|
|
6583
6712
|
elif [[ \${COMP_CWORD} -eq 3 ]] && [[ "\${COMP_WORDS[2]}" == install ]]; then
|
|
6584
6713
|
COMPREPLY=( $(compgen -W "${SHELLS.join(" ")}" -- "\${cur}") )
|
|
6585
6714
|
fi
|
|
@@ -6606,10 +6735,9 @@ function buildFish(commands, groups) {
|
|
|
6606
6735
|
}
|
|
6607
6736
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories open" -a '${DIR_TARGETS.join(" ")}'`);
|
|
6608
6737
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui" -a '${UI_NAMES.join(" ")}'`);
|
|
6609
|
-
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install' -d '\u5B89\u88C5\u8865\u5168\u5230\u9ED8\u8BA4\u4F4D\u7F6E'`);
|
|
6738
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install ${SHELLS.join(" ")}' -d '\u5B89\u88C5\u8865\u5168\u5230\u9ED8\u8BA4\u4F4D\u7F6E'`);
|
|
6610
6739
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion; and __fish_seen_subcommand_from install" -a '${SHELLS.join(" ")}'`);
|
|
6611
6740
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--mirror' -d '\u8D70\u955C\u50CF\u4E0B\u8F7D'`);
|
|
6612
|
-
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--no-mirror' -d '\u76F4\u8FDE\u4E0B\u8F7D'`);
|
|
6613
6741
|
lines.push("end");
|
|
6614
6742
|
return lines.join("\n");
|
|
6615
6743
|
}
|
|
@@ -6633,7 +6761,7 @@ function buildCompletionScript(shell, commands) {
|
|
|
6633
6761
|
}
|
|
6634
6762
|
var BASH_MARKER = "# >>> mihomo-cli completion (append)";
|
|
6635
6763
|
function completionInstallPath(shell) {
|
|
6636
|
-
const home =
|
|
6764
|
+
const home = os3.homedir();
|
|
6637
6765
|
switch (shell) {
|
|
6638
6766
|
case "zsh":
|
|
6639
6767
|
return path8.join(home, ".zsh", "completions", "_mihomo");
|
|
@@ -6656,23 +6784,30 @@ function installCompletion(shell, commands) {
|
|
|
6656
6784
|
}
|
|
6657
6785
|
const script = buildCompletionScript(shell, commands);
|
|
6658
6786
|
console.log(`\u5B89\u88C5 ${shell} \u8865\u5168: ${target}`);
|
|
6659
|
-
|
|
6660
|
-
|
|
6661
|
-
|
|
6662
|
-
|
|
6663
|
-
|
|
6664
|
-
|
|
6665
|
-
|
|
6666
|
-
|
|
6787
|
+
try {
|
|
6788
|
+
if (shell === "bash") {
|
|
6789
|
+
const existing = fs10.existsSync(target) ? fs10.readFileSync(target, "utf8") : "";
|
|
6790
|
+
if (existing.includes(BASH_MARKER)) {
|
|
6791
|
+
console.log("\u5DF2\u5B89\u88C5\u8FC7\uFF08~/.bash_completion \u5DF2\u5305\u542B mihomo \u8865\u5168\uFF09\uFF0C\u8DF3\u8FC7");
|
|
6792
|
+
return;
|
|
6793
|
+
}
|
|
6794
|
+
fs10.mkdirSync(path8.dirname(target), { recursive: true });
|
|
6795
|
+
fs10.appendFileSync(target, `
|
|
6667
6796
|
${BASH_MARKER}
|
|
6668
6797
|
${script}${BASH_MARKER.replace(">>>", "<<<")}
|
|
6669
6798
|
`);
|
|
6670
|
-
|
|
6671
|
-
|
|
6799
|
+
console.log(colors.green("\u5DF2\u8FFD\u52A0\u5230 ~/.bash_completion\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6800
|
+
return;
|
|
6801
|
+
}
|
|
6802
|
+
fs10.mkdirSync(path8.dirname(target), { recursive: true });
|
|
6803
|
+
fs10.writeFileSync(target, script, { mode: 420 });
|
|
6804
|
+
console.log(colors.green("\u5DF2\u5199\u5165\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6805
|
+
} catch (e) {
|
|
6806
|
+
throw new CliError(`\u8865\u5168\u5B89\u88C5\u5931\u8D25: ${e.message}`, {
|
|
6807
|
+
label: "\u5B89\u88C5\u5931\u8D25",
|
|
6808
|
+
hint: ["\u8BF7\u68C0\u67E5\u76EE\u6807\u76EE\u5F55\u7684\u5199\u6743\u9650\uFF0C\u6216\u624B\u52A8\u91CD\u5B9A\u5411\u8865\u5168\u811A\u672C:", ` mihomo completion ${shell} >> ${target}`]
|
|
6809
|
+
});
|
|
6672
6810
|
}
|
|
6673
|
-
fs10.mkdirSync(path8.dirname(target), { recursive: true });
|
|
6674
|
-
fs10.writeFileSync(target, script, { mode: 420 });
|
|
6675
|
-
console.log(colors.green("\u5DF2\u5199\u5165\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6676
6811
|
if (shell === "zsh") {
|
|
6677
6812
|
console.log(colors.gray("\u82E5\u8865\u5168\u4E0D\u751F\u6548\uFF0C\u5728 ~/.zshrc \u4E2D\u52A0\u4E00\u884C: fpath=(~/.zsh/completions $fpath)"));
|
|
6678
6813
|
}
|
|
@@ -6772,11 +6907,20 @@ async function cmdUpdate() {
|
|
|
6772
6907
|
console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
|
|
6773
6908
|
console.log("");
|
|
6774
6909
|
const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
|
|
6775
|
-
if (latest && latest === VERSION) {
|
|
6776
|
-
console.log(`\u5DF2\u662F\u6700\u65B0\u7248\u672C (${colors.green(VERSION)})\uFF0C\u65E0\u9700\u66F4\u65B0`);
|
|
6777
|
-
return;
|
|
6778
|
-
}
|
|
6779
6910
|
if (latest) {
|
|
6911
|
+
try {
|
|
6912
|
+
const cmp = compareVersions(VERSION, latest);
|
|
6913
|
+
if (cmp > 0) {
|
|
6914
|
+
console.log(colors.yellow(`\u5F53\u524D\u7248\u672C (${VERSION}) \u9886\u5148\u4E8E npm \u6700\u65B0\u7248 (${latest})\uFF0C\u8DF3\u8FC7\u66F4\u65B0\uFF08\u907F\u514D\u964D\u7EA7\uFF09`));
|
|
6915
|
+
console.log(colors.gray("\u5982\u9700\u5F3A\u5236\u91CD\u88C5: npm install -g mihomo-cli"));
|
|
6916
|
+
return;
|
|
6917
|
+
}
|
|
6918
|
+
if (cmp === 0) {
|
|
6919
|
+
console.log(`\u5DF2\u662F\u6700\u65B0\u7248\u672C (${colors.green(VERSION)})\uFF0C\u65E0\u9700\u66F4\u65B0`);
|
|
6920
|
+
return;
|
|
6921
|
+
}
|
|
6922
|
+
} catch {
|
|
6923
|
+
}
|
|
6780
6924
|
console.log(`\u6700\u65B0\u7248\u672C: ${colors.cyan(latest)}`);
|
|
6781
6925
|
} else {
|
|
6782
6926
|
console.log(colors.yellow("\u65E0\u6CD5\u67E5\u8BE2\u6700\u65B0\u7248\u672C\uFF08\u7F51\u7EDC\u95EE\u9898\uFF1F\uFF09\uFF0C\u5C06\u76F4\u63A5\u5C1D\u8BD5\u91CD\u65B0\u5B89\u88C5"));
|
|
@@ -6835,6 +6979,8 @@ async function collectChecks() {
|
|
|
6835
6979
|
const r = spawnSync6(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
6836
6980
|
if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
|
|
6837
6981
|
push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
|
|
6982
|
+
} else if (r.error) {
|
|
6983
|
+
push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08${r.error.message}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
|
|
6838
6984
|
} else {
|
|
6839
6985
|
push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${r.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
|
|
6840
6986
|
}
|
|
@@ -7006,6 +7152,17 @@ function assertTrustedAssetUrl(rawUrl) {
|
|
|
7006
7152
|
\u4EC5\u5141\u8BB8: ${[...ALLOWED_ASSET_HOSTS].join(", ")}`);
|
|
7007
7153
|
}
|
|
7008
7154
|
}
|
|
7155
|
+
function resolveDownloadChannel(input) {
|
|
7156
|
+
if (input.isOverride && !input.mirror) return { kind: "direct" };
|
|
7157
|
+
if (input.isOverride && input.mirror) return { kind: "mirror", mirror: input.mirror };
|
|
7158
|
+
if (input.ghAvailable) return { kind: "gh" };
|
|
7159
|
+
if (input.proxyRunning && input.proxyPort !== null) return { kind: "proxy", port: input.proxyPort };
|
|
7160
|
+
return { kind: "direct" };
|
|
7161
|
+
}
|
|
7162
|
+
function hasGh() {
|
|
7163
|
+
const result = spawnSync7("gh", ["--version"], { stdio: "ignore" });
|
|
7164
|
+
return !result.error && result.status === 0;
|
|
7165
|
+
}
|
|
7009
7166
|
function getArch() {
|
|
7010
7167
|
const arch = process.arch;
|
|
7011
7168
|
if (arch === "arm64") return "arm64";
|
|
@@ -7022,10 +7179,7 @@ function findMatchingAsset(assets, platform, arch) {
|
|
|
7022
7179
|
const standardAsset = matchingAssets.find((a) => new RegExp(`^${escapeRegExp(prefix)}-v?\\d+\\.\\d+\\.\\d+$`).test(a.name.slice(0, -3)));
|
|
7023
7180
|
return standardAsset || matchingAssets[0];
|
|
7024
7181
|
}
|
|
7025
|
-
|
|
7026
|
-
const url = `https://api.github.com/repos/${repo}/releases`;
|
|
7027
|
-
const response = await HTTP_CLIENT2.get(url, { responseType: "json" });
|
|
7028
|
-
const releases = response.data;
|
|
7182
|
+
function pickLatestRelease(releases) {
|
|
7029
7183
|
if (!Array.isArray(releases) || releases.length === 0) {
|
|
7030
7184
|
throw new Error("\u65E0\u6CD5\u83B7\u53D6\u7248\u672C\u4FE1\u606F");
|
|
7031
7185
|
}
|
|
@@ -7034,9 +7188,54 @@ async function getLatestRelease(repo) {
|
|
|
7034
7188
|
);
|
|
7035
7189
|
return stableReleases.length > 0 ? stableReleases[0] : releases[0];
|
|
7036
7190
|
}
|
|
7037
|
-
async function
|
|
7191
|
+
async function getLatestRelease(repo, proxyPort) {
|
|
7192
|
+
const url = `https://api.github.com/repos/${repo}/releases`;
|
|
7193
|
+
if (proxyPort) {
|
|
7194
|
+
const result = spawnSync7(
|
|
7195
|
+
"curl",
|
|
7196
|
+
[
|
|
7197
|
+
"-s",
|
|
7198
|
+
"-x",
|
|
7199
|
+
`http://127.0.0.1:${proxyPort}`,
|
|
7200
|
+
"--proto",
|
|
7201
|
+
"=https",
|
|
7202
|
+
"--proto-redir",
|
|
7203
|
+
"=https",
|
|
7204
|
+
"--connect-timeout",
|
|
7205
|
+
"10",
|
|
7206
|
+
"--max-time",
|
|
7207
|
+
String(Math.floor(KERNEL_HTTP_TIMEOUT / 1e3)),
|
|
7208
|
+
"-H",
|
|
7209
|
+
`User-Agent: mihomo-cli/${VERSION}`,
|
|
7210
|
+
url
|
|
7211
|
+
],
|
|
7212
|
+
{ encoding: "utf8", maxBuffer: 50 * 1024 * 1024, timeout: KERNEL_HTTP_TIMEOUT + 1e4 }
|
|
7213
|
+
);
|
|
7214
|
+
if (result.error) {
|
|
7215
|
+
if (result.error.code === "ENOENT") {
|
|
7216
|
+
throw new Error("\u672A\u627E\u5230 curl \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 curl \u540E\u91CD\u8BD5");
|
|
7217
|
+
}
|
|
7218
|
+
throw new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25: ${result.error.message}`);
|
|
7219
|
+
}
|
|
7220
|
+
if (result.status !== 0) {
|
|
7221
|
+
const stderr = (result.stderr || "").trim();
|
|
7222
|
+
const lastLine = stderr ? stderr.split("\n").pop()?.replace(/^curl: \(\d+\)\s*/, "") : void 0;
|
|
7223
|
+
throw new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25 (curl \u9000\u51FA\u7801 ${result.status}${lastLine ? `: ${lastLine}` : ""})`);
|
|
7224
|
+
}
|
|
7225
|
+
let releases;
|
|
7226
|
+
try {
|
|
7227
|
+
releases = JSON.parse(result.stdout);
|
|
7228
|
+
} catch {
|
|
7229
|
+
throw new Error("\u7248\u672C\u67E5\u8BE2\u5931\u8D25: \u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF08\u4EE3\u7406\u53EF\u80FD\u8FD4\u56DE\u4E86\u9519\u8BEF\u9875\u9762\uFF09");
|
|
7230
|
+
}
|
|
7231
|
+
return pickLatestRelease(releases);
|
|
7232
|
+
}
|
|
7233
|
+
const response = await HTTP_CLIENT2.get(url, { responseType: "json" });
|
|
7234
|
+
return pickLatestRelease(response.data);
|
|
7235
|
+
}
|
|
7236
|
+
async function checkUpdate(proxyPort) {
|
|
7038
7237
|
const currentVersion = getKernelVersion();
|
|
7039
|
-
const latest = await getLatestRelease(GITHUB_REPO);
|
|
7238
|
+
const latest = await getLatestRelease(GITHUB_REPO, proxyPort);
|
|
7040
7239
|
const latestVersion = latest.tag_name;
|
|
7041
7240
|
let needsUpdate = false;
|
|
7042
7241
|
const currentDisplay = currentVersion || "\u672A\u5B89\u88C5";
|
|
@@ -7074,9 +7273,33 @@ function findBinaryInDir(dir, maxDepth = 4) {
|
|
|
7074
7273
|
}
|
|
7075
7274
|
return null;
|
|
7076
7275
|
}
|
|
7077
|
-
|
|
7276
|
+
function buildKernelCurlArgs(args) {
|
|
7277
|
+
const argv = [
|
|
7278
|
+
"-L",
|
|
7279
|
+
"--proto",
|
|
7280
|
+
"=https",
|
|
7281
|
+
"--proto-redir",
|
|
7282
|
+
"=https",
|
|
7283
|
+
"--max-filesize",
|
|
7284
|
+
String(args.maxBytes),
|
|
7285
|
+
"--progress-bar",
|
|
7286
|
+
"--connect-timeout",
|
|
7287
|
+
"30",
|
|
7288
|
+
"--max-time",
|
|
7289
|
+
String(Math.floor(KERNEL_DOWNLOAD_TIMEOUT / 1e3))
|
|
7290
|
+
];
|
|
7291
|
+
if (args.proxyPort) {
|
|
7292
|
+
argv.push("-x", `http://127.0.0.1:${args.proxyPort}`);
|
|
7293
|
+
}
|
|
7294
|
+
argv.push("-o", args.outputPath, args.url);
|
|
7295
|
+
return argv;
|
|
7296
|
+
}
|
|
7297
|
+
function buildGhReleaseDownloadArgs(tag, assetName, dir) {
|
|
7298
|
+
return ["release", "download", tag, "--repo", GITHUB_REPO, "--pattern", assetName, "--dir", dir, "--clobber"];
|
|
7299
|
+
}
|
|
7300
|
+
async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
7078
7301
|
ensureDirs();
|
|
7079
|
-
const latest = releaseInfo || await getLatestRelease(GITHUB_REPO);
|
|
7302
|
+
const latest = releaseInfo || await getLatestRelease(GITHUB_REPO, channel.kind === "proxy" ? channel.port : null);
|
|
7080
7303
|
const arch = getArch();
|
|
7081
7304
|
const platform = process.platform;
|
|
7082
7305
|
const asset = findMatchingAsset(latest.assets, platform, arch);
|
|
@@ -7089,72 +7312,75 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
7089
7312
|
\u5E73\u53F0: ${platform}, \u67B6\u6784: ${arch}${hint}`);
|
|
7090
7313
|
}
|
|
7091
7314
|
assertTrustedAssetUrl(asset.browser_download_url);
|
|
7092
|
-
const downloadUrl = withMirror(asset.browser_download_url, mirror);
|
|
7093
|
-
const
|
|
7315
|
+
const downloadUrl = channel.kind === "mirror" ? withMirror(asset.browser_download_url, channel.mirror) : asset.browser_download_url;
|
|
7316
|
+
const tempDir = fs12.mkdtempSync(path9.join(DIRS.kernel, ".tmp-"));
|
|
7317
|
+
const tempPath = path9.join(tempDir, path9.basename(asset.name));
|
|
7094
7318
|
const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
|
|
7095
|
-
|
|
7096
|
-
|
|
7097
|
-
|
|
7098
|
-
if (progressCallback) {
|
|
7099
|
-
progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
|
|
7100
|
-
}
|
|
7101
|
-
const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
|
|
7102
|
-
const curlResult = spawnSync7(
|
|
7103
|
-
"curl",
|
|
7104
|
-
[
|
|
7105
|
-
"-L",
|
|
7106
|
-
"--proto",
|
|
7107
|
-
"=https",
|
|
7108
|
-
"--proto-redir",
|
|
7109
|
-
"=https",
|
|
7110
|
-
"--max-filesize",
|
|
7111
|
-
String(maxBytes),
|
|
7112
|
-
"--progress-bar",
|
|
7113
|
-
"--connect-timeout",
|
|
7114
|
-
"30",
|
|
7115
|
-
"--max-time",
|
|
7116
|
-
String(Math.floor(KERNEL_DOWNLOAD_TIMEOUT / 1e3)),
|
|
7117
|
-
"-o",
|
|
7118
|
-
tempPath,
|
|
7119
|
-
downloadUrl
|
|
7120
|
-
],
|
|
7121
|
-
{ stdio: "inherit" }
|
|
7122
|
-
);
|
|
7123
|
-
if (curlResult.error) {
|
|
7124
|
-
if (curlResult.error.code === "ENOENT") {
|
|
7125
|
-
throw new Error("\u672A\u627E\u5230 curl \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 curl \u540E\u91CD\u8BD5");
|
|
7319
|
+
try {
|
|
7320
|
+
if (channel.kind === "mirror" && progressCallback) {
|
|
7321
|
+
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\u6539\u7528 gh/\u672C\u673A\u4EE3\u7406\u901A\u9053\u6216\u81EA\u884C\u6821\u9A8C\u4EA7\u7269");
|
|
7126
7322
|
}
|
|
7127
|
-
|
|
7128
|
-
|
|
7129
|
-
if (curlResult.status !== 0) {
|
|
7130
|
-
try {
|
|
7131
|
-
fs12.unlinkSync(tempPath);
|
|
7132
|
-
} catch {
|
|
7323
|
+
if (progressCallback) {
|
|
7324
|
+
progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
|
|
7133
7325
|
}
|
|
7134
|
-
|
|
7135
|
-
|
|
7136
|
-
|
|
7137
|
-
|
|
7138
|
-
|
|
7139
|
-
|
|
7140
|
-
|
|
7141
|
-
|
|
7142
|
-
|
|
7143
|
-
|
|
7144
|
-
|
|
7326
|
+
if (channel.kind === "gh") {
|
|
7327
|
+
if (/[*?[\]]/.test(asset.name) || asset.name !== path9.basename(asset.name)) {
|
|
7328
|
+
throw new Error(`\u5185\u6838\u8D44\u4EA7\u540D\u542B\u975E\u6CD5\u5B57\u7B26: ${asset.name}`);
|
|
7329
|
+
}
|
|
7330
|
+
const ghResult = spawnSync7("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
|
|
7331
|
+
stdio: "inherit",
|
|
7332
|
+
timeout: KERNEL_DOWNLOAD_TIMEOUT + 3e4
|
|
7333
|
+
});
|
|
7334
|
+
if (ghResult.error) {
|
|
7335
|
+
if (ghResult.error.code === "ENOENT") {
|
|
7336
|
+
throw new Error("\u672A\u627E\u5230 gh \u547D\u4EE4\uFF08\u9009\u62E9\u901A\u9053\u65F6\u660E\u660E\u53EF\u7528\uFF09\uFF0C\u8BF7\u91CD\u8BD5\u6216\u6539\u7528\u5176\u4ED6\u901A\u9053");
|
|
7337
|
+
}
|
|
7338
|
+
if (ghResult.error.code === "ETIMEDOUT") {
|
|
7339
|
+
throw new Error(`\u4E0B\u8F7D\u8D85\u65F6\uFF08gh ${Math.floor((KERNEL_DOWNLOAD_TIMEOUT + 3e4) / 1e3)}s \u672A\u5B8C\u6210\uFF09\uFF0CGitHub \u76F4\u8FDE\u8FC7\u6162\u65F6\u6539\u7528: mihomo kernel --mirror`);
|
|
7340
|
+
}
|
|
7341
|
+
throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${ghResult.error.message}`);
|
|
7145
7342
|
}
|
|
7146
|
-
|
|
7147
|
-
`\u4E0B\u8F7D\
|
|
7148
|
-
|
|
7343
|
+
if (ghResult.status !== 0) {
|
|
7344
|
+
throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (gh \u9000\u51FA\u7801 ${ghResult.status})`);
|
|
7345
|
+
}
|
|
7346
|
+
} else {
|
|
7347
|
+
const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
|
|
7348
|
+
const curlResult = spawnSync7(
|
|
7349
|
+
"curl",
|
|
7350
|
+
buildKernelCurlArgs({
|
|
7351
|
+
url: downloadUrl,
|
|
7352
|
+
proxyPort: channel.kind === "proxy" ? channel.port : null,
|
|
7353
|
+
maxBytes,
|
|
7354
|
+
outputPath: tempPath
|
|
7355
|
+
}),
|
|
7356
|
+
{ stdio: "inherit" }
|
|
7149
7357
|
);
|
|
7358
|
+
if (curlResult.error) {
|
|
7359
|
+
if (curlResult.error.code === "ENOENT") {
|
|
7360
|
+
throw new Error("\u672A\u627E\u5230 curl \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 curl \u540E\u91CD\u8BD5");
|
|
7361
|
+
}
|
|
7362
|
+
throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${curlResult.error.message}`);
|
|
7363
|
+
}
|
|
7364
|
+
if (curlResult.status !== 0) {
|
|
7365
|
+
throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
|
|
7366
|
+
}
|
|
7150
7367
|
}
|
|
7151
|
-
|
|
7152
|
-
|
|
7153
|
-
|
|
7154
|
-
|
|
7155
|
-
|
|
7156
|
-
|
|
7157
|
-
|
|
7368
|
+
if (!fs12.existsSync(tempPath)) {
|
|
7369
|
+
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
7370
|
+
}
|
|
7371
|
+
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
7372
|
+
const actual = fs12.statSync(tempPath).size;
|
|
7373
|
+
if (actual !== asset.size) {
|
|
7374
|
+
throw new Error(
|
|
7375
|
+
`\u4E0B\u8F7D\u7684\u6587\u4EF6\u5927\u5C0F\u4E0E release \u5143\u6570\u636E\u4E0D\u7B26\uFF08\u671F\u671B ${asset.size} \u5B57\u8282\uFF0C\u5B9E\u9645 ${actual} \u5B57\u8282\uFF09
|
|
7376
|
+
\u53EF\u80FD\u662F\u4E0B\u8F7D\u88AB\u622A\u65AD\u6216\u5185\u5BB9\u88AB\u66FF\u6362\uFF0C\u8BF7\u91CD\u8BD5\u6216\u6539\u7528\u5176\u4ED6\u901A\u9053\uFF08gh/\u672C\u673A\u4EE3\u7406/--mirror direct \u76F4\u8FDE\uFF09`
|
|
7377
|
+
);
|
|
7378
|
+
}
|
|
7379
|
+
}
|
|
7380
|
+
if (progressCallback) {
|
|
7381
|
+
progressCallback("\u89E3\u538B\u5185\u6838...");
|
|
7382
|
+
}
|
|
7383
|
+
let extractedBinary = null;
|
|
7158
7384
|
if (tempPath.endsWith(".tar.gz") || tempPath.endsWith(".tgz")) {
|
|
7159
7385
|
const listResult = spawnSync7("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
|
|
7160
7386
|
if (listResult.error) throw listResult.error;
|
|
@@ -7173,7 +7399,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
7173
7399
|
throw new Error(`\u5F52\u6863\u542B\u975E\u666E\u901A\u6587\u4EF6\u6761\u76EE\uFF08\u7C7B\u578B "${typeChar}"\uFF09: ${line}`);
|
|
7174
7400
|
}
|
|
7175
7401
|
}
|
|
7176
|
-
const tarResult = spawnSync7("tar", ["--no-same-owner", "-xzf", tempPath, "-C",
|
|
7402
|
+
const tarResult = spawnSync7("tar", ["--no-same-owner", "-xzf", tempPath, "-C", tempDir], {
|
|
7177
7403
|
stdio: ["ignore", "ignore", "inherit"],
|
|
7178
7404
|
timeout: 6e4
|
|
7179
7405
|
});
|
|
@@ -7181,103 +7407,99 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
7181
7407
|
if (tarResult.status !== 0) throw new Error(`tar \u9000\u51FA\u7801 ${tarResult.status}`);
|
|
7182
7408
|
} else if (tempPath.endsWith(".gz")) {
|
|
7183
7409
|
const baseName = path9.basename(tempPath, ".gz");
|
|
7184
|
-
const outputPath = path9.join(
|
|
7410
|
+
const outputPath = path9.join(tempDir, baseName);
|
|
7185
7411
|
const gzipResult = spawnSync7("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
|
|
7186
7412
|
if (gzipResult.error) throw gzipResult.error;
|
|
7187
7413
|
if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
|
|
7188
7414
|
fs12.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
|
|
7189
7415
|
extractedBinary = outputPath;
|
|
7190
7416
|
}
|
|
7191
|
-
|
|
7192
|
-
|
|
7193
|
-
|
|
7194
|
-
} catch {
|
|
7417
|
+
const foundBinary = extractedBinary || findBinaryInDir(tempDir);
|
|
7418
|
+
if (!foundBinary) {
|
|
7419
|
+
throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
|
|
7195
7420
|
}
|
|
7196
|
-
|
|
7197
|
-
|
|
7198
|
-
const foundBinary = extractedBinary || findBinaryInDir(extractPath);
|
|
7199
|
-
if (!foundBinary) {
|
|
7200
|
-
try {
|
|
7201
|
-
fs12.unlinkSync(tempPath);
|
|
7202
|
-
} catch {
|
|
7421
|
+
if (progressCallback) {
|
|
7422
|
+
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
7203
7423
|
}
|
|
7204
|
-
|
|
7205
|
-
|
|
7206
|
-
|
|
7207
|
-
|
|
7208
|
-
|
|
7209
|
-
|
|
7210
|
-
|
|
7211
|
-
|
|
7212
|
-
|
|
7424
|
+
fs12.chmodSync(foundBinary, 493);
|
|
7425
|
+
const check = spawnSync7(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
7426
|
+
const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
|
|
7427
|
+
if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
|
|
7428
|
+
throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD
|
|
7429
|
+
\u9000\u51FA\u7801: ${check.status}
|
|
7430
|
+
\u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
|
|
7431
|
+
}
|
|
7432
|
+
const versionMatch = checkOutput.match(/v?(\d+\.\d+\.\d+)/);
|
|
7433
|
+
if (versionMatch && latest.tag_name) {
|
|
7434
|
+
const binaryVersion = versionMatch[1];
|
|
7435
|
+
const expectedVersion = latest.tag_name.replace(/^v/, "");
|
|
7436
|
+
if (binaryVersion !== expectedVersion) {
|
|
7437
|
+
throw new Error(`\u5185\u6838\u7248\u672C\u4E0D\u5339\u914D\uFF08\u671F\u671B ${expectedVersion}\uFF0C\u5B9E\u9645 ${binaryVersion}\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD`);
|
|
7213
7438
|
}
|
|
7214
7439
|
}
|
|
7440
|
+
const targetPath = PATHS.mihomoBinary;
|
|
7215
7441
|
fs12.renameSync(foundBinary, targetPath);
|
|
7216
|
-
|
|
7217
|
-
|
|
7218
|
-
|
|
7219
|
-
|
|
7220
|
-
}
|
|
7221
|
-
const check = spawnSync7(targetPath, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
7222
|
-
const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
|
|
7223
|
-
if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
|
|
7224
|
-
try {
|
|
7225
|
-
fs12.unlinkSync(targetPath);
|
|
7226
|
-
} catch {
|
|
7227
|
-
}
|
|
7442
|
+
fs12.chmodSync(targetPath, 493);
|
|
7443
|
+
clearKernelVersionCache();
|
|
7444
|
+
return { version: latest.tag_name, path: targetPath };
|
|
7445
|
+
} finally {
|
|
7228
7446
|
try {
|
|
7229
|
-
fs12.
|
|
7447
|
+
fs12.rmSync(tempDir, { recursive: true, force: true });
|
|
7230
7448
|
} catch {
|
|
7231
7449
|
}
|
|
7232
|
-
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
|
|
7233
|
-
\u9000\u51FA\u7801: ${check.status}
|
|
7234
|
-
\u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
|
|
7235
7450
|
}
|
|
7236
|
-
try {
|
|
7237
|
-
fs12.unlinkSync(tempPath);
|
|
7238
|
-
} catch {
|
|
7239
|
-
}
|
|
7240
|
-
clearKernelVersionCache();
|
|
7241
|
-
return { version: latest.tag_name, path: targetPath };
|
|
7242
7451
|
}
|
|
7243
7452
|
|
|
7244
7453
|
// src/commands/kernel.ts
|
|
7245
7454
|
function assertKnownKernelFlags(args) {
|
|
7246
|
-
const KNOWN_FLAGS = /* @__PURE__ */ new Set(["--mirror"
|
|
7247
|
-
const unknown = args.slice(1).filter((a) => a.startsWith("-") && !KNOWN_FLAGS.has(a) && !a.startsWith("--mirror=")).filter((a) => a !== "--mirror-all" && !a.startsWith("--mirror-all="));
|
|
7455
|
+
const KNOWN_FLAGS = /* @__PURE__ */ new Set(["--mirror"]);
|
|
7456
|
+
const unknown = args.slice(1).filter((a) => a.startsWith("-") && !KNOWN_FLAGS.has(a) && !a.startsWith("--mirror=")).filter((a) => a !== "--mirror-all" && !a.startsWith("--mirror-all=")).filter((a) => a !== "--no-mirror" && a !== "--direct");
|
|
7248
7457
|
if (unknown.length > 0) {
|
|
7249
7458
|
throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${unknown.join(", ")}`, {
|
|
7250
7459
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
7251
7460
|
hint: [
|
|
7252
7461
|
"",
|
|
7253
7462
|
"\u53EF\u7528\u9009\u9879:",
|
|
7254
|
-
" --mirror [\u955C\u50CF] \
|
|
7255
|
-
"
|
|
7463
|
+
" --mirror [\u955C\u50CF] \u5F3A\u5236\u8D70\u955C\u50CF\uFF08\u9ED8\u8BA4\u6309\u7F51\u7EDC\u9009 v6/\u88F8\u57DF\uFF09",
|
|
7464
|
+
"",
|
|
7465
|
+
"\u4E0D\u5E26\u9009\u9879\u65F6\u81EA\u52A8\u9009\u62E9\u901A\u9053: gh > \u672C\u673A\u4EE3\u7406 > \u76F4\u8FDE",
|
|
7256
7466
|
"",
|
|
7257
|
-
`\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}
|
|
7467
|
+
`\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`,
|
|
7468
|
+
"\u77ED\u522B\u540D: --mirror cdn | v4 | v6 | axisnow"
|
|
7258
7469
|
]
|
|
7259
7470
|
});
|
|
7260
7471
|
}
|
|
7261
7472
|
}
|
|
7262
7473
|
async function cmdKernel(args) {
|
|
7263
7474
|
assertKnownKernelFlags(args);
|
|
7264
|
-
const
|
|
7265
|
-
const mirrorInfo = parseMirrorArg(args, savedMirror);
|
|
7475
|
+
const mirrorInfo = parseMirrorArg(args);
|
|
7266
7476
|
const effectiveMirror = mirrorInfo.mirror;
|
|
7267
|
-
|
|
7268
|
-
|
|
7269
|
-
|
|
7270
|
-
|
|
7271
|
-
|
|
7272
|
-
|
|
7273
|
-
|
|
7274
|
-
|
|
7275
|
-
|
|
7477
|
+
const proxyRunning = getRunningState().running;
|
|
7478
|
+
const proxyPort = proxyRunning ? getPorts().mixed : null;
|
|
7479
|
+
const forceDirect = mirrorInfo.isOverride && !mirrorInfo.mirror;
|
|
7480
|
+
const channel = resolveDownloadChannel({
|
|
7481
|
+
mirror: mirrorInfo.mirror,
|
|
7482
|
+
isOverride: mirrorInfo.isOverride,
|
|
7483
|
+
ghAvailable: hasGh(),
|
|
7484
|
+
proxyRunning,
|
|
7485
|
+
proxyPort
|
|
7486
|
+
});
|
|
7487
|
+
if (channel.kind === "gh") {
|
|
7488
|
+
console.log("\u4E0B\u8F7D\u901A\u9053: gh\uFF08GitHub CLI \u76F4\u8FDE\uFF09");
|
|
7489
|
+
console.log("");
|
|
7490
|
+
} else if (channel.kind === "proxy") {
|
|
7491
|
+
console.log(`\u4E0B\u8F7D\u901A\u9053: \u672C\u673A\u4EE3\u7406 127.0.0.1:${channel.port}`);
|
|
7492
|
+
console.log("");
|
|
7493
|
+
} else if (channel.kind === "mirror") {
|
|
7494
|
+
const host = channel.mirror.replace(/^https?:\/\//, "").replace(/\/$/, "");
|
|
7495
|
+
console.log(`\u955C\u50CF: ${host}`);
|
|
7276
7496
|
console.log("");
|
|
7277
7497
|
}
|
|
7278
7498
|
let info;
|
|
7279
7499
|
try {
|
|
7280
|
-
|
|
7500
|
+
const useProxyForApi = proxyRunning && !forceDirect;
|
|
7501
|
+
const spinnerText = useProxyForApi ? "\u68C0\u67E5\u5185\u6838\u66F4\u65B0\uFF08\u7ECF\u672C\u673A\u4EE3\u7406\u8BBF\u95EE GitHub\uFF09" : "\u68C0\u67E5\u5185\u6838\u66F4\u65B0\uFF08GitHub \u76F4\u8FDE\uFF0C\u56FD\u5185\u7F51\u7EDC\u53EF\u80FD\u8F83\u6162\uFF09";
|
|
7502
|
+
info = await withSpinner(spinnerText, () => checkUpdate(useProxyForApi ? proxyPort : null));
|
|
7281
7503
|
} catch (e) {
|
|
7282
7504
|
if (e instanceof CliError) throw e;
|
|
7283
7505
|
const err = e;
|
|
@@ -7289,12 +7511,16 @@ async function cmdKernel(args) {
|
|
|
7289
7511
|
hint.push(`\u6587\u6863: ${err.response.data.documentation_url}`);
|
|
7290
7512
|
}
|
|
7291
7513
|
if (!effectiveMirror) {
|
|
7292
|
-
|
|
7293
|
-
"",
|
|
7294
|
-
|
|
7295
|
-
|
|
7296
|
-
|
|
7297
|
-
|
|
7514
|
+
if (proxyRunning && !forceDirect) {
|
|
7515
|
+
hint.push("", "\u63D0\u793A: \u7ECF\u672C\u673A\u4EE3\u7406\u67E5\u8BE2 GitHub \u5931\u8D25\uFF0C\u53EF\u68C0\u67E5\u4EE3\u7406\u72B6\u6001\uFF08mihomo status\uFF09\uFF0C\u6216 mihomo kernel --mirror direct \u91CD\u8BD5\u76F4\u8FDE");
|
|
7516
|
+
} else {
|
|
7517
|
+
hint.push(
|
|
7518
|
+
"",
|
|
7519
|
+
"\u63D0\u793A: \u76F4\u8FDE\u5931\u8D25\u6216\u4E0B\u8F7D\u8FC7\u6162\u65F6\u53EF\u4F7F\u7528\u955C\u50CF:",
|
|
7520
|
+
" mihomo kernel --mirror [\u955C\u50CF] # \u5F3A\u5236\u8D70\u955C\u50CF\uFF08\u9ED8\u8BA4\u6309\u7F51\u7EDC\u9009 v6/\u88F8\u57DF\uFF09",
|
|
7521
|
+
` \u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`
|
|
7522
|
+
);
|
|
7523
|
+
}
|
|
7298
7524
|
}
|
|
7299
7525
|
throw new CliError(err.message, { label: "\u66F4\u65B0\u5931\u8D25", hint });
|
|
7300
7526
|
}
|
|
@@ -7304,7 +7530,20 @@ async function cmdKernel(args) {
|
|
|
7304
7530
|
console.log("\u5DF2\u662F\u6700\u65B0\u7248\u672C");
|
|
7305
7531
|
} else {
|
|
7306
7532
|
console.log("\n\u6B63\u5728\u4E0B\u8F7D...");
|
|
7307
|
-
|
|
7533
|
+
let result;
|
|
7534
|
+
try {
|
|
7535
|
+
result = await downloadKernel((msg) => console.log(msg), channel, info.release);
|
|
7536
|
+
} catch (e) {
|
|
7537
|
+
if (e instanceof CliError) throw e;
|
|
7538
|
+
throw new CliError(e.message, {
|
|
7539
|
+
label: "\u4E0B\u8F7D\u5931\u8D25",
|
|
7540
|
+
hint: [
|
|
7541
|
+
"",
|
|
7542
|
+
"\u4E0B\u8F7D\u901A\u9053\u6309\u4F18\u5148\u7EA7\u81EA\u52A8\u9009\u62E9: gh\uFF08GitHub CLI\uFF09> \u672C\u673A\u4EE3\u7406 > \u955C\u50CF > \u76F4\u8FDE",
|
|
7543
|
+
"\u624B\u52A8\u6307\u5B9A: mihomo kernel --mirror [\u955C\u50CF]\uFF08\u5F3A\u5236\u955C\u50CF\uFF09/ mihomo kernel --mirror direct\uFF08\u5F3A\u5236\u76F4\u8FDE\uFF09"
|
|
7544
|
+
]
|
|
7545
|
+
});
|
|
7546
|
+
}
|
|
7308
7547
|
console.log(`
|
|
7309
7548
|
\u5DF2\u66F4\u65B0\u5230 ${result.version}`);
|
|
7310
7549
|
if (getRunningState().running) {
|
|
@@ -7315,10 +7554,13 @@ async function cmdKernel(args) {
|
|
|
7315
7554
|
|
|
7316
7555
|
// src/commands/log.ts
|
|
7317
7556
|
function cmdLogs(args) {
|
|
7557
|
+
assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"], "logs [-f] [-n N] [\u7F16\u53F7] [-o]");
|
|
7318
7558
|
const lines = parseIntArg(args, "-n", "--lines", 100);
|
|
7319
7559
|
const openInViewer = hasFlag(args, "-o", "--open");
|
|
7320
7560
|
const follow = hasFlag(args, "-f", "--follow");
|
|
7321
|
-
const hasLinesFlag = args.some(
|
|
7561
|
+
const hasLinesFlag = args.some(
|
|
7562
|
+
(a) => a === "-n" || a === "--lines" || a.startsWith("--lines=") || a.startsWith("-n") && a.length > 2 && /^\d+$/.test(a.slice(2))
|
|
7563
|
+
);
|
|
7322
7564
|
const targetName = getNonFlagArg(args, 1) ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
|
|
7323
7565
|
if (targetName) {
|
|
7324
7566
|
let logPath;
|
|
@@ -7516,7 +7758,8 @@ var RESET_TARGETS = [
|
|
|
7516
7758
|
aliases: ["log", "logs"],
|
|
7517
7759
|
label: "\u65E5\u5FD7",
|
|
7518
7760
|
paths: () => [DIRS.logs],
|
|
7519
|
-
|
|
7761
|
+
// 内核运行时持有日志 fd,删文件后内核继续写已删 inode,logs 0 会 tail 不存在的路径
|
|
7762
|
+
needsStop: true
|
|
7520
7763
|
},
|
|
7521
7764
|
{
|
|
7522
7765
|
id: "data",
|
|
@@ -7562,7 +7805,10 @@ var RESET_TARGETS = [
|
|
|
7562
7805
|
if (!fs14.existsSync(dir)) return [];
|
|
7563
7806
|
return fs14.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
|
|
7564
7807
|
},
|
|
7565
|
-
needsStop: false
|
|
7808
|
+
needsStop: false,
|
|
7809
|
+
onAfter: () => {
|
|
7810
|
+
writeSettings({ overwrite_enabled: false });
|
|
7811
|
+
}
|
|
7566
7812
|
},
|
|
7567
7813
|
{
|
|
7568
7814
|
id: "service",
|
|
@@ -7699,9 +7945,12 @@ async function cmdReset(args) {
|
|
|
7699
7945
|
});
|
|
7700
7946
|
}
|
|
7701
7947
|
}
|
|
7948
|
+
const deleted = [];
|
|
7702
7949
|
for (const t of targets) {
|
|
7950
|
+
let hadContent = false;
|
|
7703
7951
|
for (const p of t.paths()) {
|
|
7704
7952
|
if (fs14.existsSync(p)) {
|
|
7953
|
+
hadContent = true;
|
|
7705
7954
|
try {
|
|
7706
7955
|
rmrf(p);
|
|
7707
7956
|
} catch (e) {
|
|
@@ -7710,12 +7959,19 @@ async function cmdReset(args) {
|
|
|
7710
7959
|
}
|
|
7711
7960
|
}
|
|
7712
7961
|
await t.onAfter?.();
|
|
7962
|
+
if (hadContent || !t.checkEmpty) {
|
|
7963
|
+
deleted.push(t.label);
|
|
7964
|
+
}
|
|
7713
7965
|
}
|
|
7714
7966
|
ensureDirs();
|
|
7715
7967
|
if (targets.some((t) => t.id === "settings")) {
|
|
7716
7968
|
invalidateSettingsCache();
|
|
7717
7969
|
}
|
|
7718
|
-
|
|
7970
|
+
if (deleted.length > 0) {
|
|
7971
|
+
console.log(colors.green(`\u5DF2\u91CD\u7F6E: ${deleted.join("\u3001")}`));
|
|
7972
|
+
} else {
|
|
7973
|
+
console.log("\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
|
|
7974
|
+
}
|
|
7719
7975
|
}
|
|
7720
7976
|
|
|
7721
7977
|
// src/commands/service.ts
|
|
@@ -7800,8 +8056,7 @@ function handleStopResult(result) {
|
|
|
7800
8056
|
throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint: "\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo" });
|
|
7801
8057
|
}
|
|
7802
8058
|
}
|
|
7803
|
-
async function cmdStop(
|
|
7804
|
-
assertNoRemovedSshFlag(args);
|
|
8059
|
+
async function cmdStop(_args) {
|
|
7805
8060
|
if (detectLegacySystemInstall()) {
|
|
7806
8061
|
console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u505C\u6B62\u524D\u9700\u6E05\u7406"));
|
|
7807
8062
|
console.log(colors.gray(" \u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u5220\u9664 root \u62E5\u6709\u7684\u6587\u4EF6\uFF09"));
|
|
@@ -7957,7 +8212,14 @@ var COMMANDS = [
|
|
|
7957
8212
|
name: "log",
|
|
7958
8213
|
aliases: [],
|
|
7959
8214
|
handler: cmdLogs,
|
|
7960
|
-
|
|
8215
|
+
// 隐藏别名:log = logs 0 -f。用户传了编号时尊重编号(log 1 = logs 1 -f),
|
|
8216
|
+
// 而非恒为 0——此前编号被 '0' 顶掉,log 1 跟随的是当前日志而非归档 1
|
|
8217
|
+
rewrite: (args) => {
|
|
8218
|
+
const hasNum = args[1] !== void 0 && /^\d+$/.test(args[1]);
|
|
8219
|
+
const num = hasNum ? args[1] : "0";
|
|
8220
|
+
const rest = hasNum ? args.slice(2) : args.slice(1);
|
|
8221
|
+
return ["logs", num, "-f", ...rest];
|
|
8222
|
+
},
|
|
7961
8223
|
group: "interface",
|
|
7962
8224
|
usage: [],
|
|
7963
8225
|
hidden: true
|
|
@@ -8019,7 +8281,7 @@ var COMMANDS = [
|
|
|
8019
8281
|
aliases: [],
|
|
8020
8282
|
handler: cmdKernel,
|
|
8021
8283
|
group: "system",
|
|
8022
|
-
usage: [{ signature: "kernel [--mirror [\u955C\u50CF]]", description: "\u66F4\u65B0\u5185\u6838\uFF08\
|
|
8284
|
+
usage: [{ signature: "kernel [--mirror [\u955C\u50CF]]", description: "\u66F4\u65B0\u5185\u6838\uFF08\u81EA\u52A8\u9009\u62E9\u901A\u9053\uFF1Agh > \u672C\u673A\u4EE3\u7406 > \u955C\u50CF > \u76F4\u8FDE\uFF09" }]
|
|
8023
8285
|
},
|
|
8024
8286
|
{
|
|
8025
8287
|
name: "update",
|
|
@@ -8172,6 +8434,7 @@ async function main() {
|
|
|
8172
8434
|
assertSupportedPlatform(command.name);
|
|
8173
8435
|
assertNotRoot(command.name);
|
|
8174
8436
|
ensureDirs();
|
|
8437
|
+
assertNoRemovedSshFlag(args);
|
|
8175
8438
|
await command.handler(command.rewrite ? command.rewrite(args) : args);
|
|
8176
8439
|
}
|
|
8177
8440
|
main().catch((e) => {
|