mihomo-cli 4.2.2 → 4.2.4

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,46 @@
1
1
  # Changelog
2
2
 
3
- ## [4.2.2] - 2026-09-05
3
+ ## [4.2.4] - 2026-09-05
4
+
5
+ 内部架构清理,无用户可见的功能或行为变更(命令、配置格式、输出均不变)。单测 195 → 203。
6
+
7
+ ### 重构
8
+
9
+ - **service 层去 bash 化**:用户域 launchctl 操作(install/start/stop/uninstall/restart)从「拼 shell 脚本 + 自定义退出码协议」改为直接 `spawnSync` 逐条执行、TS 侧判定。消除了退出码协议这层不可测的 IPC 与 shell 注入面,失败时错误信息带 launchctl 原始 stderr。需要 root 的路径(TUN 启动、遗留清理)保留 sudo 脚本。`waitUntilUnloaded` 改为 async 轮询,停止期间 Ctrl+C 可响应
10
+
11
+ - **命令行选项单表登记**:新增 `src/flags.ts`,`VALUE_FLAGS`(位置参数解析跳过带值选项)与重启透传集合都从单一 `FLAGS` 表派生,替掉 utils.ts 的两张硬编码表——旧设计漏登记即静默失效(`sub use foo -s` 丢选项、`logs -n 200` 的 200 被当位置参数)
12
+
13
+ - **删死代码**:`http.ts` 未使用的 `secret` 选项(零调用,控制器 Bearer 鉴权一直在 service.ts);合并 root/平台守卫的重复豁免名单;`getProcessInfo` 的两次 `ps` 合并为一次
14
+
15
+ ### 文档
16
+
17
+ - CLAUDE.md 瘦身:与代码注释重复的事故叙事换成指针,只留稳定规则与元教训;两条独有的 launchd 实测事实(`plutil -remove` 手工收尾、`KeepAlive.PathState` 否定结论)移入 CODE_REVIEW.md
18
+
19
+ ## [4.2.3] - 2026-09-05
20
+
21
+ 四维度全面扫描(launchd 服务 / 进程生命周期 / 数据层 / 命令层)后修复九项缺陷。共同模式是**防线只铺在主路径**:此前几轮修掉的「报告成功但目标未达成」,同类缺口在 install / tun / stop / uninstall 这些次路径上原样存在。每条都经真实系统实验或复现验证(真实 launchd、三进程锁竞态、真实 release 资产列表),并补了 17 条回归测试(单测 178 → 195)。
22
+
23
+ ### 修复
24
+
25
+ - **`install` 重装恢复运行不再谎报**。重装时若服务原本在跑,装完会恢复运行并打印「已按原状态重新启动」——但判据只有「bootstrap 没报错」。这正是 v4.2.0 给 `start` 修掉的崩溃循环缺陷(launchd 装载成功 ≠ 进程活着),修复当时只铺到了 start。现在重装路径复用同一套健康确认(观察满 1.2s 窗口),失败时附日志尾部,并明确告知「服务已安装成功,仅恢复运行失败」
26
+
27
+ - **TUN 启动判据重写**。此前脚本的验证循环是 0.4s 单次检查、首次存活即收口——实测内核可在启动后 180–540ms 才退出,必然漏检;且 `kill -0` 对僵尸进程(bash 尚未收割的已死子进程)同样返回成功,桩进程实测 10 次中 5 次误报存活。现在观察满 1.2s 窗口(与服务路径对齐),判活以 `ps` 的状态列为准(Z 开头或查不到都算死),CLI 收口复核进程真实存活而非只读 pid 文件
28
+
29
+ - **`stop`/`uninstall` 停不干净时如实报错**。`waitUnloadedSteps` 此前只有等待、没有判定——bootout 未生效时轮询 25 次后静默放行,而任务仍装载着,KeepAlive 约 10s 后把内核拉回,CLI 早已打印「已停止」。现在轮询用尽仍装载即报错;`launchctl` 查询失败(112/125)也不再被当「已卸载」。uninstall 还补上了这段等待,plist 删除失败不再被吞
30
+
31
+ - **`launchctl disable` 不再吞错**。它是「TUN 用完不 stop 直接关机 → 下次开机崩溃循环」防线的第一层,也是开机自启路径上的唯一一层,此前却整体 `|| true`——失败时 CLI 照常提示「已关闭自启」。现在执行后经 `print-disabled` 复核位真生效,失败可见
32
+
33
+ - **`stop`/`tun`/`reset service` 认得遗留 root daemon 了**。v4.0 及更早装的 root LaunchDaemon 带 KeepAlive,`stop` 此前只停用户级服务——root 内核被杀后约 10s 就被拉回,「已停止」成谎报;`reset service` 在仅有 legacy 安装的机器上报「已重置」却原样保留。现在三处与 install/uninstall 一致:检测到即引导清理(需要一次管理员密码,sudo 取消会得到可读的错误而非堆栈)
34
+
35
+ - **文件锁的释放校验所有权**。锁被强夺后(持锁超 10s),原持有者退出临界区时的 `finally` 会无条件删除锁文件——删掉的是**新持有者**的锁,第三方随即直接进入临界区。三进程实测:B/C 并发 4.6s,发生的正是锁要防的静默丢数据,且双方都拿到成功回执。现在锁文件写入 `pid+hrtime` 标识,内容一致才删
36
+
37
+ - **Intel Mac 不再静默装上最低性能档的内核**。上游 release 同时提供 GOAMD64 微架构变体(`-v1`/`-v3` 后缀),而资产按名称排序时 `-v1` 变体恰好排在标准版之前——旧的判据只排除了 `-go`/`-compatible`,漏了它。于是每次内核更新都装上 baseline 构建,下载、大小校验、自检全部通过,CLI 报「已更新」。现在精确匹配标准版命名形态,任何后缀变体都不会再被选中
38
+
39
+ - **覆写 `match` 写错直接报错**。键名拼错(`subscripton`)、值滤空或空块时,此前只 warn 一声然后**对所有订阅生效**——用户写了 match 显然是想限定作用域,静默放宽比报错危险得多。现在加载侧与运行侧一致 fail-closed
40
+
41
+ - **`~proxies` patch 已有节点不再把它踢出自动分组**。patch 订阅已有节点的字段(`~` 的正当用法)不注入新节点,但旧实现照把节点名收进 exclude-filter——节点本就在池子里,被排除后反而从所有 include-all 分组消失,分流静默改变。现在只排除真正新增的节点
42
+
43
+
4
44
 
5
45
  三个「报告成功但其实没做到」的缺陷,均实测复现并回归验证。都是 v4.2.1 那个 pgrep 缺陷的同源问题:把「调用没报错」当成「目标达成」。
6
46
 
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
  }
@@ -3739,6 +3773,20 @@ function listOverwriteFile() {
3739
3773
  };
3740
3774
  }
3741
3775
 
3776
+ // src/flags.ts
3777
+ var FLAGS = [
3778
+ // === start 的选项(重启透传) ===
3779
+ { forms: ["-s", "--no-update"], takesValue: false, passthroughToRestart: true },
3780
+ { forms: ["-u", "--update-timeout"], takesValue: true, passthroughToRestart: true },
3781
+ // === logs 的选项 ===
3782
+ { forms: ["-n", "--lines"], takesValue: true }
3783
+ // 注意:`--mirror`(kernel)是可选值选项——`--mirror`、`--mirror=url`、`--mirror url`
3784
+ // 三种形式都合法,只走 parseMirrorArg。故意不在此登记:登记了 getNonFlagArg 反而会
3785
+ // 把它的值吞掉。它的移除/校验由 parseMirrorArg 自己负责。
3786
+ ];
3787
+ var VALUE_FLAGS = new Set(FLAGS.filter((f) => f.takesValue).flatMap((f) => f.forms));
3788
+ var START_RESTART_FLAGS = FLAGS.filter((f) => f.passthroughToRestart);
3789
+
3742
3790
  // src/utils.ts
3743
3791
  function sleep(ms) {
3744
3792
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -3849,18 +3897,16 @@ function assertNoRemovedSshFlag(args) {
3849
3897
  ]
3850
3898
  });
3851
3899
  }
3852
- var VALUE_FLAGS = /* @__PURE__ */ new Set(["-n", "--lines", "-u", "--update-timeout"]);
3853
3900
  function extractStartOptions(args) {
3854
3901
  if (!args) return [];
3855
- const BOOL_FLAGS = /* @__PURE__ */ new Set(["-s", "--no-update"]);
3856
3902
  const out = [];
3857
3903
  for (let i = 0; i < args.length; i++) {
3858
3904
  const a = args[i];
3859
- if (VALUE_FLAGS.has(a)) {
3860
- out.push(a);
3905
+ const spec = START_RESTART_FLAGS.find((f) => f.forms.includes(a) || f.forms.some((form) => form.startsWith("--") && a.startsWith(`${form}=`)));
3906
+ if (!spec) continue;
3907
+ out.push(a);
3908
+ if (spec.takesValue && !a.includes("=")) {
3861
3909
  if (i + 1 < args.length) out.push(args[++i]);
3862
- } else if (BOOL_FLAGS.has(a) || /^--update-timeout=/.test(a)) {
3863
- out.push(a);
3864
3910
  }
3865
3911
  }
3866
3912
  return out;
@@ -3983,7 +4029,7 @@ function parseYamlOrJson(content, errorMsg) {
3983
4029
  function dumpYaml(obj) {
3984
4030
  return dump(obj, { indent: 2, lineWidth: -1 });
3985
4031
  }
3986
- function collectOverwriteProxyNames(overwriteFiles) {
4032
+ function collectOverwriteProxyNames(overwriteFiles, baseProxyNames) {
3987
4033
  const names = [];
3988
4034
  for (const file of overwriteFiles) {
3989
4035
  for (const [key, value] of Object.entries(file.config)) {
@@ -3991,7 +4037,9 @@ function collectOverwriteProxyNames(overwriteFiles) {
3991
4037
  for (const proxy of value) {
3992
4038
  if (proxy && typeof proxy === "object" && "name" in proxy) {
3993
4039
  const name = proxy.name;
3994
- if (typeof name === "string" && name.length > 0) names.push(name);
4040
+ if (typeof name !== "string" || name.length === 0) continue;
4041
+ if (key === "~proxies" && baseProxyNames.has(name)) continue;
4042
+ names.push(name);
3995
4043
  }
3996
4044
  }
3997
4045
  }
@@ -3999,8 +4047,8 @@ function collectOverwriteProxyNames(overwriteFiles) {
3999
4047
  }
4000
4048
  return names;
4001
4049
  }
4002
- function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles) {
4003
- const injectedNames = collectOverwriteProxyNames(overwriteFiles);
4050
+ function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles, baseProxyNames = /* @__PURE__ */ new Set()) {
4051
+ const injectedNames = collectOverwriteProxyNames(overwriteFiles, baseProxyNames);
4004
4052
  if (injectedNames.length === 0) return;
4005
4053
  const groups = config["proxy-groups"];
4006
4054
  if (!groups) return;
@@ -4185,7 +4233,11 @@ function buildConfig(subRawContent, mode, scope) {
4185
4233
  const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
4186
4234
  const withOverwrites = applyOverwrite(subscriptionConfig, overwriteFiles);
4187
4235
  if (overwriteFiles.length > 0) {
4188
- excludeOverwriteProxiesFromIncludeAll(withOverwrites, overwriteFiles);
4236
+ const baseProxies = Array.isArray(subscriptionConfig.proxies) ? subscriptionConfig.proxies : [];
4237
+ const baseProxyNames = new Set(
4238
+ baseProxies.filter((p) => p && typeof p === "object" && typeof p.name === "string").map((p) => p.name)
4239
+ );
4240
+ excludeOverwriteProxiesFromIncludeAll(withOverwrites, overwriteFiles, baseProxyNames);
4189
4241
  }
4190
4242
  const systemConfig = {};
4191
4243
  for (const [key, value] of Object.entries(BASE_CONFIG)) {
@@ -4208,7 +4260,14 @@ function buildConfig(subRawContent, mode, scope) {
4208
4260
  }
4209
4261
  if (mode === "tun") {
4210
4262
  systemConfig.tun = TUN_CONFIG.tun;
4211
- const subDns = withOverwrites.dns || {};
4263
+ const dnsRaw = withOverwrites.dns;
4264
+ if (dnsRaw !== void 0 && (typeof dnsRaw !== "object" || dnsRaw === null || Array.isArray(dnsRaw))) {
4265
+ 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`}`, {
4266
+ label: "\u914D\u7F6E\u9519\u8BEF",
4267
+ 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"]
4268
+ });
4269
+ }
4270
+ const subDns = dnsRaw || {};
4212
4271
  const dns = {};
4213
4272
  if (!("enable" in subDns)) dns.enable = true;
4214
4273
  if (!("enhanced-mode" in subDns)) dns["enhanced-mode"] = "fake-ip";
@@ -4625,14 +4684,15 @@ function checkStaleState() {
4625
4684
  }
4626
4685
  function getProcessInfo(pid) {
4627
4686
  try {
4628
- const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss="], { encoding: "utf8", timeout: 5e3 });
4687
+ const result = spawnSync2("ps", ["-p", String(pid), "-o", "rss=,uid="], { encoding: "utf8", timeout: 5e3 });
4629
4688
  const psOutput = (result.stdout || "").trim();
4630
4689
  if (!psOutput) return null;
4631
- const rss = parseInt(psOutput, 10);
4690
+ const [rssRaw, uidRaw] = psOutput.split(/\s+/);
4691
+ const rss = parseInt(rssRaw, 10);
4632
4692
  return {
4633
4693
  pid,
4634
4694
  memory: rss ? `${(rss / 1024).toFixed(1)} MB` : "\u672A\u77E5",
4635
- isRoot: isProcessRoot(pid)
4695
+ isRoot: uidRaw === "0"
4636
4696
  };
4637
4697
  } catch {
4638
4698
  return { pid, memory: "\u672A\u77E5", isRoot: false };
@@ -4719,13 +4779,30 @@ cd /tmp
4719
4779
  NEW_PID=$!
4720
4780
  echo \${NEW_PID} > "\${PID_FILE}"
4721
4781
 
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
4782
+ # \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
4783
+ #\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
4784
+ # 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
4785
+ is_alive() {
4786
+ local stat
4787
+ stat=$(ps -p "$1" -o stat= 2>/dev/null) || return 1
4788
+ case "\${stat}" in
4789
+ Z*|'') return 1 ;;
4790
+ *) return 0 ;;
4791
+ esac
4792
+ }
4793
+
4794
+ # \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
4795
+ # \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
4796
+ # \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
4797
+ i=0
4798
+ while [ $i -lt 12 ]; do
4799
+ sleep 0.1
4800
+ is_alive \${NEW_PID} || break
4801
+ i=$((i+1))
4728
4802
  done
4803
+ if is_alive \${NEW_PID}; then
4804
+ exit 0
4805
+ fi
4729
4806
 
4730
4807
  # \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
4808
  rm -f "\${PID_FILE}" 2>/dev/null || true
@@ -4768,8 +4845,11 @@ async function startTun() {
4768
4845
  });
4769
4846
  await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
4770
4847
  const finalPid = getPid();
4771
- if (!finalPid) {
4772
- throw new CliError("TUN \u542F\u52A8\u5931\u8D25");
4848
+ if (!finalPid || !isRunning()) {
4849
+ const tail = readLogTail();
4850
+ throw new CliError("TUN \u542F\u52A8\u5931\u8D25\uFF08\u5185\u6838\u672A\u80FD\u4FDD\u6301\u8FD0\u884C\uFF09", {
4851
+ hint: [...tail.length > 0 ? ["--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail, ""] : [`\u65E5\u5FD7: ${PATHS.logFile}`], "", "\u5B8C\u6574\u65E5\u5FD7: mihomo logs 0"]
4852
+ });
4773
4853
  }
4774
4854
  return { success: true, pid: finalPid, mode: "tun" };
4775
4855
  }
@@ -4824,12 +4904,12 @@ function parseDisabledList(output, label) {
4824
4904
  return value === "true" || value === "disabled";
4825
4905
  }
4826
4906
  var LAUNCHCTL_NOT_LOADED = 113;
4827
- function runLaunchctl(args) {
4907
+ function runLaunchctl(args, timeoutMs = LAUNCHCTL_TIMEOUT_MS) {
4828
4908
  try {
4829
- const result = spawnSync4("launchctl", args, { encoding: "utf8", timeout: LAUNCHCTL_TIMEOUT_MS });
4830
- return { status: result.status, stdout: result.stdout || "" };
4909
+ const result = spawnSync4("launchctl", args, { encoding: "utf8", timeout: timeoutMs });
4910
+ return { status: result.status, stdout: result.stdout || "", stderr: result.stderr || "" };
4831
4911
  } catch {
4832
- return { status: null, stdout: "" };
4912
+ return { status: null, stdout: "", stderr: "" };
4833
4913
  }
4834
4914
  }
4835
4915
  function assertLaunchctlQueryOk(status, what) {
@@ -4838,6 +4918,11 @@ function assertLaunchctlQueryOk(status, what) {
4838
4918
  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
4919
  });
4840
4920
  }
4921
+ function isServiceDisabledInLaunchd() {
4922
+ const out = runLaunchctl(["print-disabled", bootstrapDomain()]);
4923
+ assertLaunchctlQueryOk(out.status, "print-disabled");
4924
+ return out.status === 0 ? parseDisabledList(out.stdout, SERVICE_LABEL) : false;
4925
+ }
4841
4926
  function getServiceStatus() {
4842
4927
  const installed = isServiceInstalled();
4843
4928
  const print = runLaunchctl(["print", serviceTarget()]);
@@ -4847,9 +4932,7 @@ function getServiceStatus() {
4847
4932
  return { installed: false, loaded: false, running: false, pid: null, disabled: false, lastExitCode: null };
4848
4933
  }
4849
4934
  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;
4935
+ const disabled = isServiceDisabledInLaunchd();
4853
4936
  return { installed, loaded, running: state === "running", pid, disabled, lastExitCode };
4854
4937
  }
4855
4938
  async function waitServiceHealthy() {
@@ -4934,33 +5017,54 @@ function ensureServiceSymlink() {
4934
5017
  }
4935
5018
  fs9.symlinkSync("mihomo", PATHS.serviceBinary);
4936
5019
  }
4937
- function runLaunchctlSteps(steps, opts) {
4938
- const script = ["#!/bin/bash", ...steps, "exit 0", ""].join("\n");
4939
- const result = spawnSync4("/bin/bash", ["-c", script], { stdio: "inherit", timeout: 6e4 });
4940
- if (result.error) throw result.error;
4941
- if (result.status !== 0) {
4942
- const custom = result.status !== null ? opts.codeMessages?.[result.status] : void 0;
4943
- throw new CliError(custom || `${opts.action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${result.status ?? "\u4FE1\u53F7\u4E2D\u65AD"}\uFF09`);
5020
+ function runLaunchctlOrThrow(args, what) {
5021
+ const result = runLaunchctl(args);
5022
+ if (result.status === 0) return;
5023
+ const detail = result.stderr.trim();
5024
+ throw new CliError(`${what}\u5931\u8D25\uFF08launchctl \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5025
+ hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl ${args.join(" ")}`].filter(Boolean)
5026
+ });
5027
+ }
5028
+ function bootoutService() {
5029
+ const result = runLaunchctl(["bootout", serviceTarget()]);
5030
+ if (result.status === 0 || result.status === 3 || result.status === LAUNCHCTL_NOT_LOADED) return;
5031
+ const detail = result.stderr.trim();
5032
+ throw new CliError(`\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B\u5931\u8D25\uFF08launchctl bootout \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5033
+ hint: [detail, `\u624B\u52A8\u786E\u8BA4: launchctl print ${serviceTarget()}`].filter(Boolean)
5034
+ });
5035
+ }
5036
+ var UNLOADED_POLL_ATTEMPTS = 25;
5037
+ var UNLOADED_POLL_INTERVAL_MS = 200;
5038
+ async function waitUntilUnloaded(target = serviceTarget()) {
5039
+ for (let i = 0; i < UNLOADED_POLL_ATTEMPTS; i++) {
5040
+ const result = runLaunchctl(["print", target]);
5041
+ if (result.status === LAUNCHCTL_NOT_LOADED) return;
5042
+ if (result.status !== 0) {
5043
+ throw new CliError(`\u65E0\u6CD5\u786E\u8BA4\u670D\u52A1\u5DF2\u5378\u8F7D\uFF08launchctl print \u9000\u51FA\u7801 ${result.status ?? "\u6267\u884C\u5931\u8D25"}\uFF09`, {
5044
+ hint: ["\u8FD9\u4E0D\u4EE3\u8868\u670D\u52A1\u4ECD\u88C5\u8F7D\uFF0C\u53EA\u8868\u793A\u67E5\u8BE2\u6CA1\u6210\u7ACB\u3002", `\u624B\u52A8\u786E\u8BA4: launchctl print ${target}`]
5045
+ });
5046
+ }
5047
+ await sleep(UNLOADED_POLL_INTERVAL_MS);
4944
5048
  }
5049
+ throw new CliError("\u670D\u52A1\u5378\u8F7D\u8D85\u65F6\uFF0C\u4EFB\u52A1\u4ECD\u5904\u4E8E\u88C5\u8F7D\u72B6\u6001\uFF08bootout \u672A\u751F\u6548\uFF09", {
5050
+ hint: ["\u5E26\u7740\u300C\u4EFB\u52A1\u4ECD\u88C5\u8F7D\u300D\u5F80\u4E0B\u8D70\uFF0C\u6B63\u662F\u300C\u62A5\u505C\u6B62\u6210\u529F\u800C KeepAlive \u7EA6 10s \u540E\u62C9\u56DE\u5185\u6838\u300D\u7684\u9759\u9ED8\u5931\u6548\u3002", `\u624B\u52A8\u786E\u8BA4: launchctl print ${target}`]
5051
+ });
4945
5052
  }
4946
5053
  function cleanupRootResidue() {
4947
5054
  const rootPids = getMihomoPids().filter(isProcessRoot);
4948
- const pidFileIsRoot = fs9.existsSync(PATHS.pidFile) && (() => {
4949
- try {
4950
- return fs9.statSync(PATHS.pidFile).uid === 0;
4951
- } catch {
4952
- return false;
4953
- }
4954
- })();
4955
- if (rootPids.length === 0 && !pidFileIsRoot) return;
5055
+ if (rootPids.length === 0 && !isPidFileOwnedByRoot()) return;
4956
5056
  const script = [
4957
5057
  "#!/bin/bash",
4958
- `pkill -9 -f ${shellQuote(MAIN_INSTANCE_PATTERN)} 2>/dev/null || true`,
5058
+ // pkill 退出码 2/3 是 pattern 编译失败等探测性错误,不能当「没有进程」吞掉
5059
+ // (与 killAllMihomo 只收 0/1 同一原则)
5060
+ `pkill -9 -f ${shellQuote(MAIN_INSTANCE_PATTERN)} 2>/dev/null`,
5061
+ "rc=$?",
5062
+ "[ $rc -le 1 ] || exit 2",
4959
5063
  `rm -f ${shellQuote(PATHS.pidFile)}`,
4960
5064
  "exit 0",
4961
5065
  ""
4962
5066
  ].join("\n");
4963
- runSudoScript(script, { action: "\u6E05\u7406\u6B8B\u7559\u8FDB\u7A0B", file: "cleanup-residue.sh" });
5067
+ 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
5068
  }
4965
5069
  function killResidualKernels() {
4966
5070
  const pids = getMihomoPids();
@@ -4975,47 +5079,39 @@ function killResidualKernels() {
4975
5079
  }
4976
5080
  if (rootPids.length > 0) cleanupRootResidue();
4977
5081
  }
4978
- function waitUnloadedSteps() {
4979
- 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"];
4981
- }
4982
- function installService(wasRunning) {
5082
+ async function installService(wasRunning) {
4983
5083
  assertServiceLabelSafe();
4984
5084
  ensureDirs();
4985
5085
  ensureServiceSymlink();
4986
5086
  const stagePath = path6.join(DIRS.runtime, "service.plist.stage");
4987
5087
  atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
4988
- const target = shellQuote(serviceTarget());
4989
- const dest = shellQuote(PATHS.userAgentPlist);
4990
- const stage = shellQuote(stagePath);
4991
- const destDir = shellQuote(path6.dirname(PATHS.userAgentPlist));
4992
- const steps = [
4993
- `plutil -lint ${stage} >/dev/null || exit 2`,
4994
- `launchctl bootout ${target} 2>/dev/null || true`,
4995
- ...waitUnloadedSteps(),
4996
- // ~/Library/LaunchAgents 在全新系统上可能不存在;只在缺失时创建,避免改动已有目录权限
4997
- `[ -d ${destDir} ] || mkdir -p ${destDir}`,
4998
- `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`]
5000
- ];
5001
5088
  try {
5002
- runLaunchctlSteps(steps, {
5003
- action: "\u5B89\u88C5\u670D\u52A1",
5004
- codeMessages: {
5005
- 2: "plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09",
5006
- 3: `\u5B89\u88C5 plist \u5230 ${path6.dirname(PATHS.userAgentPlist)} \u5931\u8D25`,
5007
- 4: "\u88C5\u8F7D\u670D\u52A1\u5931\u8D25\uFF08launchctl bootstrap\uFF09",
5008
- 5: "\u542F\u7528\u670D\u52A1\u5931\u8D25\uFF08launchctl enable\uFF09"
5009
- }
5010
- });
5089
+ const lint = spawnSync4("plutil", ["-lint", stagePath], { encoding: "utf8", timeout: 1e4 });
5090
+ if (lint.status !== 0) {
5091
+ throw new CliError("plist \u8BED\u6CD5\u6821\u9A8C\u5931\u8D25\uFF08plutil -lint\uFF09", {
5092
+ hint: [(lint.stderr || lint.stdout || "").trim()].filter(Boolean)
5093
+ });
5094
+ }
5095
+ await bootoutService();
5096
+ await waitUntilUnloaded();
5097
+ fs9.mkdirSync(path6.dirname(PATHS.userAgentPlist), { recursive: true });
5098
+ fs9.copyFileSync(stagePath, PATHS.userAgentPlist);
5099
+ fs9.chmodSync(PATHS.userAgentPlist, 420);
5100
+ if (wasRunning) {
5101
+ runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
5102
+ runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u88C5\u8F7D\u670D\u52A1");
5103
+ }
5011
5104
  } finally {
5012
5105
  try {
5013
5106
  fs9.unlinkSync(stagePath);
5014
5107
  } catch {
5015
5108
  }
5016
5109
  }
5110
+ if (!wasRunning) {
5111
+ disableServiceAutoStart();
5112
+ }
5017
5113
  }
5018
- function startService() {
5114
+ async function startService() {
5019
5115
  assertServiceLabelSafe();
5020
5116
  ensureServiceSymlink();
5021
5117
  if (!isServiceInstalled()) {
@@ -5036,38 +5132,41 @@ function startService() {
5036
5132
  });
5037
5133
  }
5038
5134
  cleanupRootResidue();
5039
- const target = shellQuote(serviceTarget());
5040
- const dest = shellQuote(PATHS.userAgentPlist);
5041
- runLaunchctlSteps([`launchctl bootout ${target} 2>/dev/null || true`, ...waitUnloadedSteps()], { action: "\u5378\u8F7D\u65E7\u670D\u52A1\u5B9E\u4F8B" });
5135
+ await bootoutService();
5136
+ await waitUntilUnloaded();
5042
5137
  rotateAndCleanupLogs();
5043
- runLaunchctlSteps([`launchctl enable ${target} || exit 2`, `launchctl bootstrap ${bootstrapDomain()} ${dest} || exit 3`], {
5044
- action: "\u542F\u52A8\u670D\u52A1",
5045
- codeMessages: { 2: "\u542F\u7528\u670D\u52A1\u5931\u8D25\uFF08launchctl enable\uFF09", 3: "\u88C5\u8F7D\u670D\u52A1\u5931\u8D25\uFF08launchctl bootstrap\uFF09" }
5046
- });
5138
+ runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
5139
+ runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u542F\u52A8\u670D\u52A1");
5047
5140
  }
5048
5141
  function disableServiceAutoStart() {
5049
5142
  assertServiceLabelSafe();
5050
- const target = shellQuote(serviceTarget());
5051
- runLaunchctlSteps([`launchctl disable ${target} 2>/dev/null || true`], { action: "\u5173\u95ED\u670D\u52A1\u81EA\u542F" });
5143
+ runLaunchctlOrThrow(["disable", serviceTarget()], "\u5173\u95ED\u670D\u52A1\u81EA\u542F");
5144
+ if (!isServiceDisabledInLaunchd()) {
5145
+ throw new CliError("\u5173\u95ED\u670D\u52A1\u81EA\u542F\u5931\u8D25\uFF1Adisable \u4F4D\u672A\u751F\u6548", {
5146
+ 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"]
5147
+ });
5148
+ }
5052
5149
  }
5053
- function stopService() {
5150
+ async function stopService() {
5054
5151
  assertServiceLabelSafe();
5055
- 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"
5058
- });
5152
+ await bootoutService();
5153
+ await waitUntilUnloaded();
5154
+ disableServiceAutoStart();
5059
5155
  killResidualKernels();
5060
5156
  }
5061
- function uninstallService() {
5157
+ async function uninstallService() {
5062
5158
  assertServiceLabelSafe();
5063
- const target = shellQuote(serviceTarget());
5064
- 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" }
5067
- );
5159
+ await bootoutService();
5160
+ await waitUntilUnloaded();
5161
+ try {
5162
+ fs9.rmSync(PATHS.userAgentPlist, { force: true });
5163
+ } catch (e) {
5164
+ throw new CliError(`\u5220\u9664 plist \u5931\u8D25\uFF08${PATHS.userAgentPlist}\uFF09: ${e.message}`);
5165
+ }
5166
+ disableServiceAutoStart();
5068
5167
  killResidualKernels();
5069
5168
  try {
5070
- fs9.unlinkSync(PATHS.serviceBinary);
5169
+ fs9.rmSync(PATHS.serviceBinary, { force: true });
5071
5170
  } catch {
5072
5171
  }
5073
5172
  }
@@ -5123,21 +5222,19 @@ async function restartService() {
5123
5222
  throw new CliError("\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u5B89\u88C5\u670D\u52A1: mihomo install" });
5124
5223
  }
5125
5224
  if (!logOversized() && await tryHotReload()) return { hotReloaded: true };
5126
- const target = shellQuote(serviceTarget());
5127
- const dest = shellQuote(PATHS.userAgentPlist);
5128
- const logFile = shellQuote(PATHS.logFile);
5129
- const archiveFile = shellQuote(path6.join(DIRS.logs, `mihomo.${formatLocalTimestamp()}.log`));
5130
- runLaunchctlSteps(
5131
- [
5132
- `if [ -f ${logFile} ] && [ "$(stat -f%z ${logFile} 2>/dev/null || echo 0)" -gt ${LOG_ROTATE_MAX_BYTES} ]; then`,
5133
- ` cp ${logFile} ${archiveFile} 2>/dev/null && : > ${logFile}`,
5134
- "fi",
5135
- `if launchctl kickstart -k ${target} 2>/dev/null; then exit 0; fi`,
5136
- `launchctl enable ${target} 2>/dev/null || true`,
5137
- `launchctl bootstrap ${bootstrapDomain()} ${dest} || exit 3`
5138
- ],
5139
- { action: "\u91CD\u542F\u670D\u52A1", codeMessages: { 3: "\u91CD\u542F\u670D\u52A1\u5931\u8D25\uFF08launchctl bootstrap\uFF09" } }
5140
- );
5225
+ if (logOversized()) {
5226
+ const archiveFile = path6.join(DIRS.logs, `mihomo.${formatLocalTimestamp()}.log`);
5227
+ try {
5228
+ fs9.copyFileSync(PATHS.logFile, archiveFile);
5229
+ fs9.writeFileSync(PATHS.logFile, "");
5230
+ } catch {
5231
+ }
5232
+ }
5233
+ const kick = runLaunchctl(["kickstart", "-k", serviceTarget()], 6e4);
5234
+ if (kick.status !== 0) {
5235
+ runLaunchctl(["enable", serviceTarget()]);
5236
+ runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u91CD\u542F\u670D\u52A1");
5237
+ }
5141
5238
  cleanupOldLogs();
5142
5239
  return { hotReloaded: false };
5143
5240
  }
@@ -5171,17 +5268,17 @@ async function launchOrRestart(mode) {
5171
5268
  const { hotReloaded } = await restartService();
5172
5269
  if (hotReloaded) return getServiceStatus().pid;
5173
5270
  } else {
5174
- startService();
5271
+ await startService();
5175
5272
  }
5176
5273
  return assertServiceHealthy();
5177
5274
  }
5178
- async function assertServiceHealthy() {
5275
+ async function assertServiceHealthy(label = "\u542F\u52A8\u5931\u8D25") {
5179
5276
  const health = await waitServiceHealthy();
5180
5277
  if (health.healthy) return health.pid;
5181
5278
  const tail = readLogTail();
5182
5279
  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
5280
  throw new CliError(reason, {
5184
- label: "\u542F\u52A8\u5931\u8D25",
5281
+ label,
5185
5282
  hint: [
5186
5283
  ...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
5284
  ...tail.length > 0 ? ["", "--- \u65E5\u5FD7\u5C3E\u90E8 ---", ...tail] : ["", `\u65E5\u5FD7: ${PATHS.logFile}`],
@@ -5195,8 +5292,7 @@ async function assertServiceHealthy() {
5195
5292
  var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
5196
5293
  var MAX_ERROR_BODY_BYTES = 64 * 1024;
5197
5294
  function createHttpClient(options = {}) {
5198
- const { timeout = 6e4, secret } = options;
5199
- const authHeaders = secret ? { Authorization: `Bearer ${secret}` } : {};
5295
+ const { timeout = 6e4 } = options;
5200
5296
  return {
5201
5297
  async get(url, config) {
5202
5298
  const controller = new AbortController();
@@ -5205,7 +5301,7 @@ function createHttpClient(options = {}) {
5205
5301
  try {
5206
5302
  const response = await fetch(url, {
5207
5303
  signal,
5208
- headers: { "User-Agent": `mihomo-cli/${VERSION}`, ...authHeaders }
5304
+ headers: { "User-Agent": `mihomo-cli/${VERSION}` }
5209
5305
  });
5210
5306
  if (!response.ok) {
5211
5307
  const error = new Error(`HTTP ${response.status}`);
@@ -5637,6 +5733,13 @@ async function cmdStart(args) {
5637
5733
  const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
5638
5734
  const serviceBefore = getServiceStatus();
5639
5735
  if (targetMode === "tun") {
5736
+ if (detectLegacySystemInstall()) {
5737
+ 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"));
5738
+ 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"));
5739
+ cleanupLegacyInstallOrThrow();
5740
+ console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
5741
+ console.log("");
5742
+ }
5640
5743
  if (serviceBefore.loaded) {
5641
5744
  throw new CliError("\u670D\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8 TUN", {
5642
5745
  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 +5820,17 @@ async function restartToApply(args) {
5717
5820
  await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
5718
5821
  return true;
5719
5822
  }
5823
+ function cleanupLegacyInstallOrThrow() {
5824
+ try {
5825
+ cleanupLegacySystemInstall();
5826
+ } catch (e) {
5827
+ if (e instanceof CliError) throw e;
5828
+ throw new CliError(e.message, {
5829
+ label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
5830
+ hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
5831
+ });
5832
+ }
5833
+ }
5720
5834
 
5721
5835
  // src/commands/directory.ts
5722
5836
  function openDirectory(args) {
@@ -5878,12 +5992,7 @@ function findMatchingAsset(assets, platform, arch) {
5878
5992
  );
5879
5993
  if (matchingAssets.length === 0) return null;
5880
5994
  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
- });
5995
+ const standardAsset = matchingAssets.find((a) => new RegExp(`^${escapeRegExp(prefix)}-v?\\d+\\.\\d+\\.\\d+$`).test(a.name.slice(0, -3)));
5887
5996
  return standardAsset || matchingAssets[0];
5888
5997
  }
5889
5998
  async function getLatestRelease(repo) {
@@ -6430,9 +6539,9 @@ var RESET_TARGETS = [
6430
6539
  label: "\u8BA2\u9605",
6431
6540
  paths: () => [DIRS.subscriptions],
6432
6541
  needsStop: true,
6433
- // 同步清空 settings 里的订阅列表:只删缓存文件会留下"列表存在但无配置"的半重置状态
6434
- // (start 会报"未找到订阅配置")。active_subscription 一并清除
6435
- onAfter: () => writeSettings({ subscriptions: void 0, active_subscription: void 0 })
6542
+ onAfter: () => {
6543
+ writeSettings({ subscriptions: void 0, active_subscription: void 0 });
6544
+ }
6436
6545
  },
6437
6546
  {
6438
6547
  id: "logs",
@@ -6496,9 +6605,10 @@ var RESET_TARGETS = [
6496
6605
  // onAfter 因幂等守卫成为 no-op,仅作单独 reset 未走前段时的兜底。
6497
6606
  paths: () => [],
6498
6607
  needsStop: false,
6499
- onAfter: () => {
6608
+ onAfter: async () => {
6500
6609
  const st = getServiceStatus();
6501
- if (st.installed || st.loaded) uninstallService();
6610
+ if (st.installed || st.loaded) await uninstallService();
6611
+ if (detectLegacySystemInstall()) cleanupLegacyInstallOrThrow();
6502
6612
  },
6503
6613
  checkEmpty: () => !isServiceInstalled() && !getServiceStatus().loaded && !detectLegacySystemInstall(),
6504
6614
  emptyMsg: "\u670D\u52A1\u672A\u5B89\u88C5\uFF0C\u65E0\u9700\u5220\u9664"
@@ -6577,6 +6687,9 @@ async function cmdReset(args) {
6577
6687
  } else if (stopsService && serviceActive) {
6578
6688
  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
6689
  }
6690
+ if (uninstallsService && detectLegacySystemInstall()) {
6691
+ 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"));
6692
+ }
6580
6693
  console.log(`\u5C06\u5220\u9664: ${targets.map((t) => t.label).join("\u3001")}`);
6581
6694
  if (!skipConfirm) {
6582
6695
  if (!await confirmOrThrow("\u786E\u8BA4?", {
@@ -6590,9 +6703,9 @@ async function cmdReset(args) {
6590
6703
  if ((uninstallsService || stopsService) && serviceActive) {
6591
6704
  try {
6592
6705
  if (uninstallsService) {
6593
- uninstallService();
6706
+ await uninstallService();
6594
6707
  } else {
6595
- stopService();
6708
+ await stopService();
6596
6709
  }
6597
6710
  } catch (e) {
6598
6711
  if (e instanceof CliError) throw e;
@@ -6628,7 +6741,7 @@ async function cmdReset(args) {
6628
6741
  }
6629
6742
  }
6630
6743
  }
6631
- t.onAfter?.();
6744
+ await t.onAfter?.();
6632
6745
  }
6633
6746
  ensureDirs();
6634
6747
  if (targets.some((t) => t.id === "settings")) {
@@ -6645,15 +6758,7 @@ async function handleLegacyInstall() {
6645
6758
  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
6759
  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
6760
  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
- }
6761
+ cleanupLegacyInstallOrThrow();
6657
6762
  console.log(`${colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1")}`);
6658
6763
  console.log("");
6659
6764
  }
@@ -6663,12 +6768,21 @@ async function cmdInstall(_args) {
6663
6768
  }
6664
6769
  await handleLegacyInstall();
6665
6770
  const wasRunning = getServiceStatus().running;
6666
- installService(wasRunning);
6771
+ await installService(wasRunning);
6667
6772
  console.log(`${colors.green("\u5DF2\u5B89\u88C5\u670D\u52A1")}`);
6668
6773
  console.log(colors.gray(` plist: ${PATHS.userAgentPlist}`));
6669
6774
  console.log(colors.gray(` \u767B\u5F55\u9879\u4E0E\u6269\u5C55\u4E2D\u663E\u793A\u4E3A: ${SERVICE_BINARY_NAME}`));
6670
6775
  console.log("");
6671
6776
  if (wasRunning) {
6777
+ try {
6778
+ await assertServiceHealthy("\u6062\u590D\u8FD0\u884C\u5931\u8D25");
6779
+ } catch (e) {
6780
+ if (!(e instanceof CliError)) throw e;
6781
+ throw new CliError(e.message, {
6782
+ label: e.label,
6783
+ 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"]
6784
+ });
6785
+ }
6672
6786
  console.log(colors.green("\u5DF2\u6309\u539F\u72B6\u6001\u91CD\u65B0\u542F\u52A8"));
6673
6787
  } else {
6674
6788
  console.log("\u542F\u52A8: mihomo start");
@@ -6691,12 +6805,12 @@ async function cmdUninstall(_args) {
6691
6805
  console.log("\u5C06\u6267\u884C launchctl bootout \u5378\u8F7D\u6B8B\u7559\u4EFB\u52A1");
6692
6806
  }
6693
6807
  if (status.installed || status.loaded) {
6694
- uninstallService();
6808
+ await uninstallService();
6695
6809
  console.log(colors.green("\u5DF2\u5378\u8F7D\u670D\u52A1"));
6696
6810
  }
6697
6811
  if (legacy) {
6698
6812
  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();
6813
+ cleanupLegacyInstallOrThrow();
6700
6814
  console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
6701
6815
  }
6702
6816
  const remaining = getMihomoPids();
@@ -6717,6 +6831,13 @@ function handleStopResult(result) {
6717
6831
  }
6718
6832
  async function cmdStop(args) {
6719
6833
  assertNoRemovedSshFlag(args);
6834
+ if (detectLegacySystemInstall()) {
6835
+ 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"));
6836
+ 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"));
6837
+ cleanupLegacyInstallOrThrow();
6838
+ console.log(colors.green("\u5DF2\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1"));
6839
+ console.log("");
6840
+ }
6720
6841
  const status = getServiceStatus();
6721
6842
  const pids = getMihomoPids();
6722
6843
  const needsServiceWork = status.loaded || status.installed && !status.disabled;
@@ -6730,7 +6851,7 @@ async function cmdStop(args) {
6730
6851
  console.log(colors.green("\u5DF2\u505C\u6B62"));
6731
6852
  return;
6732
6853
  }
6733
- stopService();
6854
+ await stopService();
6734
6855
  const remaining = getMihomoPids();
6735
6856
  if (remaining.length > 0) {
6736
6857
  throw new CliError(remaining.join(", "), {
@@ -7231,11 +7352,11 @@ function clearProxyEnv() {
7231
7352
  delete process.env.all_proxy;
7232
7353
  delete process.env.ALL_PROXY;
7233
7354
  }
7234
- var ROOT_ALLOWED_COMMANDS = /* @__PURE__ */ new Set(["help", "version"]);
7355
+ var GUARD_EXEMPT_COMMANDS = /* @__PURE__ */ new Set(["help", "version"]);
7235
7356
  function assertNotRoot(commandName) {
7236
7357
  const uid = process.getuid?.();
7237
7358
  if (uid !== 0) return;
7238
- if (ROOT_ALLOWED_COMMANDS.has(commandName)) return;
7359
+ if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
7239
7360
  throw new CliError("\u8BF7\u4E0D\u8981\u7528 sudo \u8FD0\u884C mihomo", {
7240
7361
  label: "\u8EAB\u4EFD\u9519\u8BEF",
7241
7362
  hint: [
@@ -7249,10 +7370,9 @@ function assertNotRoot(commandName) {
7249
7370
  ]
7250
7371
  });
7251
7372
  }
7252
- var PLATFORM_FREE_COMMANDS = /* @__PURE__ */ new Set(["help", "version"]);
7253
7373
  function assertSupportedPlatform(commandName) {
7254
7374
  if (process.platform === "darwin") return;
7255
- if (PLATFORM_FREE_COMMANDS.has(commandName)) return;
7375
+ if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
7256
7376
  if (process.env.MIHOMO_CLI_ALLOW_ANY_PLATFORM === "1") return;
7257
7377
  throw new CliError(`mihomo-cli \u76EE\u524D\u4EC5\u652F\u6301 macOS\uFF08\u5F53\u524D\u5E73\u53F0: ${process.platform}\uFF09`, {
7258
7378
  label: "\u5E73\u53F0\u4E0D\u652F\u6301",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mihomo-cli",
3
- "version": "4.2.2",
3
+ "version": "4.2.4",
4
4
  "type": "module",
5
5
  "description": "A terminal-based mihomo (Clash.Meta) client for macOS",
6
6
  "bin": {