mihomo-cli 26.10.101 → 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 +18 -0
- package/dist/index.js +371 -364
- 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;
|
|
@@ -3686,12 +3689,15 @@ function backupCorruptSettings(reason) {
|
|
|
3686
3689
|
backupCorruptFile(PATHS.settingsFile, "settings.json", reason, "\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E");
|
|
3687
3690
|
return {};
|
|
3688
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
|
+
}
|
|
3689
3695
|
function readSettings() {
|
|
3690
3696
|
if (!fs2.existsSync(PATHS.settingsFile)) return {};
|
|
3691
3697
|
try {
|
|
3692
3698
|
const parsed = JSON.parse(fs2.readFileSync(PATHS.settingsFile, "utf8"));
|
|
3693
3699
|
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
|
|
3694
|
-
return backupCorruptSettings(
|
|
3700
|
+
return backupCorruptSettings(nonObjectReason(parsed));
|
|
3695
3701
|
} catch (e) {
|
|
3696
3702
|
if (e.code === "ENOENT") return {};
|
|
3697
3703
|
return backupCorruptSettings("\u683C\u5F0F\u635F\u574F");
|
|
@@ -3725,7 +3731,7 @@ function updateSettings(mutate, postCommit) {
|
|
|
3725
3731
|
}
|
|
3726
3732
|
function validatePort(value, key) {
|
|
3727
3733
|
if (value === void 0) return void 0;
|
|
3728
|
-
if (
|
|
3734
|
+
if (!isValidPortNumber(value)) {
|
|
3729
3735
|
throw new CliError(`settings.json \u7684 ${key} \u9700\u4E3A 1-65535 \u7684\u6574\u6570\uFF0C\u5F53\u524D\u662F ${JSON.stringify(value)}`, {
|
|
3730
3736
|
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
3731
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"]
|
|
@@ -3753,16 +3759,9 @@ function getPorts(settings = readSettings()) {
|
|
|
3753
3759
|
}
|
|
3754
3760
|
return { mixed, controller };
|
|
3755
3761
|
}
|
|
3756
|
-
function
|
|
3757
|
-
try {
|
|
3758
|
-
return getPorts().controller;
|
|
3759
|
-
} catch {
|
|
3760
|
-
return null;
|
|
3761
|
-
}
|
|
3762
|
-
}
|
|
3763
|
-
function getMixedPortOrNull() {
|
|
3762
|
+
function getPortsOrNull() {
|
|
3764
3763
|
try {
|
|
3765
|
-
return getPorts()
|
|
3764
|
+
return getPorts();
|
|
3766
3765
|
} catch {
|
|
3767
3766
|
return null;
|
|
3768
3767
|
}
|
|
@@ -3775,7 +3774,7 @@ function readSubscriptionCache() {
|
|
|
3775
3774
|
const content = fs2.readFileSync(PATHS.subscriptionsCacheFile, "utf8");
|
|
3776
3775
|
const parsed = JSON.parse(content);
|
|
3777
3776
|
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
3778
|
-
return backupCorruptSubscriptionCache(
|
|
3777
|
+
return backupCorruptSubscriptionCache(nonObjectReason(parsed));
|
|
3779
3778
|
}
|
|
3780
3779
|
return Object.assign(empty(), parsed);
|
|
3781
3780
|
} catch (e) {
|
|
@@ -3942,6 +3941,18 @@ function parseOverrideKey(key) {
|
|
|
3942
3941
|
}
|
|
3943
3942
|
return { key: actualKey, forceOverwrite, arrayPrepend, arrayAppend };
|
|
3944
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
|
+
}
|
|
3945
3956
|
function assertValidParsedKey(rawKey, parsed) {
|
|
3946
3957
|
if (rawKey.startsWith("~") || parsed.key.includes("~")) {
|
|
3947
3958
|
throw new CliError(`\u8986\u5199\u952E "${rawKey}" \u7528\u4E86\u5DF2\u79FB\u9664\u7684 ~ \u64CD\u4F5C\u7B26`, {
|
|
@@ -4056,11 +4067,16 @@ function isYamlOverwriteFilename(filename) {
|
|
|
4056
4067
|
return filename === "overwrite.yaml" || /^overwrite\..+\.ya?ml$/.test(filename);
|
|
4057
4068
|
}
|
|
4058
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("|")})$`);
|
|
4059
4072
|
function isPrimaryScriptFilename(filename) {
|
|
4060
4073
|
return SCRIPT_EXTENSIONS.some((ext) => filename === `overwrite.${ext}`);
|
|
4061
4074
|
}
|
|
4062
4075
|
function isScriptOverwriteFilename(filename) {
|
|
4063
|
-
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";
|
|
4064
4080
|
}
|
|
4065
4081
|
function isOverwriteFilename(filename) {
|
|
4066
4082
|
return isYamlOverwriteFilename(filename) || isScriptOverwriteFilename(filename);
|
|
@@ -4068,7 +4084,11 @@ function isOverwriteFilename(filename) {
|
|
|
4068
4084
|
function isOverwriteFilenameTypo(filename) {
|
|
4069
4085
|
if (isOverwriteFilename(filename)) return false;
|
|
4070
4086
|
const lower = filename.toLowerCase();
|
|
4071
|
-
return
|
|
4087
|
+
return (
|
|
4088
|
+
// overwrite.yml 是 typo 特有的近失(主文件只认 .yaml);其余 YAML 形态直接复用
|
|
4089
|
+
// 合法判定,扩展名知识不留第二份
|
|
4090
|
+
lower === "overwrite.yml" || isYamlOverwriteFilename(lower) || lower === "overwrite.ts" || /^overwrite\..+\.ts$/.test(lower)
|
|
4091
|
+
);
|
|
4072
4092
|
}
|
|
4073
4093
|
function listTypoOverwriteFiles() {
|
|
4074
4094
|
try {
|
|
@@ -4182,7 +4202,7 @@ function summarizeMatch(match) {
|
|
|
4182
4202
|
for (const [key, value] of Object.entries(match)) {
|
|
4183
4203
|
parts.push(`${key}=${value.join("/")}`);
|
|
4184
4204
|
}
|
|
4185
|
-
return parts.
|
|
4205
|
+
return parts.join(", ");
|
|
4186
4206
|
}
|
|
4187
4207
|
function describeOverwriteScope(file) {
|
|
4188
4208
|
return `${file.name} (${summarizeMatch(file.match) ?? "\u5168\u5C40"})`;
|
|
@@ -4199,6 +4219,14 @@ function nameMatchesPattern(name, pattern) {
|
|
|
4199
4219
|
if (p.endsWith("*")) return n.startsWith(p.slice(0, -1));
|
|
4200
4220
|
return n === p;
|
|
4201
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
|
+
}
|
|
4202
4230
|
function matchesScope(match, scope) {
|
|
4203
4231
|
if (!match) return true;
|
|
4204
4232
|
if (match.name) {
|
|
@@ -4208,13 +4236,8 @@ function matchesScope(match, scope) {
|
|
|
4208
4236
|
}
|
|
4209
4237
|
if (match["url-domain"]) {
|
|
4210
4238
|
const domains = match["url-domain"];
|
|
4211
|
-
|
|
4212
|
-
|
|
4213
|
-
try {
|
|
4214
|
-
host = new URL(scope.subUrl.trim()).hostname;
|
|
4215
|
-
} catch {
|
|
4216
|
-
return false;
|
|
4217
|
-
}
|
|
4239
|
+
const host = hostFromSubUrl(scope?.subUrl);
|
|
4240
|
+
if (host === null) return false;
|
|
4218
4241
|
if (!domains.some((d) => hostMatchesDomain(host, d))) return false;
|
|
4219
4242
|
}
|
|
4220
4243
|
return true;
|
|
@@ -4278,16 +4301,16 @@ function normalizeEnabled(raw, fileName) {
|
|
|
4278
4301
|
}
|
|
4279
4302
|
);
|
|
4280
4303
|
}
|
|
4281
|
-
function toBrokenFile(file,
|
|
4304
|
+
function toBrokenFile(file, e) {
|
|
4282
4305
|
if (e instanceof CliError) {
|
|
4283
|
-
return { name: file,
|
|
4306
|
+
return { name: file, label: e.label, message: e.message, hint: e.hint };
|
|
4284
4307
|
}
|
|
4285
4308
|
const message = e.message || String(e);
|
|
4286
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"];
|
|
4287
4310
|
if (/alias/i.test(message)) {
|
|
4288
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"');
|
|
4289
4312
|
}
|
|
4290
|
-
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 };
|
|
4291
4314
|
}
|
|
4292
4315
|
function loadOverwriteScript(filePath, fileName) {
|
|
4293
4316
|
let mod;
|
|
@@ -4327,7 +4350,7 @@ function readOverwriteFiles() {
|
|
|
4327
4350
|
const filePath = path3.join(USER_DATA_DIR, file);
|
|
4328
4351
|
try {
|
|
4329
4352
|
if (isScriptOverwriteFilename(file)) {
|
|
4330
|
-
ok.push({ name: file,
|
|
4353
|
+
ok.push({ name: file, transform: loadOverwriteScript(filePath, file) });
|
|
4331
4354
|
continue;
|
|
4332
4355
|
}
|
|
4333
4356
|
const content = fs3.readFileSync(filePath, "utf8");
|
|
@@ -4337,7 +4360,7 @@ function readOverwriteFiles() {
|
|
|
4337
4360
|
const { match, enabled, ...config } = parsed;
|
|
4338
4361
|
assertNoMetadataKeyLookalikes(config, file);
|
|
4339
4362
|
assertFileLevelOperatorRules(config, file);
|
|
4340
|
-
ok.push({ name: file,
|
|
4363
|
+
ok.push({ name: file, config, match: normalizeMatch(match, file), enabled: normalizeEnabled(enabled, file) });
|
|
4341
4364
|
} else if (parsed !== null) {
|
|
4342
4365
|
const shape = Array.isArray(parsed) ? "\u6570\u7EC4" : typeof parsed;
|
|
4343
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}`, {
|
|
@@ -4346,7 +4369,7 @@ function readOverwriteFiles() {
|
|
|
4346
4369
|
});
|
|
4347
4370
|
}
|
|
4348
4371
|
} catch (e) {
|
|
4349
|
-
broken.push(toBrokenFile(file,
|
|
4372
|
+
broken.push(toBrokenFile(file, e));
|
|
4350
4373
|
}
|
|
4351
4374
|
}
|
|
4352
4375
|
return { ok, broken };
|
|
@@ -4370,16 +4393,15 @@ function loadOverwriteFile() {
|
|
|
4370
4393
|
}
|
|
4371
4394
|
return ok;
|
|
4372
4395
|
}
|
|
4373
|
-
var SCRIPT_LOCKED_PROBES = [...LOCKED_CONFIG_KEYS, "tls"];
|
|
4374
4396
|
function snapshotLockedKeys(config) {
|
|
4375
4397
|
const snap = {};
|
|
4376
|
-
for (const k of
|
|
4398
|
+
for (const k of EFFECTIVELY_LOCKED_KEYS) {
|
|
4377
4399
|
if (k in config) snap[k] = config[k];
|
|
4378
4400
|
}
|
|
4379
4401
|
return snap;
|
|
4380
4402
|
}
|
|
4381
4403
|
function diffLockedKeys(before, after) {
|
|
4382
|
-
return
|
|
4404
|
+
return EFFECTIVELY_LOCKED_KEYS.filter((k) => {
|
|
4383
4405
|
const had = k in before;
|
|
4384
4406
|
const has = k in after;
|
|
4385
4407
|
return had !== has ? has : had && before[k] !== after[k];
|
|
@@ -4390,12 +4412,7 @@ function applyOverwrite(baseConfig, files, opts) {
|
|
|
4390
4412
|
const scriptWarnings = [];
|
|
4391
4413
|
const scriptLockedHits = [];
|
|
4392
4414
|
const scriptMatches = [];
|
|
4393
|
-
|
|
4394
|
-
try {
|
|
4395
|
-
if (opts.scope?.subUrl) host = new URL(opts.scope.subUrl.trim()).hostname;
|
|
4396
|
-
} catch {
|
|
4397
|
-
host = "";
|
|
4398
|
-
}
|
|
4415
|
+
const host = hostFromSubUrl(opts.scope?.subUrl) ?? "";
|
|
4399
4416
|
const subscription = { name: opts.scope?.subName ?? "", url: opts.scope?.subUrl ?? "", host };
|
|
4400
4417
|
for (const file of files) {
|
|
4401
4418
|
if (file.transform) {
|
|
@@ -4436,7 +4453,6 @@ function listOverwriteFile(scope) {
|
|
|
4436
4453
|
entries: ok,
|
|
4437
4454
|
files: ok.map((f) => ({
|
|
4438
4455
|
name: f.name,
|
|
4439
|
-
path: f.path,
|
|
4440
4456
|
kind: f.transform ? "script" : "yaml",
|
|
4441
4457
|
keys: f.transform ? [] : Object.keys(f.config || {}),
|
|
4442
4458
|
scope: summarizeMatch(f.match),
|
|
@@ -4459,6 +4475,11 @@ function sanitizeTerminal(s) {
|
|
|
4459
4475
|
const controlChars = /[\x00-\x08\x0b\x0c\x0d\x0e-\x1f]/g;
|
|
4460
4476
|
return s.replace(ansiEscape, "").replace(controlChars, "");
|
|
4461
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
|
+
}
|
|
4462
4483
|
var TOKEN_KEY_NAMES = [
|
|
4463
4484
|
"token",
|
|
4464
4485
|
"key",
|
|
@@ -4594,7 +4615,7 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4594
4615
|
scriptLockedHits,
|
|
4595
4616
|
scriptMatches
|
|
4596
4617
|
} = applyOverwrite(subscriptionConfig, overwriteFiles, {
|
|
4597
|
-
mode
|
|
4618
|
+
mode,
|
|
4598
4619
|
scope
|
|
4599
4620
|
});
|
|
4600
4621
|
const overwriteSummaries = overwriteFiles.map(describeOverwriteScope);
|
|
@@ -4612,23 +4633,14 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4612
4633
|
}
|
|
4613
4634
|
}
|
|
4614
4635
|
for (const file of overwriteFiles) {
|
|
4615
|
-
const hit =
|
|
4616
|
-
|
|
4617
|
-
|
|
4618
|
-
const parsedKey = parseOverrideKey(rawKey).key;
|
|
4619
|
-
if (parsedKey !== rawKey && (LOCKED_CONFIG_KEYS.includes(parsedKey) || parsedKey === "tls")) {
|
|
4620
|
-
hit.add(parsedKey);
|
|
4621
|
-
}
|
|
4622
|
-
if (rawKey === "tls") hit.add("tls");
|
|
4623
|
-
}
|
|
4624
|
-
if (hit.size > 0) {
|
|
4625
|
-
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));
|
|
4626
4639
|
}
|
|
4627
4640
|
}
|
|
4628
|
-
for (const key of
|
|
4641
|
+
for (const key of EFFECTIVELY_LOCKED_KEYS) {
|
|
4629
4642
|
delete withOverwrites[key];
|
|
4630
4643
|
}
|
|
4631
|
-
delete withOverwrites.tls;
|
|
4632
4644
|
const ports = getPorts(settings);
|
|
4633
4645
|
systemConfig["external-controller"] = `127.0.0.1:${ports.controller}`;
|
|
4634
4646
|
systemConfig["mixed-port"] = ports.mixed;
|
|
@@ -4689,7 +4701,7 @@ function judgeScriptMatches(subRawContent, mode, scope, entries) {
|
|
|
4689
4701
|
const settings = readSettings();
|
|
4690
4702
|
const active = settings.overwrite_enabled !== false ? selectActiveOverwriteFiles(entries, scope) : [];
|
|
4691
4703
|
const { scriptMatches } = applyOverwrite(subscriptionConfig, active, {
|
|
4692
|
-
mode
|
|
4704
|
+
mode,
|
|
4693
4705
|
scope
|
|
4694
4706
|
});
|
|
4695
4707
|
return { matches: scriptMatches };
|
|
@@ -4700,6 +4712,17 @@ function judgeScriptMatches(subRawContent, mode, scope, entries) {
|
|
|
4700
4712
|
function deriveRuntimeMode(info) {
|
|
4701
4713
|
return info?.tun ? "tun" : "mixed";
|
|
4702
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
|
+
}
|
|
4703
4726
|
function writeMihomoConfig(configObj) {
|
|
4704
4727
|
ensureDirs();
|
|
4705
4728
|
const content = dumpYaml(configObj);
|
|
@@ -4766,12 +4789,9 @@ function getConfigInfo() {
|
|
|
4766
4789
|
const content = fs4.readFileSync(PATHS.configFile, "utf8");
|
|
4767
4790
|
const cfg = loadYamlSafe(content);
|
|
4768
4791
|
if (!cfg) return null;
|
|
4769
|
-
const proxies = cfg.proxies;
|
|
4770
|
-
const proxyGroups = cfg["proxy-groups"];
|
|
4771
4792
|
const tun = cfg.tun;
|
|
4772
4793
|
return {
|
|
4773
|
-
|
|
4774
|
-
proxyGroups: proxyGroups ? proxyGroups.length : 0,
|
|
4794
|
+
...countConfigNodes(cfg),
|
|
4775
4795
|
mixedPort: cfg["mixed-port"] || null,
|
|
4776
4796
|
tun: tun ? !!tun.enable : false
|
|
4777
4797
|
};
|
|
@@ -4901,7 +4921,7 @@ import fs13 from "fs";
|
|
|
4901
4921
|
import path7 from "path";
|
|
4902
4922
|
|
|
4903
4923
|
// src/hot-reload.ts
|
|
4904
|
-
import
|
|
4924
|
+
import fs8 from "fs";
|
|
4905
4925
|
|
|
4906
4926
|
// src/launchctl.ts
|
|
4907
4927
|
import { spawnSync as spawnSync2 } from "child_process";
|
|
@@ -5037,14 +5057,108 @@ async function waitUntilUnloaded(target = serviceTarget()) {
|
|
|
5037
5057
|
}
|
|
5038
5058
|
|
|
5039
5059
|
// src/proxy-probe.ts
|
|
5040
|
-
import { execFile as execFile2, spawnSync as
|
|
5060
|
+
import { execFile as execFile2, spawnSync as spawnSync4 } from "child_process";
|
|
5041
5061
|
import { promisify as promisify2 } from "util";
|
|
5062
|
+
|
|
5063
|
+
// src/process-probe.ts
|
|
5064
|
+
import { spawnSync as spawnSync3 } from "child_process";
|
|
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
|
|
5042
5156
|
var execFileAsync = promisify2(execFile2);
|
|
5043
5157
|
function lsofListenPids(port) {
|
|
5044
5158
|
try {
|
|
5045
|
-
const r =
|
|
5159
|
+
const r = spawnSync4("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
|
|
5046
5160
|
if (r.status !== 0) return null;
|
|
5047
|
-
return r.stdout
|
|
5161
|
+
return parsePidList(r.stdout);
|
|
5048
5162
|
} catch {
|
|
5049
5163
|
return null;
|
|
5050
5164
|
}
|
|
@@ -5054,17 +5168,7 @@ function isProbeSuccessStatus(code) {
|
|
|
5054
5168
|
return code !== null && code >= 200 && code < 300;
|
|
5055
5169
|
}
|
|
5056
5170
|
var PROBE_TIMEOUT_MS = 2e3;
|
|
5057
|
-
var PROBE_CACHE_TTL_MS = 3e3;
|
|
5058
|
-
var probeCache = null;
|
|
5059
5171
|
async function probeProxyConnectivity(port) {
|
|
5060
|
-
if (probeCache && probeCache.port === port && Date.now() - probeCache.at < PROBE_CACHE_TTL_MS) {
|
|
5061
|
-
return probeCache.result;
|
|
5062
|
-
}
|
|
5063
|
-
const result = await probeProxyConnectivityUncached(port);
|
|
5064
|
-
probeCache = { port, at: Date.now(), result };
|
|
5065
|
-
return result;
|
|
5066
|
-
}
|
|
5067
|
-
async function probeProxyConnectivityUncached(port) {
|
|
5068
5172
|
const start = Date.now();
|
|
5069
5173
|
try {
|
|
5070
5174
|
const { stdout } = await execFileAsync(
|
|
@@ -5083,18 +5187,16 @@ async function probeProxyConnectivityUncached(port) {
|
|
|
5083
5187
|
};
|
|
5084
5188
|
} catch (e) {
|
|
5085
5189
|
const err = e;
|
|
5086
|
-
const
|
|
5087
|
-
const lastLine = stderr ? stderr.split("\n").pop() : void 0;
|
|
5088
|
-
const detail = lastLine ? lastLine.replace(/^curl: \(\d+\)\s*/, "") : err.message ?? "\u8BF7\u6C42\u5931\u8D25";
|
|
5190
|
+
const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
|
|
5089
5191
|
return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
|
|
5090
5192
|
}
|
|
5091
5193
|
}
|
|
5092
5194
|
|
|
5093
5195
|
// src/stop-epoch.ts
|
|
5094
|
-
import
|
|
5196
|
+
import fs7 from "fs";
|
|
5095
5197
|
function readStopEpoch() {
|
|
5096
5198
|
try {
|
|
5097
|
-
const n = Number.parseInt(
|
|
5199
|
+
const n = Number.parseInt(fs7.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
|
|
5098
5200
|
return Number.isSafeInteger(n) && n >= 0 ? n : 0;
|
|
5099
5201
|
} catch {
|
|
5100
5202
|
return 0;
|
|
@@ -5121,21 +5223,24 @@ function recordServiceStopped() {
|
|
|
5121
5223
|
function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
|
|
5122
5224
|
return stopEpochNow !== stopEpochBefore;
|
|
5123
5225
|
}
|
|
5226
|
+
function startAbortedByConcurrentStop() {
|
|
5227
|
+
return shouldAbortStartOnDisable(stopEpochBaseline(), readStopEpoch());
|
|
5228
|
+
}
|
|
5124
5229
|
|
|
5125
5230
|
// src/hot-reload.ts
|
|
5126
5231
|
var HOT_RELOAD_TIMEOUT_MS = 5e3;
|
|
5127
5232
|
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
5128
5233
|
function logOversized() {
|
|
5129
5234
|
try {
|
|
5130
|
-
return
|
|
5235
|
+
return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
5131
5236
|
} catch {
|
|
5132
5237
|
return false;
|
|
5133
5238
|
}
|
|
5134
5239
|
}
|
|
5135
|
-
async function tryHotReload() {
|
|
5240
|
+
async function tryHotReload(prefetched) {
|
|
5136
5241
|
const controller = new AbortController();
|
|
5137
5242
|
try {
|
|
5138
|
-
const status = getServiceStatus({ withDisabled: false });
|
|
5243
|
+
const status = prefetched ?? getServiceStatus({ withDisabled: false });
|
|
5139
5244
|
if (!status.running || status.pid === null) return false;
|
|
5140
5245
|
const { controller: controllerPort } = getPorts();
|
|
5141
5246
|
const baseUrl = `http://127.0.0.1:${controllerPort}`;
|
|
@@ -5175,115 +5280,6 @@ import fs11 from "fs";
|
|
|
5175
5280
|
import { spawnSync as spawnSync6 } from "child_process";
|
|
5176
5281
|
import fs10 from "fs";
|
|
5177
5282
|
|
|
5178
|
-
// src/process-probe.ts
|
|
5179
|
-
import { spawnSync as spawnSync4 } from "child_process";
|
|
5180
|
-
import fs8 from "fs";
|
|
5181
|
-
var PS_TIMEOUT_MS = 5e3;
|
|
5182
|
-
function isProcessRunning(pid) {
|
|
5183
|
-
if (!pid) return false;
|
|
5184
|
-
try {
|
|
5185
|
-
const result = spawnSync4("ps", ["-p", String(pid), "-o", "pid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
|
|
5186
|
-
return (result.stdout || "").trim().length > 0;
|
|
5187
|
-
} catch {
|
|
5188
|
-
return false;
|
|
5189
|
-
}
|
|
5190
|
-
}
|
|
5191
|
-
function isProcessCommandMatching(pid, needle) {
|
|
5192
|
-
if (!pid) return false;
|
|
5193
|
-
try {
|
|
5194
|
-
const result = spawnSync4("ps", ["-ww", "-p", String(pid), "-o", "command="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
|
|
5195
|
-
return (result.stdout || "").includes(needle);
|
|
5196
|
-
} catch {
|
|
5197
|
-
return false;
|
|
5198
|
-
}
|
|
5199
|
-
}
|
|
5200
|
-
function isProcessRoot(pid) {
|
|
5201
|
-
if (!pid) return false;
|
|
5202
|
-
try {
|
|
5203
|
-
const result = spawnSync4("ps", ["-p", String(pid), "-o", "uid="], { encoding: "utf8", timeout: PS_TIMEOUT_MS });
|
|
5204
|
-
return (result.stdout || "").trim() === "0";
|
|
5205
|
-
} catch {
|
|
5206
|
-
return false;
|
|
5207
|
-
}
|
|
5208
|
-
}
|
|
5209
|
-
var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
|
|
5210
|
-
var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
|
|
5211
|
-
function getPid() {
|
|
5212
|
-
if (!fs8.existsSync(PATHS.pidFile)) return null;
|
|
5213
|
-
try {
|
|
5214
|
-
const pid = parseInt(fs8.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
|
|
5215
|
-
return pid > 0 ? pid : null;
|
|
5216
|
-
} catch {
|
|
5217
|
-
return null;
|
|
5218
|
-
}
|
|
5219
|
-
}
|
|
5220
|
-
function isRunning() {
|
|
5221
|
-
const pid = getPid();
|
|
5222
|
-
if (!pid) return false;
|
|
5223
|
-
return isMihomoProcess(pid);
|
|
5224
|
-
}
|
|
5225
|
-
function isMihomoProcess(pid) {
|
|
5226
|
-
if (!pid) return false;
|
|
5227
|
-
return isProcessRunning(pid) && (isProcessCommandMatching(pid, PATHS.mihomoBinary) || isProcessCommandMatching(pid, PATHS.serviceBinary));
|
|
5228
|
-
}
|
|
5229
|
-
function getMihomoPids() {
|
|
5230
|
-
const result = spawnSync4("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
|
|
5231
|
-
if (result.error || result.status === null) {
|
|
5232
|
-
throw new CliError("\u65E0\u6CD5\u63A2\u6D4B\u5185\u6838\u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
|
|
5233
|
-
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"]
|
|
5234
|
-
});
|
|
5235
|
-
}
|
|
5236
|
-
if (result.status !== 0 && result.status !== 1) {
|
|
5237
|
-
throw new CliError(`\u8FDB\u7A0B\u63A2\u6D4B\u5931\u8D25\uFF08pgrep \u9000\u51FA\u7801 ${result.status}\uFF09`, {
|
|
5238
|
-
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)
|
|
5239
|
-
});
|
|
5240
|
-
}
|
|
5241
|
-
const output = (result.stdout || "").trim();
|
|
5242
|
-
if (!output) return [];
|
|
5243
|
-
return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
|
|
5244
|
-
}
|
|
5245
|
-
function isPidFileOwnedByRoot() {
|
|
5246
|
-
if (!fs8.existsSync(PATHS.pidFile)) return false;
|
|
5247
|
-
try {
|
|
5248
|
-
const stat = fs8.statSync(PATHS.pidFile);
|
|
5249
|
-
return stat.uid === 0;
|
|
5250
|
-
} catch {
|
|
5251
|
-
return false;
|
|
5252
|
-
}
|
|
5253
|
-
}
|
|
5254
|
-
function checkStaleState() {
|
|
5255
|
-
const allPids = getMihomoPids();
|
|
5256
|
-
return {
|
|
5257
|
-
needsCleanup: allPids.length > 0 || isPidFileOwnedByRoot(),
|
|
5258
|
-
allPids
|
|
5259
|
-
};
|
|
5260
|
-
}
|
|
5261
|
-
function getProcessInfo(pid) {
|
|
5262
|
-
try {
|
|
5263
|
-
const result = spawnSync4("ps", ["-p", String(pid), "-o", "rss=,uid="], { encoding: "utf8", timeout: 5e3 });
|
|
5264
|
-
const psOutput = (result.stdout || "").trim();
|
|
5265
|
-
if (!psOutput) return null;
|
|
5266
|
-
const [rssRaw, uidRaw] = psOutput.split(/\s+/);
|
|
5267
|
-
const rss = parseInt(rssRaw, 10);
|
|
5268
|
-
return {
|
|
5269
|
-
pid,
|
|
5270
|
-
memory: rss ? `${(rss / 1024).toFixed(1)} MB` : "\u672A\u77E5",
|
|
5271
|
-
isRoot: uidRaw === "0"
|
|
5272
|
-
};
|
|
5273
|
-
} catch {
|
|
5274
|
-
return { pid, memory: "\u672A\u77E5", isRoot: false };
|
|
5275
|
-
}
|
|
5276
|
-
}
|
|
5277
|
-
function getStatus() {
|
|
5278
|
-
const running = isRunning();
|
|
5279
|
-
const pid = getPid();
|
|
5280
|
-
return {
|
|
5281
|
-
running,
|
|
5282
|
-
pid: running ? pid : null,
|
|
5283
|
-
processInfo: running && pid ? getProcessInfo(pid) : null
|
|
5284
|
-
};
|
|
5285
|
-
}
|
|
5286
|
-
|
|
5287
5283
|
// src/sudo.ts
|
|
5288
5284
|
import { spawnSync as spawnSync5 } from "child_process";
|
|
5289
5285
|
import fs9 from "fs";
|
|
@@ -5357,9 +5353,18 @@ function clearPid() {
|
|
|
5357
5353
|
return e;
|
|
5358
5354
|
}
|
|
5359
5355
|
}
|
|
5360
|
-
|
|
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) {
|
|
5361
5365
|
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
5362
|
-
|
|
5366
|
+
const stillThere = pids ? pids.some(pidAlive) : getMihomoPids().length > 0;
|
|
5367
|
+
if (!stillThere) return;
|
|
5363
5368
|
await sleep(PROCESS_WAIT_INTERVAL);
|
|
5364
5369
|
}
|
|
5365
5370
|
}
|
|
@@ -5404,7 +5409,8 @@ async function cleanupAll() {
|
|
|
5404
5409
|
let killedCount = 0;
|
|
5405
5410
|
const failedPids = [];
|
|
5406
5411
|
let scriptError = null;
|
|
5407
|
-
const
|
|
5412
|
+
const probes = new Map(pids.map((pid) => [pid, probeProcess(pid)]));
|
|
5413
|
+
const rootPids = pids.filter((pid) => probes.get(pid)?.uid === "0");
|
|
5408
5414
|
if (rootPids.length > 0) {
|
|
5409
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`);
|
|
5410
5416
|
try {
|
|
@@ -5425,7 +5431,8 @@ async function cleanupAll() {
|
|
|
5425
5431
|
}
|
|
5426
5432
|
} else {
|
|
5427
5433
|
for (const pid of pids) {
|
|
5428
|
-
|
|
5434
|
+
const probed = probes.get(pid);
|
|
5435
|
+
if (!probed || !isProbedMihomo(probed)) {
|
|
5429
5436
|
killedCount++;
|
|
5430
5437
|
continue;
|
|
5431
5438
|
}
|
|
@@ -5436,7 +5443,7 @@ async function cleanupAll() {
|
|
|
5436
5443
|
}
|
|
5437
5444
|
}
|
|
5438
5445
|
}
|
|
5439
|
-
await waitUntilNoMihomo();
|
|
5446
|
+
await waitUntilNoMihomo(pids);
|
|
5440
5447
|
const remaining = getMihomoPids();
|
|
5441
5448
|
const pidError = remaining.length === 0 ? clearPid() : null;
|
|
5442
5449
|
return { killed: killedCount, failed: failedPids.length, remaining, scriptError, pidError };
|
|
@@ -5446,7 +5453,7 @@ async function stop() {
|
|
|
5446
5453
|
if (allPids.length === 0) {
|
|
5447
5454
|
warnPidCleanupFailed(clearPid());
|
|
5448
5455
|
clearRuntime();
|
|
5449
|
-
return {
|
|
5456
|
+
return {};
|
|
5450
5457
|
}
|
|
5451
5458
|
const result = await cleanupAll();
|
|
5452
5459
|
if (result.remaining.length === 0) {
|
|
@@ -5462,10 +5469,10 @@ async function stop() {
|
|
|
5462
5469
|
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
5463
5470
|
console.log(MANUAL_PKILL_HINT);
|
|
5464
5471
|
console.log("");
|
|
5465
|
-
return {
|
|
5472
|
+
return { remaining };
|
|
5466
5473
|
}
|
|
5467
5474
|
clearRuntime();
|
|
5468
|
-
return {
|
|
5475
|
+
return {};
|
|
5469
5476
|
}
|
|
5470
5477
|
|
|
5471
5478
|
// src/legacy-cleanup.ts
|
|
@@ -5489,15 +5496,18 @@ function classifyResidueCleanup(result) {
|
|
|
5489
5496
|
if (result.remaining.length > 0) return result.scriptError !== null ? "throw" : "ok";
|
|
5490
5497
|
return result.scriptError !== null || result.pidError !== null ? "warn" : "ok";
|
|
5491
5498
|
}
|
|
5492
|
-
|
|
5493
|
-
const result = await cleanupAll();
|
|
5494
|
-
const verdict = classifyResidueCleanup(result);
|
|
5495
|
-
if (verdict === "ok") return;
|
|
5499
|
+
function warnResidueCleanup(result, ctx) {
|
|
5496
5500
|
const err = buildRootResidueCleanupError(result, ctx);
|
|
5497
|
-
if (verdict === "throw") throw err;
|
|
5498
5501
|
console.warn(colors.yellow(`\u8B66\u544A: ${err.message}`));
|
|
5499
5502
|
for (const line of err.hint) console.warn(colors.gray(line));
|
|
5500
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
|
+
}
|
|
5501
5511
|
function buildLegacyCleanupScript() {
|
|
5502
5512
|
return [
|
|
5503
5513
|
"#!/bin/bash",
|
|
@@ -5623,10 +5633,10 @@ function rotateLog() {
|
|
|
5623
5633
|
try {
|
|
5624
5634
|
stat = fs12.statSync(logFile);
|
|
5625
5635
|
} catch (e) {
|
|
5626
|
-
if (e.code === "ENOENT") return
|
|
5636
|
+
if (e.code === "ENOENT") return;
|
|
5627
5637
|
throw e;
|
|
5628
5638
|
}
|
|
5629
|
-
if (stat.size === 0) return
|
|
5639
|
+
if (stat.size === 0) return;
|
|
5630
5640
|
const rotatedPath = allocateArchivePath();
|
|
5631
5641
|
try {
|
|
5632
5642
|
fs12.renameSync(logFile, rotatedPath);
|
|
@@ -5635,19 +5645,16 @@ function rotateLog() {
|
|
|
5635
5645
|
fs12.unlinkSync(rotatedPath);
|
|
5636
5646
|
} catch {
|
|
5637
5647
|
}
|
|
5638
|
-
if (e.code === "ENOENT") return
|
|
5648
|
+
if (e.code === "ENOENT") return;
|
|
5639
5649
|
throw e;
|
|
5640
5650
|
}
|
|
5641
|
-
return rotatedPath;
|
|
5642
5651
|
}
|
|
5643
5652
|
function cleanupOldLogs() {
|
|
5644
5653
|
const logsDir = DIRS.logs;
|
|
5645
|
-
if (!fs12.existsSync(logsDir)) return
|
|
5654
|
+
if (!fs12.existsSync(logsDir)) return;
|
|
5646
5655
|
const files = fs12.readdirSync(logsDir);
|
|
5647
5656
|
const now = Date.now();
|
|
5648
5657
|
const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
|
|
5649
|
-
let deleted = 0;
|
|
5650
|
-
let errors = 0;
|
|
5651
5658
|
for (const file of files) {
|
|
5652
5659
|
if (!isArchiveLogFilename(file)) continue;
|
|
5653
5660
|
try {
|
|
@@ -5655,13 +5662,10 @@ function cleanupOldLogs() {
|
|
|
5655
5662
|
const stat = fs12.statSync(filePath);
|
|
5656
5663
|
if (now - stat.mtimeMs > maxAgeMs) {
|
|
5657
5664
|
fs12.unlinkSync(filePath);
|
|
5658
|
-
deleted++;
|
|
5659
5665
|
}
|
|
5660
5666
|
} catch {
|
|
5661
|
-
errors++;
|
|
5662
5667
|
}
|
|
5663
5668
|
}
|
|
5664
|
-
return { deleted, errors };
|
|
5665
5669
|
}
|
|
5666
5670
|
function listLogs() {
|
|
5667
5671
|
const logsDir = DIRS.logs;
|
|
@@ -5705,6 +5709,13 @@ async function waitServiceHealthy() {
|
|
|
5705
5709
|
const deadline = Date.now() + SERVICE_OBSERVE_MS;
|
|
5706
5710
|
const graceDeadline = deadline + SERVICE_HEALTH_GRACE_MS;
|
|
5707
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
|
+
});
|
|
5708
5719
|
do {
|
|
5709
5720
|
await sleep(SERVICE_HEALTH_INTERVAL_MS);
|
|
5710
5721
|
try {
|
|
@@ -5713,10 +5724,10 @@ async function waitServiceHealthy() {
|
|
|
5713
5724
|
continue;
|
|
5714
5725
|
}
|
|
5715
5726
|
if (isCrashed(last)) {
|
|
5716
|
-
return
|
|
5727
|
+
return unhealthy(last, true);
|
|
5717
5728
|
}
|
|
5718
5729
|
if (!last.loaded) {
|
|
5719
|
-
return
|
|
5730
|
+
return unhealthy(last, false);
|
|
5720
5731
|
}
|
|
5721
5732
|
} while (Date.now() < deadline);
|
|
5722
5733
|
if (last === null) return healthViaProcessProbe();
|
|
@@ -5731,13 +5742,13 @@ async function waitServiceHealthy() {
|
|
|
5731
5742
|
}
|
|
5732
5743
|
graceQueried = true;
|
|
5733
5744
|
if (isCrashed(last)) {
|
|
5734
|
-
return
|
|
5745
|
+
return unhealthy(last, true);
|
|
5735
5746
|
}
|
|
5736
5747
|
if (!last.loaded) break;
|
|
5737
5748
|
if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
|
|
5738
5749
|
}
|
|
5739
5750
|
if (!graceQueried) return healthViaProcessProbe();
|
|
5740
|
-
return
|
|
5751
|
+
return unhealthy(last, false, last.pid);
|
|
5741
5752
|
}
|
|
5742
5753
|
function healthViaProcessProbe() {
|
|
5743
5754
|
try {
|
|
@@ -5759,6 +5770,19 @@ function isCrashed(status) {
|
|
|
5759
5770
|
function describeAbnormalExit(status) {
|
|
5760
5771
|
return describeExitCause(status.lastExitCode, status.lastTerminatingSignal);
|
|
5761
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
|
+
}
|
|
5762
5786
|
function ensureServiceSymlink() {
|
|
5763
5787
|
assertKernelInstalled();
|
|
5764
5788
|
try {
|
|
@@ -5826,7 +5850,7 @@ async function installService(wasRunning) {
|
|
|
5826
5850
|
atomicWriteFileSync(PATHS.userAgentPlist, fs13.readFileSync(stagePath, "utf8"), { mode: 420 });
|
|
5827
5851
|
if (wasRunning) {
|
|
5828
5852
|
withFileLock(PATHS.serviceLock, () => {
|
|
5829
|
-
if (
|
|
5853
|
+
if (startAbortedByConcurrentStop()) {
|
|
5830
5854
|
restoreSkipped = true;
|
|
5831
5855
|
return;
|
|
5832
5856
|
}
|
|
@@ -5869,7 +5893,7 @@ async function startService() {
|
|
|
5869
5893
|
rotateAndCleanupLogs();
|
|
5870
5894
|
let started = true;
|
|
5871
5895
|
withFileLock(PATHS.serviceLock, () => {
|
|
5872
|
-
if (
|
|
5896
|
+
if (startAbortedByConcurrentStop()) {
|
|
5873
5897
|
started = false;
|
|
5874
5898
|
return;
|
|
5875
5899
|
}
|
|
@@ -5898,7 +5922,7 @@ async function bootoutAndDisableInLock() {
|
|
|
5898
5922
|
async function stopService() {
|
|
5899
5923
|
assertServiceLabelSafe();
|
|
5900
5924
|
await bootoutAndDisableInLock();
|
|
5901
|
-
|
|
5925
|
+
return cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo-cli stop" });
|
|
5902
5926
|
}
|
|
5903
5927
|
async function uninstallService() {
|
|
5904
5928
|
assertServiceLabelSafe();
|
|
@@ -5908,19 +5932,20 @@ async function uninstallService() {
|
|
|
5908
5932
|
} catch (e) {
|
|
5909
5933
|
throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
|
|
5910
5934
|
}
|
|
5911
|
-
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" });
|
|
5912
5936
|
try {
|
|
5913
5937
|
fs13.rmSync(PATHS.serviceBinary, { force: true });
|
|
5914
5938
|
} catch {
|
|
5915
5939
|
}
|
|
5940
|
+
return cleanup;
|
|
5916
5941
|
}
|
|
5917
|
-
async function restartService() {
|
|
5942
|
+
async function restartService(prefetched) {
|
|
5918
5943
|
assertServiceLabelSafe();
|
|
5919
5944
|
if (!isServiceInstalled()) {
|
|
5920
5945
|
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
|
|
5921
5946
|
}
|
|
5922
5947
|
const oversized = logOversized();
|
|
5923
|
-
if (!oversized && await tryHotReload()) {
|
|
5948
|
+
if (!oversized && await tryHotReload(prefetched)) {
|
|
5924
5949
|
return concludeHotReload(stopEpochBaseline(), readStopEpoch());
|
|
5925
5950
|
}
|
|
5926
5951
|
if (oversized) {
|
|
@@ -5935,7 +5960,7 @@ async function restartService() {
|
|
|
5935
5960
|
let started = true;
|
|
5936
5961
|
if (kick.status !== 0) {
|
|
5937
5962
|
withFileLock(PATHS.serviceLock, () => {
|
|
5938
|
-
if (
|
|
5963
|
+
if (startAbortedByConcurrentStop()) {
|
|
5939
5964
|
started = false;
|
|
5940
5965
|
return;
|
|
5941
5966
|
}
|
|
@@ -6430,30 +6455,17 @@ async function downloadSubscription(url, subName = "default", signal) {
|
|
|
6430
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"]
|
|
6431
6456
|
});
|
|
6432
6457
|
}
|
|
6433
|
-
const proxies = parsed
|
|
6434
|
-
|
|
6435
|
-
return {
|
|
6436
|
-
proxies: proxies ? proxies.length : 0,
|
|
6437
|
-
proxyGroups: proxyGroups ? proxyGroups.length : 0,
|
|
6438
|
-
userInfo: meta.userInfo,
|
|
6439
|
-
updateInterval: meta.updateInterval,
|
|
6440
|
-
webPageUrl: meta.webPageUrl,
|
|
6441
|
-
username: meta.username
|
|
6442
|
-
};
|
|
6458
|
+
const { proxies, proxyGroups } = countConfigNodes(parsed);
|
|
6459
|
+
return { proxies, proxyGroups };
|
|
6443
6460
|
}
|
|
6444
6461
|
async function prepareConfigForStart(mode, subName = "default") {
|
|
6445
6462
|
const rawContent = requireSubscriptionRawConfig(subName);
|
|
6446
6463
|
const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
|
|
6447
6464
|
const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
|
|
6448
6465
|
await validateConfigWithKernel(buildResult.config, buildResult.overwriteSummaries);
|
|
6449
|
-
const proxies = buildResult.config.proxies;
|
|
6450
|
-
const proxyGroups = buildResult.config["proxy-groups"];
|
|
6451
6466
|
return {
|
|
6452
6467
|
buildResult,
|
|
6453
|
-
info:
|
|
6454
|
-
proxies: proxies ? proxies.length : 0,
|
|
6455
|
-
proxyGroups: proxyGroups ? proxyGroups.length : 0
|
|
6456
|
-
}
|
|
6468
|
+
info: countConfigNodes(buildResult.config)
|
|
6457
6469
|
};
|
|
6458
6470
|
}
|
|
6459
6471
|
function commitPreparedConfig(prepared) {
|
|
@@ -6497,7 +6509,7 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
6497
6509
|
const allSubs = getSubscriptionsWithCache();
|
|
6498
6510
|
const staleSubs = allSubs.filter(needsAutoUpdate);
|
|
6499
6511
|
if (staleSubs.length === 0) {
|
|
6500
|
-
return
|
|
6512
|
+
return;
|
|
6501
6513
|
}
|
|
6502
6514
|
if (staleSubs.length === 1) {
|
|
6503
6515
|
const sub = staleSubs[0];
|
|
@@ -6526,14 +6538,9 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
6526
6538
|
});
|
|
6527
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`));
|
|
6528
6540
|
}
|
|
6529
|
-
let updatedCount = 0;
|
|
6530
|
-
let failedCount = 0;
|
|
6531
6541
|
for (const r of results) {
|
|
6532
|
-
if (r.success) updatedCount++;
|
|
6533
|
-
else if (!r.aborted) failedCount++;
|
|
6534
6542
|
printUpdateResult(r);
|
|
6535
6543
|
}
|
|
6536
|
-
return { total: staleSubs.length, updated: updatedCount, failed: failedCount };
|
|
6537
6544
|
}
|
|
6538
6545
|
|
|
6539
6546
|
// src/commands/config.ts
|
|
@@ -6686,14 +6693,13 @@ tail -25 "\${LOG_FILE}" 2>/dev/null
|
|
|
6686
6693
|
exit 2
|
|
6687
6694
|
`;
|
|
6688
6695
|
}
|
|
6689
|
-
async function startTun() {
|
|
6696
|
+
async function startTun(prefetched) {
|
|
6690
6697
|
ensureDirs();
|
|
6691
6698
|
assertKernelInstalled();
|
|
6692
6699
|
assertRuntimeConfigPresent();
|
|
6693
|
-
|
|
6694
|
-
|
|
6695
|
-
|
|
6696
|
-
});
|
|
6700
|
+
const serviceLoaded = prefetched ? prefetched.loaded : getServiceStatus({ withDisabled: false }).loaded;
|
|
6701
|
+
if (serviceLoaded) {
|
|
6702
|
+
throw tunBlockedByConcurrentStart();
|
|
6697
6703
|
}
|
|
6698
6704
|
rotateAndCleanupLogs();
|
|
6699
6705
|
const logFile = PATHS.logFile;
|
|
@@ -6729,7 +6735,7 @@ async function startTun() {
|
|
|
6729
6735
|
hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo-cli logs 0"]
|
|
6730
6736
|
});
|
|
6731
6737
|
}
|
|
6732
|
-
return
|
|
6738
|
+
return finalPid;
|
|
6733
6739
|
}
|
|
6734
6740
|
|
|
6735
6741
|
// src/runtime.ts
|
|
@@ -6757,15 +6763,13 @@ function restartModeOnChange() {
|
|
|
6757
6763
|
}
|
|
6758
6764
|
async function launchOrRestart(mode) {
|
|
6759
6765
|
if (mode === "tun") {
|
|
6760
|
-
assertTunStartNotRaced();
|
|
6761
|
-
const result = await startTun();
|
|
6762
|
-
return result.pid;
|
|
6766
|
+
return startTun(assertTunStartNotRaced());
|
|
6763
6767
|
}
|
|
6764
6768
|
const status = getServiceStatus();
|
|
6765
6769
|
let hotReloaded = false;
|
|
6766
6770
|
let started;
|
|
6767
6771
|
if (status.running && !status.disabled) {
|
|
6768
|
-
({ hotReloaded, started } = await restartService());
|
|
6772
|
+
({ hotReloaded, started } = await restartService(status));
|
|
6769
6773
|
} else {
|
|
6770
6774
|
({ started } = await startService());
|
|
6771
6775
|
}
|
|
@@ -6780,7 +6784,7 @@ async function launchOrRestart(mode) {
|
|
|
6780
6784
|
try {
|
|
6781
6785
|
return await assertServiceHealthy();
|
|
6782
6786
|
} catch (e) {
|
|
6783
|
-
if (
|
|
6787
|
+
if (startAbortedByConcurrentStop()) throw cancelledByConcurrentStop();
|
|
6784
6788
|
throw e;
|
|
6785
6789
|
}
|
|
6786
6790
|
}
|
|
@@ -6794,14 +6798,11 @@ function cancelledByConcurrentStop() {
|
|
|
6794
6798
|
]
|
|
6795
6799
|
});
|
|
6796
6800
|
}
|
|
6797
|
-
function tunBlockedByRunningService() {
|
|
6798
|
-
return new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
|
|
6799
|
-
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"]
|
|
6800
|
-
});
|
|
6801
|
-
}
|
|
6802
6801
|
function assertTunStartNotRaced() {
|
|
6803
|
-
if (
|
|
6804
|
-
|
|
6802
|
+
if (startAbortedByConcurrentStop()) throw cancelledByConcurrentStop();
|
|
6803
|
+
const status = getServiceStatus({ withDisabled: false });
|
|
6804
|
+
if (status.loaded) throw tunBlockedByConcurrentStart();
|
|
6805
|
+
return status;
|
|
6805
6806
|
}
|
|
6806
6807
|
function startCommandForCurrentMode(state) {
|
|
6807
6808
|
return state.kind === "tun" ? "mihomo-cli start tun" : "mihomo-cli start";
|
|
@@ -6952,6 +6953,7 @@ function expireColor(line, urgency) {
|
|
|
6952
6953
|
if (urgency === "expiring") return colors.yellow(line);
|
|
6953
6954
|
return line;
|
|
6954
6955
|
}
|
|
6956
|
+
var isActiveOverwrite = (f) => f.enabled && f.matched !== false;
|
|
6955
6957
|
function buildStatusJson(args) {
|
|
6956
6958
|
const urgency = args.cached ? subscriptionUrgency(args.cached) : null;
|
|
6957
6959
|
return {
|
|
@@ -6985,7 +6987,7 @@ function buildStatusJson(args) {
|
|
|
6985
6987
|
files: args.overwriteFiles.filter((f) => f.enabled).map((f) => f.name),
|
|
6986
6988
|
// 全局关闭时 buildConfig 不加载任何覆写,applied 必须空——只滤 enabled/match
|
|
6987
6989
|
// 会列出「生效文件」,与同一份 JSON 里的 enabled:false 自相矛盾
|
|
6988
|
-
applied: args.overwriteEnabled ? args.overwriteFiles.filter(
|
|
6990
|
+
applied: args.overwriteEnabled ? args.overwriteFiles.filter(isActiveOverwrite).map((f) => f.name) : [],
|
|
6989
6991
|
// 加载失败的文件不属于 files/applied(既没合并也无法判 enabled/match),单列 errors。
|
|
6990
6992
|
// hint 必须带出:最有用的迁移指引(已移除操作符改 JS、*edu 加引号等)都在里面,
|
|
6991
6993
|
// 只给 message 等于把可执行的修复步骤扔在启动硬失败那一条路径上
|
|
@@ -7029,7 +7031,7 @@ async function printStatus(args = []) {
|
|
|
7029
7031
|
}
|
|
7030
7032
|
const cached = activeSub ? getSubscriptionsWithCache().find((s) => s.name === activeSub.name) : void 0;
|
|
7031
7033
|
const legacy = detectLegacySystemInstall();
|
|
7032
|
-
const controllerPort =
|
|
7034
|
+
const controllerPort = getPortsOrNull()?.controller ?? null;
|
|
7033
7035
|
const { running, pid, kind } = state;
|
|
7034
7036
|
let probe = null;
|
|
7035
7037
|
if (running && info?.mixedPort && !skipProbe) {
|
|
@@ -7065,7 +7067,7 @@ async function printStatus(args = []) {
|
|
|
7065
7067
|
console.log("");
|
|
7066
7068
|
let modeLabel = "";
|
|
7067
7069
|
if (info) {
|
|
7068
|
-
const mode = info
|
|
7070
|
+
const mode = runtimeModeLabel(deriveRuntimeMode(info));
|
|
7069
7071
|
const carrier = kind === "service" ? " \xB7 \u670D\u52A1" : kind === "tun" ? " \xB7 \u4E34\u65F6" : "";
|
|
7070
7072
|
modeLabel = colors.cyan(` (${mode}${carrier})`);
|
|
7071
7073
|
}
|
|
@@ -7138,15 +7140,12 @@ async function printStatus(args = []) {
|
|
|
7138
7140
|
}
|
|
7139
7141
|
console.log("");
|
|
7140
7142
|
}
|
|
7141
|
-
function shortOverwriteName(name) {
|
|
7142
|
-
return name.replace(/\.(?:ya?ml|m?js|cjs)$/, "").replace(/^overwrite\.?/, "") || "\u4E3B\u6587\u4EF6";
|
|
7143
|
-
}
|
|
7144
7143
|
function printOverwriteLines(enabled, files, broken, activeSub) {
|
|
7145
7144
|
if (!enabled) {
|
|
7146
7145
|
console.log(`${colors.gray("\u8986\u5199: ")}${colors.yellow("\u5DF2\u7981\u7528")}`);
|
|
7147
7146
|
return;
|
|
7148
7147
|
}
|
|
7149
|
-
const active = files.filter(
|
|
7148
|
+
const active = files.filter(isActiveOverwrite);
|
|
7150
7149
|
const unmatched = files.filter((f) => f.enabled && f.matched === false);
|
|
7151
7150
|
const disabledCount = files.filter((f) => !f.enabled).length;
|
|
7152
7151
|
const suffixes = [];
|
|
@@ -7245,8 +7244,7 @@ async function cmdStart(args) {
|
|
|
7245
7244
|
throw new CliError(e.message, { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
7246
7245
|
}
|
|
7247
7246
|
const configInfo = commitPreparedConfig(prepared);
|
|
7248
|
-
|
|
7249
|
-
console.log([colors.cyan(modeLabel), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
|
|
7247
|
+
console.log([colors.cyan(runtimeModeLabel(targetMode)), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
|
|
7250
7248
|
try {
|
|
7251
7249
|
const pid = await launchOrRestart(targetMode);
|
|
7252
7250
|
console.log(`${colors.green("\u5DF2\u542F\u52A8")}${pid ? ` (PID ${pid})` : ""}`);
|
|
@@ -7426,6 +7424,7 @@ function assertTrustedAssetUrl(rawUrl) {
|
|
|
7426
7424
|
\u4EC5\u5141\u8BB8: ${[...ALLOWED_ASSET_HOSTS].join(", ")}`);
|
|
7427
7425
|
}
|
|
7428
7426
|
}
|
|
7427
|
+
var loopbackHttpUrl = (port) => `http://127.0.0.1:${port}`;
|
|
7429
7428
|
function resolveDownloadChannels(input) {
|
|
7430
7429
|
if (input.isOverride && !input.mirror) return [{ kind: "direct" }];
|
|
7431
7430
|
if (input.isOverride && input.mirror) {
|
|
@@ -7433,7 +7432,7 @@ function resolveDownloadChannels(input) {
|
|
|
7433
7432
|
}
|
|
7434
7433
|
if (input.proxyOverride) return [{ kind: "proxy", proxy: input.proxyOverride }];
|
|
7435
7434
|
if (input.proxyRunning && input.proxyPort !== null) {
|
|
7436
|
-
const proxyUrl =
|
|
7435
|
+
const proxyUrl = loopbackHttpUrl(input.proxyPort);
|
|
7437
7436
|
const channels = [{ kind: "proxy", proxy: proxyUrl }];
|
|
7438
7437
|
if (input.ghAvailable) channels.push({ kind: "gh", proxy: proxyUrl });
|
|
7439
7438
|
return channels;
|
|
@@ -7441,6 +7440,11 @@ function resolveDownloadChannels(input) {
|
|
|
7441
7440
|
if (input.ghAvailable) return [{ kind: "gh" }];
|
|
7442
7441
|
return [{ kind: "direct" }];
|
|
7443
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
|
+
}
|
|
7444
7448
|
function ghProbeNeeded(input) {
|
|
7445
7449
|
return !input.forceDirect && input.proxyOverride === null;
|
|
7446
7450
|
}
|
|
@@ -7449,10 +7453,7 @@ function hasGh() {
|
|
|
7449
7453
|
return !result.error && result.status === 0;
|
|
7450
7454
|
}
|
|
7451
7455
|
function getArch() {
|
|
7452
|
-
|
|
7453
|
-
if (arch === "arm64") return "arm64";
|
|
7454
|
-
if (arch === "x64") return "amd64";
|
|
7455
|
-
return arch;
|
|
7456
|
+
return process.arch === "x64" ? "amd64" : process.arch;
|
|
7456
7457
|
}
|
|
7457
7458
|
function findMatchingAsset(assets, platform, arch) {
|
|
7458
7459
|
const prefix = `mihomo-${platform}-${arch}`;
|
|
@@ -7518,9 +7519,8 @@ function translateReleaseApiCurlError(e) {
|
|
|
7518
7519
|
if (err.killed) {
|
|
7519
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` : ""}`);
|
|
7520
7521
|
}
|
|
7521
|
-
const
|
|
7522
|
-
|
|
7523
|
-
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}` : ""})`);
|
|
7524
7524
|
}
|
|
7525
7525
|
function buildGhApiReleaseArgs(repo) {
|
|
7526
7526
|
return ["api", `repos/${repo}/releases`, "--method", "GET"];
|
|
@@ -7535,7 +7535,7 @@ async function getLatestReleaseViaGh(repo, signal) {
|
|
|
7535
7535
|
});
|
|
7536
7536
|
return pickLatestRelease(JSON.parse(result.stdout));
|
|
7537
7537
|
}
|
|
7538
|
-
async function getLatestRelease(repo, opts
|
|
7538
|
+
async function getLatestRelease(repo, opts) {
|
|
7539
7539
|
const url = `https://api.github.com/repos/${repo}/releases`;
|
|
7540
7540
|
if (opts.useGh) {
|
|
7541
7541
|
try {
|
|
@@ -7770,12 +7770,10 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7770
7770
|
\u9000\u51FA\u7801: ${probe.status}
|
|
7771
7771
|
\u8F93\u51FA: ${probe.output || "(\u7A7A)"}`);
|
|
7772
7772
|
}
|
|
7773
|
-
|
|
7774
|
-
|
|
7775
|
-
|
|
7776
|
-
|
|
7777
|
-
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`);
|
|
7778
|
-
}
|
|
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`);
|
|
7779
7777
|
}
|
|
7780
7778
|
const targetPath = PATHS.mihomoBinary;
|
|
7781
7779
|
fs15.renameSync(foundBinary, targetPath);
|
|
@@ -7917,12 +7915,20 @@ async function collectChecks() {
|
|
|
7917
7915
|
const latestVersionPromise = getLatestNpmVersion(4e3).catch(() => null);
|
|
7918
7916
|
const earlyService = getServiceStatus();
|
|
7919
7917
|
const earlyState = getRunningState(earlyService);
|
|
7920
|
-
const kernelProxyPort = earlyState.running ?
|
|
7918
|
+
const kernelProxyPort = earlyState.running ? getPortsOrNull()?.mixed ?? null : null;
|
|
7921
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
|
+
});
|
|
7922
7928
|
const kernelVersionPromise = kernelProbe ? withAbortableTimeout(
|
|
7923
7929
|
(signal) => checkUpdate({
|
|
7924
|
-
proxy:
|
|
7925
|
-
useGh:
|
|
7930
|
+
proxy: releaseQuery.proxy,
|
|
7931
|
+
useGh: releaseQuery.useGh,
|
|
7926
7932
|
signal,
|
|
7927
7933
|
currentVersion: getKernelVersion(kernelProbe)
|
|
7928
7934
|
}),
|
|
@@ -7983,30 +7989,29 @@ async function collectChecks() {
|
|
|
7983
7989
|
}
|
|
7984
7990
|
}
|
|
7985
7991
|
}
|
|
7986
|
-
const service = earlyService;
|
|
7987
7992
|
const legacy = detectLegacySystemInstall();
|
|
7988
7993
|
if (legacy) {
|
|
7989
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");
|
|
7990
|
-
} else if (!
|
|
7995
|
+
} else if (!earlyService.installed && !earlyService.loaded) {
|
|
7991
7996
|
push("\u670D\u52A1", "warn", "\u672A\u5B89\u88C5\uFF08Mixed \u6A21\u5F0F\u9700\u8981\uFF09", "mihomo-cli install");
|
|
7992
|
-
} else if (!
|
|
7997
|
+
} else if (!earlyService.installed) {
|
|
7993
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");
|
|
7994
|
-
} else if (
|
|
7995
|
-
const abnormalExit = describeAbnormalExit(
|
|
7996
|
-
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` : ""}`);
|
|
7997
8002
|
if (abnormalExit) {
|
|
7998
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");
|
|
7999
8004
|
}
|
|
8000
8005
|
} else {
|
|
8001
|
-
const abnormalExit = describeAbnormalExit(
|
|
8002
|
-
if (!
|
|
8006
|
+
const abnormalExit = describeAbnormalExit(earlyService);
|
|
8007
|
+
if (!earlyService.disabled && abnormalExit) {
|
|
8003
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");
|
|
8004
8009
|
} else {
|
|
8005
|
-
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" : ""}`);
|
|
8006
8011
|
}
|
|
8007
8012
|
}
|
|
8008
|
-
const state = earlyState;
|
|
8009
8013
|
const info = getConfigInfo();
|
|
8014
|
+
const connectivityPromise = earlyState.running && info?.mixedPort ? probeProxyConnectivity(info.mixedPort) : null;
|
|
8010
8015
|
let mixedPortDefault = DEFAULT_MIXED_PORT;
|
|
8011
8016
|
try {
|
|
8012
8017
|
const ports = getPorts();
|
|
@@ -8015,7 +8020,7 @@ async function collectChecks() {
|
|
|
8015
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");
|
|
8016
8021
|
}
|
|
8017
8022
|
const mixedPort = info?.mixedPort ?? mixedPortDefault;
|
|
8018
|
-
if (
|
|
8023
|
+
if (earlyState.running) {
|
|
8019
8024
|
if (isPortListening(mixedPort)) {
|
|
8020
8025
|
push("\u7AEF\u53E3", "ok", `${mixedPort} \u6B63\u5728\u76D1\u542C`);
|
|
8021
8026
|
} else {
|
|
@@ -8049,8 +8054,8 @@ async function collectChecks() {
|
|
|
8049
8054
|
} else {
|
|
8050
8055
|
push("\u914D\u7F6E\u6784\u5EFA", "skip", active ? "\u672A\u5B89\u88C5\u5185\u6838\uFF0C\u8DF3\u8FC7\u6821\u9A8C" : "\u65E0\u8BA2\u9605\uFF0C\u8DF3\u8FC7");
|
|
8051
8056
|
}
|
|
8052
|
-
if (
|
|
8053
|
-
const probe = await
|
|
8057
|
+
if (connectivityPromise) {
|
|
8058
|
+
const probe = await connectivityPromise;
|
|
8054
8059
|
if (probe.ok) {
|
|
8055
8060
|
push("\u4EE3\u7406\u8FDE\u901A", "ok", `HTTP ${probe.statusCode}\uFF08${probe.durationMs}ms\uFF09`);
|
|
8056
8061
|
} else {
|
|
@@ -8112,13 +8117,14 @@ async function cmdDoctor(args = []) {
|
|
|
8112
8117
|
}
|
|
8113
8118
|
|
|
8114
8119
|
// src/kernel-args.ts
|
|
8120
|
+
var SCHEME_PREFIX_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//;
|
|
8115
8121
|
var KERNEL_FLAG_WHITELIST = ["--mirror", "--proxy", "-p"];
|
|
8116
8122
|
function normalizeMirrorUrl(val) {
|
|
8117
8123
|
if (!val) return null;
|
|
8118
8124
|
if (val === "direct") return null;
|
|
8119
8125
|
const alias = MIRROR_ALIASES[val.toLowerCase()];
|
|
8120
8126
|
if (alias) return alias;
|
|
8121
|
-
if (
|
|
8127
|
+
if (!SCHEME_PREFIX_RE.test(val) && !val.includes(".") && !val.includes(":")) {
|
|
8122
8128
|
const suggestions = suggestSimilar(val, [...Object.keys(MIRROR_ALIASES), "direct"]);
|
|
8123
8129
|
throw new CliError(`\u672A\u77E5\u7684\u955C\u50CF\u522B\u540D: "${val}"`, {
|
|
8124
8130
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
@@ -8130,7 +8136,7 @@ function normalizeMirrorUrl(val) {
|
|
|
8130
8136
|
]
|
|
8131
8137
|
});
|
|
8132
8138
|
}
|
|
8133
|
-
const withScheme =
|
|
8139
|
+
const withScheme = SCHEME_PREFIX_RE.test(val) ? val : `https://${val}`;
|
|
8134
8140
|
let parsed;
|
|
8135
8141
|
try {
|
|
8136
8142
|
parsed = new URL(withScheme);
|
|
@@ -8154,42 +8160,43 @@ function parseMirrorArg(args) {
|
|
|
8154
8160
|
return { mirror: null, isOverride: false };
|
|
8155
8161
|
}
|
|
8156
8162
|
assertKnownFlags(args.slice(1), KERNEL_FLAG_WHITELIST, "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]");
|
|
8157
|
-
const
|
|
8158
|
-
|
|
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) {
|
|
8159
8173
|
throw new CliError("--mirror \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21", {
|
|
8160
8174
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
8161
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"]
|
|
8162
8176
|
});
|
|
8163
8177
|
}
|
|
8164
|
-
const
|
|
8165
|
-
|
|
8166
|
-
|
|
8167
|
-
|
|
8168
|
-
|
|
8169
|
-
|
|
8170
|
-
label: "\u53C2\u6570\u9519\u8BEF",
|
|
8171
|
-
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"]
|
|
8172
|
-
});
|
|
8173
|
-
}
|
|
8174
|
-
const nextArg = inline ?? args[mirrorIdx + 1];
|
|
8175
|
-
if (!nextArg || nextArg.startsWith("-")) {
|
|
8176
|
-
return { mirror: MIRROR_BARE, isOverride: true };
|
|
8177
|
-
}
|
|
8178
|
-
const normalized = normalizeMirrorUrl(nextArg);
|
|
8179
|
-
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
|
+
});
|
|
8180
8184
|
}
|
|
8181
|
-
|
|
8185
|
+
if (value === null || value.startsWith("-")) {
|
|
8186
|
+
return { mirror: MIRROR_BARE, isOverride: true };
|
|
8187
|
+
}
|
|
8188
|
+
return { mirror: normalizeMirrorUrl(value), isOverride: true };
|
|
8182
8189
|
}
|
|
8183
8190
|
var PROXY_SCHEMES = /* @__PURE__ */ new Set(["http:", "https:", "socks5:", "socks5h:"]);
|
|
8184
8191
|
function normalizeProxyUrl(val) {
|
|
8185
8192
|
if (/^\d+$/.test(val)) {
|
|
8186
8193
|
const port = Number(val);
|
|
8187
|
-
if (!
|
|
8194
|
+
if (!isValidPortNumber(port)) {
|
|
8188
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"] });
|
|
8189
8196
|
}
|
|
8190
8197
|
return `http://127.0.0.1:${port}`;
|
|
8191
8198
|
}
|
|
8192
|
-
const withScheme =
|
|
8199
|
+
const withScheme = SCHEME_PREFIX_RE.test(val) ? val : `http://${val}`;
|
|
8193
8200
|
let parsed;
|
|
8194
8201
|
try {
|
|
8195
8202
|
parsed = new URL(withScheme);
|
|
@@ -8205,7 +8212,7 @@ function normalizeProxyUrl(val) {
|
|
|
8205
8212
|
if (!parsed.hostname) {
|
|
8206
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"] });
|
|
8207
8214
|
}
|
|
8208
|
-
const authority = withScheme.replace(
|
|
8215
|
+
const authority = withScheme.replace(SCHEME_PREFIX_RE, "").split(/[/?#]/)[0];
|
|
8209
8216
|
if (!/:\d+$/.test(authority)) {
|
|
8210
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"] });
|
|
8211
8218
|
}
|
|
@@ -8247,7 +8254,6 @@ function parseProxyArg(args) {
|
|
|
8247
8254
|
}
|
|
8248
8255
|
|
|
8249
8256
|
// src/commands/kernel.ts
|
|
8250
|
-
var KERNEL_VALUE_FLAGS = /* @__PURE__ */ new Set([...VALUE_FLAGS, "--mirror"]);
|
|
8251
8257
|
function channelLabel(channel, isExplicitProxy) {
|
|
8252
8258
|
switch (channel.kind) {
|
|
8253
8259
|
case "gh":
|
|
@@ -8308,7 +8314,7 @@ function buildDownloadFailureError(attempts, isExplicitProxy) {
|
|
|
8308
8314
|
async function cmdKernel(args) {
|
|
8309
8315
|
const mirrorInfo = parseMirrorArg(args);
|
|
8310
8316
|
const proxyInfo = parseProxyArg(args);
|
|
8311
|
-
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>]");
|
|
8312
8318
|
if (proxyInfo.proxy && mirrorInfo.isOverride && !mirrorInfo.mirror) {
|
|
8313
8319
|
throw new CliError("--mirror direct \u4E0E --proxy \u4E0D\u80FD\u540C\u65F6\u4F7F\u7528", {
|
|
8314
8320
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
@@ -8316,20 +8322,20 @@ async function cmdKernel(args) {
|
|
|
8316
8322
|
});
|
|
8317
8323
|
}
|
|
8318
8324
|
const proxyRunning = getRunningState().running;
|
|
8319
|
-
const proxyPort = proxyRunning ?
|
|
8325
|
+
const proxyPort = proxyRunning ? getPortsOrNull()?.mixed ?? null : null;
|
|
8320
8326
|
const forceDirect = mirrorInfo.isOverride && !mirrorInfo.mirror;
|
|
8321
8327
|
const ghAvailable = ghProbeNeeded({ forceDirect, proxyOverride: proxyInfo.proxy }) && hasGh();
|
|
8322
|
-
const
|
|
8328
|
+
const channelInput = {
|
|
8323
8329
|
mirror: mirrorInfo.mirror,
|
|
8324
8330
|
isOverride: mirrorInfo.isOverride,
|
|
8325
8331
|
ghAvailable,
|
|
8326
8332
|
proxyRunning,
|
|
8327
8333
|
proxyPort,
|
|
8328
8334
|
proxyOverride: proxyInfo.proxy
|
|
8329
|
-
}
|
|
8335
|
+
};
|
|
8336
|
+
const channels = resolveDownloadChannels(channelInput);
|
|
8330
8337
|
printChannelLine(channels[0], proxyInfo.proxy !== null);
|
|
8331
|
-
const
|
|
8332
|
-
const useGh = apiProxy === null && !forceDirect && ghAvailable;
|
|
8338
|
+
const { proxy: apiProxy, useGh } = resolveReleaseQuery(channelInput);
|
|
8333
8339
|
let info;
|
|
8334
8340
|
try {
|
|
8335
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";
|
|
@@ -8477,7 +8483,7 @@ function cmdLogs(args) {
|
|
|
8477
8483
|
num = " 0";
|
|
8478
8484
|
} else {
|
|
8479
8485
|
archiveCounter++;
|
|
8480
|
-
num = archiveCounter
|
|
8486
|
+
num = String(archiveCounter).padStart(2);
|
|
8481
8487
|
}
|
|
8482
8488
|
const time = formatDate(log.mtime);
|
|
8483
8489
|
const size = formatBytes(log.size);
|
|
@@ -8516,7 +8522,7 @@ function printOverwriteList() {
|
|
|
8516
8522
|
console.log("");
|
|
8517
8523
|
info.files.forEach((f, i) => {
|
|
8518
8524
|
const seq = i + 1;
|
|
8519
|
-
const num = seq
|
|
8525
|
+
const num = String(seq).padStart(2);
|
|
8520
8526
|
const mark = f.enabled ? "" : ` ${colors.yellow("[\u5DF2\u7981\u7528]")}`;
|
|
8521
8527
|
console.log(` ${num}. ${f.name}${mark}`);
|
|
8522
8528
|
if (f.scope) {
|
|
@@ -8532,7 +8538,7 @@ function printOverwriteList() {
|
|
|
8532
8538
|
console.log(colors.red(`\u52A0\u8F7D\u5931\u8D25 (${info.broken.length} \u4E2A\uFF0C\u672A\u53C2\u4E0E\u5408\u5E76\uFF1Bstart/doctor \u4F1A\u62A5\u9519):`));
|
|
8533
8539
|
info.broken.forEach((b, i) => {
|
|
8534
8540
|
const seq = info.files.length + i + 1;
|
|
8535
|
-
const num = seq
|
|
8541
|
+
const num = String(seq).padStart(2);
|
|
8536
8542
|
console.log(` ${num}. ${colors.red(b.name)} ${colors.red("[\u52A0\u8F7D\u5931\u8D25]")}`);
|
|
8537
8543
|
console.log(colors.red(` ${b.message}`));
|
|
8538
8544
|
for (const line of b.hint) console.log(colors.gray(` ${line}`));
|
|
@@ -8669,24 +8675,22 @@ async function cmdReset(args) {
|
|
|
8669
8675
|
if ((needsStop || serviceTargeted) && legacy) await cleanupLegacyInstallOrThrow();
|
|
8670
8676
|
const current = getServiceStatus();
|
|
8671
8677
|
serviceActive = current.installed || current.loaded;
|
|
8678
|
+
let cleanup = null;
|
|
8672
8679
|
if (serviceActive) {
|
|
8673
|
-
if (serviceTargeted) await uninstallService();
|
|
8674
|
-
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();
|
|
8675
8684
|
}
|
|
8676
|
-
if (needsStop) {
|
|
8677
|
-
const cleanup = await cleanupAll();
|
|
8685
|
+
if (needsStop && cleanup !== null) {
|
|
8678
8686
|
if (cleanup.remaining.length > 0) {
|
|
8679
8687
|
throw new CliError(cleanup.remaining.join(", "), {
|
|
8680
8688
|
label: "\u8FDB\u7A0B\u672A\u80FD\u505C\u6B62\uFF0C\u91CD\u7F6E\u4E2D\u6B62",
|
|
8681
8689
|
hint: [MANUAL_PKILL_HINT]
|
|
8682
8690
|
});
|
|
8683
8691
|
}
|
|
8684
|
-
if (
|
|
8685
|
-
|
|
8686
|
-
if (reason) {
|
|
8687
|
-
console.warn(colors.yellow(`\u8B66\u544A: ${reason}`));
|
|
8688
|
-
console.warn(colors.gray("\u91CD\u8BD5\u6E05\u7406: mihomo-cli stop"));
|
|
8689
|
-
}
|
|
8692
|
+
if (!serviceActive && (cleanup.scriptError !== null || cleanup.pidError !== null)) {
|
|
8693
|
+
warnResidueCleanup(cleanup, { mainOutcome: "\u91CD\u7F6E\u7EE7\u7EED\u6267\u884C", retryCommand: "mihomo-cli stop" });
|
|
8690
8694
|
}
|
|
8691
8695
|
recordServiceStopped();
|
|
8692
8696
|
}
|
|
@@ -8763,7 +8767,7 @@ async function cmdInstall(args) {
|
|
|
8763
8767
|
await assertServiceHealthy("\u6062\u590D\u8FD0\u884C\u5931\u8D25");
|
|
8764
8768
|
} catch (e) {
|
|
8765
8769
|
if (!(e instanceof CliError)) throw e;
|
|
8766
|
-
if (
|
|
8770
|
+
if (startAbortedByConcurrentStop()) {
|
|
8767
8771
|
printRestoreSkipped();
|
|
8768
8772
|
return;
|
|
8769
8773
|
}
|
|
@@ -8795,14 +8799,17 @@ async function cmdUninstall(args) {
|
|
|
8795
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"));
|
|
8796
8800
|
console.log("\u5C06\u6267\u884C launchctl bootout \u5378\u8F7D\u6B8B\u7559\u4EFB\u52A1");
|
|
8797
8801
|
}
|
|
8802
|
+
let remaining = null;
|
|
8798
8803
|
if (status.installed || status.loaded) {
|
|
8799
|
-
await uninstallService();
|
|
8804
|
+
const cleanup = await uninstallService();
|
|
8800
8805
|
console.log(colors.green("\u5DF2\u5378\u8F7D\u670D\u52A1"));
|
|
8806
|
+
remaining = cleanup.remaining;
|
|
8801
8807
|
}
|
|
8802
8808
|
if (legacy) {
|
|
8803
8809
|
await announceLegacyCleanupOrThrow("\u5378\u8F7D\u65F6\u4E00\u5E76\u6E05\u7406");
|
|
8810
|
+
remaining = null;
|
|
8804
8811
|
}
|
|
8805
|
-
|
|
8812
|
+
if (remaining === null) remaining = getMihomoPids();
|
|
8806
8813
|
if (remaining.length > 0) {
|
|
8807
8814
|
console.log("");
|
|
8808
8815
|
console.log(colors.yellow(`\u4ECD\u6709\u5185\u6838\u8FDB\u7A0B\u6B8B\u7559 (PID ${remaining.join(", ")})`));
|
|
@@ -8842,8 +8849,8 @@ async function cmdStop(args) {
|
|
|
8842
8849
|
console.log(colors.green("\u5DF2\u505C\u6B62"));
|
|
8843
8850
|
return;
|
|
8844
8851
|
}
|
|
8845
|
-
await stopService();
|
|
8846
|
-
handleStopResult(
|
|
8852
|
+
const cleanup = await stopService();
|
|
8853
|
+
handleStopResult(cleanup);
|
|
8847
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")}`);
|
|
8848
8855
|
}
|
|
8849
8856
|
|
|
@@ -9119,7 +9126,7 @@ function cmdUI(args) {
|
|
|
9119
9126
|
console.log("");
|
|
9120
9127
|
}
|
|
9121
9128
|
const url = UI_URLS[uiName];
|
|
9122
|
-
const controllerPort =
|
|
9129
|
+
const controllerPort = getPortsOrNull()?.controller ?? null;
|
|
9123
9130
|
console.log(`\u6253\u5F00 Web UI: ${uiName}`);
|
|
9124
9131
|
console.log(`\u9875\u9762: ${url}`);
|
|
9125
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"}`);
|
|
@@ -9341,7 +9348,7 @@ function readSelfMixedPortEarly() {
|
|
|
9341
9348
|
try {
|
|
9342
9349
|
const raw = JSON.parse(fs19.readFileSync(PATHS.settingsFile, "utf8"));
|
|
9343
9350
|
const mixed = raw?.ports?.mixed;
|
|
9344
|
-
if (
|
|
9351
|
+
if (isValidPortNumber(mixed)) return mixed;
|
|
9345
9352
|
} catch {
|
|
9346
9353
|
}
|
|
9347
9354
|
return DEFAULT_MIXED_PORT;
|