mihomo-cli 4.2.2 → 4.2.3

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 CHANGED
@@ -1,6 +1,30 @@
1
1
  # Changelog
2
2
 
3
- ## [4.2.2] - 2026-09-05
3
+ ## [4.2.3] - 2026-09-05
4
+
5
+ 四维度全面扫描(launchd 服务 / 进程生命周期 / 数据层 / 命令层)后修复九项缺陷。共同模式是**防线只铺在主路径**:此前几轮修掉的「报告成功但目标未达成」,同类缺口在 install / tun / stop / uninstall 这些次路径上原样存在。每条都经真实系统实验或复现验证(真实 launchd、三进程锁竞态、真实 release 资产列表),并补了 17 条回归测试(单测 178 → 195)。
6
+
7
+ ### 修复
8
+
9
+ - **`install` 重装恢复运行不再谎报**。重装时若服务原本在跑,装完会恢复运行并打印「已按原状态重新启动」——但判据只有「bootstrap 没报错」。这正是 v4.2.0 给 `start` 修掉的崩溃循环缺陷(launchd 装载成功 ≠ 进程活着),修复当时只铺到了 start。现在重装路径复用同一套健康确认(观察满 1.2s 窗口),失败时附日志尾部,并明确告知「服务已安装成功,仅恢复运行失败」
10
+
11
+ - **TUN 启动判据重写**。此前脚本的验证循环是 0.4s 单次检查、首次存活即收口——实测内核可在启动后 180–540ms 才退出,必然漏检;且 `kill -0` 对僵尸进程(bash 尚未收割的已死子进程)同样返回成功,桩进程实测 10 次中 5 次误报存活。现在观察满 1.2s 窗口(与服务路径对齐),判活以 `ps` 的状态列为准(Z 开头或查不到都算死),CLI 收口复核进程真实存活而非只读 pid 文件
12
+
13
+ - **`stop`/`uninstall` 停不干净时如实报错**。`waitUnloadedSteps` 此前只有等待、没有判定——bootout 未生效时轮询 25 次后静默放行,而任务仍装载着,KeepAlive 约 10s 后把内核拉回,CLI 早已打印「已停止」。现在轮询用尽仍装载即报错;`launchctl` 查询失败(112/125)也不再被当「已卸载」。uninstall 还补上了这段等待,plist 删除失败不再被吞
14
+
15
+ - **`launchctl disable` 不再吞错**。它是「TUN 用完不 stop 直接关机 → 下次开机崩溃循环」防线的第一层,也是开机自启路径上的唯一一层,此前却整体 `|| true`——失败时 CLI 照常提示「已关闭自启」。现在执行后经 `print-disabled` 复核位真生效,失败可见
16
+
17
+ - **`stop`/`tun`/`reset service` 认得遗留 root daemon 了**。v4.0 及更早装的 root LaunchDaemon 带 KeepAlive,`stop` 此前只停用户级服务——root 内核被杀后约 10s 就被拉回,「已停止」成谎报;`reset service` 在仅有 legacy 安装的机器上报「已重置」却原样保留。现在三处与 install/uninstall 一致:检测到即引导清理(需要一次管理员密码,sudo 取消会得到可读的错误而非堆栈)
18
+
19
+ - **文件锁的释放校验所有权**。锁被强夺后(持锁超 10s),原持有者退出临界区时的 `finally` 会无条件删除锁文件——删掉的是**新持有者**的锁,第三方随即直接进入临界区。三进程实测:B/C 并发 4.6s,发生的正是锁要防的静默丢数据,且双方都拿到成功回执。现在锁文件写入 `pid+hrtime` 标识,内容一致才删
20
+
21
+ - **Intel Mac 不再静默装上最低性能档的内核**。上游 release 同时提供 GOAMD64 微架构变体(`-v1`/`-v3` 后缀),而资产按名称排序时 `-v1` 变体恰好排在标准版之前——旧的判据只排除了 `-go`/`-compatible`,漏了它。于是每次内核更新都装上 baseline 构建,下载、大小校验、自检全部通过,CLI 报「已更新」。现在精确匹配标准版命名形态,任何后缀变体都不会再被选中
22
+
23
+ - **覆写 `match` 写错直接报错**。键名拼错(`subscripton`)、值滤空或空块时,此前只 warn 一声然后**对所有订阅生效**——用户写了 match 显然是想限定作用域,静默放宽比报错危险得多。现在加载侧与运行侧一致 fail-closed
24
+
25
+ - **`~proxies` patch 已有节点不再把它踢出自动分组**。patch 订阅已有节点的字段(`~` 的正当用法)不注入新节点,但旧实现照把节点名收进 exclude-filter——节点本就在池子里,被排除后反而从所有 include-all 分组消失,分流静默改变。现在只排除真正新增的节点
26
+
27
+
4
28
 
5
29
  三个「报告成功但其实没做到」的缺陷,均实测复现并回归验证。都是 v4.2.1 那个 pgrep 缺陷的同源问题:把「调用没报错」当成「目标达成」。
6
30
 
package/README.md CHANGED
@@ -225,6 +225,9 @@ mihomo status # 查看状态
225
225
  > **为什么不用 root 服务绕开**:早期版本(v3.0–v4.0)确实用 root LaunchDaemon 绕开了这个限制
226
226
  > (Apple 的规则是「以 root 运行的程序自动获得本地网络访问」——豁免条件是 root,而非「是不是 daemon」),
227
227
  > 代价是每次 `start`/`stop` 都要输管理员密码。权衡后选择免密:授权点一次,密码要输一辈子。
228
+ >
229
+ > 从旧版本升级的用户若还留着 root 安装(`~/Library/LaunchDaemons` 下带 KeepAlive 的幽灵,会抢端口且停不掉),
230
+ > `install`/`uninstall`/`stop`/`tun`/`reset` 检测到它都会引导清理——清理要删 root 属主的文件,需要输一次管理员密码。
228
231
 
229
232
  若确实有局域网节点且始终不弹框、连不通,本地网络授权**没有便捷的重置手段**(它不在 TCC 数据库里,
230
233
  `tccutil reset LocalNetwork` 会直接失败),只能进恢复模式删 `/Library/Preferences/com.apple.networkextension.*.plist`,
@@ -391,6 +394,8 @@ mihomo start --update-timeout=30000 # 长选项 + 等号
391
394
  | `subscription` | 按订阅名匹配(大小写不敏感,与 `sub use` 口径一致) |
392
395
  | `url-domain` | 按订阅 URL 的 hostname 后缀匹配(大小写不敏感) |
393
396
 
397
+ `match` 块**写错会直接报错**(键名拼错、值为空、空块),而不是静默忽略后对所有订阅生效——写了 `match` 显然是想限定作用域,悄悄放宽比报错危险得多。
398
+
394
399
  ### 示例
395
400
 
396
401
  ```yaml
package/dist/index.js CHANGED
@@ -3233,11 +3233,25 @@ var LOCK_RETRY_MS = 20;
3233
3233
  function withFileLock(filePath, fn) {
3234
3234
  const lockPath = `${filePath}.lock`;
3235
3235
  const deadline = Date.now() + LOCK_STALE_MS;
3236
+ const token = `${process.pid}-${process.hrtime.bigint()}`;
3236
3237
  let fd = null;
3237
3238
  while (fd === null) {
3238
3239
  try {
3239
3240
  fd = fs.openSync(lockPath, "wx");
3241
+ fs.writeSync(fd, token);
3240
3242
  } catch (e) {
3243
+ if (fd !== null) {
3244
+ try {
3245
+ fs.closeSync(fd);
3246
+ } catch {
3247
+ }
3248
+ try {
3249
+ fs.rmSync(lockPath, { force: true });
3250
+ } catch {
3251
+ }
3252
+ fd = null;
3253
+ throw e;
3254
+ }
3241
3255
  if (e.code !== "EEXIST") throw e;
3242
3256
  let stale = false;
3243
3257
  try {
@@ -3269,7 +3283,9 @@ function withFileLock(filePath, fn) {
3269
3283
  } catch {
3270
3284
  }
3271
3285
  try {
3272
- fs.rmSync(lockPath, { force: true });
3286
+ if (fs.readFileSync(lockPath, "utf8") === token) {
3287
+ fs.rmSync(lockPath, { force: true });
3288
+ }
3273
3289
  } catch {
3274
3290
  }
3275
3291
  }
@@ -3633,22 +3649,39 @@ var MATCH_KEYS = /* @__PURE__ */ new Set(["subscription", "url-domain"]);
3633
3649
  function normalizeMatch(raw, fileName) {
3634
3650
  if (raw == null) return void 0;
3635
3651
  if (typeof raw !== "object" || Array.isArray(raw)) {
3636
- console.warn(`\u8B66\u544A: \u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 match \u5FC5\u987B\u662F\u5BF9\u8C61\uFF0C\u5DF2\u5FFD\u7565\u4F5C\u7528\u57DF\u9650\u5B9A`);
3637
- return void 0;
3652
+ throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 match \u5FC5\u987B\u662F\u5BF9\u8C61\uFF08subscription / url-domain\uFF09`, { label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF" });
3638
3653
  }
3639
3654
  const result = {};
3640
- let hasValid = false;
3655
+ const problems = [];
3641
3656
  for (const [key, value] of Object.entries(raw)) {
3642
3657
  if (!MATCH_KEYS.has(key)) {
3643
- console.warn(`\u8B66\u544A: \u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 match \u542B\u672A\u77E5\u952E "${key}"\uFF0C\u5DF2\u5FFD\u7565`);
3658
+ problems.push(`\u672A\u77E5\u952E "${key}"`);
3644
3659
  continue;
3645
3660
  }
3646
3661
  const arr = (Array.isArray(value) ? value : [value]).filter((v) => typeof v === "string" && v.length > 0);
3647
- if (arr.length === 0) continue;
3662
+ if (arr.length === 0) {
3663
+ problems.push(`\u952E "${key}" \u7684\u503C\u4E3A\u7A7A\u6216\u65E0\u6709\u6548\u5B57\u7B26\u4E32`);
3664
+ continue;
3665
+ }
3648
3666
  result[key] = arr;
3649
- hasValid = true;
3650
3667
  }
3651
- return hasValid ? result : void 0;
3668
+ if (problems.length > 0) {
3669
+ throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 match \u5B58\u5728\u65E0\u6548\u6761\u4EF6: ${problems.join("\u3001")}`, {
3670
+ label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
3671
+ hint: [
3672
+ "match \u5199\u9519\u65F6\u8BE5\u6587\u4EF6\u4E0D\u4F1A\u9650\u5B9A\u4F5C\u7528\u57DF\u3001\u800C\u662F\u5BF9\u6240\u6709\u8BA2\u9605\u751F\u6548\uFF0C\u6545\u76F4\u63A5\u62A5\u9519\u800C\u975E\u5FFD\u7565\u3002",
3673
+ `\u53EF\u7528\u952E: ${[...MATCH_KEYS].join(", ")}`,
3674
+ "\u793A\u4F8B: match: {subscription: work} \u6216 match: {url-domain: [corp.com, github.com]}"
3675
+ ]
3676
+ });
3677
+ }
3678
+ if (Object.keys(result).length === 0) {
3679
+ throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 match \u4E3A\u7A7A\uFF08\u6CA1\u6709\u4EFB\u4F55\u6761\u4EF6\uFF09`, {
3680
+ label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF",
3681
+ hint: [`\u53EF\u7528\u952E: ${[...MATCH_KEYS].join(", ")}`, "\u793A\u4F8B: match: {subscription: work}"]
3682
+ });
3683
+ }
3684
+ return result;
3652
3685
  }
3653
3686
  function summarizeMatch(match) {
3654
3687
  if (!match) return void 0;
@@ -3709,6 +3742,7 @@ function loadOverwriteFile() {
3709
3742
  console.warn(`\u8B66\u544A: \u8986\u5199\u6587\u4EF6 "${file}" \u9876\u5C42\u5FC5\u987B\u662F\u5BF9\u8C61\uFF0C\u5DF2\u8DF3\u8FC7`);
3710
3743
  }
3711
3744
  } catch (e) {
3745
+ if (e instanceof CliError) throw e;
3712
3746
  console.warn(`\u8B66\u544A: \u8986\u5199\u6587\u4EF6 "${file}" \u89E3\u6790\u5931\u8D25: ${e.message}`);
3713
3747
  }
3714
3748
  }
@@ -3983,7 +4017,7 @@ function parseYamlOrJson(content, errorMsg) {
3983
4017
  function dumpYaml(obj) {
3984
4018
  return dump(obj, { indent: 2, lineWidth: -1 });
3985
4019
  }
3986
- function collectOverwriteProxyNames(overwriteFiles) {
4020
+ function collectOverwriteProxyNames(overwriteFiles, baseProxyNames) {
3987
4021
  const names = [];
3988
4022
  for (const file of overwriteFiles) {
3989
4023
  for (const [key, value] of Object.entries(file.config)) {
@@ -3991,7 +4025,9 @@ function collectOverwriteProxyNames(overwriteFiles) {
3991
4025
  for (const proxy of value) {
3992
4026
  if (proxy && typeof proxy === "object" && "name" in proxy) {
3993
4027
  const name = proxy.name;
3994
- if (typeof name === "string" && name.length > 0) names.push(name);
4028
+ if (typeof name !== "string" || name.length === 0) continue;
4029
+ if (key === "~proxies" && baseProxyNames.has(name)) continue;
4030
+ names.push(name);
3995
4031
  }
3996
4032
  }
3997
4033
  }
@@ -3999,8 +4035,8 @@ function collectOverwriteProxyNames(overwriteFiles) {
3999
4035
  }
4000
4036
  return names;
4001
4037
  }
4002
- function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles) {
4003
- const injectedNames = collectOverwriteProxyNames(overwriteFiles);
4038
+ function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles, baseProxyNames = /* @__PURE__ */ new Set()) {
4039
+ const injectedNames = collectOverwriteProxyNames(overwriteFiles, baseProxyNames);
4004
4040
  if (injectedNames.length === 0) return;
4005
4041
  const groups = config["proxy-groups"];
4006
4042
  if (!groups) return;
@@ -4185,7 +4221,11 @@ function buildConfig(subRawContent, mode, scope) {
4185
4221
  const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
4186
4222
  const withOverwrites = applyOverwrite(subscriptionConfig, overwriteFiles);
4187
4223
  if (overwriteFiles.length > 0) {
4188
- excludeOverwriteProxiesFromIncludeAll(withOverwrites, overwriteFiles);
4224
+ const baseProxies = Array.isArray(subscriptionConfig.proxies) ? subscriptionConfig.proxies : [];
4225
+ const baseProxyNames = new Set(
4226
+ baseProxies.filter((p) => p && typeof p === "object" && typeof p.name === "string").map((p) => p.name)
4227
+ );
4228
+ excludeOverwriteProxiesFromIncludeAll(withOverwrites, overwriteFiles, baseProxyNames);
4189
4229
  }
4190
4230
  const systemConfig = {};
4191
4231
  for (const [key, value] of Object.entries(BASE_CONFIG)) {
@@ -4208,7 +4248,14 @@ function buildConfig(subRawContent, mode, scope) {
4208
4248
  }
4209
4249
  if (mode === "tun") {
4210
4250
  systemConfig.tun = TUN_CONFIG.tun;
4211
- const subDns = withOverwrites.dns || {};
4251
+ const dnsRaw = withOverwrites.dns;
4252
+ if (dnsRaw !== void 0 && (typeof dnsRaw !== "object" || dnsRaw === null || Array.isArray(dnsRaw))) {
4253
+ 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`}`, {
4254
+ label: "\u914D\u7F6E\u9519\u8BEF",
4255
+ 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"]
4256
+ });
4257
+ }
4258
+ const subDns = dnsRaw || {};
4212
4259
  const dns = {};
4213
4260
  if (!("enable" in subDns)) dns.enable = true;
4214
4261
  if (!("enhanced-mode" in subDns)) dns["enhanced-mode"] = "fake-ip";
@@ -4719,13 +4766,30 @@ cd /tmp
4719
4766
  NEW_PID=$!
4720
4767
  echo \${NEW_PID} > "\${PID_FILE}"
4721
4768
 
4722
- # \u9A8C\u8BC1
4723
- for i in 1 2 3 4 5; do
4724
- sleep 0.4
4725
- if kill -0 \${NEW_PID} 2>/dev/null; then
4726
- exit 0
4727
- fi
4769
+ # \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
4770
+ #\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
4771
+ # 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
4772
+ is_alive() {
4773
+ local stat
4774
+ stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
4775
+ case "\${stat}" in
4776
+ Z*|'') return 1 ;;
4777
+ *) return 0 ;;
4778
+ esac
4779
+ }
4780
+
4781
+ # \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
4782
+ # \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
4783
+ # \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
4784
+ i=0
4785
+ while [ $i -lt 12 ]; do
4786
+ sleep 0.1
4787
+ is_alive \${NEW_PID} || break
4788
+ i=$((i+1))
4728
4789
  done
4790
+ if is_alive \${NEW_PID}; then
4791
+ exit 0
4792
+ fi
4729
4793
 
4730
4794
  # \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
4731
4795
  rm -f "\${PID_FILE}" 2>/dev/null || true
@@ -4768,8 +4832,11 @@ async function startTun() {
4768
4832
  });
4769
4833
  await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
4770
4834
  const finalPid = getPid();
4771
- if (!finalPid) {
4772
- throw new CliError("TUN \u542F\u52A8\u5931\u8D25");
4835
+ if (!finalPid || !isRunning()) {
4836
+ const tail = readLogTail();
4837
+ throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
4838
+ hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"]
4839
+ });
4773
4840
  }
4774
4841
  return { success: true, pid: finalPid, mode: "tun" };
4775
4842
  }
@@ -4838,6 +4905,11 @@ function assertLaunchctlQueryOk(status, what) {
4838
4905
  hint: [status === null ? "launchctl \u672A\u80FD\u6267\u884C\uFF08\u7F3A\u5931\u6216\u8D85\u65F6\uFF09\u3002" : "\u8FD9\u4E0D\u4EE3\u8868\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "", `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`]
4839
4906
  });
4840
4907
  }
4908
+ function isServiceDisabledInLaunchd() {
4909
+ const out = runLaunchctl(["print-disabled", bootstrapDomain()]);
4910
+ assertLaunchctlQueryOk(out.status, "print-disabled");
4911
+ return out.status === 0 ? parseDisabledList(out.stdout, SERVICE_LABEL) : false;
4912
+ }
4841
4913
  function getServiceStatus() {
4842
4914
  const installed = isServiceInstalled();
4843
4915
  const print = runLaunchctl(["print", serviceTarget()]);
@@ -4847,9 +4919,7 @@ function getServiceStatus() {
4847
4919
  return { installed: false, loaded: false, running: false, pid: null, disabled: false, lastExitCode: null };
4848
4920
  }
4849
4921
  const { state, pid, lastExitCode } = loaded ? parseServicePrint(print.stdout) : { state: null, pid: null, lastExitCode: null };
4850
- const disabledOut = runLaunchctl(["print-disabled", bootstrapDomain()]);
4851
- assertLaunchctlQueryOk(disabledOut.status, "print-disabled");
4852
- const disabled = disabledOut.status === 0 ? parseDisabledList(disabledOut.stdout, SERVICE_LABEL) : false;
4922
+ const disabled = isServiceDisabledInLaunchd();
4853
4923
  return { installed, loaded, running: state === "running", pid, disabled, lastExitCode };
4854
4924
  }
4855
4925
  async function waitServiceHealthy() {
@@ -4955,12 +5025,16 @@ function cleanupRootResidue() {
4955
5025
  if (rootPids.length === 0 && !pidFileIsRoot) return;
4956
5026
  const script = [
4957
5027
  "#!/bin/bash",
4958
- `pkill -9 -f ${shellQuote(MAIN_INSTANCE_PATTERN)} 2>/dev/null || true`,
5028
+ // pkill 退出码 2/3 是 pattern 编译失败等探测性错误,不能当「没有进程」吞掉
5029
+ // (与 killAllMihomo 只收 0/1 同一原则)
5030
+ `pkill -9 -f ${shellQuote(MAIN_INSTANCE_PATTERN)} 2>/dev/null`,
5031
+ "rc=$?",
5032
+ "[ $rc -le 1 ] || exit 2",
4959
5033
  `rm -f ${shellQuote(PATHS.pidFile)}`,
4960
5034
  "exit 0",
4961
5035
  ""
4962
5036
  ].join("\n");
4963
- runSudoScript(script, { action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B", file: "cleanup-residue.sh" });
5037
+ runSudoScript(script, { action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B", file: "cleanup-residue.sh", codeMessages: { 2: "\u7EC8\u6B62\u6B8B\u7559\u5185\u6838\u5931\u8D25\uFF08pkill \u9000\u51FA\u7801\u5F02\u5E38\uFF09" } });
4964
5038
  }
4965
5039
  function killResidualKernels() {
4966
5040
  const pids = getMihomoPids();
@@ -4977,7 +5051,20 @@ function killResidualKernels() {
4977
5051
  }
4978
5052
  function waitUnloadedSteps() {
4979
5053
  const target = shellQuote(serviceTarget());
4980
- return ["n=0", "while [ $n -lt 25 ]; do", ` launchctl print ${target} >/dev/null 2>&1 || break`, " sleep 0.2", " n=$((n+1))", "done"];
5054
+ return [
5055
+ "n=0",
5056
+ "while [ $n -lt 25 ]; do",
5057
+ ` launchctl print ${target} >/dev/null 2>&1`,
5058
+ " rc=$?",
5059
+ " [ $rc -eq 113 ] && break",
5060
+ " [ $rc -ne 0 ] && exit 6",
5061
+ " sleep 0.2",
5062
+ " n=$((n+1))",
5063
+ "done",
5064
+ `launchctl print ${target} >/dev/null 2>&1; rc=$?`,
5065
+ "[ $rc -eq 0 ] && exit 7",
5066
+ "[ $rc -ne 113 ] && exit 6"
5067
+ ];
4981
5068
  }
4982
5069
  function installService(wasRunning) {
4983
5070
  assertServiceLabelSafe();
@@ -4996,7 +5083,7 @@ function installService(wasRunning) {
4996
5083
  // ~/Library/LaunchAgents 在全新系统上可能不存在;只在缺失时创建,避免改动已有目录权限
4997
5084
  `[ -d ${destDir} ] || mkdir -p ${destDir}`,
4998
5085
  `install -m 644 ${stage} ${dest} || exit 3`,
4999
- ...wasRunning ? [`launchctl enable ${target} || exit 5`, `launchctl bootstrap ${bootstrapDomain()} ${dest} || exit 4`] : [`launchctl disable ${target} 2>/dev/null || true`]
5086
+ ...wasRunning ? [`launchctl enable ${target} || exit 5`, `launchctl bootstrap ${bootstrapDomain()} ${dest} || exit 4`] : []
5000
5087
  ];
5001
5088
  try {
5002
5089
  runLaunchctlSteps(steps, {
@@ -5005,9 +5092,14 @@ function installService(wasRunning) {
5005
5092
  2: "plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09",
5006
5093
  3: `\u5B89\u88C5 plist \u5230 ${path6.dirname(PATHS.userAgentPlist)} \u5931\u8D25`,
5007
5094
  4: "\u88C5\u8F7D\u670D\u52A1\u5931\u8D25\uFF08launchctl bootstrap\uFF09",
5008
- 5: "\u542F\u7528\u670D\u52A1\u5931\u8D25\uFF08launchctl enable\uFF09"
5095
+ 5: "\u542F\u7528\u670D\u52A1\u5931\u8D25\uFF08launchctl enable\uFF09",
5096
+ 6: "\u65E0\u6CD5\u786E\u8BA4\u65E7\u670D\u52A1\u5DF2\u5378\u8F7D\uFF08launchctl \u67E5\u8BE2\u5931\u8D25\uFF09",
5097
+ 7: "\u65E7\u670D\u52A1\u5378\u8F7D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u4ECD\u5904\u4E8E\u88C5\u8F7D\u72B6\u6001"
5009
5098
  }
5010
5099
  });
5100
+ if (!wasRunning) {
5101
+ disableServiceAutoStart();
5102
+ }
5011
5103
  } finally {
5012
5104
  try {
5013
5105
  fs9.unlinkSync(stagePath);
@@ -5038,7 +5130,13 @@ function startService() {
5038
5130
  cleanupRootResidue();
5039
5131
  const target = shellQuote(serviceTarget());
5040
5132
  const dest = shellQuote(PATHS.userAgentPlist);
5041
- runLaunchctlSteps([`launchctl bootout ${target} 2>/dev/null || true`, ...waitUnloadedSteps()], { action: "\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B" });
5133
+ runLaunchctlSteps([`launchctl bootout ${target} 2>/dev/null || true`, ...waitUnloadedSteps()], {
5134
+ action: "\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B",
5135
+ codeMessages: {
5136
+ 6: "\u65E0\u6CD5\u786E\u8BA4\u65E7\u670D\u52A1\u5DF2\u5378\u8F7D\uFF08launchctl \u67E5\u8BE2\u5931\u8D25\uFF09",
5137
+ 7: "\u65E7\u670D\u52A1\u5378\u8F7D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u4ECD\u5904\u4E8E\u88C5\u8F7D\u72B6\u6001"
5138
+ }
5139
+ });
5042
5140
  rotateAndCleanupLogs();
5043
5141
  runLaunchctlSteps([`launchctl enable ${target} || exit 2`, `launchctl bootstrap ${bootstrapDomain()} ${dest} || exit 3`], {
5044
5142
  action: "\u542F\u52A8\u670D\u52A1",
@@ -5048,23 +5146,49 @@ function startService() {
5048
5146
  function disableServiceAutoStart() {
5049
5147
  assertServiceLabelSafe();
5050
5148
  const target = shellQuote(serviceTarget());
5051
- runLaunchctlSteps([`launchctl disable ${target} 2>/dev/null || true`], { action: "\u5173\u95ED\u670D\u52A1\u81EA\u542F" });
5149
+ runLaunchctlSteps([`launchctl disable ${target} || exit 2`], {
5150
+ action: "\u5173\u95ED\u670D\u52A1\u81EA\u542F",
5151
+ codeMessages: { 2: "\u5173\u95ED\u670D\u52A1\u81EA\u542F\u5931\u8D25\uFF08launchctl disable\uFF09" }
5152
+ });
5153
+ if (!isServiceDisabledInLaunchd()) {
5154
+ throw new CliError("\u5173\u95ED\u670D\u52A1\u81EA\u542F\u5931\u8D25\uFF1Adisable \u4F4D\u672A\u751F\u6548", {
5155
+ hint: [`\u624B\u52A8\u786E\u8BA4: launchctl print-disabled ${bootstrapDomain()}`, "", "\u4E0D\u5173\u95ED\u81EA\u542F\u7684\u8BDD\uFF0C\u91CD\u542F\u540E\u670D\u52A1\u4F1A\u62FF TUN \u914D\u7F6E\u53CD\u590D\u62C9\u8D77\u5FC5\u7136\u5931\u8D25\u7684\u5185\u6838\u3002"]
5156
+ });
5157
+ }
5052
5158
  }
5053
5159
  function stopService() {
5054
5160
  assertServiceLabelSafe();
5055
5161
  const target = shellQuote(serviceTarget());
5056
- runLaunchctlSteps([`launchctl bootout ${target} 2>/dev/null || true`, `launchctl disable ${target} 2>/dev/null || true`, ...waitUnloadedSteps()], {
5057
- action: "\u505C\u6B62\u670D\u52A1"
5162
+ runLaunchctlSteps([`launchctl bootout ${target} 2>/dev/null || true`, ...waitUnloadedSteps()], {
5163
+ action: "\u505C\u6B62\u670D\u52A1",
5164
+ codeMessages: {
5165
+ 6: "\u65E0\u6CD5\u786E\u8BA4\u670D\u52A1\u5DF2\u5378\u8F7D\uFF08launchctl \u67E5\u8BE2\u5931\u8D25\uFF09",
5166
+ 7: "\u670D\u52A1\u5378\u8F7D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u4ECD\u5904\u4E8E\u88C5\u8F7D\u72B6\u6001\uFF08bootout \u672A\u751F\u6548\uFF09"
5167
+ }
5058
5168
  });
5169
+ disableServiceAutoStart();
5059
5170
  killResidualKernels();
5060
5171
  }
5061
5172
  function uninstallService() {
5062
5173
  assertServiceLabelSafe();
5063
5174
  const target = shellQuote(serviceTarget());
5064
5175
  runLaunchctlSteps(
5065
- [`launchctl bootout ${target} 2>/dev/null || true`, `launchctl disable ${target} 2>/dev/null || true`, `rm -f ${shellQuote(PATHS.userAgentPlist)}`],
5066
- { action: "\u5378\u8F7D\u670D\u52A1" }
5176
+ [
5177
+ `launchctl bootout ${target} 2>/dev/null || true`,
5178
+ ...waitUnloadedSteps(),
5179
+ // rm 失败被尾部 exit 0 吞掉的话,「已卸载」而 plist 还在——登录时又被扫到
5180
+ `rm -f ${shellQuote(PATHS.userAgentPlist)} || exit 3`
5181
+ ],
5182
+ {
5183
+ action: "\u5378\u8F7D\u670D\u52A1",
5184
+ codeMessages: {
5185
+ 3: `\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09`,
5186
+ 6: "\u65E0\u6CD5\u786E\u8BA4\u670D\u52A1\u5DF2\u5378\u8F7D\uFF08launchctl \u67E5\u8BE2\u5931\u8D25\uFF09",
5187
+ 7: "\u670D\u52A1\u5378\u8F7D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u4ECD\u5904\u4E8E\u88C5\u8F7D\u72B6\u6001\uFF08bootout \u672A\u751F\u6548\uFF09"
5188
+ }
5189
+ }
5067
5190
  );
5191
+ disableServiceAutoStart();
5068
5192
  killResidualKernels();
5069
5193
  try {
5070
5194
  fs9.unlinkSync(PATHS.serviceBinary);
@@ -5175,13 +5299,13 @@ async function launchOrRestart(mode) {
5175
5299
  }
5176
5300
  return assertServiceHealthy();
5177
5301
  }
5178
- async function assertServiceHealthy() {
5302
+ async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
5179
5303
  const health = await waitServiceHealthy();
5180
5304
  if (health.healthy) return health.pid;
5181
5305
  const tail = readLogTail();
5182
5306
  const reason = health.crashed ? `\u5185\u6838\u542F\u52A8\u540E\u7ACB\u5373\u9000\u51FA\uFF08\u9000\u51FA\u7801 ${health.exitCode}\uFF09` : "\u5185\u6838\u672A\u80FD\u8FDB\u5165\u8FD0\u884C\u72B6\u6001";
5183
5307
  throw new CliError(reason, {
5184
- label: "\u542F\u52A8\u5931\u8D25",
5308
+ label,
5185
5309
  hint: [
5186
5310
  ...health.crashed ? ["launchd \u4F1A\u6BCF\u9694\u7EA6 10 \u79D2\u53CD\u590D\u62C9\u8D77\u5B83\uFF0C\u8BF7\u5148\u4FEE\u6B63\u914D\u7F6E\u6216\u6267\u884C mihomo stop\u3002"] : [],
5187
5311
  ...tail.length > 0 ? ["", "--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail] : ["", `\u65E5\u5FD7: ${PATHS.logFile}`],
@@ -5637,6 +5761,13 @@ async function cmdStart(args) {
5637
5761
  const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
5638
5762
  const serviceBefore = getServiceStatus();
5639
5763
  if (targetMode === "tun") {
5764
+ if (detectLegacySystemInstall()) {
5765
+ console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u542F\u52A8 TUN \u524D\u9700\u6E05\u7406"));
5766
+ console.log(colors.gray(" \u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u5220\u9664 root \u62E5\u6709\u7684\u6587\u4EF6\uFF09"));
5767
+ cleanupLegacyInstallOrThrow();
5768
+ console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
5769
+ console.log("");
5770
+ }
5640
5771
  if (serviceBefore.loaded) {
5641
5772
  throw new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
5642
5773
  hint: ["\u4E24\u8005\u4F1A\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\u4E0E\u914D\u7F6E\u3002\u8BF7\u5148\u505C\u6B62\u670D\u52A1:", " mihomo stop", "", "TUN \u7528\u5B8C\u540E mihomo start \u53EF\u6062\u590D\u670D\u52A1"]
@@ -5717,6 +5848,17 @@ async function restartToApply(args) {
5717
5848
  await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
5718
5849
  return true;
5719
5850
  }
5851
+ function cleanupLegacyInstallOrThrow() {
5852
+ try {
5853
+ cleanupLegacySystemInstall();
5854
+ } catch (e) {
5855
+ if (e instanceof CliError) throw e;
5856
+ throw new CliError(e.message, {
5857
+ label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
5858
+ hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
5859
+ });
5860
+ }
5861
+ }
5720
5862
 
5721
5863
  // src/commands/directory.ts
5722
5864
  function openDirectory(args) {
@@ -5878,12 +6020,7 @@ function findMatchingAsset(assets, platform, arch) {
5878
6020
  );
5879
6021
  if (matchingAssets.length === 0) return null;
5880
6022
  if (matchingAssets.length === 1) return matchingAssets[0];
5881
- const standardAsset = matchingAssets.find((a) => {
5882
- const nameWithoutGz = a.name.slice(0, -3);
5883
- const parts = nameWithoutGz.split("-");
5884
- const lastPart = parts[parts.length - 1];
5885
- return /^v?\d+\.\d+\.\d+/.test(lastPart) && !nameWithoutGz.includes("-go") && !nameWithoutGz.includes("-compatible");
5886
- });
6023
+ const standardAsset = matchingAssets.find((a) => new RegExp(`^${escapeRegExp(prefix)}-v?\\d+\\.\\d+\\.\\d+$`).test(a.name.slice(0, -3)));
5887
6024
  return standardAsset || matchingAssets[0];
5888
6025
  }
5889
6026
  async function getLatestRelease(repo) {
@@ -6499,6 +6636,7 @@ var RESET_TARGETS = [
6499
6636
  onAfter: () => {
6500
6637
  const st = getServiceStatus();
6501
6638
  if (st.installed || st.loaded) uninstallService();
6639
+ if (detectLegacySystemInstall()) cleanupLegacyInstallOrThrow();
6502
6640
  },
6503
6641
  checkEmpty: () => !isServiceInstalled() && !getServiceStatus().loaded && !detectLegacySystemInstall(),
6504
6642
  emptyMsg: "\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664"
@@ -6577,6 +6715,9 @@ async function cmdReset(args) {
6577
6715
  } else if (stopsService && serviceActive) {
6578
6716
  console.log(colors.yellow("\u5C06\u505C\u6B62\u670D\u52A1\u5E76\u5173\u95ED\u767B\u5F55\u81EA\u542F\uFF08\u5B89\u88C5\u4FDD\u7559\uFF0Cmihomo start \u53EF\u91CD\u65B0\u542F\u52A8\uFF09"));
6579
6717
  }
6718
+ if (uninstallsService && detectLegacySystemInstall()) {
6719
+ console.log(colors.yellow("\u5C06\u6E05\u7406\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF0C\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF09"));
6720
+ }
6580
6721
  console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
6581
6722
  if (!skipConfirm) {
6582
6723
  if (!await confirmOrThrow("\u786E\u8BA4?", {
@@ -6645,15 +6786,7 @@ async function handleLegacyInstall() {
6645
6786
  console.log(colors.gray(" \u5B83\u4F1A\u4E0E\u65B0\u7684\u7528\u6237\u7EA7\u670D\u52A1\u62A2\u5360\u540C\u4E00\u7EC4\u7AEF\u53E3\uFF0C\u9700\u5148\u6E05\u7406"));
6646
6787
  console.log(colors.gray(" \u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u5220\u9664 root \u62E5\u6709\u7684\u6587\u4EF6\uFF09"));
6647
6788
  console.log("");
6648
- try {
6649
- cleanupLegacySystemInstall();
6650
- } catch (e) {
6651
- if (e instanceof CliError) throw e;
6652
- throw new CliError(e.message, {
6653
- label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
6654
- hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
6655
- });
6656
- }
6789
+ cleanupLegacyInstallOrThrow();
6657
6790
  console.log(`${colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1")}`);
6658
6791
  console.log("");
6659
6792
  }
@@ -6669,6 +6802,15 @@ async function cmdInstall(_args) {
6669
6802
  console.log(colors.gray(` \u767B\u5F55\u9879\u4E0E\u6269\u5C55\u4E2D\u663E\u793A\u4E3A: ${SERVICE_BINARY_NAME}`));
6670
6803
  console.log("");
6671
6804
  if (wasRunning) {
6805
+ try {
6806
+ await assertServiceHealthy("\u6062\u590D\u8FD0\u884C\u5931\u8D25");
6807
+ } catch (e) {
6808
+ if (!(e instanceof CliError)) throw e;
6809
+ throw new CliError(e.message, {
6810
+ label: e.label,
6811
+ hint: [...e.hint, "", "\u670D\u52A1\u5DF2\u5B89\u88C5\u6210\u529F\uFF0C\u4EC5\u6062\u590D\u8FD0\u884C\u5931\u8D25\uFF1B\u4FEE\u6B63\u914D\u7F6E\u540E\u53EF\u6267\u884C mihomo start \u91CD\u8BD5\u3002"]
6812
+ });
6813
+ }
6672
6814
  console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
6673
6815
  } else {
6674
6816
  console.log("\u542F\u52A8: mihomo start");
@@ -6696,7 +6838,7 @@ async function cmdUninstall(_args) {
6696
6838
  }
6697
6839
  if (legacy) {
6698
6840
  console.log(colors.gray("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF0C\u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801"));
6699
- cleanupLegacySystemInstall();
6841
+ cleanupLegacyInstallOrThrow();
6700
6842
  console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
6701
6843
  }
6702
6844
  const remaining = getMihomoPids();
@@ -6717,6 +6859,13 @@ function handleStopResult(result) {
6717
6859
  }
6718
6860
  async function cmdStop(args) {
6719
6861
  assertNoRemovedSshFlag(args);
6862
+ if (detectLegacySystemInstall()) {
6863
+ console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u505C\u6B62\u524D\u9700\u6E05\u7406"));
6864
+ console.log(colors.gray(" \u6E05\u7406\u9700\u8981\u4E00\u6B21\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u5220\u9664 root \u62E5\u6709\u7684\u6587\u4EF6\uFF09"));
6865
+ cleanupLegacyInstallOrThrow();
6866
+ console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
6867
+ console.log("");
6868
+ }
6720
6869
  const status = getServiceStatus();
6721
6870
  const pids = getMihomoPids();
6722
6871
  const needsServiceWork = status.loaded || status.installed && !status.disabled;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mihomo-cli",
3
- "version": "4.2.2",
3
+ "version": "4.2.3",
4
4
  "type": "module",
5
5
  "description": "A terminal-based mihomo (Clash.Meta) client for macOS",
6
6
  "bin": {