mihomo-cli 4.8.1 → 4.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +73 -0
- package/README.md +19 -5
- package/dist/index.js +984 -554
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -56,19 +56,22 @@ var compareVersions = (v1, v2) => {
|
|
|
56
56
|
};
|
|
57
57
|
|
|
58
58
|
// src/colors.ts
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
};
|
|
59
|
+
function colorEnabled(noColor, isTTY) {
|
|
60
|
+
return !(noColor !== void 0 && noColor !== "") && isTTY === true;
|
|
61
|
+
}
|
|
62
|
+
function createColors(enabled) {
|
|
63
|
+
const colorize = (code, str) => enabled ? `${code + String(str)}\x1B[0m` : String(str);
|
|
64
|
+
return {
|
|
65
|
+
bold: (s) => colorize("\x1B[1m", s),
|
|
66
|
+
red: (s) => colorize("\x1B[31m", s),
|
|
67
|
+
green: (s) => colorize("\x1B[32m", s),
|
|
68
|
+
yellow: (s) => colorize("\x1B[33m", s),
|
|
69
|
+
cyan: (s) => colorize("\x1B[36m", s),
|
|
70
|
+
gray: (s) => colorize("\x1B[90m", s)
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
var colors = createColors(colorEnabled(process.env.NO_COLOR, process.stdout.isTTY));
|
|
74
|
+
var stderrColors = createColors(colorEnabled(process.env.NO_COLOR, process.stderr.isTTY));
|
|
72
75
|
|
|
73
76
|
// src/config.ts
|
|
74
77
|
import { execFile, spawnSync } from "child_process";
|
|
@@ -3200,6 +3203,9 @@ var CliError = class extends Error {
|
|
|
3200
3203
|
this.exitCode = options.exitCode ?? 1;
|
|
3201
3204
|
}
|
|
3202
3205
|
};
|
|
3206
|
+
function errorMessage(e) {
|
|
3207
|
+
return e instanceof Error ? e.message : String(e);
|
|
3208
|
+
}
|
|
3203
3209
|
function withTimeout(promise, ms) {
|
|
3204
3210
|
return new Promise((resolve, reject) => {
|
|
3205
3211
|
const timer = setTimeout(() => reject(new TimeoutError()), ms);
|
|
@@ -3327,8 +3333,9 @@ function rmrf(dir) {
|
|
|
3327
3333
|
}
|
|
3328
3334
|
var LOCK_STALE_MS = 1e4;
|
|
3329
3335
|
var LOCK_RETRY_MS = 20;
|
|
3330
|
-
function withFileLock(lockPath, fn) {
|
|
3331
|
-
const
|
|
3336
|
+
function withFileLock(lockPath, fn, opts) {
|
|
3337
|
+
const staleMs = opts?.staleMs ?? LOCK_STALE_MS;
|
|
3338
|
+
const deadline = Date.now() + (opts?.deadlineMs ?? LOCK_STALE_MS);
|
|
3332
3339
|
const token = `${process.pid}-${process.hrtime.bigint()}`;
|
|
3333
3340
|
let fd = null;
|
|
3334
3341
|
while (fd === null) {
|
|
@@ -3351,7 +3358,7 @@ function withFileLock(lockPath, fn) {
|
|
|
3351
3358
|
if (e.code !== "EEXIST") throw e;
|
|
3352
3359
|
let stale = false;
|
|
3353
3360
|
try {
|
|
3354
|
-
stale = Date.now() - fs.statSync(lockPath).mtimeMs >
|
|
3361
|
+
stale = Date.now() - fs.statSync(lockPath).mtimeMs > staleMs;
|
|
3355
3362
|
} catch {
|
|
3356
3363
|
}
|
|
3357
3364
|
if (stale) {
|
|
@@ -3362,11 +3369,18 @@ function withFileLock(lockPath, fn) {
|
|
|
3362
3369
|
continue;
|
|
3363
3370
|
}
|
|
3364
3371
|
if (Date.now() > deadline) {
|
|
3372
|
+
let deadlineStale = false;
|
|
3365
3373
|
try {
|
|
3366
|
-
fs.
|
|
3374
|
+
deadlineStale = Date.now() - fs.statSync(lockPath).mtimeMs > staleMs;
|
|
3367
3375
|
} catch {
|
|
3368
3376
|
}
|
|
3369
|
-
|
|
3377
|
+
if (deadlineStale) {
|
|
3378
|
+
try {
|
|
3379
|
+
fs.rmSync(lockPath, { force: true });
|
|
3380
|
+
} catch {
|
|
3381
|
+
}
|
|
3382
|
+
continue;
|
|
3383
|
+
}
|
|
3370
3384
|
}
|
|
3371
3385
|
sleepSyncMs(LOCK_RETRY_MS);
|
|
3372
3386
|
}
|
|
@@ -3399,12 +3413,17 @@ function readSettings() {
|
|
|
3399
3413
|
const parsed = JSON.parse(fs2.readFileSync(PATHS.settingsFile, "utf8"));
|
|
3400
3414
|
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
|
|
3401
3415
|
} catch {
|
|
3402
|
-
|
|
3403
|
-
|
|
3404
|
-
|
|
3405
|
-
|
|
3406
|
-
|
|
3407
|
-
|
|
3416
|
+
const backup = `${PATHS.settingsFile}.bak`;
|
|
3417
|
+
try {
|
|
3418
|
+
if (fs2.existsSync(backup)) {
|
|
3419
|
+
console.warn(`\u8B66\u544A: settings.json \u683C\u5F0F\u635F\u574F\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E\uFF08\u539F\u4EF6\u5DF2\u5728\u65E9\u524D\u5907\u4EFD: ${backup}\uFF0C\u672A\u8986\u76D6\uFF09`);
|
|
3420
|
+
} else {
|
|
3421
|
+
fs2.copyFileSync(PATHS.settingsFile, backup);
|
|
3422
|
+
console.warn(`\u8B66\u544A: settings.json \u683C\u5F0F\u635F\u574F\uFF0C\u5DF2\u5907\u4EFD\u5230 ${backup}\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E`);
|
|
3423
|
+
}
|
|
3424
|
+
} catch {
|
|
3425
|
+
console.warn("\u8B66\u544A: settings.json \u683C\u5F0F\u635F\u574F\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E");
|
|
3426
|
+
}
|
|
3408
3427
|
}
|
|
3409
3428
|
return {};
|
|
3410
3429
|
}
|
|
@@ -3449,15 +3468,19 @@ function getPorts(settings = readSettings()) {
|
|
|
3449
3468
|
if (ports === null || typeof ports !== "object" || Array.isArray(ports)) {
|
|
3450
3469
|
throw new CliError('settings.json \u7684 ports \u9700\u4E3A\u5BF9\u8C61\uFF0C\u5982 { "mixed": 17890, "controller": 19090 }', { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
3451
3470
|
}
|
|
3452
|
-
const
|
|
3453
|
-
const
|
|
3454
|
-
|
|
3455
|
-
|
|
3471
|
+
const configuredMixed = validatePort(ports.mixed, "ports.mixed");
|
|
3472
|
+
const configuredController = validatePort(ports.controller, "ports.controller");
|
|
3473
|
+
const mixed = configuredMixed ?? DEFAULT_MIXED_PORT;
|
|
3474
|
+
const controller = configuredController ?? CONTROLLER_PORT;
|
|
3475
|
+
if (mixed === controller) {
|
|
3476
|
+
const defaultedKey = configuredMixed === void 0 ? "ports.mixed" : configuredController === void 0 ? "ports.controller" : null;
|
|
3477
|
+
const source = defaultedKey ? `\uFF1A${defaultedKey} \u672A\u914D\u7F6E\uFF0C\u53D6\u9ED8\u8BA4 ${mixed}` : "";
|
|
3478
|
+
throw new CliError(`ports.mixed \u4E0E ports.controller \u4E0D\u80FD\u76F8\u540C\uFF08\u5F53\u524D\u5747\u4E3A ${mixed}${source}\uFF09`, {
|
|
3456
3479
|
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
3457
3480
|
hint: ["\u6DF7\u5408\u7AEF\u53E3\u4E0E\u63A7\u5236\u5668\u7AEF\u53E3\u5404\u9700\u72EC\u7ACB\u7AEF\u53E3\uFF0C\u76F8\u540C\u4F1A\u5BFC\u81F4\u5185\u6838\u542F\u52A8\u5931\u8D25"]
|
|
3458
3481
|
});
|
|
3459
3482
|
}
|
|
3460
|
-
return { mixed
|
|
3483
|
+
return { mixed, controller };
|
|
3461
3484
|
}
|
|
3462
3485
|
function maskSingleUrl(url) {
|
|
3463
3486
|
try {
|
|
@@ -3512,9 +3535,14 @@ function readSubscriptionCache() {
|
|
|
3512
3535
|
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return empty();
|
|
3513
3536
|
return Object.assign(empty(), parsed);
|
|
3514
3537
|
} catch {
|
|
3538
|
+
const cacheBackup = `${PATHS.subscriptionsCacheFile}.bak`;
|
|
3515
3539
|
try {
|
|
3516
|
-
fs2.
|
|
3517
|
-
|
|
3540
|
+
if (fs2.existsSync(cacheBackup)) {
|
|
3541
|
+
console.warn(`\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58\u683C\u5F0F\u635F\u574F\uFF0C\u5DF2\u5FFD\u7565\uFF08\u65E9\u524D\u5907\u4EFD\u4FDD\u7559\u5728 ${cacheBackup}\uFF0C\u672A\u8986\u76D6\uFF09`);
|
|
3542
|
+
} else {
|
|
3543
|
+
fs2.copyFileSync(PATHS.subscriptionsCacheFile, cacheBackup);
|
|
3544
|
+
console.warn(`\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58\u683C\u5F0F\u635F\u574F\uFF0C\u5DF2\u5907\u4EFD\u5230 ${cacheBackup}`);
|
|
3545
|
+
}
|
|
3518
3546
|
} catch {
|
|
3519
3547
|
console.warn("\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58\u683C\u5F0F\u635F\u574F\uFF0C\u5DF2\u5FFD\u7565");
|
|
3520
3548
|
}
|
|
@@ -3669,6 +3697,9 @@ function parseOverrideKey(key) {
|
|
|
3669
3697
|
arrayMergeOnly = true;
|
|
3670
3698
|
actualKey = actualKey.slice(1);
|
|
3671
3699
|
}
|
|
3700
|
+
if (/^<[^>]+>$/.test(actualKey)) {
|
|
3701
|
+
actualKey = actualKey.slice(1, -1);
|
|
3702
|
+
}
|
|
3672
3703
|
} else {
|
|
3673
3704
|
if (actualKey.startsWith("+")) {
|
|
3674
3705
|
arrayPrepend = true;
|
|
@@ -3681,7 +3712,26 @@ function parseOverrideKey(key) {
|
|
|
3681
3712
|
}
|
|
3682
3713
|
return { key: actualKey, forceOverwrite, arrayPrepend, arrayAppend, arrayMergeByName, arrayMergeOnly };
|
|
3683
3714
|
}
|
|
3684
|
-
function
|
|
3715
|
+
function assertValidParsedKey(rawKey, parsed) {
|
|
3716
|
+
if (parsed.key === "") {
|
|
3717
|
+
throw new CliError(`\u8986\u5199\u952E\u540D\u4E0D\u80FD\u4E3A\u7A7A: "${rawKey}"`, {
|
|
3718
|
+
label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
|
|
3719
|
+
hint: ["\u64CD\u4F5C\u7B26\uFF08!\u3001+\u3001~\uFF09\u5FC5\u987B\u4FEE\u9970\u4E00\u4E2A\u771F\u5B9E\u7684\u952E\u540D\uFF0C\u5982 rules+\u3001~proxy-groups\u3002"]
|
|
3720
|
+
});
|
|
3721
|
+
}
|
|
3722
|
+
const ops = [];
|
|
3723
|
+
if (parsed.forceOverwrite) ops.push("!\uFF08\u6574\u4F53\u8986\u76D6\uFF09");
|
|
3724
|
+
if (parsed.arrayMergeByName || parsed.arrayMergeOnly) ops.push("~\uFF08\u6309 name \u5408\u5E76\uFF09");
|
|
3725
|
+
if (parsed.arrayPrepend) ops.push("+\u524D\u7F00\uFF08\u6570\u7EC4\u524D\u63D2\uFF09");
|
|
3726
|
+
if (parsed.arrayAppend) ops.push("+\u540E\u7F00\uFF08\u6570\u7EC4\u8FFD\u52A0\uFF09");
|
|
3727
|
+
if (ops.length > 1) {
|
|
3728
|
+
throw new CliError(`\u8986\u5199\u952E "${rawKey}" \u542B\u4E92\u65A5\u7684\u64CD\u4F5C\u7B26: ${ops.join(" \u4E0E ")}`, {
|
|
3729
|
+
label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
|
|
3730
|
+
hint: ["\u4E00\u4E2A\u952E\u53EA\u80FD\u4F7F\u7528\u4E00\u79CD\u64CD\u4F5C\u7B26\uFF1A\u6574\u4F53\u8986\u76D6 key!\u3001\u6570\u7EC4\u524D\u63D2 +key\u3001\u6570\u7EC4\u8FFD\u52A0 key+\u3001\u6309 name \u5408\u5E76 ~key\u3002"]
|
|
3731
|
+
});
|
|
3732
|
+
}
|
|
3733
|
+
}
|
|
3734
|
+
function mergeConfigLevel(target, override, collectors, parseOperators) {
|
|
3685
3735
|
let t = target;
|
|
3686
3736
|
if (t === null || t === void 0) {
|
|
3687
3737
|
t = Array.isArray(override) ? [] : {};
|
|
@@ -3697,7 +3747,18 @@ function deepMergeWithOverrides(target, override, skipped) {
|
|
|
3697
3747
|
}
|
|
3698
3748
|
const result = { ...t };
|
|
3699
3749
|
for (const [rawKey, value] of Object.entries(override)) {
|
|
3700
|
-
|
|
3750
|
+
let key = rawKey;
|
|
3751
|
+
let forceOverwrite = false;
|
|
3752
|
+
let arrayPrepend = false;
|
|
3753
|
+
let arrayAppend = false;
|
|
3754
|
+
let arrayMergeByName = false;
|
|
3755
|
+
let arrayMergeOnly = false;
|
|
3756
|
+
if (parseOperators) {
|
|
3757
|
+
({ key, forceOverwrite, arrayPrepend, arrayAppend, arrayMergeByName, arrayMergeOnly } = parseOverrideKey(rawKey));
|
|
3758
|
+
assertValidParsedKey(rawKey, { key, forceOverwrite, arrayPrepend, arrayAppend, arrayMergeByName, arrayMergeOnly });
|
|
3759
|
+
} else if (isOperatorShapedNestedKey(rawKey)) {
|
|
3760
|
+
noteOperatorShapedKey(collectors, rawKey);
|
|
3761
|
+
}
|
|
3701
3762
|
const existingValue = result[key];
|
|
3702
3763
|
if (arrayMergeByName) {
|
|
3703
3764
|
if (existingValue !== void 0 && !Array.isArray(existingValue)) {
|
|
@@ -3719,9 +3780,9 @@ function deepMergeWithOverrides(target, override, skipped) {
|
|
|
3719
3780
|
const name = item && typeof item === "object" && !Array.isArray(item) ? item.name : void 0;
|
|
3720
3781
|
const idx = name != null ? merged.findIndex((e) => e && typeof e === "object" && e.name === name) : -1;
|
|
3721
3782
|
if (idx >= 0) {
|
|
3722
|
-
merged[idx] =
|
|
3783
|
+
merged[idx] = mergeConfigLevel(merged[idx], item, collectors, false);
|
|
3723
3784
|
} else if (arrayMergeOnly) {
|
|
3724
|
-
skipped
|
|
3785
|
+
collectors.skipped.push({ key, name: name == null ? "(\u65E0 name)" : String(name) });
|
|
3725
3786
|
} else {
|
|
3726
3787
|
merged.push(item);
|
|
3727
3788
|
}
|
|
@@ -3753,13 +3814,21 @@ function deepMergeWithOverrides(target, override, skipped) {
|
|
|
3753
3814
|
continue;
|
|
3754
3815
|
}
|
|
3755
3816
|
if (value !== null && typeof value === "object" && !Array.isArray(value) && existingValue !== null && typeof existingValue === "object" && !Array.isArray(existingValue)) {
|
|
3756
|
-
result[key] =
|
|
3817
|
+
result[key] = mergeConfigLevel(existingValue, value, collectors, false);
|
|
3757
3818
|
continue;
|
|
3758
3819
|
}
|
|
3759
3820
|
result[key] = value;
|
|
3760
3821
|
}
|
|
3761
3822
|
return result;
|
|
3762
3823
|
}
|
|
3824
|
+
function isOperatorShapedNestedKey(key) {
|
|
3825
|
+
if (key.startsWith("+.")) return false;
|
|
3826
|
+
return key.startsWith("~") || key.startsWith("+") || key.endsWith("!") || key.endsWith("+") || /^<[^>]+>$/.test(key);
|
|
3827
|
+
}
|
|
3828
|
+
function noteOperatorShapedKey(collectors, key) {
|
|
3829
|
+
if (collectors.operatorShapedKeys.some((note) => note.key === key)) return;
|
|
3830
|
+
collectors.operatorShapedKeys.push({ key });
|
|
3831
|
+
}
|
|
3763
3832
|
function isOverwriteEnabled() {
|
|
3764
3833
|
const settings = readSettings();
|
|
3765
3834
|
return settings.overwrite_enabled !== false;
|
|
@@ -3770,6 +3839,11 @@ function setOverwriteEnabled(enabled) {
|
|
|
3770
3839
|
function isOverwriteFilename(filename) {
|
|
3771
3840
|
return filename === "overwrite.yaml" || /^overwrite\..+\.ya?ml$/.test(filename);
|
|
3772
3841
|
}
|
|
3842
|
+
function isOverwriteFilenameTypo(filename) {
|
|
3843
|
+
if (isOverwriteFilename(filename)) return false;
|
|
3844
|
+
const lower = filename.toLowerCase();
|
|
3845
|
+
return lower === "overwrite.yml" || lower === "overwrite.yaml" || /^overwrite\..+\.ya?ml$/.test(lower);
|
|
3846
|
+
}
|
|
3773
3847
|
var MATCH_KEYS = /* @__PURE__ */ new Set(["subscription", "url-domain"]);
|
|
3774
3848
|
function normalizeMatch(raw, fileName) {
|
|
3775
3849
|
if (raw == null) return void 0;
|
|
@@ -3852,11 +3926,17 @@ function filterOverwriteFilesByScope(files, scope) {
|
|
|
3852
3926
|
function loadOverwriteFile() {
|
|
3853
3927
|
const dir = USER_DATA_DIR;
|
|
3854
3928
|
if (!fs3.existsSync(dir)) return [];
|
|
3855
|
-
const
|
|
3929
|
+
const entries = fs3.readdirSync(dir);
|
|
3930
|
+
const files = entries.filter(isOverwriteFilename).sort((a, b) => {
|
|
3856
3931
|
if (a === "overwrite.yaml") return -1;
|
|
3857
3932
|
if (b === "overwrite.yaml") return 1;
|
|
3858
3933
|
return a.localeCompare(b);
|
|
3859
3934
|
});
|
|
3935
|
+
for (const typo of entries.filter((e) => isOverwriteFilenameTypo(e))) {
|
|
3936
|
+
console.warn(
|
|
3937
|
+
`\u8B66\u544A: "${typo}" \u4E0D\u4F1A\u88AB\u5F53\u4F5C\u8986\u5199\u6587\u4EF6\u52A0\u8F7D\uFF08\u5408\u6CD5\u6587\u4EF6\u540D: overwrite.yaml \u4E3B\u6587\u4EF6\u3001overwrite.*.yaml / overwrite.*.yml \u6269\u5C55\u6587\u4EF6\uFF1B\u4E3B\u6587\u4EF6\u4E0D\u652F\u6301 .yml\uFF09\uFF1B\u82E5\u662F\u7B14\u8BEF\u8BF7\u6539\u540D`
|
|
3938
|
+
);
|
|
3939
|
+
}
|
|
3860
3940
|
const results = [];
|
|
3861
3941
|
for (const file of files) {
|
|
3862
3942
|
const filePath = path3.join(dir, file);
|
|
@@ -3879,12 +3959,14 @@ function loadOverwriteFile() {
|
|
|
3879
3959
|
function applyOverwrite(baseConfig, files) {
|
|
3880
3960
|
let result = { ...baseConfig };
|
|
3881
3961
|
const skipped = [];
|
|
3962
|
+
const operatorShapedKeys = [];
|
|
3882
3963
|
for (const file of files) {
|
|
3883
|
-
const
|
|
3884
|
-
result =
|
|
3885
|
-
for (const s of
|
|
3964
|
+
const collectors = { skipped: [], operatorShapedKeys: [] };
|
|
3965
|
+
result = mergeConfigLevel(result, file.config, collectors, true);
|
|
3966
|
+
for (const s of collectors.skipped) skipped.push({ ...s, file: file.name });
|
|
3967
|
+
for (const k of collectors.operatorShapedKeys) operatorShapedKeys.push({ ...k, file: file.name });
|
|
3886
3968
|
}
|
|
3887
|
-
return { config: result, skipped };
|
|
3969
|
+
return { config: result, skipped, operatorShapedKeys };
|
|
3888
3970
|
}
|
|
3889
3971
|
function listOverwriteFile() {
|
|
3890
3972
|
const files = loadOverwriteFile();
|
|
@@ -3917,6 +3999,26 @@ var FLAGS = [
|
|
|
3917
3999
|
];
|
|
3918
4000
|
var VALUE_FLAGS = new Set(FLAGS.filter((f) => f.takesValue).flatMap((f) => f.forms));
|
|
3919
4001
|
var START_RESTART_FLAGS = FLAGS.filter((f) => f.passthroughToRestart);
|
|
4002
|
+
function matchValueFlagToken(token) {
|
|
4003
|
+
const byForm = (form) => FLAGS.find((f) => f.takesValue && f.forms.includes(form));
|
|
4004
|
+
const exact = byForm(token);
|
|
4005
|
+
if (exact) return { spec: exact, baseForm: token, form: "exact", inlineValue: null };
|
|
4006
|
+
if (token.startsWith("--")) {
|
|
4007
|
+
const eqIdx = token.indexOf("=");
|
|
4008
|
+
if (eqIdx > 2) {
|
|
4009
|
+
const base = token.slice(0, eqIdx);
|
|
4010
|
+
const spec = byForm(base);
|
|
4011
|
+
if (spec) return { spec, baseForm: base, form: "long-eq", inlineValue: token.slice(eqIdx + 1) };
|
|
4012
|
+
}
|
|
4013
|
+
return null;
|
|
4014
|
+
}
|
|
4015
|
+
if (token.length > 2 && token.startsWith("-")) {
|
|
4016
|
+
const base = token.slice(0, 2);
|
|
4017
|
+
const spec = byForm(base);
|
|
4018
|
+
if (spec) return { spec, baseForm: base, form: "attached-short", inlineValue: token.slice(2) };
|
|
4019
|
+
}
|
|
4020
|
+
return null;
|
|
4021
|
+
}
|
|
3920
4022
|
|
|
3921
4023
|
// src/utils.ts
|
|
3922
4024
|
function sleep(ms) {
|
|
@@ -4032,15 +4134,33 @@ function assertKnownFlags(args, known, command) {
|
|
|
4032
4134
|
for (const a of args) {
|
|
4033
4135
|
if (!a.startsWith("-") || a === "-") continue;
|
|
4034
4136
|
if (knownSet.has(a)) continue;
|
|
4035
|
-
const
|
|
4036
|
-
if (
|
|
4037
|
-
if (a.
|
|
4137
|
+
const match = matchValueFlagToken(a);
|
|
4138
|
+
if (match && match.form !== "exact" && knownSet.has(match.baseForm)) continue;
|
|
4139
|
+
if (a.startsWith("--mirror=") && knownSet.has("--mirror")) continue;
|
|
4038
4140
|
throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${a}`, {
|
|
4039
4141
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
4040
4142
|
hint: [`\u53EF\u7528\u9009\u9879: ${known.join(", ")}`, "", `\u7528\u6CD5: mihomo ${command}`]
|
|
4041
4143
|
});
|
|
4042
4144
|
}
|
|
4043
4145
|
}
|
|
4146
|
+
function assertPositionalCount(args, max, startIdx, usage, valueFlags = VALUE_FLAGS) {
|
|
4147
|
+
if (!args) return;
|
|
4148
|
+
let count = 0;
|
|
4149
|
+
for (let i = startIdx; i < args.length; i++) {
|
|
4150
|
+
const a = args[i];
|
|
4151
|
+
if (a.startsWith("-")) {
|
|
4152
|
+
if (valueFlags.has(a)) i++;
|
|
4153
|
+
continue;
|
|
4154
|
+
}
|
|
4155
|
+
count++;
|
|
4156
|
+
if (count > max) {
|
|
4157
|
+
throw new CliError(`\u591A\u4F59\u7684\u53C2\u6570: ${a}`, {
|
|
4158
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
4159
|
+
hint: [`\u7528\u6CD5: ${usage}`]
|
|
4160
|
+
});
|
|
4161
|
+
}
|
|
4162
|
+
}
|
|
4163
|
+
}
|
|
4044
4164
|
function parseIntArg(args, short, long, defaultValue) {
|
|
4045
4165
|
if (!args) return defaultValue;
|
|
4046
4166
|
const parse = (raw, flag) => {
|
|
@@ -4060,11 +4180,9 @@ function parseIntArg(args, short, long, defaultValue) {
|
|
|
4060
4180
|
}
|
|
4061
4181
|
throw new CliError(`\u9009\u9879 ${args[i]} \u7F3A\u5C11\u503C`, { hint: [`\u4F8B\u5982: ${args[i]} ${defaultValue}`] });
|
|
4062
4182
|
}
|
|
4063
|
-
|
|
4064
|
-
|
|
4065
|
-
|
|
4066
|
-
if (args[i].startsWith(short) && args[i].length > short.length && /^\d+$/.test(args[i].slice(short.length))) {
|
|
4067
|
-
return parse(args[i].slice(short.length), short);
|
|
4183
|
+
const match = matchValueFlagToken(args[i]);
|
|
4184
|
+
if (match && match.form !== "exact" && (match.spec.forms.includes(short) || match.spec.forms.includes(long))) {
|
|
4185
|
+
return parse(match.inlineValue ?? "", match.baseForm);
|
|
4068
4186
|
}
|
|
4069
4187
|
}
|
|
4070
4188
|
return defaultValue;
|
|
@@ -4073,16 +4191,24 @@ function extractStartOptions(args) {
|
|
|
4073
4191
|
if (!args) return [];
|
|
4074
4192
|
const out = [];
|
|
4075
4193
|
for (let i = 0; i < args.length; i++) {
|
|
4076
|
-
const
|
|
4077
|
-
|
|
4078
|
-
|
|
4079
|
-
|
|
4080
|
-
|
|
4081
|
-
|
|
4194
|
+
const token = args[i];
|
|
4195
|
+
if (START_RESTART_FLAGS.some((f) => !f.takesValue && f.forms.includes(token))) {
|
|
4196
|
+
out.push(token);
|
|
4197
|
+
continue;
|
|
4198
|
+
}
|
|
4199
|
+
const match = matchValueFlagToken(token);
|
|
4200
|
+
if (!match?.spec.passthroughToRestart) continue;
|
|
4201
|
+
out.push(token);
|
|
4202
|
+
if (match.form === "exact" && i + 1 < args.length) {
|
|
4203
|
+
out.push(args[++i]);
|
|
4082
4204
|
}
|
|
4083
4205
|
}
|
|
4084
4206
|
return out;
|
|
4085
4207
|
}
|
|
4208
|
+
function assertRestartOptionValues(args) {
|
|
4209
|
+
if (!args) return;
|
|
4210
|
+
parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
|
|
4211
|
+
}
|
|
4086
4212
|
function getNonFlagArg(args, startIdx, valueFlags = VALUE_FLAGS) {
|
|
4087
4213
|
if (!args) return null;
|
|
4088
4214
|
for (let i = startIdx; i < args.length; i++) {
|
|
@@ -4167,6 +4293,13 @@ function parseMirrorArg(args) {
|
|
|
4167
4293
|
return { mirror: null, isOverride: false };
|
|
4168
4294
|
}
|
|
4169
4295
|
assertKnownFlags(args.slice(1), ["--mirror"], "kernel [--mirror [\u955C\u50CF]]");
|
|
4296
|
+
const mirrorCount = args.filter((a) => a === "--mirror" || a.startsWith("--mirror=")).length;
|
|
4297
|
+
if (mirrorCount > 1) {
|
|
4298
|
+
throw new CliError("--mirror \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21", {
|
|
4299
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
4300
|
+
hint: ["\u7528\u6CD5: mihomo kernel [--mirror [\u955C\u50CF]]", "\u53EF\u7528\u955C\u50CF\u89C1: mihomo kernel --help"]
|
|
4301
|
+
});
|
|
4302
|
+
}
|
|
4170
4303
|
const mirrorEq = args.find((a) => a.startsWith("--mirror="));
|
|
4171
4304
|
const mirrorIdx = args.indexOf("--mirror");
|
|
4172
4305
|
if (mirrorIdx >= 0 || mirrorEq) {
|
|
@@ -4183,6 +4316,27 @@ function parseMirrorArg(args) {
|
|
|
4183
4316
|
|
|
4184
4317
|
// src/config.ts
|
|
4185
4318
|
var SAFE_YAML_LOAD_OPTIONS = { maxAliases: 200 };
|
|
4319
|
+
var LOCKED_CONFIG_KEYS = [
|
|
4320
|
+
"mixed-port",
|
|
4321
|
+
"port",
|
|
4322
|
+
"socks-port",
|
|
4323
|
+
"redir-port",
|
|
4324
|
+
"tproxy-port",
|
|
4325
|
+
"external-controller",
|
|
4326
|
+
"external-controller-tls",
|
|
4327
|
+
"external-controller-unix",
|
|
4328
|
+
"external-controller-pipe",
|
|
4329
|
+
"external-controller-cors",
|
|
4330
|
+
"external-controller-routing-mark",
|
|
4331
|
+
"external-doh-server",
|
|
4332
|
+
"external-ui",
|
|
4333
|
+
"external-ui-name",
|
|
4334
|
+
"external-ui-url",
|
|
4335
|
+
"secret",
|
|
4336
|
+
// 完整入站代理服务端(监听 + 认证 + 自带证书字段):订阅借此可把本机变成开放代理,
|
|
4337
|
+
// 比 redir/tproxy 严重得多,与「入站由 mixed/tun 托管」的产品边界直接冲突
|
|
4338
|
+
"tuic-server"
|
|
4339
|
+
];
|
|
4186
4340
|
function loadYamlSafe(content) {
|
|
4187
4341
|
return load(content, SAFE_YAML_LOAD_OPTIONS);
|
|
4188
4342
|
}
|
|
@@ -4270,31 +4424,57 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4270
4424
|
const settings = readSettings();
|
|
4271
4425
|
const allFiles = settings.overwrite_enabled !== false ? loadOverwriteFile() : [];
|
|
4272
4426
|
const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
|
|
4273
|
-
const { config: withOverwrites, skipped: skippedMerges } = applyOverwrite(subscriptionConfig, overwriteFiles);
|
|
4427
|
+
const { config: withOverwrites, skipped: skippedMerges, operatorShapedKeys } = applyOverwrite(subscriptionConfig, overwriteFiles);
|
|
4274
4428
|
const overwriteSummaries = overwriteFiles.map(describeOverwriteScope);
|
|
4275
4429
|
const systemConfig = {};
|
|
4276
4430
|
const lockedWarnings = [];
|
|
4277
4431
|
for (const s of skippedMerges) {
|
|
4278
4432
|
lockedWarnings.push(`\u8986\u5199 ~?${s.key} \u7684\u8865\u4E01 "${s.name}" \u672A\u5339\u914D\u5230\u5F53\u524D\u8BA2\u9605\u4E2D\u7684\u540C\u540D\u5143\u7D20\uFF0C\u5DF2\u8DF3\u8FC7${s.file ? `\uFF08${s.file}\uFF09` : ""}`);
|
|
4279
4433
|
}
|
|
4434
|
+
for (const n of operatorShapedKeys) {
|
|
4435
|
+
lockedWarnings.push(
|
|
4436
|
+
`\u8986\u5199${n.file ? `\u6587\u4EF6 ${n.file} \u7684` : ""}\u5D4C\u5957\u952E "${n.key}" \u5F62\u4F3C\u64CD\u4F5C\u7B26\uFF0C\u5DF2\u6309\u5B57\u9762\u952E\u540D\u5904\u7406\uFF1B\u64CD\u4F5C\u7B26\u53EA\u5728\u8986\u5199\u6587\u4EF6\u9876\u5C42\u751F\u6548\uFF0C\u82E5\u8FD9\u662F mihomo \u539F\u751F\u952E\u53EF\u5FFD\u7565\u672C\u63D0\u793A`
|
|
4437
|
+
);
|
|
4438
|
+
}
|
|
4280
4439
|
for (const [key, value] of Object.entries(BASE_CONFIG)) {
|
|
4281
4440
|
if (!(key in withOverwrites)) {
|
|
4282
4441
|
systemConfig[key] = value;
|
|
4283
4442
|
}
|
|
4284
4443
|
}
|
|
4444
|
+
for (const file of overwriteFiles) {
|
|
4445
|
+
const hit = /* @__PURE__ */ new Set();
|
|
4446
|
+
for (const rawKey of Object.keys(file.config)) {
|
|
4447
|
+
if (LOCKED_CONFIG_KEYS.includes(rawKey)) hit.add(rawKey);
|
|
4448
|
+
const parsedKey = parseOverrideKey(rawKey).key;
|
|
4449
|
+
if (parsedKey !== rawKey && (LOCKED_CONFIG_KEYS.includes(parsedKey) || parsedKey === "tls")) {
|
|
4450
|
+
hit.add(parsedKey);
|
|
4451
|
+
}
|
|
4452
|
+
if (rawKey === "tls") hit.add("tls");
|
|
4453
|
+
}
|
|
4454
|
+
if (hit.size > 0) {
|
|
4455
|
+
lockedWarnings.push(
|
|
4456
|
+
`\u8986\u5199\u6587\u4EF6 ${file.name} \u4E2D\u7684\u7CFB\u7EDF\u9501\u5B9A\u9879\u5DF2\u5FFD\u7565: ${[...hit].join("\u3001")}\uFF08\u5165\u7AD9\u7AEF\u53E3\u3001\u63A7\u5236\u9762\u4E0E\u63A7\u5236\u5668\u8BC1\u4E66\u7531 mihomo-cli \u7BA1\u7406\uFF1B\u7AEF\u53E3\u4E0E controller secret \u5728 settings.json \u914D\u7F6E\uFF09`
|
|
4457
|
+
);
|
|
4458
|
+
}
|
|
4459
|
+
}
|
|
4460
|
+
for (const key of LOCKED_CONFIG_KEYS) {
|
|
4461
|
+
delete withOverwrites[key];
|
|
4462
|
+
}
|
|
4463
|
+
delete withOverwrites.tls;
|
|
4285
4464
|
const ports = getPorts(settings);
|
|
4286
4465
|
systemConfig["external-controller"] = `127.0.0.1:${ports.controller}`;
|
|
4287
4466
|
systemConfig["mixed-port"] = ports.mixed;
|
|
4288
|
-
delete withOverwrites["mixed-port"];
|
|
4289
|
-
delete withOverwrites.port;
|
|
4290
|
-
delete withOverwrites["socks-port"];
|
|
4291
|
-
delete withOverwrites["external-ui"];
|
|
4292
|
-
delete withOverwrites["external-ui-name"];
|
|
4293
|
-
delete withOverwrites["external-ui-url"];
|
|
4294
|
-
delete withOverwrites.secret;
|
|
4295
4467
|
const controllerSecret = settings.controller_secret;
|
|
4296
|
-
if (controllerSecret) {
|
|
4297
|
-
|
|
4468
|
+
if (controllerSecret !== void 0) {
|
|
4469
|
+
if (typeof controllerSecret !== "string") {
|
|
4470
|
+
throw new CliError("settings.json \u7684 controller_secret \u9700\u4E3A\u5B57\u7B26\u4E32", {
|
|
4471
|
+
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
4472
|
+
hint: ['\u793A\u4F8B: "controller_secret": "your-secret"', "\u5220\u9664\u8BE5\u952E\u5219\u4E0D\u8BBE\u7F6E\u8BBF\u95EE\u5BC6\u94A5"]
|
|
4473
|
+
});
|
|
4474
|
+
}
|
|
4475
|
+
if (controllerSecret) {
|
|
4476
|
+
systemConfig.secret = controllerSecret;
|
|
4477
|
+
}
|
|
4298
4478
|
}
|
|
4299
4479
|
if (mode === "tun") {
|
|
4300
4480
|
systemConfig.tun = TUN_CONFIG.tun;
|
|
@@ -4337,7 +4517,10 @@ function writeMihomoConfig(configObj) {
|
|
|
4337
4517
|
atomicWriteFileSync(PATHS.configFile, content, { mode: 384 });
|
|
4338
4518
|
}
|
|
4339
4519
|
var HINT_INDENT = " ";
|
|
4340
|
-
function buildKernelRejectHint(detail, overwriteSummaries) {
|
|
4520
|
+
function buildKernelRejectHint(detail, overwriteSummaries, opts = {}) {
|
|
4521
|
+
if (opts.timedOut) {
|
|
4522
|
+
return ["", `${HINT_INDENT}\u5185\u6838\u5728 30s \u5185\u672A\u7ED9\u51FA\u6821\u9A8C\u7ED3\u8BBA\uFF0C\u53EF\u80FD\u662F\u5185\u6838\u6216\u7CFB\u7EDF\u5F02\u5E38\uFF08\u4E0E\u914D\u7F6E\u5185\u5BB9\u65E0\u5173\uFF09\uFF1B\u5F53\u524D\u8FD0\u884C\u65F6\u914D\u7F6E\u672A\u6539\u52A8\u3002`];
|
|
4523
|
+
}
|
|
4341
4524
|
const hint = ["", ...detail.split("\n").map((line) => line.trim() ? `${HINT_INDENT}${line}` : "")];
|
|
4342
4525
|
if (overwriteSummaries.length > 0) {
|
|
4343
4526
|
hint.push("", `${HINT_INDENT}\u5F53\u524D\u751F\u6548\u7684\u8986\u5199\u6587\u4EF6:`);
|
|
@@ -4347,7 +4530,7 @@ function buildKernelRejectHint(detail, overwriteSummaries) {
|
|
|
4347
4530
|
hint.push("", `${HINT_INDENT}\u8BF7\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\uFF1B\u5F53\u524D\u8FD0\u884C\u65F6\u914D\u7F6E\u672A\u6539\u52A8\u3002`);
|
|
4348
4531
|
return hint;
|
|
4349
4532
|
}
|
|
4350
|
-
async function validateConfigWithKernel(config, overwriteSummaries
|
|
4533
|
+
async function validateConfigWithKernel(config, overwriteSummaries) {
|
|
4351
4534
|
if (!hasKernel()) throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
4352
4535
|
ensureDirs();
|
|
4353
4536
|
const stageDir = fs4.mkdtempSync(path4.join(DIRS.runtime, "check-"));
|
|
@@ -4367,7 +4550,7 @@ ${error.stderr || ""}`).trim();
|
|
|
4367
4550
|
if (error.killed) {
|
|
4368
4551
|
throw new CliError("\u5185\u6838\u914D\u7F6E\u6821\u9A8C\u8D85\u65F6", {
|
|
4369
4552
|
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
4370
|
-
hint: buildKernelRejectHint(
|
|
4553
|
+
hint: buildKernelRejectHint("", [], { timedOut: true })
|
|
4371
4554
|
});
|
|
4372
4555
|
}
|
|
4373
4556
|
throw new CliError("\u5185\u6838\u62D2\u7EDD\u52A0\u8F7D\u914D\u7F6E", {
|
|
@@ -4476,23 +4659,51 @@ function readLogTail(maxLines = 15) {
|
|
|
4476
4659
|
}
|
|
4477
4660
|
}
|
|
4478
4661
|
}
|
|
4662
|
+
var MAX_ARCHIVE_SEQ = 1e3;
|
|
4479
4663
|
function allocateArchivePath() {
|
|
4480
4664
|
const timestamp = formatLocalTimestamp();
|
|
4481
|
-
let
|
|
4482
|
-
|
|
4483
|
-
|
|
4484
|
-
|
|
4485
|
-
|
|
4665
|
+
for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
|
|
4666
|
+
const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
|
|
4667
|
+
const archivePath = path5.join(DIRS.logs, name);
|
|
4668
|
+
let fd = null;
|
|
4669
|
+
try {
|
|
4670
|
+
fd = fs5.openSync(archivePath, "wx");
|
|
4671
|
+
} catch (e) {
|
|
4672
|
+
if (e.code === "EEXIST") continue;
|
|
4673
|
+
throw e;
|
|
4674
|
+
}
|
|
4675
|
+
try {
|
|
4676
|
+
fs5.closeSync(fd);
|
|
4677
|
+
} catch {
|
|
4678
|
+
}
|
|
4679
|
+
return archivePath;
|
|
4486
4680
|
}
|
|
4487
|
-
|
|
4681
|
+
throw new CliError(`\u540C\u4E00\u79D2\u7684\u5F52\u6863\u5E8F\u53F7\u5DF2\u8FBE\u4E0A\u9650 ${MAX_ARCHIVE_SEQ}\uFF0C\u65E0\u6CD5\u5206\u914D\u65B0\u7684\u5F52\u6863\u540D`, {
|
|
4682
|
+
label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
|
|
4683
|
+
hint: [`${DIRS.logs} \u4E0B\u5B58\u5728\u5927\u91CF\u540C\u4E00\u65F6\u95F4\u6233\u7684\u5F52\u6863\uFF0C\u901A\u5E38\u7531\u5931\u63A7\u7684\u5FAA\u73AF\u8F6E\u8F6C\u9020\u6210\uFF1B\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u811A\u672C\u5728\u53CD\u590D\u89E6\u53D1 start/tun\uFF0C\u786E\u8BA4\u540E\u624B\u52A8\u6E05\u7406\u5F52\u6863\u3002`]
|
|
4684
|
+
});
|
|
4488
4685
|
}
|
|
4489
4686
|
function rotateLog() {
|
|
4490
4687
|
const logFile = PATHS.logFile;
|
|
4491
|
-
|
|
4492
|
-
|
|
4688
|
+
let stat;
|
|
4689
|
+
try {
|
|
4690
|
+
stat = fs5.statSync(logFile);
|
|
4691
|
+
} catch (e) {
|
|
4692
|
+
if (e.code === "ENOENT") return null;
|
|
4693
|
+
throw e;
|
|
4694
|
+
}
|
|
4493
4695
|
if (stat.size === 0) return null;
|
|
4494
4696
|
const rotatedPath = allocateArchivePath();
|
|
4495
|
-
|
|
4697
|
+
try {
|
|
4698
|
+
fs5.renameSync(logFile, rotatedPath);
|
|
4699
|
+
} catch (e) {
|
|
4700
|
+
try {
|
|
4701
|
+
fs5.unlinkSync(rotatedPath);
|
|
4702
|
+
} catch {
|
|
4703
|
+
}
|
|
4704
|
+
if (e.code === "ENOENT") return null;
|
|
4705
|
+
throw e;
|
|
4706
|
+
}
|
|
4496
4707
|
return rotatedPath;
|
|
4497
4708
|
}
|
|
4498
4709
|
function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
|
|
@@ -4667,6 +4878,18 @@ import { spawnSync as spawnSync3 } from "child_process";
|
|
|
4667
4878
|
import fs7 from "fs";
|
|
4668
4879
|
import path6 from "path";
|
|
4669
4880
|
var SUDO_TIMEOUT_MS = 6e4;
|
|
4881
|
+
var SudoAuthError = class extends Error {
|
|
4882
|
+
constructor() {
|
|
4883
|
+
super("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
|
|
4884
|
+
this.name = "SudoAuthError";
|
|
4885
|
+
}
|
|
4886
|
+
};
|
|
4887
|
+
function sudoExitToError(action, status, codeMessages) {
|
|
4888
|
+
if (status === 1) return new SudoAuthError();
|
|
4889
|
+
if (status == null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
|
|
4890
|
+
const custom = codeMessages?.[status];
|
|
4891
|
+
return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
|
|
4892
|
+
}
|
|
4670
4893
|
function runSudoScript(scriptBody, opts) {
|
|
4671
4894
|
if (!process.stdin.isTTY) {
|
|
4672
4895
|
throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
|
|
@@ -4678,16 +4901,7 @@ function runSudoScript(scriptBody, opts) {
|
|
|
4678
4901
|
try {
|
|
4679
4902
|
const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
4680
4903
|
if (result.error) throw result.error;
|
|
4681
|
-
if (result.status !== 0)
|
|
4682
|
-
if (result.status === 1) {
|
|
4683
|
-
throw new Error("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
|
|
4684
|
-
}
|
|
4685
|
-
if (result.status == null) {
|
|
4686
|
-
throw new Error(`${opts.action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
|
|
4687
|
-
}
|
|
4688
|
-
const custom = opts.codeMessages?.[result.status];
|
|
4689
|
-
throw new Error(custom || `${opts.action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${result.status}\uFF09`);
|
|
4690
|
-
}
|
|
4904
|
+
if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
|
|
4691
4905
|
} finally {
|
|
4692
4906
|
try {
|
|
4693
4907
|
fs7.unlinkSync(scriptPath);
|
|
@@ -4711,6 +4925,7 @@ var SERVICE_OBSERVE_MS = 1200;
|
|
|
4711
4925
|
var SERVICE_HEALTH_GRACE_MS = 1800;
|
|
4712
4926
|
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
4713
4927
|
var LAUNCHCTL_TIMEOUT_MS = 5e3;
|
|
4928
|
+
var SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS = 3e3;
|
|
4714
4929
|
function serviceTarget() {
|
|
4715
4930
|
return `${bootstrapDomain()}/${SERVICE_LABEL}`;
|
|
4716
4931
|
}
|
|
@@ -4759,8 +4974,8 @@ function assertLaunchctlQueryOk(status, what) {
|
|
|
4759
4974
|
hint: [status === null ? "launchctl \u672A\u80FD\u6267\u884C\uFF08\u7F3A\u5931\u6216\u8D85\u65F6\uFF09\u3002" : "\u8FD9\u4E0D\u4EE3\u8868\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "", `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`]
|
|
4760
4975
|
});
|
|
4761
4976
|
}
|
|
4762
|
-
function isServiceDisabledInLaunchd() {
|
|
4763
|
-
const out = runLaunchctl(["print-disabled", bootstrapDomain()]);
|
|
4977
|
+
function isServiceDisabledInLaunchd(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
4978
|
+
const out = runLaunchctl(["print-disabled", bootstrapDomain()], timeoutMs);
|
|
4764
4979
|
assertLaunchctlQueryOk(out.status, "print-disabled");
|
|
4765
4980
|
return out.status === 0 ? parseDisabledList(out.stdout, SERVICE_LABEL) : false;
|
|
4766
4981
|
}
|
|
@@ -4867,16 +5082,16 @@ function ensureServiceSymlink() {
|
|
|
4867
5082
|
}
|
|
4868
5083
|
fs8.symlinkSync("mihomo", PATHS.serviceBinary);
|
|
4869
5084
|
}
|
|
4870
|
-
function runLaunchctlOrThrow(args, what) {
|
|
4871
|
-
const result = runLaunchctl(args);
|
|
5085
|
+
function runLaunchctlOrThrow(args, what, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
5086
|
+
const result = runLaunchctl(args, timeoutMs);
|
|
4872
5087
|
if (result.status === 0) return;
|
|
4873
5088
|
const detail = result.stderr.trim();
|
|
4874
5089
|
throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
|
|
4875
5090
|
hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl ${args.join(" ")}`].filter(Boolean)
|
|
4876
5091
|
});
|
|
4877
5092
|
}
|
|
4878
|
-
function bootoutService() {
|
|
4879
|
-
const result = runLaunchctl(["bootout", serviceTarget()]);
|
|
5093
|
+
function bootoutService(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
5094
|
+
const result = runLaunchctl(["bootout", serviceTarget()], timeoutMs);
|
|
4880
5095
|
if (result.status === 0 || result.status === 3 || result.status === LAUNCHCTL_NOT_LOADED) return;
|
|
4881
5096
|
const detail = result.stderr.trim();
|
|
4882
5097
|
throw new CliError(`\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B\u5931\u8D25\uFF08launchctl bootout \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
|
|
@@ -4916,7 +5131,36 @@ function cleanupRootResidue() {
|
|
|
4916
5131
|
].join("\n");
|
|
4917
5132
|
runSudoScript(script, { action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B", file: "cleanup-residue.sh", codeMessages: { 2: "\u7EC8\u6B62\u6B8B\u7559\u5185\u6838\u5931\u8D25\uFF08pkill \u9000\u51FA\u7801\u5F02\u5E38\uFF09" } });
|
|
4918
5133
|
}
|
|
4919
|
-
function
|
|
5134
|
+
function buildRootResidueCleanupError(e, ctx, rootPids) {
|
|
5135
|
+
const cancelled = e instanceof SudoAuthError;
|
|
5136
|
+
const hasKernelResidue = rootPids.length > 0;
|
|
5137
|
+
const hint = [
|
|
5138
|
+
ctx.mainOutcome,
|
|
5139
|
+
hasKernelResidue ? `root \u6B8B\u7559\u5185\u6838\u4ECD\u5728\u8FD0\u884C\uFF08PID ${rootPids.join(", ")}\uFF09\uFF0C\u53EF\u80FD\u7EE7\u7EED\u5360\u7528\u4EE3\u7406\u7AEF\u53E3` : `root \u5C5E\u4E3B\u7684 pid \u6587\u4EF6\u672A\u88AB\u6E05\u7406: ${PATHS.pidFile}`,
|
|
5140
|
+
`\u91CD\u65B0\u8FD0\u884C\u53EF\u518D\u6B21\u5C1D\u8BD5\u6E05\u7406: ${ctx.retryCommand}`
|
|
5141
|
+
];
|
|
5142
|
+
hint.push(hasKernelResidue ? "\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo" : `\u624B\u52A8\u6E05\u7406: sudo rm -f ${PATHS.pidFile}`);
|
|
5143
|
+
if (cancelled) {
|
|
5144
|
+
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 });
|
|
5145
|
+
}
|
|
5146
|
+
return new CliError(e.message, { label: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B\u5931\u8D25", hint });
|
|
5147
|
+
}
|
|
5148
|
+
function currentRootResiduePids() {
|
|
5149
|
+
try {
|
|
5150
|
+
return getMihomoPids().filter(isProcessRoot);
|
|
5151
|
+
} catch {
|
|
5152
|
+
return [];
|
|
5153
|
+
}
|
|
5154
|
+
}
|
|
5155
|
+
function cleanupRootResidueOrThrow(ctx) {
|
|
5156
|
+
try {
|
|
5157
|
+
cleanupRootResidue();
|
|
5158
|
+
} catch (e) {
|
|
5159
|
+
if (e instanceof CliError) throw e;
|
|
5160
|
+
throw buildRootResidueCleanupError(e, ctx, currentRootResiduePids());
|
|
5161
|
+
}
|
|
5162
|
+
}
|
|
5163
|
+
function killResidualKernels(ctx) {
|
|
4920
5164
|
const pids = getMihomoPids();
|
|
4921
5165
|
if (pids.length === 0) return;
|
|
4922
5166
|
const rootPids = pids.filter(isProcessRoot);
|
|
@@ -4927,7 +5171,7 @@ function killResidualKernels() {
|
|
|
4927
5171
|
} catch {
|
|
4928
5172
|
}
|
|
4929
5173
|
}
|
|
4930
|
-
if (rootPids.length > 0)
|
|
5174
|
+
if (rootPids.length > 0) cleanupRootResidueOrThrow(ctx);
|
|
4931
5175
|
}
|
|
4932
5176
|
async function installService(wasRunning, stopEpochBefore) {
|
|
4933
5177
|
assertServiceLabelSafe();
|
|
@@ -5010,7 +5254,7 @@ async function startService(stopEpochBefore) {
|
|
|
5010
5254
|
]
|
|
5011
5255
|
});
|
|
5012
5256
|
}
|
|
5013
|
-
|
|
5257
|
+
cleanupRootResidueOrThrow({ mainOutcome: "\u670D\u52A1\u5C1A\u672A\u542F\u52A8", retryCommand: "mihomo start" });
|
|
5014
5258
|
bootoutService();
|
|
5015
5259
|
await waitUntilUnloaded();
|
|
5016
5260
|
rotateAndCleanupLogs();
|
|
@@ -5025,10 +5269,10 @@ async function startService(stopEpochBefore) {
|
|
|
5025
5269
|
});
|
|
5026
5270
|
return { started };
|
|
5027
5271
|
}
|
|
5028
|
-
function disableServiceAutoStart() {
|
|
5272
|
+
function disableServiceAutoStart(timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
|
|
5029
5273
|
assertServiceLabelSafe();
|
|
5030
|
-
runLaunchctlOrThrow(["disable", serviceTarget()], "\u5173\u95ED\u670D\u52A1\u81EA\u542F");
|
|
5031
|
-
if (!isServiceDisabledInLaunchd()) {
|
|
5274
|
+
runLaunchctlOrThrow(["disable", serviceTarget()], "\u5173\u95ED\u670D\u52A1\u81EA\u542F", timeoutMs);
|
|
5275
|
+
if (!isServiceDisabledInLaunchd(timeoutMs)) {
|
|
5032
5276
|
throw new CliError("\u5173\u95ED\u670D\u52A1\u81EA\u542F\u5931\u8D25\uFF1Adisable \u4F4D\u672A\u751F\u6548", {
|
|
5033
5277
|
hint: [`\u624B\u52A8\u786E\u8BA4: launchctl print-disabled ${bootstrapDomain()}`, "", "\u4E0D\u5173\u95ED\u81EA\u542F\u7684\u8BDD\uFF0C\u91CD\u542F\u540E\u670D\u52A1\u4F1A\u62FF TUN \u914D\u7F6E\u53CD\u590D\u62C9\u8D77\u5FC5\u7136\u5931\u8D25\u7684\u5185\u6838\u3002"]
|
|
5034
5278
|
});
|
|
@@ -5038,17 +5282,17 @@ function disableServiceAutoStart() {
|
|
|
5038
5282
|
async function stopService() {
|
|
5039
5283
|
assertServiceLabelSafe();
|
|
5040
5284
|
withFileLock(PATHS.serviceLock, () => {
|
|
5041
|
-
bootoutService();
|
|
5042
|
-
disableServiceAutoStart();
|
|
5285
|
+
bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5286
|
+
disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5043
5287
|
});
|
|
5044
5288
|
await waitUntilUnloaded();
|
|
5045
|
-
killResidualKernels();
|
|
5289
|
+
killResidualKernels({ mainOutcome: "\u670D\u52A1\u5DF2\u505C\u6B62\uFF0C\u767B\u5F55\u81EA\u542F\u5DF2\u5173\u95ED", retryCommand: "mihomo stop" });
|
|
5046
5290
|
}
|
|
5047
5291
|
async function uninstallService() {
|
|
5048
5292
|
assertServiceLabelSafe();
|
|
5049
5293
|
withFileLock(PATHS.serviceLock, () => {
|
|
5050
|
-
bootoutService();
|
|
5051
|
-
disableServiceAutoStart();
|
|
5294
|
+
bootoutService(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5295
|
+
disableServiceAutoStart(SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
5052
5296
|
});
|
|
5053
5297
|
await waitUntilUnloaded();
|
|
5054
5298
|
try {
|
|
@@ -5057,15 +5301,14 @@ async function uninstallService() {
|
|
|
5057
5301
|
throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
|
|
5058
5302
|
}
|
|
5059
5303
|
disableServiceAutoStart();
|
|
5060
|
-
killResidualKernels();
|
|
5304
|
+
killResidualKernels({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo stop" });
|
|
5061
5305
|
try {
|
|
5062
5306
|
fs8.rmSync(PATHS.serviceBinary, { force: true });
|
|
5063
5307
|
} catch {
|
|
5064
5308
|
}
|
|
5065
5309
|
}
|
|
5066
|
-
function
|
|
5067
|
-
|
|
5068
|
-
const script = [
|
|
5310
|
+
function buildLegacyCleanupScript() {
|
|
5311
|
+
return [
|
|
5069
5312
|
"#!/bin/bash",
|
|
5070
5313
|
// bootout 退出码分级:113=未装载(daemon 已不在,正常),其余是真实失败。
|
|
5071
5314
|
// 此前 || true 吞掉所有错误,daemon 仍在跑却继续 rm plist 并报「已清理」
|
|
@@ -5073,7 +5316,7 @@ function cleanupLegacySystemInstall() {
|
|
|
5073
5316
|
`launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || bootout_code=$?`,
|
|
5074
5317
|
`if [ $bootout_code -ne 0 ] && [ $bootout_code -ne 113 ]; then`,
|
|
5075
5318
|
` echo "launchctl bootout \u5931\u8D25\uFF08\u9000\u51FA\u7801 $bootout_code\uFF09" >&2`,
|
|
5076
|
-
` exit
|
|
5319
|
+
` exit 3`,
|
|
5077
5320
|
`fi`,
|
|
5078
5321
|
`rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
|
|
5079
5322
|
`chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
|
|
@@ -5082,7 +5325,16 @@ function cleanupLegacySystemInstall() {
|
|
|
5082
5325
|
"exit 0",
|
|
5083
5326
|
""
|
|
5084
5327
|
].join("\n");
|
|
5085
|
-
|
|
5328
|
+
}
|
|
5329
|
+
function cleanupLegacySystemInstall() {
|
|
5330
|
+
assertServiceLabelSafe();
|
|
5331
|
+
runSudoScript(buildLegacyCleanupScript(), {
|
|
5332
|
+
action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1",
|
|
5333
|
+
file: "legacy-cleanup.sh",
|
|
5334
|
+
// 3 = 脚本内 bootout 真实失败(见 buildLegacyCleanupScript 的分级);
|
|
5335
|
+
// 具体退出码已由脚本 echo 到终端,故只指向「上方输出」
|
|
5336
|
+
codeMessages: { 3: "launchctl bootout \u672A\u80FD\u5378\u8F7D\u65E7 daemon\uFF08\u8BE6\u89C1\u4E0A\u65B9\u8F93\u51FA\uFF09" }
|
|
5337
|
+
});
|
|
5086
5338
|
}
|
|
5087
5339
|
function cleanupLegacyInstallOrThrow() {
|
|
5088
5340
|
try {
|
|
@@ -5103,15 +5355,15 @@ function logOversized() {
|
|
|
5103
5355
|
}
|
|
5104
5356
|
}
|
|
5105
5357
|
async function tryHotReload() {
|
|
5106
|
-
const status = getServiceStatus();
|
|
5107
|
-
if (!status.running || status.pid === null) return false;
|
|
5108
|
-
const baseUrl = `http://127.0.0.1:${getPorts().controller}`;
|
|
5109
5358
|
const controller = new AbortController();
|
|
5110
5359
|
const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
|
|
5111
|
-
const secret = readSettings().controller_secret;
|
|
5112
|
-
const headers = { "Content-Type": "application/json" };
|
|
5113
|
-
if (secret) headers.Authorization = `Bearer ${secret}`;
|
|
5114
5360
|
try {
|
|
5361
|
+
const status = getServiceStatus();
|
|
5362
|
+
if (!status.running || status.pid === null) return false;
|
|
5363
|
+
const baseUrl = `http://127.0.0.1:${getPorts().controller}`;
|
|
5364
|
+
const secret = readSettings().controller_secret;
|
|
5365
|
+
const headers = { "Content-Type": "application/json" };
|
|
5366
|
+
if (typeof secret === "string" && secret) headers.Authorization = `Bearer ${secret}`;
|
|
5115
5367
|
const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
|
|
5116
5368
|
if (!probe.ok) return false;
|
|
5117
5369
|
const info = await probe.json();
|
|
@@ -5134,11 +5386,16 @@ async function tryHotReload() {
|
|
|
5134
5386
|
clearTimeout(timer);
|
|
5135
5387
|
}
|
|
5136
5388
|
}
|
|
5389
|
+
function concludeHotReload(stopEpochBefore, stopEpochNow) {
|
|
5390
|
+
return { hotReloaded: true, started: !shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) };
|
|
5391
|
+
}
|
|
5137
5392
|
async function restartService(stopEpochBefore) {
|
|
5138
5393
|
if (!isServiceInstalled()) {
|
|
5139
5394
|
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
|
|
5140
5395
|
}
|
|
5141
|
-
if (!logOversized() && await tryHotReload())
|
|
5396
|
+
if (!logOversized() && await tryHotReload()) {
|
|
5397
|
+
return concludeHotReload(stopEpochBefore, readStopEpoch());
|
|
5398
|
+
}
|
|
5142
5399
|
if (logOversized()) {
|
|
5143
5400
|
const archiveFile = allocateArchivePath();
|
|
5144
5401
|
try {
|
|
@@ -5248,7 +5505,7 @@ function printVersion() {
|
|
|
5248
5505
|
}
|
|
5249
5506
|
|
|
5250
5507
|
// src/commands/completion.ts
|
|
5251
|
-
import
|
|
5508
|
+
import fs12 from "fs";
|
|
5252
5509
|
import os3 from "os";
|
|
5253
5510
|
import path9 from "path";
|
|
5254
5511
|
|
|
@@ -5295,7 +5552,7 @@ function viewLogWithTail(logPath, options) {
|
|
|
5295
5552
|
tailArgs.push(logPath);
|
|
5296
5553
|
const tail = spawn("tail", tailArgs, { stdio: "inherit" });
|
|
5297
5554
|
if (follow) setSilentSigint(true);
|
|
5298
|
-
tail.on("close", (code
|
|
5555
|
+
tail.on("close", (code) => process.exit(code ?? 0));
|
|
5299
5556
|
tail.on("error", (e) => {
|
|
5300
5557
|
console.error(`\u65E0\u6CD5\u8BFB\u53D6\u65E5\u5FD7: ${e.message}`);
|
|
5301
5558
|
process.exit(1);
|
|
@@ -5432,8 +5689,12 @@ function getRunningState(serviceStatus) {
|
|
|
5432
5689
|
}
|
|
5433
5690
|
return { running: false, pid: null, kind: null, processInfo: null };
|
|
5434
5691
|
}
|
|
5435
|
-
function
|
|
5436
|
-
return
|
|
5692
|
+
function restartModeFor(state, fallbackMode) {
|
|
5693
|
+
return state.kind === "tun" ? "tun" : fallbackMode;
|
|
5694
|
+
}
|
|
5695
|
+
function restartModeOnChange() {
|
|
5696
|
+
const state = getRunningState();
|
|
5697
|
+
return state.running ? restartModeFor(state, getRuntimeMode()) : null;
|
|
5437
5698
|
}
|
|
5438
5699
|
async function launchOrRestart(mode, stopEpochBefore) {
|
|
5439
5700
|
if (mode === "tun") {
|
|
@@ -5487,6 +5748,22 @@ async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
|
|
|
5487
5748
|
// src/http.ts
|
|
5488
5749
|
var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
|
|
5489
5750
|
var MAX_ERROR_BODY_BYTES = 64 * 1024;
|
|
5751
|
+
function isHttpsUrl(url) {
|
|
5752
|
+
try {
|
|
5753
|
+
return new URL(url).protocol === "https:";
|
|
5754
|
+
} catch {
|
|
5755
|
+
return false;
|
|
5756
|
+
}
|
|
5757
|
+
}
|
|
5758
|
+
function createHttpError(status, bodyText) {
|
|
5759
|
+
const error = new Error(`HTTP ${status}`);
|
|
5760
|
+
error.response = { status };
|
|
5761
|
+
try {
|
|
5762
|
+
error.response.data = JSON.parse(bodyText.slice(0, MAX_ERROR_BODY_BYTES));
|
|
5763
|
+
} catch {
|
|
5764
|
+
}
|
|
5765
|
+
return error;
|
|
5766
|
+
}
|
|
5490
5767
|
function createHttpClient(options = {}) {
|
|
5491
5768
|
const { timeout = 6e4 } = options;
|
|
5492
5769
|
return {
|
|
@@ -5499,18 +5776,16 @@ function createHttpClient(options = {}) {
|
|
|
5499
5776
|
signal,
|
|
5500
5777
|
headers: { "User-Agent": `mihomo-cli/${VERSION}` }
|
|
5501
5778
|
});
|
|
5502
|
-
if (url
|
|
5779
|
+
if (isHttpsUrl(url) && !isHttpsUrl(response.url)) {
|
|
5503
5780
|
throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${response.url}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
|
|
5504
5781
|
}
|
|
5505
5782
|
if (!response.ok) {
|
|
5506
|
-
|
|
5507
|
-
error.response = { status: response.status };
|
|
5783
|
+
let text2 = "";
|
|
5508
5784
|
try {
|
|
5509
|
-
|
|
5510
|
-
error.response.data = JSON.parse(text2);
|
|
5785
|
+
text2 = await readBodyWithLimit(response, controller, MAX_ERROR_BODY_BYTES);
|
|
5511
5786
|
} catch {
|
|
5512
5787
|
}
|
|
5513
|
-
throw
|
|
5788
|
+
throw createHttpError(response.status, text2);
|
|
5514
5789
|
}
|
|
5515
5790
|
const declaredLen = Number(response.headers.get("content-length"));
|
|
5516
5791
|
if (Number.isFinite(declaredLen) && declaredLen > MAX_RESPONSE_BYTES) {
|
|
@@ -5955,6 +6230,7 @@ function buildStatusJson(args) {
|
|
|
5955
6230
|
}
|
|
5956
6231
|
async function printStatus(args = []) {
|
|
5957
6232
|
assertKnownFlags(args, ["-j", "--json", "--no-probe"], "status [--json] [--no-probe]");
|
|
6233
|
+
assertPositionalCount(args, 0, 1, "mihomo status [-j|--json] [--no-probe]");
|
|
5958
6234
|
const asJson = hasFlag(args, "-j", "--json");
|
|
5959
6235
|
const skipProbe = hasFlag(args, "--no-probe");
|
|
5960
6236
|
const service = getServiceStatus();
|
|
@@ -6103,6 +6379,7 @@ function resolveStartMode(args) {
|
|
|
6103
6379
|
}
|
|
6104
6380
|
async function cmdStart(args) {
|
|
6105
6381
|
assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "start [tun|mixed]");
|
|
6382
|
+
assertPositionalCount(args, 1, 1, "mihomo start [tun|mixed] [-s] [-u ms]");
|
|
6106
6383
|
const targetMode = resolveStartMode(args);
|
|
6107
6384
|
if (!hasKernel()) {
|
|
6108
6385
|
throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
@@ -6170,7 +6447,23 @@ async function cmdStart(args) {
|
|
|
6170
6447
|
}
|
|
6171
6448
|
|
|
6172
6449
|
// src/commands/shared.ts
|
|
6450
|
+
var validatedTables = /* @__PURE__ */ new WeakSet();
|
|
6451
|
+
function assertUniqueTokens(table) {
|
|
6452
|
+
if (validatedTables.has(table)) return;
|
|
6453
|
+
const owner = /* @__PURE__ */ new Map();
|
|
6454
|
+
for (const cmd of table) {
|
|
6455
|
+
for (const token of [cmd.name, ...cmd.aliases ?? []]) {
|
|
6456
|
+
const prev = owner.get(token);
|
|
6457
|
+
if (prev !== void 0) {
|
|
6458
|
+
throw new Error(`\u5B50\u547D\u4EE4\u8868\u5B58\u5728\u91CD\u590D token: "${token}"\uFF08${prev} \u4E0E ${cmd.name}\uFF09`);
|
|
6459
|
+
}
|
|
6460
|
+
owner.set(token, cmd.name);
|
|
6461
|
+
}
|
|
6462
|
+
}
|
|
6463
|
+
validatedTables.add(table);
|
|
6464
|
+
}
|
|
6173
6465
|
async function dispatchSubcommand(args, table, options) {
|
|
6466
|
+
assertUniqueTokens(table);
|
|
6174
6467
|
const action = args[1];
|
|
6175
6468
|
if (action) {
|
|
6176
6469
|
const cmd = table.find((c) => c.name === action || c.aliases?.includes(action));
|
|
@@ -6197,8 +6490,8 @@ async function confirmOrThrow(question, opts) {
|
|
|
6197
6490
|
return confirmPrompt(question);
|
|
6198
6491
|
}
|
|
6199
6492
|
async function restartToApply(args) {
|
|
6200
|
-
|
|
6201
|
-
|
|
6493
|
+
const currentMode = restartModeOnChange();
|
|
6494
|
+
if (!currentMode) return false;
|
|
6202
6495
|
console.log("");
|
|
6203
6496
|
await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
|
|
6204
6497
|
return true;
|
|
@@ -6206,8 +6499,9 @@ async function restartToApply(args) {
|
|
|
6206
6499
|
|
|
6207
6500
|
// src/commands/directory.ts
|
|
6208
6501
|
function openDirectory(args) {
|
|
6502
|
+
assertPositionalCount(args, 1, 2, "mihomo dir open [root|subs|logs|data|runtime|kernel]");
|
|
6209
6503
|
const target = args[2];
|
|
6210
|
-
if (
|
|
6504
|
+
if (target === void 0 || target === "root") {
|
|
6211
6505
|
console.log(`\u6B63\u5728\u6253\u5F00: \u6839\u76EE\u5F55 (${USER_DATA_DIR})`);
|
|
6212
6506
|
openUrl(USER_DATA_DIR);
|
|
6213
6507
|
return;
|
|
@@ -6249,6 +6543,12 @@ async function cmdDirectory(args) {
|
|
|
6249
6543
|
await dispatchSubcommand(args, SUBCOMMANDS, {
|
|
6250
6544
|
fallback: printDirectoryInfo,
|
|
6251
6545
|
onUnknown: (action) => {
|
|
6546
|
+
if (action.startsWith("-")) {
|
|
6547
|
+
throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
|
|
6548
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
6549
|
+
hint: ["\u88F8 dir \u53EA\u5C55\u793A\u76EE\u5F55\u4FE1\u606F\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo dir open [root|subs|logs|data|runtime|kernel]"]
|
|
6550
|
+
});
|
|
6551
|
+
}
|
|
6252
6552
|
const names = SUBCOMMANDS.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
6253
6553
|
const suggestion = suggestSimilar(action, names);
|
|
6254
6554
|
throw new CliError(`\u672A\u77E5\u7684\u76EE\u5F55\u5B50\u547D\u4EE4: ${action}`, {
|
|
@@ -6292,6 +6592,8 @@ function printOverwriteList() {
|
|
|
6292
6592
|
console.log("");
|
|
6293
6593
|
}
|
|
6294
6594
|
async function setOverwrite(enabled, args) {
|
|
6595
|
+
assertPositionalCount(args, 0, 2, "mihomo ow [on|off]");
|
|
6596
|
+
assertRestartOptionValues(args);
|
|
6295
6597
|
if (isOverwriteEnabled() === enabled) {
|
|
6296
6598
|
console.log(`\u8986\u5199\u914D\u7F6E\u5DF2\u662F${enabled ? "\u542F\u7528" : "\u7981\u7528"}\u72B6\u6001`);
|
|
6297
6599
|
console.log("");
|
|
@@ -6317,6 +6619,12 @@ async function cmdOverwrite(args) {
|
|
|
6317
6619
|
printOverwriteList();
|
|
6318
6620
|
},
|
|
6319
6621
|
onUnknown: (action) => {
|
|
6622
|
+
if (action.startsWith("-")) {
|
|
6623
|
+
throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
|
|
6624
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
6625
|
+
hint: ["\u88F8 ow \u53EA\u67E5\u770B\u8986\u5199\u72B6\u6001\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo ow on|off [-s] [-u ms]"]
|
|
6626
|
+
});
|
|
6627
|
+
}
|
|
6320
6628
|
const names = SUBCOMMANDS2.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
6321
6629
|
const suggestion = suggestSimilar(action, names);
|
|
6322
6630
|
throw new CliError(`\u672A\u77E5\u7684\u8986\u5199\u5B50\u547D\u4EE4: ${action}`, {
|
|
@@ -6326,92 +6634,329 @@ async function cmdOverwrite(args) {
|
|
|
6326
6634
|
});
|
|
6327
6635
|
}
|
|
6328
6636
|
|
|
6329
|
-
// src/commands/
|
|
6637
|
+
// src/commands/reset.ts
|
|
6638
|
+
import fs11 from "fs";
|
|
6639
|
+
|
|
6640
|
+
// src/process-stop.ts
|
|
6330
6641
|
import { spawnSync as spawnSync5 } from "child_process";
|
|
6331
|
-
|
|
6332
|
-
|
|
6333
|
-
|
|
6334
|
-
|
|
6642
|
+
import fs10 from "fs";
|
|
6643
|
+
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
6644
|
+
var PROCESS_WAIT_INTERVAL = 100;
|
|
6645
|
+
var BATCH_KILL_THRESHOLD = 3;
|
|
6646
|
+
function clearRuntime() {
|
|
6647
|
+
if (fs10.existsSync(DIRS.runtime)) {
|
|
6648
|
+
rmrf(DIRS.runtime);
|
|
6335
6649
|
}
|
|
6650
|
+
ensureDirs();
|
|
6336
6651
|
}
|
|
6337
|
-
function
|
|
6338
|
-
|
|
6339
|
-
if (
|
|
6340
|
-
|
|
6341
|
-
|
|
6342
|
-
|
|
6343
|
-
console.log("");
|
|
6344
|
-
return;
|
|
6345
|
-
}
|
|
6346
|
-
const activeSub = getActiveSubscription();
|
|
6347
|
-
console.log(colors.cyan("\u8BA2\u9605\u5217\u8868:"));
|
|
6348
|
-
subs.forEach((s, i) => {
|
|
6349
|
-
const rel = formatRelativeTime(s.updated_at);
|
|
6350
|
-
const time = rel ? `${formatDate(s.updated_at)}\uFF08${rel}\uFF09` : formatDate(s.updated_at);
|
|
6351
|
-
const defaultMark = activeSub && s.name === activeSub.name ? colors.green(" [\u4F7F\u7528\u4E2D]") : "";
|
|
6352
|
-
const interval = resolveUpdateInterval(s.update_interval);
|
|
6353
|
-
console.log(` ${i + 1}. ${s.name}${defaultMark}`);
|
|
6354
|
-
console.log(` ${colors.gray("\u66F4\u65B0: ")}${time} (\u95F4\u9694: ${interval}h)`);
|
|
6355
|
-
if (s.username) {
|
|
6356
|
-
console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
|
|
6357
|
-
}
|
|
6358
|
-
const traffic = formatTraffic(s.upload, s.download, s.total);
|
|
6359
|
-
if (traffic) {
|
|
6360
|
-
console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
|
|
6361
|
-
}
|
|
6362
|
-
if (s.expire !== void 0) {
|
|
6363
|
-
console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
|
|
6652
|
+
function clearPid() {
|
|
6653
|
+
if (!fs10.existsSync(PATHS.pidFile)) return;
|
|
6654
|
+
if (isPidFileOwnedByRoot()) {
|
|
6655
|
+
try {
|
|
6656
|
+
spawnSync5("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
|
|
6657
|
+
} catch {
|
|
6364
6658
|
}
|
|
6365
|
-
|
|
6366
|
-
|
|
6659
|
+
} else {
|
|
6660
|
+
try {
|
|
6661
|
+
fs10.unlinkSync(PATHS.pidFile);
|
|
6662
|
+
} catch {
|
|
6367
6663
|
}
|
|
6368
|
-
});
|
|
6369
|
-
console.log("");
|
|
6370
|
-
console.log("\u5207\u6362\u8BA2\u9605: mihomo sub use <name>");
|
|
6371
|
-
console.log("\u65B0\u589E\u8BA2\u9605: mihomo sub add <url> [name]");
|
|
6372
|
-
console.log("\u66F4\u65B0\u8BA2\u9605: mihomo sub update [name]");
|
|
6373
|
-
console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
|
|
6374
|
-
console.log("");
|
|
6375
|
-
}
|
|
6376
|
-
function assertNotFlagLike(name, usage) {
|
|
6377
|
-
if (name.startsWith("-")) {
|
|
6378
|
-
throw new CliError(`\u540D\u79F0\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934: "${name}"`, {
|
|
6379
|
-
label: "\u53C2\u6570\u9519\u8BEF",
|
|
6380
|
-
hint: ['\u4EE5 "-" \u5F00\u5934\u7684\u540D\u79F0\u4F1A\u4E0E\u547D\u4EE4\u884C\u9009\u9879\u6DF7\u6DC6\uFF0C\u5220\u9664\u65F6\u65E0\u6CD5\u6307\u5B9A\u3002', `\u7528\u6CD5: ${usage}`]
|
|
6381
|
-
});
|
|
6382
6664
|
}
|
|
6383
6665
|
}
|
|
6384
|
-
function
|
|
6385
|
-
if (!process.stdin.isTTY) return null;
|
|
6666
|
+
function killProcess(pid) {
|
|
6386
6667
|
try {
|
|
6387
|
-
|
|
6388
|
-
|
|
6389
|
-
const text = (r.stdout || "").trim();
|
|
6390
|
-
return isValidHttpUrl(text) ? text : null;
|
|
6668
|
+
process.kill(pid, "SIGKILL");
|
|
6669
|
+
return true;
|
|
6391
6670
|
} catch {
|
|
6392
|
-
return
|
|
6671
|
+
return false;
|
|
6393
6672
|
}
|
|
6394
6673
|
}
|
|
6395
|
-
|
|
6396
|
-
|
|
6397
|
-
const
|
|
6398
|
-
|
|
6399
|
-
|
|
6400
|
-
|
|
6401
|
-
|
|
6402
|
-
|
|
6403
|
-
|
|
6404
|
-
|
|
6405
|
-
|
|
6406
|
-
|
|
6407
|
-
|
|
6408
|
-
|
|
6409
|
-
|
|
6410
|
-
|
|
6411
|
-
|
|
6412
|
-
|
|
6413
|
-
|
|
6414
|
-
|
|
6674
|
+
function killAllMihomo(forceSudo = false) {
|
|
6675
|
+
const pattern = MAIN_INSTANCE_PATTERN;
|
|
6676
|
+
const argv = forceSudo ? ["sudo", ["pkill", "-9", "-f", pattern]] : ["pkill", ["-9", "-f", pattern]];
|
|
6677
|
+
const options = forceSudo ? { stdio: "inherit", timeout: SUDO_TIMEOUT_MS } : { timeout: 1e4 };
|
|
6678
|
+
try {
|
|
6679
|
+
const result = spawnSync5(argv[0], argv[1], options);
|
|
6680
|
+
if (result.error) return false;
|
|
6681
|
+
return result.status === 0 || result.status === 1;
|
|
6682
|
+
} catch {
|
|
6683
|
+
return false;
|
|
6684
|
+
}
|
|
6685
|
+
}
|
|
6686
|
+
async function cleanupAll(forceSudo = false) {
|
|
6687
|
+
const pids = getMihomoPids();
|
|
6688
|
+
if (pids.length === 0) {
|
|
6689
|
+
clearPid();
|
|
6690
|
+
return { killed: 0, failed: 0, remaining: [] };
|
|
6691
|
+
}
|
|
6692
|
+
const hasRootProcess = pids.some((p) => isProcessRoot(p));
|
|
6693
|
+
const needsSudo = forceSudo || hasRootProcess;
|
|
6694
|
+
let killedCount = 0;
|
|
6695
|
+
const failedPids = [];
|
|
6696
|
+
if (needsSudo) {
|
|
6697
|
+
const success = killAllMihomo(true);
|
|
6698
|
+
if (success) {
|
|
6699
|
+
killedCount = pids.length;
|
|
6700
|
+
} else {
|
|
6701
|
+
failedPids.push(...pids);
|
|
6702
|
+
}
|
|
6703
|
+
} else {
|
|
6704
|
+
if (pids.length > BATCH_KILL_THRESHOLD) {
|
|
6705
|
+
if (killAllMihomo(false)) {
|
|
6706
|
+
killedCount = pids.length;
|
|
6707
|
+
} else {
|
|
6708
|
+
failedPids.push(...pids);
|
|
6709
|
+
}
|
|
6710
|
+
} else {
|
|
6711
|
+
for (const pid of pids) {
|
|
6712
|
+
if (killProcess(pid)) {
|
|
6713
|
+
killedCount++;
|
|
6714
|
+
} else {
|
|
6715
|
+
failedPids.push(pid);
|
|
6716
|
+
}
|
|
6717
|
+
}
|
|
6718
|
+
}
|
|
6719
|
+
}
|
|
6720
|
+
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
6721
|
+
if (getMihomoPids().length === 0) break;
|
|
6722
|
+
await sleep(PROCESS_WAIT_INTERVAL);
|
|
6723
|
+
}
|
|
6724
|
+
clearPid();
|
|
6725
|
+
return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
|
|
6726
|
+
}
|
|
6727
|
+
async function stop(forceSudo = false) {
|
|
6728
|
+
const allPids = getMihomoPids();
|
|
6729
|
+
if (allPids.length === 0) {
|
|
6730
|
+
clearPid();
|
|
6731
|
+
clearRuntime();
|
|
6732
|
+
return { success: true, notRunning: true };
|
|
6733
|
+
}
|
|
6734
|
+
const result = await cleanupAll(forceSudo);
|
|
6735
|
+
const remaining = getMihomoPids();
|
|
6736
|
+
if (remaining.length > 0) {
|
|
6737
|
+
console.log("");
|
|
6738
|
+
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
6739
|
+
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
6740
|
+
console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
|
|
6741
|
+
console.log("");
|
|
6742
|
+
return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
|
|
6743
|
+
}
|
|
6744
|
+
clearRuntime();
|
|
6745
|
+
return { success: true, killed: result.killed };
|
|
6746
|
+
}
|
|
6747
|
+
|
|
6748
|
+
// src/commands/reset.ts
|
|
6749
|
+
var RESET_TARGETS = [
|
|
6750
|
+
{ id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
|
|
6751
|
+
{ id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
|
|
6752
|
+
{ id: "data", aliases: ["data"], label: "\u8FD0\u884C\u6570\u636E", paths: () => [DIRS.data], needsStop: true },
|
|
6753
|
+
{ id: "runtime", aliases: ["runtime"], label: "\u8FD0\u884C\u65F6", paths: () => [DIRS.runtime], needsStop: true },
|
|
6754
|
+
{
|
|
6755
|
+
id: "overwrites",
|
|
6756
|
+
aliases: ["overwrite", "overwrites", "ow"],
|
|
6757
|
+
label: "\u8986\u5199",
|
|
6758
|
+
needsStop: false,
|
|
6759
|
+
preserveOnBare: true,
|
|
6760
|
+
paths: () => fs11.existsSync(USER_DATA_DIR) ? fs11.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
|
|
6761
|
+
},
|
|
6762
|
+
{
|
|
6763
|
+
id: "settings",
|
|
6764
|
+
aliases: ["setting", "settings", "config"],
|
|
6765
|
+
label: "\u8BBE\u7F6E",
|
|
6766
|
+
needsStop: false,
|
|
6767
|
+
preserveOnBare: true,
|
|
6768
|
+
// 损坏备份也包含订阅凭据,需要一起删除
|
|
6769
|
+
paths: () => [PATHS.settingsFile, `${PATHS.settingsFile}.bak`]
|
|
6770
|
+
},
|
|
6771
|
+
{ id: "kernel", aliases: ["kernel", "core"], label: "\u5185\u6838", paths: () => [DIRS.kernel], needsStop: true, preserveOnBare: true },
|
|
6772
|
+
{ id: "service", aliases: ["service"], label: "\u670D\u52A1", paths: () => [], needsStop: false, preserveOnBare: true }
|
|
6773
|
+
];
|
|
6774
|
+
function resolveResetTargets(names) {
|
|
6775
|
+
const matched = /* @__PURE__ */ new Set();
|
|
6776
|
+
for (const name of names) {
|
|
6777
|
+
const target = RESET_TARGETS.find((t) => t.aliases.includes(name.toLowerCase()));
|
|
6778
|
+
if (!target) {
|
|
6779
|
+
throw new CliError(`\u672A\u77E5\u7684\u91CD\u7F6E\u76EE\u6807: ${name}`, { hint: [`\u53EF\u7528\u76EE\u6807: ${RESET_TARGETS.map((t) => t.id).join(", ")}`] });
|
|
6780
|
+
}
|
|
6781
|
+
matched.add(target);
|
|
6782
|
+
}
|
|
6783
|
+
return [...matched];
|
|
6784
|
+
}
|
|
6785
|
+
async function cmdReset(args) {
|
|
6786
|
+
assertKnownFlags(args, ["--full", "--yes", "-y"], "reset [\u76EE\u6807...] [--full] [-y]");
|
|
6787
|
+
const names = args.slice(1).filter((a) => !a.startsWith("-"));
|
|
6788
|
+
const namedTargets = resolveResetTargets(names);
|
|
6789
|
+
const targets = args.includes("--full") ? RESET_TARGETS : names.length > 0 ? namedTargets : RESET_TARGETS.filter((t) => !t.preserveOnBare);
|
|
6790
|
+
const ids = new Set(targets.map((t) => t.id));
|
|
6791
|
+
const needsStop = targets.some((t) => t.needsStop);
|
|
6792
|
+
const serviceTargeted = ids.has("service");
|
|
6793
|
+
const service = getServiceStatus();
|
|
6794
|
+
const serviceActive = service.installed || service.loaded;
|
|
6795
|
+
const legacy = detectLegacySystemInstall();
|
|
6796
|
+
if (targets.length === 1) {
|
|
6797
|
+
if (serviceTargeted && !serviceActive && !legacy) {
|
|
6798
|
+
console.log("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664");
|
|
6799
|
+
return;
|
|
6800
|
+
}
|
|
6801
|
+
}
|
|
6802
|
+
if (ids.has("kernel") && getMihomoPids().length > 0) {
|
|
6803
|
+
console.log(colors.yellow("\u5C06\u505C\u6B62\u6B63\u5728\u8FD0\u884C\u7684\u5185\u6838\uFF0C\u5220\u9664\u540E\u9700\u91CD\u65B0\u4E0B\u8F7D\u624D\u80FD\u542F\u52A8"));
|
|
6804
|
+
}
|
|
6805
|
+
if (serviceTargeted && serviceActive) {
|
|
6806
|
+
console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
|
|
6807
|
+
} else if (needsStop && serviceActive) {
|
|
6808
|
+
console.log(colors.yellow("\u5C06\u505C\u6B62\u670D\u52A1\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF08\u5B89\u88C5\u4FDD\u7559\uFF0Cmihomo start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09"));
|
|
6809
|
+
}
|
|
6810
|
+
if ((needsStop || serviceTargeted) && legacy) {
|
|
6811
|
+
console.log(colors.yellow("\u5C06\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF0C\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
|
|
6812
|
+
}
|
|
6813
|
+
console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
|
|
6814
|
+
if (!args.includes("-y") && !args.includes("--yes") && !await confirmOrThrow("\u786E\u8BA4?", {
|
|
6815
|
+
nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
|
|
6816
|
+
hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
|
|
6817
|
+
})) {
|
|
6818
|
+
console.log("\u5DF2\u53D6\u6D88");
|
|
6819
|
+
return;
|
|
6820
|
+
}
|
|
6821
|
+
if ((needsStop || serviceTargeted) && legacy) cleanupLegacyInstallOrThrow();
|
|
6822
|
+
if (serviceActive) {
|
|
6823
|
+
if (serviceTargeted) await uninstallService();
|
|
6824
|
+
else if (needsStop) await stopService();
|
|
6825
|
+
}
|
|
6826
|
+
if (needsStop) {
|
|
6827
|
+
const cleanup = await cleanupAll();
|
|
6828
|
+
if (cleanup.remaining.length > 0) {
|
|
6829
|
+
throw new CliError(cleanup.remaining.join(", "), {
|
|
6830
|
+
label: "\u8FDB\u7A0B\u672A\u80FD\u505C\u6B62\uFF0C\u91CD\u7F6E\u4E2D\u6B62",
|
|
6831
|
+
hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
|
|
6832
|
+
});
|
|
6833
|
+
}
|
|
6834
|
+
recordServiceStopped();
|
|
6835
|
+
}
|
|
6836
|
+
const deleted = /* @__PURE__ */ new Set();
|
|
6837
|
+
for (const target of targets) {
|
|
6838
|
+
let hadContent = target.id === "service" && (serviceActive || legacy);
|
|
6839
|
+
for (const filePath of target.paths()) {
|
|
6840
|
+
if (!fs11.existsSync(filePath)) continue;
|
|
6841
|
+
try {
|
|
6842
|
+
rmrf(filePath);
|
|
6843
|
+
} catch (e) {
|
|
6844
|
+
throw new CliError(`\u65E0\u6CD5\u5220\u9664 ${filePath}: ${e.message}`, { label: "\u91CD\u7F6E\u5931\u8D25" });
|
|
6845
|
+
}
|
|
6846
|
+
hadContent = true;
|
|
6847
|
+
}
|
|
6848
|
+
if (hadContent) deleted.add(target.id);
|
|
6849
|
+
}
|
|
6850
|
+
if (!ids.has("settings") && (ids.has("subs") || ids.has("overwrites"))) {
|
|
6851
|
+
updateSettings((settings) => {
|
|
6852
|
+
const patch = {};
|
|
6853
|
+
if (ids.has("subs") && (settings.subscriptions !== void 0 || settings.active_subscription !== void 0)) {
|
|
6854
|
+
patch.subscriptions = void 0;
|
|
6855
|
+
patch.active_subscription = void 0;
|
|
6856
|
+
deleted.add("subs");
|
|
6857
|
+
}
|
|
6858
|
+
if (ids.has("overwrites") && settings.overwrite_enabled !== void 0) {
|
|
6859
|
+
patch.overwrite_enabled = void 0;
|
|
6860
|
+
deleted.add("overwrites");
|
|
6861
|
+
}
|
|
6862
|
+
return patch;
|
|
6863
|
+
});
|
|
6864
|
+
}
|
|
6865
|
+
if (ids.has("kernel")) clearKernelVersionCache();
|
|
6866
|
+
ensureDirs();
|
|
6867
|
+
const labels = targets.filter((t) => deleted.has(t.id)).map((t) => t.label);
|
|
6868
|
+
console.log(labels.length > 0 ? colors.green(`\u5DF2\u91CD\u7F6E: ${labels.join("\u3001")}`) : "\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
|
|
6869
|
+
}
|
|
6870
|
+
|
|
6871
|
+
// src/commands/subscription.ts
|
|
6872
|
+
import { spawnSync as spawnSync6 } from "child_process";
|
|
6873
|
+
function printRestartHintIfRunning() {
|
|
6874
|
+
const state = getRunningState();
|
|
6875
|
+
if (state.running) {
|
|
6876
|
+
const hintCommand = state.kind === "tun" ? "mihomo start tun" : "mihomo start";
|
|
6877
|
+
console.log(colors.yellow(`\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5B9E\u4F8B\u4ECD\u4F7F\u7528\u65E7\u914D\u7F6E\uFF0C\u6267\u884C ${hintCommand} \u4F7F\u66F4\u65B0\u751F\u6548`));
|
|
6878
|
+
console.log("");
|
|
6879
|
+
}
|
|
6880
|
+
}
|
|
6881
|
+
function printSubscriptionList() {
|
|
6882
|
+
const subs = getSubscriptionsWithCache();
|
|
6883
|
+
if (subs.length === 0) {
|
|
6884
|
+
console.log("\u6CA1\u6709\u8BA2\u9605");
|
|
6885
|
+
console.log("");
|
|
6886
|
+
console.log("\u6DFB\u52A0\u8BA2\u9605: mihomo sub add <url> [name]");
|
|
6887
|
+
console.log("");
|
|
6888
|
+
return;
|
|
6889
|
+
}
|
|
6890
|
+
const activeSub = getActiveSubscription();
|
|
6891
|
+
console.log(colors.cyan("\u8BA2\u9605\u5217\u8868:"));
|
|
6892
|
+
subs.forEach((s, i) => {
|
|
6893
|
+
const rel = formatRelativeTime(s.updated_at);
|
|
6894
|
+
const time = rel ? `${formatDate(s.updated_at)}\uFF08${rel}\uFF09` : formatDate(s.updated_at);
|
|
6895
|
+
const defaultMark = activeSub && s.name === activeSub.name ? colors.green(" [\u4F7F\u7528\u4E2D]") : "";
|
|
6896
|
+
const interval = resolveUpdateInterval(s.update_interval);
|
|
6897
|
+
console.log(` ${i + 1}. ${s.name}${defaultMark}`);
|
|
6898
|
+
console.log(` ${colors.gray("\u66F4\u65B0: ")}${time} (\u95F4\u9694: ${interval}h)`);
|
|
6899
|
+
if (s.username) {
|
|
6900
|
+
console.log(` ${colors.gray("\u7528\u6237: ")}${s.username}`);
|
|
6901
|
+
}
|
|
6902
|
+
const traffic = formatTraffic(s.upload, s.download, s.total);
|
|
6903
|
+
if (traffic) {
|
|
6904
|
+
console.log(` ${colors.gray("\u6D41\u91CF: ")}${traffic}`);
|
|
6905
|
+
}
|
|
6906
|
+
if (s.expire !== void 0) {
|
|
6907
|
+
console.log(` ${colors.gray("\u5230\u671F: ")}${formatTimestamp(s.expire)}`);
|
|
6908
|
+
}
|
|
6909
|
+
if (s.web_page_url) {
|
|
6910
|
+
console.log(` ${colors.gray("\u9875\u9762: ")}${s.web_page_url}`);
|
|
6911
|
+
}
|
|
6912
|
+
});
|
|
6913
|
+
console.log("");
|
|
6914
|
+
console.log("\u5207\u6362\u8BA2\u9605: mihomo sub use <name>");
|
|
6915
|
+
console.log("\u65B0\u589E\u8BA2\u9605: mihomo sub add <url> [name]");
|
|
6916
|
+
console.log("\u66F4\u65B0\u8BA2\u9605: mihomo sub update [name]");
|
|
6917
|
+
console.log("\u5220\u9664\u8BA2\u9605: mihomo sub remove <name>");
|
|
6918
|
+
console.log("");
|
|
6919
|
+
}
|
|
6920
|
+
function assertNotFlagLike(name, usage) {
|
|
6921
|
+
if (name.startsWith("-")) {
|
|
6922
|
+
throw new CliError(`\u540D\u79F0\u4E0D\u80FD\u4EE5 "-" \u5F00\u5934: "${name}"`, {
|
|
6923
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
6924
|
+
hint: ['\u4EE5 "-" \u5F00\u5934\u7684\u540D\u79F0\u4F1A\u4E0E\u547D\u4EE4\u884C\u9009\u9879\u6DF7\u6DC6\uFF0C\u5220\u9664\u65F6\u65E0\u6CD5\u6307\u5B9A\u3002', `\u7528\u6CD5: ${usage}`]
|
|
6925
|
+
});
|
|
6926
|
+
}
|
|
6927
|
+
}
|
|
6928
|
+
function readUrlFromClipboard() {
|
|
6929
|
+
if (!process.stdin.isTTY) return null;
|
|
6930
|
+
try {
|
|
6931
|
+
const r = spawnSync6("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
|
|
6932
|
+
if (r.status !== 0) return null;
|
|
6933
|
+
const text = (r.stdout || "").trim();
|
|
6934
|
+
return isValidHttpUrl(text) ? text : null;
|
|
6935
|
+
} catch {
|
|
6936
|
+
return null;
|
|
6937
|
+
}
|
|
6938
|
+
}
|
|
6939
|
+
async function subAdd(args) {
|
|
6940
|
+
assertPositionalCount(args, 2, 2, "mihomo sub add <url> [name]");
|
|
6941
|
+
let url = args[2]?.trim();
|
|
6942
|
+
const name = args[3] || "default";
|
|
6943
|
+
if (!url) {
|
|
6944
|
+
const clipped = readUrlFromClipboard();
|
|
6945
|
+
if (clipped) {
|
|
6946
|
+
console.log("\u672A\u63D0\u4F9B URL\uFF0C\u4ECE\u526A\u8D34\u677F\u8BFB\u53D6\u5230:");
|
|
6947
|
+
console.log(` ${maskUrl(clipped)}`);
|
|
6948
|
+
if (!await confirmPrompt(`\u6DFB\u52A0\u4E3A\u8BA2\u9605 "${name}"?`)) {
|
|
6949
|
+
console.log("\u5DF2\u53D6\u6D88");
|
|
6950
|
+
return;
|
|
6951
|
+
}
|
|
6952
|
+
url = clipped;
|
|
6953
|
+
} else if (process.stdin.isTTY) {
|
|
6954
|
+
throw new CliError("\u526A\u8D34\u677F\u4E2D\u6CA1\u6709\u6709\u6548\u7684\u8BA2\u9605 URL", {
|
|
6955
|
+
hint: ["\u5148\u590D\u5236\u8BA2\u9605\u94FE\u63A5\u540E\u91CD\u8BD5\uFF0C\u6216\u663E\u5F0F\u4F20\u5165:", " mihomo sub add <url> [name]"]
|
|
6956
|
+
});
|
|
6957
|
+
} else {
|
|
6958
|
+
throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL", { hint: ["\u7528\u6CD5: mihomo sub add <url> [name]"] });
|
|
6959
|
+
}
|
|
6415
6960
|
}
|
|
6416
6961
|
if (!isValidHttpUrl(url)) {
|
|
6417
6962
|
throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
|
|
@@ -6433,12 +6978,16 @@ async function subAdd(args) {
|
|
|
6433
6978
|
printSubscriptionList();
|
|
6434
6979
|
}
|
|
6435
6980
|
async function subUpdate(args) {
|
|
6436
|
-
|
|
6981
|
+
assertPositionalCount(args, 1, 2, "mihomo sub update [name]");
|
|
6982
|
+
const nameArg = getNonFlagArg(args, 2);
|
|
6437
6983
|
const subs = getSubscriptions();
|
|
6438
6984
|
if (subs.length === 0) {
|
|
6439
6985
|
throw new CliError("\u6CA1\u6709\u8BA2\u9605");
|
|
6440
6986
|
}
|
|
6441
|
-
if (
|
|
6987
|
+
if (nameArg === "") {
|
|
6988
|
+
throw new CliError("\u8BF7\u6307\u5B9A\u8BA2\u9605\u540D\u79F0", { hint: ["\u66F4\u65B0\u6240\u6709\u8BA2\u9605\u76F4\u63A5\u6267\u884C: mihomo sub update", `\u66F4\u65B0\u6307\u5B9A\u8BA2\u9605: mihomo sub update <\u540D\u79F0>`] });
|
|
6989
|
+
}
|
|
6990
|
+
if (nameArg === null) {
|
|
6442
6991
|
console.log(`\u66F4\u65B0\u6240\u6709 ${subs.length} \u4E2A\u8BA2\u9605...`);
|
|
6443
6992
|
const results = await withSpinner("\u5E76\u884C\u66F4\u65B0\u4E2D", () => Promise.all(subs.map((sub) => tryUpdateOne(sub))));
|
|
6444
6993
|
let ok = 0;
|
|
@@ -6452,7 +7001,7 @@ async function subUpdate(args) {
|
|
|
6452
7001
|
printSubscriptionList();
|
|
6453
7002
|
return;
|
|
6454
7003
|
}
|
|
6455
|
-
const target = resolveSubscription(subs,
|
|
7004
|
+
const target = resolveSubscription(subs, nameArg);
|
|
6456
7005
|
console.log(`\u66F4\u65B0\u8BA2\u9605: ${target.name}`);
|
|
6457
7006
|
const result = await withSpinner("\u4E0B\u8F7D\u8BA2\u9605", () => tryUpdateOne(target));
|
|
6458
7007
|
if (!result.success) {
|
|
@@ -6464,6 +7013,8 @@ async function subUpdate(args) {
|
|
|
6464
7013
|
printSubscriptionList();
|
|
6465
7014
|
}
|
|
6466
7015
|
async function subUse(args) {
|
|
7016
|
+
assertPositionalCount(args, 1, 2, "mihomo sub use <name>");
|
|
7017
|
+
assertRestartOptionValues(args);
|
|
6467
7018
|
const name = getNonFlagArg(args, 2);
|
|
6468
7019
|
const subs = getSubscriptions();
|
|
6469
7020
|
if (subs.length === 0) {
|
|
@@ -6493,6 +7044,7 @@ async function subUse(args) {
|
|
|
6493
7044
|
printSubscriptionList();
|
|
6494
7045
|
}
|
|
6495
7046
|
async function subRemove(args) {
|
|
7047
|
+
assertPositionalCount(args, 1, 2, "mihomo sub remove <name>");
|
|
6496
7048
|
const name = getNonFlagArg(args, 2);
|
|
6497
7049
|
const subs = getSubscriptions();
|
|
6498
7050
|
if (!name) {
|
|
@@ -6521,18 +7073,31 @@ async function subRemove(args) {
|
|
|
6521
7073
|
console.log("");
|
|
6522
7074
|
printSubscriptionList();
|
|
6523
7075
|
}
|
|
7076
|
+
var USE_FLAGS = START_RESTART_FLAGS.flatMap((f) => f.forms);
|
|
7077
|
+
var REMOVE_FLAGS = ["-y", "--yes"];
|
|
7078
|
+
function withKnownFlags(usage, known, handler) {
|
|
7079
|
+
return async (args) => {
|
|
7080
|
+
assertKnownFlags(args, known, usage);
|
|
7081
|
+
await handler(args);
|
|
7082
|
+
};
|
|
7083
|
+
}
|
|
6524
7084
|
var SUBCOMMANDS3 = [
|
|
6525
|
-
{ name: "add", description: "\u6DFB\u52A0\u8BA2\u9605", handler: subAdd },
|
|
6526
|
-
{ name: "update", description: "\u66F4\u65B0\u8BA2\u9605", handler: subUpdate },
|
|
6527
|
-
{ name: "use", description: "\u5207\u6362\u8BA2\u9605", handler: subUse },
|
|
6528
|
-
{ name: "remove", aliases: ["rm", "delete"], description: "\u5220\u9664\u8BA2\u9605", handler: subRemove }
|
|
7085
|
+
{ name: "add", description: "\u6DFB\u52A0\u8BA2\u9605", handler: withKnownFlags("sub add <url> [name]", [], subAdd) },
|
|
7086
|
+
{ name: "update", description: "\u66F4\u65B0\u8BA2\u9605", handler: withKnownFlags("sub update [name]", [], subUpdate) },
|
|
7087
|
+
{ name: "use", description: "\u5207\u6362\u8BA2\u9605", handler: withKnownFlags("sub use <name>", USE_FLAGS, subUse) },
|
|
7088
|
+
{ name: "remove", aliases: ["rm", "delete"], description: "\u5220\u9664\u8BA2\u9605", handler: withKnownFlags("sub remove <name>", REMOVE_FLAGS, subRemove) }
|
|
6529
7089
|
];
|
|
6530
7090
|
async function cmdSubscription(args) {
|
|
6531
|
-
assertKnownFlags(args, ["-y", "--yes", "-s", "--no-update", "-u", "--update-timeout"], "sub [add|update|use|remove]");
|
|
6532
7091
|
await dispatchSubcommand(args, SUBCOMMANDS3, {
|
|
6533
7092
|
// 无子命令 → 列表;未知子命令 → 报错
|
|
6534
7093
|
fallback: printSubscriptionList,
|
|
6535
7094
|
onUnknown: (action) => {
|
|
7095
|
+
if (action.startsWith("-")) {
|
|
7096
|
+
throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${action}`, {
|
|
7097
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
7098
|
+
hint: ["\u88F8 sub \u53EA\u5217\u51FA\u8BA2\u9605\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo sub [use|add|update|remove]\uFF08\u88F8 sub \u5373\u5217\u8868\uFF09"]
|
|
7099
|
+
});
|
|
7100
|
+
}
|
|
6536
7101
|
const names = SUBCOMMANDS3.flatMap((c) => [c.name, ...c.aliases ?? []]);
|
|
6537
7102
|
const suggestion = suggestSimilar(action, names);
|
|
6538
7103
|
throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
|
|
@@ -6559,8 +7124,10 @@ function subGroups(commands) {
|
|
|
6559
7124
|
};
|
|
6560
7125
|
return [groupOf("subscription", SUBCOMMANDS3), groupOf("overwrite", SUBCOMMANDS2), groupOf("directory", SUBCOMMANDS)];
|
|
6561
7126
|
}
|
|
6562
|
-
var DIR_TARGETS =
|
|
6563
|
-
var UI_NAMES =
|
|
7127
|
+
var DIR_TARGETS = Object.keys(DIRECTORY_TARGETS);
|
|
7128
|
+
var UI_NAMES = Object.keys(UI_URLS);
|
|
7129
|
+
var MIRROR_NAMES = Object.keys(MIRROR_ALIASES);
|
|
7130
|
+
var RESET_TARGET_NAMES = [...new Set(RESET_TARGETS.flatMap((t) => t.aliases))];
|
|
6564
7131
|
var SHELLS = ["zsh", "bash", "fish"];
|
|
6565
7132
|
function buildZsh(commands, groups) {
|
|
6566
7133
|
const lines = [
|
|
@@ -6614,11 +7181,11 @@ function buildZsh(commands, groups) {
|
|
|
6614
7181
|
` _values 'ui' ${UI_NAMES.join(" ")}`,
|
|
6615
7182
|
" ;;",
|
|
6616
7183
|
" kernel)",
|
|
6617
|
-
|
|
7184
|
+
` _arguments '--mirror[\u8D70\u955C\u50CF\u4E0B\u8F7D]:\u955C\u50CF:(${MIRROR_NAMES.join(" ")})'`,
|
|
6618
7185
|
" ;;",
|
|
6619
7186
|
" reset)",
|
|
6620
|
-
` _values 'target'
|
|
6621
|
-
" _arguments '-y[\u8DF3\u8FC7\u786E\u8BA4]' '--full[\u5220\u5168\u90E8]'",
|
|
7187
|
+
` _values 'target' ${RESET_TARGET_NAMES.join(" ")}`,
|
|
7188
|
+
" _arguments '-y[\u8DF3\u8FC7\u786E\u8BA4]' '--yes[\u8DF3\u8FC7\u786E\u8BA4]' '--full[\u5220\u5168\u90E8]'",
|
|
6622
7189
|
" ;;",
|
|
6623
7190
|
" completion)",
|
|
6624
7191
|
" if (( CURRENT == 2 )); then",
|
|
@@ -6681,10 +7248,14 @@ ${subCase}
|
|
|
6681
7248
|
COMPREPLY=( $(compgen -W "${UI_NAMES.join(" ")}" -- "\${cur}") )
|
|
6682
7249
|
;;
|
|
6683
7250
|
kernel)
|
|
6684
|
-
|
|
7251
|
+
if [[ "\${prev}" == "--mirror" ]]; then
|
|
7252
|
+
COMPREPLY=( $(compgen -W "${MIRROR_NAMES.join(" ")}" -- "\${cur}") )
|
|
7253
|
+
else
|
|
7254
|
+
COMPREPLY=( $(compgen -W "--mirror" -- "\${cur}") )
|
|
7255
|
+
fi
|
|
6685
7256
|
;;
|
|
6686
7257
|
reset)
|
|
6687
|
-
COMPREPLY=( $(compgen -W "
|
|
7258
|
+
COMPREPLY=( $(compgen -W "${RESET_TARGET_NAMES.join(" ")} --full -y --yes" -- "\${cur}") )
|
|
6688
7259
|
;;
|
|
6689
7260
|
completion)
|
|
6690
7261
|
if [[ \${COMP_CWORD} -eq 2 ]]; then
|
|
@@ -6709,15 +7280,21 @@ function buildFish(commands, groups) {
|
|
|
6709
7280
|
}
|
|
6710
7281
|
for (const group of groups) {
|
|
6711
7282
|
const seen = group.tokens.join(" ");
|
|
7283
|
+
const condition = group.tokens.includes("directory") ? `${seen}; and not __fish_seen_subcommand_from open` : seen;
|
|
6712
7284
|
for (const s of group.words) {
|
|
6713
|
-
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${
|
|
7285
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${condition}" -a '${s.word}' -d '${s.desc.replace(/'/g, "\\'")}'`);
|
|
6714
7286
|
}
|
|
6715
7287
|
}
|
|
6716
|
-
lines.push(
|
|
6717
|
-
|
|
7288
|
+
lines.push(
|
|
7289
|
+
` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories; and __fish_seen_subcommand_from open" -a '${DIR_TARGETS.join(" ")}'`
|
|
7290
|
+
);
|
|
7291
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui; and not __fish_seen_subcommand_from ${UI_NAMES.join(" ")}" -a '${UI_NAMES.join(" ")}'`);
|
|
6718
7292
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install uninstall ${SHELLS.join(" ")}' -d '\u5B89\u88C5/\u5378\u8F7D\u8865\u5168'`);
|
|
6719
7293
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion; and __fish_seen_subcommand_from install uninstall" -a '${SHELLS.join(" ")}'`);
|
|
6720
|
-
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -
|
|
7294
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -l mirror -d '\u8D70\u955C\u50CF\u4E0B\u8F7D' -a '${MIRROR_NAMES.join(" ")}'`);
|
|
7295
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from reset" -a '${RESET_TARGET_NAMES.join(" ")}'`);
|
|
7296
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from reset" -s y -l yes -d '\u8DF3\u8FC7\u786E\u8BA4'`);
|
|
7297
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from reset" -l full -d '\u5220\u5168\u90E8'`);
|
|
6721
7298
|
lines.push("end");
|
|
6722
7299
|
return lines.join("\n");
|
|
6723
7300
|
}
|
|
@@ -6747,8 +7324,10 @@ function completionInstallPath(shell) {
|
|
|
6747
7324
|
return path9.join(home, ".zsh", "completions", "_mihomo");
|
|
6748
7325
|
case "bash":
|
|
6749
7326
|
return path9.join(home, ".bash_completion");
|
|
6750
|
-
case "fish":
|
|
6751
|
-
|
|
7327
|
+
case "fish": {
|
|
7328
|
+
const fishConfigDir = process.env.XDG_CONFIG_HOME ? path9.join(process.env.XDG_CONFIG_HOME, "fish") : path9.join(home, ".config", "fish");
|
|
7329
|
+
return path9.join(fishConfigDir, "completions", "mihomo.fish");
|
|
7330
|
+
}
|
|
6752
7331
|
default:
|
|
6753
7332
|
return null;
|
|
6754
7333
|
}
|
|
@@ -6766,21 +7345,21 @@ function installCompletion(shell, commands) {
|
|
|
6766
7345
|
console.log(`\u5B89\u88C5 ${shell} \u8865\u5168: ${target}`);
|
|
6767
7346
|
try {
|
|
6768
7347
|
if (shell === "bash") {
|
|
6769
|
-
const existing =
|
|
7348
|
+
const existing = fs12.existsSync(target) ? fs12.readFileSync(target, "utf8") : "";
|
|
6770
7349
|
if (existing.includes(BASH_MARKER)) {
|
|
6771
7350
|
console.log("\u5DF2\u5B89\u88C5\u8FC7\uFF08~/.bash_completion \u5DF2\u5305\u542B mihomo \u8865\u5168\uFF09\uFF0C\u8DF3\u8FC7");
|
|
6772
7351
|
return;
|
|
6773
7352
|
}
|
|
6774
|
-
|
|
6775
|
-
|
|
7353
|
+
fs12.mkdirSync(path9.dirname(target), { recursive: true });
|
|
7354
|
+
fs12.appendFileSync(target, `
|
|
6776
7355
|
${BASH_MARKER}
|
|
6777
7356
|
${script}${BASH_MARKER.replace(">>>", "<<<")}
|
|
6778
7357
|
`);
|
|
6779
7358
|
console.log(colors.green("\u5DF2\u8FFD\u52A0\u5230 ~/.bash_completion\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6780
7359
|
return;
|
|
6781
7360
|
}
|
|
6782
|
-
|
|
6783
|
-
|
|
7361
|
+
fs12.mkdirSync(path9.dirname(target), { recursive: true });
|
|
7362
|
+
fs12.writeFileSync(target, script, { mode: 420 });
|
|
6784
7363
|
console.log(colors.green("\u5DF2\u5199\u5165\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6785
7364
|
} catch (e) {
|
|
6786
7365
|
throw new CliError(`\u8865\u5168\u5B89\u88C5\u5931\u8D25: ${e.message}`, {
|
|
@@ -6801,14 +7380,14 @@ function uninstallCompletion(shell, commands) {
|
|
|
6801
7380
|
buildCompletionScript(shell, commands);
|
|
6802
7381
|
return;
|
|
6803
7382
|
}
|
|
6804
|
-
if (!
|
|
7383
|
+
if (!fs12.existsSync(target)) {
|
|
6805
7384
|
console.log(`\u672A\u5B89\u88C5 ${shell} \u8865\u5168\uFF08${target} \u4E0D\u5B58\u5728\uFF09`);
|
|
6806
7385
|
return;
|
|
6807
7386
|
}
|
|
6808
7387
|
console.log(`\u5378\u8F7D ${shell} \u8865\u5168: ${target}`);
|
|
6809
7388
|
try {
|
|
6810
7389
|
if (shell === "bash") {
|
|
6811
|
-
const existing2 =
|
|
7390
|
+
const existing2 = fs12.readFileSync(target, "utf8");
|
|
6812
7391
|
const endMarker = BASH_MARKER.replace(">>>", "<<<");
|
|
6813
7392
|
const start = existing2.indexOf(BASH_MARKER);
|
|
6814
7393
|
const end = existing2.indexOf(endMarker);
|
|
@@ -6821,23 +7400,23 @@ function uninstallCompletion(shell, commands) {
|
|
|
6821
7400
|
const after = existing2.slice(end + endMarker.length).replace(/^\n/, "");
|
|
6822
7401
|
const rest = `${before}${after}`;
|
|
6823
7402
|
if (rest.trim() === "") {
|
|
6824
|
-
|
|
7403
|
+
fs12.rmSync(target);
|
|
6825
7404
|
console.log(colors.green("\u5DF2\u79FB\u9664\uFF08\u6587\u4EF6\u5DF2\u7A7A\uFF0C\u4E00\u5E76\u5220\u9664\uFF1B\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6826
7405
|
return;
|
|
6827
7406
|
}
|
|
6828
|
-
|
|
7407
|
+
fs12.writeFileSync(target, rest);
|
|
6829
7408
|
console.log(colors.green("\u5DF2\u79FB\u9664 mihomo \u8865\u5168\u6BB5\uFF0C\u4FDD\u7559\u6587\u4EF6\u4E2D\u5176\u4F59\u5185\u5BB9\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6830
7409
|
return;
|
|
6831
7410
|
}
|
|
6832
|
-
const existing =
|
|
6833
|
-
const fingerprint = shell === "zsh" ? "#compdef mihomo" : "for cmd in mihomo";
|
|
7411
|
+
const existing = fs12.readFileSync(target, "utf8");
|
|
7412
|
+
const fingerprint = shell === "zsh" ? "#compdef mihomo mhm mh mihomo-cli" : "for cmd in mihomo mhm mh mihomo-cli";
|
|
6834
7413
|
if (!existing.includes(fingerprint)) {
|
|
6835
7414
|
throw new CliError(`${target} \u4E0D\u50CF\u662F mihomo-cli \u751F\u6210\u7684\u8865\u5168\uFF0C\u5DF2\u8DF3\u8FC7\u5220\u9664`, {
|
|
6836
7415
|
label: "\u5378\u8F7D\u4E2D\u6B62",
|
|
6837
7416
|
hint: ["\u8BE5\u6587\u4EF6\u53EF\u80FD\u662F\u4F60\u81EA\u5DF1\u6216\u5176\u4ED6\u5DE5\u5177\u5199\u7684\u3002\u786E\u8BA4\u65E0\u7528\u540E\u624B\u52A8\u5220\u9664:", ` rm ${target}`]
|
|
6838
7417
|
});
|
|
6839
7418
|
}
|
|
6840
|
-
|
|
7419
|
+
fs12.rmSync(target);
|
|
6841
7420
|
console.log(colors.green("\u5DF2\u5220\u9664\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6842
7421
|
} catch (e) {
|
|
6843
7422
|
if (e instanceof CliError) throw e;
|
|
@@ -6850,13 +7429,16 @@ function uninstallCompletion(shell, commands) {
|
|
|
6850
7429
|
function cmdCompletion(args, commands) {
|
|
6851
7430
|
assertKnownFlags(args.slice(1), [], "completion");
|
|
6852
7431
|
if (args[1] === "install") {
|
|
7432
|
+
assertPositionalCount(args, 1, 2, `mihomo completion install <${SHELLS.join("|")}>`);
|
|
6853
7433
|
installCompletion(args[2], commands);
|
|
6854
7434
|
return;
|
|
6855
7435
|
}
|
|
6856
7436
|
if (args[1] === "uninstall") {
|
|
7437
|
+
assertPositionalCount(args, 1, 2, `mihomo completion uninstall <${SHELLS.join("|")}>`);
|
|
6857
7438
|
uninstallCompletion(args[2], commands);
|
|
6858
7439
|
return;
|
|
6859
7440
|
}
|
|
7441
|
+
assertPositionalCount(args, 1, 1, `mihomo completion <${SHELLS.join("|")}>`);
|
|
6860
7442
|
const shell = args[1];
|
|
6861
7443
|
if (!shell) {
|
|
6862
7444
|
throw new CliError("\u8BF7\u6307\u5B9A shell", {
|
|
@@ -6874,6 +7456,7 @@ function cmdCompletion(args, commands) {
|
|
|
6874
7456
|
// src/commands/config.ts
|
|
6875
7457
|
function cmdConfig(args = []) {
|
|
6876
7458
|
assertKnownFlags(args.slice(1), ["-j", "--json"], "config [--json]");
|
|
7459
|
+
assertPositionalCount(args, 0, 1, "mihomo config [--json]");
|
|
6877
7460
|
const asJson = hasFlag(args, "-j", "--json");
|
|
6878
7461
|
const active = getActiveSubscription();
|
|
6879
7462
|
if (!active) {
|
|
@@ -6886,14 +7469,14 @@ function cmdConfig(args = []) {
|
|
|
6886
7469
|
const mode = getConfigInfo()?.tun ? "tun" : "mixed";
|
|
6887
7470
|
const { config, warnings } = buildConfig(rawContent, mode, { subName: active.name, subUrl: active.url });
|
|
6888
7471
|
const shown = { ...config };
|
|
6889
|
-
if (
|
|
7472
|
+
if ("secret" in shown) shown.secret = "***";
|
|
6890
7473
|
if (asJson) {
|
|
6891
|
-
console.log(JSON.stringify(shown, null, 2));
|
|
7474
|
+
console.log(JSON.stringify({ config: shown, warnings }, null, 2));
|
|
6892
7475
|
return;
|
|
6893
7476
|
}
|
|
6894
7477
|
console.log(colors.gray(`# \u8BA2\u9605: ${active.name} \u6A21\u5F0F: ${mode}`));
|
|
6895
7478
|
console.log(colors.gray("# \u7531\u8BA2\u9605\u4E0E\u8986\u5199\u63A8\u5BFC\uFF0C\u4E0E start \u5199\u5165 runtime/config.yaml \u7684\u5185\u5BB9\u4E00\u81F4"));
|
|
6896
|
-
if (
|
|
7479
|
+
if ("secret" in config) {
|
|
6897
7480
|
console.log(colors.gray("# secret \u5DF2\u8131\u654F\u663E\u793A"));
|
|
6898
7481
|
}
|
|
6899
7482
|
console.log("");
|
|
@@ -6905,8 +7488,8 @@ function cmdConfig(args = []) {
|
|
|
6905
7488
|
}
|
|
6906
7489
|
|
|
6907
7490
|
// src/commands/doctor.ts
|
|
6908
|
-
import { spawnSync as
|
|
6909
|
-
import
|
|
7491
|
+
import { spawnSync as spawnSync7 } from "child_process";
|
|
7492
|
+
import fs13 from "fs";
|
|
6910
7493
|
|
|
6911
7494
|
// src/commands/update.ts
|
|
6912
7495
|
import { execFile as execFile3, spawn as spawn2 } from "child_process";
|
|
@@ -6924,6 +7507,7 @@ async function getLatestNpmVersion(timeoutMs = NPM_VIEW_TIMEOUT_MS) {
|
|
|
6924
7507
|
}
|
|
6925
7508
|
async function cmdUpdate(args = []) {
|
|
6926
7509
|
assertKnownFlags(args.slice(1), [], "update");
|
|
7510
|
+
assertPositionalCount(args, 0, 1, "mihomo update");
|
|
6927
7511
|
console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
|
|
6928
7512
|
console.log("");
|
|
6929
7513
|
const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
|
|
@@ -6981,7 +7565,7 @@ async function cmdUpdate(args = []) {
|
|
|
6981
7565
|
// src/commands/doctor.ts
|
|
6982
7566
|
function isPortListening(port) {
|
|
6983
7567
|
try {
|
|
6984
|
-
const r =
|
|
7568
|
+
const r = spawnSync7("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
|
|
6985
7569
|
return r.status === 0 && (r.stdout || "").trim().length > 0;
|
|
6986
7570
|
} catch {
|
|
6987
7571
|
return false;
|
|
@@ -6996,7 +7580,7 @@ async function collectChecks() {
|
|
|
6996
7580
|
push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
|
|
6997
7581
|
} else {
|
|
6998
7582
|
const v = getKernelVersion();
|
|
6999
|
-
const r =
|
|
7583
|
+
const r = spawnSync7(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
7000
7584
|
if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
|
|
7001
7585
|
push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
|
|
7002
7586
|
} else if (r.error) {
|
|
@@ -7006,13 +7590,13 @@ async function collectChecks() {
|
|
|
7006
7590
|
}
|
|
7007
7591
|
}
|
|
7008
7592
|
try {
|
|
7009
|
-
|
|
7593
|
+
fs13.accessSync(USER_DATA_DIR, fs13.constants.W_OK);
|
|
7010
7594
|
push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
|
|
7011
7595
|
} catch {
|
|
7012
7596
|
push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
|
|
7013
7597
|
}
|
|
7014
|
-
if (
|
|
7015
|
-
if (isValidSettingsContent(
|
|
7598
|
+
if (fs13.existsSync(PATHS.settingsFile)) {
|
|
7599
|
+
if (isValidSettingsContent(fs13.readFileSync(PATHS.settingsFile, "utf8"))) {
|
|
7016
7600
|
push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
|
|
7017
7601
|
} else {
|
|
7018
7602
|
push("\u8BBE\u7F6E\u6587\u4EF6", "warn", "\u683C\u5F0F\u635F\u574F\u6216\u975E\u5BF9\u8C61\uFF0C\u8BFB\u53D6\u65F6\u4F1A\u56DE\u9000\u9ED8\u8BA4\u5E76\u5907\u4EFD\u4E3A .bak", "\u5220\u9664\u6216\u4FEE\u590D settings.json");
|
|
@@ -7089,8 +7673,19 @@ async function collectChecks() {
|
|
|
7089
7673
|
if (active && hasKernel()) {
|
|
7090
7674
|
try {
|
|
7091
7675
|
const mode = info?.tun ? "tun" : "mixed";
|
|
7092
|
-
await prepareConfigForStart(mode, active.name);
|
|
7093
|
-
|
|
7676
|
+
const prepared = await prepareConfigForStart(mode, active.name);
|
|
7677
|
+
const warnings = prepared.buildResult.warnings;
|
|
7678
|
+
if (warnings.length > 0) {
|
|
7679
|
+
push(
|
|
7680
|
+
"\u914D\u7F6E\u6784\u5EFA",
|
|
7681
|
+
"warn",
|
|
7682
|
+
`\u5F53\u524D\u8BA2\u9605\u901A\u8FC7\u5185\u6838\u6821\u9A8C\uFF08${mode}\uFF09\uFF0C\u53E6\u6709 ${warnings.length} \u6761\u914D\u7F6E\u63D0\u793A`,
|
|
7683
|
+
void 0,
|
|
7684
|
+
warnings.map((w) => ` ${w}`)
|
|
7685
|
+
);
|
|
7686
|
+
} else {
|
|
7687
|
+
push("\u914D\u7F6E\u6784\u5EFA", "ok", `\u5F53\u524D\u8BA2\u9605\u901A\u8FC7\u5185\u6838\u6821\u9A8C\uFF08${mode}\uFF09`);
|
|
7688
|
+
}
|
|
7094
7689
|
} catch (e) {
|
|
7095
7690
|
const notes = e instanceof CliError ? e.hint.filter((l) => l.trim().length > 0) : void 0;
|
|
7096
7691
|
push("\u914D\u7F6E\u6784\u5EFA", "fail", e.message.split("\n")[0], "\u4FEE\u6B63\u8BA2\u9605\u6216\u8986\u5199\u540E mihomo start", notes);
|
|
@@ -7120,6 +7715,7 @@ async function collectChecks() {
|
|
|
7120
7715
|
}
|
|
7121
7716
|
async function cmdDoctor(args = []) {
|
|
7122
7717
|
assertKnownFlags(args.slice(1), [], "doctor");
|
|
7718
|
+
assertPositionalCount(args, 0, 1, "mihomo doctor");
|
|
7123
7719
|
const checks = await collectChecks();
|
|
7124
7720
|
console.log("");
|
|
7125
7721
|
for (const c of checks) {
|
|
@@ -7146,13 +7742,15 @@ async function cmdDoctor(args = []) {
|
|
|
7146
7742
|
}
|
|
7147
7743
|
|
|
7148
7744
|
// src/kernel.ts
|
|
7149
|
-
import { spawnSync as
|
|
7150
|
-
import
|
|
7745
|
+
import { execFile as execFile4, spawnSync as spawnSync8 } from "child_process";
|
|
7746
|
+
import fs14 from "fs";
|
|
7151
7747
|
import path10 from "path";
|
|
7748
|
+
import { promisify as promisify4 } from "util";
|
|
7152
7749
|
var GITHUB_REPO = "MetaCubeX/mihomo";
|
|
7153
7750
|
var KERNEL_HTTP_TIMEOUT = 12e4;
|
|
7154
7751
|
var KERNEL_DOWNLOAD_TIMEOUT = 18e4;
|
|
7155
7752
|
var HTTP_CLIENT2 = createHttpClient({ timeout: KERNEL_HTTP_TIMEOUT });
|
|
7753
|
+
var execFileAsync3 = promisify4(execFile4);
|
|
7156
7754
|
function withMirror(url, mirror) {
|
|
7157
7755
|
if (mirror && url.startsWith("https://github.com/")) {
|
|
7158
7756
|
return mirror + url;
|
|
@@ -7184,7 +7782,7 @@ function resolveDownloadChannel(input) {
|
|
|
7184
7782
|
return { kind: "direct" };
|
|
7185
7783
|
}
|
|
7186
7784
|
function hasGh() {
|
|
7187
|
-
const result =
|
|
7785
|
+
const result = spawnSync8("gh", ["--version"], { stdio: "ignore" });
|
|
7188
7786
|
return !result.error && result.status === 0;
|
|
7189
7787
|
}
|
|
7190
7788
|
function getArch() {
|
|
@@ -7213,45 +7811,75 @@ function pickLatestRelease(releases) {
|
|
|
7213
7811
|
if (stableReleases.length === 0) {
|
|
7214
7812
|
throw new Error(`\u672A\u627E\u5230\u7A33\u5B9A\u7248\u5185\u6838\uFF08\u83B7\u53D6\u5230\u7684 ${releases.length} \u6761 release \u5168\u90E8\u662F\u9884\u53D1\u5E03\u7248\uFF09`);
|
|
7215
7813
|
}
|
|
7216
|
-
return stableReleases[0];
|
|
7814
|
+
return stableReleases[0];
|
|
7815
|
+
}
|
|
7816
|
+
function buildReleaseApiCurlArgs(proxyPort, url) {
|
|
7817
|
+
return [
|
|
7818
|
+
"-s",
|
|
7819
|
+
"-x",
|
|
7820
|
+
`http://127.0.0.1:${proxyPort}`,
|
|
7821
|
+
"--proto",
|
|
7822
|
+
"=https",
|
|
7823
|
+
"--proto-redir",
|
|
7824
|
+
"=https",
|
|
7825
|
+
"--fail-with-body",
|
|
7826
|
+
"-w",
|
|
7827
|
+
"\n%{http_code}",
|
|
7828
|
+
"--connect-timeout",
|
|
7829
|
+
"10",
|
|
7830
|
+
"--max-time",
|
|
7831
|
+
String(Math.floor(KERNEL_HTTP_TIMEOUT / 1e3)),
|
|
7832
|
+
"-H",
|
|
7833
|
+
`User-Agent: mihomo-cli/${VERSION}`,
|
|
7834
|
+
url
|
|
7835
|
+
];
|
|
7836
|
+
}
|
|
7837
|
+
function parseCurlStatusOutput(stdout) {
|
|
7838
|
+
const newlineIdx = stdout.lastIndexOf("\n");
|
|
7839
|
+
if (newlineIdx === -1) return { body: stdout, statusCode: null };
|
|
7840
|
+
const code = Number.parseInt(stdout.slice(newlineIdx + 1).trim(), 10);
|
|
7841
|
+
return { body: stdout.slice(0, newlineIdx), statusCode: Number.isFinite(code) && code > 0 ? code : null };
|
|
7842
|
+
}
|
|
7843
|
+
function translateReleaseApiCurlError(e) {
|
|
7844
|
+
const err = e;
|
|
7845
|
+
if (typeof err.code === "string") {
|
|
7846
|
+
if (err.code === "ENOENT") {
|
|
7847
|
+
return new Error("\u672A\u627E\u5230 curl \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 curl \u540E\u91CD\u8BD5");
|
|
7848
|
+
}
|
|
7849
|
+
return new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25: ${err.message ?? err.code}`);
|
|
7850
|
+
}
|
|
7851
|
+
const { body, statusCode } = parseCurlStatusOutput(typeof err.stdout === "string" ? err.stdout : "");
|
|
7852
|
+
if (statusCode !== null && statusCode >= 400) {
|
|
7853
|
+
return createHttpError(statusCode, body);
|
|
7854
|
+
}
|
|
7855
|
+
if (err.killed) {
|
|
7856
|
+
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` : ""}`);
|
|
7857
|
+
}
|
|
7858
|
+
const stderr = (err.stderr || "").trim();
|
|
7859
|
+
const lastLine = stderr ? stderr.split("\n").pop()?.replace(/^curl: \(\d+\)\s*/, "") : void 0;
|
|
7860
|
+
return new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25 (curl \u9000\u51FA\u7801 ${err.code ?? "?"}${lastLine ? `: ${lastLine}` : ""})`);
|
|
7217
7861
|
}
|
|
7218
7862
|
async function getLatestRelease(repo, proxyPort) {
|
|
7219
7863
|
const url = `https://api.github.com/repos/${repo}/releases`;
|
|
7220
7864
|
if (proxyPort) {
|
|
7221
|
-
|
|
7222
|
-
|
|
7223
|
-
|
|
7224
|
-
"
|
|
7225
|
-
|
|
7226
|
-
|
|
7227
|
-
|
|
7228
|
-
|
|
7229
|
-
|
|
7230
|
-
|
|
7231
|
-
"--connect-timeout",
|
|
7232
|
-
"10",
|
|
7233
|
-
"--max-time",
|
|
7234
|
-
String(Math.floor(KERNEL_HTTP_TIMEOUT / 1e3)),
|
|
7235
|
-
"-H",
|
|
7236
|
-
`User-Agent: mihomo-cli/${VERSION}`,
|
|
7237
|
-
url
|
|
7238
|
-
],
|
|
7239
|
-
{ encoding: "utf8", maxBuffer: 50 * 1024 * 1024, timeout: KERNEL_HTTP_TIMEOUT + 1e4 }
|
|
7240
|
-
);
|
|
7241
|
-
if (result.error) {
|
|
7242
|
-
if (result.error.code === "ENOENT") {
|
|
7243
|
-
throw new Error("\u672A\u627E\u5230 curl \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 curl \u540E\u91CD\u8BD5");
|
|
7244
|
-
}
|
|
7245
|
-
throw new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25: ${result.error.message}`);
|
|
7865
|
+
let stdout;
|
|
7866
|
+
try {
|
|
7867
|
+
const result = await execFileAsync3("curl", buildReleaseApiCurlArgs(proxyPort, url), {
|
|
7868
|
+
encoding: "utf8",
|
|
7869
|
+
maxBuffer: 50 * 1024 * 1024,
|
|
7870
|
+
timeout: KERNEL_HTTP_TIMEOUT + 1e4
|
|
7871
|
+
});
|
|
7872
|
+
stdout = result.stdout;
|
|
7873
|
+
} catch (e) {
|
|
7874
|
+
throw translateReleaseApiCurlError(e);
|
|
7246
7875
|
}
|
|
7247
|
-
|
|
7248
|
-
|
|
7249
|
-
|
|
7250
|
-
throw new Error(`\u7248\u672C\u67E5\u8BE2\u5931\u8D25 (curl \u9000\u51FA\u7801 ${result.status}${lastLine ? `: ${lastLine}` : ""})`);
|
|
7876
|
+
const { body, statusCode } = parseCurlStatusOutput(stdout);
|
|
7877
|
+
if (statusCode !== null && (statusCode < 200 || statusCode >= 300)) {
|
|
7878
|
+
throw createHttpError(statusCode, body);
|
|
7251
7879
|
}
|
|
7252
7880
|
let releases;
|
|
7253
7881
|
try {
|
|
7254
|
-
releases = JSON.parse(
|
|
7882
|
+
releases = JSON.parse(body);
|
|
7255
7883
|
} catch {
|
|
7256
7884
|
throw new Error("\u7248\u672C\u67E5\u8BE2\u5931\u8D25: \u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF08\u4EE3\u7406\u53EF\u80FD\u8FD4\u56DE\u4E86\u9519\u8BEF\u9875\u9762\uFF09");
|
|
7257
7885
|
}
|
|
@@ -7285,10 +7913,10 @@ async function checkUpdate(proxyPort) {
|
|
|
7285
7913
|
}
|
|
7286
7914
|
function findBinaryInDir(dir, maxDepth = 4) {
|
|
7287
7915
|
if (maxDepth <= 0) return null;
|
|
7288
|
-
const files =
|
|
7916
|
+
const files = fs14.readdirSync(dir);
|
|
7289
7917
|
for (const f of files) {
|
|
7290
7918
|
const fullPath = path10.join(dir, f);
|
|
7291
|
-
const stat =
|
|
7919
|
+
const stat = fs14.lstatSync(fullPath);
|
|
7292
7920
|
if (stat.isDirectory()) {
|
|
7293
7921
|
const found = findBinaryInDir(fullPath, maxDepth - 1);
|
|
7294
7922
|
if (found) return found;
|
|
@@ -7300,6 +7928,15 @@ function findBinaryInDir(dir, maxDepth = 4) {
|
|
|
7300
7928
|
}
|
|
7301
7929
|
return null;
|
|
7302
7930
|
}
|
|
7931
|
+
var MAX_EXTRACTED_BYTES = 512 * 1024 * 1024;
|
|
7932
|
+
function parseTarEntrySize(line) {
|
|
7933
|
+
const tokens = line.trim().split(/\s+/);
|
|
7934
|
+
if (tokens.length < 5) return null;
|
|
7935
|
+
const sizeToken = tokens[1].includes("/") ? tokens[2] : tokens[4];
|
|
7936
|
+
if (!/^\d+$/.test(sizeToken)) return null;
|
|
7937
|
+
const size = Number(sizeToken);
|
|
7938
|
+
return Number.isSafeInteger(size) ? size : null;
|
|
7939
|
+
}
|
|
7303
7940
|
function buildKernelCurlArgs(args) {
|
|
7304
7941
|
const argv = [
|
|
7305
7942
|
"-L",
|
|
@@ -7307,6 +7944,10 @@ function buildKernelCurlArgs(args) {
|
|
|
7307
7944
|
"=https",
|
|
7308
7945
|
"--proto-redir",
|
|
7309
7946
|
"=https",
|
|
7947
|
+
// 镜像/CDN 返回 404/500 的 HTML 错误页时,curl 默认退出 0、错误内容落盘,
|
|
7948
|
+
// 最终只报「文件大小与 release 元数据不符」、丢掉真正的 HTTP 原因。
|
|
7949
|
+
// 与 release API 查询路径(buildReleaseApiCurlArgs)同一口径
|
|
7950
|
+
"--fail-with-body",
|
|
7310
7951
|
"--max-filesize",
|
|
7311
7952
|
String(args.maxBytes),
|
|
7312
7953
|
"--progress-bar",
|
|
@@ -7340,7 +7981,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7340
7981
|
}
|
|
7341
7982
|
assertTrustedAssetUrl(asset.browser_download_url);
|
|
7342
7983
|
const downloadUrl = channel.kind === "mirror" ? withMirror(asset.browser_download_url, channel.mirror) : asset.browser_download_url;
|
|
7343
|
-
const tempDir =
|
|
7984
|
+
const tempDir = fs14.mkdtempSync(path10.join(DIRS.kernel, ".tmp-"));
|
|
7344
7985
|
const tempPath = path10.join(tempDir, path10.basename(asset.name));
|
|
7345
7986
|
const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
|
|
7346
7987
|
try {
|
|
@@ -7354,7 +7995,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7354
7995
|
if (/[*?[\]]/.test(asset.name) || asset.name !== path10.basename(asset.name)) {
|
|
7355
7996
|
throw new Error(`\u5185\u6838\u8D44\u4EA7\u540D\u542B\u975E\u6CD5\u5B57\u7B26: ${asset.name}`);
|
|
7356
7997
|
}
|
|
7357
|
-
const ghResult =
|
|
7998
|
+
const ghResult = spawnSync8("gh", buildGhReleaseDownloadArgs(latest.tag_name, asset.name, tempDir), {
|
|
7358
7999
|
stdio: "inherit",
|
|
7359
8000
|
timeout: KERNEL_DOWNLOAD_TIMEOUT + 3e4
|
|
7360
8001
|
});
|
|
@@ -7372,7 +8013,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7372
8013
|
}
|
|
7373
8014
|
} else {
|
|
7374
8015
|
const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
|
|
7375
|
-
const curlResult =
|
|
8016
|
+
const curlResult = spawnSync8(
|
|
7376
8017
|
"curl",
|
|
7377
8018
|
buildKernelCurlArgs({
|
|
7378
8019
|
url: downloadUrl,
|
|
@@ -7389,14 +8030,17 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7389
8030
|
throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${curlResult.error.message}`);
|
|
7390
8031
|
}
|
|
7391
8032
|
if (curlResult.status !== 0) {
|
|
8033
|
+
if (curlResult.status === 22) {
|
|
8034
|
+
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u955C\u50CF\u6216\u670D\u52A1\u5668\u8FD4\u56DE HTTP \u9519\u8BEF\uFF084xx/5xx\uFF09\uFF0C\u8BF7\u91CD\u8BD5\u6216\u6539\u7528\u5176\u4ED6\u901A\u9053\uFF08gh/\u672C\u673A\u4EE3\u7406/--mirror direct\uFF09");
|
|
8035
|
+
}
|
|
7392
8036
|
throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
|
|
7393
8037
|
}
|
|
7394
8038
|
}
|
|
7395
|
-
if (!
|
|
8039
|
+
if (!fs14.existsSync(tempPath)) {
|
|
7396
8040
|
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
7397
8041
|
}
|
|
7398
8042
|
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
7399
|
-
const actual =
|
|
8043
|
+
const actual = fs14.statSync(tempPath).size;
|
|
7400
8044
|
if (actual !== asset.size) {
|
|
7401
8045
|
throw new Error(
|
|
7402
8046
|
`\u4E0B\u8F7D\u7684\u6587\u4EF6\u5927\u5C0F\u4E0E release \u5143\u6570\u636E\u4E0D\u7B26\uFF08\u671F\u671B ${asset.size} \u5B57\u8282\uFF0C\u5B9E\u9645 ${actual} \u5B57\u8282\uFF09
|
|
@@ -7409,7 +8053,7 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7409
8053
|
}
|
|
7410
8054
|
let extractedBinary = null;
|
|
7411
8055
|
if (tempPath.endsWith(".tar.gz") || tempPath.endsWith(".tgz")) {
|
|
7412
|
-
const listResult =
|
|
8056
|
+
const listResult = spawnSync8("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
|
|
7413
8057
|
if (listResult.error) throw listResult.error;
|
|
7414
8058
|
if (listResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${listResult.status}`);
|
|
7415
8059
|
for (const entry of (listResult.stdout || "").split("\n").filter(Boolean)) {
|
|
@@ -7417,16 +8061,24 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7417
8061
|
throw new Error(`\u5F52\u6863\u542B\u975E\u6CD5\u8DEF\u5F84\u6761\u76EE: ${entry}`);
|
|
7418
8062
|
}
|
|
7419
8063
|
}
|
|
7420
|
-
const typeResult =
|
|
8064
|
+
const typeResult = spawnSync8("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
|
|
7421
8065
|
if (typeResult.error) throw typeResult.error;
|
|
7422
8066
|
if (typeResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${typeResult.status}`);
|
|
8067
|
+
let extractedBytes = 0;
|
|
7423
8068
|
for (const line of (typeResult.stdout || "").split("\n").filter(Boolean)) {
|
|
7424
8069
|
const typeChar = line[0];
|
|
7425
8070
|
if (typeChar !== "-" && typeChar !== "d") {
|
|
7426
8071
|
throw new Error(`\u5F52\u6863\u542B\u975E\u666E\u901A\u6587\u4EF6\u6761\u76EE\uFF08\u7C7B\u578B "${typeChar}"\uFF09: ${line}`);
|
|
7427
8072
|
}
|
|
8073
|
+
const entrySize = parseTarEntrySize(line);
|
|
8074
|
+
if (entrySize !== null) extractedBytes += entrySize;
|
|
8075
|
+
}
|
|
8076
|
+
if (extractedBytes > MAX_EXTRACTED_BYTES) {
|
|
8077
|
+
throw new Error(
|
|
8078
|
+
`\u5F52\u6863\u89E3\u538B\u540E\u603B\u91CF ${(extractedBytes / 1024 / 1024).toFixed(1)}MB \u8D85\u8FC7 ${MAX_EXTRACTED_BYTES / 1024 / 1024}MB \u4E0A\u9650\uFF0C\u7591\u4F3C\u538B\u7F29\u70B8\u5F39\uFF0C\u5DF2\u62D2\u7EDD\u89E3\u538B`
|
|
8079
|
+
);
|
|
7428
8080
|
}
|
|
7429
|
-
const tarResult =
|
|
8081
|
+
const tarResult = spawnSync8("tar", ["--no-same-owner", "-xzf", tempPath, "-C", tempDir], {
|
|
7430
8082
|
stdio: ["ignore", "ignore", "inherit"],
|
|
7431
8083
|
timeout: 6e4
|
|
7432
8084
|
});
|
|
@@ -7435,10 +8087,10 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7435
8087
|
} else if (tempPath.endsWith(".gz")) {
|
|
7436
8088
|
const baseName = path10.basename(tempPath, ".gz");
|
|
7437
8089
|
const outputPath = path10.join(tempDir, baseName);
|
|
7438
|
-
const gzipResult =
|
|
8090
|
+
const gzipResult = spawnSync8("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
|
|
7439
8091
|
if (gzipResult.error) throw gzipResult.error;
|
|
7440
8092
|
if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
|
|
7441
|
-
|
|
8093
|
+
fs14.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
|
|
7442
8094
|
extractedBinary = outputPath;
|
|
7443
8095
|
}
|
|
7444
8096
|
const foundBinary = extractedBinary || findBinaryInDir(tempDir);
|
|
@@ -7448,8 +8100,8 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7448
8100
|
if (progressCallback) {
|
|
7449
8101
|
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
7450
8102
|
}
|
|
7451
|
-
|
|
7452
|
-
const check =
|
|
8103
|
+
fs14.chmodSync(foundBinary, 493);
|
|
8104
|
+
const check = spawnSync8(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
7453
8105
|
const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
|
|
7454
8106
|
if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
|
|
7455
8107
|
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
|
|
@@ -7465,21 +8117,23 @@ async function downloadKernel(progressCallback, channel, releaseInfo) {
|
|
|
7465
8117
|
}
|
|
7466
8118
|
}
|
|
7467
8119
|
const targetPath = PATHS.mihomoBinary;
|
|
7468
|
-
|
|
7469
|
-
|
|
8120
|
+
fs14.renameSync(foundBinary, targetPath);
|
|
8121
|
+
fs14.chmodSync(targetPath, 493);
|
|
7470
8122
|
clearKernelVersionCache();
|
|
7471
8123
|
return { version: latest.tag_name, path: targetPath };
|
|
7472
8124
|
} finally {
|
|
7473
8125
|
try {
|
|
7474
|
-
|
|
8126
|
+
fs14.rmSync(tempDir, { recursive: true, force: true });
|
|
7475
8127
|
} catch {
|
|
7476
8128
|
}
|
|
7477
8129
|
}
|
|
7478
8130
|
}
|
|
7479
8131
|
|
|
7480
8132
|
// src/commands/kernel.ts
|
|
8133
|
+
var KERNEL_VALUE_FLAGS = /* @__PURE__ */ new Set([...VALUE_FLAGS, "--mirror"]);
|
|
7481
8134
|
async function cmdKernel(args) {
|
|
7482
8135
|
const mirrorInfo = parseMirrorArg(args);
|
|
8136
|
+
assertPositionalCount(args, 0, 1, "mihomo kernel [--mirror [\u955C\u50CF]]", KERNEL_VALUE_FLAGS);
|
|
7483
8137
|
const effectiveMirror = mirrorInfo.mirror;
|
|
7484
8138
|
const proxyRunning = getRunningState().running;
|
|
7485
8139
|
const proxyPort = proxyRunning ? getPorts().mixed : null;
|
|
@@ -7562,12 +8216,11 @@ async function cmdKernel(args) {
|
|
|
7562
8216
|
// src/commands/log.ts
|
|
7563
8217
|
function cmdLogs(args) {
|
|
7564
8218
|
assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"], "logs [-f] [-n N] [\u7F16\u53F7] [-o]");
|
|
8219
|
+
assertPositionalCount(args, 1, 1, "mihomo logs [\u7F16\u53F7] [-f] [-n N] [-o]");
|
|
7565
8220
|
const lines = parseIntArg(args, "-n", "--lines", 100);
|
|
7566
8221
|
const openInViewer = hasFlag(args, "-o", "--open");
|
|
7567
8222
|
const follow = hasFlag(args, "-f", "--follow");
|
|
7568
|
-
const hasLinesFlag = args.some(
|
|
7569
|
-
(a) => a === "-n" || a === "--lines" || a.startsWith("--lines=") || a.startsWith("-n") && a.length > 2 && /^\d+$/.test(a.slice(2))
|
|
7570
|
-
);
|
|
8223
|
+
const hasLinesFlag = args.some((a) => matchValueFlagToken(a)?.spec.forms.includes("-n") === true);
|
|
7571
8224
|
const targetName = getNonFlagArg(args, 1) ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
|
|
7572
8225
|
if (targetName) {
|
|
7573
8226
|
let logPath;
|
|
@@ -7630,240 +8283,6 @@ function cmdLogs(args) {
|
|
|
7630
8283
|
console.log("");
|
|
7631
8284
|
}
|
|
7632
8285
|
|
|
7633
|
-
// src/commands/reset.ts
|
|
7634
|
-
import fs14 from "fs";
|
|
7635
|
-
|
|
7636
|
-
// src/process-stop.ts
|
|
7637
|
-
import { spawnSync as spawnSync8 } from "child_process";
|
|
7638
|
-
import fs13 from "fs";
|
|
7639
|
-
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
7640
|
-
var PROCESS_WAIT_INTERVAL = 100;
|
|
7641
|
-
var BATCH_KILL_THRESHOLD = 3;
|
|
7642
|
-
function clearRuntime() {
|
|
7643
|
-
if (fs13.existsSync(DIRS.runtime)) {
|
|
7644
|
-
rmrf(DIRS.runtime);
|
|
7645
|
-
}
|
|
7646
|
-
ensureDirs();
|
|
7647
|
-
}
|
|
7648
|
-
function clearPid() {
|
|
7649
|
-
if (!fs13.existsSync(PATHS.pidFile)) return;
|
|
7650
|
-
if (isPidFileOwnedByRoot()) {
|
|
7651
|
-
try {
|
|
7652
|
-
spawnSync8("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
|
|
7653
|
-
} catch {
|
|
7654
|
-
}
|
|
7655
|
-
} else {
|
|
7656
|
-
try {
|
|
7657
|
-
fs13.unlinkSync(PATHS.pidFile);
|
|
7658
|
-
} catch {
|
|
7659
|
-
}
|
|
7660
|
-
}
|
|
7661
|
-
}
|
|
7662
|
-
function killProcess(pid) {
|
|
7663
|
-
try {
|
|
7664
|
-
process.kill(pid, "SIGKILL");
|
|
7665
|
-
return true;
|
|
7666
|
-
} catch {
|
|
7667
|
-
return false;
|
|
7668
|
-
}
|
|
7669
|
-
}
|
|
7670
|
-
function killAllMihomo(forceSudo = false) {
|
|
7671
|
-
const pattern = MAIN_INSTANCE_PATTERN;
|
|
7672
|
-
const argv = forceSudo ? ["sudo", ["pkill", "-9", "-f", pattern]] : ["pkill", ["-9", "-f", pattern]];
|
|
7673
|
-
const options = forceSudo ? { stdio: "inherit", timeout: 15e3 } : { timeout: 1e4 };
|
|
7674
|
-
try {
|
|
7675
|
-
const result = spawnSync8(argv[0], argv[1], options);
|
|
7676
|
-
if (result.error) return false;
|
|
7677
|
-
return result.status === 0 || result.status === 1;
|
|
7678
|
-
} catch {
|
|
7679
|
-
return false;
|
|
7680
|
-
}
|
|
7681
|
-
}
|
|
7682
|
-
async function cleanupAll(forceSudo = false) {
|
|
7683
|
-
const pids = getMihomoPids();
|
|
7684
|
-
if (pids.length === 0) {
|
|
7685
|
-
clearPid();
|
|
7686
|
-
return { killed: 0, failed: 0, remaining: [] };
|
|
7687
|
-
}
|
|
7688
|
-
const hasRootProcess = pids.some((p) => isProcessRoot(p));
|
|
7689
|
-
const needsSudo = forceSudo || hasRootProcess;
|
|
7690
|
-
let killedCount = 0;
|
|
7691
|
-
const failedPids = [];
|
|
7692
|
-
if (needsSudo) {
|
|
7693
|
-
const success = killAllMihomo(true);
|
|
7694
|
-
if (success) {
|
|
7695
|
-
killedCount = pids.length;
|
|
7696
|
-
} else {
|
|
7697
|
-
failedPids.push(...pids);
|
|
7698
|
-
}
|
|
7699
|
-
} else {
|
|
7700
|
-
if (pids.length > BATCH_KILL_THRESHOLD) {
|
|
7701
|
-
if (killAllMihomo(false)) {
|
|
7702
|
-
killedCount = pids.length;
|
|
7703
|
-
} else {
|
|
7704
|
-
failedPids.push(...pids);
|
|
7705
|
-
}
|
|
7706
|
-
} else {
|
|
7707
|
-
for (const pid of pids) {
|
|
7708
|
-
if (killProcess(pid)) {
|
|
7709
|
-
killedCount++;
|
|
7710
|
-
} else {
|
|
7711
|
-
failedPids.push(pid);
|
|
7712
|
-
}
|
|
7713
|
-
}
|
|
7714
|
-
}
|
|
7715
|
-
}
|
|
7716
|
-
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
7717
|
-
if (getMihomoPids().length === 0) break;
|
|
7718
|
-
await sleep(PROCESS_WAIT_INTERVAL);
|
|
7719
|
-
}
|
|
7720
|
-
clearPid();
|
|
7721
|
-
return { killed: killedCount, failed: failedPids.length, remaining: getMihomoPids() };
|
|
7722
|
-
}
|
|
7723
|
-
async function stop(forceSudo = false) {
|
|
7724
|
-
const allPids = getMihomoPids();
|
|
7725
|
-
if (allPids.length === 0) {
|
|
7726
|
-
clearPid();
|
|
7727
|
-
clearRuntime();
|
|
7728
|
-
return { success: true, notRunning: true };
|
|
7729
|
-
}
|
|
7730
|
-
const result = await cleanupAll(forceSudo);
|
|
7731
|
-
const remaining = getMihomoPids();
|
|
7732
|
-
if (remaining.length > 0) {
|
|
7733
|
-
console.log("");
|
|
7734
|
-
console.log("\u4ECD\u6709\u8FDB\u7A0B\u6B8B\u7559\uFF0C\u9700\u8981\u624B\u52A8\u6E05\u7406:");
|
|
7735
|
-
console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
|
|
7736
|
-
console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
|
|
7737
|
-
console.log("");
|
|
7738
|
-
return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
|
|
7739
|
-
}
|
|
7740
|
-
clearRuntime();
|
|
7741
|
-
return { success: true, killed: result.killed };
|
|
7742
|
-
}
|
|
7743
|
-
|
|
7744
|
-
// src/commands/reset.ts
|
|
7745
|
-
var RESET_TARGETS = [
|
|
7746
|
-
{ id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
|
|
7747
|
-
{ id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
|
|
7748
|
-
{ id: "data", aliases: ["data"], label: "\u8FD0\u884C\u6570\u636E", paths: () => [DIRS.data], needsStop: true },
|
|
7749
|
-
{ id: "runtime", aliases: ["runtime"], label: "\u8FD0\u884C\u65F6", paths: () => [DIRS.runtime], needsStop: true },
|
|
7750
|
-
{
|
|
7751
|
-
id: "overwrites",
|
|
7752
|
-
aliases: ["overwrite", "overwrites", "ow"],
|
|
7753
|
-
label: "\u8986\u5199",
|
|
7754
|
-
needsStop: false,
|
|
7755
|
-
preserveOnBare: true,
|
|
7756
|
-
paths: () => fs14.existsSync(USER_DATA_DIR) ? fs14.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
|
|
7757
|
-
},
|
|
7758
|
-
{
|
|
7759
|
-
id: "settings",
|
|
7760
|
-
aliases: ["setting", "settings", "config"],
|
|
7761
|
-
label: "\u8BBE\u7F6E",
|
|
7762
|
-
needsStop: false,
|
|
7763
|
-
preserveOnBare: true,
|
|
7764
|
-
// 损坏备份也包含订阅凭据,需要一起删除
|
|
7765
|
-
paths: () => [PATHS.settingsFile, `${PATHS.settingsFile}.bak`]
|
|
7766
|
-
},
|
|
7767
|
-
{ id: "kernel", aliases: ["kernel", "core"], label: "\u5185\u6838", paths: () => [DIRS.kernel], needsStop: true, preserveOnBare: true },
|
|
7768
|
-
{ id: "service", aliases: ["service"], label: "\u670D\u52A1", paths: () => [], needsStop: false, preserveOnBare: true }
|
|
7769
|
-
];
|
|
7770
|
-
function resolveResetTargets(names) {
|
|
7771
|
-
const matched = /* @__PURE__ */ new Set();
|
|
7772
|
-
for (const name of names) {
|
|
7773
|
-
const target = RESET_TARGETS.find((t) => t.aliases.includes(name.toLowerCase()));
|
|
7774
|
-
if (!target) {
|
|
7775
|
-
throw new CliError(`\u672A\u77E5\u7684\u91CD\u7F6E\u76EE\u6807: ${name}`, { hint: [`\u53EF\u7528\u76EE\u6807: ${RESET_TARGETS.map((t) => t.id).join(", ")}`] });
|
|
7776
|
-
}
|
|
7777
|
-
matched.add(target);
|
|
7778
|
-
}
|
|
7779
|
-
return [...matched];
|
|
7780
|
-
}
|
|
7781
|
-
async function cmdReset(args) {
|
|
7782
|
-
assertKnownFlags(args, ["--full", "--yes", "-y"], "reset [\u76EE\u6807...] [--full] [-y]");
|
|
7783
|
-
const names = args.slice(1).filter((a) => !a.startsWith("-"));
|
|
7784
|
-
const namedTargets = resolveResetTargets(names);
|
|
7785
|
-
const targets = args.includes("--full") ? RESET_TARGETS : names.length > 0 ? namedTargets : RESET_TARGETS.filter((t) => !t.preserveOnBare);
|
|
7786
|
-
const ids = new Set(targets.map((t) => t.id));
|
|
7787
|
-
const needsStop = targets.some((t) => t.needsStop);
|
|
7788
|
-
const serviceTargeted = ids.has("service");
|
|
7789
|
-
const service = getServiceStatus();
|
|
7790
|
-
const serviceActive = service.installed || service.loaded;
|
|
7791
|
-
const legacy = detectLegacySystemInstall();
|
|
7792
|
-
if (targets.length === 1) {
|
|
7793
|
-
if (serviceTargeted && !serviceActive && !legacy) {
|
|
7794
|
-
console.log("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664");
|
|
7795
|
-
return;
|
|
7796
|
-
}
|
|
7797
|
-
}
|
|
7798
|
-
if (ids.has("kernel") && getMihomoPids().length > 0) {
|
|
7799
|
-
console.log(colors.yellow("\u5C06\u505C\u6B62\u6B63\u5728\u8FD0\u884C\u7684\u5185\u6838\uFF0C\u5220\u9664\u540E\u9700\u91CD\u65B0\u4E0B\u8F7D\u624D\u80FD\u542F\u52A8"));
|
|
7800
|
-
}
|
|
7801
|
-
if (serviceTargeted && serviceActive) {
|
|
7802
|
-
console.log(colors.yellow("\u5C06\u5378\u8F7D launchd \u670D\u52A1\uFF08Mixed \u6A21\u5F0F\u9700\u91CD\u65B0 install \u624D\u80FD\u4F7F\u7528\uFF09"));
|
|
7803
|
-
} else if (needsStop && serviceActive) {
|
|
7804
|
-
console.log(colors.yellow("\u5C06\u505C\u6B62\u670D\u52A1\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF08\u5B89\u88C5\u4FDD\u7559\uFF0Cmihomo start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09"));
|
|
7805
|
-
}
|
|
7806
|
-
if ((needsStop || serviceTargeted) && legacy) {
|
|
7807
|
-
console.log(colors.yellow("\u5C06\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF0C\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
|
|
7808
|
-
}
|
|
7809
|
-
console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
|
|
7810
|
-
if (!args.includes("-y") && !args.includes("--yes") && !await confirmOrThrow("\u786E\u8BA4?", {
|
|
7811
|
-
nonTtyMessage: "\u975E\u4EA4\u4E92\u73AF\u5883\u65E0\u6CD5\u786E\u8BA4",
|
|
7812
|
-
hint: ["\u8DF3\u8FC7\u786E\u8BA4\u8BF7\u52A0 -y: mihomo reset ... -y"]
|
|
7813
|
-
})) {
|
|
7814
|
-
console.log("\u5DF2\u53D6\u6D88");
|
|
7815
|
-
return;
|
|
7816
|
-
}
|
|
7817
|
-
if ((needsStop || serviceTargeted) && legacy) cleanupLegacyInstallOrThrow();
|
|
7818
|
-
if (serviceActive) {
|
|
7819
|
-
if (serviceTargeted) await uninstallService();
|
|
7820
|
-
else if (needsStop) await stopService();
|
|
7821
|
-
}
|
|
7822
|
-
if (needsStop) {
|
|
7823
|
-
const cleanup = await cleanupAll();
|
|
7824
|
-
if (cleanup.remaining.length > 0) {
|
|
7825
|
-
throw new CliError(cleanup.remaining.join(", "), {
|
|
7826
|
-
label: "\u8FDB\u7A0B\u672A\u80FD\u505C\u6B62\uFF0C\u91CD\u7F6E\u4E2D\u6B62",
|
|
7827
|
-
hint: ["\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo"]
|
|
7828
|
-
});
|
|
7829
|
-
}
|
|
7830
|
-
recordServiceStopped();
|
|
7831
|
-
}
|
|
7832
|
-
const deleted = /* @__PURE__ */ new Set();
|
|
7833
|
-
for (const target of targets) {
|
|
7834
|
-
let hadContent = target.id === "service" && (serviceActive || legacy);
|
|
7835
|
-
for (const filePath of target.paths()) {
|
|
7836
|
-
if (!fs14.existsSync(filePath)) continue;
|
|
7837
|
-
try {
|
|
7838
|
-
rmrf(filePath);
|
|
7839
|
-
} catch (e) {
|
|
7840
|
-
throw new CliError(`\u65E0\u6CD5\u5220\u9664 ${filePath}: ${e.message}`, { label: "\u91CD\u7F6E\u5931\u8D25" });
|
|
7841
|
-
}
|
|
7842
|
-
hadContent = true;
|
|
7843
|
-
}
|
|
7844
|
-
if (hadContent) deleted.add(target.id);
|
|
7845
|
-
}
|
|
7846
|
-
if (!ids.has("settings") && (ids.has("subs") || ids.has("overwrites"))) {
|
|
7847
|
-
updateSettings((settings) => {
|
|
7848
|
-
const patch = {};
|
|
7849
|
-
if (ids.has("subs") && (settings.subscriptions !== void 0 || settings.active_subscription !== void 0)) {
|
|
7850
|
-
patch.subscriptions = void 0;
|
|
7851
|
-
patch.active_subscription = void 0;
|
|
7852
|
-
deleted.add("subs");
|
|
7853
|
-
}
|
|
7854
|
-
if (ids.has("overwrites") && settings.overwrite_enabled !== void 0) {
|
|
7855
|
-
patch.overwrite_enabled = void 0;
|
|
7856
|
-
deleted.add("overwrites");
|
|
7857
|
-
}
|
|
7858
|
-
return patch;
|
|
7859
|
-
});
|
|
7860
|
-
}
|
|
7861
|
-
if (ids.has("kernel")) clearKernelVersionCache();
|
|
7862
|
-
ensureDirs();
|
|
7863
|
-
const labels = targets.filter((t) => deleted.has(t.id)).map((t) => t.label);
|
|
7864
|
-
console.log(labels.length > 0 ? colors.green(`\u5DF2\u91CD\u7F6E: ${labels.join("\u3001")}`) : "\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
|
|
7865
|
-
}
|
|
7866
|
-
|
|
7867
8286
|
// src/commands/service.ts
|
|
7868
8287
|
import fs15 from "fs";
|
|
7869
8288
|
async function handleLegacyInstall() {
|
|
@@ -7884,6 +8303,7 @@ function printRestoreSkipped() {
|
|
|
7884
8303
|
}
|
|
7885
8304
|
async function cmdInstall(args) {
|
|
7886
8305
|
assertKnownFlags(args.slice(1), [], "install");
|
|
8306
|
+
assertPositionalCount(args, 0, 1, "mihomo install");
|
|
7887
8307
|
if (!hasKernel()) {
|
|
7888
8308
|
throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
7889
8309
|
}
|
|
@@ -7924,6 +8344,7 @@ async function cmdInstall(args) {
|
|
|
7924
8344
|
}
|
|
7925
8345
|
async function cmdUninstall(args) {
|
|
7926
8346
|
assertKnownFlags(args.slice(1), [], "uninstall");
|
|
8347
|
+
assertPositionalCount(args, 0, 1, "mihomo uninstall");
|
|
7927
8348
|
const status = getServiceStatus();
|
|
7928
8349
|
const legacy = detectLegacySystemInstall();
|
|
7929
8350
|
const residue = getMihomoPids();
|
|
@@ -7965,6 +8386,7 @@ function handleStopResult(result) {
|
|
|
7965
8386
|
}
|
|
7966
8387
|
async function cmdStop(args) {
|
|
7967
8388
|
assertKnownFlags(args.slice(1), [], "stop");
|
|
8389
|
+
assertPositionalCount(args, 0, 1, "mihomo stop");
|
|
7968
8390
|
if (detectLegacySystemInstall()) {
|
|
7969
8391
|
console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u505C\u6B62\u524D\u9700\u6E05\u7406"));
|
|
7970
8392
|
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"));
|
|
@@ -8000,6 +8422,13 @@ async function cmdStop(args) {
|
|
|
8000
8422
|
|
|
8001
8423
|
// src/commands/ui.ts
|
|
8002
8424
|
import { spawnSync as spawnSync9 } from "child_process";
|
|
8425
|
+
function resolveUiName(args) {
|
|
8426
|
+
const name = (args[1] ?? "zash").toLowerCase();
|
|
8427
|
+
if (name === "" || !Object.hasOwn(UI_URLS, name)) {
|
|
8428
|
+
throw new CliError(`\u672A\u77E5\u7684 UI "${args[1] ?? ""}"`, { hint: "\u53EF\u7528 UI: zash (\u9ED8\u8BA4), dash, yacd" });
|
|
8429
|
+
}
|
|
8430
|
+
return name;
|
|
8431
|
+
}
|
|
8003
8432
|
function copyToClipboard(text) {
|
|
8004
8433
|
try {
|
|
8005
8434
|
return spawnSync9("pbcopy", [], { input: text }).status === 0;
|
|
@@ -8009,10 +8438,8 @@ function copyToClipboard(text) {
|
|
|
8009
8438
|
}
|
|
8010
8439
|
function cmdUI(args) {
|
|
8011
8440
|
assertKnownFlags(args.slice(1), [], "ui");
|
|
8012
|
-
|
|
8013
|
-
|
|
8014
|
-
throw new CliError(`\u672A\u77E5\u7684 UI "${uiName}"`, { hint: "\u53EF\u7528 UI: zash (\u9ED8\u8BA4), dash, yacd" });
|
|
8015
|
-
}
|
|
8441
|
+
assertPositionalCount(args, 1, 1, "mihomo ui [zash|dash|yacd]");
|
|
8442
|
+
const uiName = resolveUiName(args);
|
|
8016
8443
|
if (!getRunningState().running) {
|
|
8017
8444
|
console.log(colors.yellow("\u63D0\u793A: mihomo \u672A\u8FD0\u884C\uFF0CUI \u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\uFF08\u5148\u6267\u884C mihomo start \u542F\u52A8\uFF09"));
|
|
8018
8445
|
console.log("");
|
|
@@ -8021,7 +8448,7 @@ function cmdUI(args) {
|
|
|
8021
8448
|
console.log(`\u6253\u5F00 Web UI: ${uiName}`);
|
|
8022
8449
|
console.log(`\u5730\u5740: ${url}`);
|
|
8023
8450
|
const secret = readSettings().controller_secret;
|
|
8024
|
-
if (secret) {
|
|
8451
|
+
if (typeof secret === "string" && secret) {
|
|
8025
8452
|
console.log(
|
|
8026
8453
|
copyToClipboard(secret) ? "\u5DF2\u914D\u7F6E\u8BBF\u95EE\u5BC6\u94A5\uFF08\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\uFF0CUI \u8FDE\u63A5\u65F6\u7C98\u8D34\uFF09" : `\u5DF2\u914D\u7F6E\u8BBF\u95EE\u5BC6\u94A5\uFF08UI \u8FDE\u63A5 127.0.0.1:${getPorts().controller} \u65F6\u9700\u8F93\u5165\uFF0C\u5BC6\u94A5\u89C1 settings.json\uFF09`
|
|
8027
8454
|
);
|
|
@@ -8219,7 +8646,7 @@ function allCommandTokens() {
|
|
|
8219
8646
|
// src/index.ts
|
|
8220
8647
|
process.on("SIGINT", () => {
|
|
8221
8648
|
if (!isSilentSigint()) {
|
|
8222
|
-
console.
|
|
8649
|
+
console.error("\n\u6B63\u5728\u9000\u51FA...");
|
|
8223
8650
|
}
|
|
8224
8651
|
process.exit(130);
|
|
8225
8652
|
});
|
|
@@ -8228,16 +8655,15 @@ process.on("SIGTERM", () => {
|
|
|
8228
8655
|
});
|
|
8229
8656
|
process.on("uncaughtException", (e) => {
|
|
8230
8657
|
console.error(`
|
|
8231
|
-
\u672A\u6355\u83B7\u7684\u5F02\u5E38: ${e
|
|
8232
|
-
if (e.stack) {
|
|
8658
|
+
\u672A\u6355\u83B7\u7684\u5F02\u5E38: ${errorMessage(e)}`);
|
|
8659
|
+
if (e instanceof Error && e.stack) {
|
|
8233
8660
|
console.error(e.stack.split("\n").slice(1).join("\n"));
|
|
8234
8661
|
}
|
|
8235
8662
|
process.exit(1);
|
|
8236
8663
|
});
|
|
8237
8664
|
process.on("unhandledRejection", (reason) => {
|
|
8238
|
-
const msg = reason instanceof Error ? reason.message : String(reason);
|
|
8239
8665
|
console.error(`
|
|
8240
|
-
\u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD: ${
|
|
8666
|
+
\u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD: ${errorMessage(reason)}`);
|
|
8241
8667
|
process.exit(1);
|
|
8242
8668
|
});
|
|
8243
8669
|
function clearProxyEnv() {
|
|
@@ -8312,19 +8738,23 @@ async function main() {
|
|
|
8312
8738
|
assertSupportedNodeVersion(command.name);
|
|
8313
8739
|
assertSupportedPlatform(command.name);
|
|
8314
8740
|
assertNotRoot(command.name);
|
|
8315
|
-
|
|
8316
|
-
|
|
8741
|
+
if (!GUARD_EXEMPT_COMMANDS.has(command.name)) {
|
|
8742
|
+
ensureDirs();
|
|
8743
|
+
}
|
|
8744
|
+
if (command.group === "meta") {
|
|
8745
|
+
assertKnownFlags(args.slice(1), [], command.name);
|
|
8746
|
+
assertPositionalCount(args, 0, 1, `mihomo ${command.name}`);
|
|
8747
|
+
}
|
|
8317
8748
|
await command.handler(command.rewrite ? command.rewrite(args) : args);
|
|
8318
8749
|
}
|
|
8319
8750
|
main().catch((e) => {
|
|
8320
8751
|
if (e instanceof CliError) {
|
|
8321
|
-
console.error(`${
|
|
8752
|
+
console.error(`${stderrColors.red(`${e.label}:`)} ${e.message}`);
|
|
8322
8753
|
for (const line of e.hint) console.error(line);
|
|
8323
8754
|
process.exit(e.exitCode);
|
|
8324
8755
|
}
|
|
8325
|
-
|
|
8326
|
-
console.error(
|
|
8327
|
-
if (err.stack) console.error(err.stack.split("\n").slice(1).join("\n"));
|
|
8756
|
+
console.error(`${stderrColors.red("\u9519\u8BEF:")} ${errorMessage(e)}`);
|
|
8757
|
+
if (e instanceof Error && e.stack) console.error(e.stack.split("\n").slice(1).join("\n"));
|
|
8328
8758
|
process.exit(1);
|
|
8329
8759
|
});
|
|
8330
8760
|
/*! Bundled license information:
|