mihomo-cli 26.10.100 → 26.10.102
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 -1
- package/README.md +11 -6
- package/dist/index.js +630 -641
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -136,6 +136,9 @@ var SERVICE_LABEL = RAW_SERVICE_LABEL && isValidServiceLabel(RAW_SERVICE_LABEL)
|
|
|
136
136
|
var SERVICE_BINARY_NAME = "mihomo-cli-service";
|
|
137
137
|
var DEFAULT_MIXED_PORT = 7890;
|
|
138
138
|
var CONTROLLER_PORT = 9090;
|
|
139
|
+
function isValidPortNumber(value) {
|
|
140
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535;
|
|
141
|
+
}
|
|
139
142
|
var TUN_CONFIG = {
|
|
140
143
|
tun: {
|
|
141
144
|
enable: true,
|
|
@@ -204,6 +207,7 @@ var LOCKED_CONFIG_KEYS = [
|
|
|
204
207
|
"lan-allowed-ips",
|
|
205
208
|
"lan-disallowed-ips"
|
|
206
209
|
];
|
|
210
|
+
var EFFECTIVELY_LOCKED_KEYS = [...LOCKED_CONFIG_KEYS, "tls"];
|
|
207
211
|
var BASE_CONFIG = {
|
|
208
212
|
// 注意:mixed-port、external-controller 与 allow-lan 不在此表——前两个来自
|
|
209
213
|
// settings.ports(getPorts),allow-lan 恒为 false,三者都由 config.ts 单独写入
|
|
@@ -240,20 +244,20 @@ function assertServiceLabelSafe() {
|
|
|
240
244
|
var FLAGS = [
|
|
241
245
|
// === start 的选项(重启透传) ===
|
|
242
246
|
{ forms: ["-s", "--no-update"], takesValue: false, passthroughToRestart: true },
|
|
243
|
-
{ forms: ["-u", "--update-timeout"], takesValue:
|
|
247
|
+
{ forms: ["-u", "--update-timeout"], takesValue: "required", passthroughToRestart: true },
|
|
244
248
|
// === logs 的选项 ===
|
|
245
|
-
{ forms: ["-n", "--lines"], takesValue:
|
|
249
|
+
{ forms: ["-n", "--lines"], takesValue: "required" },
|
|
246
250
|
// === kernel 的选项 ===
|
|
247
|
-
{ forms: ["-p", "--proxy"], takesValue:
|
|
248
|
-
//
|
|
249
|
-
//
|
|
250
|
-
//
|
|
251
|
-
|
|
251
|
+
{ forms: ["-p", "--proxy"], takesValue: "required" },
|
|
252
|
+
// `--mirror`(kernel)是可选值选项:裸 `--mirror` = 默认镜像域,`--mirror direct`
|
|
253
|
+
// 与 `--mirror=url` 同样合法。词法(三种形式/跳值边界)随登记表走,与 --proxy
|
|
254
|
+
// 同一套白名单与位置参数口径;值的归一化(别名/https/direct)仍由 parseMirrorArg 负责
|
|
255
|
+
{ forms: ["--mirror"], takesValue: "optional" }
|
|
252
256
|
];
|
|
253
|
-
var VALUE_FLAGS = new Set(FLAGS.filter((f) => f.takesValue).flatMap((f) => f.forms));
|
|
257
|
+
var VALUE_FLAGS = new Set(FLAGS.filter((f) => f.takesValue !== false).flatMap((f) => f.forms));
|
|
254
258
|
var START_RESTART_FLAGS = FLAGS.filter((f) => f.passthroughToRestart);
|
|
255
259
|
function matchValueFlagToken(token) {
|
|
256
|
-
const byForm = (form) => FLAGS.find((f) => f.takesValue && f.forms.includes(form));
|
|
260
|
+
const byForm = (form) => FLAGS.find((f) => f.takesValue !== false && f.forms.includes(form));
|
|
257
261
|
const exact = byForm(token);
|
|
258
262
|
if (exact) return { spec: exact, baseForm: token, form: "exact", inlineValue: null };
|
|
259
263
|
if (token.startsWith("--")) {
|
|
@@ -285,7 +289,6 @@ function assertKnownFlags(args, known, command) {
|
|
|
285
289
|
if (knownSet.has(a)) continue;
|
|
286
290
|
const match = matchValueFlagToken(a);
|
|
287
291
|
if (match && match.form !== "exact" && knownSet.has(match.baseForm)) continue;
|
|
288
|
-
if (a.startsWith("--mirror=") && knownSet.has("--mirror")) continue;
|
|
289
292
|
const isHelpFlag = a === "-h" || a === "--help";
|
|
290
293
|
const helpNote = isHelpFlag ? ["", `${a} \u53EA\u5728\u9876\u5C42\u53EF\u7528\uFF0C\u547D\u4EE4\u7528\u6CD5\u89C1: mihomo-cli help`] : [];
|
|
291
294
|
const hasValueFlag = known.some((f) => VALUE_FLAGS.has(f));
|
|
@@ -387,7 +390,7 @@ function getNonFlagArg(args, startIdx) {
|
|
|
387
390
|
for (let i = startIdx; i < args.length; i++) {
|
|
388
391
|
const a = args[i];
|
|
389
392
|
if (a.startsWith("-")) {
|
|
390
|
-
if (VALUE_FLAGS.has(a)) i++;
|
|
393
|
+
if (VALUE_FLAGS.has(a) && i + 1 < args.length && !args[i + 1].startsWith("-")) i++;
|
|
391
394
|
continue;
|
|
392
395
|
}
|
|
393
396
|
return a;
|
|
@@ -3669,26 +3672,32 @@ function sleepSyncMs(ms) {
|
|
|
3669
3672
|
// src/settings.ts
|
|
3670
3673
|
import fs2 from "fs";
|
|
3671
3674
|
import path2 from "path";
|
|
3672
|
-
function
|
|
3673
|
-
const backup = `${
|
|
3675
|
+
function backupCorruptFile(file, noun, reason, fallbackNote) {
|
|
3676
|
+
const backup = `${file}.bak`;
|
|
3674
3677
|
try {
|
|
3675
3678
|
if (fs2.existsSync(backup)) {
|
|
3676
|
-
console.warn(`\u8B66\u544A:
|
|
3679
|
+
console.warn(`\u8B66\u544A: ${noun} ${reason}\uFF0C${fallbackNote}\uFF08\u539F\u4EF6\u5DF2\u5728\u65E9\u524D\u5907\u4EFD: ${backup}\uFF0C\u672A\u8986\u76D6\uFF09`);
|
|
3677
3680
|
} else {
|
|
3678
|
-
fs2.copyFileSync(
|
|
3679
|
-
console.warn(`\u8B66\u544A:
|
|
3681
|
+
fs2.copyFileSync(file, backup);
|
|
3682
|
+
console.warn(`\u8B66\u544A: ${noun} ${reason}\uFF0C\u5DF2\u5907\u4EFD\u5230 ${backup}\uFF0C${fallbackNote}`);
|
|
3680
3683
|
}
|
|
3681
3684
|
} catch {
|
|
3682
|
-
console.warn(`\u8B66\u544A:
|
|
3685
|
+
console.warn(`\u8B66\u544A: ${noun} ${reason}\uFF0C${fallbackNote}`);
|
|
3683
3686
|
}
|
|
3687
|
+
}
|
|
3688
|
+
function backupCorruptSettings(reason) {
|
|
3689
|
+
backupCorruptFile(PATHS.settingsFile, "settings.json", reason, "\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E");
|
|
3684
3690
|
return {};
|
|
3685
3691
|
}
|
|
3692
|
+
function nonObjectReason(parsed) {
|
|
3693
|
+
return `\u5185\u5BB9\u4E0D\u662F\u5BF9\u8C61\uFF08\u5F53\u524D\u662F${Array.isArray(parsed) ? "\u6570\u7EC4" : parsed === null ? "null" : typeof parsed}\uFF09`;
|
|
3694
|
+
}
|
|
3686
3695
|
function readSettings() {
|
|
3687
3696
|
if (!fs2.existsSync(PATHS.settingsFile)) return {};
|
|
3688
3697
|
try {
|
|
3689
3698
|
const parsed = JSON.parse(fs2.readFileSync(PATHS.settingsFile, "utf8"));
|
|
3690
3699
|
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
|
|
3691
|
-
return backupCorruptSettings(
|
|
3700
|
+
return backupCorruptSettings(nonObjectReason(parsed));
|
|
3692
3701
|
} catch (e) {
|
|
3693
3702
|
if (e.code === "ENOENT") return {};
|
|
3694
3703
|
return backupCorruptSettings("\u683C\u5F0F\u635F\u574F");
|
|
@@ -3722,7 +3731,7 @@ function updateSettings(mutate, postCommit) {
|
|
|
3722
3731
|
}
|
|
3723
3732
|
function validatePort(value, key) {
|
|
3724
3733
|
if (value === void 0) return void 0;
|
|
3725
|
-
if (
|
|
3734
|
+
if (!isValidPortNumber(value)) {
|
|
3726
3735
|
throw new CliError(`settings.json \u7684 ${key} \u9700\u4E3A 1-65535 \u7684\u6574\u6570\uFF0C\u5F53\u524D\u662F ${JSON.stringify(value)}`, {
|
|
3727
3736
|
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
3728
3737
|
hint: ["\u793A\u4F8B:", ' "ports": { "mixed": 17890, "controller": 19090 }', "\u4E24\u4E2A\u952E\u5747\u53EF\u9009\uFF1B\u5220\u6389 ports \u5219\u56DE\u5230\u9ED8\u8BA4\u7AEF\u53E3 7890/9090"]
|
|
@@ -3750,51 +3759,9 @@ function getPorts(settings = readSettings()) {
|
|
|
3750
3759
|
}
|
|
3751
3760
|
return { mixed, controller };
|
|
3752
3761
|
}
|
|
3753
|
-
function
|
|
3754
|
-
try {
|
|
3755
|
-
const parsed = new URL(url);
|
|
3756
|
-
const TOKEN_KEY_NAMES = [
|
|
3757
|
-
"token",
|
|
3758
|
-
"key",
|
|
3759
|
-
"secret",
|
|
3760
|
-
"pass",
|
|
3761
|
-
"password",
|
|
3762
|
-
"auth",
|
|
3763
|
-
"access_token",
|
|
3764
|
-
"api_key",
|
|
3765
|
-
"uuid",
|
|
3766
|
-
"sid",
|
|
3767
|
-
"id",
|
|
3768
|
-
"sub",
|
|
3769
|
-
"user",
|
|
3770
|
-
"email",
|
|
3771
|
-
"passwd",
|
|
3772
|
-
"apikey",
|
|
3773
|
-
"access"
|
|
3774
|
-
];
|
|
3775
|
-
if (new Set(TOKEN_KEY_NAMES).size !== TOKEN_KEY_NAMES.length) {
|
|
3776
|
-
throw new Error("tokenKeys \u5B58\u5728\u91CD\u590D\u767B\u8BB0");
|
|
3777
|
-
}
|
|
3778
|
-
const tokenKeys = new Set(TOKEN_KEY_NAMES);
|
|
3779
|
-
for (const [key, value] of parsed.searchParams) {
|
|
3780
|
-
if (tokenKeys.has(key.toLowerCase()) || value.length >= 16) {
|
|
3781
|
-
parsed.searchParams.set(key, "***");
|
|
3782
|
-
}
|
|
3783
|
-
}
|
|
3784
|
-
if (parsed.username) parsed.username = "***";
|
|
3785
|
-
if (parsed.password) parsed.password = "***";
|
|
3786
|
-
parsed.pathname = parsed.pathname.split("/").map((seg) => seg.length >= 16 ? `${seg.slice(0, 4)}***${seg.slice(-4)}` : seg).join("/");
|
|
3787
|
-
return parsed.toString();
|
|
3788
|
-
} catch {
|
|
3789
|
-
if (url.length > 15) {
|
|
3790
|
-
return `${url.slice(0, 15)}...`;
|
|
3791
|
-
}
|
|
3792
|
-
return url;
|
|
3793
|
-
}
|
|
3794
|
-
}
|
|
3795
|
-
function getControllerPortOrNull() {
|
|
3762
|
+
function getPortsOrNull() {
|
|
3796
3763
|
try {
|
|
3797
|
-
return getPorts()
|
|
3764
|
+
return getPorts();
|
|
3798
3765
|
} catch {
|
|
3799
3766
|
return null;
|
|
3800
3767
|
}
|
|
@@ -3807,7 +3774,7 @@ function readSubscriptionCache() {
|
|
|
3807
3774
|
const content = fs2.readFileSync(PATHS.subscriptionsCacheFile, "utf8");
|
|
3808
3775
|
const parsed = JSON.parse(content);
|
|
3809
3776
|
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
3810
|
-
return backupCorruptSubscriptionCache(
|
|
3777
|
+
return backupCorruptSubscriptionCache(nonObjectReason(parsed));
|
|
3811
3778
|
}
|
|
3812
3779
|
return Object.assign(empty(), parsed);
|
|
3813
3780
|
} catch (e) {
|
|
@@ -3818,17 +3785,7 @@ function readSubscriptionCache() {
|
|
|
3818
3785
|
return empty();
|
|
3819
3786
|
}
|
|
3820
3787
|
function backupCorruptSubscriptionCache(reason) {
|
|
3821
|
-
|
|
3822
|
-
try {
|
|
3823
|
-
if (fs2.existsSync(cacheBackup)) {
|
|
3824
|
-
console.warn(`\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58${reason}\uFF0C\u5DF2\u5FFD\u7565\uFF08\u65E9\u524D\u5907\u4EFD\u4FDD\u7559\u5728 ${cacheBackup}\uFF0C\u672A\u8986\u76D6\uFF09`);
|
|
3825
|
-
} else {
|
|
3826
|
-
fs2.copyFileSync(PATHS.subscriptionsCacheFile, cacheBackup);
|
|
3827
|
-
console.warn(`\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58${reason}\uFF0C\u5DF2\u5907\u4EFD\u5230 ${cacheBackup}`);
|
|
3828
|
-
}
|
|
3829
|
-
} catch {
|
|
3830
|
-
console.warn(`\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58${reason}\uFF0C\u5DF2\u5FFD\u7565`);
|
|
3831
|
-
}
|
|
3788
|
+
backupCorruptFile(PATHS.subscriptionsCacheFile, "\u8BA2\u9605\u7F13\u5B58", reason, "\u5DF2\u5FFD\u7565");
|
|
3832
3789
|
return /* @__PURE__ */ Object.create(null);
|
|
3833
3790
|
}
|
|
3834
3791
|
function writeSubscriptionCache(cache) {
|
|
@@ -3956,6 +3913,13 @@ function readSubscriptionRawConfig(subName) {
|
|
|
3956
3913
|
if (!fs2.existsSync(filePath)) return null;
|
|
3957
3914
|
return fs2.readFileSync(filePath, "utf8");
|
|
3958
3915
|
}
|
|
3916
|
+
function requireSubscriptionRawConfig(subName) {
|
|
3917
|
+
const content = readSubscriptionRawConfig(subName);
|
|
3918
|
+
if (content === null) {
|
|
3919
|
+
throw new CliError(`\u8BA2\u9605 "${subName}" \u6709\u6761\u76EE\u4F46\u6CA1\u6709\u672C\u5730\u914D\u7F6E\u6587\u4EF6`, { hint: `\u66F4\u65B0\u8BA2\u9605: mihomo-cli sub update ${subName}` });
|
|
3920
|
+
}
|
|
3921
|
+
return content;
|
|
3922
|
+
}
|
|
3959
3923
|
|
|
3960
3924
|
// src/overwrite.ts
|
|
3961
3925
|
function parseOverrideKey(key) {
|
|
@@ -3977,6 +3941,18 @@ function parseOverrideKey(key) {
|
|
|
3977
3941
|
}
|
|
3978
3942
|
return { key: actualKey, forceOverwrite, arrayPrepend, arrayAppend };
|
|
3979
3943
|
}
|
|
3944
|
+
function lockedKeysReferencedBy(rawKeys) {
|
|
3945
|
+
const hit = /* @__PURE__ */ new Set();
|
|
3946
|
+
for (const rawKey of rawKeys) {
|
|
3947
|
+
if (EFFECTIVELY_LOCKED_KEYS.includes(rawKey)) {
|
|
3948
|
+
hit.add(rawKey);
|
|
3949
|
+
continue;
|
|
3950
|
+
}
|
|
3951
|
+
const parsedKey = parseOverrideKey(rawKey).key;
|
|
3952
|
+
if (parsedKey !== rawKey && EFFECTIVELY_LOCKED_KEYS.includes(parsedKey)) hit.add(parsedKey);
|
|
3953
|
+
}
|
|
3954
|
+
return [...hit];
|
|
3955
|
+
}
|
|
3980
3956
|
function assertValidParsedKey(rawKey, parsed) {
|
|
3981
3957
|
if (rawKey.startsWith("~") || parsed.key.includes("~")) {
|
|
3982
3958
|
throw new CliError(`\u8986\u5199\u952E "${rawKey}" \u7528\u4E86\u5DF2\u79FB\u9664\u7684 ~ \u64CD\u4F5C\u7B26`, {
|
|
@@ -4091,11 +4067,16 @@ function isYamlOverwriteFilename(filename) {
|
|
|
4091
4067
|
return filename === "overwrite.yaml" || /^overwrite\..+\.ya?ml$/.test(filename);
|
|
4092
4068
|
}
|
|
4093
4069
|
var SCRIPT_EXTENSIONS = ["js", "mjs", "cjs"];
|
|
4070
|
+
var SCRIPT_EXTENSION_PATTERN = `(?:${SCRIPT_EXTENSIONS.join("|")})`;
|
|
4071
|
+
var OVERWRITE_EXTENSION_RE = new RegExp(`\\.(?:ya?ml|${SCRIPT_EXTENSIONS.join("|")})$`);
|
|
4094
4072
|
function isPrimaryScriptFilename(filename) {
|
|
4095
4073
|
return SCRIPT_EXTENSIONS.some((ext) => filename === `overwrite.${ext}`);
|
|
4096
4074
|
}
|
|
4097
4075
|
function isScriptOverwriteFilename(filename) {
|
|
4098
|
-
return isPrimaryScriptFilename(filename) ||
|
|
4076
|
+
return isPrimaryScriptFilename(filename) || new RegExp(`^overwrite\\..+\\.${SCRIPT_EXTENSION_PATTERN}$`).test(filename);
|
|
4077
|
+
}
|
|
4078
|
+
function shortOverwriteName(name) {
|
|
4079
|
+
return name.replace(OVERWRITE_EXTENSION_RE, "").replace(/^overwrite\.?/, "") || "\u4E3B\u6587\u4EF6";
|
|
4099
4080
|
}
|
|
4100
4081
|
function isOverwriteFilename(filename) {
|
|
4101
4082
|
return isYamlOverwriteFilename(filename) || isScriptOverwriteFilename(filename);
|
|
@@ -4103,7 +4084,11 @@ function isOverwriteFilename(filename) {
|
|
|
4103
4084
|
function isOverwriteFilenameTypo(filename) {
|
|
4104
4085
|
if (isOverwriteFilename(filename)) return false;
|
|
4105
4086
|
const lower = filename.toLowerCase();
|
|
4106
|
-
return
|
|
4087
|
+
return (
|
|
4088
|
+
// overwrite.yml 是 typo 特有的近失(主文件只认 .yaml);其余 YAML 形态直接复用
|
|
4089
|
+
// 合法判定,扩展名知识不留第二份
|
|
4090
|
+
lower === "overwrite.yml" || isYamlOverwriteFilename(lower) || lower === "overwrite.ts" || /^overwrite\..+\.ts$/.test(lower)
|
|
4091
|
+
);
|
|
4107
4092
|
}
|
|
4108
4093
|
function listTypoOverwriteFiles() {
|
|
4109
4094
|
try {
|
|
@@ -4215,10 +4200,9 @@ function summarizeMatch(match) {
|
|
|
4215
4200
|
if (!match) return void 0;
|
|
4216
4201
|
const parts = [];
|
|
4217
4202
|
for (const [key, value] of Object.entries(match)) {
|
|
4218
|
-
|
|
4219
|
-
parts.push(`${key}=${vals.join("/")}`);
|
|
4203
|
+
parts.push(`${key}=${value.join("/")}`);
|
|
4220
4204
|
}
|
|
4221
|
-
return parts.
|
|
4205
|
+
return parts.join(", ");
|
|
4222
4206
|
}
|
|
4223
4207
|
function describeOverwriteScope(file) {
|
|
4224
4208
|
return `${file.name} (${summarizeMatch(file.match) ?? "\u5168\u5C40"})`;
|
|
@@ -4235,23 +4219,25 @@ function nameMatchesPattern(name, pattern) {
|
|
|
4235
4219
|
if (p.endsWith("*")) return n.startsWith(p.slice(0, -1));
|
|
4236
4220
|
return n === p;
|
|
4237
4221
|
}
|
|
4222
|
+
function hostFromSubUrl(subUrl) {
|
|
4223
|
+
if (!subUrl) return null;
|
|
4224
|
+
try {
|
|
4225
|
+
return new URL(subUrl.trim()).hostname;
|
|
4226
|
+
} catch {
|
|
4227
|
+
return null;
|
|
4228
|
+
}
|
|
4229
|
+
}
|
|
4238
4230
|
function matchesScope(match, scope) {
|
|
4239
4231
|
if (!match) return true;
|
|
4240
4232
|
if (match.name) {
|
|
4241
|
-
const names = Array.isArray(match.name) ? match.name : [match.name];
|
|
4242
4233
|
if (!scope?.subName) return false;
|
|
4243
4234
|
const subName = scope.subName;
|
|
4244
|
-
if (!
|
|
4235
|
+
if (!match.name.some((n) => nameMatchesPattern(subName, n))) return false;
|
|
4245
4236
|
}
|
|
4246
4237
|
if (match["url-domain"]) {
|
|
4247
|
-
const domains =
|
|
4248
|
-
|
|
4249
|
-
|
|
4250
|
-
try {
|
|
4251
|
-
host = new URL(scope.subUrl.trim()).hostname;
|
|
4252
|
-
} catch {
|
|
4253
|
-
return false;
|
|
4254
|
-
}
|
|
4238
|
+
const domains = match["url-domain"];
|
|
4239
|
+
const host = hostFromSubUrl(scope?.subUrl);
|
|
4240
|
+
if (host === null) return false;
|
|
4255
4241
|
if (!domains.some((d) => hostMatchesDomain(host, d))) return false;
|
|
4256
4242
|
}
|
|
4257
4243
|
return true;
|
|
@@ -4315,16 +4301,16 @@ function normalizeEnabled(raw, fileName) {
|
|
|
4315
4301
|
}
|
|
4316
4302
|
);
|
|
4317
4303
|
}
|
|
4318
|
-
function toBrokenFile(file,
|
|
4304
|
+
function toBrokenFile(file, e) {
|
|
4319
4305
|
if (e instanceof CliError) {
|
|
4320
|
-
return { name: file,
|
|
4306
|
+
return { name: file, label: e.label, message: e.message, hint: e.hint };
|
|
4321
4307
|
}
|
|
4322
4308
|
const message = e.message || String(e);
|
|
4323
4309
|
const hint = ["\u8BE5\u6587\u4EF6\u5F53\u524D\u672A\u53C2\u4E0E\u5408\u5E76\uFF0C\u8BF7\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF08mihomo-cli ow \u53EF\u67E5\u770B\u5168\u90E8\u8986\u5199\u6587\u4EF6\uFF09\u3002"];
|
|
4324
4310
|
if (/alias/i.test(message)) {
|
|
4325
4311
|
hint.push('\u82E5\u5199\u4E86\u4EE5 * \u5F00\u5934\u7684\u901A\u914D\u503C\uFF08\u5982 name: *edu\uFF09\uFF0CYAML \u4F1A\u628A\u5B83\u5F53\u522B\u540D\u8BED\u6CD5\uFF0C\u8BF7\u52A0\u5F15\u53F7\u5199\u6210 name: "*edu"');
|
|
4326
4312
|
}
|
|
4327
|
-
return { name: file,
|
|
4313
|
+
return { name: file, label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF", message: `\u8986\u5199\u6587\u4EF6 "${file}" \u89E3\u6790\u5931\u8D25: ${message}`, hint };
|
|
4328
4314
|
}
|
|
4329
4315
|
function loadOverwriteScript(filePath, fileName) {
|
|
4330
4316
|
let mod;
|
|
@@ -4341,7 +4327,7 @@ function loadOverwriteScript(filePath, fileName) {
|
|
|
4341
4327
|
throw new CliError(`\u8986\u5199\u811A\u672C "${fileName}" \u7F3A\u5C11\u53D8\u6362\u51FD\u6570`, {
|
|
4342
4328
|
label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
|
|
4343
4329
|
hint: [
|
|
4344
|
-
"\u5199\u6CD5\uFF08\u5C31\u5730\u4FEE\u6539\u4F20\u5165\u7684 config\uFF0C\u8FD4\u56DE\u503C\u5FFD\u7565\uFF09:",
|
|
4330
|
+
"\u5199\u6CD5\uFF08\u5C31\u5730\u4FEE\u6539\u4F20\u5165\u7684 config\uFF1Breturn true \u8868\u793A\u547D\u4E2D\u5F53\u524D\u8BA2\u9605\uFF0C\u5176\u4F59\u8FD4\u56DE\u503C\u5FFD\u7565\uFF09:",
|
|
4345
4331
|
" export default function (config, ctx) { ... }",
|
|
4346
4332
|
"CommonJS \u5199\u6CD5 module.exports = function (config, ctx) { ... } \u540C\u6837\u8BA4\u3002"
|
|
4347
4333
|
]
|
|
@@ -4364,7 +4350,7 @@ function readOverwriteFiles() {
|
|
|
4364
4350
|
const filePath = path3.join(USER_DATA_DIR, file);
|
|
4365
4351
|
try {
|
|
4366
4352
|
if (isScriptOverwriteFilename(file)) {
|
|
4367
|
-
ok.push({ name: file,
|
|
4353
|
+
ok.push({ name: file, transform: loadOverwriteScript(filePath, file) });
|
|
4368
4354
|
continue;
|
|
4369
4355
|
}
|
|
4370
4356
|
const content = fs3.readFileSync(filePath, "utf8");
|
|
@@ -4374,7 +4360,7 @@ function readOverwriteFiles() {
|
|
|
4374
4360
|
const { match, enabled, ...config } = parsed;
|
|
4375
4361
|
assertNoMetadataKeyLookalikes(config, file);
|
|
4376
4362
|
assertFileLevelOperatorRules(config, file);
|
|
4377
|
-
ok.push({ name: file,
|
|
4363
|
+
ok.push({ name: file, config, match: normalizeMatch(match, file), enabled: normalizeEnabled(enabled, file) });
|
|
4378
4364
|
} else if (parsed !== null) {
|
|
4379
4365
|
const shape = Array.isArray(parsed) ? "\u6570\u7EC4" : typeof parsed;
|
|
4380
4366
|
throw new CliError(`\u8986\u5199\u6587\u4EF6 "${file}" \u9876\u5C42\u5FC5\u987B\u662F\u6620\u5C04\uFF08\u952E\u503C\u5BF9\uFF09\uFF0C\u5F53\u524D\u662F ${shape}`, {
|
|
@@ -4383,7 +4369,7 @@ function readOverwriteFiles() {
|
|
|
4383
4369
|
});
|
|
4384
4370
|
}
|
|
4385
4371
|
} catch (e) {
|
|
4386
|
-
broken.push(toBrokenFile(file,
|
|
4372
|
+
broken.push(toBrokenFile(file, e));
|
|
4387
4373
|
}
|
|
4388
4374
|
}
|
|
4389
4375
|
return { ok, broken };
|
|
@@ -4407,16 +4393,15 @@ function loadOverwriteFile() {
|
|
|
4407
4393
|
}
|
|
4408
4394
|
return ok;
|
|
4409
4395
|
}
|
|
4410
|
-
var SCRIPT_LOCKED_PROBES = [...LOCKED_CONFIG_KEYS, "tls"];
|
|
4411
4396
|
function snapshotLockedKeys(config) {
|
|
4412
4397
|
const snap = {};
|
|
4413
|
-
for (const k of
|
|
4398
|
+
for (const k of EFFECTIVELY_LOCKED_KEYS) {
|
|
4414
4399
|
if (k in config) snap[k] = config[k];
|
|
4415
4400
|
}
|
|
4416
4401
|
return snap;
|
|
4417
4402
|
}
|
|
4418
4403
|
function diffLockedKeys(before, after) {
|
|
4419
|
-
return
|
|
4404
|
+
return EFFECTIVELY_LOCKED_KEYS.filter((k) => {
|
|
4420
4405
|
const had = k in before;
|
|
4421
4406
|
const has = k in after;
|
|
4422
4407
|
return had !== has ? has : had && before[k] !== after[k];
|
|
@@ -4426,12 +4411,8 @@ function applyOverwrite(baseConfig, files, opts) {
|
|
|
4426
4411
|
let result = { ...baseConfig };
|
|
4427
4412
|
const scriptWarnings = [];
|
|
4428
4413
|
const scriptLockedHits = [];
|
|
4429
|
-
|
|
4430
|
-
|
|
4431
|
-
if (opts.scope?.subUrl) host = new URL(opts.scope.subUrl.trim()).hostname;
|
|
4432
|
-
} catch {
|
|
4433
|
-
host = "";
|
|
4434
|
-
}
|
|
4414
|
+
const scriptMatches = [];
|
|
4415
|
+
const host = hostFromSubUrl(opts.scope?.subUrl) ?? "";
|
|
4435
4416
|
const subscription = { name: opts.scope?.subName ?? "", url: opts.scope?.subUrl ?? "", host };
|
|
4436
4417
|
for (const file of files) {
|
|
4437
4418
|
if (file.transform) {
|
|
@@ -4454,13 +4435,14 @@ function applyOverwrite(baseConfig, files, opts) {
|
|
|
4454
4435
|
});
|
|
4455
4436
|
}
|
|
4456
4437
|
scriptWarnings.push(...notes.map((message) => `${message}\uFF08\u811A\u672C ${file.name}\uFF09`));
|
|
4438
|
+
scriptMatches.push({ file: file.name, matched: returned === true });
|
|
4457
4439
|
const keys = diffLockedKeys(before, result);
|
|
4458
4440
|
if (keys.length > 0) scriptLockedHits.push({ file: file.name, keys });
|
|
4459
4441
|
continue;
|
|
4460
4442
|
}
|
|
4461
4443
|
result = mergeConfigLevel(result, file.config ?? {}, true);
|
|
4462
4444
|
}
|
|
4463
|
-
return { config: result, scriptWarnings, scriptLockedHits };
|
|
4445
|
+
return { config: result, scriptWarnings, scriptLockedHits, scriptMatches };
|
|
4464
4446
|
}
|
|
4465
4447
|
function listOverwriteFile(scope) {
|
|
4466
4448
|
const { ok, broken } = readOverwriteFiles();
|
|
@@ -4468,9 +4450,9 @@ function listOverwriteFile(scope) {
|
|
|
4468
4450
|
return {
|
|
4469
4451
|
enabled,
|
|
4470
4452
|
dir: USER_DATA_DIR,
|
|
4453
|
+
entries: ok,
|
|
4471
4454
|
files: ok.map((f) => ({
|
|
4472
4455
|
name: f.name,
|
|
4473
|
-
path: f.path,
|
|
4474
4456
|
kind: f.transform ? "script" : "yaml",
|
|
4475
4457
|
keys: f.transform ? [] : Object.keys(f.config || {}),
|
|
4476
4458
|
scope: summarizeMatch(f.match),
|
|
@@ -4493,6 +4475,50 @@ function sanitizeTerminal(s) {
|
|
|
4493
4475
|
const controlChars = /[\x00-\x08\x0b\x0c\x0d\x0e-\x1f]/g;
|
|
4494
4476
|
return s.replace(ansiEscape, "").replace(controlChars, "");
|
|
4495
4477
|
}
|
|
4478
|
+
function lastCurlErrorLine(stderr) {
|
|
4479
|
+
const text = typeof stderr === "string" || Buffer.isBuffer(stderr) ? stderr.toString().trim() : "";
|
|
4480
|
+
const lastLine = text ? text.split("\n").pop() : void 0;
|
|
4481
|
+
return lastLine ? lastLine.replace(/^curl: \(\d+\)\s*/, "") : void 0;
|
|
4482
|
+
}
|
|
4483
|
+
var TOKEN_KEY_NAMES = [
|
|
4484
|
+
"token",
|
|
4485
|
+
"key",
|
|
4486
|
+
"secret",
|
|
4487
|
+
"pass",
|
|
4488
|
+
"password",
|
|
4489
|
+
"auth",
|
|
4490
|
+
"access_token",
|
|
4491
|
+
"api_key",
|
|
4492
|
+
"uuid",
|
|
4493
|
+
"sid",
|
|
4494
|
+
"id",
|
|
4495
|
+
"sub",
|
|
4496
|
+
"user",
|
|
4497
|
+
"email",
|
|
4498
|
+
"passwd",
|
|
4499
|
+
"apikey",
|
|
4500
|
+
"access"
|
|
4501
|
+
];
|
|
4502
|
+
var TOKEN_KEYS = new Set(TOKEN_KEY_NAMES);
|
|
4503
|
+
function maskUrl(url) {
|
|
4504
|
+
try {
|
|
4505
|
+
const parsed = new URL(url);
|
|
4506
|
+
for (const [key, value] of parsed.searchParams) {
|
|
4507
|
+
if (TOKEN_KEYS.has(key.toLowerCase()) || value.length >= 16) {
|
|
4508
|
+
parsed.searchParams.set(key, "***");
|
|
4509
|
+
}
|
|
4510
|
+
}
|
|
4511
|
+
if (parsed.username) parsed.username = "***";
|
|
4512
|
+
if (parsed.password) parsed.password = "***";
|
|
4513
|
+
parsed.pathname = parsed.pathname.split("/").map((seg) => seg.length >= 16 ? `${seg.slice(0, 4)}***${seg.slice(-4)}` : seg).join("/");
|
|
4514
|
+
return parsed.toString();
|
|
4515
|
+
} catch {
|
|
4516
|
+
if (url.length > 15) {
|
|
4517
|
+
return `${url.slice(0, 15)}...`;
|
|
4518
|
+
}
|
|
4519
|
+
return url;
|
|
4520
|
+
}
|
|
4521
|
+
}
|
|
4496
4522
|
|
|
4497
4523
|
// src/config.ts
|
|
4498
4524
|
var SAFE_YAML_LOAD_OPTIONS = { maxAliases: YAML_MAX_ALIASES };
|
|
@@ -4586,14 +4612,18 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4586
4612
|
const {
|
|
4587
4613
|
config: withOverwrites,
|
|
4588
4614
|
scriptWarnings,
|
|
4589
|
-
scriptLockedHits
|
|
4615
|
+
scriptLockedHits,
|
|
4616
|
+
scriptMatches
|
|
4590
4617
|
} = applyOverwrite(subscriptionConfig, overwriteFiles, {
|
|
4591
|
-
mode
|
|
4618
|
+
mode,
|
|
4592
4619
|
scope
|
|
4593
4620
|
});
|
|
4594
4621
|
const overwriteSummaries = overwriteFiles.map(describeOverwriteScope);
|
|
4595
4622
|
const systemConfig = {};
|
|
4596
4623
|
const lockedWarnings = [...scriptWarnings];
|
|
4624
|
+
for (const m of scriptMatches.filter((s) => !s.matched)) {
|
|
4625
|
+
lockedWarnings.push(`\u8986\u5199\u811A\u672C ${m.file} \u672A\u8FD4\u56DE true\uFF0C\u4E0D\u89C6\u4E3A\u547D\u4E2D\u5F53\u524D\u8BA2\u9605${scope?.subName ? ` ${scope.subName}` : ""}`);
|
|
4626
|
+
}
|
|
4597
4627
|
for (const hit of scriptLockedHits) {
|
|
4598
4628
|
lockedWarnings.push(renderLockedWarning(`\u8986\u5199\u811A\u672C ${hit.file} \u4E2D\u7684`, hit.keys));
|
|
4599
4629
|
}
|
|
@@ -4603,23 +4633,14 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4603
4633
|
}
|
|
4604
4634
|
}
|
|
4605
4635
|
for (const file of overwriteFiles) {
|
|
4606
|
-
const hit =
|
|
4607
|
-
|
|
4608
|
-
|
|
4609
|
-
const parsedKey = parseOverrideKey(rawKey).key;
|
|
4610
|
-
if (parsedKey !== rawKey && (LOCKED_CONFIG_KEYS.includes(parsedKey) || parsedKey === "tls")) {
|
|
4611
|
-
hit.add(parsedKey);
|
|
4612
|
-
}
|
|
4613
|
-
if (rawKey === "tls") hit.add("tls");
|
|
4614
|
-
}
|
|
4615
|
-
if (hit.size > 0) {
|
|
4616
|
-
lockedWarnings.push(renderLockedWarning(`\u8986\u5199\u6587\u4EF6 ${file.name} \u4E2D\u7684`, [...hit]));
|
|
4636
|
+
const hit = lockedKeysReferencedBy(Object.keys(file.config ?? {}));
|
|
4637
|
+
if (hit.length > 0) {
|
|
4638
|
+
lockedWarnings.push(renderLockedWarning(`\u8986\u5199\u6587\u4EF6 ${file.name} \u4E2D\u7684`, hit));
|
|
4617
4639
|
}
|
|
4618
4640
|
}
|
|
4619
|
-
for (const key of
|
|
4641
|
+
for (const key of EFFECTIVELY_LOCKED_KEYS) {
|
|
4620
4642
|
delete withOverwrites[key];
|
|
4621
4643
|
}
|
|
4622
|
-
delete withOverwrites.tls;
|
|
4623
4644
|
const ports = getPorts(settings);
|
|
4624
4645
|
systemConfig["external-controller"] = `127.0.0.1:${ports.controller}`;
|
|
4625
4646
|
systemConfig["mixed-port"] = ports.mixed;
|
|
@@ -4669,11 +4690,39 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4669
4690
|
};
|
|
4670
4691
|
}
|
|
4671
4692
|
assertConfigShape(merged);
|
|
4672
|
-
return { config: merged, warnings: lockedWarnings, overwriteSummaries };
|
|
4693
|
+
return { config: merged, warnings: lockedWarnings, overwriteSummaries, scriptMatches };
|
|
4673
4694
|
}
|
|
4674
4695
|
function renderLockedWarning(source, keys) {
|
|
4675
4696
|
return `${source}\u7CFB\u7EDF\u9501\u5B9A\u9879\u5DF2\u5FFD\u7565: ${keys.join("\u3001")}\uFF08\u5165\u7AD9\u7AEF\u53E3\u3001\u63A7\u5236\u9762\u3001\u63A7\u5236\u5668\u8BC1\u4E66\u4E0E\u5C40\u57DF\u7F51/\u5165\u7AD9\u9274\u6743\u7531 mihomo-cli \u7BA1\u7406\uFF1B\u7AEF\u53E3\u4E0E controller secret \u5728 settings.json \u914D\u7F6E\uFF0C\u5165\u7AD9\u56FA\u5B9A\u53EA\u76D1\u542C\u56DE\u73AF\uFF0C\u9700\u8981\u5C40\u57DF\u7F51\u5165\u7AD9\u8BF7\u5728\u672C\u673A\u53E6\u8D77\u4E00\u4E2A mihomo-cli \u5B9E\u4F8B\uFF09`;
|
|
4676
4697
|
}
|
|
4698
|
+
function judgeScriptMatches(subRawContent, mode, scope, entries) {
|
|
4699
|
+
try {
|
|
4700
|
+
const subscriptionConfig = parseConfigContent(subRawContent, "\u8BA2\u9605\u5185\u5BB9");
|
|
4701
|
+
const settings = readSettings();
|
|
4702
|
+
const active = settings.overwrite_enabled !== false ? selectActiveOverwriteFiles(entries, scope) : [];
|
|
4703
|
+
const { scriptMatches } = applyOverwrite(subscriptionConfig, active, {
|
|
4704
|
+
mode,
|
|
4705
|
+
scope
|
|
4706
|
+
});
|
|
4707
|
+
return { matches: scriptMatches };
|
|
4708
|
+
} catch (e) {
|
|
4709
|
+
return { matches: [], error: e.message?.split("\n")[0] ?? String(e) };
|
|
4710
|
+
}
|
|
4711
|
+
}
|
|
4712
|
+
function deriveRuntimeMode(info) {
|
|
4713
|
+
return info?.tun ? "tun" : "mixed";
|
|
4714
|
+
}
|
|
4715
|
+
function runtimeModeLabel(mode) {
|
|
4716
|
+
return mode === "tun" ? "TUN" : "Mixed";
|
|
4717
|
+
}
|
|
4718
|
+
function countConfigNodes(config) {
|
|
4719
|
+
const proxies = config.proxies;
|
|
4720
|
+
const proxyGroups = config["proxy-groups"];
|
|
4721
|
+
return {
|
|
4722
|
+
proxies: proxies ? proxies.length : 0,
|
|
4723
|
+
proxyGroups: proxyGroups ? proxyGroups.length : 0
|
|
4724
|
+
};
|
|
4725
|
+
}
|
|
4677
4726
|
function writeMihomoConfig(configObj) {
|
|
4678
4727
|
ensureDirs();
|
|
4679
4728
|
const content = dumpYaml(configObj);
|
|
@@ -4700,7 +4749,7 @@ function buildKernelRejectHint(detail, overwriteSummaries, opts = {}) {
|
|
|
4700
4749
|
return hint;
|
|
4701
4750
|
}
|
|
4702
4751
|
async function validateConfigWithKernel(config, overwriteSummaries) {
|
|
4703
|
-
|
|
4752
|
+
assertKernelInstalled();
|
|
4704
4753
|
ensureDirs();
|
|
4705
4754
|
const stageDir = fs4.mkdtempSync(path4.join(DIRS.runtime, "check-"));
|
|
4706
4755
|
const stageFile = path4.join(stageDir, "config.yaml");
|
|
@@ -4740,12 +4789,9 @@ function getConfigInfo() {
|
|
|
4740
4789
|
const content = fs4.readFileSync(PATHS.configFile, "utf8");
|
|
4741
4790
|
const cfg = loadYamlSafe(content);
|
|
4742
4791
|
if (!cfg) return null;
|
|
4743
|
-
const proxies = cfg.proxies;
|
|
4744
|
-
const proxyGroups = cfg["proxy-groups"];
|
|
4745
4792
|
const tun = cfg.tun;
|
|
4746
4793
|
return {
|
|
4747
|
-
|
|
4748
|
-
proxyGroups: proxyGroups ? proxyGroups.length : 0,
|
|
4794
|
+
...countConfigNodes(cfg),
|
|
4749
4795
|
mixedPort: cfg["mixed-port"] || null,
|
|
4750
4796
|
tun: tun ? !!tun.enable : false
|
|
4751
4797
|
};
|
|
@@ -4756,14 +4802,24 @@ function getConfigInfo() {
|
|
|
4756
4802
|
function hasKernel() {
|
|
4757
4803
|
return fs4.existsSync(PATHS.mihomoBinary);
|
|
4758
4804
|
}
|
|
4759
|
-
function
|
|
4805
|
+
function assertKernelInstalled() {
|
|
4806
|
+
if (!hasKernel()) throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
|
|
4807
|
+
}
|
|
4808
|
+
function assertRuntimeConfigPresent() {
|
|
4809
|
+
if (!fs4.existsSync(PATHS.configFile)) throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
|
|
4810
|
+
}
|
|
4811
|
+
function probeKernelVersion(binary = PATHS.mihomoBinary) {
|
|
4812
|
+
const r = spawnSync(binary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
4813
|
+
const output = `${r.stdout || ""}${r.stderr || ""}`.trim();
|
|
4814
|
+
const match = output.match(/v?\d+\.\d+\.\d+/);
|
|
4815
|
+
return { spawnError: r.error ?? null, status: r.status ?? null, output, version: match ? match[0] : null };
|
|
4816
|
+
}
|
|
4817
|
+
function getKernelVersion(probe) {
|
|
4760
4818
|
if (!hasKernel()) return null;
|
|
4761
4819
|
try {
|
|
4762
|
-
const
|
|
4763
|
-
|
|
4764
|
-
|
|
4765
|
-
const match = output.match(/v?[\d]+\.[\d]+\.[\d]+/);
|
|
4766
|
-
return match ? match[0] : output.split("\n")[0];
|
|
4820
|
+
const p = probe ?? probeKernelVersion();
|
|
4821
|
+
if (!p.output) return "unknown";
|
|
4822
|
+
return p.version ?? p.output.split("\n")[0];
|
|
4767
4823
|
} catch {
|
|
4768
4824
|
return "unknown";
|
|
4769
4825
|
}
|
|
@@ -4865,8 +4921,7 @@ import fs13 from "fs";
|
|
|
4865
4921
|
import path7 from "path";
|
|
4866
4922
|
|
|
4867
4923
|
// src/hot-reload.ts
|
|
4868
|
-
import
|
|
4869
|
-
import fs7 from "fs";
|
|
4924
|
+
import fs8 from "fs";
|
|
4870
4925
|
|
|
4871
4926
|
// src/launchctl.ts
|
|
4872
4927
|
import { spawnSync as spawnSync2 } from "child_process";
|
|
@@ -4904,7 +4959,7 @@ function parseServicePrint(output) {
|
|
|
4904
4959
|
};
|
|
4905
4960
|
}
|
|
4906
4961
|
function parseDisabledList(output, label) {
|
|
4907
|
-
const escaped = label
|
|
4962
|
+
const escaped = escapeRegExp(label);
|
|
4908
4963
|
const match = output.match(new RegExp(`^\\s*"${escaped}" => (\\S+)$`, "m"));
|
|
4909
4964
|
if (!match) return false;
|
|
4910
4965
|
const value = match[1].toLowerCase();
|
|
@@ -5001,11 +5056,147 @@ async function waitUntilUnloaded(target = serviceTarget()) {
|
|
|
5001
5056
|
});
|
|
5002
5057
|
}
|
|
5003
5058
|
|
|
5004
|
-
// src/
|
|
5059
|
+
// src/proxy-probe.ts
|
|
5060
|
+
import { execFile as execFile2, spawnSync as spawnSync4 } from "child_process";
|
|
5061
|
+
import { promisify as promisify2 } from "util";
|
|
5062
|
+
|
|
5063
|
+
// src/process-probe.ts
|
|
5064
|
+
import { spawnSync as spawnSync3 } from "child_process";
|
|
5005
5065
|
import fs6 from "fs";
|
|
5066
|
+
var PS_TIMEOUT_MS = 5e3;
|
|
5067
|
+
var NOT_RUNNING = { alive: false, uid: null, rss: null, command: "" };
|
|
5068
|
+
function probeProcess(pid) {
|
|
5069
|
+
if (!pid) return NOT_RUNNING;
|
|
5070
|
+
try {
|
|
5071
|
+
const result = spawnSync3("ps", ["-ww", "-p", String(pid), "-o", "pid=,uid=,rss=,command="], {
|
|
5072
|
+
encoding: "utf8",
|
|
5073
|
+
timeout: PS_TIMEOUT_MS
|
|
5074
|
+
});
|
|
5075
|
+
const match = (result.stdout || "").trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/);
|
|
5076
|
+
if (!match) return NOT_RUNNING;
|
|
5077
|
+
return { alive: true, uid: match[2], rss: Number.parseInt(match[3], 10), command: match[4] };
|
|
5078
|
+
} catch {
|
|
5079
|
+
return NOT_RUNNING;
|
|
5080
|
+
}
|
|
5081
|
+
}
|
|
5082
|
+
function isProbedMihomo(p) {
|
|
5083
|
+
return p.alive && (p.command.includes(PATHS.mihomoBinary) || p.command.includes(PATHS.serviceBinary));
|
|
5084
|
+
}
|
|
5085
|
+
var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
|
|
5086
|
+
var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
|
|
5087
|
+
function getPid() {
|
|
5088
|
+
if (!fs6.existsSync(PATHS.pidFile)) return null;
|
|
5089
|
+
try {
|
|
5090
|
+
const pid = parseInt(fs6.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
|
|
5091
|
+
return pid > 0 ? pid : null;
|
|
5092
|
+
} catch {
|
|
5093
|
+
return null;
|
|
5094
|
+
}
|
|
5095
|
+
}
|
|
5096
|
+
function isRunning() {
|
|
5097
|
+
const pid = getPid();
|
|
5098
|
+
if (!pid) return false;
|
|
5099
|
+
return isMihomoProcess(pid);
|
|
5100
|
+
}
|
|
5101
|
+
function isMihomoProcess(pid) {
|
|
5102
|
+
return isProbedMihomo(probeProcess(pid));
|
|
5103
|
+
}
|
|
5104
|
+
function getMihomoPids() {
|
|
5105
|
+
const result = spawnSync3("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
|
|
5106
|
+
if (result.error || result.status === null) {
|
|
5107
|
+
throw new CliError("\u65E0\u6CD5\u63A2\u6D4B\u5185\u6838\u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
|
|
5108
|
+
hint: ["\u8FD9\u4E0D\u4EE3\u8868\u5185\u6838\u672A\u8FD0\u884C\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "\u8BF7\u624B\u52A8\u786E\u8BA4: pgrep -fl mihomo-cli"]
|
|
5109
|
+
});
|
|
5110
|
+
}
|
|
5111
|
+
if (result.status !== 0 && result.status !== 1) {
|
|
5112
|
+
throw new CliError(`\u8FDB\u7A0B\u63A2\u6D4B\u5931\u8D25\uFF08pgrep \u9000\u51FA\u7801 ${result.status}\uFF09`, {
|
|
5113
|
+
hint: [(result.stderr || "").trim(), "", "\u8FD9\u662F CLI \u7684\u7F3A\u9677\uFF0C\u8BF7\u53CD\u9988\u3002\u624B\u52A8\u786E\u8BA4\u5185\u6838\u72B6\u6001: pgrep -fl mihomo-cli"].filter(Boolean)
|
|
5114
|
+
});
|
|
5115
|
+
}
|
|
5116
|
+
return parsePidList(result.stdout);
|
|
5117
|
+
}
|
|
5118
|
+
function parsePidList(stdout) {
|
|
5119
|
+
const output = stdout.trim();
|
|
5120
|
+
if (!output) return [];
|
|
5121
|
+
return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
|
|
5122
|
+
}
|
|
5123
|
+
function isPidFileOwnedByRoot() {
|
|
5124
|
+
if (!fs6.existsSync(PATHS.pidFile)) return false;
|
|
5125
|
+
try {
|
|
5126
|
+
const stat = fs6.statSync(PATHS.pidFile);
|
|
5127
|
+
return stat.uid === 0;
|
|
5128
|
+
} catch {
|
|
5129
|
+
return false;
|
|
5130
|
+
}
|
|
5131
|
+
}
|
|
5132
|
+
function checkStaleState() {
|
|
5133
|
+
const allPids = getMihomoPids();
|
|
5134
|
+
return {
|
|
5135
|
+
needsCleanup: allPids.length > 0 || isPidFileOwnedByRoot(),
|
|
5136
|
+
allPids
|
|
5137
|
+
};
|
|
5138
|
+
}
|
|
5139
|
+
function getStatus() {
|
|
5140
|
+
const pid = getPid();
|
|
5141
|
+
if (!pid) return { running: false, pid: null, processInfo: null };
|
|
5142
|
+
const p = probeProcess(pid);
|
|
5143
|
+
if (!isProbedMihomo(p)) return { running: false, pid: null, processInfo: null };
|
|
5144
|
+
return {
|
|
5145
|
+
running: true,
|
|
5146
|
+
pid,
|
|
5147
|
+
processInfo: {
|
|
5148
|
+
pid,
|
|
5149
|
+
memory: p.rss ? `${(p.rss / 1024).toFixed(1)} MB` : "\u672A\u77E5",
|
|
5150
|
+
isRoot: p.uid === "0"
|
|
5151
|
+
}
|
|
5152
|
+
};
|
|
5153
|
+
}
|
|
5154
|
+
|
|
5155
|
+
// src/proxy-probe.ts
|
|
5156
|
+
var execFileAsync = promisify2(execFile2);
|
|
5157
|
+
function lsofListenPids(port) {
|
|
5158
|
+
try {
|
|
5159
|
+
const r = spawnSync4("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
|
|
5160
|
+
if (r.status !== 0) return null;
|
|
5161
|
+
return parsePidList(r.stdout);
|
|
5162
|
+
} catch {
|
|
5163
|
+
return null;
|
|
5164
|
+
}
|
|
5165
|
+
}
|
|
5166
|
+
var PROBE_URL = "https://www.gstatic.com/generate_204";
|
|
5167
|
+
function isProbeSuccessStatus(code) {
|
|
5168
|
+
return code !== null && code >= 200 && code < 300;
|
|
5169
|
+
}
|
|
5170
|
+
var PROBE_TIMEOUT_MS = 2e3;
|
|
5171
|
+
async function probeProxyConnectivity(port) {
|
|
5172
|
+
const start = Date.now();
|
|
5173
|
+
try {
|
|
5174
|
+
const { stdout } = await execFileAsync(
|
|
5175
|
+
"curl",
|
|
5176
|
+
["-x", `http://127.0.0.1:${port}`, "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
|
|
5177
|
+
{ timeout: PROBE_TIMEOUT_MS + 2e3 }
|
|
5178
|
+
);
|
|
5179
|
+
const code = Number.parseInt(stdout.trim(), 10);
|
|
5180
|
+
const statusCode = Number.isFinite(code) ? code : null;
|
|
5181
|
+
const ok = isProbeSuccessStatus(statusCode);
|
|
5182
|
+
return {
|
|
5183
|
+
ok,
|
|
5184
|
+
statusCode,
|
|
5185
|
+
error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
|
|
5186
|
+
durationMs: Date.now() - start
|
|
5187
|
+
};
|
|
5188
|
+
} catch (e) {
|
|
5189
|
+
const err = e;
|
|
5190
|
+
const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
|
|
5191
|
+
return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
|
|
5192
|
+
}
|
|
5193
|
+
}
|
|
5194
|
+
|
|
5195
|
+
// src/stop-epoch.ts
|
|
5196
|
+
import fs7 from "fs";
|
|
5006
5197
|
function readStopEpoch() {
|
|
5007
5198
|
try {
|
|
5008
|
-
const n = Number.parseInt(
|
|
5199
|
+
const n = Number.parseInt(fs7.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
|
|
5009
5200
|
return Number.isSafeInteger(n) && n >= 0 ? n : 0;
|
|
5010
5201
|
} catch {
|
|
5011
5202
|
return 0;
|
|
@@ -5032,23 +5223,27 @@ function recordServiceStopped() {
|
|
|
5032
5223
|
function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
|
|
5033
5224
|
return stopEpochNow !== stopEpochBefore;
|
|
5034
5225
|
}
|
|
5226
|
+
function startAbortedByConcurrentStop() {
|
|
5227
|
+
return shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch());
|
|
5228
|
+
}
|
|
5035
5229
|
|
|
5036
5230
|
// src/hot-reload.ts
|
|
5037
5231
|
var HOT_RELOAD_TIMEOUT_MS = 5e3;
|
|
5038
5232
|
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
5039
5233
|
function logOversized() {
|
|
5040
5234
|
try {
|
|
5041
|
-
return
|
|
5235
|
+
return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
5042
5236
|
} catch {
|
|
5043
5237
|
return false;
|
|
5044
5238
|
}
|
|
5045
5239
|
}
|
|
5046
|
-
async function tryHotReload() {
|
|
5240
|
+
async function tryHotReload(prefetched) {
|
|
5047
5241
|
const controller = new AbortController();
|
|
5048
5242
|
try {
|
|
5049
|
-
const status = getServiceStatus({ withDisabled: false });
|
|
5243
|
+
const status = prefetched ?? getServiceStatus({ withDisabled: false });
|
|
5050
5244
|
if (!status.running || status.pid === null) return false;
|
|
5051
|
-
const
|
|
5245
|
+
const { controller: controllerPort } = getPorts();
|
|
5246
|
+
const baseUrl = `http://127.0.0.1:${controllerPort}`;
|
|
5052
5247
|
const secret = readSettings().controller_secret;
|
|
5053
5248
|
const headers = { "Content-Type": "application/json" };
|
|
5054
5249
|
if (typeof secret === "string" && secret) headers.Authorization = `Bearer ${secret}`;
|
|
@@ -5058,11 +5253,8 @@ async function tryHotReload() {
|
|
|
5058
5253
|
if (!probe.ok) return false;
|
|
5059
5254
|
const info = await probe.json();
|
|
5060
5255
|
if (typeof info?.version !== "string") return false;
|
|
5061
|
-
const
|
|
5062
|
-
|
|
5063
|
-
if (lsofResult.status !== 0) return false;
|
|
5064
|
-
const listenerPid = Number.parseInt(lsofResult.stdout.trim(), 10);
|
|
5065
|
-
if (!Number.isFinite(listenerPid) || listenerPid !== status.pid) return false;
|
|
5256
|
+
const listenerPids = lsofListenPids(controllerPort);
|
|
5257
|
+
if (listenerPids === null || listenerPids[0] !== status.pid) return false;
|
|
5066
5258
|
const res = await fetch(`${baseUrl}/configs?force=true`, {
|
|
5067
5259
|
method: "PUT",
|
|
5068
5260
|
headers,
|
|
@@ -5088,115 +5280,6 @@ import fs11 from "fs";
|
|
|
5088
5280
|
import { spawnSync as spawnSync6 } from "child_process";
|
|
5089
5281
|
import fs10 from "fs";
|
|
5090
5282
|
|
|
5091
|
-
// src/process-probe.ts
|
|
5092
|
-
import { spawnSync as spawnSync4 } from "child_process";
|
|
5093
|
-
import fs8 from "fs";
|
|
5094
|
-
var PS_TIMEOUT_MS = 5e3;
|
|
5095
|
-
function isProcessRunning(pid) {
|
|
5096
|
-
if (!pid) return false;
|
|
5097
|
-
try {
|
|
5098
|
-
const result = spawnSync4("ps", ["-p", String(pid), "-o", "pid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
|
|
5099
|
-
return (result.stdout || "").trim().length > 0;
|
|
5100
|
-
} catch {
|
|
5101
|
-
return false;
|
|
5102
|
-
}
|
|
5103
|
-
}
|
|
5104
|
-
function isProcessCommandMatching(pid, needle) {
|
|
5105
|
-
if (!pid) return false;
|
|
5106
|
-
try {
|
|
5107
|
-
const result = spawnSync4("ps", ["-ww", "-p", String(pid), "-o", "command="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
|
|
5108
|
-
return (result.stdout || "").includes(needle);
|
|
5109
|
-
} catch {
|
|
5110
|
-
return false;
|
|
5111
|
-
}
|
|
5112
|
-
}
|
|
5113
|
-
function isProcessRoot(pid) {
|
|
5114
|
-
if (!pid) return false;
|
|
5115
|
-
try {
|
|
5116
|
-
const result = spawnSync4("ps", ["-p", String(pid), "-o", "uid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
|
|
5117
|
-
return (result.stdout || "").trim() === "0";
|
|
5118
|
-
} catch {
|
|
5119
|
-
return false;
|
|
5120
|
-
}
|
|
5121
|
-
}
|
|
5122
|
-
var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
|
|
5123
|
-
var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
|
|
5124
|
-
function getPid() {
|
|
5125
|
-
if (!fs8.existsSync(PATHS.pidFile)) return null;
|
|
5126
|
-
try {
|
|
5127
|
-
const pid = parseInt(fs8.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
|
|
5128
|
-
return pid > 0 ? pid : null;
|
|
5129
|
-
} catch {
|
|
5130
|
-
return null;
|
|
5131
|
-
}
|
|
5132
|
-
}
|
|
5133
|
-
function isRunning() {
|
|
5134
|
-
const pid = getPid();
|
|
5135
|
-
if (!pid) return false;
|
|
5136
|
-
return isMihomoProcess(pid);
|
|
5137
|
-
}
|
|
5138
|
-
function isMihomoProcess(pid) {
|
|
5139
|
-
if (!pid) return false;
|
|
5140
|
-
return isProcessRunning(pid) && (isProcessCommandMatching(pid, PATHS.mihomoBinary) || isProcessCommandMatching(pid, PATHS.serviceBinary));
|
|
5141
|
-
}
|
|
5142
|
-
function getMihomoPids() {
|
|
5143
|
-
const result = spawnSync4("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
|
|
5144
|
-
if (result.error || result.status === null) {
|
|
5145
|
-
throw new CliError("\u65E0\u6CD5\u63A2\u6D4B\u5185\u6838\u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
|
|
5146
|
-
hint: ["\u8FD9\u4E0D\u4EE3\u8868\u5185\u6838\u672A\u8FD0\u884C\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "\u8BF7\u624B\u52A8\u786E\u8BA4: pgrep -fl mihomo-cli"]
|
|
5147
|
-
});
|
|
5148
|
-
}
|
|
5149
|
-
if (result.status !== 0 && result.status !== 1) {
|
|
5150
|
-
throw new CliError(`\u8FDB\u7A0B\u63A2\u6D4B\u5931\u8D25\uFF08pgrep \u9000\u51FA\u7801 ${result.status}\uFF09`, {
|
|
5151
|
-
hint: [(result.stderr || "").trim(), "", "\u8FD9\u662F CLI \u7684\u7F3A\u9677\uFF0C\u8BF7\u53CD\u9988\u3002\u624B\u52A8\u786E\u8BA4\u5185\u6838\u72B6\u6001: pgrep -fl mihomo-cli"].filter(Boolean)
|
|
5152
|
-
});
|
|
5153
|
-
}
|
|
5154
|
-
const output = (result.stdout || "").trim();
|
|
5155
|
-
if (!output) return [];
|
|
5156
|
-
return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
|
|
5157
|
-
}
|
|
5158
|
-
function isPidFileOwnedByRoot() {
|
|
5159
|
-
if (!fs8.existsSync(PATHS.pidFile)) return false;
|
|
5160
|
-
try {
|
|
5161
|
-
const stat = fs8.statSync(PATHS.pidFile);
|
|
5162
|
-
return stat.uid === 0;
|
|
5163
|
-
} catch {
|
|
5164
|
-
return false;
|
|
5165
|
-
}
|
|
5166
|
-
}
|
|
5167
|
-
function checkStaleState() {
|
|
5168
|
-
const allPids = getMihomoPids();
|
|
5169
|
-
return {
|
|
5170
|
-
needsCleanup: allPids.length > 0 || isPidFileOwnedByRoot(),
|
|
5171
|
-
allPids
|
|
5172
|
-
};
|
|
5173
|
-
}
|
|
5174
|
-
function getProcessInfo(pid) {
|
|
5175
|
-
try {
|
|
5176
|
-
const result = spawnSync4("ps", ["-p", String(pid), "-o", "rss=,uid="], { encoding: "utf8", timeout: 5e3 });
|
|
5177
|
-
const psOutput = (result.stdout || "").trim();
|
|
5178
|
-
if (!psOutput) return null;
|
|
5179
|
-
const [rssRaw, uidRaw] = psOutput.split(/\s+/);
|
|
5180
|
-
const rss = parseInt(rssRaw, 10);
|
|
5181
|
-
return {
|
|
5182
|
-
pid,
|
|
5183
|
-
memory: rss ? `${(rss / 1024).toFixed(1)} MB` : "\u672A\u77E5",
|
|
5184
|
-
isRoot: uidRaw === "0"
|
|
5185
|
-
};
|
|
5186
|
-
} catch {
|
|
5187
|
-
return { pid, memory: "\u672A\u77E5", isRoot: false };
|
|
5188
|
-
}
|
|
5189
|
-
}
|
|
5190
|
-
function getStatus() {
|
|
5191
|
-
const running = isRunning();
|
|
5192
|
-
const pid = getPid();
|
|
5193
|
-
return {
|
|
5194
|
-
running,
|
|
5195
|
-
pid: running ? pid : null,
|
|
5196
|
-
processInfo: running && pid ? getProcessInfo(pid) : null
|
|
5197
|
-
};
|
|
5198
|
-
}
|
|
5199
|
-
|
|
5200
5283
|
// src/sudo.ts
|
|
5201
5284
|
import { spawnSync as spawnSync5 } from "child_process";
|
|
5202
5285
|
import fs9 from "fs";
|
|
@@ -5256,6 +5339,7 @@ function clearRuntime() {
|
|
|
5256
5339
|
function describePidCleanupFailure(err) {
|
|
5257
5340
|
return `pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08${err.message}\uFF09`;
|
|
5258
5341
|
}
|
|
5342
|
+
var MANUAL_PKILL_HINT = "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo";
|
|
5259
5343
|
function warnPidCleanupFailed(err) {
|
|
5260
5344
|
if (!err) return;
|
|
5261
5345
|
console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(err)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
|
|
@@ -5269,9 +5353,18 @@ function clearPid() {
|
|
|
5269
5353
|
return e;
|
|
5270
5354
|
}
|
|
5271
5355
|
}
|
|
5272
|
-
|
|
5356
|
+
function pidAlive(pid) {
|
|
5357
|
+
try {
|
|
5358
|
+
process.kill(pid, 0);
|
|
5359
|
+
return true;
|
|
5360
|
+
} catch (e) {
|
|
5361
|
+
return e.code !== "ESRCH";
|
|
5362
|
+
}
|
|
5363
|
+
}
|
|
5364
|
+
async function waitUntilNoMihomo(pids) {
|
|
5273
5365
|
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
5274
|
-
|
|
5366
|
+
const stillThere = pids ? pids.some(pidAlive) : getMihomoPids().length > 0;
|
|
5367
|
+
if (!stillThere) return;
|
|
5275
5368
|
await sleep(PROCESS_WAIT_INTERVAL);
|
|
5276
5369
|
}
|
|
5277
5370
|
}
|
|
@@ -5316,7 +5409,8 @@ async function cleanupAll() {
|
|
|
5316
5409
|
let killedCount = 0;
|
|
5317
5410
|
const failedPids = [];
|
|
5318
5411
|
let scriptError = null;
|
|
5319
|
-
const
|
|
5412
|
+
const probes = new Map(pids.map((pid) => [pid, probeProcess(pid)]));
|
|
5413
|
+
const rootPids = pids.filter((pid) => probes.get(pid)?.uid === "0");
|
|
5320
5414
|
if (rootPids.length > 0) {
|
|
5321
5415
|
console.log(`\u68C0\u6D4B\u5230 root \u5C5E\u4E3B\u7684\u5185\u6838\u6B8B\u7559\uFF08PID ${rootPids.join(", ")}\uFF09\uFF0C\u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801`);
|
|
5322
5416
|
try {
|
|
@@ -5337,7 +5431,8 @@ async function cleanupAll() {
|
|
|
5337
5431
|
}
|
|
5338
5432
|
} else {
|
|
5339
5433
|
for (const pid of pids) {
|
|
5340
|
-
|
|
5434
|
+
const probed = probes.get(pid);
|
|
5435
|
+
if (!probed || !isProbedMihomo(probed)) {
|
|
5341
5436
|
killedCount++;
|
|
5342
5437
|
continue;
|
|
5343
5438
|
}
|
|
@@ -5348,7 +5443,7 @@ async function cleanupAll() {
|
|
|
5348
5443
|
}
|
|
5349
5444
|
}
|
|
5350
5445
|
}
|
|
5351
|
-
await waitUntilNoMihomo();
|
|
5446
|
+
await waitUntilNoMihomo(pids);
|
|
5352
5447
|
const remaining = getMihomoPids();
|
|
5353
5448
|
const pidError = remaining.length === 0 ? clearPid() : null;
|
|
5354
5449
|
return { killed: killedCount, failed: failedPids.length, remaining, scriptError, pidError };
|
|
@@ -5358,7 +5453,7 @@ async function stop() {
|
|
|
5358
5453
|
if (allPids.length === 0) {
|
|
5359
5454
|
warnPidCleanupFailed(clearPid());
|
|
5360
5455
|
clearRuntime();
|
|
5361
|
-
return {
|
|
5456
|
+
return {};
|
|
5362
5457
|
}
|
|
5363
5458
|
const result = await cleanupAll();
|
|
5364
5459
|
if (result.remaining.length === 0) {
|
|
@@ -5367,17 +5462,17 @@ async function stop() {
|
|
|
5367
5462
|
console.warn(colors.yellow(`\u8B66\u544A: root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF08${describeSudoFailure(result.scriptError)}\uFF09\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF1B\u518D\u53D1\u73B0\u6B8B\u7559\u53EF\u91CD\u8BD5 mihomo-cli stop`));
|
|
5368
5463
|
}
|
|
5369
5464
|
}
|
|
5370
|
-
const remaining =
|
|
5465
|
+
const remaining = result.remaining;
|
|
5371
5466
|
if (remaining.length > 0) {
|
|
5372
5467
|
console.log("");
|
|
5373
5468
|
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
5374
5469
|
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
5375
|
-
console.log(
|
|
5470
|
+
console.log(MANUAL_PKILL_HINT);
|
|
5376
5471
|
console.log("");
|
|
5377
|
-
return {
|
|
5472
|
+
return { remaining };
|
|
5378
5473
|
}
|
|
5379
5474
|
clearRuntime();
|
|
5380
|
-
return {
|
|
5475
|
+
return {};
|
|
5381
5476
|
}
|
|
5382
5477
|
|
|
5383
5478
|
// src/legacy-cleanup.ts
|
|
@@ -5391,7 +5486,7 @@ function buildRootResidueCleanupError(result, ctx) {
|
|
|
5391
5486
|
const pidList = `PID ${result.remaining.join(", ")}`;
|
|
5392
5487
|
const residueHint = hasKernelResidue ? scriptError ? `root \u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\uFF0C\u53EF\u80FD\u7EE7\u7EED\u5360\u7528\u4EE3\u7406\u7AEF\u53E3` : `\u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08${pidList}\uFF09\u2014\u2014\u7528\u6237\u6001\u672A\u80FD\u7EC8\u6B62\uFF0C\u4E0E\u63D0\u6743\u65E0\u5173` : scriptError ? `root \u6B8B\u7559\u6E05\u7406\u672A\u5B8C\u6210\uFF0C\u8FDB\u7A0B\u76EE\u524D\u5DF2\u4E0D\u5728\uFF08\u6B7B\u4EA1\u7B49\u5F85\u5185\u81EA\u884C\u9000\u51FA\uFF0C\u975E sudo \u6E05\u7406\uFF09${pidError ? `\uFF1B${describePidCleanupFailure(pidError)}` : ""}` : pidError ? `${describePidCleanupFailure(pidError)}: ${PATHS.pidFile}` : "root \u6B8B\u7559\u672A\u6E05\u7406\u5E72\u51C0";
|
|
5393
5488
|
const hint = [ctx.mainOutcome, residueHint, `\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`];
|
|
5394
|
-
hint.push(hasKernelResidue || scriptError ?
|
|
5489
|
+
hint.push(hasKernelResidue || scriptError ? MANUAL_PKILL_HINT : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
|
|
5395
5490
|
if (cancelled) {
|
|
5396
5491
|
return new CliError("\u7BA1\u7406\u5458\u5BC6\u7801\u672A\u8F93\u5165\u6216\u6709\u8BEF\uFF0Croot \u6B8B\u7559\u672A\u88AB\u6E05\u7406", { label: "\u5DF2\u53D6\u6D88", hint });
|
|
5397
5492
|
}
|
|
@@ -5401,15 +5496,18 @@ function classifyResidueCleanup(result) {
|
|
|
5401
5496
|
if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
|
|
5402
5497
|
return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
|
|
5403
5498
|
}
|
|
5404
|
-
|
|
5405
|
-
const result = await cleanupAll();
|
|
5406
|
-
const verdict = classifyResidueCleanup(result);
|
|
5407
|
-
if (verdict === "ok") return;
|
|
5499
|
+
function warnResidueCleanup(result, ctx) {
|
|
5408
5500
|
const err = buildRootResidueCleanupError(result, ctx);
|
|
5409
|
-
if (verdict === "throw") throw err;
|
|
5410
5501
|
console.warn(colors.yellow(`\u8B66\u544A: ${err.message}`));
|
|
5411
5502
|
for (const line of err.hint) console.warn(colors.gray(line));
|
|
5412
5503
|
}
|
|
5504
|
+
async function cleanupKernelsOrThrow(ctx) {
|
|
5505
|
+
const result = await cleanupAll();
|
|
5506
|
+
const verdict = classifyResidueCleanup(result);
|
|
5507
|
+
if (verdict === "throw") throw buildRootResidueCleanupError(result, ctx);
|
|
5508
|
+
if (verdict === "warn") warnResidueCleanup(result, ctx);
|
|
5509
|
+
return result;
|
|
5510
|
+
}
|
|
5413
5511
|
function buildLegacyCleanupScript() {
|
|
5414
5512
|
return [
|
|
5415
5513
|
"#!/bin/bash",
|
|
@@ -5460,6 +5558,14 @@ async function cleanupLegacyInstallOrThrow() {
|
|
|
5460
5558
|
console.warn(colors.yellow(`\u8B66\u544A: ${describePidCleanupFailure(pidError)}\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5`));
|
|
5461
5559
|
}
|
|
5462
5560
|
}
|
|
5561
|
+
async function announceLegacyCleanupOrThrow(reason, extraNotes = []) {
|
|
5562
|
+
console.log(colors.yellow(`\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C${reason}`));
|
|
5563
|
+
for (const note of extraNotes) console.log(colors.gray(note));
|
|
5564
|
+
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"));
|
|
5565
|
+
await cleanupLegacyInstallOrThrow();
|
|
5566
|
+
console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
|
|
5567
|
+
console.log("");
|
|
5568
|
+
}
|
|
5463
5569
|
|
|
5464
5570
|
// src/log-files.ts
|
|
5465
5571
|
import fs12 from "fs";
|
|
@@ -5527,10 +5633,10 @@ function rotateLog() {
|
|
|
5527
5633
|
try {
|
|
5528
5634
|
stat = fs12.statSync(logFile);
|
|
5529
5635
|
} catch (e) {
|
|
5530
|
-
if (e.code === "ENOENT") return
|
|
5636
|
+
if (e.code === "ENOENT") return;
|
|
5531
5637
|
throw e;
|
|
5532
5638
|
}
|
|
5533
|
-
if (stat.size === 0) return
|
|
5639
|
+
if (stat.size === 0) return;
|
|
5534
5640
|
const rotatedPath = allocateArchivePath();
|
|
5535
5641
|
try {
|
|
5536
5642
|
fs12.renameSync(logFile, rotatedPath);
|
|
@@ -5539,19 +5645,16 @@ function rotateLog() {
|
|
|
5539
5645
|
fs12.unlinkSync(rotatedPath);
|
|
5540
5646
|
} catch {
|
|
5541
5647
|
}
|
|
5542
|
-
if (e.code === "ENOENT") return
|
|
5648
|
+
if (e.code === "ENOENT") return;
|
|
5543
5649
|
throw e;
|
|
5544
5650
|
}
|
|
5545
|
-
return rotatedPath;
|
|
5546
5651
|
}
|
|
5547
5652
|
function cleanupOldLogs() {
|
|
5548
5653
|
const logsDir = DIRS.logs;
|
|
5549
|
-
if (!fs12.existsSync(logsDir)) return
|
|
5654
|
+
if (!fs12.existsSync(logsDir)) return;
|
|
5550
5655
|
const files = fs12.readdirSync(logsDir);
|
|
5551
5656
|
const now = Date.now();
|
|
5552
5657
|
const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
|
|
5553
|
-
let deleted = 0;
|
|
5554
|
-
let errors = 0;
|
|
5555
5658
|
for (const file of files) {
|
|
5556
5659
|
if (!isArchiveLogFilename(file)) continue;
|
|
5557
5660
|
try {
|
|
@@ -5559,13 +5662,10 @@ function cleanupOldLogs() {
|
|
|
5559
5662
|
const stat = fs12.statSync(filePath);
|
|
5560
5663
|
if (now - stat.mtimeMs > maxAgeMs) {
|
|
5561
5664
|
fs12.unlinkSync(filePath);
|
|
5562
|
-
deleted++;
|
|
5563
5665
|
}
|
|
5564
5666
|
} catch {
|
|
5565
|
-
errors++;
|
|
5566
5667
|
}
|
|
5567
5668
|
}
|
|
5568
|
-
return { deleted, errors };
|
|
5569
5669
|
}
|
|
5570
5670
|
function listLogs() {
|
|
5571
5671
|
const logsDir = DIRS.logs;
|
|
@@ -5609,6 +5709,13 @@ async function waitServiceHealthy() {
|
|
|
5609
5709
|
const deadline = Date.now() + SERVICE_OBSERVE_MS;
|
|
5610
5710
|
const graceDeadline = deadline + SERVICE_HEALTH_GRACE_MS;
|
|
5611
5711
|
let last = null;
|
|
5712
|
+
const unhealthy = (state, crashed, pid = null) => ({
|
|
5713
|
+
healthy: false,
|
|
5714
|
+
crashed,
|
|
5715
|
+
pid,
|
|
5716
|
+
exitCode: state.lastExitCode,
|
|
5717
|
+
terminatingSignal: state.lastTerminatingSignal
|
|
5718
|
+
});
|
|
5612
5719
|
do {
|
|
5613
5720
|
await sleep(SERVICE_HEALTH_INTERVAL_MS);
|
|
5614
5721
|
try {
|
|
@@ -5617,10 +5724,10 @@ async function waitServiceHealthy() {
|
|
|
5617
5724
|
continue;
|
|
5618
5725
|
}
|
|
5619
5726
|
if (isCrashed(last)) {
|
|
5620
|
-
return
|
|
5727
|
+
return unhealthy(last, true);
|
|
5621
5728
|
}
|
|
5622
5729
|
if (!last.loaded) {
|
|
5623
|
-
return
|
|
5730
|
+
return unhealthy(last, false);
|
|
5624
5731
|
}
|
|
5625
5732
|
} while (Date.now() < deadline);
|
|
5626
5733
|
if (last === null) return healthViaProcessProbe();
|
|
@@ -5635,13 +5742,13 @@ async function waitServiceHealthy() {
|
|
|
5635
5742
|
}
|
|
5636
5743
|
graceQueried = true;
|
|
5637
5744
|
if (isCrashed(last)) {
|
|
5638
|
-
return
|
|
5745
|
+
return unhealthy(last, true);
|
|
5639
5746
|
}
|
|
5640
5747
|
if (!last.loaded) break;
|
|
5641
5748
|
if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
|
|
5642
5749
|
}
|
|
5643
5750
|
if (!graceQueried) return healthViaProcessProbe();
|
|
5644
|
-
return
|
|
5751
|
+
return unhealthy(last, false, last.pid);
|
|
5645
5752
|
}
|
|
5646
5753
|
function healthViaProcessProbe() {
|
|
5647
5754
|
try {
|
|
@@ -5663,10 +5770,21 @@ function isCrashed(status) {
|
|
|
5663
5770
|
function describeAbnormalExit(status) {
|
|
5664
5771
|
return describeExitCause(status.lastExitCode, status.lastTerminatingSignal);
|
|
5665
5772
|
}
|
|
5773
|
+
function tunBlockedHint(lastLine) {
|
|
5774
|
+
return ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo-cli stop", "", lastLine];
|
|
5775
|
+
}
|
|
5776
|
+
function tunBlockedByRunningService() {
|
|
5777
|
+
return new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
|
|
5778
|
+
hint: tunBlockedHint("TUN \u7528\u5B8C\u540E mihomo-cli start \u53EF\u6062\u590D\u670D\u52A1")
|
|
5779
|
+
});
|
|
5780
|
+
}
|
|
5781
|
+
function tunBlockedByConcurrentStart() {
|
|
5782
|
+
return new CliError("\u53E6\u4E00\u7EC8\u7AEF\u5DF2\u542F\u52A8 Mixed \u670D\u52A1\uFF0CTUN \u672A\u542F\u52A8", {
|
|
5783
|
+
hint: tunBlockedHint("\u4E4B\u540E\u53EF\u91CD\u8BD5 TUN: mihomo-cli start tun")
|
|
5784
|
+
});
|
|
5785
|
+
}
|
|
5666
5786
|
function ensureServiceSymlink() {
|
|
5667
|
-
|
|
5668
|
-
throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
|
|
5669
|
-
}
|
|
5787
|
+
assertKernelInstalled();
|
|
5670
5788
|
try {
|
|
5671
5789
|
const current = fs13.readlinkSync(PATHS.serviceBinary);
|
|
5672
5790
|
if (current === "mihomo") return;
|
|
@@ -5732,7 +5850,7 @@ async function installService(wasRunning) {
|
|
|
5732
5850
|
atomicWriteFileSync(PATHS.userAgentPlist, fs13.readFileSync(stagePath, "utf8"), { mode: 420 });
|
|
5733
5851
|
if (wasRunning) {
|
|
5734
5852
|
withFileLock(PATHS.serviceLock, () => {
|
|
5735
|
-
if (
|
|
5853
|
+
if (startAbortedByConcurrentStop()) {
|
|
5736
5854
|
restoreSkipped = true;
|
|
5737
5855
|
return;
|
|
5738
5856
|
}
|
|
@@ -5757,9 +5875,7 @@ async function startService() {
|
|
|
5757
5875
|
if (!isServiceInstalled()) {
|
|
5758
5876
|
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
|
|
5759
5877
|
}
|
|
5760
|
-
|
|
5761
|
-
throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E", { hint: "\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
|
|
5762
|
-
}
|
|
5878
|
+
assertRuntimeConfigPresent();
|
|
5763
5879
|
if (getConfigInfo()?.tun) {
|
|
5764
5880
|
throw new CliError("\u8FD0\u884C\u65F6\u914D\u7F6E\u4E3A TUN \u6A21\u5F0F\uFF0C\u670D\u52A1\u65E0\u6CD5\u4F7F\u7528", {
|
|
5765
5881
|
hint: [
|
|
@@ -5777,7 +5893,7 @@ async function startService() {
|
|
|
5777
5893
|
rotateAndCleanupLogs();
|
|
5778
5894
|
let started = true;
|
|
5779
5895
|
withFileLock(PATHS.serviceLock, () => {
|
|
5780
|
-
if (
|
|
5896
|
+
if (startAbortedByConcurrentStop()) {
|
|
5781
5897
|
started = false;
|
|
5782
5898
|
return;
|
|
5783
5899
|
}
|
|
@@ -5796,42 +5912,43 @@ function disableServiceAutoStart(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
|
5796
5912
|
}
|
|
5797
5913
|
bumpStopEpoch();
|
|
5798
5914
|
}
|
|
5799
|
-
async function
|
|
5800
|
-
assertServiceLabelSafe();
|
|
5915
|
+
async function bootoutAndDisableInLock() {
|
|
5801
5916
|
withFileLock(PATHS.serviceLock, () => {
|
|
5802
5917
|
bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5803
5918
|
disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5804
5919
|
});
|
|
5805
5920
|
await waitUntilUnloaded();
|
|
5806
|
-
|
|
5921
|
+
}
|
|
5922
|
+
async function stopService() {
|
|
5923
|
+
assertServiceLabelSafe();
|
|
5924
|
+
await bootoutAndDisableInLock();
|
|
5925
|
+
return cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo-cli stop" });
|
|
5807
5926
|
}
|
|
5808
5927
|
async function uninstallService() {
|
|
5809
5928
|
assertServiceLabelSafe();
|
|
5810
|
-
|
|
5811
|
-
bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5812
|
-
disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5813
|
-
});
|
|
5814
|
-
await waitUntilUnloaded();
|
|
5929
|
+
await bootoutAndDisableInLock();
|
|
5815
5930
|
try {
|
|
5816
5931
|
fs13.rmSync(PATHS.userAgentPlist, { force: true });
|
|
5817
5932
|
} catch (e) {
|
|
5818
5933
|
throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
|
|
5819
5934
|
}
|
|
5820
|
-
await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
|
|
5935
|
+
const cleanup = await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
|
|
5821
5936
|
try {
|
|
5822
5937
|
fs13.rmSync(PATHS.serviceBinary, { force: true });
|
|
5823
5938
|
} catch {
|
|
5824
5939
|
}
|
|
5940
|
+
return cleanup;
|
|
5825
5941
|
}
|
|
5826
|
-
async function restartService() {
|
|
5942
|
+
async function restartService(prefetched) {
|
|
5827
5943
|
assertServiceLabelSafe();
|
|
5828
5944
|
if (!isServiceInstalled()) {
|
|
5829
5945
|
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
|
|
5830
5946
|
}
|
|
5831
|
-
|
|
5947
|
+
const oversized = logOversized();
|
|
5948
|
+
if (!oversized && await tryHotReload(prefetched)) {
|
|
5832
5949
|
return concludeHotReload(stopEpochBaseline(), readStopEpoch());
|
|
5833
5950
|
}
|
|
5834
|
-
if (
|
|
5951
|
+
if (oversized) {
|
|
5835
5952
|
const archiveFile = allocateArchivePath();
|
|
5836
5953
|
try {
|
|
5837
5954
|
fs13.copyFileSync(PATHS.logFile, archiveFile);
|
|
@@ -5843,7 +5960,7 @@ async function restartService() {
|
|
|
5843
5960
|
let started = true;
|
|
5844
5961
|
if (kick.status !== 0) {
|
|
5845
5962
|
withFileLock(PATHS.serviceLock, () => {
|
|
5846
|
-
if (
|
|
5963
|
+
if (startAbortedByConcurrentStop()) {
|
|
5847
5964
|
started = false;
|
|
5848
5965
|
return;
|
|
5849
5966
|
}
|
|
@@ -5897,7 +6014,7 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))} (mihomo-cli help \u67E5\u
|
|
|
5897
6014
|
const steps = [];
|
|
5898
6015
|
if (!hasKernel()) steps.push(["mihomo-cli kernel", "\u4E0B\u8F7D\u5185\u6838"]);
|
|
5899
6016
|
if (getSubscriptions().length === 0) steps.push(["mihomo-cli sub add <url>", "\u6DFB\u52A0\u8BA2\u9605"]);
|
|
5900
|
-
if (!
|
|
6017
|
+
if (!isServiceInstalled()) steps.push(["mihomo-cli install", "\u5B89\u88C5\u670D\u52A1\uFF08\u53EA\u9700\u4E00\u6B21\uFF09"]);
|
|
5901
6018
|
if (steps.length > 0) {
|
|
5902
6019
|
steps.push(["mihomo-cli start", "\u542F\u52A8\u4EE3\u7406"]);
|
|
5903
6020
|
const width = Math.max(...steps.map(([cmd]) => displayWidth(cmd)));
|
|
@@ -6338,35 +6455,17 @@ async function downloadSubscription(url, subName = "default", signal) {
|
|
|
6338
6455
|
hint: ["\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664", "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
|
|
6339
6456
|
});
|
|
6340
6457
|
}
|
|
6341
|
-
const proxies = parsed
|
|
6342
|
-
|
|
6343
|
-
return {
|
|
6344
|
-
proxies: proxies ? proxies.length : 0,
|
|
6345
|
-
proxyGroups: proxyGroups ? proxyGroups.length : 0,
|
|
6346
|
-
userInfo: meta.userInfo,
|
|
6347
|
-
updateInterval: meta.updateInterval,
|
|
6348
|
-
webPageUrl: meta.webPageUrl,
|
|
6349
|
-
username: meta.username
|
|
6350
|
-
};
|
|
6458
|
+
const { proxies, proxyGroups } = countConfigNodes(parsed);
|
|
6459
|
+
return { proxies, proxyGroups };
|
|
6351
6460
|
}
|
|
6352
6461
|
async function prepareConfigForStart(mode, subName = "default") {
|
|
6353
|
-
const rawContent =
|
|
6354
|
-
if (!rawContent) {
|
|
6355
|
-
throw new CliError(`\u8BA2\u9605 "${subName}" \u6709\u6761\u76EE\u4F46\u6CA1\u6709\u672C\u5730\u914D\u7F6E\u6587\u4EF6`, {
|
|
6356
|
-
hint: `\u66F4\u65B0\u8BA2\u9605: mihomo-cli sub update ${subName}`
|
|
6357
|
-
});
|
|
6358
|
-
}
|
|
6462
|
+
const rawContent = requireSubscriptionRawConfig(subName);
|
|
6359
6463
|
const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
|
|
6360
6464
|
const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
|
|
6361
6465
|
await validateConfigWithKernel(buildResult.config, buildResult.overwriteSummaries);
|
|
6362
|
-
const proxies = buildResult.config.proxies;
|
|
6363
|
-
const proxyGroups = buildResult.config["proxy-groups"];
|
|
6364
6466
|
return {
|
|
6365
6467
|
buildResult,
|
|
6366
|
-
info:
|
|
6367
|
-
proxies: proxies ? proxies.length : 0,
|
|
6368
|
-
proxyGroups: proxyGroups ? proxyGroups.length : 0
|
|
6369
|
-
}
|
|
6468
|
+
info: countConfigNodes(buildResult.config)
|
|
6370
6469
|
};
|
|
6371
6470
|
}
|
|
6372
6471
|
function commitPreparedConfig(prepared) {
|
|
@@ -6410,7 +6509,7 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
6410
6509
|
const allSubs = getSubscriptionsWithCache();
|
|
6411
6510
|
const staleSubs = allSubs.filter(needsAutoUpdate);
|
|
6412
6511
|
if (staleSubs.length === 0) {
|
|
6413
|
-
return
|
|
6512
|
+
return;
|
|
6414
6513
|
}
|
|
6415
6514
|
if (staleSubs.length === 1) {
|
|
6416
6515
|
const sub = staleSubs[0];
|
|
@@ -6439,14 +6538,9 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
6439
6538
|
});
|
|
6440
6539
|
console.log(colors.yellow(`\u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 (${timeoutMs / 1e3}s)\uFF0C\u5DF2\u5B8C\u6210\u7684\u66F4\u65B0\u751F\u6548\uFF0C\u5176\u4F59\u4F7F\u7528\u7F13\u5B58\u914D\u7F6E`));
|
|
6441
6540
|
}
|
|
6442
|
-
let updatedCount = 0;
|
|
6443
|
-
let failedCount = 0;
|
|
6444
6541
|
for (const r of results) {
|
|
6445
|
-
if (r.success) updatedCount++;
|
|
6446
|
-
else if (!r.aborted) failedCount++;
|
|
6447
6542
|
printUpdateResult(r);
|
|
6448
6543
|
}
|
|
6449
|
-
return { total: staleSubs.length, updated: updatedCount, failed: failedCount };
|
|
6450
6544
|
}
|
|
6451
6545
|
|
|
6452
6546
|
// src/commands/config.ts
|
|
@@ -6459,11 +6553,8 @@ function cmdConfig(args = []) {
|
|
|
6459
6553
|
if (!active) {
|
|
6460
6554
|
throw new CliError("\u5C1A\u65E0\u8BA2\u9605\uFF0C\u65E0\u6CD5\u63A8\u5BFC\u914D\u7F6E", { hint: "\u6DFB\u52A0\u8BA2\u9605: mihomo-cli sub add <url>" });
|
|
6461
6555
|
}
|
|
6462
|
-
const rawContent =
|
|
6463
|
-
|
|
6464
|
-
throw new CliError(`\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u6CA1\u6709\u672C\u5730\u914D\u7F6E\u6587\u4EF6`, { hint: `\u66F4\u65B0\u8BA2\u9605: mihomo-cli sub update ${active.name}` });
|
|
6465
|
-
}
|
|
6466
|
-
const mode = getConfigInfo()?.tun ? "tun" : "mixed";
|
|
6556
|
+
const rawContent = requireSubscriptionRawConfig(active.name);
|
|
6557
|
+
const mode = deriveRuntimeMode(getConfigInfo());
|
|
6467
6558
|
const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
|
|
6468
6559
|
const redacted = reveal ? { config, changed: false } : redactConfigSecrets(config);
|
|
6469
6560
|
const shown = redacted.config;
|
|
@@ -6602,18 +6693,13 @@ tail -25 "\${LOG_FILE}" 2>/dev/null
|
|
|
6602
6693
|
exit 2
|
|
6603
6694
|
`;
|
|
6604
6695
|
}
|
|
6605
|
-
async function startTun() {
|
|
6696
|
+
async function startTun(prefetched) {
|
|
6606
6697
|
ensureDirs();
|
|
6607
|
-
|
|
6608
|
-
|
|
6609
|
-
}
|
|
6610
|
-
if (
|
|
6611
|
-
throw
|
|
6612
|
-
}
|
|
6613
|
-
if (getServiceStatus().loaded) {
|
|
6614
|
-
throw new CliError("\u53E6\u4E00\u7EC8\u7AEF\u5DF2\u542F\u52A8 Mixed \u670D\u52A1\uFF0CTUN \u672A\u542F\u52A8", {
|
|
6615
|
-
hint: ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo-cli stop", "", "\u4E4B\u540E\u53EF\u91CD\u8BD5 TUN: mihomo-cli start tun"]
|
|
6616
|
-
});
|
|
6698
|
+
assertKernelInstalled();
|
|
6699
|
+
assertRuntimeConfigPresent();
|
|
6700
|
+
const serviceLoaded = prefetched ? prefetched.loaded : getServiceStatus({ withDisabled: false }).loaded;
|
|
6701
|
+
if (serviceLoaded) {
|
|
6702
|
+
throw tunBlockedByConcurrentStart();
|
|
6617
6703
|
}
|
|
6618
6704
|
rotateAndCleanupLogs();
|
|
6619
6705
|
const logFile = PATHS.logFile;
|
|
@@ -6641,7 +6727,7 @@ async function startTun() {
|
|
|
6641
6727
|
file: "launch-tun.sh",
|
|
6642
6728
|
codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
|
|
6643
6729
|
});
|
|
6644
|
-
await
|
|
6730
|
+
await sleep(TUN_MODE_POST_WAIT_MS);
|
|
6645
6731
|
const finalPid = getPid();
|
|
6646
6732
|
if (!finalPid || !isRunning()) {
|
|
6647
6733
|
const tail = readLogTail();
|
|
@@ -6649,7 +6735,7 @@ async function startTun() {
|
|
|
6649
6735
|
hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo-cli logs 0"]
|
|
6650
6736
|
});
|
|
6651
6737
|
}
|
|
6652
|
-
return
|
|
6738
|
+
return finalPid;
|
|
6653
6739
|
}
|
|
6654
6740
|
|
|
6655
6741
|
// src/runtime.ts
|
|
@@ -6658,7 +6744,7 @@ function getRuntimeMode() {
|
|
|
6658
6744
|
return getConfigInfo()?.tun ? "tun" : "mixed";
|
|
6659
6745
|
}
|
|
6660
6746
|
function getRunningState(serviceStatus) {
|
|
6661
|
-
const service = serviceStatus ?? getServiceStatus();
|
|
6747
|
+
const service = serviceStatus ?? getServiceStatus({ withDisabled: false });
|
|
6662
6748
|
if (service.running) {
|
|
6663
6749
|
return { running: true, pid: service.pid, kind: "service", processInfo: null };
|
|
6664
6750
|
}
|
|
@@ -6677,15 +6763,13 @@ function restartModeOnChange() {
|
|
|
6677
6763
|
}
|
|
6678
6764
|
async function launchOrRestart(mode) {
|
|
6679
6765
|
if (mode === "tun") {
|
|
6680
|
-
assertTunStartNotRaced();
|
|
6681
|
-
const result = await startTun();
|
|
6682
|
-
return result.pid;
|
|
6766
|
+
return startTun(assertTunStartNotRaced());
|
|
6683
6767
|
}
|
|
6684
6768
|
const status = getServiceStatus();
|
|
6685
6769
|
let hotReloaded = false;
|
|
6686
6770
|
let started;
|
|
6687
6771
|
if (status.running && !status.disabled) {
|
|
6688
|
-
({ hotReloaded, started } = await restartService());
|
|
6772
|
+
({ hotReloaded, started } = await restartService(status));
|
|
6689
6773
|
} else {
|
|
6690
6774
|
({ started } = await startService());
|
|
6691
6775
|
}
|
|
@@ -6700,7 +6784,7 @@ async function launchOrRestart(mode) {
|
|
|
6700
6784
|
try {
|
|
6701
6785
|
return await assertServiceHealthy();
|
|
6702
6786
|
} catch (e) {
|
|
6703
|
-
if (
|
|
6787
|
+
if (startAbortedByConcurrentStop()) throw cancelledByConcurrentStop();
|
|
6704
6788
|
throw e;
|
|
6705
6789
|
}
|
|
6706
6790
|
}
|
|
@@ -6714,14 +6798,11 @@ function cancelledByConcurrentStop() {
|
|
|
6714
6798
|
]
|
|
6715
6799
|
});
|
|
6716
6800
|
}
|
|
6717
|
-
function tunBlockedByRunningService() {
|
|
6718
|
-
return new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
|
|
6719
|
-
hint: ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo-cli stop", "", "TUN \u7528\u5B8C\u540E mihomo-cli start \u53EF\u6062\u590D\u670D\u52A1"]
|
|
6720
|
-
});
|
|
6721
|
-
}
|
|
6722
6801
|
function assertTunStartNotRaced() {
|
|
6723
|
-
if (
|
|
6724
|
-
|
|
6802
|
+
if (startAbortedByConcurrentStop()) throw cancelledByConcurrentStop();
|
|
6803
|
+
const status = getServiceStatus({ withDisabled: false });
|
|
6804
|
+
if (status.loaded) throw tunBlockedByConcurrentStart();
|
|
6805
|
+
return status;
|
|
6725
6806
|
}
|
|
6726
6807
|
function startCommandForCurrentMode(state) {
|
|
6727
6808
|
return state.kind === "tun" ? "mihomo-cli start tun" : "mihomo-cli start";
|
|
@@ -6853,51 +6934,6 @@ function printSystemProxyHint(mixedPort) {
|
|
|
6853
6934
|
console.log(colors.gray(` networksetup -setsocksfirewallproxy "Wi-Fi" 127.0.0.1 ${mixedPort}`));
|
|
6854
6935
|
}
|
|
6855
6936
|
|
|
6856
|
-
// src/proxy-probe.ts
|
|
6857
|
-
import { execFile as execFile2 } from "child_process";
|
|
6858
|
-
import { promisify as promisify2 } from "util";
|
|
6859
|
-
var execFileAsync = promisify2(execFile2);
|
|
6860
|
-
var PROBE_URL = "https://www.gstatic.com/generate_204";
|
|
6861
|
-
function isProbeSuccessStatus(code) {
|
|
6862
|
-
return code !== null && code >= 200 && code < 300;
|
|
6863
|
-
}
|
|
6864
|
-
var PROBE_TIMEOUT_MS = 2e3;
|
|
6865
|
-
var PROBE_CACHE_TTL_MS = 3e3;
|
|
6866
|
-
var probeCache = null;
|
|
6867
|
-
async function probeProxyConnectivity(port) {
|
|
6868
|
-
if (probeCache && probeCache.port === port && Date.now() - probeCache.at < PROBE_CACHE_TTL_MS) {
|
|
6869
|
-
return probeCache.result;
|
|
6870
|
-
}
|
|
6871
|
-
const result = await probeProxyConnectivityUncached(port);
|
|
6872
|
-
probeCache = { port, at: Date.now(), result };
|
|
6873
|
-
return result;
|
|
6874
|
-
}
|
|
6875
|
-
async function probeProxyConnectivityUncached(port) {
|
|
6876
|
-
const start = Date.now();
|
|
6877
|
-
try {
|
|
6878
|
-
const { stdout } = await execFileAsync(
|
|
6879
|
-
"curl",
|
|
6880
|
-
["-x", `http://127.0.0.1:${port}`, "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
|
|
6881
|
-
{ timeout: PROBE_TIMEOUT_MS + 2e3 }
|
|
6882
|
-
);
|
|
6883
|
-
const code = Number.parseInt(stdout.trim(), 10);
|
|
6884
|
-
const statusCode = Number.isFinite(code) ? code : null;
|
|
6885
|
-
const ok = isProbeSuccessStatus(statusCode);
|
|
6886
|
-
return {
|
|
6887
|
-
ok,
|
|
6888
|
-
statusCode,
|
|
6889
|
-
error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
|
|
6890
|
-
durationMs: Date.now() - start
|
|
6891
|
-
};
|
|
6892
|
-
} catch (e) {
|
|
6893
|
-
const err = e;
|
|
6894
|
-
const stderr = err.stderr?.toString().trim();
|
|
6895
|
-
const lastLine = stderr ? stderr.split("\n").pop() : void 0;
|
|
6896
|
-
const detail = lastLine ? lastLine.replace(/^curl: \(\d+\)\s*/, "") : err.message ?? "\u8BF7\u6C42\u5931\u8D25";
|
|
6897
|
-
return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
|
|
6898
|
-
}
|
|
6899
|
-
}
|
|
6900
|
-
|
|
6901
6937
|
// src/commands/status.ts
|
|
6902
6938
|
function connectivityHint(urgency) {
|
|
6903
6939
|
if (urgency === "expired") return "\u8BA2\u9605\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u7EED\u8D39\u6216\u66F4\u6362\u8BA2\u9605";
|
|
@@ -6917,13 +6953,14 @@ function expireColor(line, urgency) {
|
|
|
6917
6953
|
if (urgency === "expiring") return colors.yellow(line);
|
|
6918
6954
|
return line;
|
|
6919
6955
|
}
|
|
6956
|
+
var isActiveOverwrite = (f) => f.enabled && f.matched !== false;
|
|
6920
6957
|
function buildStatusJson(args) {
|
|
6921
6958
|
const urgency = args.cached ? subscriptionUrgency(args.cached) : null;
|
|
6922
6959
|
return {
|
|
6923
6960
|
version: VERSION,
|
|
6924
6961
|
running: args.running,
|
|
6925
6962
|
connectivity: args.probe ? { ok: args.probe.ok, statusCode: args.probe.statusCode, error: args.probe.error, durationMs: args.probe.durationMs } : null,
|
|
6926
|
-
mode: args.info ? args.info
|
|
6963
|
+
mode: args.info ? deriveRuntimeMode(args.info) : null,
|
|
6927
6964
|
carrier: args.kind,
|
|
6928
6965
|
pid: args.pid,
|
|
6929
6966
|
kernel: getKernelVersion(),
|
|
@@ -6950,7 +6987,7 @@ function buildStatusJson(args) {
|
|
|
6950
6987
|
files: args.overwriteFiles.filter((f) => f.enabled).map((f) => f.name),
|
|
6951
6988
|
// 全局关闭时 buildConfig 不加载任何覆写,applied 必须空——只滤 enabled/match
|
|
6952
6989
|
// 会列出「生效文件」,与同一份 JSON 里的 enabled:false 自相矛盾
|
|
6953
|
-
applied: args.overwriteEnabled ? args.overwriteFiles.filter(
|
|
6990
|
+
applied: args.overwriteEnabled ? args.overwriteFiles.filter(isActiveOverwrite).map((f) => f.name) : [],
|
|
6954
6991
|
// 加载失败的文件不属于 files/applied(既没合并也无法判 enabled/match),单列 errors。
|
|
6955
6992
|
// hint 必须带出:最有用的迁移指引(已移除操作符改 JS、*edu 加引号等)都在里面,
|
|
6956
6993
|
// 只给 message 等于把可执行的修复步骤扔在启动硬失败那一条路径上
|
|
@@ -6979,11 +7016,22 @@ async function printStatus(args = []) {
|
|
|
6979
7016
|
const {
|
|
6980
7017
|
enabled: overwriteEnabled,
|
|
6981
7018
|
files: overwriteFiles,
|
|
7019
|
+
entries: overwriteEntries,
|
|
6982
7020
|
broken: overwriteBroken
|
|
6983
7021
|
} = listOverwriteFile(activeSub ? { subName: activeSub.name, subUrl: activeSub.url } : void 0);
|
|
7022
|
+
if (activeSub && overwriteEnabled && overwriteFiles.some((f) => f.kind === "script")) {
|
|
7023
|
+
const rawContent = readSubscriptionRawConfig(activeSub.name);
|
|
7024
|
+
if (rawContent) {
|
|
7025
|
+
const { matches } = judgeScriptMatches(rawContent, deriveRuntimeMode(info), { subName: activeSub.name, subUrl: activeSub.url }, overwriteEntries);
|
|
7026
|
+
const matchedByName = new Map(matches.map((m) => [m.file, m.matched]));
|
|
7027
|
+
for (const f of overwriteFiles) {
|
|
7028
|
+
if (f.kind === "script" && matchedByName.has(f.name)) f.matched = matchedByName.get(f.name);
|
|
7029
|
+
}
|
|
7030
|
+
}
|
|
7031
|
+
}
|
|
6984
7032
|
const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
|
|
6985
7033
|
const legacy = detectLegacySystemInstall();
|
|
6986
|
-
const controllerPort =
|
|
7034
|
+
const controllerPort = getPortsOrNull()?.controller ?? null;
|
|
6987
7035
|
const { running, pid, kind } = state;
|
|
6988
7036
|
let probe = null;
|
|
6989
7037
|
if (running && info?.mixedPort && !skipProbe) {
|
|
@@ -7019,7 +7067,7 @@ async function printStatus(args = []) {
|
|
|
7019
7067
|
console.log("");
|
|
7020
7068
|
let modeLabel = "";
|
|
7021
7069
|
if (info) {
|
|
7022
|
-
const mode = info
|
|
7070
|
+
const mode = runtimeModeLabel(deriveRuntimeMode(info));
|
|
7023
7071
|
const carrier = kind === "service" ? " \xB7 \u670D\u52A1" : kind === "tun" ? " \xB7 \u4E34\u65F6" : "";
|
|
7024
7072
|
modeLabel = colors.cyan(` (${mode}${carrier})`);
|
|
7025
7073
|
}
|
|
@@ -7092,15 +7140,12 @@ async function printStatus(args = []) {
|
|
|
7092
7140
|
}
|
|
7093
7141
|
console.log("");
|
|
7094
7142
|
}
|
|
7095
|
-
function shortOverwriteName(name) {
|
|
7096
|
-
return name.replace(/\.(?:ya?ml|m?js|cjs)$/, "").replace(/^overwrite\.?/, "") || "\u4E3B\u6587\u4EF6";
|
|
7097
|
-
}
|
|
7098
7143
|
function printOverwriteLines(enabled, files, broken, activeSub) {
|
|
7099
7144
|
if (!enabled) {
|
|
7100
7145
|
console.log(`${colors.gray("\u8986\u5199: ")}${colors.yellow("\u5DF2\u7981\u7528")}`);
|
|
7101
7146
|
return;
|
|
7102
7147
|
}
|
|
7103
|
-
const active = files.filter(
|
|
7148
|
+
const active = files.filter(isActiveOverwrite);
|
|
7104
7149
|
const unmatched = files.filter((f) => f.enabled && f.matched === false);
|
|
7105
7150
|
const disabledCount = files.filter((f) => !f.enabled).length;
|
|
7106
7151
|
const suffixes = [];
|
|
@@ -7113,8 +7158,8 @@ function printOverwriteLines(enabled, files, broken, activeSub) {
|
|
|
7113
7158
|
console.log(`${colors.gray("\u8986\u5199: ")}${colors.green("\u5DF2\u542F\u7528")} (${files.length > 0 ? `\u65E0\u751F\u6548\u6587\u4EF6${suffix}` : "\u65E0\u6587\u4EF6"})`);
|
|
7114
7159
|
}
|
|
7115
7160
|
for (const f of unmatched) {
|
|
7116
|
-
const
|
|
7117
|
-
console.log(colors.gray(` ${shortOverwriteName(f.name)} \u4E0D\u9002\u7528\u4E8E\u5F53\u524D\u8BA2\u9605${activeSub ? ` ${activeSub.name}` : ""}\uFF08${
|
|
7161
|
+
const reason = f.kind === "script" ? "\u811A\u672C\u672A\u8FD4\u56DE true" : f.scope ? `\u4F5C\u7528\u57DF ${f.scope}` : "\u4F5C\u7528\u57DF\u53D7\u9650";
|
|
7162
|
+
console.log(colors.gray(` ${shortOverwriteName(f.name)} \u4E0D\u9002\u7528\u4E8E\u5F53\u524D\u8BA2\u9605${activeSub ? ` ${activeSub.name}` : ""}\uFF08${reason}\uFF09`));
|
|
7118
7163
|
}
|
|
7119
7164
|
for (const b of broken) {
|
|
7120
7165
|
console.log(colors.red(` ${b.message}`));
|
|
@@ -7158,17 +7203,11 @@ async function cmdStart(args) {
|
|
|
7158
7203
|
const skipUpdate = hasFlag(args, "-s", "--no-update");
|
|
7159
7204
|
const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
|
|
7160
7205
|
let disabledAutoStartForTun = false;
|
|
7161
|
-
|
|
7162
|
-
throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
|
|
7163
|
-
}
|
|
7206
|
+
assertKernelInstalled();
|
|
7164
7207
|
const serviceBefore = getServiceStatus();
|
|
7165
7208
|
if (targetMode === "tun") {
|
|
7166
7209
|
if (detectLegacySystemInstall()) {
|
|
7167
|
-
|
|
7168
|
-
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"));
|
|
7169
|
-
await cleanupLegacyInstallOrThrow();
|
|
7170
|
-
console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
|
|
7171
|
-
console.log("");
|
|
7210
|
+
await announceLegacyCleanupOrThrow("\u542F\u52A8 TUN \u524D\u9700\u6E05\u7406");
|
|
7172
7211
|
}
|
|
7173
7212
|
if (serviceBefore.loaded) {
|
|
7174
7213
|
throw tunBlockedByRunningService();
|
|
@@ -7205,8 +7244,7 @@ async function cmdStart(args) {
|
|
|
7205
7244
|
throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
7206
7245
|
}
|
|
7207
7246
|
const configInfo = commitPreparedConfig(prepared);
|
|
7208
|
-
|
|
7209
|
-
console.log([colors.cyan(modeLabel), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
|
|
7247
|
+
console.log([colors.cyan(runtimeModeLabel(targetMode)), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
|
|
7210
7248
|
try {
|
|
7211
7249
|
const pid = await launchOrRestart(targetMode);
|
|
7212
7250
|
console.log(`${colors.green("\u5DF2\u542F\u52A8")}${pid ? ` (PID ${pid})` : ""}`);
|
|
@@ -7260,6 +7298,16 @@ async function dispatchSubcommand(args, table, options) {
|
|
|
7260
7298
|
}
|
|
7261
7299
|
return options.fallback(args);
|
|
7262
7300
|
}
|
|
7301
|
+
function unknownSubcommandError(action, table, opts) {
|
|
7302
|
+
if (action.startsWith("-")) {
|
|
7303
|
+
throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, { label: "\u53C2\u6570\u9519\u8BEF", hint: opts.optionHint });
|
|
7304
|
+
}
|
|
7305
|
+
const names = table.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
7306
|
+
const suggestion = suggestSimilar(action, names);
|
|
7307
|
+
throw new CliError(`\u672A\u77E5\u7684${opts.what}: ${action}`, {
|
|
7308
|
+
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], ...opts.unknownHint]
|
|
7309
|
+
});
|
|
7310
|
+
}
|
|
7263
7311
|
async function confirmPrompt(question) {
|
|
7264
7312
|
if (!process.stdin.isTTY) return false;
|
|
7265
7313
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
@@ -7330,29 +7378,16 @@ async function cmdDirectory(args) {
|
|
|
7330
7378
|
assertKnownFlags(args.slice(1), [], "dir");
|
|
7331
7379
|
await dispatchSubcommand(args, SUBCOMMANDS, {
|
|
7332
7380
|
fallback: printDirectoryInfo,
|
|
7333
|
-
|
|
7334
|
-
|
|
7335
|
-
|
|
7336
|
-
|
|
7337
|
-
|
|
7338
|
-
|
|
7339
|
-
}
|
|
7340
|
-
const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
7341
|
-
const suggestion = suggestSimilar(action, names);
|
|
7342
|
-
throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
|
|
7343
|
-
hint: [
|
|
7344
|
-
...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
|
|
7345
|
-
"",
|
|
7346
|
-
"\u53EF\u7528\u5B50\u547D\u4EE4: open",
|
|
7347
|
-
"\u6253\u5F00\u6307\u5B9A\u76EE\u5F55: mihomo-cli dir open <target>"
|
|
7348
|
-
]
|
|
7349
|
-
});
|
|
7350
|
-
}
|
|
7381
|
+
// 裸 dir 只展示目录信息(选项由分发前的白名单统一拦);守卫收口在 shared
|
|
7382
|
+
onUnknown: (action) => unknownSubcommandError(action, SUBCOMMANDS, {
|
|
7383
|
+
what: "\u76EE\u5F55\u5B50\u547D\u4EE4",
|
|
7384
|
+
optionHint: ["\u88F8 dir \u53EA\u5C55\u793A\u76EE\u5F55\u4FE1\u606F\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo-cli dir open [root|subs|logs|data|runtime|kernel]"],
|
|
7385
|
+
unknownHint: ["", "\u53EF\u7528\u5B50\u547D\u4EE4: open", "\u6253\u5F00\u6307\u5B9A\u76EE\u5F55: mihomo-cli dir open <target>"]
|
|
7386
|
+
})
|
|
7351
7387
|
});
|
|
7352
7388
|
}
|
|
7353
7389
|
|
|
7354
7390
|
// src/commands/doctor.ts
|
|
7355
|
-
import { spawnSync as spawnSync10 } from "child_process";
|
|
7356
7391
|
import fs16 from "fs";
|
|
7357
7392
|
|
|
7358
7393
|
// src/kernel.ts
|
|
@@ -7389,6 +7424,7 @@ function assertTrustedAssetUrl(rawUrl) {
|
|
|
7389
7424
|
\u4EC5\u5141\u8BB8: ${[...ALLOWED_ASSET_HOSTS].join(", ")}`);
|
|
7390
7425
|
}
|
|
7391
7426
|
}
|
|
7427
|
+
var loopbackHttpUrl = (port) => `http://127.0.0.1:${port}`;
|
|
7392
7428
|
function resolveDownloadChannels(input) {
|
|
7393
7429
|
if (input.isOverride && !input.mirror) return [{ kind: "direct" }];
|
|
7394
7430
|
if (input.isOverride && input.mirror) {
|
|
@@ -7396,7 +7432,7 @@ function resolveDownloadChannels(input) {
|
|
|
7396
7432
|
}
|
|
7397
7433
|
if (input.proxyOverride) return [{ kind: "proxy", proxy: input.proxyOverride }];
|
|
7398
7434
|
if (input.proxyRunning && input.proxyPort !== null) {
|
|
7399
|
-
const proxyUrl =
|
|
7435
|
+
const proxyUrl = loopbackHttpUrl(input.proxyPort);
|
|
7400
7436
|
const channels = [{ kind: "proxy", proxy: proxyUrl }];
|
|
7401
7437
|
if (input.ghAvailable) channels.push({ kind: "gh", proxy: proxyUrl });
|
|
7402
7438
|
return channels;
|
|
@@ -7404,6 +7440,11 @@ function resolveDownloadChannels(input) {
|
|
|
7404
7440
|
if (input.ghAvailable) return [{ kind: "gh" }];
|
|
7405
7441
|
return [{ kind: "direct" }];
|
|
7406
7442
|
}
|
|
7443
|
+
function resolveReleaseQuery(input) {
|
|
7444
|
+
const forceDirect = input.isOverride && !input.mirror;
|
|
7445
|
+
const proxy = input.proxyOverride ?? (!forceDirect && input.proxyRunning && input.proxyPort !== null ? loopbackHttpUrl(input.proxyPort) : null);
|
|
7446
|
+
return { proxy, useGh: proxy === null && !forceDirect && input.ghAvailable };
|
|
7447
|
+
}
|
|
7407
7448
|
function ghProbeNeeded(input) {
|
|
7408
7449
|
return !input.forceDirect && input.proxyOverride === null;
|
|
7409
7450
|
}
|
|
@@ -7412,10 +7453,7 @@ function hasGh() {
|
|
|
7412
7453
|
return !result.error && result.status === 0;
|
|
7413
7454
|
}
|
|
7414
7455
|
function getArch() {
|
|
7415
|
-
|
|
7416
|
-
if (arch === "arm64") return "arm64";
|
|
7417
|
-
if (arch === "x64") return "amd64";
|
|
7418
|
-
return arch;
|
|
7456
|
+
return process.arch === "x64" ? "amd64" : process.arch;
|
|
7419
7457
|
}
|
|
7420
7458
|
function findMatchingAsset(assets, platform, arch) {
|
|
7421
7459
|
const prefix = `mihomo-${platform}-${arch}`;
|
|
@@ -7481,9 +7519,8 @@ function translateReleaseApiCurlError(e) {
|
|
|
7481
7519
|
if (err.killed) {
|
|
7482
7520
|
return new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25: curl ${Math.floor((KERNEL_HTTP_TIMEOUT + 1e4) / 1e3)}s \u672A\u5B8C\u6210\uFF0C\u5DF2\u7EC8\u6B62${err.signal ? `\uFF08${err.signal}\uFF09` : ""}`);
|
|
7483
7521
|
}
|
|
7484
|
-
const
|
|
7485
|
-
|
|
7486
|
-
return new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25 (curl \u9000\u51FA\u7801 ${err.code ?? "?"}${lastLine ? `: ${lastLine}` : ""})`);
|
|
7522
|
+
const suffix = lastCurlErrorLine(typeof err.stderr === "string" ? err.stderr : "");
|
|
7523
|
+
return new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25 (curl \u9000\u51FA\u7801 ${err.code ?? "?"}${suffix ? `: ${suffix}` : ""})`);
|
|
7487
7524
|
}
|
|
7488
7525
|
function buildGhApiReleaseArgs(repo) {
|
|
7489
7526
|
return ["api", `repos/${repo}/releases`, "--method", "GET"];
|
|
@@ -7498,7 +7535,7 @@ async function getLatestReleaseViaGh(repo, signal) {
|
|
|
7498
7535
|
});
|
|
7499
7536
|
return pickLatestRelease(JSON.parse(result.stdout));
|
|
7500
7537
|
}
|
|
7501
|
-
async function getLatestRelease(repo, opts
|
|
7538
|
+
async function getLatestRelease(repo, opts) {
|
|
7502
7539
|
const url = `https://api.github.com/repos/${repo}/releases`;
|
|
7503
7540
|
if (opts.useGh) {
|
|
7504
7541
|
try {
|
|
@@ -7537,7 +7574,7 @@ async function getLatestRelease(repo, opts = { proxy: null, useGh: false }) {
|
|
|
7537
7574
|
return pickLatestRelease(response.data);
|
|
7538
7575
|
}
|
|
7539
7576
|
async function checkUpdate(opts) {
|
|
7540
|
-
const currentVersion = getKernelVersion();
|
|
7577
|
+
const currentVersion = opts.currentVersion !== void 0 ? opts.currentVersion : getKernelVersion();
|
|
7541
7578
|
let ghFallbackToDirect = false;
|
|
7542
7579
|
const optsWithFallbackNote = {
|
|
7543
7580
|
...opts,
|
|
@@ -7627,7 +7664,7 @@ function resolveFallbackQueryOptions(channel) {
|
|
|
7627
7664
|
}
|
|
7628
7665
|
async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
7629
7666
|
ensureDirs();
|
|
7630
|
-
const apiProxy = channel.kind === "
|
|
7667
|
+
const apiProxy = channel.kind === "direct" ? null : channel.proxy ?? null;
|
|
7631
7668
|
const latest = releaseInfo || await getLatestRelease(GITHUB_REPO, resolveFallbackQueryOptions(channel));
|
|
7632
7669
|
const arch = getArch();
|
|
7633
7670
|
const platform = process.platform;
|
|
@@ -7642,7 +7679,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7642
7679
|
}
|
|
7643
7680
|
assertTrustedAssetUrl(asset.browser_download_url);
|
|
7644
7681
|
const downloadUrl = channel.kind === "mirror" ? withMirror(asset.browser_download_url, channel.mirror) : asset.browser_download_url;
|
|
7645
|
-
const mirrorIneffective = channel.kind === "mirror" &&
|
|
7682
|
+
const mirrorIneffective = channel.kind === "mirror" && downloadUrl === asset.browser_download_url;
|
|
7646
7683
|
if (mirrorIneffective) {
|
|
7647
7684
|
console.warn("\u8B66\u544A: \u955C\u50CF\u524D\u7F00\u672A\u80FD\u4F5C\u7528\u4E8E\u8BE5\u8D44\u4EA7\u5730\u5740\uFF08host \u975E github.com\uFF09\uFF0C\u672C\u6B21\u4E3A\u76F4\u8FDE\u4E0B\u8F7D\uFF1B\u82E5\u76F4\u8FDE\u8D85\u65F6\u53EF\u6539\u7528 gh \u901A\u9053\uFF08mihomo-cli kernel\uFF09");
|
|
7648
7685
|
}
|
|
@@ -7727,20 +7764,16 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7727
7764
|
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
7728
7765
|
}
|
|
7729
7766
|
fs15.chmodSync(foundBinary, 493);
|
|
7730
|
-
const
|
|
7731
|
-
|
|
7732
|
-
if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
|
|
7767
|
+
const probe = probeKernelVersion(foundBinary);
|
|
7768
|
+
if (probe.spawnError || probe.status !== 0 || probe.version === null) {
|
|
7733
7769
|
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
|
|
7734
|
-
\u9000\u51FA\u7801: ${
|
|
7735
|
-
\u8F93\u51FA: ${
|
|
7736
|
-
}
|
|
7737
|
-
const
|
|
7738
|
-
|
|
7739
|
-
|
|
7740
|
-
|
|
7741
|
-
if (binaryVersion !== expectedVersion) {
|
|
7742
|
-
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`);
|
|
7743
|
-
}
|
|
7770
|
+
\u9000\u51FA\u7801: ${probe.status}
|
|
7771
|
+
\u8F93\u51FA: ${probe.output || "(\u7A7A)"}`);
|
|
7772
|
+
}
|
|
7773
|
+
const binaryVersion = probe.version.replace(/^v/, "");
|
|
7774
|
+
const expectedVersion = latest.tag_name.replace(/^v/, "");
|
|
7775
|
+
if (binaryVersion !== expectedVersion) {
|
|
7776
|
+
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`);
|
|
7744
7777
|
}
|
|
7745
7778
|
const targetPath = PATHS.mihomoBinary;
|
|
7746
7779
|
fs15.renameSync(foundBinary, targetPath);
|
|
@@ -7872,12 +7905,7 @@ function withAbortableTimeout(promise, ms) {
|
|
|
7872
7905
|
return promise(controller.signal).finally(() => clearTimeout(timer));
|
|
7873
7906
|
}
|
|
7874
7907
|
function isPortListening(port) {
|
|
7875
|
-
|
|
7876
|
-
const r = spawnSync10("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
|
|
7877
|
-
return r.status === 0 && (r.stdout || "").trim().length > 0;
|
|
7878
|
-
} catch {
|
|
7879
|
-
return false;
|
|
7880
|
-
}
|
|
7908
|
+
return (lsofListenPids(port)?.length ?? 0) > 0;
|
|
7881
7909
|
}
|
|
7882
7910
|
async function collectChecks() {
|
|
7883
7911
|
const checks = [];
|
|
@@ -7885,33 +7913,35 @@ async function collectChecks() {
|
|
|
7885
7913
|
checks.push({ name, status, detail, fix, notes });
|
|
7886
7914
|
};
|
|
7887
7915
|
const latestVersionPromise = getLatestNpmVersion(4e3).catch(() => null);
|
|
7888
|
-
const
|
|
7889
|
-
|
|
7890
|
-
|
|
7891
|
-
|
|
7892
|
-
|
|
7893
|
-
|
|
7894
|
-
|
|
7895
|
-
|
|
7916
|
+
const earlyService = getServiceStatus();
|
|
7917
|
+
const earlyState = getRunningState(earlyService);
|
|
7918
|
+
const kernelProxyPort = earlyState.running ? getPortsOrNull()?.mixed ?? null : null;
|
|
7919
|
+
const kernelProbe = hasKernel() ? probeKernelVersion() : null;
|
|
7920
|
+
const releaseQuery = resolveReleaseQuery({
|
|
7921
|
+
mirror: null,
|
|
7922
|
+
isOverride: false,
|
|
7923
|
+
ghAvailable: kernelProxyPort === null && hasGh(),
|
|
7924
|
+
proxyRunning: earlyState.running,
|
|
7925
|
+
proxyPort: kernelProxyPort,
|
|
7926
|
+
proxyOverride: null
|
|
7927
|
+
});
|
|
7928
|
+
const kernelVersionPromise = kernelProbe ? withAbortableTimeout(
|
|
7896
7929
|
(signal) => checkUpdate({
|
|
7897
|
-
proxy:
|
|
7898
|
-
useGh:
|
|
7899
|
-
signal
|
|
7930
|
+
proxy: releaseQuery.proxy,
|
|
7931
|
+
useGh: releaseQuery.useGh,
|
|
7932
|
+
signal,
|
|
7933
|
+
currentVersion: getKernelVersion(kernelProbe)
|
|
7900
7934
|
}),
|
|
7901
7935
|
4e3
|
|
7902
7936
|
).catch(() => null) : Promise.resolve(null);
|
|
7903
|
-
if (!
|
|
7937
|
+
if (!kernelProbe) {
|
|
7904
7938
|
push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo-cli kernel");
|
|
7939
|
+
} else if (kernelProbe.status === 0 && kernelProbe.version !== null) {
|
|
7940
|
+
push("\u5185\u6838", "ok", getKernelVersion(kernelProbe) || "\u53EF\u6267\u884C");
|
|
7941
|
+
} else if (kernelProbe.spawnError) {
|
|
7942
|
+
push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08${kernelProbe.spawnError.message}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
|
|
7905
7943
|
} else {
|
|
7906
|
-
|
|
7907
|
-
const r = spawnSync10(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
7908
|
-
if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
|
|
7909
|
-
push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
|
|
7910
|
-
} else if (r.error) {
|
|
7911
|
-
push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08${r.error.message}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
|
|
7912
|
-
} else {
|
|
7913
|
-
push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${r.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
|
|
7914
|
-
}
|
|
7944
|
+
push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${kernelProbe.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
|
|
7915
7945
|
}
|
|
7916
7946
|
if (fs16.existsSync(KERNEL_SELF_UPDATE_DIR)) {
|
|
7917
7947
|
push("\u5185\u6838\u81EA\u5347\u7EA7\u6B8B\u7559", "warn", `\u4E2D\u65AD\u7684\u4E0B\u8F7D\u6682\u5B58: ${KERNEL_SELF_UPDATE_DIR}`, `rm -rf ${KERNEL_SELF_UPDATE_DIR}`);
|
|
@@ -7941,18 +7971,12 @@ async function collectChecks() {
|
|
|
7941
7971
|
} else {
|
|
7942
7972
|
push("\u8BA2\u9605", "ok", `${subs.length} \u4E2A${active ? `\uFF0C\u5F53\u524D: ${active.name}` : ""}`);
|
|
7943
7973
|
if (active) {
|
|
7944
|
-
let rawConfig;
|
|
7945
7974
|
try {
|
|
7946
|
-
|
|
7947
|
-
} catch (e) {
|
|
7948
|
-
rawConfig = e;
|
|
7949
|
-
}
|
|
7950
|
-
if (rawConfig instanceof Error) {
|
|
7951
|
-
push("\u8BA2\u9605\u914D\u7F6E", "fail", `${rawConfig.message}`, "\u624B\u5DE5\u4FEE\u6B63 settings.json \u4E2D\u7684\u8BA2\u9605\u540D\u540E\u91CD\u8BD5");
|
|
7952
|
-
} else if (!rawConfig) {
|
|
7953
|
-
push("\u8BA2\u9605\u914D\u7F6E", "fail", `\u5F53\u524D\u8BA2\u9605 "${active.name}" \u6709\u6761\u76EE\u4F46\u65E0\u914D\u7F6E\u6587\u4EF6`, `mihomo-cli sub update ${active.name}`);
|
|
7954
|
-
} else {
|
|
7975
|
+
requireSubscriptionRawConfig(active.name);
|
|
7955
7976
|
push("\u8BA2\u9605\u914D\u7F6E", "ok", `"${active.name}" \u914D\u7F6E\u6587\u4EF6\u5B58\u5728`);
|
|
7977
|
+
} catch (e) {
|
|
7978
|
+
const err = e;
|
|
7979
|
+
push("\u8BA2\u9605\u914D\u7F6E", "fail", err.message, err.hint[0] ?? "\u624B\u5DE5\u4FEE\u6B63 settings.json \u4E2D\u7684\u8BA2\u9605\u540D\u540E\u91CD\u8BD5");
|
|
7956
7980
|
}
|
|
7957
7981
|
const cached = subs.find((s) => s.name === active.name);
|
|
7958
7982
|
if (cached?.updated_at) {
|
|
@@ -7965,30 +7989,29 @@ async function collectChecks() {
|
|
|
7965
7989
|
}
|
|
7966
7990
|
}
|
|
7967
7991
|
}
|
|
7968
|
-
const service = getServiceStatus();
|
|
7969
7992
|
const legacy = detectLegacySystemInstall();
|
|
7970
7993
|
if (legacy) {
|
|
7971
7994
|
push("\u670D\u52A1", "fail", "\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u4F1A\u62A2\u5360\u7AEF\u53E3", "mihomo-cli uninstall\uFF08\u9700\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09");
|
|
7972
|
-
} else if (!
|
|
7995
|
+
} else if (!earlyService.installed && !earlyService.loaded) {
|
|
7973
7996
|
push("\u670D\u52A1", "warn", "\u672A\u5B89\u88C5\uFF08Mixed \u6A21\u5F0F\u9700\u8981\uFF09", "mihomo-cli install");
|
|
7974
|
-
} else if (!
|
|
7997
|
+
} else if (!earlyService.installed) {
|
|
7975
7998
|
push("\u670D\u52A1", "fail", "plist \u4E0D\u5B58\u5728\u4F46\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF0CKeepAlive \u4F1A\u6301\u7EED\u62C9\u8D77\u5185\u6838", "mihomo-cli uninstall");
|
|
7976
|
-
} else if (
|
|
7977
|
-
const abnormalExit = describeAbnormalExit(
|
|
7978
|
-
push("\u670D\u52A1", "ok", `\u8FD0\u884C\u4E2D${
|
|
7999
|
+
} else if (earlyService.running) {
|
|
8000
|
+
const abnormalExit = describeAbnormalExit(earlyService);
|
|
8001
|
+
push("\u670D\u52A1", "ok", `\u8FD0\u884C\u4E2D${earlyService.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}${abnormalExit ? `\uFF0C\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09` : ""}`);
|
|
7979
8002
|
if (abnormalExit) {
|
|
7980
8003
|
push("\u670D\u52A1\u7A33\u5B9A\u6027", "warn", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09`, "mihomo-cli logs 0 \u67E5\u770B\u539F\u56E0");
|
|
7981
8004
|
}
|
|
7982
8005
|
} else {
|
|
7983
|
-
const abnormalExit = describeAbnormalExit(
|
|
7984
|
-
if (!
|
|
8006
|
+
const abnormalExit = describeAbnormalExit(earlyService);
|
|
8007
|
+
if (!earlyService.disabled && abnormalExit) {
|
|
7985
8008
|
push("\u670D\u52A1", "fail", `\u5185\u6838\u4E0A\u6B21\u5F02\u5E38\u9000\u51FA\uFF08${abnormalExit}\uFF09\uFF0Claunchd \u6B63\u5728\u53CD\u590D\u62C9\u8D77`, "mihomo-cli logs 0 \u67E5\u770B\u539F\u56E0\uFF0Cmihomo-cli stop \u505C\u6B62\u91CD\u8BD5");
|
|
7986
8009
|
} else {
|
|
7987
|
-
push("\u670D\u52A1", "ok", `\u5DF2\u5B89\u88C5\uFF0C\u672A\u8FD0\u884C${
|
|
8010
|
+
push("\u670D\u52A1", "ok", `\u5DF2\u5B89\u88C5\uFF0C\u672A\u8FD0\u884C${earlyService.disabled ? "\uFF08\u81EA\u542F\u5DF2\u5173\u95ED\uFF09" : ""}`);
|
|
7988
8011
|
}
|
|
7989
8012
|
}
|
|
7990
|
-
const state = getRunningState();
|
|
7991
8013
|
const info = getConfigInfo();
|
|
8014
|
+
const connectivityPromise = earlyState.running && info?.mixedPort ? probeProxyConnectivity(info.mixedPort) : null;
|
|
7992
8015
|
let mixedPortDefault = DEFAULT_MIXED_PORT;
|
|
7993
8016
|
try {
|
|
7994
8017
|
const ports = getPorts();
|
|
@@ -7997,7 +8020,7 @@ async function collectChecks() {
|
|
|
7997
8020
|
push("\u7AEF\u53E3\u914D\u7F6E", "fail", e.message, "\u4FEE\u6B63 settings.json \u7684 ports\uFF081-65535 \u6574\u6570\uFF0Cmixed \u4E0E controller \u4E0D\u80FD\u76F8\u540C\uFF09");
|
|
7998
8021
|
}
|
|
7999
8022
|
const mixedPort = info?.mixedPort ?? mixedPortDefault;
|
|
8000
|
-
if (
|
|
8023
|
+
if (earlyState.running) {
|
|
8001
8024
|
if (isPortListening(mixedPort)) {
|
|
8002
8025
|
push("\u7AEF\u53E3", "ok", `${mixedPort} \u6B63\u5728\u76D1\u542C`);
|
|
8003
8026
|
} else {
|
|
@@ -8010,7 +8033,7 @@ async function collectChecks() {
|
|
|
8010
8033
|
}
|
|
8011
8034
|
if (active && hasKernel()) {
|
|
8012
8035
|
try {
|
|
8013
|
-
const mode = info
|
|
8036
|
+
const mode = deriveRuntimeMode(info);
|
|
8014
8037
|
const prepared = await prepareConfigForStart(mode, active.name);
|
|
8015
8038
|
const warnings = prepared.buildResult.warnings;
|
|
8016
8039
|
if (warnings.length > 0) {
|
|
@@ -8031,8 +8054,8 @@ async function collectChecks() {
|
|
|
8031
8054
|
} else {
|
|
8032
8055
|
push("\u914D\u7F6E\u6784\u5EFA", "skip", active ? "\u672A\u5B89\u88C5\u5185\u6838\uFF0C\u8DF3\u8FC7\u6821\u9A8C" : "\u65E0\u8BA2\u9605\uFF0C\u8DF3\u8FC7");
|
|
8033
8056
|
}
|
|
8034
|
-
if (
|
|
8035
|
-
const probe = await
|
|
8057
|
+
if (connectivityPromise) {
|
|
8058
|
+
const probe = await connectivityPromise;
|
|
8036
8059
|
if (probe.ok) {
|
|
8037
8060
|
push("\u4EE3\u7406\u8FDE\u901A", "ok", `HTTP ${probe.statusCode}\uFF08${probe.durationMs}ms\uFF09`);
|
|
8038
8061
|
} else {
|
|
@@ -8094,13 +8117,14 @@ async function cmdDoctor(args = []) {
|
|
|
8094
8117
|
}
|
|
8095
8118
|
|
|
8096
8119
|
// src/kernel-args.ts
|
|
8120
|
+
var SCHEME_PREFIX_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//;
|
|
8097
8121
|
var KERNEL_FLAG_WHITELIST = ["--mirror", "--proxy", "-p"];
|
|
8098
8122
|
function normalizeMirrorUrl(val) {
|
|
8099
8123
|
if (!val) return null;
|
|
8100
8124
|
if (val === "direct") return null;
|
|
8101
8125
|
const alias = MIRROR_ALIASES[val.toLowerCase()];
|
|
8102
8126
|
if (alias) return alias;
|
|
8103
|
-
if (
|
|
8127
|
+
if (!SCHEME_PREFIX_RE.test(val) && !val.includes(".") && !val.includes(":")) {
|
|
8104
8128
|
const suggestions = suggestSimilar(val, [...Object.keys(MIRROR_ALIASES), "direct"]);
|
|
8105
8129
|
throw new CliError(`\u672A\u77E5\u7684\u955C\u50CF\u522B\u540D: "${val}"`, {
|
|
8106
8130
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
@@ -8112,7 +8136,7 @@ function normalizeMirrorUrl(val) {
|
|
|
8112
8136
|
]
|
|
8113
8137
|
});
|
|
8114
8138
|
}
|
|
8115
|
-
const withScheme =
|
|
8139
|
+
const withScheme = SCHEME_PREFIX_RE.test(val) ? val : `https://${val}`;
|
|
8116
8140
|
let parsed;
|
|
8117
8141
|
try {
|
|
8118
8142
|
parsed = new URL(withScheme);
|
|
@@ -8136,42 +8160,43 @@ function parseMirrorArg(args) {
|
|
|
8136
8160
|
return { mirror: null, isOverride: false };
|
|
8137
8161
|
}
|
|
8138
8162
|
assertKnownFlags(args.slice(1), KERNEL_FLAG_WHITELIST, "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]");
|
|
8139
|
-
const
|
|
8140
|
-
|
|
8163
|
+
const hits = [];
|
|
8164
|
+
for (let i = 0; i < args.length; i++) {
|
|
8165
|
+
const match = matchValueFlagToken(args[i]);
|
|
8166
|
+
if (!match?.spec.forms.includes("--mirror")) continue;
|
|
8167
|
+
hits.push({ value: match.form === "exact" ? args[i + 1] ?? null : match.inlineValue });
|
|
8168
|
+
}
|
|
8169
|
+
if (hits.length === 0) {
|
|
8170
|
+
return { mirror: null, isOverride: false };
|
|
8171
|
+
}
|
|
8172
|
+
if (hits.length > 1) {
|
|
8141
8173
|
throw new CliError("--mirror \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21", {
|
|
8142
8174
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
8143
8175
|
hint: ["\u7528\u6CD5: mihomo-cli kernel [--mirror [\u955C\u50CF]]", `\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`, "\u4E0D\u4F7F\u7528\u955C\u50CF: mihomo-cli kernel --mirror direct"]
|
|
8144
8176
|
});
|
|
8145
8177
|
}
|
|
8146
|
-
const
|
|
8147
|
-
|
|
8148
|
-
|
|
8149
|
-
|
|
8150
|
-
|
|
8151
|
-
|
|
8152
|
-
|
|
8153
|
-
|
|
8154
|
-
|
|
8155
|
-
}
|
|
8156
|
-
const nextArg = inline ?? args[mirrorIdx + 1];
|
|
8157
|
-
if (!nextArg || nextArg.startsWith("-")) {
|
|
8158
|
-
return { mirror: MIRROR_BARE, isOverride: true };
|
|
8159
|
-
}
|
|
8160
|
-
const normalized = normalizeMirrorUrl(nextArg);
|
|
8161
|
-
return { mirror: normalized, isOverride: true };
|
|
8178
|
+
const value = hits[0].value;
|
|
8179
|
+
if (value === "") {
|
|
8180
|
+
throw new CliError("--mirror \u7684\u503C\u4E0D\u80FD\u4E3A\u7A7A\uFF08\u5355\u72EC\u7684 --mirror \u8868\u793A\u4F7F\u7528\u9ED8\u8BA4\u955C\u50CF\u57DF\uFF09", {
|
|
8181
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
8182
|
+
hint: ["\u7528\u6CD5: mihomo-cli kernel [--mirror [\u955C\u50CF]]", `\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`, "\u4E0D\u4F7F\u7528\u955C\u50CF: mihomo-cli kernel --mirror direct"]
|
|
8183
|
+
});
|
|
8184
|
+
}
|
|
8185
|
+
if (value === null || value.startsWith("-")) {
|
|
8186
|
+
return { mirror: MIRROR_BARE, isOverride: true };
|
|
8162
8187
|
}
|
|
8163
|
-
return { mirror:
|
|
8188
|
+
return { mirror: normalizeMirrorUrl(value), isOverride: true };
|
|
8164
8189
|
}
|
|
8165
8190
|
var PROXY_SCHEMES = /* @__PURE__ */ new Set(["http:", "https:", "socks5:", "socks5h:"]);
|
|
8166
8191
|
function normalizeProxyUrl(val) {
|
|
8167
8192
|
if (/^\d+$/.test(val)) {
|
|
8168
8193
|
const port = Number(val);
|
|
8169
|
-
if (!
|
|
8194
|
+
if (!isValidPortNumber(port)) {
|
|
8170
8195
|
throw new CliError(`\u4EE3\u7406\u7AEF\u53E3\u65E0\u6548: "${val}"`, { label: "\u53C2\u6570\u9519\u8BEF", hint: ["\u7AEF\u53E3\u8303\u56F4 1-65535\uFF0C\u4F8B\u5982: --proxy 7897"] });
|
|
8171
8196
|
}
|
|
8172
8197
|
return `http://127.0.0.1:${port}`;
|
|
8173
8198
|
}
|
|
8174
|
-
const withScheme =
|
|
8199
|
+
const withScheme = SCHEME_PREFIX_RE.test(val) ? val : `http://${val}`;
|
|
8175
8200
|
let parsed;
|
|
8176
8201
|
try {
|
|
8177
8202
|
parsed = new URL(withScheme);
|
|
@@ -8187,7 +8212,7 @@ function normalizeProxyUrl(val) {
|
|
|
8187
8212
|
if (!parsed.hostname) {
|
|
8188
8213
|
throw new CliError(`\u4EE3\u7406\u5730\u5740\u65E0\u6548: "${val}"\uFF08\u7F3A\u5C11\u4E3B\u673A\u540D\uFF09`, { label: "\u53C2\u6570\u9519\u8BEF", hint: ["\u4F8B\u5982: --proxy 127.0.0.1:7897"] });
|
|
8189
8214
|
}
|
|
8190
|
-
const authority = withScheme.replace(
|
|
8215
|
+
const authority = withScheme.replace(SCHEME_PREFIX_RE, "").split(/[/?#]/)[0];
|
|
8191
8216
|
if (!/:\d+$/.test(authority)) {
|
|
8192
8217
|
throw new CliError(`\u4EE3\u7406\u5730\u5740\u9700\u8981\u7AEF\u53E3: "${val}"`, { label: "\u53C2\u6570\u9519\u8BEF", hint: ["\u4F8B\u5982: --proxy 127.0.0.1:7897"] });
|
|
8193
8218
|
}
|
|
@@ -8229,7 +8254,6 @@ function parseProxyArg(args) {
|
|
|
8229
8254
|
}
|
|
8230
8255
|
|
|
8231
8256
|
// src/commands/kernel.ts
|
|
8232
|
-
var KERNEL_VALUE_FLAGS = /* @__PURE__ */ new Set([...VALUE_FLAGS, "--mirror"]);
|
|
8233
8257
|
function channelLabel(channel, isExplicitProxy) {
|
|
8234
8258
|
switch (channel.kind) {
|
|
8235
8259
|
case "gh":
|
|
@@ -8290,7 +8314,7 @@ function buildDownloadFailureError(attempts, isExplicitProxy) {
|
|
|
8290
8314
|
async function cmdKernel(args) {
|
|
8291
8315
|
const mirrorInfo = parseMirrorArg(args);
|
|
8292
8316
|
const proxyInfo = parseProxyArg(args);
|
|
8293
|
-
assertPositionalCount(args, 0, 1, "mihomo-cli kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]"
|
|
8317
|
+
assertPositionalCount(args, 0, 1, "mihomo-cli kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]");
|
|
8294
8318
|
if (proxyInfo.proxy && mirrorInfo.isOverride && !mirrorInfo.mirror) {
|
|
8295
8319
|
throw new CliError("--mirror direct \u4E0E --proxy \u4E0D\u80FD\u540C\u65F6\u4F7F\u7528", {
|
|
8296
8320
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
@@ -8298,27 +8322,20 @@ async function cmdKernel(args) {
|
|
|
8298
8322
|
});
|
|
8299
8323
|
}
|
|
8300
8324
|
const proxyRunning = getRunningState().running;
|
|
8301
|
-
|
|
8302
|
-
if (proxyRunning) {
|
|
8303
|
-
try {
|
|
8304
|
-
proxyPort = getPorts().mixed;
|
|
8305
|
-
} catch {
|
|
8306
|
-
proxyPort = null;
|
|
8307
|
-
}
|
|
8308
|
-
}
|
|
8325
|
+
const proxyPort = proxyRunning ? getPortsOrNull()?.mixed ?? null : null;
|
|
8309
8326
|
const forceDirect = mirrorInfo.isOverride && !mirrorInfo.mirror;
|
|
8310
8327
|
const ghAvailable = ghProbeNeeded({ forceDirect, proxyOverride: proxyInfo.proxy }) && hasGh();
|
|
8311
|
-
const
|
|
8328
|
+
const channelInput = {
|
|
8312
8329
|
mirror: mirrorInfo.mirror,
|
|
8313
8330
|
isOverride: mirrorInfo.isOverride,
|
|
8314
8331
|
ghAvailable,
|
|
8315
8332
|
proxyRunning,
|
|
8316
8333
|
proxyPort,
|
|
8317
8334
|
proxyOverride: proxyInfo.proxy
|
|
8318
|
-
}
|
|
8335
|
+
};
|
|
8336
|
+
const channels = resolveDownloadChannels(channelInput);
|
|
8319
8337
|
printChannelLine(channels[0], proxyInfo.proxy !== null);
|
|
8320
|
-
const
|
|
8321
|
-
const useGh = apiProxy === null && !forceDirect && ghAvailable;
|
|
8338
|
+
const { proxy: apiProxy, useGh } = resolveReleaseQuery(channelInput);
|
|
8322
8339
|
let info;
|
|
8323
8340
|
try {
|
|
8324
8341
|
const spinnerText = apiProxy ? `\u68C0\u67E5\u5185\u6838\u66F4\u65B0\uFF08\u7ECF\u4EE3\u7406 ${apiProxy}\uFF09` : useGh ? "\u68C0\u67E5\u5185\u6838\u66F4\u65B0\uFF08gh \u8BA4\u8BC1\u901A\u9053\uFF09" : "\u68C0\u67E5\u5185\u6838\u66F4\u65B0\uFF08GitHub \u76F4\u8FDE\uFF0C\u56FD\u5185\u7F51\u7EDC\u53EF\u80FD\u8F83\u6162\uFF09";
|
|
@@ -8466,7 +8483,7 @@ function cmdLogs(args) {
|
|
|
8466
8483
|
num = " 0";
|
|
8467
8484
|
} else {
|
|
8468
8485
|
archiveCounter++;
|
|
8469
|
-
num = archiveCounter
|
|
8486
|
+
num = String(archiveCounter).padStart(2);
|
|
8470
8487
|
}
|
|
8471
8488
|
const time = formatDate(log.mtime);
|
|
8472
8489
|
const size = formatBytes(log.size);
|
|
@@ -8505,14 +8522,14 @@ function printOverwriteList() {
|
|
|
8505
8522
|
console.log("");
|
|
8506
8523
|
info.files.forEach((f, i) => {
|
|
8507
8524
|
const seq = i + 1;
|
|
8508
|
-
const num = seq
|
|
8525
|
+
const num = String(seq).padStart(2);
|
|
8509
8526
|
const mark = f.enabled ? "" : ` ${colors.yellow("[\u5DF2\u7981\u7528]")}`;
|
|
8510
8527
|
console.log(` ${num}. ${f.name}${mark}`);
|
|
8511
8528
|
if (f.scope) {
|
|
8512
8529
|
console.log(` ${colors.gray("\u4F5C\u7528\u57DF: ")}${f.scope}`);
|
|
8513
8530
|
}
|
|
8514
8531
|
if (f.kind === "script") {
|
|
8515
|
-
console.log(` ${colors.gray("\u7C7B\u578B: ")}JS \u811A\u672C\uFF08\u5728\u5168\u90E8 YAML \u8986\u5199\u4E4B\u524D\u6267\u884C\uFF09`);
|
|
8532
|
+
console.log(` ${colors.gray("\u7C7B\u578B: ")}JS \u811A\u672C\uFF08\u5728\u5168\u90E8 YAML \u8986\u5199\u4E4B\u524D\u6267\u884C\uFF1B\u9002\u7528\u4E8E\u5F53\u524D\u8BA2\u9605\u65F6\u672B\u5C3E return true\uFF0Cstatus \u636E\u6B64\u533A\u5206\u751F\u6548\u4E0E\u4E0D\u9002\u7528\uFF09`);
|
|
8516
8533
|
} else if (f.keys.length > 0) {
|
|
8517
8534
|
console.log(` ${colors.gray("\u5B57\u6BB5: ")}${f.keys.join(", ")}`);
|
|
8518
8535
|
}
|
|
@@ -8521,7 +8538,7 @@ function printOverwriteList() {
|
|
|
8521
8538
|
console.log(colors.red(`\u52A0\u8F7D\u5931\u8D25 (${info.broken.length} \u4E2A\uFF0C\u672A\u53C2\u4E0E\u5408\u5E76\uFF1Bstart/doctor \u4F1A\u62A5\u9519):`));
|
|
8522
8539
|
info.broken.forEach((b, i) => {
|
|
8523
8540
|
const seq = info.files.length + i + 1;
|
|
8524
|
-
const num = seq
|
|
8541
|
+
const num = String(seq).padStart(2);
|
|
8525
8542
|
console.log(` ${num}. ${colors.red(b.name)} ${colors.red("[\u52A0\u8F7D\u5931\u8D25]")}`);
|
|
8526
8543
|
console.log(colors.red(` ${b.message}`));
|
|
8527
8544
|
for (const line of b.hint) console.log(colors.gray(` ${line}`));
|
|
@@ -8556,24 +8573,17 @@ var SUBCOMMANDS2 = [
|
|
|
8556
8573
|
async function cmdOverwrite(args) {
|
|
8557
8574
|
assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "ow [on|off]");
|
|
8558
8575
|
await dispatchSubcommand(args, SUBCOMMANDS2, {
|
|
8559
|
-
// 无子命令 → 列表;未知子命令 →
|
|
8576
|
+
// 无子命令 → 列表;未知子命令 → 报错(守卫与 did-you-mean 拼装收口在 shared)
|
|
8560
8577
|
fallback: () => {
|
|
8561
8578
|
console.log("");
|
|
8562
8579
|
printOverwriteList();
|
|
8563
8580
|
},
|
|
8564
|
-
onUnknown: (action) => {
|
|
8565
|
-
|
|
8566
|
-
|
|
8567
|
-
|
|
8568
|
-
|
|
8569
|
-
|
|
8570
|
-
}
|
|
8571
|
-
const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
8572
|
-
const suggestion = suggestSimilar(action, names);
|
|
8573
|
-
throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
|
|
8574
|
-
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
|
|
8575
|
-
});
|
|
8576
|
-
}
|
|
8581
|
+
onUnknown: (action) => unknownSubcommandError(action, SUBCOMMANDS2, {
|
|
8582
|
+
what: "\u8986\u5199\u5B50\u547D\u4EE4",
|
|
8583
|
+
// 重启透传选项必须跟在 on/off 后,裸 ow 不消费任何选项
|
|
8584
|
+
optionHint: ["\u88F8 ow \u53EA\u67E5\u770B\u8986\u5199\u72B6\u6001\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo-cli ow on|off [-s] [-u ms]"],
|
|
8585
|
+
unknownHint: ["", "\u53EF\u7528\u5B50\u547D\u4EE4: on, off"]
|
|
8586
|
+
})
|
|
8577
8587
|
});
|
|
8578
8588
|
}
|
|
8579
8589
|
|
|
@@ -8665,24 +8675,22 @@ async function cmdReset(args) {
|
|
|
8665
8675
|
if ((needsStop || serviceTargeted) && legacy) await cleanupLegacyInstallOrThrow();
|
|
8666
8676
|
const current = getServiceStatus();
|
|
8667
8677
|
serviceActive = current.installed || current.loaded;
|
|
8678
|
+
let cleanup = null;
|
|
8668
8679
|
if (serviceActive) {
|
|
8669
|
-
if (serviceTargeted) await uninstallService();
|
|
8670
|
-
else if (needsStop) await stopService();
|
|
8680
|
+
if (serviceTargeted) cleanup = await uninstallService();
|
|
8681
|
+
else if (needsStop) cleanup = await stopService();
|
|
8682
|
+
} else if (needsStop) {
|
|
8683
|
+
cleanup = await cleanupAll();
|
|
8671
8684
|
}
|
|
8672
|
-
if (needsStop) {
|
|
8673
|
-
const cleanup = await cleanupAll();
|
|
8685
|
+
if (needsStop && cleanup !== null) {
|
|
8674
8686
|
if (cleanup.remaining.length > 0) {
|
|
8675
8687
|
throw new CliError(cleanup.remaining.join(", "), {
|
|
8676
8688
|
label: "\u8FDB\u7A0B\u672A\u80FD\u505C\u6B62\uFF0C\u91CD\u7F6E\u4E2D\u6B62",
|
|
8677
|
-
hint: [
|
|
8689
|
+
hint: [MANUAL_PKILL_HINT]
|
|
8678
8690
|
});
|
|
8679
8691
|
}
|
|
8680
|
-
if (
|
|
8681
|
-
|
|
8682
|
-
if (reason) {
|
|
8683
|
-
console.warn(colors.yellow(`\u8B66\u544A: ${reason}`));
|
|
8684
|
-
console.warn(colors.gray("\u91CD\u8BD5\u6E05\u7406: mihomo-cli stop"));
|
|
8685
|
-
}
|
|
8692
|
+
if (!serviceActive && (cleanup.scriptError !== null || cleanup.pidError !== null)) {
|
|
8693
|
+
warnResidueCleanup(cleanup, { mainOutcome: "\u91CD\u7F6E\u7EE7\u7EED\u6267\u884C", retryCommand: "mihomo-cli stop" });
|
|
8686
8694
|
}
|
|
8687
8695
|
recordServiceStopped();
|
|
8688
8696
|
}
|
|
@@ -8731,13 +8739,7 @@ async function cmdReset(args) {
|
|
|
8731
8739
|
import fs18 from "fs";
|
|
8732
8740
|
async function handleLegacyInstall() {
|
|
8733
8741
|
if (!detectLegacySystemInstall()) return;
|
|
8734
|
-
|
|
8735
|
-
console.log(colors.gray(" \u5B83\u4F1A\u4E0E\u65B0\u7684\u7528\u6237\u7EA7\u670D\u52A1\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\uFF0C\u9700\u5148\u6E05\u7406"));
|
|
8736
|
-
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"));
|
|
8737
|
-
console.log("");
|
|
8738
|
-
await cleanupLegacyInstallOrThrow();
|
|
8739
|
-
console.log(`${colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1")}`);
|
|
8740
|
-
console.log("");
|
|
8742
|
+
await announceLegacyCleanupOrThrow("\u9700\u5148\u6E05\u7406", [" \u5B83\u4F1A\u4E0E\u65B0\u7684\u7528\u6237\u7EA7\u670D\u52A1\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3"]);
|
|
8741
8743
|
}
|
|
8742
8744
|
function printRestoreSkipped() {
|
|
8743
8745
|
console.log(colors.yellow("\u672A\u6062\u590D\u8FD0\u884C\uFF1A\u5B89\u88C5\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C"));
|
|
@@ -8748,9 +8750,7 @@ function printRestoreSkipped() {
|
|
|
8748
8750
|
async function cmdInstall(args) {
|
|
8749
8751
|
assertKnownFlags(args.slice(1), [], "install");
|
|
8750
8752
|
assertPositionalCount(args, 0, 1, "mihomo-cli install");
|
|
8751
|
-
|
|
8752
|
-
throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo-cli kernel" });
|
|
8753
|
-
}
|
|
8753
|
+
assertKernelInstalled();
|
|
8754
8754
|
await handleLegacyInstall();
|
|
8755
8755
|
const wasRunning = getServiceStatus().running;
|
|
8756
8756
|
const { restoreSkipped } = await installService(wasRunning);
|
|
@@ -8767,7 +8767,7 @@ async function cmdInstall(args) {
|
|
|
8767
8767
|
await assertServiceHealthy("\u6062\u590D\u8FD0\u884C\u5931\u8D25");
|
|
8768
8768
|
} catch (e) {
|
|
8769
8769
|
if (!(e instanceof CliError)) throw e;
|
|
8770
|
-
if (
|
|
8770
|
+
if (startAbortedByConcurrentStop()) {
|
|
8771
8771
|
printRestoreSkipped();
|
|
8772
8772
|
return;
|
|
8773
8773
|
}
|
|
@@ -8799,20 +8799,21 @@ async function cmdUninstall(args) {
|
|
|
8799
8799
|
console.log(colors.yellow("\u672A\u627E\u5230 plist\uFF0C\u4F46\u670D\u52A1\u4ECD\u5904\u88C5\u8F7D\u72B6\u6001\uFF08plist \u53EF\u80FD\u88AB\u624B\u52A8\u5220\u9664\uFF09"));
|
|
8800
8800
|
console.log("\u5C06\u6267\u884C launchctl bootout \u5378\u8F7D\u6B8B\u7559\u4EFB\u52A1");
|
|
8801
8801
|
}
|
|
8802
|
+
let remaining = null;
|
|
8802
8803
|
if (status.installed || status.loaded) {
|
|
8803
|
-
await uninstallService();
|
|
8804
|
+
const cleanup = await uninstallService();
|
|
8804
8805
|
console.log(colors.green("\u5DF2\u5378\u8F7D\u670D\u52A1"));
|
|
8806
|
+
remaining = cleanup.remaining;
|
|
8805
8807
|
}
|
|
8806
8808
|
if (legacy) {
|
|
8807
|
-
|
|
8808
|
-
|
|
8809
|
-
console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
|
|
8809
|
+
await announceLegacyCleanupOrThrow("\u5378\u8F7D\u65F6\u4E00\u5E76\u6E05\u7406");
|
|
8810
|
+
remaining = null;
|
|
8810
8811
|
}
|
|
8811
|
-
|
|
8812
|
+
if (remaining === null) remaining = getMihomoPids();
|
|
8812
8813
|
if (remaining.length > 0) {
|
|
8813
8814
|
console.log("");
|
|
8814
8815
|
console.log(colors.yellow(`\u4ECD\u6709\u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${remaining.join(", ")})`));
|
|
8815
|
-
console.log(
|
|
8816
|
+
console.log(MANUAL_PKILL_HINT);
|
|
8816
8817
|
}
|
|
8817
8818
|
console.log(colors.gray("\u91CD\u65B0\u5B89\u88C5: mihomo-cli install"));
|
|
8818
8819
|
console.log(colors.gray("\u5F7B\u5E95\u79FB\u9664 mihomo-cli:"));
|
|
@@ -8824,18 +8825,14 @@ async function cmdUninstall(args) {
|
|
|
8824
8825
|
// src/commands/stop.ts
|
|
8825
8826
|
function handleStopResult(result) {
|
|
8826
8827
|
if (result.remaining && result.remaining.length > 0) {
|
|
8827
|
-
throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint:
|
|
8828
|
+
throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint: MANUAL_PKILL_HINT });
|
|
8828
8829
|
}
|
|
8829
8830
|
}
|
|
8830
8831
|
async function cmdStop(args) {
|
|
8831
8832
|
assertKnownFlags(args.slice(1), [], "stop");
|
|
8832
8833
|
assertPositionalCount(args, 0, 1, "mihomo-cli stop");
|
|
8833
8834
|
if (detectLegacySystemInstall()) {
|
|
8834
|
-
|
|
8835
|
-
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"));
|
|
8836
|
-
await cleanupLegacyInstallOrThrow();
|
|
8837
|
-
console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
|
|
8838
|
-
console.log("");
|
|
8835
|
+
await announceLegacyCleanupOrThrow("\u505C\u6B62\u524D\u9700\u6E05\u7406");
|
|
8839
8836
|
}
|
|
8840
8837
|
const status = getServiceStatus();
|
|
8841
8838
|
const pids = getMihomoPids();
|
|
@@ -8852,13 +8849,13 @@ async function cmdStop(args) {
|
|
|
8852
8849
|
console.log(colors.green("\u5DF2\u505C\u6B62"));
|
|
8853
8850
|
return;
|
|
8854
8851
|
}
|
|
8855
|
-
await stopService();
|
|
8856
|
-
handleStopResult(
|
|
8852
|
+
const cleanup = await stopService();
|
|
8853
|
+
handleStopResult(cleanup);
|
|
8857
8854
|
console.log(`${colors.green("\u5DF2\u505C\u6B62")}${colors.gray("\uFF08\u5DF2\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF0Cmihomo-cli start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09")}`);
|
|
8858
8855
|
}
|
|
8859
8856
|
|
|
8860
8857
|
// src/commands/subscription.ts
|
|
8861
|
-
import { spawnSync as
|
|
8858
|
+
import { spawnSync as spawnSync10 } from "child_process";
|
|
8862
8859
|
function printRestartHintIfRunning(variant = "update") {
|
|
8863
8860
|
const state = getRunningState();
|
|
8864
8861
|
if (state.running) {
|
|
@@ -8913,7 +8910,7 @@ function printSubscriptionList() {
|
|
|
8913
8910
|
function readUrlFromClipboard() {
|
|
8914
8911
|
if (!process.stdin.isTTY) return null;
|
|
8915
8912
|
try {
|
|
8916
|
-
const r =
|
|
8913
|
+
const r = spawnSync10("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
|
|
8917
8914
|
if (r.status !== 0) return null;
|
|
8918
8915
|
const text = (r.stdout || "").trim();
|
|
8919
8916
|
return isValidHttpUrl(text) ? text : null;
|
|
@@ -9092,26 +9089,18 @@ var SUBCOMMANDS3 = [
|
|
|
9092
9089
|
];
|
|
9093
9090
|
async function cmdSubscription(args) {
|
|
9094
9091
|
await dispatchSubcommand(args, SUBCOMMANDS3, {
|
|
9095
|
-
// 无子命令 → 列表;未知子命令 →
|
|
9092
|
+
// 无子命令 → 列表;未知子命令 → 报错(守卫与 did-you-mean 拼装收口在 shared)
|
|
9096
9093
|
fallback: printSubscriptionList,
|
|
9097
|
-
onUnknown: (action) => {
|
|
9098
|
-
|
|
9099
|
-
|
|
9100
|
-
|
|
9101
|
-
|
|
9102
|
-
});
|
|
9103
|
-
}
|
|
9104
|
-
const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
9105
|
-
const suggestion = suggestSimilar(action, names);
|
|
9106
|
-
throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
|
|
9107
|
-
hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "\u7528\u6CD5: mihomo-cli sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
|
|
9108
|
-
});
|
|
9109
|
-
}
|
|
9094
|
+
onUnknown: (action) => unknownSubcommandError(action, SUBCOMMANDS3, {
|
|
9095
|
+
what: "\u8BA2\u9605\u547D\u4EE4",
|
|
9096
|
+
optionHint: ["\u88F8 sub \u53EA\u5217\u51FA\u8BA2\u9605\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo-cli sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"],
|
|
9097
|
+
unknownHint: ["\u7528\u6CD5: mihomo-cli sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
|
|
9098
|
+
})
|
|
9110
9099
|
});
|
|
9111
9100
|
}
|
|
9112
9101
|
|
|
9113
9102
|
// src/commands/ui.ts
|
|
9114
|
-
import { spawnSync as
|
|
9103
|
+
import { spawnSync as spawnSync11 } from "child_process";
|
|
9115
9104
|
function resolveUiName(args) {
|
|
9116
9105
|
const raw = getNonFlagArg(args, 1);
|
|
9117
9106
|
const name = (raw ?? "zash").toLowerCase();
|
|
@@ -9122,7 +9111,7 @@ function resolveUiName(args) {
|
|
|
9122
9111
|
}
|
|
9123
9112
|
function copyToClipboard(text) {
|
|
9124
9113
|
try {
|
|
9125
|
-
return
|
|
9114
|
+
return spawnSync11("pbcopy", [], { input: text }).status === 0;
|
|
9126
9115
|
} catch {
|
|
9127
9116
|
return false;
|
|
9128
9117
|
}
|
|
@@ -9137,7 +9126,7 @@ function cmdUI(args) {
|
|
|
9137
9126
|
console.log("");
|
|
9138
9127
|
}
|
|
9139
9128
|
const url = UI_URLS[uiName];
|
|
9140
|
-
const controllerPort =
|
|
9129
|
+
const controllerPort = getPortsOrNull()?.controller ?? null;
|
|
9141
9130
|
console.log(`\u6253\u5F00 Web UI: ${uiName}`);
|
|
9142
9131
|
console.log(`\u9875\u9762: ${url}`);
|
|
9143
9132
|
console.log(`\u63A7\u5236\u5668: http://127.0.0.1:${controllerPort ?? "\uFF08settings.json \u7684 ports \u914D\u7F6E\u975E\u6CD5\uFF0C\u65E0\u6CD5\u786E\u5B9A\uFF09"}`);
|
|
@@ -9359,7 +9348,7 @@ function readSelfMixedPortEarly() {
|
|
|
9359
9348
|
try {
|
|
9360
9349
|
const raw = JSON.parse(fs19.readFileSync(PATHS.settingsFile, "utf8"));
|
|
9361
9350
|
const mixed = raw?.ports?.mixed;
|
|
9362
|
-
if (
|
|
9351
|
+
if (isValidPortNumber(mixed)) return mixed;
|
|
9363
9352
|
} catch {
|
|
9364
9353
|
}
|
|
9365
9354
|
return DEFAULT_MIXED_PORT;
|