mihomo-cli 4.4.0 → 4.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +73 -0
- package/README.md +68 -16
- package/dist/index.js +615 -337
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -3076,9 +3076,8 @@ var RAW_SERVICE_LABEL = process.env.MIHOMO_CLI_DAEMON_LABEL;
|
|
|
3076
3076
|
var RAW_SERVICE_LABEL_INPUT = RAW_SERVICE_LABEL;
|
|
3077
3077
|
var SERVICE_LABEL = RAW_SERVICE_LABEL && isValidServiceLabel(RAW_SERVICE_LABEL) ? RAW_SERVICE_LABEL : DEFAULT_SERVICE_LABEL;
|
|
3078
3078
|
var SERVICE_BINARY_NAME = "mihomo-cli-service";
|
|
3079
|
+
var DEFAULT_MIXED_PORT = 7890;
|
|
3079
3080
|
var CONTROLLER_PORT = 9090;
|
|
3080
|
-
var CONTROLLER_ADDR = `127.0.0.1:${CONTROLLER_PORT}`;
|
|
3081
|
-
var CONTROLLER_BASE_URL = `http://${CONTROLLER_ADDR}`;
|
|
3082
3081
|
var TUN_CONFIG = {
|
|
3083
3082
|
tun: {
|
|
3084
3083
|
enable: true,
|
|
@@ -3090,9 +3089,9 @@ var TUN_CONFIG = {
|
|
|
3090
3089
|
}
|
|
3091
3090
|
};
|
|
3092
3091
|
var BASE_CONFIG = {
|
|
3093
|
-
|
|
3092
|
+
// 注意:mixed-port 与 external-controller 不在此表——它们来自 settings.ports(getPorts),
|
|
3093
|
+
// config.ts 单独写入 systemConfig,订阅/覆写恒不可改
|
|
3094
3094
|
"allow-lan": false,
|
|
3095
|
-
"external-controller": CONTROLLER_ADDR,
|
|
3096
3095
|
"unified-delay": true,
|
|
3097
3096
|
"tcp-concurrent": true,
|
|
3098
3097
|
"geo-auto-update": true,
|
|
@@ -3186,6 +3185,8 @@ var PATHS = {
|
|
|
3186
3185
|
configFile: path.join(DIRS.runtime, "config.yaml"),
|
|
3187
3186
|
logFile: path.join(DIRS.logs, "mihomo.log"),
|
|
3188
3187
|
pidFile: path.join(DIRS.runtime, "pid"),
|
|
3188
|
+
/** 服务操作跨进程锁:start/stop/install/uninstall 的 enable/bootstrap/bootout/disable 串行化 */
|
|
3189
|
+
serviceLock: path.join(DIRS.runtime, "service.lock"),
|
|
3189
3190
|
configStage1Subscription: path.join(DIRS.runtime, "1.subscription.yaml"),
|
|
3190
3191
|
configStage2Overwrite: path.join(DIRS.runtime, "2.overwrite.yaml"),
|
|
3191
3192
|
configStage3System: path.join(DIRS.runtime, "3.system.yaml"),
|
|
@@ -3360,12 +3361,57 @@ function updateSettings(mutate) {
|
|
|
3360
3361
|
function invalidateSettingsCache() {
|
|
3361
3362
|
settingsCache = null;
|
|
3362
3363
|
}
|
|
3364
|
+
function validatePort(value, key) {
|
|
3365
|
+
if (value === void 0) return void 0;
|
|
3366
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 65535) {
|
|
3367
|
+
throw new CliError(`settings.json \u7684 ${key} \u9700\u4E3A 1-65535 \u7684\u6574\u6570\uFF0C\u5F53\u524D\u662F ${JSON.stringify(value)}`, {
|
|
3368
|
+
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
3369
|
+
hint: ["\u793A\u4F8B:", ' "ports": { "mixed": 17890, "controller": 19090 }', "\u4E24\u4E2A\u952E\u5747\u53EF\u9009\uFF1B\u5220\u6389 ports \u5219\u56DE\u5230\u9ED8\u8BA4\u7AEF\u53E3 7890/9090"]
|
|
3370
|
+
});
|
|
3371
|
+
}
|
|
3372
|
+
return value;
|
|
3373
|
+
}
|
|
3374
|
+
function getPorts() {
|
|
3375
|
+
const ports = readSettings().ports;
|
|
3376
|
+
if (ports === void 0) return { mixed: DEFAULT_MIXED_PORT, controller: CONTROLLER_PORT };
|
|
3377
|
+
if (ports === null || typeof ports !== "object" || Array.isArray(ports)) {
|
|
3378
|
+
throw new CliError('settings.json \u7684 ports \u9700\u4E3A\u5BF9\u8C61\uFF0C\u5982 { "mixed": 17890, "controller": 19090 }', { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
3379
|
+
}
|
|
3380
|
+
const mixed = validatePort(ports.mixed, "ports.mixed");
|
|
3381
|
+
const controller = validatePort(ports.controller, "ports.controller");
|
|
3382
|
+
if (mixed !== void 0 && controller !== void 0 && mixed === controller) {
|
|
3383
|
+
throw new CliError(`ports.mixed \u4E0E ports.controller \u4E0D\u80FD\u76F8\u540C\uFF08\u5F53\u524D\u5747\u4E3A ${mixed}\uFF09`, {
|
|
3384
|
+
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
3385
|
+
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"]
|
|
3386
|
+
});
|
|
3387
|
+
}
|
|
3388
|
+
return { mixed: mixed ?? DEFAULT_MIXED_PORT, controller: controller ?? CONTROLLER_PORT };
|
|
3389
|
+
}
|
|
3363
3390
|
function maskSingleUrl(url) {
|
|
3364
3391
|
try {
|
|
3365
3392
|
const parsed = new URL(url);
|
|
3366
|
-
const tokenKeys =
|
|
3367
|
-
|
|
3368
|
-
|
|
3393
|
+
const tokenKeys = /* @__PURE__ */ new Set([
|
|
3394
|
+
"token",
|
|
3395
|
+
"key",
|
|
3396
|
+
"secret",
|
|
3397
|
+
"pass",
|
|
3398
|
+
"password",
|
|
3399
|
+
"auth",
|
|
3400
|
+
"access_token",
|
|
3401
|
+
"api_key",
|
|
3402
|
+
"uuid",
|
|
3403
|
+
"sid",
|
|
3404
|
+
"id",
|
|
3405
|
+
"sub",
|
|
3406
|
+
"user",
|
|
3407
|
+
"email",
|
|
3408
|
+
"passwd",
|
|
3409
|
+
"apikey",
|
|
3410
|
+
"api_key",
|
|
3411
|
+
"access"
|
|
3412
|
+
]);
|
|
3413
|
+
for (const [key, value] of parsed.searchParams) {
|
|
3414
|
+
if (tokenKeys.has(key.toLowerCase()) || value.length >= 16) {
|
|
3369
3415
|
parsed.searchParams.set(key, "***");
|
|
3370
3416
|
}
|
|
3371
3417
|
}
|
|
@@ -3413,7 +3459,8 @@ function saveSubscriptionCache(subName, data) {
|
|
|
3413
3459
|
ensureDirs();
|
|
3414
3460
|
withFileLock(PATHS.subscriptionsCacheFile, () => {
|
|
3415
3461
|
const cache = readSubscriptionCache();
|
|
3416
|
-
|
|
3462
|
+
const old = cache[subName];
|
|
3463
|
+
cache[subName] = { ...old && typeof old === "object" && !Array.isArray(old) ? old : {}, ...data };
|
|
3417
3464
|
writeSubscriptionCache(cache);
|
|
3418
3465
|
});
|
|
3419
3466
|
}
|
|
@@ -3487,14 +3534,14 @@ function removeSubscription(name) {
|
|
|
3487
3534
|
switchedTo = subs.length > 0 ? subs[0].name : null;
|
|
3488
3535
|
updates.active_subscription = switchedTo ?? void 0;
|
|
3489
3536
|
}
|
|
3537
|
+
try {
|
|
3538
|
+
fs2.rmSync(getSubscriptionRawConfigPath(name), { force: true });
|
|
3539
|
+
} catch {
|
|
3540
|
+
}
|
|
3490
3541
|
return updates;
|
|
3491
3542
|
});
|
|
3492
3543
|
if (!found) return null;
|
|
3493
3544
|
deleteSubscriptionCache(name);
|
|
3494
|
-
try {
|
|
3495
|
-
fs2.rmSync(getSubscriptionRawConfigPath(name), { force: true });
|
|
3496
|
-
} catch {
|
|
3497
|
-
}
|
|
3498
3545
|
return switchedTo;
|
|
3499
3546
|
}
|
|
3500
3547
|
function setDefaultSubscription(name) {
|
|
@@ -3801,6 +3848,11 @@ function sleep(ms) {
|
|
|
3801
3848
|
function escapeRegExp(s) {
|
|
3802
3849
|
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
3803
3850
|
}
|
|
3851
|
+
function sanitizeTerminal(s) {
|
|
3852
|
+
const ansiEscape = /\x1b\[[0-9;]*[a-zA-Z]/g;
|
|
3853
|
+
const controlChars = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g;
|
|
3854
|
+
return s.replace(ansiEscape, "").replace(controlChars, "");
|
|
3855
|
+
}
|
|
3804
3856
|
function shellQuote(s) {
|
|
3805
3857
|
return `'${s.replace(/'/g, "'\\''")}'`;
|
|
3806
3858
|
}
|
|
@@ -3897,6 +3949,21 @@ function subscriptionUrgency(entry, nowMs = Date.now()) {
|
|
|
3897
3949
|
function hasFlag(args, short, long) {
|
|
3898
3950
|
return !!args && (args.includes(short) || long !== void 0 && args.includes(long));
|
|
3899
3951
|
}
|
|
3952
|
+
function assertKnownFlags(args, known, command) {
|
|
3953
|
+
if (!args) return;
|
|
3954
|
+
const knownSet = new Set(known);
|
|
3955
|
+
for (const a of args) {
|
|
3956
|
+
if (!a.startsWith("-") || a === "-") continue;
|
|
3957
|
+
if (knownSet.has(a)) continue;
|
|
3958
|
+
const eqIdx = a.indexOf("=");
|
|
3959
|
+
if (eqIdx > 0 && knownSet.has(a.slice(0, eqIdx))) continue;
|
|
3960
|
+
if (a.length > 2 && a.startsWith("-") && !a.startsWith("--") && knownSet.has(a.slice(0, 2))) continue;
|
|
3961
|
+
throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${a}`, {
|
|
3962
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
3963
|
+
hint: [`\u53EF\u7528\u9009\u9879: ${known.join(", ")}`, "", `\u7528\u6CD5: mihomo ${command}`]
|
|
3964
|
+
});
|
|
3965
|
+
}
|
|
3966
|
+
}
|
|
3900
3967
|
function parseIntArg(args, short, long, defaultValue) {
|
|
3901
3968
|
if (!args) return defaultValue;
|
|
3902
3969
|
const parse = (raw, flag) => {
|
|
@@ -3919,6 +3986,9 @@ function parseIntArg(args, short, long, defaultValue) {
|
|
|
3919
3986
|
if (args[i].startsWith(`${long}=`)) {
|
|
3920
3987
|
return parse(args[i].slice(long.length + 1), long);
|
|
3921
3988
|
}
|
|
3989
|
+
if (args[i].startsWith(short) && args[i].length > short.length && /^\d+$/.test(args[i].slice(short.length))) {
|
|
3990
|
+
return parse(args[i].slice(short.length), short);
|
|
3991
|
+
}
|
|
3922
3992
|
}
|
|
3923
3993
|
return defaultValue;
|
|
3924
3994
|
}
|
|
@@ -4058,8 +4128,11 @@ function parseYamlOrJson(content, errorMsg) {
|
|
|
4058
4128
|
} catch {
|
|
4059
4129
|
}
|
|
4060
4130
|
try {
|
|
4061
|
-
|
|
4062
|
-
|
|
4131
|
+
const result = JSON.parse(content);
|
|
4132
|
+
if (result != null && typeof result === "object" && !Array.isArray(result)) return result;
|
|
4133
|
+
throw new Error(`${errorMsg || "\u5185\u5BB9"}\u4E0D\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61`);
|
|
4134
|
+
} catch (e) {
|
|
4135
|
+
if (e instanceof Error && e.message.includes("\u4E0D\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61")) throw e;
|
|
4063
4136
|
throw new Error(`${errorMsg || "\u5185\u5BB9"}\u683C\u5F0F\u9519\u8BEF\uFF0C\u65E0\u6CD5\u89E3\u6790\u4E3A YAML \u6216 JSON`);
|
|
4064
4137
|
}
|
|
4065
4138
|
}
|
|
@@ -4268,7 +4341,8 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4268
4341
|
const overwriteEnabled = isOverwriteEnabled();
|
|
4269
4342
|
const allFiles = overwriteEnabled ? loadOverwriteFile() : [];
|
|
4270
4343
|
const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
|
|
4271
|
-
const
|
|
4344
|
+
const working = structuredClone(subscriptionConfig);
|
|
4345
|
+
const withOverwrites = applyOverwrite(working, overwriteFiles);
|
|
4272
4346
|
if (overwriteFiles.length > 0) {
|
|
4273
4347
|
const baseProxies = Array.isArray(subscriptionConfig.proxies) ? subscriptionConfig.proxies : [];
|
|
4274
4348
|
const baseProxyNames = new Set(
|
|
@@ -4282,8 +4356,9 @@ function buildConfig(subRawContent, mode, scope) {
|
|
|
4282
4356
|
systemConfig[key] = value;
|
|
4283
4357
|
}
|
|
4284
4358
|
}
|
|
4285
|
-
|
|
4286
|
-
systemConfig["
|
|
4359
|
+
const ports = getPorts();
|
|
4360
|
+
systemConfig["external-controller"] = `127.0.0.1:${ports.controller}`;
|
|
4361
|
+
systemConfig["mixed-port"] = ports.mixed;
|
|
4287
4362
|
delete withOverwrites["mixed-port"];
|
|
4288
4363
|
delete withOverwrites.port;
|
|
4289
4364
|
delete withOverwrites["socks-port"];
|
|
@@ -4450,8 +4525,15 @@ function rotateLog() {
|
|
|
4450
4525
|
if (!fs5.existsSync(logFile)) return null;
|
|
4451
4526
|
const stat = fs5.statSync(logFile);
|
|
4452
4527
|
if (stat.size === 0) return null;
|
|
4453
|
-
const
|
|
4454
|
-
|
|
4528
|
+
const timestamp = formatLocalTimestamp();
|
|
4529
|
+
let rotatedName = `mihomo.${timestamp}.log`;
|
|
4530
|
+
let rotatedPath = path4.join(DIRS.logs, rotatedName);
|
|
4531
|
+
let seq = 1;
|
|
4532
|
+
while (fs5.existsSync(rotatedPath)) {
|
|
4533
|
+
rotatedName = `mihomo.${timestamp}.${seq}.log`;
|
|
4534
|
+
rotatedPath = path4.join(DIRS.logs, rotatedName);
|
|
4535
|
+
seq++;
|
|
4536
|
+
}
|
|
4455
4537
|
fs5.renameSync(logFile, rotatedPath);
|
|
4456
4538
|
return rotatedPath;
|
|
4457
4539
|
}
|
|
@@ -4464,7 +4546,7 @@ function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
|
|
|
4464
4546
|
let deleted = 0;
|
|
4465
4547
|
let errors = 0;
|
|
4466
4548
|
for (const file of files) {
|
|
4467
|
-
if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}
|
|
4549
|
+
if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(\.\d+)?\.log$/)) continue;
|
|
4468
4550
|
try {
|
|
4469
4551
|
const filePath = path4.join(logsDir, file);
|
|
4470
4552
|
const stat = fs5.statSync(filePath);
|
|
@@ -4901,8 +4983,10 @@ async function installService(wasRunning) {
|
|
|
4901
4983
|
fs8.copyFileSync(stagePath, PATHS.userAgentPlist);
|
|
4902
4984
|
fs8.chmodSync(PATHS.userAgentPlist, 420);
|
|
4903
4985
|
if (wasRunning) {
|
|
4904
|
-
|
|
4905
|
-
|
|
4986
|
+
withFileLock(PATHS.serviceLock, () => {
|
|
4987
|
+
runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
|
|
4988
|
+
runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u88C5\u8F7D\u670D\u52A1");
|
|
4989
|
+
});
|
|
4906
4990
|
}
|
|
4907
4991
|
} finally {
|
|
4908
4992
|
try {
|
|
@@ -4938,8 +5022,13 @@ async function startService() {
|
|
|
4938
5022
|
await bootoutService();
|
|
4939
5023
|
await waitUntilUnloaded();
|
|
4940
5024
|
rotateAndCleanupLogs();
|
|
4941
|
-
|
|
4942
|
-
|
|
5025
|
+
withFileLock(PATHS.serviceLock, () => {
|
|
5026
|
+
if (isServiceDisabledInLaunchd()) {
|
|
5027
|
+
return;
|
|
5028
|
+
}
|
|
5029
|
+
runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
|
|
5030
|
+
runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u542F\u52A8\u670D\u52A1");
|
|
5031
|
+
});
|
|
4943
5032
|
}
|
|
4944
5033
|
function disableServiceAutoStart() {
|
|
4945
5034
|
assertServiceLabelSafe();
|
|
@@ -4952,14 +5041,19 @@ function disableServiceAutoStart() {
|
|
|
4952
5041
|
}
|
|
4953
5042
|
async function stopService() {
|
|
4954
5043
|
assertServiceLabelSafe();
|
|
4955
|
-
await
|
|
5044
|
+
await withFileLock(PATHS.serviceLock, () => {
|
|
5045
|
+
bootoutService();
|
|
5046
|
+
disableServiceAutoStart();
|
|
5047
|
+
});
|
|
4956
5048
|
await waitUntilUnloaded();
|
|
4957
|
-
disableServiceAutoStart();
|
|
4958
5049
|
killResidualKernels();
|
|
4959
5050
|
}
|
|
4960
5051
|
async function uninstallService() {
|
|
4961
5052
|
assertServiceLabelSafe();
|
|
4962
|
-
await
|
|
5053
|
+
await withFileLock(PATHS.serviceLock, () => {
|
|
5054
|
+
bootoutService();
|
|
5055
|
+
disableServiceAutoStart();
|
|
5056
|
+
});
|
|
4963
5057
|
await waitUntilUnloaded();
|
|
4964
5058
|
try {
|
|
4965
5059
|
fs8.rmSync(PATHS.userAgentPlist, { force: true });
|
|
@@ -4977,7 +5071,14 @@ function cleanupLegacySystemInstall() {
|
|
|
4977
5071
|
assertServiceLabelSafe();
|
|
4978
5072
|
const script = [
|
|
4979
5073
|
"#!/bin/bash",
|
|
4980
|
-
|
|
5074
|
+
// bootout 退出码分级:113=未装载(daemon 已不在,正常),其余是真实失败。
|
|
5075
|
+
// 此前 || true 吞掉所有错误,daemon 仍在跑却继续 rm plist 并报「已清理」
|
|
5076
|
+
`bootout_code=0`,
|
|
5077
|
+
`launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || bootout_code=$?`,
|
|
5078
|
+
`if [ $bootout_code -ne 0 ] && [ $bootout_code -ne 113 ]; then`,
|
|
5079
|
+
` echo "launchctl bootout \u5931\u8D25\uFF08\u9000\u51FA\u7801 $bootout_code\uFF09" >&2`,
|
|
5080
|
+
` exit 1`,
|
|
5081
|
+
`fi`,
|
|
4981
5082
|
`rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
|
|
4982
5083
|
`chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
|
|
4983
5084
|
`chown -R "$SUDO_UID:$SUDO_GID" ${shellQuote(DIRS.data)} 2>/dev/null || true`,
|
|
@@ -4987,6 +5088,17 @@ function cleanupLegacySystemInstall() {
|
|
|
4987
5088
|
].join("\n");
|
|
4988
5089
|
runSudoScript(script, { action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1", file: "legacy-cleanup.sh" });
|
|
4989
5090
|
}
|
|
5091
|
+
function cleanupLegacyInstallOrThrow() {
|
|
5092
|
+
try {
|
|
5093
|
+
cleanupLegacySystemInstall();
|
|
5094
|
+
} catch (e) {
|
|
5095
|
+
if (e instanceof CliError) throw e;
|
|
5096
|
+
throw new CliError(e.message, {
|
|
5097
|
+
label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
|
|
5098
|
+
hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
|
|
5099
|
+
});
|
|
5100
|
+
}
|
|
5101
|
+
}
|
|
4990
5102
|
function logOversized() {
|
|
4991
5103
|
try {
|
|
4992
5104
|
return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
@@ -4997,17 +5109,23 @@ function logOversized() {
|
|
|
4997
5109
|
async function tryHotReload() {
|
|
4998
5110
|
const status = getServiceStatus();
|
|
4999
5111
|
if (!status.running || status.pid === null) return false;
|
|
5112
|
+
const baseUrl = `http://127.0.0.1:${getPorts().controller}`;
|
|
5000
5113
|
const controller = new AbortController();
|
|
5001
5114
|
const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
|
|
5002
5115
|
const secret = readSettings().controller_secret;
|
|
5003
5116
|
const headers = { "Content-Type": "application/json" };
|
|
5004
5117
|
if (secret) headers.Authorization = `Bearer ${secret}`;
|
|
5005
5118
|
try {
|
|
5006
|
-
const probe = await fetch(`${
|
|
5119
|
+
const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
|
|
5007
5120
|
if (!probe.ok) return false;
|
|
5008
5121
|
const info = await probe.json();
|
|
5009
5122
|
if (typeof info?.version !== "string") return false;
|
|
5010
|
-
const
|
|
5123
|
+
const port = getPorts().controller;
|
|
5124
|
+
const lsofResult = spawnSync4("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
|
|
5125
|
+
if (lsofResult.status !== 0) return false;
|
|
5126
|
+
const listenerPid = Number.parseInt(lsofResult.stdout.trim(), 10);
|
|
5127
|
+
if (!Number.isFinite(listenerPid) || listenerPid !== status.pid) return false;
|
|
5128
|
+
const res = await fetch(`${baseUrl}/configs?force=true`, {
|
|
5011
5129
|
method: "PUT",
|
|
5012
5130
|
headers,
|
|
5013
5131
|
body: "{}",
|
|
@@ -5026,7 +5144,13 @@ async function restartService() {
|
|
|
5026
5144
|
}
|
|
5027
5145
|
if (!logOversized() && await tryHotReload()) return { hotReloaded: true };
|
|
5028
5146
|
if (logOversized()) {
|
|
5029
|
-
const
|
|
5147
|
+
const timestamp = formatLocalTimestamp();
|
|
5148
|
+
let archiveFile = path6.join(DIRS.logs, `mihomo.${timestamp}.log`);
|
|
5149
|
+
let seq = 1;
|
|
5150
|
+
while (fs8.existsSync(archiveFile)) {
|
|
5151
|
+
archiveFile = path6.join(DIRS.logs, `mihomo.${timestamp}.${seq}.log`);
|
|
5152
|
+
seq++;
|
|
5153
|
+
}
|
|
5030
5154
|
try {
|
|
5031
5155
|
fs8.copyFileSync(PATHS.logFile, archiveFile);
|
|
5032
5156
|
fs8.writeFileSync(PATHS.logFile, "");
|
|
@@ -5125,6 +5249,11 @@ function printVersion() {
|
|
|
5125
5249
|
console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
|
|
5126
5250
|
}
|
|
5127
5251
|
|
|
5252
|
+
// src/commands/completion.ts
|
|
5253
|
+
import fs10 from "fs";
|
|
5254
|
+
import os2 from "os";
|
|
5255
|
+
import path8 from "path";
|
|
5256
|
+
|
|
5128
5257
|
// src/open.ts
|
|
5129
5258
|
import { spawn } from "child_process";
|
|
5130
5259
|
|
|
@@ -5271,7 +5400,11 @@ async function startTun() {
|
|
|
5271
5400
|
}
|
|
5272
5401
|
const staleState = checkStaleState();
|
|
5273
5402
|
if (staleState.needsCleanup) {
|
|
5274
|
-
|
|
5403
|
+
if (staleState.allPids.length > 0) {
|
|
5404
|
+
console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
|
|
5405
|
+
} else {
|
|
5406
|
+
console.log("\u6E05\u7406\u6B8B\u7559\u7684 root pid \u6587\u4EF6...");
|
|
5407
|
+
}
|
|
5275
5408
|
}
|
|
5276
5409
|
console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
|
|
5277
5410
|
runSudoScript(buildTunLaunchScript(), {
|
|
@@ -5354,6 +5487,9 @@ function createHttpClient(options = {}) {
|
|
|
5354
5487
|
signal,
|
|
5355
5488
|
headers: { "User-Agent": `mihomo-cli/${VERSION}` }
|
|
5356
5489
|
});
|
|
5490
|
+
if (url.startsWith("https://") && !response.url.startsWith("https://")) {
|
|
5491
|
+
throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${response.url}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
|
|
5492
|
+
}
|
|
5357
5493
|
if (!response.ok) {
|
|
5358
5494
|
const error = new Error(`HTTP ${response.status}`);
|
|
5359
5495
|
error.response = { status: response.status };
|
|
@@ -5430,6 +5566,13 @@ async function withSpinner(label, fn) {
|
|
|
5430
5566
|
function resolveUpdateInterval(cachedInterval) {
|
|
5431
5567
|
return cachedInterval && cachedInterval > 0 ? cachedInterval : DEFAULT_UPDATE_INTERVAL_HOURS;
|
|
5432
5568
|
}
|
|
5569
|
+
function isSubscriptionStale(cached, nowMs = Date.now()) {
|
|
5570
|
+
if (!cached.updated_at) return false;
|
|
5571
|
+
const t = new Date(cached.updated_at).getTime();
|
|
5572
|
+
if (Number.isNaN(t) || t > nowMs) return false;
|
|
5573
|
+
const ageHours = (nowMs - t) / 36e5;
|
|
5574
|
+
return ageHours > resolveUpdateInterval(cached.update_interval);
|
|
5575
|
+
}
|
|
5433
5576
|
var HTTP_CLIENT = createHttpClient({ timeout: 6e4 });
|
|
5434
5577
|
function isValidHttpUrl(url) {
|
|
5435
5578
|
try {
|
|
@@ -5472,8 +5615,9 @@ function extractSubscriptionMeta(headers) {
|
|
|
5472
5615
|
return {
|
|
5473
5616
|
userInfo: parseUserInfo(headers?.get("subscription-userinfo") ?? null),
|
|
5474
5617
|
updateInterval: parsePositiveInterval(headers?.get("profile-update-interval")),
|
|
5475
|
-
|
|
5476
|
-
|
|
5618
|
+
// 服务器返回的字符串可能含 ANSI 转义/控制字符,展示前消毒(防终端输出伪造)
|
|
5619
|
+
webPageUrl: sanitizeTerminal(headers?.get("profile-web-page-url") || "") || null,
|
|
5620
|
+
username: sanitizeTerminal(parseUsernameFromContentDisposition(headers?.get("content-disposition") ?? null) || "") || null
|
|
5477
5621
|
};
|
|
5478
5622
|
}
|
|
5479
5623
|
function saveSubscriptionMeta(subName, meta) {
|
|
@@ -5551,7 +5695,9 @@ function assertLooksLikeSubscription(parsed, maskedUrl) {
|
|
|
5551
5695
|
const providers = parsed["proxy-providers"];
|
|
5552
5696
|
const hasProviders = providers != null && typeof providers === "object" && Object.keys(providers).length > 0;
|
|
5553
5697
|
if (hasProxies || hasGroups || hasProviders) return;
|
|
5554
|
-
const serverMsg =
|
|
5698
|
+
const serverMsg = sanitizeTerminal(
|
|
5699
|
+
["error", "message", "msg", "info"].map((k) => parsed[k]).find((v) => typeof v === "string" && v.length > 0) ?? ""
|
|
5700
|
+
);
|
|
5555
5701
|
throw new CliError("\u8BA2\u9605\u5185\u5BB9\u4E0D\u542B\u4EFB\u4F55\u8282\u70B9\u6765\u6E90\uFF08proxies / proxy-groups / proxy-providers \u5747\u4E3A\u7A7A\uFF09", {
|
|
5556
5702
|
label: "\u8BA2\u9605\u65E0\u6548",
|
|
5557
5703
|
hint: [
|
|
@@ -5782,6 +5928,8 @@ function buildStatusJson(args) {
|
|
|
5782
5928
|
...args.cached?.download !== void 0 ? { download: args.cached.download } : {},
|
|
5783
5929
|
...args.cached?.total !== void 0 ? { total: args.cached.total } : {},
|
|
5784
5930
|
...args.cached?.expire !== void 0 ? { expire: args.cached.expire } : {},
|
|
5931
|
+
...args.cached?.updated_at !== void 0 ? { updatedAt: args.cached.updated_at } : {},
|
|
5932
|
+
stale: args.cached ? isSubscriptionStale(args.cached) : false,
|
|
5785
5933
|
urgency
|
|
5786
5934
|
} : null,
|
|
5787
5935
|
overwrite: { enabled: args.overwriteEnabled, files: args.overwriteFiles },
|
|
@@ -5796,6 +5944,7 @@ function buildStatusJson(args) {
|
|
|
5796
5944
|
};
|
|
5797
5945
|
}
|
|
5798
5946
|
async function printStatus(args = []) {
|
|
5947
|
+
assertKnownFlags(args, ["-j", "--json", "--no-probe"], "status [--json] [--no-probe]");
|
|
5799
5948
|
const asJson = hasFlag(args, "-j", "--json");
|
|
5800
5949
|
const skipProbe = hasFlag(args, "--no-probe");
|
|
5801
5950
|
const service = getServiceStatus();
|
|
@@ -5886,6 +6035,14 @@ async function printStatus(args = []) {
|
|
|
5886
6035
|
subLine += ` (${formatProxySummary(info)})`;
|
|
5887
6036
|
}
|
|
5888
6037
|
console.log(subLine);
|
|
6038
|
+
if (cached?.updated_at) {
|
|
6039
|
+
const rel = formatRelativeTime(cached.updated_at) || formatDate(cached.updated_at);
|
|
6040
|
+
if (isSubscriptionStale(cached)) {
|
|
6041
|
+
console.log(colors.yellow(`\u66F4\u65B0: ${rel}\uFF08\u5DF2\u8D85\u8FC7 ${resolveUpdateInterval(cached.update_interval)} \u5C0F\u65F6\u95F4\u9694\uFF0C\u5EFA\u8BAE mihomo sub update\uFF09`));
|
|
6042
|
+
} else {
|
|
6043
|
+
console.log(`${colors.gray("\u66F4\u65B0: ")}${rel}`);
|
|
6044
|
+
}
|
|
6045
|
+
}
|
|
5889
6046
|
const traffic = cached ? formatTraffic(cached.upload, cached.download, cached.total) : null;
|
|
5890
6047
|
if (traffic) {
|
|
5891
6048
|
console.log(`${colors.gray("\u6D41\u91CF: ")}${trafficColor(traffic, urgency, cached?.total, cached?.upload, cached?.download)}`);
|
|
@@ -5938,7 +6095,7 @@ function resolveStartMode(args) {
|
|
|
5938
6095
|
return modeToken === "tun" ? "tun" : "mixed";
|
|
5939
6096
|
}
|
|
5940
6097
|
async function cmdStart(args) {
|
|
5941
|
-
|
|
6098
|
+
assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "start [tun|mixed]");
|
|
5942
6099
|
const targetMode = resolveStartMode(args);
|
|
5943
6100
|
if (!hasKernel()) {
|
|
5944
6101
|
throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
|
|
@@ -5999,7 +6156,7 @@ async function cmdStart(args) {
|
|
|
5999
6156
|
}
|
|
6000
6157
|
await printStatus();
|
|
6001
6158
|
if (targetMode === "mixed") {
|
|
6002
|
-
console.log(colors.gray(
|
|
6159
|
+
console.log(colors.gray(`\u63D0\u793A: Mixed \u6A21\u5F0F\u9700\u5728\u7CFB\u7EDF\u8BBE\u7F6E\u914D\u7F6E HTTP/SOCKS \u4EE3\u7406 127.0.0.1:${getPorts().mixed}\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`));
|
|
6003
6160
|
console.log("");
|
|
6004
6161
|
}
|
|
6005
6162
|
}
|
|
@@ -6038,17 +6195,6 @@ async function restartToApply(args) {
|
|
|
6038
6195
|
await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
|
|
6039
6196
|
return true;
|
|
6040
6197
|
}
|
|
6041
|
-
function cleanupLegacyInstallOrThrow() {
|
|
6042
|
-
try {
|
|
6043
|
-
cleanupLegacySystemInstall();
|
|
6044
|
-
} catch (e) {
|
|
6045
|
-
if (e instanceof CliError) throw e;
|
|
6046
|
-
throw new CliError(e.message, {
|
|
6047
|
-
label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
|
|
6048
|
-
hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
|
|
6049
|
-
});
|
|
6050
|
-
}
|
|
6051
|
-
}
|
|
6052
6198
|
|
|
6053
6199
|
// src/commands/directory.ts
|
|
6054
6200
|
function openDirectory(args) {
|
|
@@ -6160,6 +6306,7 @@ var SUBCOMMANDS2 = [
|
|
|
6160
6306
|
{ name: "off", aliases: ["disable"], description: "\u7981\u7528\u8986\u5199", handler: (args) => setOverwrite(false, args) }
|
|
6161
6307
|
];
|
|
6162
6308
|
async function cmdOverwrite(args) {
|
|
6309
|
+
assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "ow [on|off]");
|
|
6163
6310
|
await dispatchSubcommand(args, SUBCOMMANDS2, {
|
|
6164
6311
|
// 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
|
|
6165
6312
|
fallback: () => {
|
|
@@ -6177,6 +6324,7 @@ async function cmdOverwrite(args) {
|
|
|
6177
6324
|
}
|
|
6178
6325
|
|
|
6179
6326
|
// src/commands/subscription.ts
|
|
6327
|
+
import { spawnSync as spawnSync5 } from "child_process";
|
|
6180
6328
|
function printRestartHintIfRunning() {
|
|
6181
6329
|
if (getRunningState().running) {
|
|
6182
6330
|
console.log(colors.yellow("\u63D0\u793A: \u8FD0\u884C\u4E2D\u7684\u5B9E\u4F8B\u4ECD\u4F7F\u7528\u65E7\u914D\u7F6E\uFF0C\u6267\u884C mihomo start \u4F7F\u66F4\u65B0\u751F\u6548"));
|
|
@@ -6230,11 +6378,37 @@ function assertNotFlagLike(name, usage) {
|
|
|
6230
6378
|
});
|
|
6231
6379
|
}
|
|
6232
6380
|
}
|
|
6381
|
+
function readUrlFromClipboard() {
|
|
6382
|
+
if (!process.stdin.isTTY) return null;
|
|
6383
|
+
try {
|
|
6384
|
+
const r = spawnSync5("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
|
|
6385
|
+
if (r.status !== 0) return null;
|
|
6386
|
+
const text = (r.stdout || "").trim();
|
|
6387
|
+
return isValidHttpUrl(text) ? text : null;
|
|
6388
|
+
} catch {
|
|
6389
|
+
return null;
|
|
6390
|
+
}
|
|
6391
|
+
}
|
|
6233
6392
|
async function subAdd(args) {
|
|
6234
|
-
|
|
6393
|
+
let url = args[2]?.trim();
|
|
6235
6394
|
const name = args[3] || "default";
|
|
6236
6395
|
if (!url) {
|
|
6237
|
-
|
|
6396
|
+
const clipped = readUrlFromClipboard();
|
|
6397
|
+
if (clipped) {
|
|
6398
|
+
console.log("\u672A\u63D0\u4F9B URL\uFF0C\u4ECE\u526A\u8D34\u677F\u8BFB\u53D6\u5230:");
|
|
6399
|
+
console.log(` ${maskUrl(clipped)}`);
|
|
6400
|
+
if (!await confirmPrompt(`\u6DFB\u52A0\u4E3A\u8BA2\u9605 "${name}"?`)) {
|
|
6401
|
+
console.log("\u5DF2\u53D6\u6D88");
|
|
6402
|
+
return;
|
|
6403
|
+
}
|
|
6404
|
+
url = clipped;
|
|
6405
|
+
} else if (process.stdin.isTTY) {
|
|
6406
|
+
throw new CliError("\u526A\u8D34\u677F\u4E2D\u6CA1\u6709\u6709\u6548\u7684\u8BA2\u9605 URL", {
|
|
6407
|
+
hint: ["\u5148\u590D\u5236\u8BA2\u9605\u94FE\u63A5\u540E\u91CD\u8BD5\uFF0C\u6216\u663E\u5F0F\u4F20\u5165:", " mihomo sub add <url> [name]"]
|
|
6408
|
+
});
|
|
6409
|
+
} else {
|
|
6410
|
+
throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL", { hint: ["\u7528\u6CD5: mihomo sub add <url> [name]"] });
|
|
6411
|
+
}
|
|
6238
6412
|
}
|
|
6239
6413
|
if (!isValidHttpUrl(url)) {
|
|
6240
6414
|
throw new CliError("\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u8BA2\u9605 URL\uFF08\u9700\u4EE5 http:// \u6216 https:// \u5F00\u5934\uFF09");
|
|
@@ -6252,10 +6426,11 @@ async function subAdd(args) {
|
|
|
6252
6426
|
throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25" });
|
|
6253
6427
|
}
|
|
6254
6428
|
console.log("");
|
|
6429
|
+
printRestartHintIfRunning();
|
|
6255
6430
|
printSubscriptionList();
|
|
6256
6431
|
}
|
|
6257
6432
|
async function subUpdate(args) {
|
|
6258
|
-
const name = args
|
|
6433
|
+
const name = getNonFlagArg(args, 2);
|
|
6259
6434
|
const subs = getSubscriptions();
|
|
6260
6435
|
if (subs.length === 0) {
|
|
6261
6436
|
throw new CliError("\u6CA1\u6709\u8BA2\u9605");
|
|
@@ -6286,7 +6461,7 @@ async function subUpdate(args) {
|
|
|
6286
6461
|
printSubscriptionList();
|
|
6287
6462
|
}
|
|
6288
6463
|
async function subUse(args) {
|
|
6289
|
-
const name = args
|
|
6464
|
+
const name = getNonFlagArg(args, 2);
|
|
6290
6465
|
const subs = getSubscriptions();
|
|
6291
6466
|
if (subs.length === 0) {
|
|
6292
6467
|
throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo sub add <url> [name]" });
|
|
@@ -6350,6 +6525,7 @@ var SUBCOMMANDS3 = [
|
|
|
6350
6525
|
{ name: "remove", aliases: ["rm", "delete"], description: "\u5220\u9664\u8BA2\u9605", handler: subRemove }
|
|
6351
6526
|
];
|
|
6352
6527
|
async function cmdSubscription(args) {
|
|
6528
|
+
assertKnownFlags(args, ["-y", "--yes", "-s", "--no-update", "-u", "--update-timeout"], "sub [add|update|use|remove]");
|
|
6353
6529
|
await dispatchSubcommand(args, SUBCOMMANDS3, {
|
|
6354
6530
|
// 无子命令 → 列表;未知子命令 → 报错
|
|
6355
6531
|
fallback: printSubscriptionList,
|
|
@@ -6365,7 +6541,7 @@ async function cmdSubscription(args) {
|
|
|
6365
6541
|
|
|
6366
6542
|
// src/commands/completion.ts
|
|
6367
6543
|
function commandWords(commands) {
|
|
6368
|
-
return commands.filter((c) => !c.hidden).
|
|
6544
|
+
return commands.filter((c) => !c.hidden).flatMap((c) => [{ word: c.name, desc: c.usage[0]?.description ?? "" }, ...c.aliases.map((a) => ({ word: a, desc: c.usage[0]?.description ?? "" }))]);
|
|
6369
6545
|
}
|
|
6370
6546
|
function subWords(subs) {
|
|
6371
6547
|
return subs.flatMap((s) => [{ word: s.name, desc: s.description ?? "" }, ...(s.aliases ?? []).map((a) => ({ word: a, desc: s.description ?? "" }))]);
|
|
@@ -6384,7 +6560,7 @@ function buildZsh(commands, groups) {
|
|
|
6384
6560
|
const lines = [
|
|
6385
6561
|
"#compdef mihomo mhm mh mihomo-cli",
|
|
6386
6562
|
"",
|
|
6387
|
-
'# mihomo-cli zsh \u8865\u5168\uFF08mihomo completion zsh \u751F\u6210\uFF1B\u5B89\u88C5:
|
|
6563
|
+
'# mihomo-cli zsh \u8865\u5168\uFF08mihomo completion zsh \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion install zsh\uFF0C\u6216 eval "$(mihomo completion zsh)"\uFF09',
|
|
6388
6564
|
"",
|
|
6389
6565
|
"_mihomo() {",
|
|
6390
6566
|
" local -a commands subcmds",
|
|
@@ -6405,23 +6581,26 @@ function buildZsh(commands, groups) {
|
|
|
6405
6581
|
];
|
|
6406
6582
|
for (const group of groups) {
|
|
6407
6583
|
const aliases = group.tokens.join("|");
|
|
6584
|
+
const isDirectory = group.tokens.includes("directory");
|
|
6408
6585
|
lines.push(` ${aliases})`);
|
|
6409
6586
|
lines.push(" subcmds=(");
|
|
6410
6587
|
for (const s of group.words) lines.push(` '${s.word}:${s.desc.replace(/'/g, "''")}'`);
|
|
6411
6588
|
lines.push(" )");
|
|
6412
6589
|
lines.push(" if (( CURRENT == 2 )); then");
|
|
6413
6590
|
lines.push(" _describe 'subcommand' subcmds");
|
|
6414
|
-
|
|
6415
|
-
|
|
6591
|
+
if (isDirectory) {
|
|
6592
|
+
lines.push(" elif (( CURRENT == 3 )) && [[ ${words[2]} == open ]]; then");
|
|
6593
|
+
lines.push(` _values 'target' ${DIR_TARGETS.join(" ")}`);
|
|
6594
|
+
lines.push(" else");
|
|
6595
|
+
lines.push(" _files");
|
|
6596
|
+
} else {
|
|
6597
|
+
lines.push(" else");
|
|
6598
|
+
lines.push(" _files");
|
|
6599
|
+
}
|
|
6416
6600
|
lines.push(" fi");
|
|
6417
6601
|
lines.push(" ;;");
|
|
6418
6602
|
}
|
|
6419
6603
|
lines.push(
|
|
6420
|
-
" directory|dir|dirs|directories)",
|
|
6421
|
-
" if (( CURRENT == 3 )); then",
|
|
6422
|
-
` _values 'target' ${DIR_TARGETS.join(" ")}`,
|
|
6423
|
-
" fi",
|
|
6424
|
-
" ;;",
|
|
6425
6604
|
" logs)",
|
|
6426
6605
|
" _arguments '-f[\u5B9E\u65F6\u8DDF\u968F]' '-n[\u663E\u793A\u884C\u6570]:\u884C\u6570:' '-o[\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00]' '1::\u7F16\u53F7:'",
|
|
6427
6606
|
" ;;",
|
|
@@ -6436,7 +6615,11 @@ function buildZsh(commands, groups) {
|
|
|
6436
6615
|
" _arguments '-y[\u8DF3\u8FC7\u786E\u8BA4]' '--full[\u5220\u5168\u90E8]'",
|
|
6437
6616
|
" ;;",
|
|
6438
6617
|
" completion)",
|
|
6439
|
-
|
|
6618
|
+
" if (( CURRENT == 2 )); then",
|
|
6619
|
+
` _values 'action' install ${SHELLS.join(" ")}`,
|
|
6620
|
+
" elif (( CURRENT == 3 )) && [[ ${words[2]} == install ]]; then",
|
|
6621
|
+
` _values 'shell' ${SHELLS.join(" ")}`,
|
|
6622
|
+
" fi",
|
|
6440
6623
|
" ;;",
|
|
6441
6624
|
" *)",
|
|
6442
6625
|
" _files",
|
|
@@ -6470,7 +6653,7 @@ function buildBash(commands, groups) {
|
|
|
6470
6653
|
fi
|
|
6471
6654
|
;;`;
|
|
6472
6655
|
}).join("\n");
|
|
6473
|
-
return `# mihomo-cli bash \u8865\u5168\uFF08mihomo completion bash \u751F\u6210\uFF1B\u5B89\u88C5: eval "$(mihomo completion bash)"\uFF09
|
|
6656
|
+
return `# mihomo-cli bash \u8865\u5168\uFF08mihomo completion bash \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion install bash\uFF0C\u6216 eval "$(mihomo completion bash)"\uFF09
|
|
6474
6657
|
|
|
6475
6658
|
_mihomo_completions() {
|
|
6476
6659
|
local cur prev
|
|
@@ -6486,7 +6669,7 @@ _mihomo_completions() {
|
|
|
6486
6669
|
case "\${COMP_WORDS[1]}" in
|
|
6487
6670
|
${subCase}
|
|
6488
6671
|
logs)
|
|
6489
|
-
COMPREPLY=( $(compgen -W "-f -n -o --
|
|
6672
|
+
COMPREPLY=( $(compgen -W "-f -n -o --lines --follow --open" -- "\${cur}") )
|
|
6490
6673
|
;;
|
|
6491
6674
|
ui)
|
|
6492
6675
|
COMPREPLY=( $(compgen -W "${UI_NAMES.join(" ")}" -- "\${cur}") )
|
|
@@ -6498,7 +6681,11 @@ ${subCase}
|
|
|
6498
6681
|
COMPREPLY=( $(compgen -W "subs logs data runtime settings kernel overwrites service --full -y" -- "\${cur}") )
|
|
6499
6682
|
;;
|
|
6500
6683
|
completion)
|
|
6501
|
-
|
|
6684
|
+
if [[ \${COMP_CWORD} -eq 2 ]]; then
|
|
6685
|
+
COMPREPLY=( $(compgen -W "install ${SHELLS.join(" ")}" -- "\${cur}") )
|
|
6686
|
+
elif [[ \${COMP_CWORD} -eq 3 ]] && [[ "\${COMP_WORDS[2]}" == install ]]; then
|
|
6687
|
+
COMPREPLY=( $(compgen -W "${SHELLS.join(" ")}" -- "\${cur}") )
|
|
6688
|
+
fi
|
|
6502
6689
|
;;
|
|
6503
6690
|
esac
|
|
6504
6691
|
}
|
|
@@ -6507,7 +6694,7 @@ complete -F _mihomo_completions mihomo mhm mh mihomo-cli
|
|
|
6507
6694
|
}
|
|
6508
6695
|
function buildFish(commands, groups) {
|
|
6509
6696
|
const lines = [
|
|
6510
|
-
"# mihomo-cli fish \u8865\u5168\uFF08mihomo completion fish \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion fish | source\uFF09",
|
|
6697
|
+
"# mihomo-cli fish \u8865\u5168\uFF08mihomo completion fish \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion install fish\uFF0C\u6216 mihomo completion fish | source\uFF09",
|
|
6511
6698
|
"",
|
|
6512
6699
|
"for cmd in mihomo mhm mh mihomo-cli"
|
|
6513
6700
|
];
|
|
@@ -6522,7 +6709,8 @@ function buildFish(commands, groups) {
|
|
|
6522
6709
|
}
|
|
6523
6710
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories open" -a '${DIR_TARGETS.join(" ")}'`);
|
|
6524
6711
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui" -a '${UI_NAMES.join(" ")}'`);
|
|
6525
|
-
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a '${SHELLS.join(" ")}'`);
|
|
6712
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install ${SHELLS.join(" ")}' -d '\u5B89\u88C5\u8865\u5168\u5230\u9ED8\u8BA4\u4F4D\u7F6E'`);
|
|
6713
|
+
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion; and __fish_seen_subcommand_from install" -a '${SHELLS.join(" ")}'`);
|
|
6526
6714
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--mirror' -d '\u8D70\u955C\u50CF\u4E0B\u8F7D'`);
|
|
6527
6715
|
lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--no-mirror' -d '\u76F4\u8FDE\u4E0B\u8F7D'`);
|
|
6528
6716
|
lines.push("end");
|
|
@@ -6546,22 +6734,209 @@ function buildCompletionScript(shell, commands) {
|
|
|
6546
6734
|
}
|
|
6547
6735
|
}
|
|
6548
6736
|
}
|
|
6737
|
+
var BASH_MARKER = "# >>> mihomo-cli completion (append)";
|
|
6738
|
+
function completionInstallPath(shell) {
|
|
6739
|
+
const home = os2.homedir();
|
|
6740
|
+
switch (shell) {
|
|
6741
|
+
case "zsh":
|
|
6742
|
+
return path8.join(home, ".zsh", "completions", "_mihomo");
|
|
6743
|
+
case "bash":
|
|
6744
|
+
return path8.join(home, ".bash_completion");
|
|
6745
|
+
case "fish":
|
|
6746
|
+
return path8.join(home, ".config", "fish", "completions", "mihomo.fish");
|
|
6747
|
+
default:
|
|
6748
|
+
return null;
|
|
6749
|
+
}
|
|
6750
|
+
}
|
|
6751
|
+
function installCompletion(shell, commands) {
|
|
6752
|
+
if (!shell) {
|
|
6753
|
+
throw new CliError("\u8BF7\u6307\u5B9A shell", { hint: [`\u7528\u6CD5: mihomo completion install <${SHELLS.join("|")}>`] });
|
|
6754
|
+
}
|
|
6755
|
+
const target = completionInstallPath(shell);
|
|
6756
|
+
if (!target) {
|
|
6757
|
+
buildCompletionScript(shell, commands);
|
|
6758
|
+
return;
|
|
6759
|
+
}
|
|
6760
|
+
const script = buildCompletionScript(shell, commands);
|
|
6761
|
+
console.log(`\u5B89\u88C5 ${shell} \u8865\u5168: ${target}`);
|
|
6762
|
+
try {
|
|
6763
|
+
if (shell === "bash") {
|
|
6764
|
+
const existing = fs10.existsSync(target) ? fs10.readFileSync(target, "utf8") : "";
|
|
6765
|
+
if (existing.includes(BASH_MARKER)) {
|
|
6766
|
+
console.log("\u5DF2\u5B89\u88C5\u8FC7\uFF08~/.bash_completion \u5DF2\u5305\u542B mihomo \u8865\u5168\uFF09\uFF0C\u8DF3\u8FC7");
|
|
6767
|
+
return;
|
|
6768
|
+
}
|
|
6769
|
+
fs10.mkdirSync(path8.dirname(target), { recursive: true });
|
|
6770
|
+
fs10.appendFileSync(target, `
|
|
6771
|
+
${BASH_MARKER}
|
|
6772
|
+
${script}${BASH_MARKER.replace(">>>", "<<<")}
|
|
6773
|
+
`);
|
|
6774
|
+
console.log(colors.green("\u5DF2\u8FFD\u52A0\u5230 ~/.bash_completion\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6775
|
+
return;
|
|
6776
|
+
}
|
|
6777
|
+
fs10.mkdirSync(path8.dirname(target), { recursive: true });
|
|
6778
|
+
fs10.writeFileSync(target, script, { mode: 420 });
|
|
6779
|
+
console.log(colors.green("\u5DF2\u5199\u5165\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
|
|
6780
|
+
} catch (e) {
|
|
6781
|
+
throw new CliError(`\u8865\u5168\u5B89\u88C5\u5931\u8D25: ${e.message}`, {
|
|
6782
|
+
label: "\u5B89\u88C5\u5931\u8D25",
|
|
6783
|
+
hint: ["\u8BF7\u68C0\u67E5\u76EE\u6807\u76EE\u5F55\u7684\u5199\u6743\u9650\uFF0C\u6216\u624B\u52A8\u91CD\u5B9A\u5411\u8865\u5168\u811A\u672C:", ` mihomo completion ${shell} >> ${target}`]
|
|
6784
|
+
});
|
|
6785
|
+
}
|
|
6786
|
+
if (shell === "zsh") {
|
|
6787
|
+
console.log(colors.gray("\u82E5\u8865\u5168\u4E0D\u751F\u6548\uFF0C\u5728 ~/.zshrc \u4E2D\u52A0\u4E00\u884C: fpath=(~/.zsh/completions $fpath)"));
|
|
6788
|
+
}
|
|
6789
|
+
}
|
|
6549
6790
|
function cmdCompletion(args, commands) {
|
|
6791
|
+
if (args[1] === "install") {
|
|
6792
|
+
installCompletion(args[2], commands);
|
|
6793
|
+
return;
|
|
6794
|
+
}
|
|
6550
6795
|
const shell = args[1];
|
|
6551
6796
|
if (!shell) {
|
|
6552
6797
|
throw new CliError("\u8BF7\u6307\u5B9A shell", {
|
|
6553
|
-
hint: [
|
|
6798
|
+
hint: [
|
|
6799
|
+
`\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`,
|
|
6800
|
+
`\u5B89\u88C5\u5230\u9ED8\u8BA4\u4F4D\u7F6E: mihomo completion install <${SHELLS.join("|")}>`,
|
|
6801
|
+
'\u4E34\u65F6\u542F\u7528: eval "$(mihomo completion zsh)"'
|
|
6802
|
+
]
|
|
6554
6803
|
});
|
|
6555
6804
|
}
|
|
6556
6805
|
console.log(buildCompletionScript(shell, commands));
|
|
6557
6806
|
}
|
|
6558
6807
|
|
|
6559
6808
|
// src/commands/doctor.ts
|
|
6560
|
-
import { spawnSync as
|
|
6561
|
-
import
|
|
6809
|
+
import { spawnSync as spawnSync6 } from "child_process";
|
|
6810
|
+
import fs11 from "fs";
|
|
6811
|
+
|
|
6812
|
+
// node_modules/compare-versions/lib/esm/utils.js
|
|
6813
|
+
var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
|
|
6814
|
+
var validateAndParse = (version) => {
|
|
6815
|
+
if (typeof version !== "string") {
|
|
6816
|
+
throw new TypeError("Invalid argument expected string");
|
|
6817
|
+
}
|
|
6818
|
+
const match = version.match(semver);
|
|
6819
|
+
if (!match) {
|
|
6820
|
+
throw new Error(`Invalid argument not valid semver ('${version}' received)`);
|
|
6821
|
+
}
|
|
6822
|
+
match.shift();
|
|
6823
|
+
return match;
|
|
6824
|
+
};
|
|
6825
|
+
var isWildcard = (s) => s === "*" || s === "x" || s === "X";
|
|
6826
|
+
var tryParse = (v) => {
|
|
6827
|
+
const n = parseInt(v, 10);
|
|
6828
|
+
return isNaN(n) ? v : n;
|
|
6829
|
+
};
|
|
6830
|
+
var forceType = (a, b) => typeof a !== typeof b ? [String(a), String(b)] : [a, b];
|
|
6831
|
+
var compareStrings = (a, b) => {
|
|
6832
|
+
if (isWildcard(a) || isWildcard(b))
|
|
6833
|
+
return 0;
|
|
6834
|
+
const [ap, bp] = forceType(tryParse(a), tryParse(b));
|
|
6835
|
+
if (ap > bp)
|
|
6836
|
+
return 1;
|
|
6837
|
+
if (ap < bp)
|
|
6838
|
+
return -1;
|
|
6839
|
+
return 0;
|
|
6840
|
+
};
|
|
6841
|
+
var compareSegments = (a, b) => {
|
|
6842
|
+
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
|
6843
|
+
const r = compareStrings(a[i] || "0", b[i] || "0");
|
|
6844
|
+
if (r !== 0)
|
|
6845
|
+
return r;
|
|
6846
|
+
}
|
|
6847
|
+
return 0;
|
|
6848
|
+
};
|
|
6849
|
+
|
|
6850
|
+
// node_modules/compare-versions/lib/esm/compareVersions.js
|
|
6851
|
+
var compareVersions = (v1, v2) => {
|
|
6852
|
+
const n1 = validateAndParse(v1);
|
|
6853
|
+
const n2 = validateAndParse(v2);
|
|
6854
|
+
const p1 = n1.pop();
|
|
6855
|
+
const p2 = n2.pop();
|
|
6856
|
+
const r = compareSegments(n1, n2);
|
|
6857
|
+
if (r !== 0)
|
|
6858
|
+
return r;
|
|
6859
|
+
if (p1 && p2) {
|
|
6860
|
+
return compareSegments(p1.split("."), p2.split("."));
|
|
6861
|
+
} else if (p1 || p2) {
|
|
6862
|
+
return p1 ? -1 : 1;
|
|
6863
|
+
}
|
|
6864
|
+
return 0;
|
|
6865
|
+
};
|
|
6866
|
+
|
|
6867
|
+
// src/commands/update.ts
|
|
6868
|
+
import { execFile as execFile2, spawn as spawn2 } from "child_process";
|
|
6869
|
+
import { promisify as promisify2 } from "util";
|
|
6870
|
+
var execFileAsync2 = promisify2(execFile2);
|
|
6871
|
+
var NPM_VIEW_TIMEOUT_MS = 15e3;
|
|
6872
|
+
async function getLatestNpmVersion(timeoutMs = NPM_VIEW_TIMEOUT_MS) {
|
|
6873
|
+
try {
|
|
6874
|
+
const { stdout } = await execFileAsync2("npm", ["view", PKG_NAME, "version"], { timeout: timeoutMs });
|
|
6875
|
+
const version = stdout.trim().split("\n").pop()?.trim();
|
|
6876
|
+
return version || null;
|
|
6877
|
+
} catch {
|
|
6878
|
+
return null;
|
|
6879
|
+
}
|
|
6880
|
+
}
|
|
6881
|
+
async function cmdUpdate() {
|
|
6882
|
+
console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
|
|
6883
|
+
console.log("");
|
|
6884
|
+
const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
|
|
6885
|
+
if (latest) {
|
|
6886
|
+
try {
|
|
6887
|
+
const cmp = compareVersions(VERSION, latest);
|
|
6888
|
+
if (cmp > 0) {
|
|
6889
|
+
console.log(colors.yellow(`\u5F53\u524D\u7248\u672C (${VERSION}) \u9886\u5148\u4E8E npm \u6700\u65B0\u7248 (${latest})\uFF0C\u8DF3\u8FC7\u66F4\u65B0\uFF08\u907F\u514D\u964D\u7EA7\uFF09`));
|
|
6890
|
+
console.log(colors.gray("\u5982\u9700\u5F3A\u5236\u91CD\u88C5: npm install -g mihomo-cli"));
|
|
6891
|
+
return;
|
|
6892
|
+
}
|
|
6893
|
+
if (cmp === 0) {
|
|
6894
|
+
console.log(`\u5DF2\u662F\u6700\u65B0\u7248\u672C (${colors.green(VERSION)})\uFF0C\u65E0\u9700\u66F4\u65B0`);
|
|
6895
|
+
return;
|
|
6896
|
+
}
|
|
6897
|
+
} catch {
|
|
6898
|
+
}
|
|
6899
|
+
console.log(`\u6700\u65B0\u7248\u672C: ${colors.cyan(latest)}`);
|
|
6900
|
+
} else {
|
|
6901
|
+
console.log(colors.yellow("\u65E0\u6CD5\u67E5\u8BE2\u6700\u65B0\u7248\u672C\uFF08\u7F51\u7EDC\u95EE\u9898\uFF1F\uFF09\uFF0C\u5C06\u76F4\u63A5\u5C1D\u8BD5\u91CD\u65B0\u5B89\u88C5"));
|
|
6902
|
+
}
|
|
6903
|
+
console.log("");
|
|
6904
|
+
console.log("\u6B63\u5728\u66F4\u65B0 mihomo-cli...");
|
|
6905
|
+
console.log("");
|
|
6906
|
+
await new Promise((resolve, reject) => {
|
|
6907
|
+
const npm = spawn2("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
|
|
6908
|
+
npm.on("close", (code) => {
|
|
6909
|
+
if (code === 0) {
|
|
6910
|
+
resolve();
|
|
6911
|
+
} else {
|
|
6912
|
+
reject(new CliError("\u66F4\u65B0\u5931\u8D25\u3002\u82E5\u4E3A\u6743\u9650\u95EE\u9898\uFF08EACCES\uFF09\uFF0C\u8BF7\u68C0\u67E5 npm \u5168\u5C40\u76EE\u5F55\u6743\u9650\u6216\u4F7F\u7528 nvm \u7BA1\u7406 Node", { exitCode: code || 1 }));
|
|
6913
|
+
}
|
|
6914
|
+
});
|
|
6915
|
+
npm.on("error", (e) => {
|
|
6916
|
+
const perm = e.message.includes("EACCES") || e.message.includes("permission");
|
|
6917
|
+
reject(perm ? new CliError("\u6743\u9650\u4E0D\u8DB3\uFF08EACCES\uFF09\uFF0C\u8BF7\u68C0\u67E5 npm \u5168\u5C40\u76EE\u5F55\u6743\u9650\u6216\u4F7F\u7528 nvm \u7BA1\u7406 Node") : new CliError(`\u6267\u884C\u5931\u8D25: ${e.message}`));
|
|
6918
|
+
});
|
|
6919
|
+
});
|
|
6920
|
+
try {
|
|
6921
|
+
const { stdout } = await execFileAsync2("npm", ["list", "-g", PKG_NAME, "--json", "--depth=0"]);
|
|
6922
|
+
const result = JSON.parse(stdout);
|
|
6923
|
+
const newVersion = result.dependencies?.[PKG_NAME]?.version;
|
|
6924
|
+
console.log("");
|
|
6925
|
+
if (newVersion) {
|
|
6926
|
+
console.log(`\u66F4\u65B0\u5B8C\u6210\uFF0C\u6700\u65B0\u7248\u672C: ${colors.green(newVersion)}`);
|
|
6927
|
+
} else {
|
|
6928
|
+
console.log("\u66F4\u65B0\u5B8C\u6210");
|
|
6929
|
+
}
|
|
6930
|
+
} catch {
|
|
6931
|
+
console.log("");
|
|
6932
|
+
console.log("\u66F4\u65B0\u5B8C\u6210");
|
|
6933
|
+
}
|
|
6934
|
+
}
|
|
6935
|
+
|
|
6936
|
+
// src/commands/doctor.ts
|
|
6562
6937
|
function isPortListening(port) {
|
|
6563
6938
|
try {
|
|
6564
|
-
const r =
|
|
6939
|
+
const r = spawnSync6("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN"], { encoding: "utf8", timeout: 5e3 });
|
|
6565
6940
|
return r.status === 0 && (r.stdout || "").trim().length > 0;
|
|
6566
6941
|
} catch {
|
|
6567
6942
|
return false;
|
|
@@ -6576,21 +6951,23 @@ async function collectChecks() {
|
|
|
6576
6951
|
push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
|
|
6577
6952
|
} else {
|
|
6578
6953
|
const v = getKernelVersion();
|
|
6579
|
-
const r =
|
|
6954
|
+
const r = spawnSync6(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
6580
6955
|
if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
|
|
6581
6956
|
push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
|
|
6957
|
+
} else if (r.error) {
|
|
6958
|
+
push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08${r.error.message}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
|
|
6582
6959
|
} else {
|
|
6583
6960
|
push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${r.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
|
|
6584
6961
|
}
|
|
6585
6962
|
}
|
|
6586
6963
|
try {
|
|
6587
|
-
|
|
6964
|
+
fs11.accessSync(USER_DATA_DIR, fs11.constants.W_OK);
|
|
6588
6965
|
push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
|
|
6589
6966
|
} catch {
|
|
6590
6967
|
push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
|
|
6591
6968
|
}
|
|
6592
|
-
if (
|
|
6593
|
-
if (isValidSettingsContent(
|
|
6969
|
+
if (fs11.existsSync(PATHS.settingsFile)) {
|
|
6970
|
+
if (isValidSettingsContent(fs11.readFileSync(PATHS.settingsFile, "utf8"))) {
|
|
6594
6971
|
push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
|
|
6595
6972
|
} else {
|
|
6596
6973
|
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");
|
|
@@ -6613,10 +6990,8 @@ async function collectChecks() {
|
|
|
6613
6990
|
const cached = subs.find((s) => s.name === active.name);
|
|
6614
6991
|
if (cached?.updated_at) {
|
|
6615
6992
|
const rel = formatRelativeTime(cached.updated_at);
|
|
6616
|
-
|
|
6617
|
-
|
|
6618
|
-
if (ageH > intervalH) {
|
|
6619
|
-
push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "warn", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0\uFF0C\u5DF2\u8D85\u8FC7 ${intervalH} \u5C0F\u65F6\u95F4\u9694`, "mihomo sub update");
|
|
6993
|
+
if (isSubscriptionStale(cached)) {
|
|
6994
|
+
push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "warn", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0\uFF0C\u5DF2\u8D85\u8FC7 ${resolveUpdateInterval(cached.update_interval)} \u5C0F\u65F6\u95F4\u9694`, "mihomo sub update");
|
|
6620
6995
|
} else {
|
|
6621
6996
|
push("\u8BA2\u9605\u65B0\u9C9C\u5EA6", "ok", `${rel ?? "\u672A\u77E5"}\u524D\u66F4\u65B0`);
|
|
6622
6997
|
}
|
|
@@ -6646,7 +7021,14 @@ async function collectChecks() {
|
|
|
6646
7021
|
}
|
|
6647
7022
|
const state = getRunningState();
|
|
6648
7023
|
const info = getConfigInfo();
|
|
6649
|
-
|
|
7024
|
+
let mixedPortDefault = DEFAULT_MIXED_PORT;
|
|
7025
|
+
try {
|
|
7026
|
+
const ports = getPorts();
|
|
7027
|
+
mixedPortDefault = ports.mixed;
|
|
7028
|
+
} catch (e) {
|
|
7029
|
+
push("\u7AEF\u53E3\u914D\u7F6E", "fail", e.message, "\u4FEE\u6B63 settings.json \u7684 ports\uFF081-65535 \u6574\u6570\uFF0Cmixed \u4E0E controller \u4E0D\u80FD\u76F8\u540C\uFF09");
|
|
7030
|
+
}
|
|
7031
|
+
const mixedPort = info?.mixedPort ?? mixedPortDefault;
|
|
6650
7032
|
if (state.running) {
|
|
6651
7033
|
if (isPortListening(mixedPort)) {
|
|
6652
7034
|
push("\u7AEF\u53E3", "ok", `${mixedPort} \u6B63\u5728\u76D1\u542C`);
|
|
@@ -6679,6 +7061,14 @@ async function collectChecks() {
|
|
|
6679
7061
|
} else {
|
|
6680
7062
|
push("\u4EE3\u7406\u8FDE\u901A", "skip", "\u672A\u8FD0\u884C");
|
|
6681
7063
|
}
|
|
7064
|
+
const latest = await getLatestNpmVersion(4e3);
|
|
7065
|
+
if (latest === null) {
|
|
7066
|
+
push("CLI \u7248\u672C", "skip", "npm registry \u4E0D\u53EF\u8FBE\uFF0C\u8DF3\u8FC7\u68C0\u67E5");
|
|
7067
|
+
} else if (compareVersions(latest, VERSION) > 0) {
|
|
7068
|
+
push("CLI \u7248\u672C", "warn", `\u5F53\u524D ${VERSION}\uFF0C\u6700\u65B0 ${latest}`, "mihomo update");
|
|
7069
|
+
} else {
|
|
7070
|
+
push("CLI \u7248\u672C", "ok", `${VERSION}\uFF08\u6700\u65B0\uFF09`);
|
|
7071
|
+
}
|
|
6682
7072
|
return checks;
|
|
6683
7073
|
}
|
|
6684
7074
|
async function cmdDoctor() {
|
|
@@ -6707,66 +7097,9 @@ async function cmdDoctor() {
|
|
|
6707
7097
|
}
|
|
6708
7098
|
|
|
6709
7099
|
// src/kernel.ts
|
|
6710
|
-
import { spawnSync as
|
|
6711
|
-
import
|
|
6712
|
-
import
|
|
6713
|
-
|
|
6714
|
-
// node_modules/compare-versions/lib/esm/utils.js
|
|
6715
|
-
var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
|
|
6716
|
-
var validateAndParse = (version) => {
|
|
6717
|
-
if (typeof version !== "string") {
|
|
6718
|
-
throw new TypeError("Invalid argument expected string");
|
|
6719
|
-
}
|
|
6720
|
-
const match = version.match(semver);
|
|
6721
|
-
if (!match) {
|
|
6722
|
-
throw new Error(`Invalid argument not valid semver ('${version}' received)`);
|
|
6723
|
-
}
|
|
6724
|
-
match.shift();
|
|
6725
|
-
return match;
|
|
6726
|
-
};
|
|
6727
|
-
var isWildcard = (s) => s === "*" || s === "x" || s === "X";
|
|
6728
|
-
var tryParse = (v) => {
|
|
6729
|
-
const n = parseInt(v, 10);
|
|
6730
|
-
return isNaN(n) ? v : n;
|
|
6731
|
-
};
|
|
6732
|
-
var forceType = (a, b) => typeof a !== typeof b ? [String(a), String(b)] : [a, b];
|
|
6733
|
-
var compareStrings = (a, b) => {
|
|
6734
|
-
if (isWildcard(a) || isWildcard(b))
|
|
6735
|
-
return 0;
|
|
6736
|
-
const [ap, bp] = forceType(tryParse(a), tryParse(b));
|
|
6737
|
-
if (ap > bp)
|
|
6738
|
-
return 1;
|
|
6739
|
-
if (ap < bp)
|
|
6740
|
-
return -1;
|
|
6741
|
-
return 0;
|
|
6742
|
-
};
|
|
6743
|
-
var compareSegments = (a, b) => {
|
|
6744
|
-
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
|
6745
|
-
const r = compareStrings(a[i] || "0", b[i] || "0");
|
|
6746
|
-
if (r !== 0)
|
|
6747
|
-
return r;
|
|
6748
|
-
}
|
|
6749
|
-
return 0;
|
|
6750
|
-
};
|
|
6751
|
-
|
|
6752
|
-
// node_modules/compare-versions/lib/esm/compareVersions.js
|
|
6753
|
-
var compareVersions = (v1, v2) => {
|
|
6754
|
-
const n1 = validateAndParse(v1);
|
|
6755
|
-
const n2 = validateAndParse(v2);
|
|
6756
|
-
const p1 = n1.pop();
|
|
6757
|
-
const p2 = n2.pop();
|
|
6758
|
-
const r = compareSegments(n1, n2);
|
|
6759
|
-
if (r !== 0)
|
|
6760
|
-
return r;
|
|
6761
|
-
if (p1 && p2) {
|
|
6762
|
-
return compareSegments(p1.split("."), p2.split("."));
|
|
6763
|
-
} else if (p1 || p2) {
|
|
6764
|
-
return p1 ? -1 : 1;
|
|
6765
|
-
}
|
|
6766
|
-
return 0;
|
|
6767
|
-
};
|
|
6768
|
-
|
|
6769
|
-
// src/kernel.ts
|
|
7100
|
+
import { spawnSync as spawnSync7 } from "child_process";
|
|
7101
|
+
import fs12 from "fs";
|
|
7102
|
+
import path9 from "path";
|
|
6770
7103
|
var GITHUB_REPO = "MetaCubeX/mihomo";
|
|
6771
7104
|
var KERNEL_HTTP_TIMEOUT = 12e4;
|
|
6772
7105
|
var KERNEL_DOWNLOAD_TIMEOUT = 18e4;
|
|
@@ -6847,10 +7180,10 @@ async function checkUpdate() {
|
|
|
6847
7180
|
}
|
|
6848
7181
|
function findBinaryInDir(dir, maxDepth = 4) {
|
|
6849
7182
|
if (maxDepth <= 0) return null;
|
|
6850
|
-
const files =
|
|
7183
|
+
const files = fs12.readdirSync(dir);
|
|
6851
7184
|
for (const f of files) {
|
|
6852
|
-
const fullPath =
|
|
6853
|
-
const stat =
|
|
7185
|
+
const fullPath = path9.join(dir, f);
|
|
7186
|
+
const stat = fs12.lstatSync(fullPath);
|
|
6854
7187
|
if (stat.isDirectory()) {
|
|
6855
7188
|
const found = findBinaryInDir(fullPath, maxDepth - 1);
|
|
6856
7189
|
if (found) return found;
|
|
@@ -6878,73 +7211,65 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6878
7211
|
}
|
|
6879
7212
|
assertTrustedAssetUrl(asset.browser_download_url);
|
|
6880
7213
|
const downloadUrl = withMirror(asset.browser_download_url, mirror);
|
|
6881
|
-
const
|
|
7214
|
+
const tempDir = fs12.mkdtempSync(path9.join(DIRS.kernel, ".tmp-"));
|
|
7215
|
+
const tempPath = path9.join(tempDir, path9.basename(asset.name));
|
|
6882
7216
|
const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
|
|
6883
|
-
|
|
6884
|
-
|
|
6885
|
-
|
|
6886
|
-
if (progressCallback) {
|
|
6887
|
-
progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
|
|
6888
|
-
}
|
|
6889
|
-
const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
|
|
6890
|
-
const curlResult = spawnSync6(
|
|
6891
|
-
"curl",
|
|
6892
|
-
[
|
|
6893
|
-
"-L",
|
|
6894
|
-
"--proto",
|
|
6895
|
-
"=https",
|
|
6896
|
-
"--proto-redir",
|
|
6897
|
-
"=https",
|
|
6898
|
-
"--max-filesize",
|
|
6899
|
-
String(maxBytes),
|
|
6900
|
-
"--progress-bar",
|
|
6901
|
-
"--connect-timeout",
|
|
6902
|
-
"30",
|
|
6903
|
-
"--max-time",
|
|
6904
|
-
String(Math.floor(KERNEL_DOWNLOAD_TIMEOUT / 1e3)),
|
|
6905
|
-
"-o",
|
|
6906
|
-
tempPath,
|
|
6907
|
-
downloadUrl
|
|
6908
|
-
],
|
|
6909
|
-
{ stdio: "inherit" }
|
|
6910
|
-
);
|
|
6911
|
-
if (curlResult.error) {
|
|
6912
|
-
if (curlResult.error.code === "ENOENT") {
|
|
6913
|
-
throw new Error("\u672A\u627E\u5230 curl \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 curl \u540E\u91CD\u8BD5");
|
|
7217
|
+
try {
|
|
7218
|
+
if (mirror && progressCallback) {
|
|
7219
|
+
progressCallback("\u63D0\u793A: \u7ECF\u7B2C\u4E09\u65B9\u955C\u50CF\u4E2D\u8F6C\u4E0B\u8F7D\uFF0C\u65E0\u6CD5\u9A8C\u8BC1\u6765\u6E90\u5B8C\u6574\u6027\uFF0C\u5EFA\u8BAE\u76F4\u8FDE\u6216\u81EA\u884C\u6821\u9A8C\u4EA7\u7269");
|
|
6914
7220
|
}
|
|
6915
|
-
|
|
6916
|
-
|
|
6917
|
-
if (curlResult.status !== 0) {
|
|
6918
|
-
try {
|
|
6919
|
-
fs11.unlinkSync(tempPath);
|
|
6920
|
-
} catch {
|
|
7221
|
+
if (progressCallback) {
|
|
7222
|
+
progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
|
|
6921
7223
|
}
|
|
6922
|
-
|
|
6923
|
-
|
|
6924
|
-
|
|
6925
|
-
|
|
6926
|
-
|
|
6927
|
-
|
|
6928
|
-
|
|
6929
|
-
|
|
6930
|
-
|
|
6931
|
-
|
|
6932
|
-
|
|
7224
|
+
const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
|
|
7225
|
+
const curlResult = spawnSync7(
|
|
7226
|
+
"curl",
|
|
7227
|
+
[
|
|
7228
|
+
"-L",
|
|
7229
|
+
"--proto",
|
|
7230
|
+
"=https",
|
|
7231
|
+
"--proto-redir",
|
|
7232
|
+
"=https",
|
|
7233
|
+
"--max-filesize",
|
|
7234
|
+
String(maxBytes),
|
|
7235
|
+
"--progress-bar",
|
|
7236
|
+
"--connect-timeout",
|
|
7237
|
+
"30",
|
|
7238
|
+
"--max-time",
|
|
7239
|
+
String(Math.floor(KERNEL_DOWNLOAD_TIMEOUT / 1e3)),
|
|
7240
|
+
"-o",
|
|
7241
|
+
tempPath,
|
|
7242
|
+
downloadUrl
|
|
7243
|
+
],
|
|
7244
|
+
{ stdio: "inherit" }
|
|
7245
|
+
);
|
|
7246
|
+
if (curlResult.error) {
|
|
7247
|
+
if (curlResult.error.code === "ENOENT") {
|
|
7248
|
+
throw new Error("\u672A\u627E\u5230 curl \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 curl \u540E\u91CD\u8BD5");
|
|
6933
7249
|
}
|
|
6934
|
-
throw new Error(
|
|
6935
|
-
|
|
7250
|
+
throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${curlResult.error.message}`);
|
|
7251
|
+
}
|
|
7252
|
+
if (curlResult.status !== 0) {
|
|
7253
|
+
throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
|
|
7254
|
+
}
|
|
7255
|
+
if (!fs12.existsSync(tempPath)) {
|
|
7256
|
+
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
7257
|
+
}
|
|
7258
|
+
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
7259
|
+
const actual = fs12.statSync(tempPath).size;
|
|
7260
|
+
if (actual !== asset.size) {
|
|
7261
|
+
throw new Error(
|
|
7262
|
+
`\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
|
|
6936
7263
|
\u53EF\u80FD\u662F\u4E0B\u8F7D\u88AB\u622A\u65AD\u6216\u5185\u5BB9\u88AB\u66FF\u6362\uFF0C\u8BF7\u91CD\u8BD5\u6216\u6539\u7528 --no-mirror \u76F4\u8FDE`
|
|
6937
|
-
|
|
7264
|
+
);
|
|
7265
|
+
}
|
|
6938
7266
|
}
|
|
6939
|
-
|
|
6940
|
-
|
|
6941
|
-
|
|
6942
|
-
|
|
6943
|
-
const extractPath = DIRS.kernel;
|
|
6944
|
-
let extractedBinary = null;
|
|
6945
|
-
try {
|
|
7267
|
+
if (progressCallback) {
|
|
7268
|
+
progressCallback("\u89E3\u538B\u5185\u6838...");
|
|
7269
|
+
}
|
|
7270
|
+
let extractedBinary = null;
|
|
6946
7271
|
if (tempPath.endsWith(".tar.gz") || tempPath.endsWith(".tgz")) {
|
|
6947
|
-
const listResult =
|
|
7272
|
+
const listResult = spawnSync7("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
|
|
6948
7273
|
if (listResult.error) throw listResult.error;
|
|
6949
7274
|
if (listResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${listResult.status}`);
|
|
6950
7275
|
for (const entry of (listResult.stdout || "").split("\n").filter(Boolean)) {
|
|
@@ -6952,7 +7277,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6952
7277
|
throw new Error(`\u5F52\u6863\u542B\u975E\u6CD5\u8DEF\u5F84\u6761\u76EE: ${entry}`);
|
|
6953
7278
|
}
|
|
6954
7279
|
}
|
|
6955
|
-
const typeResult =
|
|
7280
|
+
const typeResult = spawnSync7("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
|
|
6956
7281
|
if (typeResult.error) throw typeResult.error;
|
|
6957
7282
|
if (typeResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${typeResult.status}`);
|
|
6958
7283
|
for (const line of (typeResult.stdout || "").split("\n").filter(Boolean)) {
|
|
@@ -6961,72 +7286,55 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
|
|
|
6961
7286
|
throw new Error(`\u5F52\u6863\u542B\u975E\u666E\u901A\u6587\u4EF6\u6761\u76EE\uFF08\u7C7B\u578B "${typeChar}"\uFF09: ${line}`);
|
|
6962
7287
|
}
|
|
6963
7288
|
}
|
|
6964
|
-
const tarResult =
|
|
7289
|
+
const tarResult = spawnSync7("tar", ["--no-same-owner", "-xzf", tempPath, "-C", tempDir], {
|
|
6965
7290
|
stdio: ["ignore", "ignore", "inherit"],
|
|
6966
7291
|
timeout: 6e4
|
|
6967
7292
|
});
|
|
6968
7293
|
if (tarResult.error) throw tarResult.error;
|
|
6969
7294
|
if (tarResult.status !== 0) throw new Error(`tar \u9000\u51FA\u7801 ${tarResult.status}`);
|
|
6970
7295
|
} else if (tempPath.endsWith(".gz")) {
|
|
6971
|
-
const baseName =
|
|
6972
|
-
const outputPath =
|
|
6973
|
-
const gzipResult =
|
|
7296
|
+
const baseName = path9.basename(tempPath, ".gz");
|
|
7297
|
+
const outputPath = path9.join(tempDir, baseName);
|
|
7298
|
+
const gzipResult = spawnSync7("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
|
|
6974
7299
|
if (gzipResult.error) throw gzipResult.error;
|
|
6975
7300
|
if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
|
|
6976
|
-
|
|
7301
|
+
fs12.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
|
|
6977
7302
|
extractedBinary = outputPath;
|
|
6978
7303
|
}
|
|
6979
|
-
|
|
6980
|
-
|
|
6981
|
-
|
|
6982
|
-
} catch {
|
|
7304
|
+
const foundBinary = extractedBinary || findBinaryInDir(tempDir);
|
|
7305
|
+
if (!foundBinary) {
|
|
7306
|
+
throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
|
|
6983
7307
|
}
|
|
6984
|
-
|
|
6985
|
-
|
|
6986
|
-
const foundBinary = extractedBinary || findBinaryInDir(extractPath);
|
|
6987
|
-
if (!foundBinary) {
|
|
6988
|
-
try {
|
|
6989
|
-
fs11.unlinkSync(tempPath);
|
|
6990
|
-
} catch {
|
|
7308
|
+
if (progressCallback) {
|
|
7309
|
+
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
6991
7310
|
}
|
|
6992
|
-
|
|
6993
|
-
|
|
6994
|
-
|
|
6995
|
-
|
|
6996
|
-
|
|
6997
|
-
|
|
6998
|
-
|
|
6999
|
-
fs11.unlinkSync(targetPath);
|
|
7000
|
-
} catch {
|
|
7001
|
-
}
|
|
7311
|
+
fs12.chmodSync(foundBinary, 493);
|
|
7312
|
+
const check = spawnSync7(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
|
|
7313
|
+
const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
|
|
7314
|
+
if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
|
|
7315
|
+
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
|
|
7316
|
+
\u9000\u51FA\u7801: ${check.status}
|
|
7317
|
+
\u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
|
|
7002
7318
|
}
|
|
7003
|
-
|
|
7004
|
-
|
|
7005
|
-
|
|
7006
|
-
|
|
7007
|
-
|
|
7008
|
-
|
|
7009
|
-
|
|
7010
|
-
const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
|
|
7011
|
-
if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
|
|
7012
|
-
try {
|
|
7013
|
-
fs11.unlinkSync(targetPath);
|
|
7014
|
-
} catch {
|
|
7319
|
+
const versionMatch = checkOutput.match(/v?(\d+\.\d+\.\d+)/);
|
|
7320
|
+
if (versionMatch && latest.tag_name) {
|
|
7321
|
+
const binaryVersion = versionMatch[1];
|
|
7322
|
+
const expectedVersion = latest.tag_name.replace(/^v/, "");
|
|
7323
|
+
if (binaryVersion !== expectedVersion) {
|
|
7324
|
+
throw new Error(`\u5185\u6838\u7248\u672C\u4E0D\u5339\u914D\uFF08\u671F\u671B ${expectedVersion}\uFF0C\u5B9E\u9645 ${binaryVersion}\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD`);
|
|
7325
|
+
}
|
|
7015
7326
|
}
|
|
7327
|
+
const targetPath = PATHS.mihomoBinary;
|
|
7328
|
+
fs12.renameSync(foundBinary, targetPath);
|
|
7329
|
+
fs12.chmodSync(targetPath, 493);
|
|
7330
|
+
clearKernelVersionCache();
|
|
7331
|
+
return { version: latest.tag_name, path: targetPath };
|
|
7332
|
+
} finally {
|
|
7016
7333
|
try {
|
|
7017
|
-
|
|
7334
|
+
fs12.rmSync(tempDir, { recursive: true, force: true });
|
|
7018
7335
|
} catch {
|
|
7019
7336
|
}
|
|
7020
|
-
throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u5DF2\u5220\u9664
|
|
7021
|
-
\u9000\u51FA\u7801: ${check.status}
|
|
7022
|
-
\u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
|
|
7023
7337
|
}
|
|
7024
|
-
try {
|
|
7025
|
-
fs11.unlinkSync(tempPath);
|
|
7026
|
-
} catch {
|
|
7027
|
-
}
|
|
7028
|
-
clearKernelVersionCache();
|
|
7029
|
-
return { version: latest.tag_name, path: targetPath };
|
|
7030
7338
|
}
|
|
7031
7339
|
|
|
7032
7340
|
// src/commands/kernel.ts
|
|
@@ -7103,10 +7411,13 @@ async function cmdKernel(args) {
|
|
|
7103
7411
|
|
|
7104
7412
|
// src/commands/log.ts
|
|
7105
7413
|
function cmdLogs(args) {
|
|
7414
|
+
assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"], "logs [-f] [-n N] [\u7F16\u53F7] [-o]");
|
|
7106
7415
|
const lines = parseIntArg(args, "-n", "--lines", 100);
|
|
7107
7416
|
const openInViewer = hasFlag(args, "-o", "--open");
|
|
7108
7417
|
const follow = hasFlag(args, "-f", "--follow");
|
|
7109
|
-
const hasLinesFlag = args.some(
|
|
7418
|
+
const hasLinesFlag = args.some(
|
|
7419
|
+
(a) => a === "-n" || a === "--lines" || a.startsWith("--lines=") || a.startsWith("-n") && a.length > 2 && /^\d+$/.test(a.slice(2))
|
|
7420
|
+
);
|
|
7110
7421
|
const targetName = getNonFlagArg(args, 1) ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
|
|
7111
7422
|
if (targetName) {
|
|
7112
7423
|
let logPath;
|
|
@@ -7177,30 +7488,30 @@ function removedCommand(name, version, hint) {
|
|
|
7177
7488
|
}
|
|
7178
7489
|
|
|
7179
7490
|
// src/commands/reset.ts
|
|
7180
|
-
import
|
|
7491
|
+
import fs14 from "fs";
|
|
7181
7492
|
|
|
7182
7493
|
// src/process-stop.ts
|
|
7183
|
-
import { spawnSync as
|
|
7184
|
-
import
|
|
7494
|
+
import { spawnSync as spawnSync8 } from "child_process";
|
|
7495
|
+
import fs13 from "fs";
|
|
7185
7496
|
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
7186
7497
|
var PROCESS_WAIT_INTERVAL = 100;
|
|
7187
7498
|
var BATCH_KILL_THRESHOLD = 3;
|
|
7188
7499
|
function clearRuntime() {
|
|
7189
|
-
if (
|
|
7500
|
+
if (fs13.existsSync(DIRS.runtime)) {
|
|
7190
7501
|
rmrf(DIRS.runtime);
|
|
7191
7502
|
}
|
|
7192
7503
|
ensureDirs();
|
|
7193
7504
|
}
|
|
7194
7505
|
function clearPid() {
|
|
7195
|
-
if (!
|
|
7506
|
+
if (!fs13.existsSync(PATHS.pidFile)) return;
|
|
7196
7507
|
if (isPidFileOwnedByRoot()) {
|
|
7197
7508
|
try {
|
|
7198
|
-
|
|
7509
|
+
spawnSync8("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
|
|
7199
7510
|
} catch {
|
|
7200
7511
|
}
|
|
7201
7512
|
} else {
|
|
7202
7513
|
try {
|
|
7203
|
-
|
|
7514
|
+
fs13.unlinkSync(PATHS.pidFile);
|
|
7204
7515
|
} catch {
|
|
7205
7516
|
}
|
|
7206
7517
|
}
|
|
@@ -7218,7 +7529,7 @@ function killAllMihomo(forceSudo = false) {
|
|
|
7218
7529
|
const argv = forceSudo ? ["sudo", ["pkill", "-9", "-f", pattern]] : ["pkill", ["-9", "-f", pattern]];
|
|
7219
7530
|
const options = forceSudo ? { stdio: "inherit", timeout: 15e3 } : { timeout: 1e4 };
|
|
7220
7531
|
try {
|
|
7221
|
-
const result =
|
|
7532
|
+
const result = spawnSync8(argv[0], argv[1], options);
|
|
7222
7533
|
if (result.error) return false;
|
|
7223
7534
|
return result.status === 0 || result.status === 1;
|
|
7224
7535
|
} catch {
|
|
@@ -7304,7 +7615,8 @@ var RESET_TARGETS = [
|
|
|
7304
7615
|
aliases: ["log", "logs"],
|
|
7305
7616
|
label: "\u65E5\u5FD7",
|
|
7306
7617
|
paths: () => [DIRS.logs],
|
|
7307
|
-
|
|
7618
|
+
// 内核运行时持有日志 fd,删文件后内核继续写已删 inode,logs 0 会 tail 不存在的路径
|
|
7619
|
+
needsStop: true
|
|
7308
7620
|
},
|
|
7309
7621
|
{
|
|
7310
7622
|
id: "data",
|
|
@@ -7347,10 +7659,13 @@ var RESET_TARGETS = [
|
|
|
7347
7659
|
label: "\u8986\u5199",
|
|
7348
7660
|
paths: () => {
|
|
7349
7661
|
const dir = USER_DATA_DIR;
|
|
7350
|
-
if (!
|
|
7351
|
-
return
|
|
7662
|
+
if (!fs14.existsSync(dir)) return [];
|
|
7663
|
+
return fs14.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
|
|
7352
7664
|
},
|
|
7353
|
-
needsStop: false
|
|
7665
|
+
needsStop: false,
|
|
7666
|
+
onAfter: () => {
|
|
7667
|
+
writeSettings({ overwrite_enabled: false });
|
|
7668
|
+
}
|
|
7354
7669
|
},
|
|
7355
7670
|
{
|
|
7356
7671
|
id: "service",
|
|
@@ -7487,9 +7802,12 @@ async function cmdReset(args) {
|
|
|
7487
7802
|
});
|
|
7488
7803
|
}
|
|
7489
7804
|
}
|
|
7805
|
+
const deleted = [];
|
|
7490
7806
|
for (const t of targets) {
|
|
7807
|
+
let hadContent = false;
|
|
7491
7808
|
for (const p of t.paths()) {
|
|
7492
|
-
if (
|
|
7809
|
+
if (fs14.existsSync(p)) {
|
|
7810
|
+
hadContent = true;
|
|
7493
7811
|
try {
|
|
7494
7812
|
rmrf(p);
|
|
7495
7813
|
} catch (e) {
|
|
@@ -7498,16 +7816,23 @@ async function cmdReset(args) {
|
|
|
7498
7816
|
}
|
|
7499
7817
|
}
|
|
7500
7818
|
await t.onAfter?.();
|
|
7819
|
+
if (hadContent || !t.checkEmpty) {
|
|
7820
|
+
deleted.push(t.label);
|
|
7821
|
+
}
|
|
7501
7822
|
}
|
|
7502
7823
|
ensureDirs();
|
|
7503
7824
|
if (targets.some((t) => t.id === "settings")) {
|
|
7504
7825
|
invalidateSettingsCache();
|
|
7505
7826
|
}
|
|
7506
|
-
|
|
7827
|
+
if (deleted.length > 0) {
|
|
7828
|
+
console.log(colors.green(`\u5DF2\u91CD\u7F6E: ${deleted.join("\u3001")}`));
|
|
7829
|
+
} else {
|
|
7830
|
+
console.log("\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
|
|
7831
|
+
}
|
|
7507
7832
|
}
|
|
7508
7833
|
|
|
7509
7834
|
// src/commands/service.ts
|
|
7510
|
-
import
|
|
7835
|
+
import fs15 from "fs";
|
|
7511
7836
|
async function handleLegacyInstall() {
|
|
7512
7837
|
if (!detectLegacySystemInstall()) return;
|
|
7513
7838
|
console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09"));
|
|
@@ -7542,7 +7867,7 @@ async function cmdInstall(_args) {
|
|
|
7542
7867
|
console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
|
|
7543
7868
|
} else {
|
|
7544
7869
|
console.log("\u542F\u52A8: mihomo start");
|
|
7545
|
-
if (!
|
|
7870
|
+
if (!fs15.existsSync(PATHS.configFile)) {
|
|
7546
7871
|
console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
|
|
7547
7872
|
}
|
|
7548
7873
|
}
|
|
@@ -7576,6 +7901,9 @@ async function cmdUninstall(_args) {
|
|
|
7576
7901
|
console.log("\u624B\u52A8\u6E05\u7406: sudo pkill -9 mihomo");
|
|
7577
7902
|
}
|
|
7578
7903
|
console.log(colors.gray("\u91CD\u65B0\u5B89\u88C5: mihomo install"));
|
|
7904
|
+
console.log(colors.gray("\u5F7B\u5E95\u79FB\u9664 mihomo-cli:"));
|
|
7905
|
+
console.log(colors.gray(" mihomo reset --full # \u5220\u9664\u5168\u90E8\u6570\u636E\uFF08\u8BA2\u9605/\u5185\u6838/\u65E5\u5FD7\u7B49\uFF09"));
|
|
7906
|
+
console.log(colors.gray(" npm uninstall -g mihomo-cli"));
|
|
7579
7907
|
console.log("");
|
|
7580
7908
|
}
|
|
7581
7909
|
|
|
@@ -7585,8 +7913,7 @@ function handleStopResult(result) {
|
|
|
7585
7913
|
throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint: "\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo" });
|
|
7586
7914
|
}
|
|
7587
7915
|
}
|
|
7588
|
-
async function cmdStop(
|
|
7589
|
-
assertNoRemovedSshFlag(args);
|
|
7916
|
+
async function cmdStop(_args) {
|
|
7590
7917
|
if (detectLegacySystemInstall()) {
|
|
7591
7918
|
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"));
|
|
7592
7919
|
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"));
|
|
@@ -7619,10 +7946,10 @@ async function cmdStop(args) {
|
|
|
7619
7946
|
}
|
|
7620
7947
|
|
|
7621
7948
|
// src/commands/ui.ts
|
|
7622
|
-
import { spawnSync as
|
|
7949
|
+
import { spawnSync as spawnSync9 } from "child_process";
|
|
7623
7950
|
function copyToClipboard(text) {
|
|
7624
7951
|
try {
|
|
7625
|
-
return
|
|
7952
|
+
return spawnSync9("pbcopy", [], { input: text }).status === 0;
|
|
7626
7953
|
} catch {
|
|
7627
7954
|
return false;
|
|
7628
7955
|
}
|
|
@@ -7642,7 +7969,7 @@ function cmdUI(args) {
|
|
|
7642
7969
|
const secret = readSettings().controller_secret;
|
|
7643
7970
|
if (secret) {
|
|
7644
7971
|
console.log(
|
|
7645
|
-
copyToClipboard(secret) ? "\u5DF2\u914D\u7F6E\u8BBF\u95EE\u5BC6\u94A5\uFF08\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\uFF0CUI \u8FDE\u63A5\u65F6\u7C98\u8D34\uFF09" :
|
|
7972
|
+
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`
|
|
7646
7973
|
);
|
|
7647
7974
|
}
|
|
7648
7975
|
const success = openUrl(url);
|
|
@@ -7651,66 +7978,6 @@ function cmdUI(args) {
|
|
|
7651
7978
|
}
|
|
7652
7979
|
}
|
|
7653
7980
|
|
|
7654
|
-
// src/commands/update.ts
|
|
7655
|
-
import { execFile as execFile2, spawn as spawn2 } from "child_process";
|
|
7656
|
-
import { promisify as promisify2 } from "util";
|
|
7657
|
-
var execFileAsync2 = promisify2(execFile2);
|
|
7658
|
-
var NPM_VIEW_TIMEOUT_MS = 15e3;
|
|
7659
|
-
async function getLatestNpmVersion() {
|
|
7660
|
-
try {
|
|
7661
|
-
const { stdout } = await execFileAsync2("npm", ["view", PKG_NAME, "version"], { timeout: NPM_VIEW_TIMEOUT_MS });
|
|
7662
|
-
const version = stdout.trim().split("\n").pop()?.trim();
|
|
7663
|
-
return version || null;
|
|
7664
|
-
} catch {
|
|
7665
|
-
return null;
|
|
7666
|
-
}
|
|
7667
|
-
}
|
|
7668
|
-
async function cmdUpdate() {
|
|
7669
|
-
console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
|
|
7670
|
-
console.log("");
|
|
7671
|
-
const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
|
|
7672
|
-
if (latest && latest === VERSION) {
|
|
7673
|
-
console.log(`\u5DF2\u662F\u6700\u65B0\u7248\u672C (${colors.green(VERSION)})\uFF0C\u65E0\u9700\u66F4\u65B0`);
|
|
7674
|
-
return;
|
|
7675
|
-
}
|
|
7676
|
-
if (latest) {
|
|
7677
|
-
console.log(`\u6700\u65B0\u7248\u672C: ${colors.cyan(latest)}`);
|
|
7678
|
-
} else {
|
|
7679
|
-
console.log(colors.yellow("\u65E0\u6CD5\u67E5\u8BE2\u6700\u65B0\u7248\u672C\uFF08\u7F51\u7EDC\u95EE\u9898\uFF1F\uFF09\uFF0C\u5C06\u76F4\u63A5\u5C1D\u8BD5\u91CD\u65B0\u5B89\u88C5"));
|
|
7680
|
-
}
|
|
7681
|
-
console.log("");
|
|
7682
|
-
console.log("\u6B63\u5728\u66F4\u65B0 mihomo-cli...");
|
|
7683
|
-
console.log("");
|
|
7684
|
-
await new Promise((resolve, reject) => {
|
|
7685
|
-
const npm = spawn2("npm", ["install", "-g", PKG_NAME], { stdio: "inherit" });
|
|
7686
|
-
npm.on("close", (code) => {
|
|
7687
|
-
if (code === 0) {
|
|
7688
|
-
resolve();
|
|
7689
|
-
} else {
|
|
7690
|
-
reject(new CliError("\u66F4\u65B0\u5931\u8D25\u3002\u82E5\u4E3A\u6743\u9650\u95EE\u9898\uFF08EACCES\uFF09\uFF0C\u8BF7\u68C0\u67E5 npm \u5168\u5C40\u76EE\u5F55\u6743\u9650\u6216\u4F7F\u7528 nvm \u7BA1\u7406 Node", { exitCode: code || 1 }));
|
|
7691
|
-
}
|
|
7692
|
-
});
|
|
7693
|
-
npm.on("error", (e) => {
|
|
7694
|
-
const perm = e.message.includes("EACCES") || e.message.includes("permission");
|
|
7695
|
-
reject(perm ? new CliError("\u6743\u9650\u4E0D\u8DB3\uFF08EACCES\uFF09\uFF0C\u8BF7\u68C0\u67E5 npm \u5168\u5C40\u76EE\u5F55\u6743\u9650\u6216\u4F7F\u7528 nvm \u7BA1\u7406 Node") : new CliError(`\u6267\u884C\u5931\u8D25: ${e.message}`));
|
|
7696
|
-
});
|
|
7697
|
-
});
|
|
7698
|
-
try {
|
|
7699
|
-
const { stdout } = await execFileAsync2("npm", ["list", "-g", PKG_NAME, "--json", "--depth=0"]);
|
|
7700
|
-
const result = JSON.parse(stdout);
|
|
7701
|
-
const newVersion = result.dependencies?.[PKG_NAME]?.version;
|
|
7702
|
-
console.log("");
|
|
7703
|
-
if (newVersion) {
|
|
7704
|
-
console.log(`\u66F4\u65B0\u5B8C\u6210\uFF0C\u6700\u65B0\u7248\u672C: ${colors.green(newVersion)}`);
|
|
7705
|
-
} else {
|
|
7706
|
-
console.log("\u66F4\u65B0\u5B8C\u6210");
|
|
7707
|
-
}
|
|
7708
|
-
} catch {
|
|
7709
|
-
console.log("");
|
|
7710
|
-
console.log("\u66F4\u65B0\u5B8C\u6210");
|
|
7711
|
-
}
|
|
7712
|
-
}
|
|
7713
|
-
|
|
7714
7981
|
// src/commands/registry.ts
|
|
7715
7982
|
var COMMANDS = [
|
|
7716
7983
|
// === 控制 ===
|
|
@@ -7802,7 +8069,14 @@ var COMMANDS = [
|
|
|
7802
8069
|
name: "log",
|
|
7803
8070
|
aliases: [],
|
|
7804
8071
|
handler: cmdLogs,
|
|
7805
|
-
|
|
8072
|
+
// 隐藏别名:log = logs 0 -f。用户传了编号时尊重编号(log 1 = logs 1 -f),
|
|
8073
|
+
// 而非恒为 0——此前编号被 '0' 顶掉,log 1 跟随的是当前日志而非归档 1
|
|
8074
|
+
rewrite: (args) => {
|
|
8075
|
+
const hasNum = args[1] !== void 0 && /^\d+$/.test(args[1]);
|
|
8076
|
+
const num = hasNum ? args[1] : "0";
|
|
8077
|
+
const rest = hasNum ? args.slice(2) : args.slice(1);
|
|
8078
|
+
return ["logs", num, "-f", ...rest];
|
|
8079
|
+
},
|
|
7806
8080
|
group: "interface",
|
|
7807
8081
|
usage: [],
|
|
7808
8082
|
hidden: true
|
|
@@ -7885,14 +8159,17 @@ var COMMANDS = [
|
|
|
7885
8159
|
aliases: [],
|
|
7886
8160
|
handler: cmdDoctor,
|
|
7887
8161
|
group: "system",
|
|
7888
|
-
usage: [{ signature: "doctor", description: "\u4F53\u68C0\u8BCA\u65AD\uFF08\u5185\u6838/\u670D\u52A1/\u7AEF\u53E3/\u8BA2\u9605/\u914D\u7F6E/\u8FDE\u901A\u6027\uFF0C\u6709\u5F02\u5E38\u9000\u51FA\u7801 1\uFF09" }]
|
|
8162
|
+
usage: [{ signature: "doctor", description: "\u4F53\u68C0\u8BCA\u65AD\uFF08\u5185\u6838/\u670D\u52A1/\u7AEF\u53E3/\u8BA2\u9605/\u914D\u7F6E/\u8FDE\u901A\u6027/CLI \u7248\u672C\uFF0C\u6709\u5F02\u5E38\u9000\u51FA\u7801 1\uFF09" }]
|
|
7889
8163
|
},
|
|
7890
8164
|
{
|
|
7891
8165
|
name: "completion",
|
|
7892
8166
|
aliases: [],
|
|
7893
8167
|
handler: (args) => cmdCompletion(args, COMMANDS),
|
|
7894
8168
|
group: "system",
|
|
7895
|
-
usage: [
|
|
8169
|
+
usage: [
|
|
8170
|
+
{ signature: "completion install <zsh|bash|fish>", description: "\u5B89\u88C5\u8865\u5168\u5230\u5BF9\u5E94 shell \u7684\u9ED8\u8BA4\u4F4D\u7F6E" },
|
|
8171
|
+
{ signature: "completion <zsh|bash|fish>", description: "\u8F93\u51FA\u8865\u5168\u811A\u672C\uFF08\u91CD\u5B9A\u5411\u6216 eval \u4F7F\u7528\uFF09" }
|
|
8172
|
+
]
|
|
7896
8173
|
},
|
|
7897
8174
|
// === meta(不在分组清单展示,help 末尾单列) ===
|
|
7898
8175
|
{
|
|
@@ -8014,6 +8291,7 @@ async function main() {
|
|
|
8014
8291
|
assertSupportedPlatform(command.name);
|
|
8015
8292
|
assertNotRoot(command.name);
|
|
8016
8293
|
ensureDirs();
|
|
8294
|
+
assertNoRemovedSshFlag(args);
|
|
8017
8295
|
await command.handler(command.rewrite ? command.rewrite(args) : args);
|
|
8018
8296
|
}
|
|
8019
8297
|
main().catch((e) => {
|