mihomo-cli 26.10.115 → 26.11.117
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 +22 -25
- package/LICENSE +4 -0
- package/README.md +7 -22
- package/SECURITY.md +3 -3
- package/dist/index.js +735 -1195
- package/docs/overwrite.md +1 -1
- package/package.json +3 -5
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
|
-
import
|
|
4
|
+
import fs17 from "fs";
|
|
5
5
|
|
|
6
6
|
// node_modules/compare-versions/lib/esm/utils.js
|
|
7
7
|
var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
|
|
@@ -168,6 +168,7 @@ var pkg = require2("../package.json");
|
|
|
168
168
|
var YAML_MAX_ALIASES = 200;
|
|
169
169
|
var VERSION = pkg.version;
|
|
170
170
|
var PKG_NAME = pkg.name;
|
|
171
|
+
var CLI_ALIASES = Object.keys(pkg.bin).filter((name) => name !== PKG_NAME);
|
|
171
172
|
var NODE_ENGINES = typeof pkg.engines?.node === "string" ? pkg.engines.node : null;
|
|
172
173
|
var MIRROR_HOST = "gh-proxy.org";
|
|
173
174
|
var MIRROR_ALIASES = {
|
|
@@ -196,6 +197,9 @@ var CONTROLLER_PORT = 9090;
|
|
|
196
197
|
function isValidPortNumber(value) {
|
|
197
198
|
return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535;
|
|
198
199
|
}
|
|
200
|
+
function isPlainObject(value) {
|
|
201
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
202
|
+
}
|
|
199
203
|
var TUN_CONFIG = {
|
|
200
204
|
tun: {
|
|
201
205
|
enable: true,
|
|
@@ -334,6 +338,22 @@ function matchValueFlagToken(token) {
|
|
|
334
338
|
}
|
|
335
339
|
return null;
|
|
336
340
|
}
|
|
341
|
+
function collectFlagValues(args, forms) {
|
|
342
|
+
const hits = [];
|
|
343
|
+
for (let i = 0; i < args.length; i++) {
|
|
344
|
+
const match = matchValueFlagToken(args[i]);
|
|
345
|
+
if (!match || !forms.some((f) => match.spec.forms.includes(f))) continue;
|
|
346
|
+
if (match.form !== "exact") {
|
|
347
|
+
hits.push({ flag: match.baseForm, value: match.inlineValue });
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
const next = args[i + 1];
|
|
351
|
+
const takesNext = next !== void 0 && (match.spec.takesValue === "required" || !next.startsWith("-"));
|
|
352
|
+
hits.push({ flag: match.baseForm, value: takesNext ? next : null });
|
|
353
|
+
if (takesNext) i++;
|
|
354
|
+
}
|
|
355
|
+
return hits;
|
|
356
|
+
}
|
|
337
357
|
|
|
338
358
|
// src/argv.ts
|
|
339
359
|
function hasFlag(args, short, long) {
|
|
@@ -358,68 +378,48 @@ function assertKnownFlags(args, known, command) {
|
|
|
358
378
|
});
|
|
359
379
|
}
|
|
360
380
|
}
|
|
361
|
-
function
|
|
362
|
-
|
|
363
|
-
let count = 0;
|
|
381
|
+
function positionalArgs(args, startIdx) {
|
|
382
|
+
const out = [];
|
|
364
383
|
for (let i = startIdx; i < args.length; i++) {
|
|
365
384
|
const a = args[i];
|
|
366
|
-
if (a.startsWith("-")) {
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
count++;
|
|
371
|
-
if (count > max) {
|
|
372
|
-
throw new CliError(`\u591A\u4F59\u7684\u53C2\u6570: ${a}`, {
|
|
373
|
-
label: "\u53C2\u6570\u9519\u8BEF",
|
|
374
|
-
hint: [`\u7528\u6CD5: ${usage}`]
|
|
375
|
-
});
|
|
385
|
+
if (!a.startsWith("-")) {
|
|
386
|
+
out.push(a);
|
|
387
|
+
} else if (VALUE_FLAGS.has(a) && i + 1 < args.length && !args[i + 1].startsWith("-")) {
|
|
388
|
+
i++;
|
|
376
389
|
}
|
|
377
390
|
}
|
|
391
|
+
return out;
|
|
392
|
+
}
|
|
393
|
+
function assertPositionalCount(args, max, startIdx, usage) {
|
|
394
|
+
if (!args) return;
|
|
395
|
+
const extra = positionalArgs(args, startIdx)[max];
|
|
396
|
+
if (extra !== void 0) {
|
|
397
|
+
throw new CliError(`\u591A\u4F59\u7684\u53C2\u6570: ${extra}`, {
|
|
398
|
+
label: "\u53C2\u6570\u9519\u8BEF",
|
|
399
|
+
hint: [`\u7528\u6CD5: ${usage}`]
|
|
400
|
+
});
|
|
401
|
+
}
|
|
378
402
|
}
|
|
379
403
|
function parseIntArg(args, short, long, defaultValue) {
|
|
380
404
|
if (!args) return defaultValue;
|
|
381
|
-
const
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
throw new CliError(`\u9009\u9879 ${flag} \u9700\u8981 >= 1 \u7684\u6574\u6570\uFF0C\u6536\u5230 "${raw}"`, { hint: [`\u4F8B\u5982: ${flag} ${defaultValue}`] });
|
|
388
|
-
}
|
|
389
|
-
return val;
|
|
390
|
-
};
|
|
391
|
-
let first = null;
|
|
392
|
-
let count = 0;
|
|
393
|
-
for (let i = 0; i < args.length; i++) {
|
|
394
|
-
if (args[i] === short || args[i] === long) {
|
|
395
|
-
if (first === null && count === 0) {
|
|
396
|
-
if (i + 1 >= args.length) {
|
|
397
|
-
throw new CliError(`\u9009\u9879 ${args[i]} \u7F3A\u5C11\u503C`, { hint: [`\u4F8B\u5982: ${args[i]} ${defaultValue}`] });
|
|
398
|
-
}
|
|
399
|
-
first = { value: args[i + 1], flag: args[i] };
|
|
400
|
-
i++;
|
|
401
|
-
count++;
|
|
402
|
-
continue;
|
|
403
|
-
}
|
|
404
|
-
count++;
|
|
405
|
-
continue;
|
|
406
|
-
}
|
|
407
|
-
const match = matchValueFlagToken(args[i]);
|
|
408
|
-
if (match && match.form !== "exact" && (match.spec.forms.includes(short) || match.spec.forms.includes(long))) {
|
|
409
|
-
if (first === null && count === 0) {
|
|
410
|
-
first = { value: match.inlineValue ?? "", flag: match.baseForm };
|
|
411
|
-
}
|
|
412
|
-
count++;
|
|
413
|
-
}
|
|
405
|
+
const hits = collectFlagValues(args, [short, long]);
|
|
406
|
+
if (hits.length === 0) return defaultValue;
|
|
407
|
+
const { flag, value } = hits[0];
|
|
408
|
+
const hint = [`\u4F8B\u5982: ${flag} ${defaultValue}`];
|
|
409
|
+
if (hits.length > 1) {
|
|
410
|
+
throw new CliError(`\u9009\u9879 ${flag} \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21\uFF08\u51FA\u73B0 ${hits.length} \u6B21\uFF09`, { hint });
|
|
414
411
|
}
|
|
415
|
-
if (
|
|
416
|
-
|
|
417
|
-
throw new CliError(`\u9009\u9879 ${flag} \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21\uFF08\u51FA\u73B0 ${count} \u6B21\uFF09`, { hint: [`\u4F8B\u5982: ${flag} ${defaultValue}`] });
|
|
412
|
+
if (value === null) {
|
|
413
|
+
throw new CliError(`\u9009\u9879 ${flag} \u7F3A\u5C11\u503C`, { hint });
|
|
418
414
|
}
|
|
419
|
-
if (
|
|
420
|
-
|
|
415
|
+
if (!/^\d+$/.test(value.trim())) {
|
|
416
|
+
throw new CliError(`\u9009\u9879 ${flag} \u9700\u8981\u6B63\u6574\u6570\uFF0C\u6536\u5230 "${value}"`, { hint });
|
|
421
417
|
}
|
|
422
|
-
|
|
418
|
+
const val = Number(value);
|
|
419
|
+
if (!Number.isSafeInteger(val) || val < 1) {
|
|
420
|
+
throw new CliError(`\u9009\u9879 ${flag} \u9700\u8981 >= 1 \u7684\u6574\u6570\uFF0C\u6536\u5230 "${value}"`, { hint });
|
|
421
|
+
}
|
|
422
|
+
return val;
|
|
423
423
|
}
|
|
424
424
|
function extractStartOptions(args) {
|
|
425
425
|
if (!args) return [];
|
|
@@ -445,15 +445,7 @@ function assertRestartOptionValues(args) {
|
|
|
445
445
|
}
|
|
446
446
|
function getNonFlagArg(args, startIdx) {
|
|
447
447
|
if (!args) return null;
|
|
448
|
-
|
|
449
|
-
const a = args[i];
|
|
450
|
-
if (a.startsWith("-")) {
|
|
451
|
-
if (VALUE_FLAGS.has(a) && i + 1 < args.length && !args[i + 1].startsWith("-")) i++;
|
|
452
|
-
continue;
|
|
453
|
-
}
|
|
454
|
-
return a;
|
|
455
|
-
}
|
|
456
|
-
return null;
|
|
448
|
+
return positionalArgs(args, startIdx)[0] ?? null;
|
|
457
449
|
}
|
|
458
450
|
|
|
459
451
|
// src/colors.ts
|
|
@@ -954,7 +946,7 @@ var seqTag = defineSequenceTag("tag:yaml.org,2002:seq", {
|
|
|
954
946
|
},
|
|
955
947
|
identify: Array.isArray
|
|
956
948
|
});
|
|
957
|
-
function
|
|
949
|
+
function isPlainObject2(data) {
|
|
958
950
|
if (data === null || typeof data !== "object" || Array.isArray(data)) return false;
|
|
959
951
|
const prototype = Object.getPrototypeOf(data);
|
|
960
952
|
return prototype === null || prototype === Object.prototype;
|
|
@@ -974,7 +966,7 @@ var omapTag = defineSequenceTag("tag:yaml.org,2002:omap", {
|
|
|
974
966
|
if (item instanceof Map) {
|
|
975
967
|
if (item.size !== 1) return "cannot resolve an ordered map item";
|
|
976
968
|
key = item.keys().next().value;
|
|
977
|
-
} else if (
|
|
969
|
+
} else if (isPlainObject2(item)) {
|
|
978
970
|
const itemKeys = Object.keys(item);
|
|
979
971
|
if (itemKeys.length !== 1) return "cannot resolve an ordered map item";
|
|
980
972
|
key = itemKeys[0];
|
|
@@ -1006,7 +998,7 @@ var pairsTag = defineSequenceTag("tag:yaml.org,2002:pairs", {
|
|
|
1006
998
|
});
|
|
1007
999
|
var mapTag = defineMappingTag("tag:yaml.org,2002:map", {
|
|
1008
1000
|
create: () => ({}),
|
|
1009
|
-
identify:
|
|
1001
|
+
identify: isPlainObject2,
|
|
1010
1002
|
represent: (o) => {
|
|
1011
1003
|
const map = /* @__PURE__ */ new Map();
|
|
1012
1004
|
for (const key of Object.keys(o)) map.set(key, o[key]);
|
|
@@ -1263,7 +1255,7 @@ var realMapTag = defineMappingTag("tag:yaml.org,2002:map", {
|
|
|
1263
1255
|
has: (container, key) => container.has(key),
|
|
1264
1256
|
keys: (container) => container.keys(),
|
|
1265
1257
|
get: (container, key) => container.get(key),
|
|
1266
|
-
identify: (data) => data instanceof Map ||
|
|
1258
|
+
identify: (data) => data instanceof Map || isPlainObject2(data),
|
|
1267
1259
|
represent: (data) => {
|
|
1268
1260
|
if (data instanceof Map) return data;
|
|
1269
1261
|
const map = /* @__PURE__ */ new Map();
|
|
@@ -1286,7 +1278,7 @@ function normalizeKey(key) {
|
|
|
1286
1278
|
}
|
|
1287
1279
|
var legacyMapTag = defineMappingTag("tag:yaml.org,2002:map", {
|
|
1288
1280
|
create: () => ({}),
|
|
1289
|
-
identify:
|
|
1281
|
+
identify: isPlainObject2,
|
|
1290
1282
|
represent: (o) => {
|
|
1291
1283
|
const map = /* @__PURE__ */ new Map();
|
|
1292
1284
|
for (const key of Object.keys(o)) map.set(key, o[key]);
|
|
@@ -3684,8 +3676,6 @@ var PATHS = {
|
|
|
3684
3676
|
subscriptionsCacheFile: path.join(DIRS.subscriptions, "cache.json"),
|
|
3685
3677
|
configFile: path.join(DIRS.runtime, "config.yaml"),
|
|
3686
3678
|
logFile: path.join(DIRS.logs, "mihomo.log"),
|
|
3687
|
-
/** CLI 结构化操作事件;独立于内核文本日志及其归档编号,由 diagnostic-events.ts 自管轮转 */
|
|
3688
|
-
diagnosticEventsFile: path.join(DIRS.logs, "diagnostic.jsonl"),
|
|
3689
3679
|
pidFile: path.join(DIRS.runtime, "pid"),
|
|
3690
3680
|
/**
|
|
3691
3681
|
* installService 的 plist 暂存文件(plutil -lint 校验通过后才原子写
|
|
@@ -3727,7 +3717,7 @@ var PATHS = {
|
|
|
3727
3717
|
userAgentPlist: path.join(os.homedir(), "Library/LaunchAgents", `${SERVICE_LABEL}.plist`)
|
|
3728
3718
|
};
|
|
3729
3719
|
var DIRECTORY_TARGETS = {
|
|
3730
|
-
root: { path:
|
|
3720
|
+
root: { path: USER_DATA_DIR, label: "\u6839\u76EE\u5F55" },
|
|
3731
3721
|
subs: { path: DIRS.subscriptions, label: "\u8BA2\u9605\u76EE\u5F55" },
|
|
3732
3722
|
logs: { path: DIRS.logs, label: "\u65E5\u5FD7\u76EE\u5F55" },
|
|
3733
3723
|
data: { path: DIRS.data, label: "\u8FD0\u884C\u6570\u636E\u76EE\u5F55" },
|
|
@@ -3890,7 +3880,7 @@ function readSettings() {
|
|
|
3890
3880
|
if (!fs2.existsSync(PATHS.settingsFile)) return {};
|
|
3891
3881
|
try {
|
|
3892
3882
|
const parsed = JSON.parse(fs2.readFileSync(PATHS.settingsFile, "utf8"));
|
|
3893
|
-
if (
|
|
3883
|
+
if (isPlainObject(parsed)) return parsed;
|
|
3894
3884
|
return backupCorruptSettings(nonObjectReason(parsed));
|
|
3895
3885
|
} catch (e) {
|
|
3896
3886
|
if (e.code === "ENOENT") return {};
|
|
@@ -3900,7 +3890,7 @@ function readSettings() {
|
|
|
3900
3890
|
function isValidSettingsContent(content) {
|
|
3901
3891
|
try {
|
|
3902
3892
|
const parsed = JSON.parse(content);
|
|
3903
|
-
return
|
|
3893
|
+
return isPlainObject(parsed);
|
|
3904
3894
|
} catch {
|
|
3905
3895
|
return false;
|
|
3906
3896
|
}
|
|
@@ -3936,7 +3926,7 @@ function validatePort(value, key) {
|
|
|
3936
3926
|
function getPorts(settings = readSettings()) {
|
|
3937
3927
|
const ports = settings.ports;
|
|
3938
3928
|
if (ports === void 0) return { mixed: DEFAULT_MIXED_PORT, controller: CONTROLLER_PORT };
|
|
3939
|
-
if (
|
|
3929
|
+
if (!isPlainObject(ports)) {
|
|
3940
3930
|
throw new CliError('settings.json \u7684 ports \u9700\u4E3A\u5BF9\u8C61\uFF0C\u5982 { "mixed": 17890, "controller": 19090 }', { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
3941
3931
|
}
|
|
3942
3932
|
const configuredMixed = validatePort(ports.mixed, "ports.mixed");
|
|
@@ -3973,7 +3963,7 @@ function readSubscriptionCache() {
|
|
|
3973
3963
|
try {
|
|
3974
3964
|
const content = fs2.readFileSync(PATHS.subscriptionsCacheFile, "utf8");
|
|
3975
3965
|
const parsed = JSON.parse(content);
|
|
3976
|
-
if (
|
|
3966
|
+
if (!isPlainObject(parsed)) {
|
|
3977
3967
|
return backupCorruptSubscriptionCache(nonObjectReason(parsed));
|
|
3978
3968
|
}
|
|
3979
3969
|
return Object.assign(empty(), parsed);
|
|
@@ -3997,7 +3987,7 @@ function saveSubscriptionCache(subName, data) {
|
|
|
3997
3987
|
withFileLock(PATHS.subscriptionCacheLock, () => {
|
|
3998
3988
|
const cache = readSubscriptionCache();
|
|
3999
3989
|
const old = cache[subName];
|
|
4000
|
-
cache[subName] = { ...
|
|
3990
|
+
cache[subName] = { ...isPlainObject(old) ? old : {}, ...data };
|
|
4001
3991
|
writeSubscriptionCache(cache);
|
|
4002
3992
|
});
|
|
4003
3993
|
}
|
|
@@ -4036,7 +4026,7 @@ function getSubscriptionsWithCache() {
|
|
|
4036
4026
|
const cache = readSubscriptionCache();
|
|
4037
4027
|
return subs.map((s) => {
|
|
4038
4028
|
const entry = cache[s.name];
|
|
4039
|
-
const safe =
|
|
4029
|
+
const safe = isPlainObject(entry) ? entry : {};
|
|
4040
4030
|
return { ...s, ...safe };
|
|
4041
4031
|
});
|
|
4042
4032
|
}
|
|
@@ -4274,20 +4264,7 @@ function protoKeyInOverwriteError() {
|
|
|
4274
4264
|
});
|
|
4275
4265
|
}
|
|
4276
4266
|
function mergeConfigLevel(target, override, parseOperators) {
|
|
4277
|
-
|
|
4278
|
-
if (t === null || t === void 0) {
|
|
4279
|
-
t = Array.isArray(override) ? [] : {};
|
|
4280
|
-
}
|
|
4281
|
-
if (override === null || override === void 0) {
|
|
4282
|
-
return t;
|
|
4283
|
-
}
|
|
4284
|
-
if (typeof override !== "object") {
|
|
4285
|
-
return override;
|
|
4286
|
-
}
|
|
4287
|
-
if (Array.isArray(override)) {
|
|
4288
|
-
return override;
|
|
4289
|
-
}
|
|
4290
|
-
const result = { ...t };
|
|
4267
|
+
const result = { ...target };
|
|
4291
4268
|
for (const [rawKey, value] of Object.entries(override)) {
|
|
4292
4269
|
let key = rawKey;
|
|
4293
4270
|
let forceOverwrite = false;
|
|
@@ -4321,7 +4298,7 @@ function mergeConfigLevel(target, override, parseOperators) {
|
|
|
4321
4298
|
result[key] = value;
|
|
4322
4299
|
continue;
|
|
4323
4300
|
}
|
|
4324
|
-
if (
|
|
4301
|
+
if (isPlainObject(value) && isPlainObject(existingValue)) {
|
|
4325
4302
|
result[key] = mergeConfigLevel(existingValue, value, false);
|
|
4326
4303
|
continue;
|
|
4327
4304
|
}
|
|
@@ -4329,8 +4306,7 @@ function mergeConfigLevel(target, override, parseOperators) {
|
|
|
4329
4306
|
}
|
|
4330
4307
|
return result;
|
|
4331
4308
|
}
|
|
4332
|
-
function isOverwriteEnabled() {
|
|
4333
|
-
const settings = readSettings();
|
|
4309
|
+
function isOverwriteEnabled(settings = readSettings()) {
|
|
4334
4310
|
return settings.overwrite_enabled !== false;
|
|
4335
4311
|
}
|
|
4336
4312
|
function setOverwriteEnabled(enabled) {
|
|
@@ -4379,13 +4355,12 @@ function normalizeMatch(raw, fileName) {
|
|
|
4379
4355
|
hint: ["match: \u540E\u9762\u8981\u8DDF\u6761\u4EF6\u5757\uFF08\u68C0\u67E5\u7F29\u8FDB\uFF09\uFF0C\u5982:", " match:", " name: edu*"]
|
|
4380
4356
|
});
|
|
4381
4357
|
}
|
|
4382
|
-
if (
|
|
4358
|
+
if (!isPlainObject(raw)) {
|
|
4383
4359
|
throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 match \u5FC5\u987B\u662F\u5BF9\u8C61\uFF08name / url-domain\uFF09`, { label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF" });
|
|
4384
4360
|
}
|
|
4385
|
-
const rawEntries = raw;
|
|
4386
4361
|
const result = {};
|
|
4387
4362
|
const problems = [];
|
|
4388
|
-
for (const [key, value] of Object.entries(
|
|
4363
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
4389
4364
|
if (!MATCH_KEYS.has(key)) {
|
|
4390
4365
|
problems.push(`\u672A\u77E5\u952E "${key}"`);
|
|
4391
4366
|
continue;
|
|
@@ -4595,7 +4570,7 @@ function readOverwriteFiles() {
|
|
|
4595
4570
|
if (isBlankYamlDocument(content)) continue;
|
|
4596
4571
|
const parsed = load(content, { maxAliases: YAML_MAX_ALIASES });
|
|
4597
4572
|
assertConfigGraphSafe(parsed, `\u8986\u5199\u6587\u4EF6 "${file}"`);
|
|
4598
|
-
if (
|
|
4573
|
+
if (isPlainObject(parsed)) {
|
|
4599
4574
|
const { match, enabled, ...config } = parsed;
|
|
4600
4575
|
assertNoMetadataKeyLookalikes(config, file);
|
|
4601
4576
|
assertFileLevelOperatorRules(config, file);
|
|
@@ -4614,10 +4589,14 @@ function readOverwriteFiles() {
|
|
|
4614
4589
|
return { ok, broken };
|
|
4615
4590
|
}
|
|
4616
4591
|
function isBlankYamlDocument(content) {
|
|
4617
|
-
|
|
4618
|
-
const
|
|
4619
|
-
|
|
4620
|
-
|
|
4592
|
+
for (let start = 0; start < content.length; ) {
|
|
4593
|
+
const end = content.indexOf("\n", start);
|
|
4594
|
+
const line = content.slice(start, end === -1 ? void 0 : end).trimStart();
|
|
4595
|
+
if (line && !line.startsWith("#")) return false;
|
|
4596
|
+
if (end === -1) break;
|
|
4597
|
+
start = end + 1;
|
|
4598
|
+
}
|
|
4599
|
+
return true;
|
|
4621
4600
|
}
|
|
4622
4601
|
function overwriteSortKey(filename) {
|
|
4623
4602
|
const segment = isScriptOverwriteFilename(filename) ? "0" : "1";
|
|
@@ -4716,7 +4695,7 @@ function parseConfigContent(content, errorMsg) {
|
|
|
4716
4695
|
} catch (e) {
|
|
4717
4696
|
throw new CliError(`${label}\u683C\u5F0F\u9519\u8BEF\uFF0C\u65E0\u6CD5\u89E3\u6790: ${firstLine(e.message)}`, { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
4718
4697
|
}
|
|
4719
|
-
if (
|
|
4698
|
+
if (!isPlainObject(result)) {
|
|
4720
4699
|
throw new CliError(`${label}\u4E0D\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61\uFF08\u9876\u5C42\u9700\u4E3A\u6620\u5C04\uFF0C\u5F53\u524D\u662F${Array.isArray(result) ? "\u5217\u8868" : typeof result}\uFF09`, { label: "\u914D\u7F6E\u9519\u8BEF" });
|
|
4721
4700
|
}
|
|
4722
4701
|
assertConfigGraphSafe(result, label);
|
|
@@ -4727,7 +4706,7 @@ function dumpYaml(obj) {
|
|
|
4727
4706
|
}
|
|
4728
4707
|
function assertDnsShape(dnsRaw) {
|
|
4729
4708
|
if (dnsRaw === void 0 || dnsRaw === null) return;
|
|
4730
|
-
if (
|
|
4709
|
+
if (!isPlainObject(dnsRaw)) {
|
|
4731
4710
|
throw new CliError(`dns \u914D\u7F6E\u5FC5\u987B\u662F\u6620\u5C04\uFF0C\u5F53\u524D\u662F${Array.isArray(dnsRaw) ? "\u6570\u7EC4" : `\u6807\u91CF\uFF08${typeof dnsRaw}\uFF09`}`, {
|
|
4732
4711
|
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
4733
4712
|
hint: ["dns \u662F\u8BA2\u9605/\u8986\u5199\u91CC\u7684\u5BF9\u8C61\u914D\u7F6E\u5757\uFF08enable\u3001nameserver \u7B49\uFF09\uFF0C\u4E0D\u652F\u6301\u6807\u91CF\u6216\u6570\u7EC4\u3002"]
|
|
@@ -4763,7 +4742,7 @@ function assertConfigShape(config) {
|
|
|
4763
4742
|
});
|
|
4764
4743
|
}
|
|
4765
4744
|
if (needsName) {
|
|
4766
|
-
if (
|
|
4745
|
+
if (!isPlainObject(item)) {
|
|
4767
4746
|
throw new CliError(`${key}[${i}] \u5FC5\u987B\u662F\u6620\u5C04`, {
|
|
4768
4747
|
label: "\u914D\u7F6E\u9519\u8BEF",
|
|
4769
4748
|
hint: [`${label}\u6BB5\uFF08${key}\uFF09\u7B2C ${i + 1} \u9879\u5E94\u4E3A {name: ..., ...} \u5F62\u5F0F\uFF0C\u5F53\u524D\u662F ${Array.isArray(item) ? "\u5217\u8868" : typeof item}\u3002`]
|
|
@@ -4788,7 +4767,7 @@ function assertConfigShape(config) {
|
|
|
4788
4767
|
function buildConfig(subRawContent, mode, scope) {
|
|
4789
4768
|
const subscriptionConfig = parseConfigContent(subRawContent, "\u8BA2\u9605\u5185\u5BB9");
|
|
4790
4769
|
const settings = readSettings();
|
|
4791
|
-
const allFiles = settings
|
|
4770
|
+
const allFiles = isOverwriteEnabled(settings) ? loadOverwriteFile() : [];
|
|
4792
4771
|
const overwriteFiles = selectActiveOverwriteFiles(allFiles, scope);
|
|
4793
4772
|
const {
|
|
4794
4773
|
config: withOverwrites,
|
|
@@ -4887,9 +4866,8 @@ function countConfigNodes(config) {
|
|
|
4887
4866
|
proxyGroups: proxyGroups ? proxyGroups.length : 0
|
|
4888
4867
|
};
|
|
4889
4868
|
}
|
|
4890
|
-
function writeMihomoConfig(
|
|
4869
|
+
function writeMihomoConfig(content) {
|
|
4891
4870
|
ensureDirs();
|
|
4892
|
-
const content = dumpYaml(configObj);
|
|
4893
4871
|
atomicWriteFileSync(PATHS.configFile, content, { mode: 384 });
|
|
4894
4872
|
}
|
|
4895
4873
|
var HINT_INDENT = " ";
|
|
@@ -5086,13 +5064,7 @@ function formatRelativeTime(dateOrIso, nowMs = Date.now()) {
|
|
|
5086
5064
|
// src/launchctl.ts
|
|
5087
5065
|
import { spawnSync as spawnSync2 } from "child_process";
|
|
5088
5066
|
import fs5 from "fs";
|
|
5089
|
-
|
|
5090
|
-
// src/utils.ts
|
|
5091
|
-
function sleep(ms) {
|
|
5092
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
5093
|
-
}
|
|
5094
|
-
|
|
5095
|
-
// src/launchctl.ts
|
|
5067
|
+
import { setTimeout as sleep } from "timers/promises";
|
|
5096
5068
|
var LAUNCHCTL_TIMEOUT_MS = 5e3;
|
|
5097
5069
|
var SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS = 3e3;
|
|
5098
5070
|
function serviceTarget() {
|
|
@@ -5224,6 +5196,58 @@ async function waitUntilUnloaded(target = serviceTarget(), options = {}) {
|
|
|
5224
5196
|
});
|
|
5225
5197
|
}
|
|
5226
5198
|
|
|
5199
|
+
// src/sudo.ts
|
|
5200
|
+
import { spawnSync as spawnSync3 } from "child_process";
|
|
5201
|
+
import fs6 from "fs";
|
|
5202
|
+
import path5 from "path";
|
|
5203
|
+
var SUDO_TIMEOUT_MS = 6e4;
|
|
5204
|
+
function isRoot() {
|
|
5205
|
+
return process.getuid?.() === 0 || process.geteuid?.() === 0;
|
|
5206
|
+
}
|
|
5207
|
+
var SudoAuthError = class extends Error {
|
|
5208
|
+
constructor() {
|
|
5209
|
+
super("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
|
|
5210
|
+
this.name = "SudoAuthError";
|
|
5211
|
+
}
|
|
5212
|
+
};
|
|
5213
|
+
function describeSudoFailure(e) {
|
|
5214
|
+
return e instanceof SudoAuthError ? "sudo \u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF" : e.message;
|
|
5215
|
+
}
|
|
5216
|
+
function sudoResultToError(action, result, codeMessages) {
|
|
5217
|
+
if (result.error) {
|
|
5218
|
+
if (result.error.code === "ETIMEDOUT") return sudoTimeoutError(action);
|
|
5219
|
+
return result.error;
|
|
5220
|
+
}
|
|
5221
|
+
const { status } = result;
|
|
5222
|
+
if (status === 0) return null;
|
|
5223
|
+
if (status === 1) return new SudoAuthError();
|
|
5224
|
+
if (status === null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
|
|
5225
|
+
const custom = codeMessages?.[status];
|
|
5226
|
+
return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
|
|
5227
|
+
}
|
|
5228
|
+
function sudoTimeoutError(action) {
|
|
5229
|
+
return new Error(`${action}\u8D85\u65F6\uFF08${SUDO_TIMEOUT_MS / 1e3}s \u672A\u5B8C\u6210\uFF09\uFF1A\u5BC6\u7801\u8F93\u5165\u6216\u811A\u672C\u6267\u884C\u8D85\u8FC7\u65F6\u9650\uFF0C\u64CD\u4F5C\u53EF\u80FD\u53EA\u5B8C\u6210\u4E86\u4E00\u90E8\u5206\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u8BD5`);
|
|
5230
|
+
}
|
|
5231
|
+
function runSudoScript(scriptBody, opts) {
|
|
5232
|
+
if (!process.stdin.isTTY) {
|
|
5233
|
+
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");
|
|
5234
|
+
}
|
|
5235
|
+
ensureDirs();
|
|
5236
|
+
const scriptPath = path5.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
|
|
5237
|
+
fs6.writeFileSync(scriptPath, scriptBody, { mode: 448 });
|
|
5238
|
+
fs6.chmodSync(scriptPath, 448);
|
|
5239
|
+
try {
|
|
5240
|
+
const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
5241
|
+
const error = sudoResultToError(opts.action, result, opts.codeMessages);
|
|
5242
|
+
if (error) throw error;
|
|
5243
|
+
} finally {
|
|
5244
|
+
try {
|
|
5245
|
+
fs6.unlinkSync(scriptPath);
|
|
5246
|
+
} catch {
|
|
5247
|
+
}
|
|
5248
|
+
}
|
|
5249
|
+
}
|
|
5250
|
+
|
|
5227
5251
|
// src/suggest.ts
|
|
5228
5252
|
function levenshtein(a, b) {
|
|
5229
5253
|
if (a === b) return 0;
|
|
@@ -5293,8 +5317,15 @@ var GROUP_TITLES = [
|
|
|
5293
5317
|
["system", "\u7CFB\u7EDF:"]
|
|
5294
5318
|
];
|
|
5295
5319
|
function printHelp(commands) {
|
|
5296
|
-
const lines = [
|
|
5297
|
-
|
|
5320
|
+
const lines = [
|
|
5321
|
+
`
|
|
5322
|
+
${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`,
|
|
5323
|
+
"",
|
|
5324
|
+
`\u547D\u4EE4\u522B\u540D: ${CLI_ALIASES.join(", ")}`,
|
|
5325
|
+
"",
|
|
5326
|
+
"\u7528\u6CD5:",
|
|
5327
|
+
" mihomo-cli <\u547D\u4EE4> [\u9009\u9879]"
|
|
5328
|
+
];
|
|
5298
5329
|
const allUsage = commands.flatMap((c) => c.usage);
|
|
5299
5330
|
const signatureWidth = Math.max(...allUsage.map((u) => displayWidth(u.signature)));
|
|
5300
5331
|
const formatUsage = (u) => ` ${colors.bold(padEndDisplay(u.signature, signatureWidth))} ${u.description}`;
|
|
@@ -5371,9 +5402,9 @@ function printHelpEntry(args, commands, finder) {
|
|
|
5371
5402
|
printCommandHelp(command);
|
|
5372
5403
|
}
|
|
5373
5404
|
function printVersion() {
|
|
5374
|
-
const kv = getKernelVersion() || "\u672A\u5B89\u88C5";
|
|
5375
5405
|
console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
|
|
5376
|
-
|
|
5406
|
+
if (isRoot()) return;
|
|
5407
|
+
console.log(`${colors.gray("\u5185\u6838: ")}${getKernelVersion() || "\u672A\u5B89\u88C5"}`);
|
|
5377
5408
|
console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
|
|
5378
5409
|
}
|
|
5379
5410
|
|
|
@@ -5415,238 +5446,8 @@ function redactConfigSecrets(config) {
|
|
|
5415
5446
|
return { config: walk(config, false, state), changed: state.changed };
|
|
5416
5447
|
}
|
|
5417
5448
|
|
|
5418
|
-
// src/diagnostic-events.ts
|
|
5419
|
-
import { createHash, randomUUID } from "crypto";
|
|
5420
|
-
import fs7 from "fs";
|
|
5421
|
-
|
|
5422
|
-
// src/log-files.ts
|
|
5423
|
-
import fs6 from "fs";
|
|
5424
|
-
import path5 from "path";
|
|
5425
|
-
var DEFAULT_LOG_RETENTION_DAYS = 7;
|
|
5426
|
-
var LOG_TAIL_LINES = 15;
|
|
5427
|
-
var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
|
|
5428
|
-
function isArchiveLogFilename(filename) {
|
|
5429
|
-
return ARCHIVE_LOG_RE.test(filename);
|
|
5430
|
-
}
|
|
5431
|
-
function rotateAndCleanupLogs() {
|
|
5432
|
-
rotateLog();
|
|
5433
|
-
cleanupOldLogs();
|
|
5434
|
-
}
|
|
5435
|
-
function readLogTail() {
|
|
5436
|
-
const TAIL_BYTES = 64 * 1024;
|
|
5437
|
-
let fd = null;
|
|
5438
|
-
try {
|
|
5439
|
-
const size = fs6.statSync(PATHS.logFile).size;
|
|
5440
|
-
if (size === 0) return [];
|
|
5441
|
-
const start = Math.max(0, size - TAIL_BYTES);
|
|
5442
|
-
const length = size - start;
|
|
5443
|
-
const buf = Buffer.alloc(length);
|
|
5444
|
-
fd = fs6.openSync(PATHS.logFile, "r");
|
|
5445
|
-
const bytesRead = fs6.readSync(fd, buf, 0, length, start);
|
|
5446
|
-
return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
|
|
5447
|
-
} catch {
|
|
5448
|
-
return [];
|
|
5449
|
-
} finally {
|
|
5450
|
-
if (fd !== null) {
|
|
5451
|
-
try {
|
|
5452
|
-
fs6.closeSync(fd);
|
|
5453
|
-
} catch {
|
|
5454
|
-
}
|
|
5455
|
-
}
|
|
5456
|
-
}
|
|
5457
|
-
}
|
|
5458
|
-
var MAX_ARCHIVE_SEQ = 1e3;
|
|
5459
|
-
function allocateArchivePath(prefix = "mihomo", extension = "log") {
|
|
5460
|
-
const timestamp = formatLocalTimestamp();
|
|
5461
|
-
for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
|
|
5462
|
-
const name = seq === 0 ? `${prefix}.${timestamp}.${extension}` : `${prefix}.${timestamp}.${seq}.${extension}`;
|
|
5463
|
-
const archivePath = path5.join(DIRS.logs, name);
|
|
5464
|
-
let fd = null;
|
|
5465
|
-
try {
|
|
5466
|
-
fd = fs6.openSync(archivePath, "wx");
|
|
5467
|
-
} catch (e) {
|
|
5468
|
-
if (e.code === "EEXIST") continue;
|
|
5469
|
-
throw e;
|
|
5470
|
-
}
|
|
5471
|
-
try {
|
|
5472
|
-
fs6.closeSync(fd);
|
|
5473
|
-
} catch {
|
|
5474
|
-
}
|
|
5475
|
-
return archivePath;
|
|
5476
|
-
}
|
|
5477
|
-
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`, {
|
|
5478
|
-
label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
|
|
5479
|
-
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`]
|
|
5480
|
-
});
|
|
5481
|
-
}
|
|
5482
|
-
function rotateFile(filePath, minBytes, prefix = "mihomo", extension = "log") {
|
|
5483
|
-
let stat;
|
|
5484
|
-
try {
|
|
5485
|
-
stat = fs6.statSync(filePath);
|
|
5486
|
-
} catch (e) {
|
|
5487
|
-
if (e.code === "ENOENT") return false;
|
|
5488
|
-
throw e;
|
|
5489
|
-
}
|
|
5490
|
-
if (stat.size < minBytes) return false;
|
|
5491
|
-
const rotatedPath = allocateArchivePath(prefix, extension);
|
|
5492
|
-
try {
|
|
5493
|
-
fs6.renameSync(filePath, rotatedPath);
|
|
5494
|
-
return true;
|
|
5495
|
-
} catch (e) {
|
|
5496
|
-
try {
|
|
5497
|
-
fs6.unlinkSync(rotatedPath);
|
|
5498
|
-
} catch {
|
|
5499
|
-
}
|
|
5500
|
-
if (e.code === "ENOENT") return false;
|
|
5501
|
-
throw e;
|
|
5502
|
-
}
|
|
5503
|
-
}
|
|
5504
|
-
function rotateLog() {
|
|
5505
|
-
rotateFile(PATHS.logFile, 1);
|
|
5506
|
-
}
|
|
5507
|
-
function cleanupOldArchives(isArchive) {
|
|
5508
|
-
const logsDir = DIRS.logs;
|
|
5509
|
-
if (!fs6.existsSync(logsDir)) return;
|
|
5510
|
-
const files = fs6.readdirSync(logsDir);
|
|
5511
|
-
const now = Date.now();
|
|
5512
|
-
const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
|
|
5513
|
-
for (const file of files) {
|
|
5514
|
-
if (!isArchive(file)) continue;
|
|
5515
|
-
try {
|
|
5516
|
-
const filePath = path5.join(logsDir, file);
|
|
5517
|
-
const stat = fs6.statSync(filePath);
|
|
5518
|
-
if (now - stat.mtimeMs > maxAgeMs) {
|
|
5519
|
-
fs6.unlinkSync(filePath);
|
|
5520
|
-
}
|
|
5521
|
-
} catch {
|
|
5522
|
-
}
|
|
5523
|
-
}
|
|
5524
|
-
}
|
|
5525
|
-
function cleanupOldLogs() {
|
|
5526
|
-
cleanupOldArchives(isArchiveLogFilename);
|
|
5527
|
-
}
|
|
5528
|
-
function listLogs() {
|
|
5529
|
-
const logsDir = DIRS.logs;
|
|
5530
|
-
const result = { current: null, archives: [] };
|
|
5531
|
-
if (fs6.existsSync(PATHS.logFile)) {
|
|
5532
|
-
const stat = fs6.statSync(PATHS.logFile);
|
|
5533
|
-
result.current = {
|
|
5534
|
-
name: "mihomo.log (\u5F53\u524D)",
|
|
5535
|
-
path: PATHS.logFile,
|
|
5536
|
-
size: stat.size,
|
|
5537
|
-
mtime: stat.mtime,
|
|
5538
|
-
isCurrent: true
|
|
5539
|
-
};
|
|
5540
|
-
}
|
|
5541
|
-
if (!fs6.existsSync(logsDir)) return result;
|
|
5542
|
-
const files = fs6.readdirSync(logsDir);
|
|
5543
|
-
for (const file of files) {
|
|
5544
|
-
if (!isArchiveLogFilename(file)) continue;
|
|
5545
|
-
try {
|
|
5546
|
-
const filePath = path5.join(logsDir, file);
|
|
5547
|
-
const stat = fs6.statSync(filePath);
|
|
5548
|
-
result.archives.push({
|
|
5549
|
-
name: file,
|
|
5550
|
-
path: filePath,
|
|
5551
|
-
size: stat.size,
|
|
5552
|
-
mtime: stat.mtime,
|
|
5553
|
-
isCurrent: false
|
|
5554
|
-
});
|
|
5555
|
-
} catch {
|
|
5556
|
-
}
|
|
5557
|
-
}
|
|
5558
|
-
result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
|
|
5559
|
-
return result;
|
|
5560
|
-
}
|
|
5561
|
-
|
|
5562
|
-
// src/diagnostic-events.ts
|
|
5563
|
-
var context = null;
|
|
5564
|
-
var exitHookRegistered = false;
|
|
5565
|
-
var DIAGNOSTIC_LOG_MAX_BYTES = 2 * 1024 * 1024;
|
|
5566
|
-
var DIAGNOSTIC_ARCHIVE_RE = /^diagnostic\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(?:\.\d+)?\.jsonl$/;
|
|
5567
|
-
function beginDiagnosticOperation(command) {
|
|
5568
|
-
context = { operationId: randomUUID(), command, startedAt: Date.now() };
|
|
5569
|
-
if (exitHookRegistered) return;
|
|
5570
|
-
exitHookRegistered = true;
|
|
5571
|
-
process.once("exit", (exitCode) => {
|
|
5572
|
-
if (!context) return;
|
|
5573
|
-
recordDiagnosticEvent("cli.command", exitCode === 0 ? "success" : "failure", {
|
|
5574
|
-
exitCode,
|
|
5575
|
-
durationMs: Date.now() - context.startedAt
|
|
5576
|
-
});
|
|
5577
|
-
});
|
|
5578
|
-
}
|
|
5579
|
-
function setDiagnosticCommand(command) {
|
|
5580
|
-
if (context) context.command = command;
|
|
5581
|
-
}
|
|
5582
|
-
function hashDiagnosticContent(content) {
|
|
5583
|
-
return createHash("sha256").update(content, "utf8").digest("hex");
|
|
5584
|
-
}
|
|
5585
|
-
function hashDiagnosticFile(filePath) {
|
|
5586
|
-
try {
|
|
5587
|
-
return hashDiagnosticContent(fs7.readFileSync(filePath, "utf8"));
|
|
5588
|
-
} catch {
|
|
5589
|
-
return null;
|
|
5590
|
-
}
|
|
5591
|
-
}
|
|
5592
|
-
var KNOWN_ERROR_NAMES = /* @__PURE__ */ new Set(["Error", "TypeError", "RangeError", "SyntaxError", "CliError", "AbortError", "TimeoutError", "SudoAuthError"]);
|
|
5593
|
-
function safeErrorCode(value) {
|
|
5594
|
-
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
5595
|
-
if (typeof value === "string" && /^[A-Z][A-Z0-9_]{1,63}$/.test(value)) return value;
|
|
5596
|
-
return void 0;
|
|
5597
|
-
}
|
|
5598
|
-
function safeHttpStatus(value) {
|
|
5599
|
-
return typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599 ? value : void 0;
|
|
5600
|
-
}
|
|
5601
|
-
function diagnosticErrorDetails(error) {
|
|
5602
|
-
if (!(error instanceof Error)) return { errorType: "NonError" };
|
|
5603
|
-
const details = {};
|
|
5604
|
-
let current = error;
|
|
5605
|
-
for (let depth = 0; depth < 6 && current instanceof Error; depth++) {
|
|
5606
|
-
details.errorType = KNOWN_ERROR_NAMES.has(current.name) ? current.name : "Error";
|
|
5607
|
-
if (current instanceof CliError) details.errorLabel = current.label;
|
|
5608
|
-
if (current.name === "AbortError") details.aborted = true;
|
|
5609
|
-
const withMetadata = current;
|
|
5610
|
-
const errorCode = safeErrorCode(withMetadata.code);
|
|
5611
|
-
const httpStatus = safeHttpStatus(withMetadata.response?.status);
|
|
5612
|
-
if (details.errorCode === void 0 && errorCode !== void 0) details.errorCode = errorCode;
|
|
5613
|
-
if (details.httpStatus === void 0 && httpStatus !== void 0) details.httpStatus = httpStatus;
|
|
5614
|
-
current = withMetadata.cause;
|
|
5615
|
-
}
|
|
5616
|
-
return details;
|
|
5617
|
-
}
|
|
5618
|
-
function rotateDiagnosticLogIfNeeded() {
|
|
5619
|
-
if (rotateFile(PATHS.diagnosticEventsFile, DIAGNOSTIC_LOG_MAX_BYTES, "diagnostic", "jsonl")) {
|
|
5620
|
-
cleanupOldArchives((file) => DIAGNOSTIC_ARCHIVE_RE.test(file));
|
|
5621
|
-
}
|
|
5622
|
-
}
|
|
5623
|
-
function recordDiagnosticEvent(event, result, details = {}) {
|
|
5624
|
-
if (!context) return;
|
|
5625
|
-
try {
|
|
5626
|
-
const line = `${JSON.stringify({
|
|
5627
|
-
v: 1,
|
|
5628
|
-
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5629
|
-
event,
|
|
5630
|
-
result,
|
|
5631
|
-
operationId: context.operationId,
|
|
5632
|
-
command: context.command,
|
|
5633
|
-
pid: process.pid,
|
|
5634
|
-
...details
|
|
5635
|
-
})}
|
|
5636
|
-
`;
|
|
5637
|
-
rotateDiagnosticLogIfNeeded();
|
|
5638
|
-
try {
|
|
5639
|
-
fs7.appendFileSync(PATHS.diagnosticEventsFile, line, { encoding: "utf8", mode: 384 });
|
|
5640
|
-
} catch (e) {
|
|
5641
|
-
if (e.code !== "ENOENT") throw e;
|
|
5642
|
-
fs7.mkdirSync(DIRS.logs, { recursive: true, mode: 448 });
|
|
5643
|
-
fs7.appendFileSync(PATHS.diagnosticEventsFile, line, { encoding: "utf8", mode: 384 });
|
|
5644
|
-
}
|
|
5645
|
-
} catch {
|
|
5646
|
-
}
|
|
5647
|
-
}
|
|
5648
|
-
|
|
5649
5449
|
// src/http.ts
|
|
5450
|
+
import { StringDecoder } from "string_decoder";
|
|
5650
5451
|
var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
|
|
5651
5452
|
var MAX_REDIRECTS = 20;
|
|
5652
5453
|
var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
|
|
@@ -5724,7 +5525,8 @@ function createHttpClient(options = {}) {
|
|
|
5724
5525
|
async function readBodyWithLimit(response, controller, limit) {
|
|
5725
5526
|
if (!response.body) return response.text();
|
|
5726
5527
|
const reader = response.body.getReader();
|
|
5727
|
-
const
|
|
5528
|
+
const decoder = new StringDecoder("utf8");
|
|
5529
|
+
let text = "";
|
|
5728
5530
|
let total = 0;
|
|
5729
5531
|
try {
|
|
5730
5532
|
while (true) {
|
|
@@ -5736,13 +5538,13 @@ async function readBodyWithLimit(response, controller, limit) {
|
|
|
5736
5538
|
controller.abort();
|
|
5737
5539
|
throw new Error(`\u54CD\u5E94\u4F53\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650\uFF08${formatBytes(limit)}\uFF09`);
|
|
5738
5540
|
}
|
|
5739
|
-
|
|
5541
|
+
text += decoder.write(value);
|
|
5740
5542
|
}
|
|
5741
5543
|
}
|
|
5742
5544
|
} finally {
|
|
5743
5545
|
reader.releaseLock();
|
|
5744
5546
|
}
|
|
5745
|
-
return
|
|
5547
|
+
return text + decoder.end();
|
|
5746
5548
|
}
|
|
5747
5549
|
|
|
5748
5550
|
// src/spinner.ts
|
|
@@ -5922,176 +5724,75 @@ function assertLooksLikeSubscription(parsed, maskedUrl) {
|
|
|
5922
5724
|
});
|
|
5923
5725
|
}
|
|
5924
5726
|
async function downloadSubscription(url, subName, signal) {
|
|
5925
|
-
|
|
5926
|
-
let stage = "http";
|
|
5927
|
-
let rollback;
|
|
5727
|
+
let response;
|
|
5928
5728
|
try {
|
|
5929
|
-
|
|
5729
|
+
response = await HTTP_CLIENT.get(url, { signal });
|
|
5730
|
+
} catch (e) {
|
|
5731
|
+
throw new Error(`\u83B7\u53D6\u8BA2\u9605\u5931\u8D25: ${errorMessage(e)}
|
|
5732
|
+
URL: ${maskUrl(url)}`);
|
|
5733
|
+
}
|
|
5734
|
+
const content = response.data;
|
|
5735
|
+
if (!content?.trim()) {
|
|
5736
|
+
throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
|
|
5737
|
+
}
|
|
5738
|
+
const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
|
|
5739
|
+
assertLooksLikeSubscription(parsed, maskUrl(url));
|
|
5740
|
+
const { proxies, proxyGroups } = countConfigNodes(parsed);
|
|
5741
|
+
const meta = extractSubscriptionMeta(response.headers);
|
|
5742
|
+
withFileLock(PATHS.subscriptionCommitLock, () => {
|
|
5743
|
+
const previousContent = readSubscriptionRawConfig(subName);
|
|
5744
|
+
saveSubscriptionRawConfig(subName, content);
|
|
5930
5745
|
try {
|
|
5931
|
-
|
|
5746
|
+
saveSubscriptionMeta(subName, meta);
|
|
5932
5747
|
} catch (e) {
|
|
5933
|
-
|
|
5934
|
-
let errorMsg = `\u83B7\u53D6\u8BA2\u9605\u5931\u8D25: ${e.message}`;
|
|
5935
|
-
const err = e;
|
|
5936
|
-
if (err.response) {
|
|
5937
|
-
errorMsg += ` (HTTP ${err.response.status})`;
|
|
5938
|
-
}
|
|
5939
|
-
errorMsg += `
|
|
5940
|
-
URL: ${maskedUrl}`;
|
|
5941
|
-
throw new Error(errorMsg, { cause: e });
|
|
5942
|
-
}
|
|
5943
|
-
stage = "empty-response";
|
|
5944
|
-
const content = response.data;
|
|
5945
|
-
if (!content?.trim()) {
|
|
5946
|
-
throw new Error("\u8BA2\u9605\u5185\u5BB9\u4E3A\u7A7A");
|
|
5947
|
-
}
|
|
5948
|
-
stage = "parse";
|
|
5949
|
-
const parsed = parseConfigContent(content, "\u8BA2\u9605\u5185\u5BB9");
|
|
5950
|
-
stage = "content-validation";
|
|
5951
|
-
assertLooksLikeSubscription(parsed, maskUrl(url));
|
|
5952
|
-
const { proxies, proxyGroups } = countConfigNodes(parsed);
|
|
5953
|
-
const rawAfterSha256 = hashDiagnosticContent(content);
|
|
5954
|
-
const meta = extractSubscriptionMeta(response.headers);
|
|
5955
|
-
stage = "raw-commit";
|
|
5956
|
-
const previousContent = withFileLock(PATHS.subscriptionCommitLock, () => {
|
|
5957
|
-
const previousContent2 = readSubscriptionRawConfig(subName);
|
|
5958
|
-
saveSubscriptionRawConfig(subName, content);
|
|
5959
|
-
stage = "cache-commit";
|
|
5748
|
+
let rollbackHint;
|
|
5960
5749
|
try {
|
|
5961
|
-
|
|
5962
|
-
|
|
5963
|
-
|
|
5964
|
-
|
|
5965
|
-
|
|
5966
|
-
|
|
5967
|
-
rollback = "deleted";
|
|
5968
|
-
rollbackHint = "\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664";
|
|
5969
|
-
} else {
|
|
5970
|
-
saveSubscriptionRawConfig(subName, previousContent2);
|
|
5971
|
-
rollback = "restored";
|
|
5972
|
-
rollbackHint = "\u8BA2\u9605\u6587\u4EF6\u5DF2\u6062\u590D\u4E3A\u66F4\u65B0\u524D\u5185\u5BB9";
|
|
5973
|
-
}
|
|
5974
|
-
} catch (rollbackError) {
|
|
5975
|
-
rollback = "failed";
|
|
5976
|
-
rollbackHint = `\u8BA2\u9605\u6587\u4EF6\u56DE\u6EDA\u5931\u8D25\uFF08${rollbackError.message}\uFF09\uFF0C\u5F53\u524D\u5185\u5BB9\u672A\u786E\u8BA4\uFF0C\u8BF7\u624B\u5DE5\u68C0\u67E5`;
|
|
5750
|
+
if (previousContent === null) {
|
|
5751
|
+
removeSubscriptionRawConfig(subName);
|
|
5752
|
+
rollbackHint = "\u8BA2\u9605\u6587\u4EF6\u5DF2\u968F\u5931\u8D25\u56DE\u6EDA\u5220\u9664";
|
|
5753
|
+
} else {
|
|
5754
|
+
saveSubscriptionRawConfig(subName, previousContent);
|
|
5755
|
+
rollbackHint = "\u8BA2\u9605\u6587\u4EF6\u5DF2\u6062\u590D\u4E3A\u66F4\u65B0\u524D\u5185\u5BB9";
|
|
5977
5756
|
}
|
|
5978
|
-
|
|
5979
|
-
|
|
5980
|
-
// 不给命令级指引:add 与 update 两个消费方都会走到这里,而 add 失败后条目已
|
|
5981
|
-
// 回滚删除,照「sub update」执行只会得到「没有订阅」——hint 只陈述已做的事
|
|
5982
|
-
hint: [rollbackHint, "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
|
|
5983
|
-
});
|
|
5757
|
+
} catch (rollbackError) {
|
|
5758
|
+
rollbackHint = `\u8BA2\u9605\u6587\u4EF6\u56DE\u6EDA\u5931\u8D25\uFF08${rollbackError.message}\uFF09\uFF0C\u5F53\u524D\u5185\u5BB9\u672A\u786E\u8BA4\uFF0C\u8BF7\u624B\u5DE5\u68C0\u67E5`;
|
|
5984
5759
|
}
|
|
5985
|
-
|
|
5986
|
-
|
|
5987
|
-
|
|
5988
|
-
|
|
5989
|
-
|
|
5990
|
-
|
|
5991
|
-
|
|
5992
|
-
|
|
5993
|
-
|
|
5994
|
-
changed,
|
|
5995
|
-
proxies,
|
|
5996
|
-
proxyGroups
|
|
5997
|
-
});
|
|
5998
|
-
return { proxies, proxyGroups };
|
|
5999
|
-
} catch (e) {
|
|
6000
|
-
recordDiagnosticEvent("subscription.download", signal?.aborted === true ? "aborted" : "failure", {
|
|
6001
|
-
stage,
|
|
6002
|
-
durationMs: Date.now() - startedAt,
|
|
6003
|
-
rollback,
|
|
6004
|
-
...diagnosticErrorDetails(e)
|
|
6005
|
-
});
|
|
6006
|
-
throw e;
|
|
6007
|
-
}
|
|
5760
|
+
throw new CliError(`\u8BA2\u9605\u7F13\u5B58\u5199\u5165\u5931\u8D25: ${e.message}`, {
|
|
5761
|
+
label: "\u66F4\u65B0\u5931\u8D25",
|
|
5762
|
+
// 不给命令级指引:add 与 update 两个消费方都会走到这里,而 add 失败后条目已
|
|
5763
|
+
// 回滚删除,照「sub update」执行只会得到「没有订阅」——hint 只陈述已做的事
|
|
5764
|
+
hint: [rollbackHint, "\u82E5 cache.json \u88AB\u624B\u5DE5\u6539\u52A8\uFF0C\u4FEE\u590D\u540E\u91CD\u8BD5"]
|
|
5765
|
+
});
|
|
5766
|
+
}
|
|
5767
|
+
});
|
|
5768
|
+
return { proxies, proxyGroups };
|
|
6008
5769
|
}
|
|
6009
|
-
async function prepareConfigForStart(mode, subName
|
|
6010
|
-
|
|
6011
|
-
let stage = "read";
|
|
6012
|
-
let sourceRawSha256;
|
|
6013
|
-
let candidateSha256;
|
|
5770
|
+
async function prepareConfigForStart(mode, subName) {
|
|
5771
|
+
let rawContent;
|
|
6014
5772
|
try {
|
|
6015
|
-
|
|
6016
|
-
try {
|
|
6017
|
-
rawContent = requireSubscriptionRawConfig(subName);
|
|
6018
|
-
} catch (e) {
|
|
6019
|
-
if (e instanceof CliError && !getSubscriptions().some((s) => s.name === subName)) {
|
|
6020
|
-
throw new CliError(`\u8BA2\u9605 "${subName}" \u5DF2\u5728\u542F\u52A8\u8FC7\u7A0B\u4E2D\u88AB\u79FB\u9664\uFF08\u53EF\u80FD\u53E6\u4E00\u7EC8\u7AEF\u6267\u884C\u4E86 sub remove/reset\uFF09`, {
|
|
6021
|
-
hint: ["\u67E5\u770B\u5F53\u524D\u5217\u8868: mihomo-cli sub", "\u786E\u8BA4\u540E\u91CD\u8BD5: mihomo-cli start"]
|
|
6022
|
-
});
|
|
6023
|
-
}
|
|
6024
|
-
throw e;
|
|
6025
|
-
}
|
|
6026
|
-
sourceRawSha256 = hashDiagnosticContent(rawContent);
|
|
6027
|
-
stage = "build";
|
|
6028
|
-
const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
|
|
6029
|
-
const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
|
|
6030
|
-
const candidateContent = dumpYaml(buildResult.config);
|
|
6031
|
-
candidateSha256 = hashDiagnosticContent(candidateContent);
|
|
6032
|
-
stage = "validate";
|
|
6033
|
-
await validateConfigWithKernel(candidateContent, buildResult.overwriteSummaries);
|
|
6034
|
-
const info = countConfigNodes(buildResult.config);
|
|
6035
|
-
recordDiagnosticEvent("config.prepare", "success", {
|
|
6036
|
-
stage,
|
|
6037
|
-
purpose,
|
|
6038
|
-
mode,
|
|
6039
|
-
durationMs: Date.now() - startedAt,
|
|
6040
|
-
sourceRawSha256,
|
|
6041
|
-
candidateSha256,
|
|
6042
|
-
...info
|
|
6043
|
-
});
|
|
6044
|
-
return {
|
|
6045
|
-
buildResult,
|
|
6046
|
-
info,
|
|
6047
|
-
diagnostic: { sourceRawSha256, candidateSha256 }
|
|
6048
|
-
};
|
|
5773
|
+
rawContent = requireSubscriptionRawConfig(subName);
|
|
6049
5774
|
} catch (e) {
|
|
6050
|
-
|
|
6051
|
-
|
|
6052
|
-
|
|
6053
|
-
|
|
6054
|
-
|
|
6055
|
-
sourceRawSha256,
|
|
6056
|
-
candidateSha256,
|
|
6057
|
-
...diagnosticErrorDetails(e)
|
|
6058
|
-
});
|
|
5775
|
+
if (e instanceof CliError && !getSubscriptions().some((s) => s.name === subName)) {
|
|
5776
|
+
throw new CliError(`\u8BA2\u9605 "${subName}" \u5DF2\u5728\u542F\u52A8\u8FC7\u7A0B\u4E2D\u88AB\u79FB\u9664\uFF08\u53EF\u80FD\u53E6\u4E00\u7EC8\u7AEF\u6267\u884C\u4E86 sub remove/reset\uFF09`, {
|
|
5777
|
+
hint: ["\u67E5\u770B\u5F53\u524D\u5217\u8868: mihomo-cli sub", "\u786E\u8BA4\u540E\u91CD\u8BD5: mihomo-cli start"]
|
|
5778
|
+
});
|
|
5779
|
+
}
|
|
6059
5780
|
throw e;
|
|
6060
5781
|
}
|
|
5782
|
+
const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
|
|
5783
|
+
const { config, warnings, overwriteSummaries } = buildConfig(rawContent, mode, { subName, subUrl });
|
|
5784
|
+
const candidateContent = dumpYaml(config);
|
|
5785
|
+
await validateConfigWithKernel(candidateContent, overwriteSummaries);
|
|
5786
|
+
return { warnings, candidateContent, info: countConfigNodes(config) };
|
|
6061
5787
|
}
|
|
6062
5788
|
function commitPreparedConfig(prepared) {
|
|
6063
|
-
|
|
6064
|
-
|
|
6065
|
-
if (buildResult.warnings.length > 0) {
|
|
6066
|
-
for (const warning of buildResult.warnings) {
|
|
5789
|
+
if (prepared.warnings.length > 0) {
|
|
5790
|
+
for (const warning of prepared.warnings) {
|
|
6067
5791
|
console.log(`${colors.yellow("\u914D\u7F6E\u63D0\u793A:")} ${warning}`);
|
|
6068
5792
|
}
|
|
6069
5793
|
console.log("");
|
|
6070
5794
|
}
|
|
6071
|
-
|
|
6072
|
-
try {
|
|
6073
|
-
writeMihomoConfig(buildResult.config);
|
|
6074
|
-
} catch (e) {
|
|
6075
|
-
recordDiagnosticEvent("config.commit", "failure", {
|
|
6076
|
-
stage: "write",
|
|
6077
|
-
durationMs: Date.now() - startedAt,
|
|
6078
|
-
sourceRawSha256: prepared.diagnostic.sourceRawSha256,
|
|
6079
|
-
candidateSha256: prepared.diagnostic.candidateSha256,
|
|
6080
|
-
runtimeBeforeSha256,
|
|
6081
|
-
...diagnosticErrorDetails(e)
|
|
6082
|
-
});
|
|
6083
|
-
throw e;
|
|
6084
|
-
}
|
|
6085
|
-
recordDiagnosticEvent("config.commit", "success", {
|
|
6086
|
-
stage: "write",
|
|
6087
|
-
durationMs: Date.now() - startedAt,
|
|
6088
|
-
sourceRawSha256: prepared.diagnostic.sourceRawSha256,
|
|
6089
|
-
candidateSha256: prepared.diagnostic.candidateSha256,
|
|
6090
|
-
runtimeBeforeSha256,
|
|
6091
|
-
runtimeAfterSha256: prepared.diagnostic.candidateSha256,
|
|
6092
|
-
changed: runtimeBeforeSha256 === null ? null : runtimeBeforeSha256 !== prepared.diagnostic.candidateSha256,
|
|
6093
|
-
...prepared.info
|
|
6094
|
-
});
|
|
5795
|
+
writeMihomoConfig(prepared.candidateContent);
|
|
6095
5796
|
return prepared.info;
|
|
6096
5797
|
}
|
|
6097
5798
|
function needsAutoUpdate(sub) {
|
|
@@ -6123,10 +5824,7 @@ function printUpdateResult(r) {
|
|
|
6123
5824
|
async function autoUpdateStaleSubscription(options = {}) {
|
|
6124
5825
|
const allSubs = getSubscriptionsWithCache();
|
|
6125
5826
|
const staleSubs = allSubs.filter(needsAutoUpdate);
|
|
6126
|
-
if (staleSubs.length === 0)
|
|
6127
|
-
recordDiagnosticEvent("subscription.auto-update", "skipped", { reason: "fresh", staleCount: 0 });
|
|
6128
|
-
return;
|
|
6129
|
-
}
|
|
5827
|
+
if (staleSubs.length === 0) return;
|
|
6130
5828
|
if (staleSubs.length === 1) {
|
|
6131
5829
|
const sub = staleSubs[0];
|
|
6132
5830
|
const interval = resolveUpdateInterval(sub.update_interval);
|
|
@@ -6154,24 +5852,7 @@ async function autoUpdateStaleSubscription(options = {}) {
|
|
|
6154
5852
|
});
|
|
6155
5853
|
console.log(colors.yellow(`\u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 (${timeoutMs / 1e3}s)\uFF0C\u5DF2\u5B8C\u6210\u7684\u66F4\u65B0\u751F\u6548\uFF0C\u5176\u4F59\u4F7F\u7528\u7F13\u5B58\u914D\u7F6E`));
|
|
6156
5854
|
}
|
|
6157
|
-
const
|
|
6158
|
-
let succeeded = 0;
|
|
6159
|
-
let abortedCount = 0;
|
|
6160
|
-
let failed = 0;
|
|
6161
|
-
for (const r of results) {
|
|
6162
|
-
printUpdateResult(r);
|
|
6163
|
-
if (r.success) succeeded++;
|
|
6164
|
-
else if (r.aborted === true) abortedCount++;
|
|
6165
|
-
else failed++;
|
|
6166
|
-
}
|
|
6167
|
-
recordDiagnosticEvent("subscription.auto-update", timedOut ? "timeout" : failed > 0 ? "failure" : "success", {
|
|
6168
|
-
staleCount: staleSubs.length,
|
|
6169
|
-
timeoutMs,
|
|
6170
|
-
timedOut,
|
|
6171
|
-
succeeded,
|
|
6172
|
-
failed,
|
|
6173
|
-
abortedCount
|
|
6174
|
-
});
|
|
5855
|
+
for (const r of results) printUpdateResult(r);
|
|
6175
5856
|
}
|
|
6176
5857
|
|
|
6177
5858
|
// src/commands/config.ts
|
|
@@ -6284,15 +5965,150 @@ function viewLogWithTail(logPath, options) {
|
|
|
6284
5965
|
// src/commands/shared.ts
|
|
6285
5966
|
import readline from "readline";
|
|
6286
5967
|
|
|
5968
|
+
// src/runtime.ts
|
|
5969
|
+
import fs12 from "fs";
|
|
5970
|
+
import { setTimeout as sleep4 } from "timers/promises";
|
|
5971
|
+
|
|
5972
|
+
// src/log-files.ts
|
|
5973
|
+
import fs7 from "fs";
|
|
5974
|
+
import path6 from "path";
|
|
5975
|
+
var DEFAULT_LOG_RETENTION_DAYS = 7;
|
|
5976
|
+
var LOG_TAIL_LINES = 15;
|
|
5977
|
+
var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
|
|
5978
|
+
function isArchiveLogFilename(filename) {
|
|
5979
|
+
return ARCHIVE_LOG_RE.test(filename);
|
|
5980
|
+
}
|
|
5981
|
+
function rotateAndCleanupLogs() {
|
|
5982
|
+
rotateLog();
|
|
5983
|
+
cleanupOldLogs();
|
|
5984
|
+
}
|
|
5985
|
+
function readLogTail() {
|
|
5986
|
+
const TAIL_BYTES = 64 * 1024;
|
|
5987
|
+
let fd = null;
|
|
5988
|
+
try {
|
|
5989
|
+
const size = fs7.statSync(PATHS.logFile).size;
|
|
5990
|
+
if (size === 0) return [];
|
|
5991
|
+
const start = Math.max(0, size - TAIL_BYTES);
|
|
5992
|
+
const length = size - start;
|
|
5993
|
+
const buf = Buffer.alloc(length);
|
|
5994
|
+
fd = fs7.openSync(PATHS.logFile, "r");
|
|
5995
|
+
const bytesRead = fs7.readSync(fd, buf, 0, length, start);
|
|
5996
|
+
return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
|
|
5997
|
+
} catch {
|
|
5998
|
+
return [];
|
|
5999
|
+
} finally {
|
|
6000
|
+
if (fd !== null) {
|
|
6001
|
+
try {
|
|
6002
|
+
fs7.closeSync(fd);
|
|
6003
|
+
} catch {
|
|
6004
|
+
}
|
|
6005
|
+
}
|
|
6006
|
+
}
|
|
6007
|
+
}
|
|
6008
|
+
var MAX_ARCHIVE_SEQ = 1e3;
|
|
6009
|
+
function allocateArchivePath() {
|
|
6010
|
+
const timestamp = formatLocalTimestamp();
|
|
6011
|
+
for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
|
|
6012
|
+
const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
|
|
6013
|
+
const archivePath = path6.join(DIRS.logs, name);
|
|
6014
|
+
let fd = null;
|
|
6015
|
+
try {
|
|
6016
|
+
fd = fs7.openSync(archivePath, "wx");
|
|
6017
|
+
} catch (e) {
|
|
6018
|
+
if (e.code === "EEXIST") continue;
|
|
6019
|
+
throw e;
|
|
6020
|
+
}
|
|
6021
|
+
try {
|
|
6022
|
+
fs7.closeSync(fd);
|
|
6023
|
+
} catch {
|
|
6024
|
+
}
|
|
6025
|
+
return archivePath;
|
|
6026
|
+
}
|
|
6027
|
+
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`, {
|
|
6028
|
+
label: "\u65E5\u5FD7\u8F6E\u8F6C\u5931\u8D25",
|
|
6029
|
+
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`]
|
|
6030
|
+
});
|
|
6031
|
+
}
|
|
6032
|
+
function rotateLog() {
|
|
6033
|
+
let stat;
|
|
6034
|
+
try {
|
|
6035
|
+
stat = fs7.statSync(PATHS.logFile);
|
|
6036
|
+
} catch (e) {
|
|
6037
|
+
if (e.code === "ENOENT") return;
|
|
6038
|
+
throw e;
|
|
6039
|
+
}
|
|
6040
|
+
if (stat.size === 0) return;
|
|
6041
|
+
const rotatedPath = allocateArchivePath();
|
|
6042
|
+
try {
|
|
6043
|
+
fs7.renameSync(PATHS.logFile, rotatedPath);
|
|
6044
|
+
} catch (e) {
|
|
6045
|
+
try {
|
|
6046
|
+
fs7.unlinkSync(rotatedPath);
|
|
6047
|
+
} catch {
|
|
6048
|
+
}
|
|
6049
|
+
if (e.code === "ENOENT") return;
|
|
6050
|
+
throw e;
|
|
6051
|
+
}
|
|
6052
|
+
}
|
|
6053
|
+
function cleanupOldLogs() {
|
|
6054
|
+
const logsDir = DIRS.logs;
|
|
6055
|
+
if (!fs7.existsSync(logsDir)) return;
|
|
6056
|
+
const files = fs7.readdirSync(logsDir);
|
|
6057
|
+
const now = Date.now();
|
|
6058
|
+
const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
|
|
6059
|
+
for (const file of files) {
|
|
6060
|
+
if (!isArchiveLogFilename(file)) continue;
|
|
6061
|
+
try {
|
|
6062
|
+
const filePath = path6.join(logsDir, file);
|
|
6063
|
+
const stat = fs7.statSync(filePath);
|
|
6064
|
+
if (now - stat.mtimeMs > maxAgeMs) {
|
|
6065
|
+
fs7.unlinkSync(filePath);
|
|
6066
|
+
}
|
|
6067
|
+
} catch {
|
|
6068
|
+
}
|
|
6069
|
+
}
|
|
6070
|
+
}
|
|
6071
|
+
function listLogs() {
|
|
6072
|
+
const logsDir = DIRS.logs;
|
|
6073
|
+
const result = { current: null, archives: [] };
|
|
6074
|
+
if (fs7.existsSync(PATHS.logFile)) {
|
|
6075
|
+
const stat = fs7.statSync(PATHS.logFile);
|
|
6076
|
+
result.current = {
|
|
6077
|
+
name: path6.basename(PATHS.logFile),
|
|
6078
|
+
path: PATHS.logFile,
|
|
6079
|
+
size: stat.size,
|
|
6080
|
+
mtime: stat.mtime
|
|
6081
|
+
};
|
|
6082
|
+
}
|
|
6083
|
+
if (!fs7.existsSync(logsDir)) return result;
|
|
6084
|
+
const files = fs7.readdirSync(logsDir);
|
|
6085
|
+
for (const file of files) {
|
|
6086
|
+
if (!isArchiveLogFilename(file)) continue;
|
|
6087
|
+
try {
|
|
6088
|
+
const filePath = path6.join(logsDir, file);
|
|
6089
|
+
const stat = fs7.statSync(filePath);
|
|
6090
|
+
result.archives.push({
|
|
6091
|
+
name: file,
|
|
6092
|
+
path: filePath,
|
|
6093
|
+
size: stat.size,
|
|
6094
|
+
mtime: stat.mtime
|
|
6095
|
+
});
|
|
6096
|
+
} catch {
|
|
6097
|
+
}
|
|
6098
|
+
}
|
|
6099
|
+
result.archives.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
|
|
6100
|
+
return result;
|
|
6101
|
+
}
|
|
6102
|
+
|
|
6287
6103
|
// src/process-probe.ts
|
|
6288
|
-
import { spawnSync as
|
|
6104
|
+
import { spawnSync as spawnSync4 } from "child_process";
|
|
6289
6105
|
import fs8 from "fs";
|
|
6290
6106
|
var PS_TIMEOUT_MS = 5e3;
|
|
6291
6107
|
var NOT_RUNNING = { alive: false, uid: null, rss: null, command: "" };
|
|
6292
6108
|
function probeProcess(pid) {
|
|
6293
6109
|
if (!pid) return NOT_RUNNING;
|
|
6294
6110
|
try {
|
|
6295
|
-
const result =
|
|
6111
|
+
const result = spawnSync4("ps", ["-ww", "-p", String(pid), "-o", "pid=,uid=,rss=,command="], {
|
|
6296
6112
|
encoding: "utf8",
|
|
6297
6113
|
timeout: PS_TIMEOUT_MS
|
|
6298
6114
|
});
|
|
@@ -6326,7 +6142,7 @@ function isMihomoProcess(pid) {
|
|
|
6326
6142
|
return isProbedMihomo(probeProcess(pid));
|
|
6327
6143
|
}
|
|
6328
6144
|
function getMihomoPids() {
|
|
6329
|
-
const result =
|
|
6145
|
+
const result = spawnSync4("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
|
|
6330
6146
|
if (result.error || result.status === null) {
|
|
6331
6147
|
throw new CliError("\u65E0\u6CD5\u63A2\u6D4B\u5185\u6838\u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
|
|
6332
6148
|
hint: ["\u8FD9\u4E0D\u4EE3\u8868\u5185\u6838\u672A\u8FD0\u884C\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "\u8BF7\u624B\u52A8\u786E\u8BA4: pgrep -fl mihomo-cli"]
|
|
@@ -6365,190 +6181,15 @@ function getStatus() {
|
|
|
6365
6181
|
};
|
|
6366
6182
|
}
|
|
6367
6183
|
|
|
6368
|
-
// src/process-start.ts
|
|
6369
|
-
import fs14 from "fs";
|
|
6370
|
-
|
|
6371
|
-
// src/service.ts
|
|
6372
|
-
import { spawnSync as spawnSync7 } from "child_process";
|
|
6373
|
-
import fs13 from "fs";
|
|
6374
|
-
import path7 from "path";
|
|
6375
|
-
|
|
6376
|
-
// src/hot-reload.ts
|
|
6377
|
-
import fs9 from "fs";
|
|
6378
|
-
|
|
6379
|
-
// src/proxy-probe.ts
|
|
6380
|
-
import { execFile as execFile2, spawnSync as spawnSync4 } from "child_process";
|
|
6381
|
-
import { promisify as promisify2 } from "util";
|
|
6382
|
-
|
|
6383
|
-
// src/curl-spawn.ts
|
|
6384
|
-
function buildCurlSpawnEnv() {
|
|
6385
|
-
const env = { ...process.env };
|
|
6386
|
-
env.no_proxy = "";
|
|
6387
|
-
env.NO_PROXY = "";
|
|
6388
|
-
return env;
|
|
6389
|
-
}
|
|
6390
|
-
|
|
6391
|
-
// src/proxy-probe.ts
|
|
6392
|
-
var execFileAsync = promisify2(execFile2);
|
|
6393
|
-
function lsofListenPids(port) {
|
|
6394
|
-
try {
|
|
6395
|
-
const r = spawnSync4("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
|
|
6396
|
-
if (r.status !== 0) return null;
|
|
6397
|
-
return parsePidList(r.stdout);
|
|
6398
|
-
} catch {
|
|
6399
|
-
return null;
|
|
6400
|
-
}
|
|
6401
|
-
}
|
|
6402
|
-
var PROBE_URL = "https://www.gstatic.com/generate_204";
|
|
6403
|
-
function isProbeSuccessStatus(code) {
|
|
6404
|
-
return code !== null && code >= 200 && code < 300;
|
|
6405
|
-
}
|
|
6406
|
-
var PROBE_TIMEOUT_MS = 2e3;
|
|
6407
|
-
async function probeProxyConnectivity(port) {
|
|
6408
|
-
const start = Date.now();
|
|
6409
|
-
try {
|
|
6410
|
-
const { stdout } = await execFileAsync(
|
|
6411
|
-
"curl",
|
|
6412
|
-
["-x", `http://127.0.0.1:${port}`, "-sS", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
|
|
6413
|
-
{
|
|
6414
|
-
timeout: PROBE_TIMEOUT_MS + 2e3,
|
|
6415
|
-
// 例外表会绕过显式 -x、让探测考成直连(绿灯作废),置空兜住统一走 curl-spawn.ts 出口
|
|
6416
|
-
env: buildCurlSpawnEnv()
|
|
6417
|
-
}
|
|
6418
|
-
);
|
|
6419
|
-
const code = Number.parseInt(stdout.trim(), 10);
|
|
6420
|
-
const statusCode = Number.isFinite(code) ? code : null;
|
|
6421
|
-
const ok = isProbeSuccessStatus(statusCode);
|
|
6422
|
-
const durationMs = Date.now() - start;
|
|
6423
|
-
recordDiagnosticEvent("proxy.probe", ok ? "success" : "failure", { port, httpStatus: statusCode, durationMs });
|
|
6424
|
-
return {
|
|
6425
|
-
ok,
|
|
6426
|
-
statusCode,
|
|
6427
|
-
error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
|
|
6428
|
-
durationMs
|
|
6429
|
-
};
|
|
6430
|
-
} catch (e) {
|
|
6431
|
-
const err = e;
|
|
6432
|
-
const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
|
|
6433
|
-
const durationMs = Date.now() - start;
|
|
6434
|
-
recordDiagnosticEvent("proxy.probe", "failure", { port, httpStatus: null, durationMs, ...diagnosticErrorDetails(e) });
|
|
6435
|
-
return { ok: false, statusCode: null, error: detail, durationMs };
|
|
6436
|
-
}
|
|
6437
|
-
}
|
|
6438
|
-
|
|
6439
|
-
// src/hot-reload.ts
|
|
6440
|
-
var HOT_RELOAD_TIMEOUT_MS = 5e3;
|
|
6441
|
-
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
6442
|
-
function logOversized() {
|
|
6443
|
-
try {
|
|
6444
|
-
return fs9.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
6445
|
-
} catch {
|
|
6446
|
-
return false;
|
|
6447
|
-
}
|
|
6448
|
-
}
|
|
6449
|
-
async function tryHotReload(prefetched) {
|
|
6450
|
-
const controller = new AbortController();
|
|
6451
|
-
let stage = "status";
|
|
6452
|
-
try {
|
|
6453
|
-
const status = prefetched ?? getServiceStatus({ withDisabled: false });
|
|
6454
|
-
if (!status.running || status.pid === null) return { ok: false, stage, reason: "service-not-running" };
|
|
6455
|
-
stage = "controller";
|
|
6456
|
-
const endpoint = getControllerEndpoint();
|
|
6457
|
-
if (endpoint.port === null) return { ok: false, stage, reason: "controller-unavailable" };
|
|
6458
|
-
const baseUrl = `http://127.0.0.1:${endpoint.port}`;
|
|
6459
|
-
const headers = { "Content-Type": "application/json" };
|
|
6460
|
-
if (endpoint.secret) headers.Authorization = `Bearer ${endpoint.secret}`;
|
|
6461
|
-
const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
|
|
6462
|
-
try {
|
|
6463
|
-
stage = "version";
|
|
6464
|
-
const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
|
|
6465
|
-
if (!probe.ok) return { ok: false, stage, reason: "http-status", httpStatus: probe.status };
|
|
6466
|
-
const info = await probe.json();
|
|
6467
|
-
if (typeof info?.version !== "string") return { ok: false, stage, reason: "invalid-response" };
|
|
6468
|
-
stage = "identity";
|
|
6469
|
-
const listenerPids = lsofListenPids(endpoint.port);
|
|
6470
|
-
if (listenerPids === null) return { ok: false, stage, reason: "listener-unknown" };
|
|
6471
|
-
if (listenerPids[0] !== status.pid) return { ok: false, stage, reason: "owner-mismatch" };
|
|
6472
|
-
stage = "put";
|
|
6473
|
-
const res = await fetch(`${baseUrl}/configs?force=true`, {
|
|
6474
|
-
method: "PUT",
|
|
6475
|
-
headers,
|
|
6476
|
-
body: "{}",
|
|
6477
|
-
signal: controller.signal
|
|
6478
|
-
});
|
|
6479
|
-
if (!res.ok) return { ok: false, stage, reason: "http-status", httpStatus: res.status };
|
|
6480
|
-
return { ok: true };
|
|
6481
|
-
} finally {
|
|
6482
|
-
clearTimeout(timer);
|
|
6483
|
-
}
|
|
6484
|
-
} catch (e) {
|
|
6485
|
-
const aborted = controller.signal.aborted;
|
|
6486
|
-
return {
|
|
6487
|
-
ok: false,
|
|
6488
|
-
stage,
|
|
6489
|
-
reason: aborted ? "timeout" : "exception",
|
|
6490
|
-
errorType: e instanceof Error && e.name === "AbortError" ? "AbortError" : "Error",
|
|
6491
|
-
...aborted ? { aborted: true } : {}
|
|
6492
|
-
};
|
|
6493
|
-
}
|
|
6494
|
-
}
|
|
6495
|
-
|
|
6496
6184
|
// src/process-stop.ts
|
|
6497
|
-
import { spawnSync as spawnSync6 } from "child_process";
|
|
6498
|
-
import fs11 from "fs";
|
|
6499
|
-
|
|
6500
|
-
// src/sudo.ts
|
|
6501
6185
|
import { spawnSync as spawnSync5 } from "child_process";
|
|
6502
|
-
import
|
|
6503
|
-
import
|
|
6504
|
-
var SUDO_TIMEOUT_MS = 6e4;
|
|
6505
|
-
var SudoAuthError = class extends Error {
|
|
6506
|
-
constructor() {
|
|
6507
|
-
super("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
|
|
6508
|
-
this.name = "SudoAuthError";
|
|
6509
|
-
}
|
|
6510
|
-
};
|
|
6511
|
-
function describeSudoFailure(e) {
|
|
6512
|
-
return e instanceof SudoAuthError ? "sudo \u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF" : e.message;
|
|
6513
|
-
}
|
|
6514
|
-
function sudoExitToError(action, status, codeMessages) {
|
|
6515
|
-
if (status === 1) return new SudoAuthError();
|
|
6516
|
-
if (status == null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
|
|
6517
|
-
const custom = codeMessages?.[status];
|
|
6518
|
-
return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
|
|
6519
|
-
}
|
|
6520
|
-
function sudoTimeoutError(action) {
|
|
6521
|
-
return new Error(`${action}\u8D85\u65F6\uFF08${SUDO_TIMEOUT_MS / 1e3}s \u672A\u5B8C\u6210\uFF09\uFF1A\u5BC6\u7801\u8F93\u5165\u6216\u811A\u672C\u6267\u884C\u8D85\u8FC7\u65F6\u9650\uFF0C\u64CD\u4F5C\u53EF\u80FD\u53EA\u5B8C\u6210\u4E86\u4E00\u90E8\u5206\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u8BD5`);
|
|
6522
|
-
}
|
|
6523
|
-
function runSudoScript(scriptBody, opts) {
|
|
6524
|
-
if (!process.stdin.isTTY) {
|
|
6525
|
-
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");
|
|
6526
|
-
}
|
|
6527
|
-
ensureDirs();
|
|
6528
|
-
const scriptPath = path6.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
|
|
6529
|
-
fs10.writeFileSync(scriptPath, scriptBody, { mode: 448 });
|
|
6530
|
-
fs10.chmodSync(scriptPath, 448);
|
|
6531
|
-
try {
|
|
6532
|
-
const result = spawnSync5("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
|
|
6533
|
-
if (result.error) {
|
|
6534
|
-
if (result.error.code === "ETIMEDOUT") throw sudoTimeoutError(opts.action);
|
|
6535
|
-
throw result.error;
|
|
6536
|
-
}
|
|
6537
|
-
if (result.status !== 0) throw sudoExitToError(opts.action, result.status, opts.codeMessages);
|
|
6538
|
-
} finally {
|
|
6539
|
-
try {
|
|
6540
|
-
fs10.unlinkSync(scriptPath);
|
|
6541
|
-
} catch {
|
|
6542
|
-
}
|
|
6543
|
-
}
|
|
6544
|
-
}
|
|
6545
|
-
|
|
6546
|
-
// src/process-stop.ts
|
|
6186
|
+
import fs9 from "fs";
|
|
6187
|
+
import { setTimeout as sleep2 } from "timers/promises";
|
|
6547
6188
|
var PROCESS_WAIT_ATTEMPTS = 50;
|
|
6548
6189
|
var PROCESS_WAIT_INTERVAL = 100;
|
|
6549
6190
|
var BATCH_KILL_THRESHOLD = 3;
|
|
6550
6191
|
function clearRuntime() {
|
|
6551
|
-
if (
|
|
6192
|
+
if (fs9.existsSync(DIRS.runtime)) {
|
|
6552
6193
|
rmrf(DIRS.runtime);
|
|
6553
6194
|
}
|
|
6554
6195
|
ensureDirs();
|
|
@@ -6560,7 +6201,7 @@ function printResidueWarning(remaining) {
|
|
|
6560
6201
|
}
|
|
6561
6202
|
function clearPid() {
|
|
6562
6203
|
try {
|
|
6563
|
-
|
|
6204
|
+
fs9.unlinkSync(PATHS.pidFile);
|
|
6564
6205
|
return null;
|
|
6565
6206
|
} catch (e) {
|
|
6566
6207
|
if (e.code === "ENOENT") return null;
|
|
@@ -6578,7 +6219,7 @@ function pidAlive(pid) {
|
|
|
6578
6219
|
async function waitUntilNoMihomo(pids) {
|
|
6579
6220
|
for (let i = 0; i < PROCESS_WAIT_ATTEMPTS; i++) {
|
|
6580
6221
|
if (!pids.some(pidAlive)) return;
|
|
6581
|
-
await
|
|
6222
|
+
await sleep2(PROCESS_WAIT_INTERVAL);
|
|
6582
6223
|
}
|
|
6583
6224
|
}
|
|
6584
6225
|
function killProcess(pid) {
|
|
@@ -6588,7 +6229,7 @@ function killProcess(pid) {
|
|
|
6588
6229
|
}
|
|
6589
6230
|
}
|
|
6590
6231
|
function killAllMihomo() {
|
|
6591
|
-
|
|
6232
|
+
spawnSync5("pkill", ["-9", "-f", MAIN_INSTANCE_PATTERN], { timeout: 1e4 });
|
|
6592
6233
|
}
|
|
6593
6234
|
function buildKernelCleanupScript() {
|
|
6594
6235
|
return [
|
|
@@ -6674,23 +6315,81 @@ async function stop() {
|
|
|
6674
6315
|
return {};
|
|
6675
6316
|
}
|
|
6676
6317
|
|
|
6318
|
+
// src/service.ts
|
|
6319
|
+
import { spawnSync as spawnSync7 } from "child_process";
|
|
6320
|
+
import fs11 from "fs";
|
|
6321
|
+
import path7 from "path";
|
|
6322
|
+
import { setTimeout as sleep3 } from "timers/promises";
|
|
6323
|
+
|
|
6324
|
+
// src/proxy-probe.ts
|
|
6325
|
+
import { execFile as execFile2, spawnSync as spawnSync6 } from "child_process";
|
|
6326
|
+
import { promisify as promisify2 } from "util";
|
|
6327
|
+
|
|
6328
|
+
// src/curl-spawn.ts
|
|
6329
|
+
function buildCurlSpawnEnv() {
|
|
6330
|
+
const env = { ...process.env };
|
|
6331
|
+
env.no_proxy = "";
|
|
6332
|
+
env.NO_PROXY = "";
|
|
6333
|
+
return env;
|
|
6334
|
+
}
|
|
6335
|
+
|
|
6336
|
+
// src/proxy-probe.ts
|
|
6337
|
+
var execFileAsync = promisify2(execFile2);
|
|
6338
|
+
function lsofListenPids(port) {
|
|
6339
|
+
try {
|
|
6340
|
+
const r = spawnSync6("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
|
|
6341
|
+
if (r.status !== 0) return null;
|
|
6342
|
+
return parsePidList(r.stdout);
|
|
6343
|
+
} catch {
|
|
6344
|
+
return null;
|
|
6345
|
+
}
|
|
6346
|
+
}
|
|
6347
|
+
var PROBE_URL = "https://www.gstatic.com/generate_204";
|
|
6348
|
+
function isProbeSuccessStatus(code) {
|
|
6349
|
+
return code !== null && code >= 200 && code < 300;
|
|
6350
|
+
}
|
|
6351
|
+
var PROBE_TIMEOUT_MS = 2e3;
|
|
6352
|
+
async function probeProxyConnectivity(port) {
|
|
6353
|
+
const start = Date.now();
|
|
6354
|
+
try {
|
|
6355
|
+
const { stdout } = await execFileAsync(
|
|
6356
|
+
"curl",
|
|
6357
|
+
["-x", `http://127.0.0.1:${port}`, "-sS", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
|
|
6358
|
+
{
|
|
6359
|
+
timeout: PROBE_TIMEOUT_MS + 2e3,
|
|
6360
|
+
// 例外表会绕过显式 -x、让探测考成直连(绿灯作废),置空兜住统一走 curl-spawn.ts 出口
|
|
6361
|
+
env: buildCurlSpawnEnv()
|
|
6362
|
+
}
|
|
6363
|
+
);
|
|
6364
|
+
const code = Number.parseInt(stdout.trim(), 10);
|
|
6365
|
+
const statusCode = Number.isFinite(code) ? code : null;
|
|
6366
|
+
const ok = isProbeSuccessStatus(statusCode);
|
|
6367
|
+
return {
|
|
6368
|
+
ok,
|
|
6369
|
+
statusCode,
|
|
6370
|
+
error: ok ? null : `HTTP ${statusCode ?? "\u65E0\u54CD\u5E94"}`,
|
|
6371
|
+
durationMs: Date.now() - start
|
|
6372
|
+
};
|
|
6373
|
+
} catch (e) {
|
|
6374
|
+
const err = e;
|
|
6375
|
+
const detail = lastCurlErrorLine(err.stderr) ?? err.message ?? "\u8BF7\u6C42\u5931\u8D25";
|
|
6376
|
+
return { ok: false, statusCode: null, error: detail, durationMs: Date.now() - start };
|
|
6377
|
+
}
|
|
6378
|
+
}
|
|
6379
|
+
|
|
6677
6380
|
// src/stop-epoch.ts
|
|
6678
|
-
import
|
|
6381
|
+
import fs10 from "fs";
|
|
6679
6382
|
function readStopEpoch() {
|
|
6680
6383
|
try {
|
|
6681
|
-
const n = Number.parseInt(
|
|
6384
|
+
const n = Number.parseInt(fs10.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
|
|
6682
6385
|
return Number.isSafeInteger(n) && n >= 0 ? n : 0;
|
|
6683
6386
|
} catch {
|
|
6684
6387
|
return 0;
|
|
6685
6388
|
}
|
|
6686
6389
|
}
|
|
6687
|
-
var
|
|
6390
|
+
var stopEpochBaseline = null;
|
|
6688
6391
|
function captureStopEpochBaseline() {
|
|
6689
|
-
|
|
6690
|
-
return stopEpochBaselineCaptured;
|
|
6691
|
-
}
|
|
6692
|
-
function stopEpochBaseline() {
|
|
6693
|
-
return stopEpochBaselineCaptured ?? readStopEpoch();
|
|
6392
|
+
stopEpochBaseline = readStopEpoch();
|
|
6694
6393
|
}
|
|
6695
6394
|
function bumpStopEpoch() {
|
|
6696
6395
|
try {
|
|
@@ -6703,7 +6402,7 @@ function epochChanged(before, now) {
|
|
|
6703
6402
|
return now !== before;
|
|
6704
6403
|
}
|
|
6705
6404
|
function startAbortedByConcurrentStop() {
|
|
6706
|
-
return epochChanged(stopEpochBaseline
|
|
6405
|
+
return stopEpochBaseline !== null && epochChanged(stopEpochBaseline, readStopEpoch());
|
|
6707
6406
|
}
|
|
6708
6407
|
|
|
6709
6408
|
// src/service.ts
|
|
@@ -6722,7 +6421,7 @@ async function waitServiceHealthy() {
|
|
|
6722
6421
|
terminatingSignal: state.lastTerminatingSignal
|
|
6723
6422
|
});
|
|
6724
6423
|
do {
|
|
6725
|
-
await
|
|
6424
|
+
await sleep3(SERVICE_HEALTH_INTERVAL_MS);
|
|
6726
6425
|
try {
|
|
6727
6426
|
last = getServiceStatus({ withDisabled: false });
|
|
6728
6427
|
} catch {
|
|
@@ -6739,7 +6438,7 @@ async function waitServiceHealthy() {
|
|
|
6739
6438
|
if (last.running) return { healthy: true, crashed: false, pid: last.pid, exitCode: null, terminatingSignal: null };
|
|
6740
6439
|
let graceQueried = false;
|
|
6741
6440
|
while (Date.now() < graceDeadline) {
|
|
6742
|
-
await
|
|
6441
|
+
await sleep3(SERVICE_HEALTH_INTERVAL_MS);
|
|
6743
6442
|
try {
|
|
6744
6443
|
last = getServiceStatus({ withDisabled: false });
|
|
6745
6444
|
} catch {
|
|
@@ -6791,14 +6490,14 @@ function tunBlockedByConcurrentStart() {
|
|
|
6791
6490
|
function ensureServiceSymlink() {
|
|
6792
6491
|
assertKernelInstalled();
|
|
6793
6492
|
try {
|
|
6794
|
-
const current =
|
|
6493
|
+
const current = fs11.readlinkSync(PATHS.serviceBinary);
|
|
6795
6494
|
if (current === "mihomo") return;
|
|
6796
|
-
|
|
6495
|
+
fs11.unlinkSync(PATHS.serviceBinary);
|
|
6797
6496
|
} catch (e) {
|
|
6798
6497
|
const code = e.code;
|
|
6799
6498
|
if (code === "EINVAL") {
|
|
6800
6499
|
try {
|
|
6801
|
-
|
|
6500
|
+
fs11.unlinkSync(PATHS.serviceBinary);
|
|
6802
6501
|
} catch {
|
|
6803
6502
|
}
|
|
6804
6503
|
} else if (code !== "ENOENT") {
|
|
@@ -6806,12 +6505,12 @@ function ensureServiceSymlink() {
|
|
|
6806
6505
|
}
|
|
6807
6506
|
}
|
|
6808
6507
|
try {
|
|
6809
|
-
|
|
6508
|
+
fs11.symlinkSync("mihomo", PATHS.serviceBinary);
|
|
6810
6509
|
} catch (e) {
|
|
6811
6510
|
if (e.code !== "EEXIST") throw e;
|
|
6812
6511
|
let existing;
|
|
6813
6512
|
try {
|
|
6814
|
-
existing =
|
|
6513
|
+
existing = fs11.readlinkSync(PATHS.serviceBinary);
|
|
6815
6514
|
} catch {
|
|
6816
6515
|
throw e;
|
|
6817
6516
|
}
|
|
@@ -6851,8 +6550,8 @@ async function installService(wasRunning) {
|
|
|
6851
6550
|
}
|
|
6852
6551
|
bootoutService();
|
|
6853
6552
|
await waitUntilUnloaded();
|
|
6854
|
-
|
|
6855
|
-
atomicWriteFileSync(PATHS.userAgentPlist,
|
|
6553
|
+
fs11.mkdirSync(path7.dirname(PATHS.userAgentPlist), { recursive: true });
|
|
6554
|
+
atomicWriteFileSync(PATHS.userAgentPlist, fs11.readFileSync(stagePath, "utf8"), { mode: 420 });
|
|
6856
6555
|
if (wasRunning) {
|
|
6857
6556
|
withFileLock(PATHS.serviceLock, () => {
|
|
6858
6557
|
if (startAbortedByConcurrentStop()) {
|
|
@@ -6865,7 +6564,7 @@ async function installService(wasRunning) {
|
|
|
6865
6564
|
}
|
|
6866
6565
|
} finally {
|
|
6867
6566
|
try {
|
|
6868
|
-
|
|
6567
|
+
fs11.unlinkSync(stagePath);
|
|
6869
6568
|
} catch {
|
|
6870
6569
|
}
|
|
6871
6570
|
}
|
|
@@ -6937,180 +6636,92 @@ async function uninstallService() {
|
|
|
6937
6636
|
assertServiceLabelSafe();
|
|
6938
6637
|
await bootoutAndDisableInLock();
|
|
6939
6638
|
try {
|
|
6940
|
-
|
|
6639
|
+
fs11.rmSync(PATHS.userAgentPlist, { force: true });
|
|
6941
6640
|
} catch (e) {
|
|
6942
6641
|
throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
|
|
6943
6642
|
}
|
|
6944
6643
|
const cleanup = await cleanupKernelsOrThrow({ mainOutcome: "\u670D\u52A1\u5DF2\u5378\u8F7D", retryCommand: "mihomo-cli stop" });
|
|
6945
6644
|
try {
|
|
6946
|
-
|
|
6645
|
+
fs11.rmSync(PATHS.serviceBinary, { force: true });
|
|
6947
6646
|
} catch {
|
|
6948
6647
|
}
|
|
6949
6648
|
return cleanup;
|
|
6950
6649
|
}
|
|
6951
|
-
|
|
6952
|
-
|
|
6953
|
-
|
|
6954
|
-
|
|
6955
|
-
|
|
6956
|
-
|
|
6957
|
-
|
|
6958
|
-
if (hotReload?.ok) {
|
|
6959
|
-
recordDiagnosticEvent("service.hot-reload", "success", { stage: "put" });
|
|
6960
|
-
return { hotReloaded: true, started: !startAbortedByConcurrentStop() };
|
|
6961
|
-
}
|
|
6962
|
-
recordDiagnosticEvent("service.hot-reload", "fallback", {
|
|
6963
|
-
stage: hotReload?.stage ?? "log-rotation",
|
|
6964
|
-
reason: hotReload?.reason ?? "log-oversized",
|
|
6965
|
-
httpStatus: hotReload?.httpStatus,
|
|
6966
|
-
errorType: hotReload?.errorType,
|
|
6967
|
-
aborted: hotReload?.aborted
|
|
6968
|
-
});
|
|
6969
|
-
if (oversized) {
|
|
6970
|
-
const archiveFile = allocateArchivePath();
|
|
6971
|
-
try {
|
|
6972
|
-
fs13.copyFileSync(PATHS.logFile, archiveFile);
|
|
6973
|
-
fs13.writeFileSync(PATHS.logFile, "");
|
|
6974
|
-
} catch {
|
|
6975
|
-
}
|
|
6650
|
+
var HOT_RELOAD_TIMEOUT_MS = 5e3;
|
|
6651
|
+
var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
|
|
6652
|
+
function logOversized() {
|
|
6653
|
+
try {
|
|
6654
|
+
return fs11.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
|
|
6655
|
+
} catch {
|
|
6656
|
+
return false;
|
|
6976
6657
|
}
|
|
6977
|
-
|
|
6978
|
-
|
|
6979
|
-
|
|
6980
|
-
|
|
6658
|
+
}
|
|
6659
|
+
async function tryHotReload(prefetched) {
|
|
6660
|
+
try {
|
|
6661
|
+
const status = prefetched ?? getServiceStatus({ withDisabled: false });
|
|
6662
|
+
if (!status.running || status.pid === null) return false;
|
|
6663
|
+
const endpoint = getControllerEndpoint();
|
|
6664
|
+
if (endpoint.port === null) return false;
|
|
6665
|
+
const baseUrl = `http://127.0.0.1:${endpoint.port}`;
|
|
6666
|
+
const headers = { "Content-Type": "application/json" };
|
|
6667
|
+
if (endpoint.secret) headers.Authorization = `Bearer ${endpoint.secret}`;
|
|
6668
|
+
const controller = new AbortController();
|
|
6669
|
+
const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
|
|
6981
6670
|
try {
|
|
6982
|
-
|
|
6983
|
-
|
|
6984
|
-
|
|
6985
|
-
|
|
6986
|
-
|
|
6987
|
-
|
|
6988
|
-
|
|
6989
|
-
|
|
6990
|
-
|
|
6991
|
-
|
|
6992
|
-
recordDiagnosticEvent("service.bootstrap", "cancelled", { reason: "concurrent-stop" });
|
|
6993
|
-
return { hotReloaded: false, started: false };
|
|
6994
|
-
}
|
|
6995
|
-
if (!bootstrapped) {
|
|
6996
|
-
recordDiagnosticEvent("service.bootstrap", "failure", { reason: "replacement-not-bootstrapped", exitCode: kick.status });
|
|
6997
|
-
const detail = kick.stderr.trim();
|
|
6998
|
-
throw new CliError(`\u91CD\u542F\u670D\u52A1\u5931\u8D25\uFF08kickstart \u9000\u51FA\u7801 ${kick.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09\uFF1A\u670D\u52A1\u4ECD\u5DF2\u88C5\u8F7D\uFF0C\u672C\u6B21\u672A\u91CD\u65B0\u88C5\u8F7D`, {
|
|
6999
|
-
hint: [detail, "\u65E7\u8FDB\u7A0B\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\uFF0C\u65B0\u914D\u7F6E\u672A\u786E\u8BA4\u751F\u6548\uFF1B\u8BF7\u91CD\u8BD5: mihomo-cli start", `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
|
|
6671
|
+
const probe = await fetch(`${baseUrl}/version`, { headers, signal: controller.signal });
|
|
6672
|
+
if (!probe.ok) return false;
|
|
6673
|
+
const info = await probe.json();
|
|
6674
|
+
if (typeof info?.version !== "string") return false;
|
|
6675
|
+
if (lsofListenPids(endpoint.port)?.[0] !== status.pid) return false;
|
|
6676
|
+
const res = await fetch(`${baseUrl}/configs?force=true`, {
|
|
6677
|
+
method: "PUT",
|
|
6678
|
+
headers,
|
|
6679
|
+
body: "{}",
|
|
6680
|
+
signal: controller.signal
|
|
7000
6681
|
});
|
|
6682
|
+
return res.ok;
|
|
6683
|
+
} finally {
|
|
6684
|
+
clearTimeout(timer);
|
|
7001
6685
|
}
|
|
7002
|
-
|
|
6686
|
+
} catch {
|
|
6687
|
+
return false;
|
|
7003
6688
|
}
|
|
7004
|
-
cleanupOldLogs();
|
|
7005
|
-
return { hotReloaded: false, started: true };
|
|
7006
|
-
}
|
|
7007
|
-
|
|
7008
|
-
// src/process-start.ts
|
|
7009
|
-
var TUN_MODE_POST_WAIT_MS = 500;
|
|
7010
|
-
function buildTunLaunchScript() {
|
|
7011
|
-
const binary = shellQuote(PATHS.mihomoBinary);
|
|
7012
|
-
const configFile = shellQuote(PATHS.configFile);
|
|
7013
|
-
const logFile = shellQuote(PATHS.logFile);
|
|
7014
|
-
const pidFile = shellQuote(PATHS.pidFile);
|
|
7015
|
-
const dataDir = shellQuote(DIRS.data);
|
|
7016
|
-
const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
|
|
7017
|
-
return `#!/bin/bash
|
|
7018
|
-
BINARY=${binary}
|
|
7019
|
-
CONFIG_FILE=${configFile}
|
|
7020
|
-
LOG_FILE=${logFile}
|
|
7021
|
-
PID_FILE=${pidFile}
|
|
7022
|
-
DATA_DIR=${dataDir}
|
|
7023
|
-
KILL_PATTERN=${killPattern}
|
|
7024
|
-
|
|
7025
|
-
# \u7EC8\u6B62\u65E7\u8FDB\u7A0B
|
|
7026
|
-
pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
|
|
7027
|
-
sleep 0.2
|
|
7028
|
-
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
7029
|
-
|
|
7030
|
-
# \u5199\u5165\u542F\u52A8\u6807\u8BB0
|
|
7031
|
-
echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
|
|
7032
|
-
|
|
7033
|
-
# \u542F\u52A8
|
|
7034
|
-
cd /tmp
|
|
7035
|
-
"\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
|
|
7036
|
-
NEW_PID=$!
|
|
7037
|
-
echo \${NEW_PID} > "\${PID_FILE}"
|
|
7038
|
-
|
|
7039
|
-
# \u8FDB\u7A0B\u5224\u5B9A\uFF1A\u6D3B\u7740 = ps \u80FD\u67E5\u5230\u4E14\u72B6\u6001\u975E Z\u3002\u4E0D\u80FD\u53EA\u7528 kill -0\u2014\u2014\u5B83\u5BF9\u50F5\u5C38
|
|
7040
|
-
#\uFF08bash \u5C1A\u672A\u6536\u5272\u7684\u5DF2\u6B7B\u5B50\u8FDB\u7A0B\uFF09\u540C\u6837\u8FD4\u56DE\u6210\u529F\uFF0C\u5B9E\u6D4B 150ms \u9000\u51FA\u7684\u6869\u8FDB\u7A0B 10 \u6B21\u4E2D
|
|
7041
|
-
# 5 \u6B21\u88AB\u8BEF\u62A5\u5B58\u6D3B\uFF1B\u67E5\u4E0D\u5230\uFF08\u5DF2\u88AB\u6536\u5272/\u4E0D\u5B58\u5728\uFF09\u540C\u6837\u7B97\u6B7B\u3002
|
|
7042
|
-
is_alive() {
|
|
7043
|
-
local stat
|
|
7044
|
-
stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
|
|
7045
|
-
case "\${stat}" in
|
|
7046
|
-
Z*|'') return 1 ;;
|
|
7047
|
-
*) return 0 ;;
|
|
7048
|
-
esac
|
|
7049
|
-
}
|
|
7050
|
-
|
|
7051
|
-
# \u9A8C\u8BC1\uFF1A\u89C2\u5BDF\u6EE1\u4E00\u4E2A\u7A97\u53E3\uFF0812 \xD7 0.1s \u2248 1.2s\uFF0C\u4E0E\u670D\u52A1\u8DEF\u5F84 SERVICE_OBSERVE_MS \u5BF9\u9F50\uFF09\u3002
|
|
7052
|
-
# \u4E0D\u80FD\u300C\u4E00\u770B\u5230\u6D3B\u7740\u5C31\u6536\u53E3\u300D\u2014\u2014\u5185\u6838\u5E38\u5728 spawn \u540E\u6570\u767E ms \u624D\u9000\u51FA\uFF08\u5B9E\u6D4B 180ms \u4E0E 540ms
|
|
7053
|
-
# \u4E24\u79CD\uFF09\uFF0C\u6B64\u524D\u7684 0.4s \u5355\u6B21\u68C0\u67E5\u5FC5\u6F0F\uFF1B\u671F\u95F4\u6B7B\u4EA1\u7ACB\u5373\u8D70\u5931\u8D25\u8DEF\u5F84\u3002
|
|
7054
|
-
i=0
|
|
7055
|
-
while [ $i -lt 12 ]; do
|
|
7056
|
-
sleep 0.1
|
|
7057
|
-
is_alive \${NEW_PID} || break
|
|
7058
|
-
i=$((i+1))
|
|
7059
|
-
done
|
|
7060
|
-
if is_alive \${NEW_PID}; then
|
|
7061
|
-
exit 0
|
|
7062
|
-
fi
|
|
7063
|
-
|
|
7064
|
-
# \u5931\u8D25\uFF0C\u663E\u793A\u65E5\u5FD7\uFF08\u9000\u51FA\u7801 2\uFF1A\u907F\u5F00 sudo \u7684 1=\u9274\u6743\u5931\u8D25/\u53D6\u6D88\uFF0C\u4F9B\u8C03\u7528\u65B9\u533A\u5206\uFF09
|
|
7065
|
-
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
7066
|
-
echo "TUN \u542F\u52A8\u5931\u8D25"
|
|
7067
|
-
echo ""
|
|
7068
|
-
echo "--- \u65E5\u5FD7 ---"
|
|
7069
|
-
tail -25 "\${LOG_FILE}" 2>/dev/null
|
|
7070
|
-
exit 2
|
|
7071
|
-
`;
|
|
7072
6689
|
}
|
|
7073
|
-
async function
|
|
7074
|
-
|
|
7075
|
-
|
|
7076
|
-
|
|
7077
|
-
const serviceLoaded = prefetched ? prefetched.loaded : getServiceStatus({ withDisabled: false }).loaded;
|
|
7078
|
-
if (serviceLoaded) {
|
|
7079
|
-
throw tunBlockedByConcurrentStart();
|
|
7080
|
-
}
|
|
7081
|
-
rotateAndCleanupLogs();
|
|
7082
|
-
const logFile = PATHS.logFile;
|
|
7083
|
-
if (fs14.existsSync(logFile)) {
|
|
7084
|
-
try {
|
|
7085
|
-
fs14.accessSync(logFile, fs14.constants.W_OK);
|
|
7086
|
-
} catch {
|
|
7087
|
-
try {
|
|
7088
|
-
fs14.unlinkSync(logFile);
|
|
7089
|
-
} catch {
|
|
7090
|
-
}
|
|
7091
|
-
}
|
|
7092
|
-
}
|
|
7093
|
-
const stalePids = getMihomoPids();
|
|
7094
|
-
if (stalePids.length > 0) {
|
|
7095
|
-
console.log(`\u6E05\u7406 ${stalePids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
|
|
7096
|
-
} else if (isPidFileOwnedByRoot()) {
|
|
7097
|
-
console.log("\u6E05\u7406\u6B8B\u7559\u7684 root pid \u6587\u4EF6...");
|
|
6690
|
+
async function restartService(prefetched) {
|
|
6691
|
+
assertServiceLabelSafe();
|
|
6692
|
+
if (!isServiceInstalled()) {
|
|
6693
|
+
throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo-cli install" });
|
|
7098
6694
|
}
|
|
7099
|
-
|
|
7100
|
-
|
|
7101
|
-
|
|
7102
|
-
|
|
7103
|
-
|
|
7104
|
-
|
|
7105
|
-
|
|
7106
|
-
|
|
7107
|
-
|
|
7108
|
-
|
|
7109
|
-
|
|
7110
|
-
|
|
6695
|
+
const oversized = logOversized();
|
|
6696
|
+
const hotReloaded = !oversized && await tryHotReload(prefetched);
|
|
6697
|
+
if (hotReloaded) {
|
|
6698
|
+
return { hotReloaded: true, started: !startAbortedByConcurrentStop() };
|
|
6699
|
+
}
|
|
6700
|
+
if (oversized) {
|
|
6701
|
+
const archiveFile = allocateArchivePath();
|
|
6702
|
+
try {
|
|
6703
|
+
fs11.copyFileSync(PATHS.logFile, archiveFile);
|
|
6704
|
+
fs11.writeFileSync(PATHS.logFile, "");
|
|
6705
|
+
} catch {
|
|
6706
|
+
}
|
|
6707
|
+
}
|
|
6708
|
+
const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
|
|
6709
|
+
if (kick.status !== 0) {
|
|
6710
|
+
const bootstrapped = withFileLock(PATHS.serviceLock, () => {
|
|
6711
|
+
if (startAbortedByConcurrentStop()) return null;
|
|
6712
|
+
runLaunchctl(["enable", serviceTarget()], SERVICE_LOCK_LAUNCHCTL_TIMEOUT_MS);
|
|
6713
|
+
return bootstrapServiceIdempotentOrThrow("\u91CD\u542F\u670D\u52A1");
|
|
7111
6714
|
});
|
|
6715
|
+
if (bootstrapped === null) return { hotReloaded: false, started: false };
|
|
6716
|
+
if (!bootstrapped) {
|
|
6717
|
+
const detail = kick.stderr.trim();
|
|
6718
|
+
throw new CliError(`\u91CD\u542F\u670D\u52A1\u5931\u8D25\uFF08kickstart \u9000\u51FA\u7801 ${kick.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09\uFF1A\u670D\u52A1\u4ECD\u5DF2\u88C5\u8F7D\uFF0C\u672C\u6B21\u672A\u91CD\u65B0\u88C5\u8F7D`, {
|
|
6719
|
+
hint: [detail, "\u65E7\u8FDB\u7A0B\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\uFF0C\u65B0\u914D\u7F6E\u672A\u786E\u8BA4\u751F\u6548\uFF1B\u8BF7\u91CD\u8BD5: mihomo-cli start", `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
|
|
6720
|
+
});
|
|
6721
|
+
}
|
|
7112
6722
|
}
|
|
7113
|
-
|
|
6723
|
+
cleanupOldLogs();
|
|
6724
|
+
return { hotReloaded: false, started: true };
|
|
7114
6725
|
}
|
|
7115
6726
|
|
|
7116
6727
|
// src/runtime.ts
|
|
@@ -7130,24 +6741,13 @@ function getRunningState(serviceStatus) {
|
|
|
7130
6741
|
return { running: false, pid: null, kind: null, memory: null };
|
|
7131
6742
|
}
|
|
7132
6743
|
function restartModeFor(state, fallbackMode) {
|
|
7133
|
-
return state.kind === "tun" ? "tun" : fallbackMode;
|
|
6744
|
+
return state.kind === "tun" ? "tun" : fallbackMode();
|
|
7134
6745
|
}
|
|
7135
6746
|
function restartModeOnChange() {
|
|
7136
6747
|
const state = getRunningState();
|
|
7137
|
-
return state.running ? restartModeFor(state, getRuntimeMode
|
|
6748
|
+
return state.running ? restartModeFor(state, getRuntimeMode) : null;
|
|
7138
6749
|
}
|
|
7139
6750
|
async function launchOrRestart(mode) {
|
|
7140
|
-
const startedAt = Date.now();
|
|
7141
|
-
try {
|
|
7142
|
-
const pid = await launchOrRestartImpl(mode);
|
|
7143
|
-
recordDiagnosticEvent("runtime.launch", "success", { mode, kernelPid: pid, durationMs: Date.now() - startedAt });
|
|
7144
|
-
return pid;
|
|
7145
|
-
} catch (e) {
|
|
7146
|
-
recordDiagnosticEvent("runtime.launch", "failure", { mode, durationMs: Date.now() - startedAt, ...diagnosticErrorDetails(e) });
|
|
7147
|
-
throw e;
|
|
7148
|
-
}
|
|
7149
|
-
}
|
|
7150
|
-
async function launchOrRestartImpl(mode) {
|
|
7151
6751
|
if (mode === "tun") {
|
|
7152
6752
|
const prefetched = assertTunStartNotRaced();
|
|
7153
6753
|
let pid;
|
|
@@ -7171,7 +6771,7 @@ async function launchOrRestartImpl(mode) {
|
|
|
7171
6771
|
if (!started) throw cancelledByConcurrentStop();
|
|
7172
6772
|
if (hotReloaded) {
|
|
7173
6773
|
try {
|
|
7174
|
-
return getServiceStatus().pid;
|
|
6774
|
+
return getServiceStatus({ withDisabled: false }).pid;
|
|
7175
6775
|
} catch {
|
|
7176
6776
|
return null;
|
|
7177
6777
|
}
|
|
@@ -7217,15 +6817,7 @@ function startCommandForCurrentMode(state) {
|
|
|
7217
6817
|
return state.kind === "tun" ? "mihomo-cli start tun" : "mihomo-cli start";
|
|
7218
6818
|
}
|
|
7219
6819
|
async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
|
|
7220
|
-
const startedAt = Date.now();
|
|
7221
6820
|
const health = await waitServiceHealthy();
|
|
7222
|
-
recordDiagnosticEvent("service.health", health.healthy ? "success" : "failure", {
|
|
7223
|
-
reason: health.healthy ? void 0 : health.crashed ? "crashed" : "not-running",
|
|
7224
|
-
kernelPid: health.pid,
|
|
7225
|
-
lastExitCode: health.exitCode,
|
|
7226
|
-
lastTerminatingSignal: health.terminatingSignal,
|
|
7227
|
-
durationMs: Date.now() - startedAt
|
|
7228
|
-
});
|
|
7229
6821
|
if (health.healthy) return health.pid;
|
|
7230
6822
|
const tail = readLogTail();
|
|
7231
6823
|
const cause = describeExitCause(health.exitCode, health.terminatingSignal);
|
|
@@ -7240,117 +6832,111 @@ async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
|
|
|
7240
6832
|
]
|
|
7241
6833
|
});
|
|
7242
6834
|
}
|
|
6835
|
+
var TUN_MODE_POST_WAIT_MS = 500;
|
|
6836
|
+
function buildTunLaunchScript() {
|
|
6837
|
+
const binary = shellQuote(PATHS.mihomoBinary);
|
|
6838
|
+
const configFile = shellQuote(PATHS.configFile);
|
|
6839
|
+
const logFile = shellQuote(PATHS.logFile);
|
|
6840
|
+
const pidFile = shellQuote(PATHS.pidFile);
|
|
6841
|
+
const dataDir = shellQuote(DIRS.data);
|
|
6842
|
+
const killPattern = shellQuote(MAIN_INSTANCE_PATTERN);
|
|
6843
|
+
return `#!/bin/bash
|
|
6844
|
+
BINARY=${binary}
|
|
6845
|
+
CONFIG_FILE=${configFile}
|
|
6846
|
+
LOG_FILE=${logFile}
|
|
6847
|
+
PID_FILE=${pidFile}
|
|
6848
|
+
DATA_DIR=${dataDir}
|
|
6849
|
+
KILL_PATTERN=${killPattern}
|
|
7243
6850
|
|
|
7244
|
-
|
|
7245
|
-
|
|
7246
|
-
|
|
7247
|
-
|
|
7248
|
-
|
|
6851
|
+
# \u7EC8\u6B62\u65E7\u8FDB\u7A0B
|
|
6852
|
+
pkill -9 -f "\${KILL_PATTERN}" 2>/dev/null || true
|
|
6853
|
+
sleep 0.2
|
|
6854
|
+
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
6855
|
+
|
|
6856
|
+
# \u5199\u5165\u542F\u52A8\u6807\u8BB0
|
|
6857
|
+
echo "=== TUN \u542F\u52A8: $(date) ===" >> "\${LOG_FILE}"
|
|
6858
|
+
|
|
6859
|
+
# \u542F\u52A8
|
|
6860
|
+
cd /tmp
|
|
6861
|
+
"\${BINARY}" -d "\${DATA_DIR}" -f "\${CONFIG_FILE}" >> "\${LOG_FILE}" 2>&1 &
|
|
6862
|
+
NEW_PID=$!
|
|
6863
|
+
echo \${NEW_PID} > "\${PID_FILE}"
|
|
6864
|
+
|
|
6865
|
+
# \u8FDB\u7A0B\u5224\u5B9A\uFF1A\u6D3B\u7740 = ps \u80FD\u67E5\u5230\u4E14\u72B6\u6001\u975E Z\u3002\u4E0D\u80FD\u53EA\u7528 kill -0\u2014\u2014\u5B83\u5BF9\u50F5\u5C38
|
|
6866
|
+
#\uFF08bash \u5C1A\u672A\u6536\u5272\u7684\u5DF2\u6B7B\u5B50\u8FDB\u7A0B\uFF09\u540C\u6837\u8FD4\u56DE\u6210\u529F\uFF0C\u5B9E\u6D4B 150ms \u9000\u51FA\u7684\u6869\u8FDB\u7A0B 10 \u6B21\u4E2D
|
|
6867
|
+
# 5 \u6B21\u88AB\u8BEF\u62A5\u5B58\u6D3B\uFF1B\u67E5\u4E0D\u5230\uFF08\u5DF2\u88AB\u6536\u5272/\u4E0D\u5B58\u5728\uFF09\u540C\u6837\u7B97\u6B7B\u3002
|
|
6868
|
+
is_alive() {
|
|
6869
|
+
local stat
|
|
6870
|
+
stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
|
|
6871
|
+
case "\${stat}" in
|
|
6872
|
+
Z*|'') return 1 ;;
|
|
6873
|
+
*) return 0 ;;
|
|
6874
|
+
esac
|
|
7249
6875
|
}
|
|
7250
|
-
|
|
7251
|
-
|
|
7252
|
-
|
|
7253
|
-
|
|
7254
|
-
|
|
7255
|
-
|
|
6876
|
+
|
|
6877
|
+
# \u9A8C\u8BC1\uFF1A\u89C2\u5BDF\u6EE1\u4E00\u4E2A\u7A97\u53E3\uFF0812 \xD7 0.1s \u2248 1.2s\uFF0C\u4E0E\u670D\u52A1\u8DEF\u5F84 SERVICE_OBSERVE_MS \u5BF9\u9F50\uFF09\u3002
|
|
6878
|
+
# \u4E0D\u80FD\u300C\u4E00\u770B\u5230\u6D3B\u7740\u5C31\u6536\u53E3\u300D\u2014\u2014\u5185\u6838\u5E38\u5728 spawn \u540E\u6570\u767E ms \u624D\u9000\u51FA\uFF08\u5B9E\u6D4B 180ms \u4E0E 540ms
|
|
6879
|
+
# \u4E24\u79CD\uFF09\uFF0C\u6B64\u524D\u7684 0.4s \u5355\u6B21\u68C0\u67E5\u5FC5\u6F0F\uFF1B\u671F\u95F4\u6B7B\u4EA1\u7ACB\u5373\u8D70\u5931\u8D25\u8DEF\u5F84\u3002
|
|
6880
|
+
i=0
|
|
6881
|
+
while [ $i -lt 12 ]; do
|
|
6882
|
+
sleep 0.1
|
|
6883
|
+
is_alive \${NEW_PID} || break
|
|
6884
|
+
i=$((i+1))
|
|
6885
|
+
done
|
|
6886
|
+
if is_alive \${NEW_PID}; then
|
|
6887
|
+
exit 0
|
|
6888
|
+
fi
|
|
6889
|
+
|
|
6890
|
+
# \u5931\u8D25\uFF0C\u663E\u793A\u65E5\u5FD7\uFF08\u9000\u51FA\u7801 2\uFF1A\u907F\u5F00 sudo \u7684 1=\u9274\u6743\u5931\u8D25/\u53D6\u6D88\uFF0C\u4F9B\u8C03\u7528\u65B9\u533A\u5206\uFF09
|
|
6891
|
+
rm -f "\${PID_FILE}" 2>/dev/null || true
|
|
6892
|
+
echo "TUN \u542F\u52A8\u5931\u8D25"
|
|
6893
|
+
echo ""
|
|
6894
|
+
echo "--- \u65E5\u5FD7 ---"
|
|
6895
|
+
tail -25 "\${LOG_FILE}" 2>/dev/null
|
|
6896
|
+
exit 2
|
|
6897
|
+
`;
|
|
6898
|
+
}
|
|
6899
|
+
async function startTun(prefetched) {
|
|
6900
|
+
ensureDirs();
|
|
6901
|
+
assertKernelInstalled();
|
|
6902
|
+
assertRuntimeConfigPresent();
|
|
6903
|
+
const serviceLoaded = prefetched ? prefetched.loaded : getServiceStatus({ withDisabled: false }).loaded;
|
|
6904
|
+
if (serviceLoaded) {
|
|
6905
|
+
throw tunBlockedByConcurrentStart();
|
|
6906
|
+
}
|
|
6907
|
+
rotateAndCleanupLogs();
|
|
6908
|
+
const logFile = PATHS.logFile;
|
|
6909
|
+
if (fs12.existsSync(logFile)) {
|
|
7256
6910
|
try {
|
|
7257
|
-
|
|
6911
|
+
fs12.accessSync(logFile, fs12.constants.W_OK);
|
|
7258
6912
|
} catch {
|
|
7259
|
-
|
|
6913
|
+
try {
|
|
6914
|
+
fs12.unlinkSync(logFile);
|
|
6915
|
+
} catch {
|
|
6916
|
+
}
|
|
7260
6917
|
}
|
|
7261
6918
|
}
|
|
7262
|
-
const
|
|
7263
|
-
|
|
7264
|
-
|
|
7265
|
-
|
|
7266
|
-
|
|
7267
|
-
function proxyEnvPointsAtSelf(value, selfPort) {
|
|
7268
|
-
const endpoint = parseProxyEndpoint(value);
|
|
7269
|
-
if (!endpoint) return false;
|
|
7270
|
-
return isLoopbackHost(endpoint.host) && endpoint.port === selfPort;
|
|
7271
|
-
}
|
|
7272
|
-
var clearedSelfProxyEnv = null;
|
|
7273
|
-
function recordClearedProxyEnv(cleared) {
|
|
7274
|
-
clearedSelfProxyEnv = cleared === null ? null : { ...cleared };
|
|
7275
|
-
}
|
|
7276
|
-
function getClearedProxyEnv() {
|
|
7277
|
-
return clearedSelfProxyEnv === null ? null : { ...clearedSelfProxyEnv };
|
|
7278
|
-
}
|
|
7279
|
-
function parseScutilProxy(stdout) {
|
|
7280
|
-
const values = /* @__PURE__ */ new Map();
|
|
7281
|
-
for (const line of stdout.split("\n")) {
|
|
7282
|
-
const m = line.match(/^ {2}([A-Za-z]+) : (.+)$/);
|
|
7283
|
-
if (m) values.set(m[1], m[2].trim());
|
|
7284
|
-
}
|
|
7285
|
-
const read = (prefix) => {
|
|
7286
|
-
if (values.get(`${prefix}Enable`) !== "1") return void 0;
|
|
7287
|
-
const host = values.get(`${prefix}Proxy`);
|
|
7288
|
-
const port = Number.parseInt(values.get(`${prefix}Port`) ?? "", 10);
|
|
7289
|
-
if (!host || !Number.isFinite(port)) return void 0;
|
|
7290
|
-
return { host, port };
|
|
7291
|
-
};
|
|
7292
|
-
const readPac = () => {
|
|
7293
|
-
if (values.get("ProxyAutoConfigEnable") === "1") {
|
|
7294
|
-
const url = values.get("ProxyAutoConfigURLString") ?? "";
|
|
7295
|
-
const host = values.get("ProxyAutoConfigHost");
|
|
7296
|
-
const port = values.get("ProxyAutoConfigPort");
|
|
7297
|
-
const legacy = host ? `${host}${port ? `:${port}` : ""}` : "";
|
|
7298
|
-
return { source: url || legacy, wpad: false };
|
|
7299
|
-
}
|
|
7300
|
-
if (values.get("ProxyAutoDiscoveryEnable") === "1") {
|
|
7301
|
-
return { source: "", wpad: true };
|
|
7302
|
-
}
|
|
7303
|
-
return void 0;
|
|
7304
|
-
};
|
|
7305
|
-
return { http: read("HTTP"), https: read("HTTPS"), socks: read("SOCKS"), pac: readPac() };
|
|
7306
|
-
}
|
|
7307
|
-
var entryMatches = (e, mixedPort) => isLoopbackHost(e.host) && e.port === mixedPort;
|
|
7308
|
-
function summarizeSystemProxy(view, mixedPort) {
|
|
7309
|
-
const entries = [view.http, view.https, view.socks].filter((e) => e !== void 0);
|
|
7310
|
-
return {
|
|
7311
|
-
matched: entries.some((e) => entryMatches(e, mixedPort)),
|
|
7312
|
-
active: [...new Set(entries.map((e) => `${e.host}:${e.port}`))],
|
|
7313
|
-
diverged: [...new Set(entries.filter((e) => !entryMatches(e, mixedPort)).map((e) => `${e.host}:${e.port}`))],
|
|
7314
|
-
pac: view.pac ?? null
|
|
7315
|
-
};
|
|
7316
|
-
}
|
|
7317
|
-
function detectSystemProxy(mixedPort) {
|
|
7318
|
-
let r;
|
|
7319
|
-
try {
|
|
7320
|
-
r = spawnSync8("scutil", ["--proxy"], { encoding: "utf8", timeout: 3e3 });
|
|
7321
|
-
} catch {
|
|
7322
|
-
return null;
|
|
7323
|
-
}
|
|
7324
|
-
if (r.error || r.status !== 0 || typeof r.stdout !== "string" || !r.stdout.includes("<dictionary>")) return null;
|
|
7325
|
-
return summarizeSystemProxy(parseScutilProxy(r.stdout), mixedPort);
|
|
7326
|
-
}
|
|
7327
|
-
function buildSystemProxyHint(summary, mixedPort) {
|
|
7328
|
-
const applicationGuide = `\u9700\u8981\u4EE3\u7406\u7684\u5177\u4F53\u5E94\u7528\u8BF7\u914D\u7F6E HTTP/SOCKS5 127.0.0.1:${mixedPort}\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`;
|
|
7329
|
-
if (summary === null) {
|
|
7330
|
-
return { text: `\u63D0\u793A: Mixed \u4E0D\u81EA\u52A8\u4FEE\u6539 macOS \u7CFB\u7EDF\u4EE3\u7406\uFF1B${applicationGuide}`, warning: false };
|
|
7331
|
-
}
|
|
7332
|
-
if (summary.pac) {
|
|
7333
|
-
const desc = summary.pac.wpad ? "WPAD \u81EA\u52A8\u53D1\u73B0" : `PAC \u6587\u4EF6${summary.pac.source ? `\uFF08${summary.pac.source}\uFF09` : ""}`;
|
|
7334
|
-
return { text: `\u7CFB\u7EDF\u4EE3\u7406\u7531 ${desc} \u63A5\u7BA1\uFF0C\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u5B83\uFF1B${applicationGuide}`, warning: false };
|
|
6919
|
+
const stalePids = getMihomoPids();
|
|
6920
|
+
if (stalePids.length > 0) {
|
|
6921
|
+
console.log(`\u6E05\u7406 ${stalePids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
|
|
6922
|
+
} else if (isPidFileOwnedByRoot()) {
|
|
6923
|
+
console.log("\u6E05\u7406\u6B8B\u7559\u7684 root pid \u6587\u4EF6...");
|
|
7335
6924
|
}
|
|
7336
|
-
|
|
7337
|
-
|
|
7338
|
-
|
|
7339
|
-
|
|
7340
|
-
|
|
7341
|
-
|
|
7342
|
-
|
|
7343
|
-
|
|
6925
|
+
console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
|
|
6926
|
+
runSudoScript(buildTunLaunchScript(), {
|
|
6927
|
+
action: "TUN \u542F\u52A8",
|
|
6928
|
+
file: "launch-tun.sh",
|
|
6929
|
+
codeMessages: { 2: "TUN \u542F\u52A8\u5931\u8D25\uFF08\u8BE6\u89C1\u4E0A\u65B9\u65E5\u5FD7\uFF09" }
|
|
6930
|
+
});
|
|
6931
|
+
await sleep4(TUN_MODE_POST_WAIT_MS);
|
|
6932
|
+
const finalPid = getPid();
|
|
6933
|
+
if (!finalPid || !isRunning()) {
|
|
6934
|
+
const tail = readLogTail();
|
|
6935
|
+
throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
|
|
6936
|
+
hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo-cli logs 0"]
|
|
6937
|
+
});
|
|
7344
6938
|
}
|
|
7345
|
-
|
|
7346
|
-
return {
|
|
7347
|
-
text: `\u63D0\u793A: \u7CFB\u7EDF\u4EE3\u7406\u672A\u6307\u5411 127.0.0.1:${mixedPort}${pointing}\uFF0C\u672C\u5DE5\u5177\u4E0D\u4F1A\u4FEE\u6539\u5B83\uFF1B${applicationGuide}`,
|
|
7348
|
-
warning: true
|
|
7349
|
-
};
|
|
7350
|
-
}
|
|
7351
|
-
function printSystemProxyHint(mixedPort) {
|
|
7352
|
-
const hint = buildSystemProxyHint(detectSystemProxy(mixedPort), mixedPort);
|
|
7353
|
-
console.log(hint.warning ? colors.yellow(hint.text) : colors.gray(hint.text));
|
|
6939
|
+
return finalPid;
|
|
7354
6940
|
}
|
|
7355
6941
|
|
|
7356
6942
|
// src/commands/status.ts
|
|
@@ -7405,7 +6991,7 @@ function buildStatusJson(args) {
|
|
|
7405
6991
|
// 会与同一份 JSON 里的 overwrite.enabled:false 自相矛盾
|
|
7406
6992
|
applied: args.overwriteEnabled ? args.overwriteFiles.filter(isActiveOverwrite).map((f) => f.name) : [],
|
|
7407
6993
|
// 加载失败的文件不属于 applied(既没合并也无法判 enabled/match),单列 errors。
|
|
7408
|
-
// hint
|
|
6994
|
+
// hint 必须带出:可执行的修复指引(*edu 加引号、操作符写法等)都在里面,
|
|
7409
6995
|
// 只给 message 等于把可执行的修复步骤扔在启动硬失败那一条路径上
|
|
7410
6996
|
errors: args.overwriteBroken.map((b) => ({ name: b.name, message: b.message, hint: b.hint }))
|
|
7411
6997
|
},
|
|
@@ -7594,7 +7180,6 @@ async function cmdStart(args) {
|
|
|
7594
7180
|
const targetMode = resolveStartMode(args);
|
|
7595
7181
|
const skipUpdate = hasFlag(args, "-s", "--no-update");
|
|
7596
7182
|
const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
|
|
7597
|
-
recordDiagnosticEvent("start", "begin", { mode: targetMode, updateRequested: !skipUpdate, timeoutMs: updateTimeout });
|
|
7598
7183
|
let disabledAutoStartForTun = false;
|
|
7599
7184
|
assertKernelInstalled();
|
|
7600
7185
|
const serviceBefore = getServiceStatus();
|
|
@@ -7656,7 +7241,8 @@ async function cmdStart(args) {
|
|
|
7656
7241
|
console.log(colors.yellow(`\u72B6\u6001\u5C55\u793A\u5931\u8D25\uFF08\u4E0D\u5F71\u54CD\u5DF2\u5B8C\u6210\u7684\u542F\u52A8\uFF09: ${firstLine(e.message)}`));
|
|
7657
7242
|
}
|
|
7658
7243
|
if (targetMode === "mixed") {
|
|
7659
|
-
|
|
7244
|
+
const mixedPort = getPortsOrNull()?.mixed ?? DEFAULT_MIXED_PORT;
|
|
7245
|
+
console.log(colors.gray(`\u63D0\u793A: Mixed \u4E0D\u81EA\u52A8\u4FEE\u6539 macOS \u7CFB\u7EDF\u4EE3\u7406\uFF1B\u9700\u8981\u4EE3\u7406\u7684\u5177\u4F53\u5E94\u7528\u8BF7\u914D\u7F6E HTTP/SOCKS5 127.0.0.1:${mixedPort}\uFF08TUN \u6A21\u5F0F\u65E0\u9700\uFF09`));
|
|
7660
7246
|
} else {
|
|
7661
7247
|
console.log(colors.gray("TUN \u4E3A\u4E34\u65F6\u8FDB\u7A0B\uFF0C\u5173\u95ED\u7EC8\u7AEF\u4E0D\u4F1A\u505C\u6B62\uFF1B\u505C\u6B62: mihomo-cli stop\uFF08\u4E4B\u540E mihomo-cli start \u6062\u590D Mixed\uFF09"));
|
|
7662
7248
|
}
|
|
@@ -7664,20 +7250,20 @@ async function cmdStart(args) {
|
|
|
7664
7250
|
}
|
|
7665
7251
|
|
|
7666
7252
|
// src/commands/shared.ts
|
|
7667
|
-
function assertUniqueTokens(
|
|
7253
|
+
function assertUniqueTokens(entries, what) {
|
|
7668
7254
|
const owner = /* @__PURE__ */ new Map();
|
|
7669
|
-
for (const
|
|
7670
|
-
for (const token of [
|
|
7255
|
+
for (const entry of entries) {
|
|
7256
|
+
for (const token of [entry.name, ...entry.aliases ?? []]) {
|
|
7671
7257
|
const prev = owner.get(token);
|
|
7672
7258
|
if (prev !== void 0) {
|
|
7673
|
-
throw new Error(
|
|
7259
|
+
throw new Error(`${what}\u5B58\u5728\u91CD\u590D token: "${token}"\uFF08${prev} \u4E0E ${entry.name}\uFF09`);
|
|
7674
7260
|
}
|
|
7675
|
-
owner.set(token,
|
|
7261
|
+
owner.set(token, entry.name);
|
|
7676
7262
|
}
|
|
7677
7263
|
}
|
|
7678
7264
|
}
|
|
7679
7265
|
async function dispatchSubcommand(args, table, options) {
|
|
7680
|
-
assertUniqueTokens(table);
|
|
7266
|
+
assertUniqueTokens(table, "\u5B50\u547D\u4EE4\u8868");
|
|
7681
7267
|
const action = args[1]?.toLowerCase();
|
|
7682
7268
|
if (action === "") {
|
|
7683
7269
|
throw new CliError("\u5B50\u547D\u4EE4\u4E0D\u80FD\u4E3A\u7A7A", { hint: [`\u7528\u6CD5: mihomo-cli ${args[0]} <\u5B50\u547D\u4EE4>`] });
|
|
@@ -7727,18 +7313,12 @@ async function restartToApply(args) {
|
|
|
7727
7313
|
// src/commands/directory.ts
|
|
7728
7314
|
function openDirectory(args) {
|
|
7729
7315
|
assertPositionalCount(args, 1, 2, "mihomo-cli dir open [root|subs|logs|data|runtime|kernel]");
|
|
7730
|
-
const target = args[2];
|
|
7731
|
-
if (target === void 0 || target === "root") {
|
|
7732
|
-
console.log(`\u6B63\u5728\u6253\u5F00: \u6839\u76EE\u5F55 (${USER_DATA_DIR})`);
|
|
7733
|
-
openUrl(USER_DATA_DIR);
|
|
7734
|
-
return;
|
|
7735
|
-
}
|
|
7316
|
+
const target = args[2] ?? "root";
|
|
7736
7317
|
const key = target.toLowerCase();
|
|
7737
7318
|
const targetInfo = Object.hasOwn(DIRECTORY_TARGETS, key) ? DIRECTORY_TARGETS[key] : void 0;
|
|
7738
7319
|
if (targetInfo) {
|
|
7739
|
-
|
|
7740
|
-
|
|
7741
|
-
openUrl(targetPath);
|
|
7320
|
+
console.log(`\u6B63\u5728\u6253\u5F00: ${targetInfo.label} (${targetInfo.path})`);
|
|
7321
|
+
openUrl(targetInfo.path);
|
|
7742
7322
|
return;
|
|
7743
7323
|
}
|
|
7744
7324
|
const hint = ["", "\u53EF\u7528\u76EE\u6807:", " root (\u9ED8\u8BA4) \u6839\u76EE\u5F55"];
|
|
@@ -7769,21 +7349,19 @@ async function cmdDirectory(args) {
|
|
|
7769
7349
|
assertKnownFlags(args.slice(1), [], "dir");
|
|
7770
7350
|
await dispatchSubcommand(args, SUBCOMMANDS, {
|
|
7771
7351
|
fallback: printDirectoryInfo,
|
|
7772
|
-
// 裸 dir 只展示目录信息(选项由分发前的白名单统一拦);守卫收口在 shared
|
|
7773
7352
|
onUnknown: (action) => unknownSubcommandError(action, SUBCOMMANDS, {
|
|
7774
7353
|
what: "\u76EE\u5F55\u5B50\u547D\u4EE4",
|
|
7775
|
-
optionHint: ["\u88F8 dir \u53EA\u5C55\u793A\u76EE\u5F55\u4FE1\u606F\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo-cli dir open [root|subs|logs|data|runtime|kernel]"],
|
|
7776
7354
|
unknownHint: ["", "\u53EF\u7528\u5B50\u547D\u4EE4: open", "\u6253\u5F00\u6307\u5B9A\u76EE\u5F55: mihomo-cli dir open <target>"]
|
|
7777
7355
|
})
|
|
7778
7356
|
});
|
|
7779
7357
|
}
|
|
7780
7358
|
|
|
7781
7359
|
// src/commands/doctor.ts
|
|
7782
|
-
import
|
|
7360
|
+
import fs14 from "fs";
|
|
7783
7361
|
|
|
7784
7362
|
// src/kernel.ts
|
|
7785
|
-
import { execFile as execFile3, spawn as spawn2, spawnSync as
|
|
7786
|
-
import
|
|
7363
|
+
import { execFile as execFile3, spawn as spawn2, spawnSync as spawnSync8 } from "child_process";
|
|
7364
|
+
import fs13 from "fs";
|
|
7787
7365
|
import path8 from "path";
|
|
7788
7366
|
import { promisify as promisify3 } from "util";
|
|
7789
7367
|
var GITHUB_REPO = "MetaCubeX/mihomo";
|
|
@@ -7821,7 +7399,7 @@ function resolveDownloadChannels(input) {
|
|
|
7821
7399
|
return [input.proxyOverride ? { kind: "mirror", mirror: input.mirror, proxy: input.proxyOverride } : { kind: "mirror", mirror: input.mirror }];
|
|
7822
7400
|
}
|
|
7823
7401
|
if (input.proxyOverride) return [{ kind: "proxy", proxy: input.proxyOverride }];
|
|
7824
|
-
if (input.
|
|
7402
|
+
if (input.proxyPort !== null) {
|
|
7825
7403
|
const proxyUrl = loopbackHttpUrl(input.proxyPort);
|
|
7826
7404
|
const channels = [{ kind: "proxy", proxy: proxyUrl }];
|
|
7827
7405
|
if (input.ghAvailable) channels.push({ kind: "gh", proxy: proxyUrl });
|
|
@@ -7832,14 +7410,11 @@ function resolveDownloadChannels(input) {
|
|
|
7832
7410
|
}
|
|
7833
7411
|
function resolveReleaseQuery(input) {
|
|
7834
7412
|
const forceDirect = input.isOverride && !input.mirror;
|
|
7835
|
-
const proxy = input.proxyOverride ?? (!forceDirect && input.
|
|
7413
|
+
const proxy = input.proxyOverride ?? (!forceDirect && input.proxyPort !== null ? loopbackHttpUrl(input.proxyPort) : null);
|
|
7836
7414
|
return { proxy, useGh: proxy === null && !forceDirect && input.ghAvailable };
|
|
7837
7415
|
}
|
|
7838
|
-
function ghProbeNeeded(input) {
|
|
7839
|
-
return !input.forceDirect && input.proxyOverride === null;
|
|
7840
|
-
}
|
|
7841
7416
|
function hasGh() {
|
|
7842
|
-
const result =
|
|
7417
|
+
const result = spawnSync8("gh", ["--version"], { stdio: "ignore", timeout: 3e3 });
|
|
7843
7418
|
return !result.error && result.status === 0;
|
|
7844
7419
|
}
|
|
7845
7420
|
function getArch() {
|
|
@@ -7927,10 +7502,9 @@ async function getLatestReleaseViaGh(repo, signal) {
|
|
|
7927
7502
|
async function getLatestRelease(repo, opts) {
|
|
7928
7503
|
if (opts.useGh) {
|
|
7929
7504
|
try {
|
|
7930
|
-
return await getLatestReleaseViaGh(repo, opts.signal);
|
|
7505
|
+
return { release: await getLatestReleaseViaGh(repo, opts.signal), ghFallbackToDirect: false };
|
|
7931
7506
|
} catch (e) {
|
|
7932
7507
|
if (opts.signal?.aborted) throw e;
|
|
7933
|
-
opts.onGhFallback?.();
|
|
7934
7508
|
}
|
|
7935
7509
|
}
|
|
7936
7510
|
const url = `https://api.github.com/repos/${repo}/releases`;
|
|
@@ -7959,16 +7533,11 @@ async function getLatestRelease(repo, opts) {
|
|
|
7959
7533
|
} catch {
|
|
7960
7534
|
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");
|
|
7961
7535
|
}
|
|
7962
|
-
return pickLatestRelease(releases);
|
|
7536
|
+
return { release: pickLatestRelease(releases), ghFallbackToDirect: opts.useGh && !opts.proxy };
|
|
7963
7537
|
}
|
|
7964
7538
|
async function checkUpdate(opts) {
|
|
7965
7539
|
const currentVersion = opts.currentVersion !== void 0 ? opts.currentVersion : getKernelVersion();
|
|
7966
|
-
|
|
7967
|
-
const optsWithFallbackNote = {
|
|
7968
|
-
...opts,
|
|
7969
|
-
onGhFallback: opts.useGh && !opts.proxy ? () => ghFallbackToDirect = true : void 0
|
|
7970
|
-
};
|
|
7971
|
-
const latest = await getLatestRelease(GITHUB_REPO, optsWithFallbackNote);
|
|
7540
|
+
const { release: latest, ghFallbackToDirect } = await getLatestRelease(GITHUB_REPO, opts);
|
|
7972
7541
|
const latestVersion = latest.tag_name;
|
|
7973
7542
|
let needsUpdate = false;
|
|
7974
7543
|
const currentDisplay = currentVersion || "\u672A\u5B89\u88C5";
|
|
@@ -8038,6 +7607,8 @@ function buildGhReleaseDownloadArgs(tag, assetName, dir) {
|
|
|
8038
7607
|
function buildGhDownloadEnv(proxy) {
|
|
8039
7608
|
const env = { ...process.env };
|
|
8040
7609
|
if (proxy) {
|
|
7610
|
+
delete env.no_proxy;
|
|
7611
|
+
delete env.NO_PROXY;
|
|
8041
7612
|
env.HTTPS_PROXY = proxy;
|
|
8042
7613
|
env.https_proxy = proxy;
|
|
8043
7614
|
}
|
|
@@ -8131,7 +7702,7 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
8131
7702
|
if (mirrorIneffective) {
|
|
8132
7703
|
console.warn("\u8B66\u544A: \u955C\u50CF\u524D\u7F00\u672A\u80FD\u4F5C\u7528\u4E8E\u8BE5\u8D44\u4EA7\u5730\u5740\uFF08host \u975E github.com\uFF09\uFF0C\u672C\u6B21\u4E3A\u76F4\u8FDE\u4E0B\u8F7D\uFF1B\u82E5\u76F4\u8FDE\u8D85\u65F6\u53EF\u6539\u7528 gh \u901A\u9053\uFF08mihomo-cli kernel\uFF09");
|
|
8133
7704
|
}
|
|
8134
|
-
const tempDir =
|
|
7705
|
+
const tempDir = fs13.mkdtempSync(path8.join(DIRS.kernel, ".tmp-"));
|
|
8135
7706
|
const tempPath = path8.join(tempDir, path8.basename(asset.name));
|
|
8136
7707
|
const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
|
|
8137
7708
|
try {
|
|
@@ -8185,11 +7756,11 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
8185
7756
|
throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${describeCurlDownloadError(curlResult.status ?? 1)}`);
|
|
8186
7757
|
}
|
|
8187
7758
|
}
|
|
8188
|
-
if (!
|
|
7759
|
+
if (!fs13.existsSync(tempPath)) {
|
|
8189
7760
|
throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
|
|
8190
7761
|
}
|
|
8191
7762
|
if (Number.isFinite(asset.size) && asset.size > 0) {
|
|
8192
|
-
const actual =
|
|
7763
|
+
const actual = fs13.statSync(tempPath).size;
|
|
8193
7764
|
if (actual !== asset.size) {
|
|
8194
7765
|
throw new Error(
|
|
8195
7766
|
`\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
|
|
@@ -8202,11 +7773,11 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
8202
7773
|
}
|
|
8203
7774
|
const foundBinary = path8.join(tempDir, path8.basename(tempPath, ".gz"));
|
|
8204
7775
|
const gzipStdout = await decompressGzip(tempPath);
|
|
8205
|
-
|
|
7776
|
+
fs13.writeFileSync(foundBinary, gzipStdout, { mode: 493 });
|
|
8206
7777
|
if (progressCallback) {
|
|
8207
7778
|
progressCallback("\u6821\u9A8C\u5185\u6838...");
|
|
8208
7779
|
}
|
|
8209
|
-
|
|
7780
|
+
fs13.chmodSync(foundBinary, 493);
|
|
8210
7781
|
const probe = probeKernelVersion(foundBinary);
|
|
8211
7782
|
if (probe.spawnError || probe.status !== 0 || probe.version === null) {
|
|
8212
7783
|
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
|
|
@@ -8219,11 +7790,11 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
8219
7790
|
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`);
|
|
8220
7791
|
}
|
|
8221
7792
|
const targetPath = PATHS.mihomoBinary;
|
|
8222
|
-
|
|
7793
|
+
fs13.renameSync(foundBinary, targetPath);
|
|
8223
7794
|
return { version: latest.tag_name };
|
|
8224
7795
|
} finally {
|
|
8225
7796
|
try {
|
|
8226
|
-
|
|
7797
|
+
fs13.rmSync(tempDir, { recursive: true, force: true });
|
|
8227
7798
|
} catch {
|
|
8228
7799
|
}
|
|
8229
7800
|
}
|
|
@@ -8233,6 +7804,56 @@ async function downloadKernel(progressCallback, channel, latest) {
|
|
|
8233
7804
|
import { execFile as execFile4, spawn as spawn3 } from "child_process";
|
|
8234
7805
|
import net from "net";
|
|
8235
7806
|
import { promisify as promisify4 } from "util";
|
|
7807
|
+
|
|
7808
|
+
// src/proxy-env.ts
|
|
7809
|
+
var PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
|
|
7810
|
+
function isLoopbackHost(host) {
|
|
7811
|
+
const h = host.toLowerCase();
|
|
7812
|
+
return h === "127.0.0.1" || h === "localhost" || h === "::1" || h === "0.0.0.0" || h === "::";
|
|
7813
|
+
}
|
|
7814
|
+
function parseProxyEndpoint(value) {
|
|
7815
|
+
let parsed;
|
|
7816
|
+
try {
|
|
7817
|
+
parsed = new URL(value);
|
|
7818
|
+
if (parsed.hostname === "") parsed = new URL(`http://${value}`);
|
|
7819
|
+
} catch {
|
|
7820
|
+
try {
|
|
7821
|
+
parsed = new URL(`http://${value}`);
|
|
7822
|
+
} catch {
|
|
7823
|
+
return null;
|
|
7824
|
+
}
|
|
7825
|
+
}
|
|
7826
|
+
const host = parsed.hostname.replace(/^\[|\]$/g, "");
|
|
7827
|
+
const defaultPort = parsed.protocol === "http:" ? 80 : parsed.protocol === "https:" ? 443 : null;
|
|
7828
|
+
const port = parsed.port === "" ? defaultPort : Number.parseInt(parsed.port, 10);
|
|
7829
|
+
if (!host || port === null || !Number.isInteger(port)) return null;
|
|
7830
|
+
return { host, port };
|
|
7831
|
+
}
|
|
7832
|
+
function proxyEnvPointsAtSelf(value, selfPort) {
|
|
7833
|
+
const endpoint = parseProxyEndpoint(value);
|
|
7834
|
+
if (!endpoint) return false;
|
|
7835
|
+
return isLoopbackHost(endpoint.host) && endpoint.port === selfPort;
|
|
7836
|
+
}
|
|
7837
|
+
function clearSelfProxyEnv(source, selfPort) {
|
|
7838
|
+
const cleared = {};
|
|
7839
|
+
for (const key of PROXY_ENV_KEYS) {
|
|
7840
|
+
const value = source[key];
|
|
7841
|
+
if (value && proxyEnvPointsAtSelf(value, selfPort)) {
|
|
7842
|
+
cleared[key] = value;
|
|
7843
|
+
delete source[key];
|
|
7844
|
+
}
|
|
7845
|
+
}
|
|
7846
|
+
return cleared;
|
|
7847
|
+
}
|
|
7848
|
+
var clearedSelfProxyEnv = null;
|
|
7849
|
+
function recordClearedProxyEnv(cleared) {
|
|
7850
|
+
clearedSelfProxyEnv = cleared === null ? null : { ...cleared };
|
|
7851
|
+
}
|
|
7852
|
+
function getClearedProxyEnv() {
|
|
7853
|
+
return clearedSelfProxyEnv === null ? null : { ...clearedSelfProxyEnv };
|
|
7854
|
+
}
|
|
7855
|
+
|
|
7856
|
+
// src/commands/update.ts
|
|
8236
7857
|
var execFileAsync3 = promisify4(execFile4);
|
|
8237
7858
|
function restoreProxyEnvForNpm(cleared, listening) {
|
|
8238
7859
|
return cleared !== null && listening ? cleared : {};
|
|
@@ -8362,8 +7983,7 @@ async function collectChecks() {
|
|
|
8362
7983
|
const releaseQuery = resolveReleaseQuery({
|
|
8363
7984
|
mirror: null,
|
|
8364
7985
|
isOverride: false,
|
|
8365
|
-
ghAvailable: kernelProxyPort === null && hasGh(),
|
|
8366
|
-
proxyRunning: earlyState.running,
|
|
7986
|
+
ghAvailable: kernelProbe !== null && kernelProxyPort === null && hasGh(),
|
|
8367
7987
|
proxyPort: kernelProxyPort,
|
|
8368
7988
|
proxyOverride: null
|
|
8369
7989
|
});
|
|
@@ -8385,20 +8005,20 @@ async function collectChecks() {
|
|
|
8385
8005
|
} else {
|
|
8386
8006
|
push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${kernelProbe.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
|
|
8387
8007
|
}
|
|
8388
|
-
if (
|
|
8389
|
-
push("\u5185\u6838\u81EA\u5347\u7EA7\u6B8B\u7559", "warn", `\u4E2D\u65AD\u7684\u4E0B\u8F7D\u6682\u5B58: ${KERNEL_SELF_UPDATE_DIR}`, `rm -rf ${KERNEL_SELF_UPDATE_DIR}`);
|
|
8008
|
+
if (fs14.existsSync(KERNEL_SELF_UPDATE_DIR)) {
|
|
8009
|
+
push("\u5185\u6838\u81EA\u5347\u7EA7\u6B8B\u7559", "warn", `\u4E2D\u65AD\u7684\u4E0B\u8F7D\u6682\u5B58: ${KERNEL_SELF_UPDATE_DIR}`, `rm -rf -- ${shellQuote(KERNEL_SELF_UPDATE_DIR)}`);
|
|
8390
8010
|
}
|
|
8391
|
-
if (
|
|
8392
|
-
push("\u5185\u6838\u81EA\u5347\u7EA7\u5907\u4EFD", "ok", `\u65E7\u5185\u6838\u526F\u672C\uFF08\u9762\u677F\u5347\u7EA7\u81EA\u52A8\u4FDD\u7559\uFF0C\u4F9B\u56DE\u6EDA\uFF1B\u786E\u8BA4\u65B0\u7248\u7A33\u5B9A\u540E\u53EF\u5220: rm -rf ${KERNEL_SELF_BACKUP_DIR}\uFF09`);
|
|
8011
|
+
if (fs14.existsSync(KERNEL_SELF_BACKUP_DIR)) {
|
|
8012
|
+
push("\u5185\u6838\u81EA\u5347\u7EA7\u5907\u4EFD", "ok", `\u65E7\u5185\u6838\u526F\u672C\uFF08\u9762\u677F\u5347\u7EA7\u81EA\u52A8\u4FDD\u7559\uFF0C\u4F9B\u56DE\u6EDA\uFF1B\u786E\u8BA4\u65B0\u7248\u7A33\u5B9A\u540E\u53EF\u5220: rm -rf -- ${shellQuote(KERNEL_SELF_BACKUP_DIR)}\uFF09`);
|
|
8393
8013
|
}
|
|
8394
8014
|
try {
|
|
8395
|
-
|
|
8015
|
+
fs14.accessSync(USER_DATA_DIR, fs14.constants.W_OK);
|
|
8396
8016
|
push("\u6570\u636E\u76EE\u5F55", "ok", USER_DATA_DIR);
|
|
8397
8017
|
} catch {
|
|
8398
8018
|
push("\u6570\u636E\u76EE\u5F55", "fail", `\u4E0D\u53EF\u5199: ${USER_DATA_DIR}`, "\u68C0\u67E5\u76EE\u5F55\u6743\u9650");
|
|
8399
8019
|
}
|
|
8400
|
-
if (
|
|
8401
|
-
if (isValidSettingsContent(
|
|
8020
|
+
if (fs14.existsSync(PATHS.settingsFile)) {
|
|
8021
|
+
if (isValidSettingsContent(fs14.readFileSync(PATHS.settingsFile, "utf8"))) {
|
|
8402
8022
|
push("\u8BBE\u7F6E\u6587\u4EF6", "ok", "\u683C\u5F0F\u6709\u6548");
|
|
8403
8023
|
} else {
|
|
8404
8024
|
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");
|
|
@@ -8473,8 +8093,7 @@ async function collectChecks() {
|
|
|
8473
8093
|
if (active && hasKernel()) {
|
|
8474
8094
|
try {
|
|
8475
8095
|
const mode = deriveRuntimeMode(info);
|
|
8476
|
-
const
|
|
8477
|
-
const warnings = prepared.buildResult.warnings;
|
|
8096
|
+
const { warnings } = await prepareConfigForStart(mode, active.name);
|
|
8478
8097
|
if (warnings.length > 0) {
|
|
8479
8098
|
push(
|
|
8480
8099
|
"\u914D\u7F6E\u6784\u5EFA",
|
|
@@ -8601,12 +8220,7 @@ function parseMirrorArg(args) {
|
|
|
8601
8220
|
return { mirror: null, isOverride: false };
|
|
8602
8221
|
}
|
|
8603
8222
|
assertKnownFlags(args.slice(1), KERNEL_FLAG_WHITELIST, "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]");
|
|
8604
|
-
const hits = [];
|
|
8605
|
-
for (let i = 0; i < args.length; i++) {
|
|
8606
|
-
const match = matchValueFlagToken(args[i]);
|
|
8607
|
-
if (!match?.spec.forms.includes("--mirror")) continue;
|
|
8608
|
-
hits.push({ value: match.form === "exact" ? args[i + 1] ?? null : match.inlineValue });
|
|
8609
|
-
}
|
|
8223
|
+
const hits = collectFlagValues(args, ["--mirror"]);
|
|
8610
8224
|
if (hits.length === 0) {
|
|
8611
8225
|
return { mirror: null, isOverride: false };
|
|
8612
8226
|
}
|
|
@@ -8664,17 +8278,7 @@ function parseProxyArg(args) {
|
|
|
8664
8278
|
return { proxy: null };
|
|
8665
8279
|
}
|
|
8666
8280
|
assertKnownFlags(args.slice(1), KERNEL_FLAG_WHITELIST, "kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]");
|
|
8667
|
-
const hits = [];
|
|
8668
|
-
for (let i = 0; i < args.length; i++) {
|
|
8669
|
-
const match = matchValueFlagToken(args[i]);
|
|
8670
|
-
if (!match?.spec.forms.includes("--proxy")) continue;
|
|
8671
|
-
if (match.form === "exact") {
|
|
8672
|
-
hits.push(args[i + 1] ?? "");
|
|
8673
|
-
i++;
|
|
8674
|
-
} else {
|
|
8675
|
-
hits.push(match.inlineValue ?? "");
|
|
8676
|
-
}
|
|
8677
|
-
}
|
|
8281
|
+
const hits = collectFlagValues(args, ["--proxy"]);
|
|
8678
8282
|
if (hits.length === 0) {
|
|
8679
8283
|
return { proxy: null };
|
|
8680
8284
|
}
|
|
@@ -8684,7 +8288,7 @@ function parseProxyArg(args) {
|
|
|
8684
8288
|
hint: ["\u7528\u6CD5: mihomo-cli kernel --proxy <\u7AEF\u53E3|\u5730\u5740>", "\u4F8B\u5982: mihomo-cli kernel --proxy 7897"]
|
|
8685
8289
|
});
|
|
8686
8290
|
}
|
|
8687
|
-
const raw = hits[0].trim();
|
|
8291
|
+
const raw = (hits[0].value ?? "").trim();
|
|
8688
8292
|
if (!raw || raw.startsWith("-")) {
|
|
8689
8293
|
throw new CliError("--proxy \u9700\u8981\u4E00\u4E2A\u7AEF\u53E3\u6216\u4EE3\u7406\u5730\u5740", {
|
|
8690
8294
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
@@ -8759,21 +8363,23 @@ async function cmdKernel(args) {
|
|
|
8759
8363
|
const mirrorInfo = parseMirrorArg(args);
|
|
8760
8364
|
const proxyInfo = parseProxyArg(args);
|
|
8761
8365
|
assertPositionalCount(args, 0, 1, "mihomo-cli kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]");
|
|
8762
|
-
|
|
8366
|
+
const forceDirect = mirrorInfo.isOverride && !mirrorInfo.mirror;
|
|
8367
|
+
if (proxyInfo.proxy && forceDirect) {
|
|
8763
8368
|
throw new CliError("--mirror direct \u4E0E --proxy \u4E0D\u80FD\u540C\u65F6\u4F7F\u7528", {
|
|
8764
8369
|
label: "\u53C2\u6570\u9519\u8BEF",
|
|
8765
8370
|
hint: ["--mirror direct \u5F3A\u5236\u4E0D\u7ECF\u4EE3\u7406\u76F4\u8FDE\uFF0C\u9700\u8D70\u4EE3\u7406\u65F6\u53BB\u6389\u5B83:", " mihomo-cli kernel --proxy <\u7AEF\u53E3|\u5730\u5740>"]
|
|
8766
8371
|
});
|
|
8767
8372
|
}
|
|
8768
|
-
const
|
|
8769
|
-
const proxyPort =
|
|
8770
|
-
|
|
8771
|
-
const ghAvailable = ghProbeNeeded({ forceDirect, proxyOverride: proxyInfo.proxy }) && hasGh();
|
|
8373
|
+
const probeLocalChannels = !forceDirect && proxyInfo.proxy === null;
|
|
8374
|
+
const proxyPort = probeLocalChannels && getRunningState().running ? getPortsOrNull()?.mixed ?? null : null;
|
|
8375
|
+
let ghAvailable;
|
|
8772
8376
|
const channelInput = {
|
|
8773
8377
|
mirror: mirrorInfo.mirror,
|
|
8774
8378
|
isOverride: mirrorInfo.isOverride,
|
|
8775
|
-
ghAvailable
|
|
8776
|
-
|
|
8379
|
+
get ghAvailable() {
|
|
8380
|
+
ghAvailable ??= hasGh();
|
|
8381
|
+
return ghAvailable;
|
|
8382
|
+
},
|
|
8777
8383
|
proxyPort,
|
|
8778
8384
|
proxyOverride: proxyInfo.proxy
|
|
8779
8385
|
};
|
|
@@ -8855,35 +8461,21 @@ async function cmdKernel(args) {
|
|
|
8855
8461
|
}
|
|
8856
8462
|
|
|
8857
8463
|
// src/commands/log.ts
|
|
8858
|
-
import fs17 from "fs";
|
|
8859
8464
|
var INVALID_INDEX_HINT = "\u7528\u6CD5: mihomo-cli logs <\u7F16\u53F7>\uFF080=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF09\uFF1B\u67E5\u770B\u5217\u8868: mihomo-cli logs";
|
|
8860
8465
|
function cmdLogs(args) {
|
|
8861
|
-
assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"
|
|
8862
|
-
assertPositionalCount(args, 1, 1, "mihomo-cli logs [
|
|
8466
|
+
assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"], "logs [-f] [-n N] [\u7F16\u53F7] [-o]");
|
|
8467
|
+
assertPositionalCount(args, 1, 1, "mihomo-cli logs [-f] [-n N] [\u7F16\u53F7] [-o]");
|
|
8863
8468
|
const lines = parseIntArg(args, "-n", "--lines", 100);
|
|
8864
8469
|
const openInViewer = hasFlag(args, "-o", "--open");
|
|
8865
8470
|
const follow = hasFlag(args, "-f", "--follow");
|
|
8866
|
-
const hasLinesFlag = args.some((a) => matchValueFlagToken(a)?.spec.forms.includes("-n") === true);
|
|
8867
8471
|
const positional = getNonFlagArg(args, 1);
|
|
8868
|
-
const diagnostic = hasFlag(args, "--diagnostic");
|
|
8869
|
-
if (diagnostic && positional !== null) {
|
|
8870
|
-
throw new CliError("--diagnostic \u4E0E\u5185\u6838\u65E5\u5FD7\u7F16\u53F7\u4E92\u65A5", {
|
|
8871
|
-
hint: ["\u67E5\u770B\u8BCA\u65AD\u4E8B\u4EF6: mihomo-cli logs --diagnostic", "\u67E5\u770B\u5185\u6838\u65E5\u5FD7: mihomo-cli logs <\u7F16\u53F7>"]
|
|
8872
|
-
});
|
|
8873
|
-
}
|
|
8874
8472
|
if (positional === "") {
|
|
8875
8473
|
throw new CliError('\u65E0\u6548\u7684\u65E5\u5FD7\u7F16\u53F7 ""', { hint: INVALID_INDEX_HINT });
|
|
8876
8474
|
}
|
|
8877
|
-
|
|
8878
|
-
console.log("\u6682\u65E0\u8BCA\u65AD\u4E8B\u4EF6");
|
|
8879
|
-
return;
|
|
8880
|
-
}
|
|
8881
|
-
const targetName = diagnostic ? "0" : positional ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
|
|
8475
|
+
const targetName = positional ?? (args.length > 1 ? "0" : null);
|
|
8882
8476
|
if (targetName) {
|
|
8883
8477
|
let logPath;
|
|
8884
|
-
if (
|
|
8885
|
-
logPath = PATHS.diagnosticEventsFile;
|
|
8886
|
-
} else if (targetName === "0") {
|
|
8478
|
+
if (targetName === "0") {
|
|
8887
8479
|
logPath = PATHS.logFile;
|
|
8888
8480
|
} else {
|
|
8889
8481
|
const parsedIdx = parseInt(targetName, 10);
|
|
@@ -8899,7 +8491,7 @@ function cmdLogs(args) {
|
|
|
8899
8491
|
if (openInViewer) {
|
|
8900
8492
|
if (follow) {
|
|
8901
8493
|
throw new CliError("-o\uFF08\u7CFB\u7EDF\u67E5\u770B\u5668\u6253\u5F00\uFF09\u4E0E -f\uFF08\u7EC8\u7AEF\u8DDF\u968F\uFF09\u4E92\u65A5", {
|
|
8902
|
-
hint:
|
|
8494
|
+
hint: "\u8DDF\u968F\u8F93\u51FA\u8BF7\u53BB\u6389 -o: mihomo-cli logs 0 -f"
|
|
8903
8495
|
});
|
|
8904
8496
|
}
|
|
8905
8497
|
console.log(`\u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00: ${logPath}`);
|
|
@@ -8909,41 +8501,27 @@ function cmdLogs(args) {
|
|
|
8909
8501
|
viewLogWithTail(logPath, { follow, lines });
|
|
8910
8502
|
return;
|
|
8911
8503
|
}
|
|
8912
|
-
const
|
|
8913
|
-
|
|
8914
|
-
if (logs.current) all.push(logs.current);
|
|
8915
|
-
all.push(...logs.archives);
|
|
8916
|
-
if (all.length === 0) {
|
|
8504
|
+
const { current, archives } = listLogs();
|
|
8505
|
+
if (!current && archives.length === 0) {
|
|
8917
8506
|
console.log("\u6682\u65E0\u5185\u6838\u65E5\u5FD7");
|
|
8918
|
-
console.log("\u8BCA\u65AD\u4E8B\u4EF6: mihomo-cli logs --diagnostic");
|
|
8919
8507
|
return;
|
|
8920
8508
|
}
|
|
8921
8509
|
console.log("");
|
|
8922
8510
|
console.log("\u65E5\u5FD7\u5217\u8868:");
|
|
8923
8511
|
console.log("");
|
|
8924
|
-
|
|
8925
|
-
|
|
8926
|
-
|
|
8927
|
-
if (log.isCurrent) {
|
|
8928
|
-
num = " 0";
|
|
8929
|
-
} else {
|
|
8930
|
-
archiveCounter++;
|
|
8931
|
-
num = String(archiveCounter).padStart(2);
|
|
8932
|
-
}
|
|
8933
|
-
const time = formatDate(log.mtime);
|
|
8934
|
-
const size = formatBytes(log.size);
|
|
8935
|
-
const name = log.isCurrent ? "mihomo.log (\u5F53\u524D\u8FD0\u884C\u4E2D)" : log.name;
|
|
8936
|
-
console.log(` ${num}. ${name}`);
|
|
8937
|
-
console.log(` \u65F6\u95F4: ${time} \u5927\u5C0F: ${size}`);
|
|
8512
|
+
const printEntry = (log, index) => {
|
|
8513
|
+
console.log(` ${String(index).padStart(2)}. ${log.name}${index === 0 ? " (\u5F53\u524D\u8FD0\u884C\u4E2D)" : ""}`);
|
|
8514
|
+
console.log(` \u65F6\u95F4: ${formatDate(log.mtime)} \u5927\u5C0F: ${formatBytes(log.size)}`);
|
|
8938
8515
|
console.log("");
|
|
8939
|
-
}
|
|
8516
|
+
};
|
|
8517
|
+
if (current) printEntry(current, 0);
|
|
8518
|
+
for (const [i, log] of archives.entries()) printEntry(log, i + 1);
|
|
8940
8519
|
console.log("\u7528\u6CD5:");
|
|
8941
8520
|
console.log(" mihomo-cli logs 0 # \u67E5\u770B\u5F53\u524D\u65E5\u5FD7 (\u6700\u540E 100 \u884C)");
|
|
8942
8521
|
console.log(" mihomo-cli logs 0 -f # \u5B9E\u65F6\u8DDF\u968F\u5F53\u524D\u65E5\u5FD7");
|
|
8943
8522
|
console.log(" mihomo-cli logs 1 # \u67E5\u770B\u7B2C 1 \u4E2A\u5F52\u6863\u65E5\u5FD7(\u6700\u65B0)");
|
|
8944
8523
|
console.log(" mihomo-cli logs 1 -n 200 # \u67E5\u770B 200 \u884C");
|
|
8945
8524
|
console.log(" mihomo-cli logs 1 -o # \u7528\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00");
|
|
8946
|
-
console.log(" mihomo-cli logs --diagnostic # \u67E5\u770B CLI \u8BCA\u65AD\u4E8B\u4EF6 (JSONL)");
|
|
8947
8525
|
console.log("");
|
|
8948
8526
|
}
|
|
8949
8527
|
|
|
@@ -9034,7 +8612,7 @@ async function cmdOverwrite(args) {
|
|
|
9034
8612
|
}
|
|
9035
8613
|
|
|
9036
8614
|
// src/commands/reset.ts
|
|
9037
|
-
import
|
|
8615
|
+
import fs15 from "fs";
|
|
9038
8616
|
var RESET_TARGETS = [
|
|
9039
8617
|
{ id: "subs", aliases: ["sub", "subs", "subscription", "subscriptions"], label: "\u8BA2\u9605", paths: () => [DIRS.subscriptions], needsStop: true },
|
|
9040
8618
|
{ id: "logs", aliases: ["log", "logs"], label: "\u65E5\u5FD7", paths: () => [DIRS.logs], needsStop: true },
|
|
@@ -9046,7 +8624,7 @@ var RESET_TARGETS = [
|
|
|
9046
8624
|
label: "\u8986\u5199",
|
|
9047
8625
|
needsStop: false,
|
|
9048
8626
|
preserveOnBare: true,
|
|
9049
|
-
paths: () =>
|
|
8627
|
+
paths: () => fs15.existsSync(USER_DATA_DIR) ? fs15.readdirSync(USER_DATA_DIR).filter(isOverwriteFilename).map((f) => `${USER_DATA_DIR}/${f}`) : []
|
|
9050
8628
|
},
|
|
9051
8629
|
{
|
|
9052
8630
|
// 别名刻意不含 'config':用户从 `mihomo-cli config` 命令得到的直觉是「运行配置」
|
|
@@ -9146,7 +8724,7 @@ async function cmdReset(args) {
|
|
|
9146
8724
|
for (const target of targets) {
|
|
9147
8725
|
let hadContent = target.id === "service" && serviceActive;
|
|
9148
8726
|
for (const filePath of target.paths()) {
|
|
9149
|
-
if (!
|
|
8727
|
+
if (!fs15.existsSync(filePath)) continue;
|
|
9150
8728
|
try {
|
|
9151
8729
|
rmrf(filePath);
|
|
9152
8730
|
} catch (e) {
|
|
@@ -9184,7 +8762,7 @@ async function cmdReset(args) {
|
|
|
9184
8762
|
}
|
|
9185
8763
|
|
|
9186
8764
|
// src/commands/service.ts
|
|
9187
|
-
import
|
|
8765
|
+
import fs16 from "fs";
|
|
9188
8766
|
function printRestoreSkipped() {
|
|
9189
8767
|
console.log(colors.yellow("\u672A\u6062\u590D\u8FD0\u884C\uFF1A\u5B89\u88C5\u671F\u95F4\u68C0\u6D4B\u5230\u505C\u6B62\u64CD\u4F5C"));
|
|
9190
8768
|
console.log(colors.gray(" \u53E6\u4E00\u4E2A\u7EC8\u7AEF\u5173\u95ED\u4E86\u670D\u52A1\u81EA\u542F\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62"));
|
|
@@ -9221,7 +8799,7 @@ async function cmdInstall(args) {
|
|
|
9221
8799
|
console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
|
|
9222
8800
|
} else {
|
|
9223
8801
|
console.log("\u542F\u52A8: mihomo-cli start");
|
|
9224
|
-
if (!
|
|
8802
|
+
if (!fs16.existsSync(PATHS.configFile)) {
|
|
9225
8803
|
console.log(colors.gray(" \u5C1A\u65E0\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0Cstart \u4F1A\u5148\u8981\u6C42\u6DFB\u52A0\u8BA2\u9605"));
|
|
9226
8804
|
}
|
|
9227
8805
|
}
|
|
@@ -9289,7 +8867,7 @@ async function cmdStop(args) {
|
|
|
9289
8867
|
}
|
|
9290
8868
|
|
|
9291
8869
|
// src/commands/subscription.ts
|
|
9292
|
-
import { spawnSync as
|
|
8870
|
+
import { spawnSync as spawnSync9 } from "child_process";
|
|
9293
8871
|
function printRestartHintIfRunning(variant = "update") {
|
|
9294
8872
|
const state = getRunningState();
|
|
9295
8873
|
if (!state.running) return;
|
|
@@ -9344,7 +8922,7 @@ function printSubscriptionList() {
|
|
|
9344
8922
|
function readUrlFromClipboard() {
|
|
9345
8923
|
if (!process.stdin.isTTY) return null;
|
|
9346
8924
|
try {
|
|
9347
|
-
const r =
|
|
8925
|
+
const r = spawnSync9("pbpaste", [], { encoding: "utf8", timeout: 3e3 });
|
|
9348
8926
|
if (r.status !== 0) return null;
|
|
9349
8927
|
const text = (r.stdout || "").trim();
|
|
9350
8928
|
return isValidHttpUrl(text) ? text : null;
|
|
@@ -9353,7 +8931,6 @@ function readUrlFromClipboard() {
|
|
|
9353
8931
|
}
|
|
9354
8932
|
}
|
|
9355
8933
|
async function subAdd(args) {
|
|
9356
|
-
setDiagnosticCommand("sub add");
|
|
9357
8934
|
assertPositionalCount(args, 2, 2, "mihomo-cli sub add <url> [name]");
|
|
9358
8935
|
let url = args[2]?.trim();
|
|
9359
8936
|
const name = args[3] === void 0 ? "default" : args[3];
|
|
@@ -9397,7 +8974,6 @@ async function subAdd(args) {
|
|
|
9397
8974
|
printSubscriptionList();
|
|
9398
8975
|
}
|
|
9399
8976
|
async function subUpdate(args) {
|
|
9400
|
-
setDiagnosticCommand("sub update");
|
|
9401
8977
|
assertPositionalCount(args, 1, 2, "mihomo-cli sub update [name]");
|
|
9402
8978
|
const nameArg = getNonFlagArg(args, 2);
|
|
9403
8979
|
const subs = getSubscriptions();
|
|
@@ -9442,7 +9018,6 @@ async function subUpdate(args) {
|
|
|
9442
9018
|
printSubscriptionList();
|
|
9443
9019
|
}
|
|
9444
9020
|
async function subUse(args) {
|
|
9445
|
-
setDiagnosticCommand("sub use");
|
|
9446
9021
|
assertPositionalCount(args, 1, 2, "mihomo-cli sub use <name>");
|
|
9447
9022
|
assertRestartOptionValues(args);
|
|
9448
9023
|
const name = getNonFlagArg(args, 2);
|
|
@@ -9474,7 +9049,6 @@ async function subUse(args) {
|
|
|
9474
9049
|
printSubscriptionList();
|
|
9475
9050
|
}
|
|
9476
9051
|
async function subRemove(args) {
|
|
9477
|
-
setDiagnosticCommand("sub remove");
|
|
9478
9052
|
assertPositionalCount(args, 1, 2, "mihomo-cli sub remove <name>");
|
|
9479
9053
|
const name = getNonFlagArg(args, 2);
|
|
9480
9054
|
const subs = getSubscriptions();
|
|
@@ -9539,7 +9113,7 @@ async function cmdSubscription(args) {
|
|
|
9539
9113
|
}
|
|
9540
9114
|
|
|
9541
9115
|
// src/commands/ui.ts
|
|
9542
|
-
import { spawnSync as
|
|
9116
|
+
import { spawnSync as spawnSync10 } from "child_process";
|
|
9543
9117
|
function resolveUiName(args) {
|
|
9544
9118
|
const raw = getNonFlagArg(args, 1);
|
|
9545
9119
|
const name = (raw ?? "zash").toLowerCase();
|
|
@@ -9550,7 +9124,7 @@ function resolveUiName(args) {
|
|
|
9550
9124
|
}
|
|
9551
9125
|
function copyToClipboard(text) {
|
|
9552
9126
|
try {
|
|
9553
|
-
return
|
|
9127
|
+
return spawnSync10("pbcopy", [], { input: text, timeout: 3e3 }).status === 0;
|
|
9554
9128
|
} catch {
|
|
9555
9129
|
return false;
|
|
9556
9130
|
}
|
|
@@ -9644,8 +9218,8 @@ var COMMANDS = [
|
|
|
9644
9218
|
group: "interface",
|
|
9645
9219
|
usage: [
|
|
9646
9220
|
{
|
|
9647
|
-
signature: "logs [
|
|
9648
|
-
description: "\u88F8 logs \u5217\u5217\u8868\uFF1B0=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF1B\u7701\u7565\u7F16\u53F7\u4F46\u7ED9 -f/-n/-o \u65F6\u770B\u5F53\u524D\u65E5\u5FD7
|
|
9221
|
+
signature: "logs [-f] [-n N] [\u7F16\u53F7] [-o]",
|
|
9222
|
+
description: "\u88F8 logs \u5217\u5217\u8868\uFF1B0=\u5F53\u524D\uFF0C1+=\u5F52\u6863\uFF1B\u7701\u7565\u7F16\u53F7\u4F46\u7ED9 -f/-n/-o \u65F6\u770B\u5F53\u524D\u65E5\u5FD7"
|
|
9649
9223
|
}
|
|
9650
9224
|
]
|
|
9651
9225
|
},
|
|
@@ -9747,18 +9321,8 @@ var COMMANDS = [
|
|
|
9747
9321
|
usage: [{ signature: "version", description: "\u663E\u793A\u7248\u672C" }]
|
|
9748
9322
|
}
|
|
9749
9323
|
];
|
|
9750
|
-
|
|
9751
|
-
|
|
9752
|
-
for (const cmd of COMMANDS) {
|
|
9753
|
-
for (const token of [cmd.name, ...cmd.aliases]) {
|
|
9754
|
-
if (index.has(token)) {
|
|
9755
|
-
throw new Error(`\u547D\u4EE4\u6CE8\u518C\u8868\u5B58\u5728\u91CD\u590D token: "${token}"\uFF08${index.get(token)?.name} \u4E0E ${cmd.name}\uFF09`);
|
|
9756
|
-
}
|
|
9757
|
-
index.set(token, cmd);
|
|
9758
|
-
}
|
|
9759
|
-
}
|
|
9760
|
-
return index;
|
|
9761
|
-
})();
|
|
9324
|
+
assertUniqueTokens(COMMANDS, "\u547D\u4EE4\u6CE8\u518C\u8868");
|
|
9325
|
+
var COMMAND_INDEX = new Map(COMMANDS.flatMap((cmd) => [cmd.name, ...cmd.aliases].map((token) => [token, cmd])));
|
|
9762
9326
|
function findCommand(token) {
|
|
9763
9327
|
return COMMAND_INDEX.get(token);
|
|
9764
9328
|
}
|
|
@@ -9791,10 +9355,9 @@ process.on("unhandledRejection", (reason) => {
|
|
|
9791
9355
|
\u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD: ${errorMessage(reason)}`);
|
|
9792
9356
|
process.exit(1);
|
|
9793
9357
|
});
|
|
9794
|
-
var PROXY_ENV_KEYS = ["http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"];
|
|
9795
9358
|
function readSelfMixedPortEarly() {
|
|
9796
9359
|
try {
|
|
9797
|
-
const raw = JSON.parse(
|
|
9360
|
+
const raw = JSON.parse(fs17.readFileSync(PATHS.settingsFile, "utf8"));
|
|
9798
9361
|
const mixed = raw?.ports?.mixed;
|
|
9799
9362
|
if (isValidPortNumber(mixed)) return mixed;
|
|
9800
9363
|
} catch {
|
|
@@ -9802,22 +9365,12 @@ function readSelfMixedPortEarly() {
|
|
|
9802
9365
|
return DEFAULT_MIXED_PORT;
|
|
9803
9366
|
}
|
|
9804
9367
|
function clearProxyEnv() {
|
|
9805
|
-
const
|
|
9806
|
-
const cleared = {};
|
|
9807
|
-
for (const key of PROXY_ENV_KEYS) {
|
|
9808
|
-
const value = process.env[key];
|
|
9809
|
-
if (value && proxyEnvPointsAtSelf(value, selfPort)) {
|
|
9810
|
-
cleared[key] = value;
|
|
9811
|
-
delete process.env[key];
|
|
9812
|
-
}
|
|
9813
|
-
}
|
|
9368
|
+
const cleared = clearSelfProxyEnv(process.env, readSelfMixedPortEarly());
|
|
9814
9369
|
if (Object.keys(cleared).length > 0) recordClearedProxyEnv(cleared);
|
|
9815
9370
|
}
|
|
9816
9371
|
var GUARD_EXEMPT_COMMANDS = /* @__PURE__ */ new Set(["help", "version"]);
|
|
9817
9372
|
function assertNotRoot(commandName) {
|
|
9818
|
-
|
|
9819
|
-
if (uid !== 0) return;
|
|
9820
|
-
if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
|
|
9373
|
+
if (!isRoot()) return;
|
|
9821
9374
|
throw new CliError("\u8BF7\u4E0D\u8981\u7528 sudo \u8FD0\u884C mihomo-cli", {
|
|
9822
9375
|
label: "\u8EAB\u4EFD\u9519\u8BEF",
|
|
9823
9376
|
hint: [
|
|
@@ -9831,9 +9384,8 @@ function assertNotRoot(commandName) {
|
|
|
9831
9384
|
]
|
|
9832
9385
|
});
|
|
9833
9386
|
}
|
|
9834
|
-
function assertSupportedNodeVersion(
|
|
9387
|
+
function assertSupportedNodeVersion() {
|
|
9835
9388
|
if (!NODE_ENGINES) return;
|
|
9836
|
-
if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
|
|
9837
9389
|
const current = process.versions.node;
|
|
9838
9390
|
if (satisfies(current, NODE_ENGINES)) return;
|
|
9839
9391
|
throw new CliError(`Node \u7248\u672C\u8FC7\u4F4E\uFF08\u5F53\u524D ${current}\uFF0C\u9700\u8981 ${NODE_ENGINES}\uFF09`, {
|
|
@@ -9841,9 +9393,8 @@ function assertSupportedNodeVersion(commandName) {
|
|
|
9841
9393
|
hint: ["\u5347\u7EA7 Node \u540E\u91CD\u8BD5\uFF0C\u4F8B\u5982:", " brew upgrade node", " \u6216\u7528 nvm: nvm install --lts && nvm use --lts", "", `\u5F53\u524D\u89E3\u91CA\u5668: ${process.execPath}`]
|
|
9842
9394
|
});
|
|
9843
9395
|
}
|
|
9844
|
-
function assertSupportedPlatform(
|
|
9396
|
+
function assertSupportedPlatform() {
|
|
9845
9397
|
if (process.platform === "darwin") return;
|
|
9846
|
-
if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
|
|
9847
9398
|
if (process.env.MIHOMO_CLI_ALLOW_ANY_PLATFORM === "1") return;
|
|
9848
9399
|
throw new CliError(`mihomo-cli \u76EE\u524D\u4EC5\u652F\u6301 macOS\uFF08\u5F53\u524D\u5E73\u53F0: ${process.platform}\uFF09`, {
|
|
9849
9400
|
label: "\u5E73\u53F0\u4E0D\u652F\u6301",
|
|
@@ -9857,18 +9408,7 @@ function assertSupportedPlatform(commandName) {
|
|
|
9857
9408
|
async function main() {
|
|
9858
9409
|
clearProxyEnv();
|
|
9859
9410
|
const args = process.argv.slice(2);
|
|
9860
|
-
|
|
9861
|
-
assertSupportedNodeVersion("status");
|
|
9862
|
-
assertSupportedPlatform("status");
|
|
9863
|
-
assertNotRoot("status");
|
|
9864
|
-
ensureDirs();
|
|
9865
|
-
cleanupStaleTmpFiles();
|
|
9866
|
-
beginDiagnosticOperation("status");
|
|
9867
|
-
await printStatus();
|
|
9868
|
-
printShortHelp();
|
|
9869
|
-
return;
|
|
9870
|
-
}
|
|
9871
|
-
const token = args[0].toLowerCase();
|
|
9411
|
+
const token = (args[0] ?? "status").toLowerCase();
|
|
9872
9412
|
const command = findCommand(token);
|
|
9873
9413
|
if (!command) {
|
|
9874
9414
|
const suggestion = suggestSimilar(token, allCommandTokens());
|
|
@@ -9876,14 +9416,13 @@ async function main() {
|
|
|
9876
9416
|
hint: [suggestion.length > 0 ? `\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?` : '\u4F7F\u7528 "mihomo-cli help" \u67E5\u770B\u5E2E\u52A9']
|
|
9877
9417
|
});
|
|
9878
9418
|
}
|
|
9879
|
-
assertSupportedNodeVersion(command.name);
|
|
9880
|
-
assertSupportedPlatform(command.name);
|
|
9881
|
-
assertNotRoot(command.name);
|
|
9882
9419
|
if (!GUARD_EXEMPT_COMMANDS.has(command.name)) {
|
|
9420
|
+
assertSupportedNodeVersion();
|
|
9421
|
+
assertSupportedPlatform();
|
|
9422
|
+
assertNotRoot(command.name);
|
|
9883
9423
|
ensureDirs();
|
|
9884
9424
|
cleanupStaleTmpFiles();
|
|
9885
|
-
captureStopEpochBaseline();
|
|
9886
|
-
beginDiagnosticOperation(command.name);
|
|
9425
|
+
if (args.length > 0) captureStopEpochBaseline();
|
|
9887
9426
|
}
|
|
9888
9427
|
if (command.group === "meta") {
|
|
9889
9428
|
assertKnownFlags(args.slice(1), [], command.name);
|
|
@@ -9894,6 +9433,7 @@ async function main() {
|
|
|
9894
9433
|
return;
|
|
9895
9434
|
}
|
|
9896
9435
|
await command.handler(command.rewrite ? command.rewrite(args) : args);
|
|
9436
|
+
if (args.length === 0) printShortHelp();
|
|
9897
9437
|
}
|
|
9898
9438
|
main().catch((e) => {
|
|
9899
9439
|
if (e instanceof CliError) {
|