mihomo-cli 26.9.90 → 26.9.91

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.
Files changed (3) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/index.js +154 -83
  3. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
1
1
  # Changelog
2
2
 
3
+ ## [26.9.91] - 2026-09-30
4
+
5
+ ### 修复
6
+
7
+ - `start tun` 补上对并发 `start` 的防线(此前只有 mixed 侧防「stop 被 start 覆盖」,反方向裸奔):TUN 分支确认服务停着后立即递增停止计数——慢速阶段(订阅更新 + sudo 密码窗口最长 60s)里另一终端 `start` 会在锁内检出变化而放弃启动;`startTun` 执行含 pkill 的 sudo 脚本前再复核一次服务装载状态,检出即中止,否则脚本会杀掉刚起的服务内核、KeepAlive 拉回后与 root TUN 内核互抢端口。
8
+ - 覆写文件写了 `match:` 但条件块缩进笔误(解析成空值)时不再静默全局生效,改为报错并给出正确写法——此前该文件会应用到**所有**订阅,笔误的垃圾键还进最终配置。
9
+ - `https_proxy=localhost:7890`(无协议、localhost 形态)现在能被识别为「指向本机自己的 Mixed 端口」并在启动/下载前清除:curl 与 gh 都认这个形态的代理 env,漏识别时重启内核后下载仍经已死的代理出网,正是这段清除逻辑唯一要防的死锁。
10
+ - 订阅缓存 cache.json 变成「合法 JSON 但不是对象」(如数组/数字)时先备份 `.bak` 再回退空缓存——与 settings.json 的既有处理对齐,此前下一次写缓存会把原件无声覆盖。
11
+ - sudo 脚本改写在数据根目录而非 runtime/:runtime 会被 stop/reset 整体删除,密码窗口内脚本被连带删掉的话,用户输完密码后 sudo 执行不存在的文件,错误被误诊成「密码错误」。
12
+ - 清理 root 属主 pid 文件的 sudo 分支超时对齐统一的 60s 并检查结果:此前自抄 10s,密码输得慢的用户提示被杀、删除从未执行且无人知晓。
13
+
14
+ ### 内部
15
+
16
+ - 删除无消费者的 `StopResult.warning` 字段与探测 curl 恒不可达的 `--connect-timeout` 参数;CLAUDE.md 修正版本查询优先级描述(代理可用直接经代理)并补登 `system-proxy.ts` 模块行。
17
+
18
+ ### 修复(第二轮复审)
19
+
20
+ - 覆写里出现 `__proto__` 键(无论嵌套层还是 `~key` 元素补丁)改为可读报错:此前它会静默把合并结果的原型换掉,写配置时抛带堆栈的裸异常、按程序 bug 渲染,用户无从定位源头。
21
+ - `sub remove` 删原始配置文件挪到设置写盘成功之后(仍在同一锁内):此前先删文件后写设置,磁盘满/权限失败时留下「条目还在、文件已没」的不一致。
22
+ - 原子写补 fsync(临时文件 + rename 后父目录):OS 崩溃/掉电时 settings.json 不再可能截断为空;崩溃遗留的 `*.tmp` 临时文件由每次命令执行时按龄清扫。
23
+ - `doctor` 的内核版本查询超时改为真正中止子进程(AbortSignal 透传 gh/curl/直连三路):此前只弃掉等待,报告打完后进程还要等满子进程自身超时(最长约两分钟)才退出,CI 里体检结论已打印却拿不到退出码。
24
+ - 覆写 `match` 的 `url-domain` 值含 `*`/`?` 时报错:它只做字面后缀比对,通配恒不命中,此前文件静默对任何订阅都不生效且零提示。
25
+ - `mihomo kernel` 在 settings.ports 损坏时降级走 gh/直连(与 doctor/status 同姿态),不再在做任何下载前就中止。
26
+ - `start tun` 的日志轮转挪到内核/配置存在性校验之后:秒失败错误不再先把日志 rename 成归档、留下运行中内核往归档文件写的错位。
27
+ - 逐 pid 清理内核进程在发信号前复核命令行(`isMihomoProcess`):pid 被复用时不再可能误杀无关进程,与批量 pkill 分支的安全性对齐。
28
+ - `logs 0 -f -o` 报互斥错误:`-o` 打开系统查看器后 `-f` 无处生效,静默忽略会让用户以为在跟随刷新。
29
+ - `sub add <url> ""` 报「订阅名不能为空」:不再静默把空串命名成 default(与其他命令对空串位置参数的处理对齐)。
30
+ - settings.json 在并发 `reset` 间隙被删除时不再误报「格式损坏」。
31
+
32
+ ### 内部(第二轮)
33
+
34
+ - `YAML_MAX_ALIASES` 收成共享常量(config/overwrite 两处解析共用);`needsAutoUpdate` 与 `isSubscriptionStale` 对异常时间戳**刻意相反**的口径加用例锁死,防止重构合并去重时悄悄统一。
35
+
3
36
  ## [26.9.90] - 2026-09-29
4
37
 
5
38
  版本号序号修正,无代码变化:26.9.37 的序号误取了当月发布计数,自本版起序号为**全局历史发布计数**(本版是第 90 个发布)。年.月 仍取发布当日日历,序号永不重置。26.9.37 已标记 deprecated,装到该版本执行 `mihomo update` 会直接升到本版。
package/dist/index.js CHANGED
@@ -3121,6 +3121,7 @@ var CHOMPING_KEEP = CHOMPING_MODE.KEEP;
3121
3121
  import { createRequire } from "module";
3122
3122
  var require2 = createRequire(import.meta.url);
3123
3123
  var pkg = require2("../package.json");
3124
+ var YAML_MAX_ALIASES = 200;
3124
3125
  var VERSION = pkg.version;
3125
3126
  var PKG_NAME = pkg.name;
3126
3127
  var MIN_NODE_VERSION = (() => {
@@ -3322,8 +3323,23 @@ var atomicWriteSeq = 0;
3322
3323
  function atomicWriteFileSync(filePath, content, options) {
3323
3324
  const tmp = `${filePath}.${process.pid}.${atomicWriteSeq++}.tmp`;
3324
3325
  try {
3325
- fs.writeFileSync(tmp, content, options);
3326
+ const fd = fs.openSync(tmp, "w", options?.mode ?? 384);
3327
+ try {
3328
+ fs.writeFileSync(fd, content);
3329
+ fs.fsyncSync(fd);
3330
+ } finally {
3331
+ fs.closeSync(fd);
3332
+ }
3326
3333
  fs.renameSync(tmp, filePath);
3334
+ try {
3335
+ const dirFd = fs.openSync(path.dirname(filePath), "r");
3336
+ try {
3337
+ fs.fsyncSync(dirFd);
3338
+ } finally {
3339
+ fs.closeSync(dirFd);
3340
+ }
3341
+ } catch {
3342
+ }
3327
3343
  } catch (e) {
3328
3344
  try {
3329
3345
  fs.unlinkSync(tmp);
@@ -3335,6 +3351,20 @@ function atomicWriteFileSync(filePath, content, options) {
3335
3351
  function rmrf(dir) {
3336
3352
  fs.rmSync(dir, { recursive: true, force: true });
3337
3353
  }
3354
+ function cleanupStaleTmpFiles() {
3355
+ try {
3356
+ const cutoff = Date.now() - 60 * 60 * 1e3;
3357
+ for (const entry of fs.readdirSync(USER_DATA_DIR)) {
3358
+ if (!entry.endsWith(".tmp")) continue;
3359
+ const full = path.join(USER_DATA_DIR, entry);
3360
+ try {
3361
+ if (fs.statSync(full).mtimeMs < cutoff) fs.rmSync(full, { force: true });
3362
+ } catch {
3363
+ }
3364
+ }
3365
+ } catch {
3366
+ }
3367
+ }
3338
3368
  var LOCK_STALE_MS = 1e4;
3339
3369
  var LOCK_RETRY_MS = 20;
3340
3370
  function withFileLock(lockPath, fn, opts) {
@@ -3431,7 +3461,8 @@ function readSettings() {
3431
3461
  const parsed = JSON.parse(fs2.readFileSync(PATHS.settingsFile, "utf8"));
3432
3462
  if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
3433
3463
  return backupCorruptSettings(`\u5185\u5BB9\u4E0D\u662F\u5BF9\u8C61\uFF08\u5F53\u524D\u662F${Array.isArray(parsed) ? "\u6570\u7EC4" : parsed === null ? "null" : typeof parsed}\uFF09`);
3434
- } catch {
3464
+ } catch (e) {
3465
+ if (e.code === "ENOENT") return {};
3435
3466
  return backupCorruptSettings("\u683C\u5F0F\u635F\u574F");
3436
3467
  }
3437
3468
  }
@@ -3446,7 +3477,7 @@ function isValidSettingsContent(content) {
3446
3477
  function writeSettings(settings) {
3447
3478
  return updateSettings(() => settings);
3448
3479
  }
3449
- function updateSettings(mutate) {
3480
+ function updateSettings(mutate, postCommit) {
3450
3481
  ensureDirs();
3451
3482
  return withFileLock(PATHS.settingsLock, () => {
3452
3483
  const current = readSettings();
@@ -3457,6 +3488,7 @@ function updateSettings(mutate) {
3457
3488
  if (value === void 0) delete merged[key];
3458
3489
  }
3459
3490
  atomicWriteFileSync(PATHS.settingsFile, JSON.stringify(merged, null, 2), { mode: 384 });
3491
+ postCommit?.();
3460
3492
  return merged;
3461
3493
  });
3462
3494
  }
@@ -3540,25 +3572,30 @@ function readSubscriptionCache() {
3540
3572
  try {
3541
3573
  const content = fs2.readFileSync(PATHS.subscriptionsCacheFile, "utf8");
3542
3574
  const parsed = JSON.parse(content);
3543
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return empty();
3575
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
3576
+ return backupCorruptSubscriptionCache(`\u5185\u5BB9\u4E0D\u662F\u5BF9\u8C61\uFF08\u5F53\u524D\u662F${Array.isArray(parsed) ? "\u6570\u7EC4" : parsed === null ? "null" : typeof parsed}\uFF09`);
3577
+ }
3544
3578
  return Object.assign(empty(), parsed);
3545
3579
  } catch {
3546
- const cacheBackup = `${PATHS.subscriptionsCacheFile}.bak`;
3547
- try {
3548
- if (fs2.existsSync(cacheBackup)) {
3549
- console.warn(`\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58\u683C\u5F0F\u635F\u574F\uFF0C\u5DF2\u5FFD\u7565\uFF08\u65E9\u524D\u5907\u4EFD\u4FDD\u7559\u5728 ${cacheBackup}\uFF0C\u672A\u8986\u76D6\uFF09`);
3550
- } else {
3551
- fs2.copyFileSync(PATHS.subscriptionsCacheFile, cacheBackup);
3552
- console.warn(`\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58\u683C\u5F0F\u635F\u574F\uFF0C\u5DF2\u5907\u4EFD\u5230 ${cacheBackup}`);
3553
- }
3554
- } catch {
3555
- console.warn("\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58\u683C\u5F0F\u635F\u574F\uFF0C\u5DF2\u5FFD\u7565");
3556
- }
3557
- return empty();
3580
+ return backupCorruptSubscriptionCache("\u683C\u5F0F\u635F\u574F");
3558
3581
  }
3559
3582
  }
3560
3583
  return empty();
3561
3584
  }
3585
+ function backupCorruptSubscriptionCache(reason) {
3586
+ const cacheBackup = `${PATHS.subscriptionsCacheFile}.bak`;
3587
+ try {
3588
+ if (fs2.existsSync(cacheBackup)) {
3589
+ console.warn(`\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58${reason}\uFF0C\u5DF2\u5FFD\u7565\uFF08\u65E9\u524D\u5907\u4EFD\u4FDD\u7559\u5728 ${cacheBackup}\uFF0C\u672A\u8986\u76D6\uFF09`);
3590
+ } else {
3591
+ fs2.copyFileSync(PATHS.subscriptionsCacheFile, cacheBackup);
3592
+ console.warn(`\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58${reason}\uFF0C\u5DF2\u5907\u4EFD\u5230 ${cacheBackup}`);
3593
+ }
3594
+ } catch {
3595
+ console.warn(`\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58${reason}\uFF0C\u5DF2\u5FFD\u7565`);
3596
+ }
3597
+ return /* @__PURE__ */ Object.create(null);
3598
+ }
3562
3599
  function writeSubscriptionCache(cache) {
3563
3600
  ensureDirs();
3564
3601
  atomicWriteFileSync(PATHS.subscriptionsCacheFile, JSON.stringify(cache, null, 2), { mode: 384 });
@@ -3624,23 +3661,27 @@ function addSubscription(url, name = "default") {
3624
3661
  function removeSubscription(name) {
3625
3662
  let switchedTo = null;
3626
3663
  let found = false;
3627
- updateSettings((settings) => {
3628
- const subs = getSubscriptions(settings);
3629
- const idx = subs.findIndex((s) => s.name === name);
3630
- if (idx < 0) return {};
3631
- found = true;
3632
- subs.splice(idx, 1);
3633
- const updates = { subscriptions: subs };
3634
- if (settings.active_subscription === name) {
3635
- switchedTo = subs.length > 0 ? subs[0].name : null;
3636
- updates.active_subscription = switchedTo ?? void 0;
3637
- }
3638
- try {
3639
- fs2.rmSync(getSubscriptionRawConfigPath(name), { force: true });
3640
- } catch {
3664
+ updateSettings(
3665
+ (settings) => {
3666
+ const subs = getSubscriptions(settings);
3667
+ const idx = subs.findIndex((s) => s.name === name);
3668
+ if (idx < 0) return {};
3669
+ found = true;
3670
+ subs.splice(idx, 1);
3671
+ const updates = { subscriptions: subs };
3672
+ if (settings.active_subscription === name) {
3673
+ switchedTo = subs.length > 0 ? subs[0].name : null;
3674
+ updates.active_subscription = switchedTo ?? void 0;
3675
+ }
3676
+ return updates;
3677
+ },
3678
+ () => {
3679
+ try {
3680
+ fs2.rmSync(getSubscriptionRawConfigPath(name), { force: true });
3681
+ } catch {
3682
+ }
3641
3683
  }
3642
- return updates;
3643
- });
3684
+ );
3644
3685
  if (!found) return null;
3645
3686
  deleteSubscriptionCache(name);
3646
3687
  return switchedTo;
@@ -3767,6 +3808,12 @@ function mergeConfigLevel(target, override, collectors, parseOperators) {
3767
3808
  } else if (isOperatorShapedNestedKey(rawKey)) {
3768
3809
  noteOperatorShapedKey(collectors, rawKey);
3769
3810
  }
3811
+ if (key === "__proto__") {
3812
+ throw new CliError('\u8986\u5199\u91CC\u51FA\u73B0\u4E86 "__proto__" \u952E', {
3813
+ label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
3814
+ hint: ["\u6B63\u5E38 mihomo \u914D\u7F6E\u6CA1\u6709\u8FD9\u4E2A\u952E\uFF0C\u8BF7\u68C0\u67E5\u8986\u5199\u6587\u4EF6\u7684\u5185\u5BB9\u4E0E\u6765\u6E90\u3002"]
3815
+ });
3816
+ }
3770
3817
  const existingValue = result[key];
3771
3818
  if (arrayMergeByName) {
3772
3819
  if (existingValue !== void 0 && !Array.isArray(existingValue)) {
@@ -3855,7 +3902,13 @@ function isOverwriteFilenameTypo(filename) {
3855
3902
  var MATCH_KEYS = /* @__PURE__ */ new Set(["name", "subscription", "url-domain"]);
3856
3903
  var SUBSCRIPTION_KEYS = ["name", "subscription"];
3857
3904
  function normalizeMatch(raw, fileName) {
3858
- if (raw == null) return void 0;
3905
+ if (raw === void 0) return void 0;
3906
+ if (raw === null) {
3907
+ throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 match \u4E3A\u7A7A`, {
3908
+ label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
3909
+ hint: ["match: \u540E\u9762\u8981\u8DDF\u6761\u4EF6\u5757\uFF08\u68C0\u67E5\u7F29\u8FDB\uFF09\uFF0C\u5982:", " match:", " name: edu*"]
3910
+ });
3911
+ }
3859
3912
  if (typeof raw !== "object" || Array.isArray(raw)) {
3860
3913
  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" });
3861
3914
  }
@@ -3884,6 +3937,13 @@ function normalizeMatch(raw, fileName) {
3884
3937
  result.subscriptionKey = key;
3885
3938
  continue;
3886
3939
  }
3940
+ if (key === "url-domain") {
3941
+ const wildcard = arr.find((v) => v.includes("*") || v.includes("?"));
3942
+ if (wildcard) {
3943
+ problems.push(`url-domain \u4E0D\u652F\u6301\u901A\u914D\u7B26\uFF08\u5F53\u524D\u503C "${wildcard}"\uFF09\uFF0C\u53EA\u505A\u5B57\u9762\u540E\u7F00\u6BD4\u5BF9`);
3944
+ continue;
3945
+ }
3946
+ }
3887
3947
  result[key] = arr;
3888
3948
  }
3889
3949
  if (problems.length > 0) {
@@ -4041,7 +4101,7 @@ function readOverwriteFiles() {
4041
4101
  const filePath = path3.join(USER_DATA_DIR, file);
4042
4102
  try {
4043
4103
  const content = fs3.readFileSync(filePath, "utf8");
4044
- const parsed = load(content, { maxAliases: 200 });
4104
+ const parsed = load(content, { maxAliases: YAML_MAX_ALIASES });
4045
4105
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
4046
4106
  const { match, enabled, ...config } = parsed;
4047
4107
  assertNoMetadataKeyLookalikes(config, file);
@@ -4157,6 +4217,7 @@ function proxyEnvPointsAtSelf(value, selfPort) {
4157
4217
  let parsed;
4158
4218
  try {
4159
4219
  parsed = new URL(value);
4220
+ if (parsed.hostname === "") parsed = new URL(`http://${value}`);
4160
4221
  } catch {
4161
4222
  try {
4162
4223
  parsed = new URL(`http://${value}`);
@@ -4518,7 +4579,7 @@ function parseProxyArg(args) {
4518
4579
  }
4519
4580
 
4520
4581
  // src/config.ts
4521
- var SAFE_YAML_LOAD_OPTIONS = { maxAliases: 200 };
4582
+ var SAFE_YAML_LOAD_OPTIONS = { maxAliases: YAML_MAX_ALIASES };
4522
4583
  var LOCKED_CONFIG_KEYS = [
4523
4584
  "mixed-port",
4524
4585
  "port",
@@ -5060,6 +5121,10 @@ function getPid() {
5060
5121
  }
5061
5122
  function isRunning() {
5062
5123
  const pid = getPid();
5124
+ if (!pid) return false;
5125
+ return isMihomoProcess(pid);
5126
+ }
5127
+ function isMihomoProcess(pid) {
5063
5128
  if (!pid) return false;
5064
5129
  return isProcessRunning(pid) && (isProcessCommandMatching(pid, PATHS.mihomoBinary) || isProcessCommandMatching(pid, PATHS.serviceBinary));
5065
5130
  }
@@ -5148,7 +5213,7 @@ function runSudoScript(scriptBody, opts) {
5148
5213
  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");
5149
5214
  }
5150
5215
  ensureDirs();
5151
- const scriptPath = path6.join(DIRS.runtime, opts.file);
5216
+ const scriptPath = path6.join(USER_DATA_DIR, opts.file);
5152
5217
  fs7.writeFileSync(scriptPath, scriptBody, { mode: 448 });
5153
5218
  fs7.chmodSync(scriptPath, 448);
5154
5219
  try {
@@ -5419,6 +5484,7 @@ function killResidualKernels(ctx) {
5419
5484
  const rootPids = pids.filter(isProcessRoot);
5420
5485
  for (const pid of pids) {
5421
5486
  if (rootPids.includes(pid)) continue;
5487
+ if (!isMihomoProcess(pid)) continue;
5422
5488
  try {
5423
5489
  process.kill(pid, "SIGKILL");
5424
5490
  } catch {
@@ -5632,7 +5698,7 @@ async function tryHotReload() {
5632
5698
  body: "{}",
5633
5699
  signal: controller.signal
5634
5700
  });
5635
- return res.status === 204 || res.ok;
5701
+ return res.ok;
5636
5702
  } catch {
5637
5703
  return false;
5638
5704
  } finally {
@@ -6358,13 +6424,13 @@ exit 2
6358
6424
  }
6359
6425
  async function startTun() {
6360
6426
  ensureDirs();
6361
- rotateAndCleanupLogs();
6362
6427
  if (!fs9.existsSync(PATHS.mihomoBinary)) {
6363
6428
  throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
6364
6429
  }
6365
6430
  if (!fs9.existsSync(PATHS.configFile)) {
6366
6431
  throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
6367
6432
  }
6433
+ rotateAndCleanupLogs();
6368
6434
  const logFile = PATHS.logFile;
6369
6435
  if (fs9.existsSync(logFile)) {
6370
6436
  try {
@@ -6385,6 +6451,11 @@ async function startTun() {
6385
6451
  }
6386
6452
  }
6387
6453
  console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
6454
+ if (getServiceStatus().loaded) {
6455
+ throw new CliError("\u53E6\u4E00\u7EC8\u7AEF\u5DF2\u542F\u52A8 Mixed \u670D\u52A1\uFF0CTUN \u672A\u542F\u52A8", {
6456
+ hint: ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo stop", "", "\u4E4B\u540E\u53EF\u91CD\u8BD5 TUN: mihomo start tun"]
6457
+ });
6458
+ }
6388
6459
  runSudoScript(buildTunLaunchScript(), {
6389
6460
  action: "TUN \u542F\u52A8",
6390
6461
  file: "launch-tun.sh",
@@ -6564,20 +6635,7 @@ async function probeProxyConnectivity(port) {
6564
6635
  try {
6565
6636
  const { stdout } = await execFileAsync(
6566
6637
  "curl",
6567
- [
6568
- "-x",
6569
- `http://127.0.0.1:${port}`,
6570
- "-s",
6571
- "-o",
6572
- "/dev/null",
6573
- "-w",
6574
- "%{http_code}",
6575
- "--connect-timeout",
6576
- "3",
6577
- "--max-time",
6578
- String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)),
6579
- PROBE_URL
6580
- ],
6638
+ ["-x", `http://127.0.0.1:${port}`, "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", String(Math.ceil(PROBE_TIMEOUT_MS / 1e3)), PROBE_URL],
6581
6639
  { timeout: PROBE_TIMEOUT_MS + 2e3 }
6582
6640
  );
6583
6641
  const code = Number.parseInt(stdout.trim(), 10);
@@ -6884,6 +6942,8 @@ async function cmdStart(args) {
6884
6942
  console.log(colors.gray("\u5DF2\u4E34\u65F6\u5173\u95ED\u670D\u52A1\u81EA\u542F\uFF08\u907F\u514D\u91CD\u542F\u540E\u670D\u52A1\u62FF TUN \u914D\u7F6E\u542F\u52A8\uFF09"));
6885
6943
  console.log(colors.gray("TUN \u7528\u5B8C\u540E mihomo start \u53EF\u6062\u590D"));
6886
6944
  console.log("");
6945
+ } else {
6946
+ recordServiceStopped();
6887
6947
  }
6888
6948
  } else if (!serviceBefore.installed) {
6889
6949
  if (serviceBefore.loaded) {
@@ -7168,11 +7228,12 @@ function buildGhApiReleaseArgs(repo) {
7168
7228
  return ["api", `repos/${repo}/releases`, "--method", "GET"];
7169
7229
  }
7170
7230
  var GH_API_TIMEOUT = 1e4;
7171
- async function getLatestReleaseViaGh(repo) {
7231
+ async function getLatestReleaseViaGh(repo, signal) {
7172
7232
  const result = await execFileAsync2("gh", buildGhApiReleaseArgs(repo), {
7173
7233
  encoding: "utf8",
7174
7234
  maxBuffer: 50 * 1024 * 1024,
7175
- timeout: GH_API_TIMEOUT
7235
+ timeout: GH_API_TIMEOUT,
7236
+ signal
7176
7237
  });
7177
7238
  return pickLatestRelease(JSON.parse(result.stdout));
7178
7239
  }
@@ -7180,8 +7241,9 @@ async function getLatestRelease(repo, opts = { proxy: null, useGh: false }) {
7180
7241
  const url = `https://api.github.com/repos/${repo}/releases`;
7181
7242
  if (opts.useGh) {
7182
7243
  try {
7183
- return await getLatestReleaseViaGh(repo);
7184
- } catch {
7244
+ return await getLatestReleaseViaGh(repo, opts.signal);
7245
+ } catch (e) {
7246
+ if (opts.signal?.aborted) throw e;
7185
7247
  }
7186
7248
  }
7187
7249
  if (opts.proxy) {
@@ -7190,7 +7252,8 @@ async function getLatestRelease(repo, opts = { proxy: null, useGh: false }) {
7190
7252
  const result = await execFileAsync2("curl", buildReleaseApiCurlArgs(opts.proxy, url), {
7191
7253
  encoding: "utf8",
7192
7254
  maxBuffer: 50 * 1024 * 1024,
7193
- timeout: KERNEL_HTTP_TIMEOUT + 1e4
7255
+ timeout: KERNEL_HTTP_TIMEOUT + 1e4,
7256
+ signal: opts.signal
7194
7257
  });
7195
7258
  stdout = result.stdout;
7196
7259
  } catch (e) {
@@ -7208,7 +7271,7 @@ async function getLatestRelease(repo, opts = { proxy: null, useGh: false }) {
7208
7271
  }
7209
7272
  return pickLatestRelease(releases);
7210
7273
  }
7211
- const response = await HTTP_CLIENT2.get(url, { responseType: "json" });
7274
+ const response = await HTTP_CLIENT2.get(url, { responseType: "json", signal: opts.signal });
7212
7275
  return pickLatestRelease(response.data);
7213
7276
  }
7214
7277
  async function checkUpdate(opts) {
@@ -7462,19 +7525,9 @@ async function cmdUpdate(args = []) {
7462
7525
 
7463
7526
  // src/commands/doctor.ts
7464
7527
  function withTimeout2(promise, ms) {
7465
- return new Promise((resolve, reject) => {
7466
- const timer = setTimeout(() => reject(new Error("timeout")), ms);
7467
- promise.then(
7468
- (v) => {
7469
- clearTimeout(timer);
7470
- resolve(v);
7471
- },
7472
- (e) => {
7473
- clearTimeout(timer);
7474
- reject(e);
7475
- }
7476
- );
7477
- });
7528
+ const controller = new AbortController();
7529
+ const timer = setTimeout(() => controller.abort(), ms);
7530
+ return promise(controller.signal).finally(() => clearTimeout(timer));
7478
7531
  }
7479
7532
  function isPortListening(port) {
7480
7533
  try {
@@ -7498,15 +7551,13 @@ async function collectChecks() {
7498
7551
  kernelProxyPort = null;
7499
7552
  }
7500
7553
  const kernelVersionPromise = hasKernel() ? withTimeout2(
7501
- checkUpdate({
7554
+ (signal) => checkUpdate({
7502
7555
  proxy: kernelProxyPort !== null ? `http://127.0.0.1:${kernelProxyPort}` : null,
7503
- useGh: kernelProxyPort === null && hasGh()
7556
+ useGh: kernelProxyPort === null && hasGh(),
7557
+ signal
7504
7558
  }),
7505
7559
  4e3
7506
- ).then(
7507
- (v) => v,
7508
- () => null
7509
- ) : Promise.resolve(null);
7560
+ ).catch(() => null) : Promise.resolve(null);
7510
7561
  if (!hasKernel()) {
7511
7562
  push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
7512
7563
  } else {
@@ -7693,7 +7744,14 @@ async function cmdKernel(args) {
7693
7744
  });
7694
7745
  }
7695
7746
  const proxyRunning = getRunningState().running;
7696
- const proxyPort = proxyRunning ? getPorts().mixed : null;
7747
+ let proxyPort = null;
7748
+ if (proxyRunning) {
7749
+ try {
7750
+ proxyPort = getPorts().mixed;
7751
+ } catch {
7752
+ proxyPort = null;
7753
+ }
7754
+ }
7697
7755
  const forceDirect = mirrorInfo.isOverride && !mirrorInfo.mirror;
7698
7756
  const ghAvailable = hasGh();
7699
7757
  const channel = resolveDownloadChannel({
@@ -7814,6 +7872,11 @@ function cmdLogs(args) {
7814
7872
  logPath = archive.path;
7815
7873
  }
7816
7874
  if (openInViewer) {
7875
+ if (follow) {
7876
+ throw new CliError("-o\uFF08\u7CFB\u7EDF\u67E5\u770B\u5668\u6253\u5F00\uFF09\u4E0E -f\uFF08\u7EC8\u7AEF\u8DDF\u968F\uFF09\u4E92\u65A5", {
7877
+ hint: "\u8DDF\u968F\u8F93\u51FA\u8BF7\u53BB\u6389 -o: mihomo logs 0 -f"
7878
+ });
7879
+ }
7817
7880
  openLogFile(logPath);
7818
7881
  return;
7819
7882
  }
@@ -7967,9 +8030,9 @@ function clearRuntime() {
7967
8030
  function clearPid() {
7968
8031
  if (!fs12.existsSync(PATHS.pidFile)) return;
7969
8032
  if (isPidFileOwnedByRoot()) {
7970
- try {
7971
- spawnSync8("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
7972
- } catch {
8033
+ const result = spawnSync8("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
8034
+ if (result.error || result.status !== 0) {
8035
+ console.warn("\u8B66\u544A: root \u5C5E\u4E3B\u7684 pid \u6587\u4EF6\u672A\u80FD\u6E05\u7406\uFF08sudo \u5931\u8D25\u6216\u5DF2\u53D6\u6D88\uFF09\uFF0C\u4E0B\u6B21 stop \u4F1A\u518D\u6B21\u5C1D\u8BD5");
7973
8036
  }
7974
8037
  } else {
7975
8038
  try {
@@ -8024,6 +8087,10 @@ async function cleanupAll(forceSudo = false) {
8024
8087
  }
8025
8088
  } else {
8026
8089
  for (const pid of pids) {
8090
+ if (!isMihomoProcess(pid)) {
8091
+ killedCount++;
8092
+ continue;
8093
+ }
8027
8094
  if (killProcess(pid)) {
8028
8095
  killedCount++;
8029
8096
  } else {
@@ -8054,7 +8121,7 @@ async function stop(forceSudo = false) {
8054
8121
  console.log(`\u8FDB\u7A0B PID: ${remaining.join(", ")}`);
8055
8122
  console.log("\u624B\u52A8\u547D\u4EE4: sudo pkill -9 mihomo");
8056
8123
  console.log("");
8057
- return { success: true, warning: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", remaining };
8124
+ return { success: true, remaining };
8058
8125
  }
8059
8126
  clearRuntime();
8060
8127
  return { success: true, killed: result.killed };
@@ -8397,7 +8464,10 @@ function readUrlFromClipboard() {
8397
8464
  async function subAdd(args) {
8398
8465
  assertPositionalCount(args, 2, 2, "mihomo sub add <url> [name]");
8399
8466
  let url = args[2]?.trim();
8400
- const name = args[3] || "default";
8467
+ const name = args[3] === void 0 ? "default" : args[3];
8468
+ if (!name.trim()) {
8469
+ throw new CliError("\u8BA2\u9605\u540D\u4E0D\u80FD\u4E3A\u7A7A", { hint: "\u4E0D\u6307\u5B9A\u540D\u79F0\u65F6\u7701\u7565\u8BE5\u53C2\u6570\u5373\u53EF\uFF08\u9ED8\u8BA4\u540D default\uFF09" });
8470
+ }
8401
8471
  if (!url) {
8402
8472
  const clipped = readUrlFromClipboard();
8403
8473
  if (clipped) {
@@ -8880,6 +8950,7 @@ function assertSupportedPlatform(commandName) {
8880
8950
  }
8881
8951
  async function main() {
8882
8952
  clearProxyEnv();
8953
+ cleanupStaleTmpFiles();
8883
8954
  const args = process.argv.slice(2);
8884
8955
  if (args.length === 0) {
8885
8956
  assertSupportedNodeVersion("status");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mihomo-cli",
3
- "version": "26.9.90",
3
+ "version": "26.9.91",
4
4
  "type": "module",
5
5
  "description": "A terminal-based mihomo (Clash.Meta) client for macOS",
6
6
  "bin": {