mihomo-cli 4.11.0 → 4.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,51 @@
1
1
  # Changelog
2
2
 
3
+ ## [4.13.0] - 2026-09-13
4
+
5
+ 一项入站安全边界修复,并给锁定清单补上防漏机制。单测 700(+11)。
6
+
7
+ ### 安全
8
+
9
+ - **订阅/覆写里的 `allow-lan` 等六个键不再进运行配置**:`allow-lan`、`bind-address`、`authentication`、`skip-auth-prefixes`、`lan-allowed-ips`、`lan-disallowed-ips` 是上游 `config.Inbound` 里与已锁的 `ss-config`/`listeners` 并列的字段,此前从未被剥除。远端订阅一行 `allow-lan: true` 就让内核把混合端口从回环绑到全网卡,而 `skip-auth-prefixes: ["0.0.0.0/0"]` 会让唯一的补偿防线 `authentication` 整个失效——三行 YAML 即可把本机变成全网卡无鉴权开放代理,与 README「入站默认关闭」的承诺直接冲突。判据与已锁的入站键完全相同,只因形态是布尔/字符串而非映射或 URL 被漏看
10
+
11
+ ### 变更
12
+
13
+ - **`allow-lan` 现由本工具恒定为 `false`,订阅与覆写都改不了**(上一条的直接后果)。此前 README 写着「可在订阅或覆写中显式开启」,该说法把远端下发的订阅当成了用户的意图表达,与「订阅不可信」这一整套锁定机制的前提矛盾。**破坏性变更**:靠订阅或覆写开局域网入站的用户会失去该能力(覆写侧有提示,订阅侧按既有设计静默)——确需局域网设备连入请在本机另起一个 mihomo 实例。同理,`authentication` 被锁后不能再经覆写给混合端口设代理鉴权;混合端口现固定只监听回环,局域网威胁面已不存在
14
+ - `iptables` 之外,`inbound-tfo` / `inbound-mptcp` 也明确记为刻意不锁:传输层 socket 选项,不开监听、不改绑定地址、不绕鉴权
15
+
16
+ ### 新增
17
+
18
+ - **锁定清单新增字段快照测试**:`LOCKED_CONFIG_KEYS` 已连续五轮各漏一批入站键,每轮复审都写着「这次逐个核对过了」。现存一份带上游版本号的 `config.Inbound` 字段快照,凡不在锁定表里的字段必须写明放行理由,否则测试失败——「待定」在实现上等于放行,这类决策不能再静默通过。该快照是冻结副本,发现不了上游新增字段,内核大版本升级时仍需人工刷新
19
+
20
+ ## [4.12.0] - 2026-09-13
21
+
22
+ 全仓复审修出的十一项:两项入站/文件安全边界、六项修复、两处词表与文案收口、一项性能。单测 689(+32)。
23
+
24
+ ### 安全
25
+
26
+ - **订阅/覆写里的 `listeners` 与 `tunnels` 不再进运行配置**:两者自带监听地址、不受 `allow-lan` 约束,远端订阅一条 `listeners: [{type: socks, listen: 0.0.0.0, port: 18080}]` 即可在全网卡开出无鉴权 SOCKS 入站。判据与已锁的 `ss-config`/`vmess-config`/`tuic-server` 完全相同,此前因被记作「未定的产品决策」而放行了三个版本。确需额外入站请在本机另起实例;`iptables` 仍保留(Linux 专用、非监听)
27
+ - **`completion install zsh|fish` 不再覆盖非本工具生成的同名文件**:此前是无条件写入,用户手写或第三方分发的 `~/.zsh/completions/_mihomo` 会被静默销毁且无备份。判据与 `uninstall` 的删除守卫收口为同一条——此前卸载侧严格把关、安装侧直接覆盖,守的那道形同虚设(覆盖之后指纹就匹配了,卸载反而删得干干净净)
28
+
29
+ ### 修复
30
+
31
+ - **`status` 把主覆写文件显示成 `yaml`**:剥前缀与剥扩展名的顺序写反,`overwrite.yaml` 剩下 `yaml`、「主文件」兜底永不触发。只有一个主文件是最常见的配置形态,该行现显示 `覆写: 已启用 (主文件)`
32
+ - **`--mirror` 重复时的提示指向一个会报错的命令**:原提示「可用镜像见 `mihomo kernel --help`」,而命令级 `--help` 并不存在(只是顶层 help 的别名),照做会得到「未知的选项」。改为直接列出可用镜像
33
+ - **`eval "$(mihomo completion zsh)"` 实际不注册补全**:脚本结尾是裸调用 `_mihomo "$@"`,eval 下 `#compdef` 只是注释,裸调用则在补全上下文之外执行 `_arguments` 并报错,而 `eval` 仍返回 0——用户照 README 做了却发现补全不工作。改为 `compdef` 注册,两条安装路径(fpath 文件 / eval)现在都生效
34
+ - **bash 半截标记块导致 install 与 uninstall 互相甩锅**:`~/.bash_completion` 只剩起始标记时(手工编辑或上次写入中断),install 报「已安装过」、uninstall 报「未找到标记」,双双退出 0 且都不改文件,用户没有 CLI 路径可修。install 的幂等判据改为要求成对标记,可自愈
35
+ - **zsh 补全描述里的撇号被静默吞掉**:转义用了 `''`,而该写法仅在 `RC_QUOTES` 选项下才是转义(默认关闭),默认下是字符串拼接。改用 `'\''`。当前注册表无此类描述,属预防性修复
36
+ - **fish 补全描述以反斜杠结尾会让脚本语法错误**:只转义了撇号、未转义反斜杠,`-d 'desc\'` 的末尾 `\'` 被读作转义撇号。同为预防性修复
37
+ - **`settings.json` 内容是 JSON 合法的非对象时被静默丢弃**:`[1,2,3]`、`"str"`、`42`、`null` 这几种形态此前既不备份也不告警,而下一次写设置会把文件整个覆盖成默认内容——用户原件无声无息地没了。现与「JSON 解析失败」同样备份到 `.bak` 并告警
38
+ - **bash 补全有重复标记块时需卸载两次**:`uninstall` 只切第一对标记就报「已移除」,文件里仍留着一份生效的 `_mihomo_completions` 定义。现循环剥离到一个不剩,多份时如实告知移除了几份
39
+
40
+ ### 变更
41
+
42
+ - 补全的两处硬编码词表改为从单一真相源派生:bash 的 `dir` 分支不再写死 `open`(改用 `DIRECTORY_SUBCOMMANDS`),fish 的目录目标行不再写死四个 `directory` 别名(改从注册表取)。此前给 `directory` 加别名或子命令时,相邻的派生分支会跟上而这两处不会
43
+ - 不接受任何选项的命令(`completion`/`dir`/`stop` 等)在选项报错时不再打印空的「可用选项: 」,改说「该命令不接受任何选项」;`-h`/`--help` 额外点明它只在顶层可用。`completion install|uninstall <shell>` 的 shell 名报错也带上自己的动词,照提示改不会丢掉 `install` 这一步
44
+
45
+ ### 性能
46
+
47
+ - **`doctor` 的 npm 版本查询改为与本地检查并行**:该查询是纯网络往返(约 780ms),原先串在全部检查之后,而它不依赖任何前序结果。装了内核时体检从约 1070ms 降到约 837ms(省 22%);未装内核时本地检查太短,耗时下界即 npm 查询本身
48
+
3
49
  ## [4.11.0] - 2026-09-13
4
50
 
5
51
  一处展示层误导的修复:`status` 此前会把「不适用于当前订阅」的覆写文件与真正生效的并排列出。单测 657(+8)。
package/README.md CHANGED
@@ -196,6 +196,9 @@ mihomo completion fish | source
196
196
  mihomo completion uninstall zsh # bash 只剥掉自己那段,保留 ~/.bash_completion 中你自己的内容
197
197
  ```
198
198
 
199
+ > zsh/fish 的目标文件名由本工具独占,但**安装前会先确认那是不是自己生成的**:目标已存在且不像本工具的产物时报错退出、不覆盖(你手写或第三方分发的同名补全不会被销毁)。
200
+ > 确认无用后手动 `rm` 再装,或用 `mihomo completion <shell> > <自选路径>` 输出到别处。
201
+
199
202
  > zsh 的 `~/.zsh/completions` 不在默认 `fpath` 里(oh-my-zsh 默认已包含):
200
203
  > 补全不生效时在 `~/.zshrc` 加一行 `fpath=(~/.zsh/completions $fpath)`,重新打开终端。
201
204
 
@@ -687,8 +690,8 @@ sudo pkill -9 mihomo
687
690
 
688
691
  - **URL 脱敏**:订阅 URL 中的 token、key、password 等敏感参数(含 query、userinfo 及路径型令牌)自动替换为 `***`。按整条 URL 处理、不按逗号切分——逗号在 query 中合法,切开会让 `?nodes=us,hk&token=xxx` 的 token 参数识别不出而明文输出
689
692
  - **文件权限**:配置文件使用 `0o600` 权限(仅所有者可读可写),目录使用 `0o700` 权限
690
- - **入站默认关闭**:订阅/覆写未指定时 `allow-lan` 默认 `false`;如需局域网设备连入代理端口,可在订阅或覆写中显式开启
691
- - **入站与控制面由本工具独占**:订阅与覆写里的入站端口(`mixed-port`/`port`/`socks-port`/`redir-port`/`tproxy-port`)、独立入站服务端(`tuic-server`/`ss-config`/`vmess-config`)、外部控制器全家桶(`external-controller*`、`external-doh-server`、`secret`、`external-ui*`)与控制器证书段(`tls`)一律剥除,不进运行配置。这些键自带监听地址、不受 `allow-lan` 约束,远端订阅若能投递即可在全网卡开出无鉴权控制器或开放代理;端口与密钥只认 `settings.json`。覆写文件里写了会有提示,订阅侧静默剥除
693
+ - **入站固定只监听回环**:`allow-lan` 由本工具恒定为 `false`,**订阅与覆写都改不了**(自 v4.13.0;此前订阅里写 `allow-lan: true` 即可把混合端口开到全网卡)。确需局域网设备连入的场景请在本机另起一个 mihomo 实例,不通过订阅投递
694
+ - **入站与控制面由本工具独占**:订阅与覆写里的入站端口(`mixed-port`/`port`/`socks-port`/`redir-port`/`tproxy-port`)、独立入站服务端(`tuic-server`/`ss-config`/`vmess-config`)、通用入站声明(`listeners`/`tunnels`)、局域网暴露与入站鉴权(`allow-lan`/`bind-address`/`authentication`/`skip-auth-prefixes`/`lan-allowed-ips`/`lan-disallowed-ips`)、外部控制器全家桶(`external-controller*`、`external-doh-server`、`secret`、`external-ui*`)与控制器证书段(`tls`)一律剥除,不进运行配置。这些键要么自带监听地址、要么直接决定「监听在哪、要不要验身份」,远端订阅若能投递即可在全网卡开出无鉴权控制器或开放代理——`allow-lan: true` 让内核把端口绑到所有网卡,而 `skip-auth-prefixes: ["0.0.0.0/0"]` 会让唯一的补偿防线 `authentication` 整个失效;端口与密钥只认 `settings.json`。覆写文件里写了会有提示,订阅侧静默剥除。确需额外入站的场景请在本机另起一个 mihomo 实例,不通过订阅投递
692
695
  - **信号处理**:优雅处理 SIGINT/SIGTERM 信号
693
696
  - **异常捕获**:全局 uncaughtException 和 unhandledRejection 处理
694
697
 
package/dist/index.js CHANGED
@@ -3162,9 +3162,10 @@ var TUN_CONFIG = {
3162
3162
  }
3163
3163
  };
3164
3164
  var BASE_CONFIG = {
3165
- // 注意:mixed-port 与 external-controller 不在此表——它们来自 settings.ports(getPorts),
3166
- // config.ts 单独写入 systemConfig,订阅/覆写恒不可改
3167
- "allow-lan": false,
3165
+ // 注意:mixed-port、external-controller 与 allow-lan 不在此表——前两个来自
3166
+ // settings.ports(getPorts),allow-lan 恒为 false,三者都由 config.ts 单独写入
3167
+ // systemConfig,订阅/覆写恒不可改。本表的语义是「用户没写时的默认」(可被覆盖),
3168
+ // 锁定项的语义是「恒定此值」,两者不能混在一张表里
3168
3169
  "unified-delay": true,
3169
3170
  "tcp-concurrent": true,
3170
3171
  "geo-auto-update": true,
@@ -3407,25 +3408,29 @@ function sleepSyncMs(ms) {
3407
3408
  // src/settings.ts
3408
3409
  import fs2 from "fs";
3409
3410
  import path2 from "path";
3411
+ function backupCorruptSettings(reason) {
3412
+ const backup = `${PATHS.settingsFile}.bak`;
3413
+ try {
3414
+ if (fs2.existsSync(backup)) {
3415
+ console.warn(`\u8B66\u544A: settings.json ${reason}\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E\uFF08\u539F\u4EF6\u5DF2\u5728\u65E9\u524D\u5907\u4EFD: ${backup}\uFF0C\u672A\u8986\u76D6\uFF09`);
3416
+ } else {
3417
+ fs2.copyFileSync(PATHS.settingsFile, backup);
3418
+ console.warn(`\u8B66\u544A: settings.json ${reason}\uFF0C\u5DF2\u5907\u4EFD\u5230 ${backup}\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E`);
3419
+ }
3420
+ } catch {
3421
+ console.warn(`\u8B66\u544A: settings.json ${reason}\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E`);
3422
+ }
3423
+ return {};
3424
+ }
3410
3425
  function readSettings() {
3411
3426
  if (!fs2.existsSync(PATHS.settingsFile)) return {};
3412
3427
  try {
3413
3428
  const parsed = JSON.parse(fs2.readFileSync(PATHS.settingsFile, "utf8"));
3414
3429
  if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
3430
+ return backupCorruptSettings(`\u5185\u5BB9\u4E0D\u662F\u5BF9\u8C61\uFF08\u5F53\u524D\u662F${Array.isArray(parsed) ? "\u6570\u7EC4" : parsed === null ? "null" : typeof parsed}\uFF09`);
3415
3431
  } catch {
3416
- const backup = `${PATHS.settingsFile}.bak`;
3417
- try {
3418
- if (fs2.existsSync(backup)) {
3419
- console.warn(`\u8B66\u544A: settings.json \u683C\u5F0F\u635F\u574F\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E\uFF08\u539F\u4EF6\u5DF2\u5728\u65E9\u524D\u5907\u4EFD: ${backup}\uFF0C\u672A\u8986\u76D6\uFF09`);
3420
- } else {
3421
- fs2.copyFileSync(PATHS.settingsFile, backup);
3422
- console.warn(`\u8B66\u544A: settings.json \u683C\u5F0F\u635F\u574F\uFF0C\u5DF2\u5907\u4EFD\u5230 ${backup}\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E`);
3423
- }
3424
- } catch {
3425
- console.warn("\u8B66\u544A: settings.json \u683C\u5F0F\u635F\u574F\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u8BBE\u7F6E");
3426
- }
3432
+ return backupCorruptSettings("\u683C\u5F0F\u635F\u574F");
3427
3433
  }
3428
- return {};
3429
3434
  }
3430
3435
  function isValidSettingsContent(content) {
3431
3436
  try {
@@ -4222,9 +4227,11 @@ function assertKnownFlags(args, known, command) {
4222
4227
  const match = matchValueFlagToken(a);
4223
4228
  if (match && match.form !== "exact" && knownSet.has(match.baseForm)) continue;
4224
4229
  if (a.startsWith("--mirror=") && knownSet.has("--mirror")) continue;
4230
+ const isHelpFlag = a === "-h" || a === "--help";
4231
+ const helpNote = isHelpFlag ? ["", `${a} \u53EA\u5728\u9876\u5C42\u53EF\u7528\uFF0C\u547D\u4EE4\u7528\u6CD5\u89C1: mihomo help`] : [];
4225
4232
  throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${a}`, {
4226
4233
  label: "\u53C2\u6570\u9519\u8BEF",
4227
- hint: [`\u53EF\u7528\u9009\u9879: ${known.join(", ")}`, "", `\u7528\u6CD5: mihomo ${command}`]
4234
+ hint: [known.length > 0 ? `\u53EF\u7528\u9009\u9879: ${known.join(", ")}` : "\u8BE5\u547D\u4EE4\u4E0D\u63A5\u53D7\u4EFB\u4F55\u9009\u9879", ...helpNote, "", `\u7528\u6CD5: mihomo ${command}`]
4228
4235
  });
4229
4236
  }
4230
4237
  }
@@ -4382,7 +4389,10 @@ function parseMirrorArg(args) {
4382
4389
  if (mirrorCount > 1) {
4383
4390
  throw new CliError("--mirror \u53EA\u80FD\u6307\u5B9A\u4E00\u6B21", {
4384
4391
  label: "\u53C2\u6570\u9519\u8BEF",
4385
- hint: ["\u7528\u6CD5: mihomo kernel [--mirror [\u955C\u50CF]]", "\u53EF\u7528\u955C\u50CF\u89C1: mihomo kernel --help"]
4392
+ // 直接列出镜像,不说「见 mihomo kernel --help」:命令级 `--help` 并不存在
4393
+ // (`--help` 只是顶层 help 的别名,`kernel --help` 会撞 assertKnownFlags 报
4394
+ // 「未知的选项」),把用户指向一个必定报错的命令比不给提示更糟
4395
+ hint: ["\u7528\u6CD5: mihomo kernel [--mirror [\u955C\u50CF]]", `\u53EF\u7528\u955C\u50CF: ${AVAILABLE_MIRRORS.join(", ")}`, "\u4E0D\u4F7F\u7528\u955C\u50CF: mihomo kernel --mirror direct"]
4386
4396
  });
4387
4397
  }
4388
4398
  const mirrorEq = args.find((a) => a.startsWith("--mirror="));
@@ -4427,7 +4437,42 @@ var LOCKED_CONFIG_KEYS = [
4427
4437
  // bind-address 都管不到它们(那两个只作用于 HTTP/Socks/Redir/TProxy/Mixed)。
4428
4438
  // 即订阅里一行 `ss-config: ss://aes-128-gcm:pass@0.0.0.0:8388` 就是全网卡开放代理
4429
4439
  "ss-config",
4430
- "vmess-config"
4440
+ "vmess-config",
4441
+ // 通用入站声明:`listeners` 每个元素自带 type + listen,一条
4442
+ // `{type: socks, listen: 0.0.0.0, port: 18080}` 即在全网卡开出无鉴权 SOCKS 入站;
4443
+ // `tunnels` 声明本地端口到目标地址的直通转发,同样自带监听地址。两者与上面三个
4444
+ // 入站服务端满足完全相同的判据(订阅可指定监听地址、不经 genAddr、allow-lan 管不到),
4445
+ // 只因在上游是 RawConfig 顶层字段而非 Inbound 结构体成员,此前被记成「未定的产品决策」
4446
+ // 挂了三个版本——而「待定」在实现上等于放行:实测订阅里写 listeners 会原样进运行配置,
4447
+ // 与 README「入站默认关闭 / 入站与控制面由本工具独占」的承诺直接冲突。
4448
+ // 需要额外入站的用户改由本机另起实例,不接受远端订阅投递
4449
+ "listeners",
4450
+ "tunnels",
4451
+ // 局域网暴露与入站鉴权:上游 `config.Inbound` 里与上面几个并列的字段,只因形态是
4452
+ // 布尔/字符串而非映射或 URL 被漏看了五轮(与 ss-config 当年被漏的原因一模一样)。
4453
+ // 实测链条(v1.19.30):
4454
+ // - `listener.genAddr(host, port, allowLan)` 在 allowLan 为真、bind-address 为默认
4455
+ // `"*"` 时返回 `":%d"`,即**全网卡监听**——订阅一行 `allow-lan: true` 就把 Mixed
4456
+ // 端口挪出回环;bind-address 则直接指定监听地址
4457
+ // - `authentication` 是这种情况下唯一的补偿防线,而 `skip-auth-prefixes` 能把它废掉:
4458
+ // `listener/http/server.go` 的 accept 循环里
4459
+ // `if inbound.SkipAuthRemoteAddr(conn.RemoteAddr()) { store = authStore.Nil }`,
4460
+ // `0.0.0.0/0` 命中所有来源,鉴权 store 被换成空实现
4461
+ // 即远端订阅三行 YAML = 全网卡无鉴权开放代理。lan-allowed-ips/lan-disallowed-ips
4462
+ // 同属这套来源准入判定,一并锁死;bind-address 单看无害(allow-lan 为假时 genAddr
4463
+ // 根本不读它),锁它是为了消除「两个键配合才危险」这种要跨键推理的组合。
4464
+ //
4465
+ // allow-lan 恒为 false 由下方 systemConfig 写入(**不在 BASE_CONFIG**,理由同
4466
+ // mixed-port:锁定项是「恒定此值」,不是「用户没写时的默认」)。需要局域网入站的
4467
+ // 用户请在本机另起一个 mihomo 实例,不通过订阅投递。
4468
+ // 代价:剥除来源盲,故覆写也不能再给 Mixed 端口设 authentication——缓解是
4469
+ // allow-lan 已强制 false、Mixed 只在回环,残余威胁面是同机其他进程(见 CODE_REVIEW)
4470
+ "allow-lan",
4471
+ "bind-address",
4472
+ "authentication",
4473
+ "skip-auth-prefixes",
4474
+ "lan-allowed-ips",
4475
+ "lan-disallowed-ips"
4431
4476
  ];
4432
4477
  function loadYamlSafe(content) {
4433
4478
  return load(content, SAFE_YAML_LOAD_OPTIONS);
@@ -4545,7 +4590,7 @@ function buildConfig(subRawContent, mode, scope) {
4545
4590
  }
4546
4591
  if (hit.size > 0) {
4547
4592
  lockedWarnings.push(
4548
- `\u8986\u5199\u6587\u4EF6 ${file.name} \u4E2D\u7684\u7CFB\u7EDF\u9501\u5B9A\u9879\u5DF2\u5FFD\u7565: ${[...hit].join("\u3001")}\uFF08\u5165\u7AD9\u7AEF\u53E3\u3001\u63A7\u5236\u9762\u4E0E\u63A7\u5236\u5668\u8BC1\u4E66\u7531 mihomo-cli \u7BA1\u7406\uFF1B\u7AEF\u53E3\u4E0E controller secret \u5728 settings.json \u914D\u7F6E\uFF09`
4593
+ `\u8986\u5199\u6587\u4EF6 ${file.name} \u4E2D\u7684\u7CFB\u7EDF\u9501\u5B9A\u9879\u5DF2\u5FFD\u7565: ${[...hit].join("\u3001")}\uFF08\u5165\u7AD9\u7AEF\u53E3\u3001\u63A7\u5236\u9762\u3001\u63A7\u5236\u5668\u8BC1\u4E66\u4E0E\u5C40\u57DF\u7F51/\u5165\u7AD9\u9274\u6743\u7531 mihomo-cli \u7BA1\u7406\uFF1B\u7AEF\u53E3\u4E0E controller secret \u5728 settings.json \u914D\u7F6E\uFF0C\u5165\u7AD9\u56FA\u5B9A\u53EA\u76D1\u542C\u56DE\u73AF\uFF0C\u9700\u8981\u5C40\u57DF\u7F51\u5165\u7AD9\u8BF7\u5728\u672C\u673A\u53E6\u8D77\u4E00\u4E2A mihomo \u5B9E\u4F8B\uFF09`
4549
4594
  );
4550
4595
  }
4551
4596
  }
@@ -4556,6 +4601,7 @@ function buildConfig(subRawContent, mode, scope) {
4556
4601
  const ports = getPorts(settings);
4557
4602
  systemConfig["external-controller"] = `127.0.0.1:${ports.controller}`;
4558
4603
  systemConfig["mixed-port"] = ports.mixed;
4604
+ systemConfig["allow-lan"] = false;
4559
4605
  const controllerSecret = settings.controller_secret;
4560
4606
  if (controllerSecret !== void 0) {
4561
4607
  if (typeof controllerSecret !== "string") {
@@ -6441,7 +6487,7 @@ async function printStatus(args = []) {
6441
6487
  console.log("");
6442
6488
  }
6443
6489
  function shortOverwriteName(name) {
6444
- return name.replace(/^overwrite\.?/, "").replace(/\.ya?ml$/, "") || "\u4E3B\u6587\u4EF6";
6490
+ return name.replace(/\.ya?ml$/, "").replace(/^overwrite\.?/, "") || "\u4E3B\u6587\u4EF6";
6445
6491
  }
6446
6492
  function printOverwriteLines(enabled, files, activeSub) {
6447
6493
  if (!enabled) {
@@ -7251,6 +7297,9 @@ var UI_NAMES = Object.keys(UI_URLS);
7251
7297
  var MIRROR_NAMES = Object.keys(MIRROR_ALIASES);
7252
7298
  var RESET_TARGET_NAMES = [...new Set(RESET_TARGETS.flatMap((t) => t.aliases))];
7253
7299
  var SHELLS = ["zsh", "bash", "fish"];
7300
+ function zshSingleQuote(s) {
7301
+ return s.replace(/'/g, "'\\''");
7302
+ }
7254
7303
  function buildZsh(commands, groups) {
7255
7304
  const lines = [
7256
7305
  "#compdef mihomo mhm mh mihomo-cli",
@@ -7260,7 +7309,7 @@ function buildZsh(commands, groups) {
7260
7309
  "_mihomo() {",
7261
7310
  " local -a commands subcmds",
7262
7311
  " commands=(",
7263
- ...commandWords(commands).map((c) => ` '${c.word}:${c.desc.replace(/'/g, "''")}'`),
7312
+ ...commandWords(commands).map((c) => ` '${c.word}:${zshSingleQuote(c.desc)}'`),
7264
7313
  " )",
7265
7314
  "",
7266
7315
  " _arguments -C \\",
@@ -7279,7 +7328,7 @@ function buildZsh(commands, groups) {
7279
7328
  const isDirectory = group.tokens.includes("directory");
7280
7329
  lines.push(` ${aliases})`);
7281
7330
  lines.push(" subcmds=(");
7282
- for (const s of group.words) lines.push(` '${s.word}:${s.desc.replace(/'/g, "''")}'`);
7331
+ for (const s of group.words) lines.push(` '${s.word}:${zshSingleQuote(s.desc)}'`);
7283
7332
  lines.push(" )");
7284
7333
  lines.push(" if (( CURRENT == 2 )); then");
7285
7334
  lines.push(" _describe 'subcommand' subcmds");
@@ -7324,7 +7373,19 @@ function buildZsh(commands, groups) {
7324
7373
  " esac",
7325
7374
  "}",
7326
7375
  "",
7327
- '_mihomo "$@"'
7376
+ // 结尾必须是 compdef 注册,**不能是裸调用 `_mihomo "$@"`**。
7377
+ //
7378
+ // 两条安装路径对结尾行的要求不同,而裸调用只满足其中一条:
7379
+ // - 放进 fpath(`completion install zsh`):compinit 按 `#compdef` 首行自动注册,
7380
+ // 函数体被 autoload,结尾写什么都行——两种写法实测都能注册全部四个别名
7381
+ // - `eval "$(mihomo completion zsh)"`(README 与下方 CLI 提示都推荐):`#compdef`
7382
+ // 只是条注释、不起作用,而裸调用会在补全上下文之外执行 `_arguments`,实测报
7383
+ // `_arguments:comparguments:327: can only be called from completion function`,
7384
+ // 且 `_comps[mihomo]` 前后都是 0 —— 补全完全没注册,eval 却返回 0。
7385
+ // 用户照文档做了、看到没报错(错误在 stderr 一闪而过)、补全就是不工作。
7386
+ //
7387
+ // compdef 同时满足两条:实测 eval 后四个别名 `_comps` 全部为 1,fpath 安装不受影响。
7388
+ "compdef _mihomo mihomo mhm mh mihomo-cli"
7328
7389
  );
7329
7390
  return lines.join("\n");
7330
7391
  }
@@ -7336,7 +7397,7 @@ function buildBash(commands, groups) {
7336
7397
  if (group.tokens[0] === "directory") {
7337
7398
  return ` ${aliases})
7338
7399
  if [[ \${COMP_CWORD} -eq 2 ]]; then
7339
- COMPREPLY=( $(compgen -W "open" -- "\${cur}") )
7400
+ COMPREPLY=( $(compgen -W "${words}" -- "\${cur}") )
7340
7401
  elif [[ "\${COMP_WORDS[2]}" == "open" ]]; then
7341
7402
  COMPREPLY=( $(compgen -W "${DIR_TARGETS.join(" ")}" -- "\${cur}") )
7342
7403
  fi
@@ -7391,6 +7452,9 @@ ${subCase}
7391
7452
  complete -F _mihomo_completions mihomo mhm mh mihomo-cli
7392
7453
  `;
7393
7454
  }
7455
+ function fishSingleQuote(s) {
7456
+ return s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
7457
+ }
7394
7458
  function buildFish(commands, groups) {
7395
7459
  const lines = [
7396
7460
  "# mihomo-cli fish \u8865\u5168\uFF08mihomo completion fish \u751F\u6210\uFF1B\u5B89\u88C5: mihomo completion install fish\uFF0C\u6216 mihomo completion fish | source\uFF09",
@@ -7398,18 +7462,17 @@ function buildFish(commands, groups) {
7398
7462
  "for cmd in mihomo mhm mh mihomo-cli"
7399
7463
  ];
7400
7464
  for (const c of commandWords(commands)) {
7401
- lines.push(` complete -c $cmd -f -a '${c.word}' -d '${c.desc.replace(/'/g, "\\'")}'`);
7465
+ lines.push(` complete -c $cmd -f -a '${c.word}' -d '${fishSingleQuote(c.desc)}'`);
7402
7466
  }
7403
7467
  for (const group of groups) {
7404
7468
  const seen = group.tokens.join(" ");
7405
7469
  const condition = group.tokens.includes("directory") ? `${seen}; and not __fish_seen_subcommand_from open` : seen;
7406
7470
  for (const s of group.words) {
7407
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${condition}" -a '${s.word}' -d '${s.desc.replace(/'/g, "\\'")}'`);
7471
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${condition}" -a '${s.word}' -d '${fishSingleQuote(s.desc)}'`);
7408
7472
  }
7409
7473
  }
7410
- lines.push(
7411
- ` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories; and __fish_seen_subcommand_from open" -a '${DIR_TARGETS.join(" ")}'`
7412
- );
7474
+ const directoryTokens = groups.find((g) => g.tokens.includes("directory"))?.tokens.join(" ") ?? "directory";
7475
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ${directoryTokens}; and __fish_seen_subcommand_from open" -a '${DIR_TARGETS.join(" ")}'`);
7413
7476
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui; and not __fish_seen_subcommand_from ${UI_NAMES.join(" ")}" -a '${UI_NAMES.join(" ")}'`);
7414
7477
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install uninstall ${SHELLS.join(" ")}' -d '\u5B89\u88C5/\u5378\u8F7D\u8865\u5168'`);
7415
7478
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion; and __fish_seen_subcommand_from install uninstall" -a '${SHELLS.join(" ")}'`);
@@ -7420,7 +7483,7 @@ function buildFish(commands, groups) {
7420
7483
  lines.push("end");
7421
7484
  return lines.join("\n");
7422
7485
  }
7423
- function buildCompletionScript(shell, commands) {
7486
+ function buildCompletionScript(shell, commands, usageVerb = "") {
7424
7487
  const groups = subGroups(commands);
7425
7488
  switch (shell) {
7426
7489
  case "zsh":
@@ -7431,14 +7494,26 @@ function buildCompletionScript(shell, commands) {
7431
7494
  return buildFish(commands, groups);
7432
7495
  default: {
7433
7496
  const suggestion = suggestSimilar(shell, [...SHELLS]);
7497
+ const usage = `\u7528\u6CD5: mihomo completion ${usageVerb ? `${usageVerb} ` : ""}<${SHELLS.join("|")}>`;
7434
7498
  throw new CliError(`\u672A\u77E5\u7684 shell: ${shell}`, {
7435
7499
  label: "\u53C2\u6570\u9519\u8BEF",
7436
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], `\u7528\u6CD5: mihomo completion <${SHELLS.join("|")}>`]
7500
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], usage]
7437
7501
  });
7438
7502
  }
7439
7503
  }
7440
7504
  }
7441
7505
  var BASH_MARKER = "# >>> mihomo-cli completion (append)";
7506
+ var BASH_END_MARKER = BASH_MARKER.replace(">>>", "<<<");
7507
+ function hasBashMarkerBlock(content) {
7508
+ const start = content.indexOf(BASH_MARKER);
7509
+ const end = content.indexOf(BASH_END_MARKER);
7510
+ return start !== -1 && end !== -1 && end > start;
7511
+ }
7512
+ function productFingerprint(shell) {
7513
+ if (shell === "zsh") return "#compdef mihomo mhm mh mihomo-cli";
7514
+ if (shell === "fish") return "for cmd in mihomo mhm mh mihomo-cli";
7515
+ return null;
7516
+ }
7442
7517
  function completionInstallPath(shell) {
7443
7518
  const home = os3.homedir();
7444
7519
  switch (shell) {
@@ -7460,7 +7535,7 @@ function installCompletion(shell, commands) {
7460
7535
  }
7461
7536
  const target = completionInstallPath(shell);
7462
7537
  if (!target) {
7463
- buildCompletionScript(shell, commands);
7538
+ buildCompletionScript(shell, commands, "install");
7464
7539
  return;
7465
7540
  }
7466
7541
  const script = buildCompletionScript(shell, commands);
@@ -7468,18 +7543,36 @@ function installCompletion(shell, commands) {
7468
7543
  try {
7469
7544
  if (shell === "bash") {
7470
7545
  const existing = fs12.existsSync(target) ? fs12.readFileSync(target, "utf8") : "";
7471
- if (existing.includes(BASH_MARKER)) {
7546
+ if (hasBashMarkerBlock(existing)) {
7472
7547
  console.log("\u5DF2\u5B89\u88C5\u8FC7\uFF08~/.bash_completion \u5DF2\u5305\u542B mihomo \u8865\u5168\uFF09\uFF0C\u8DF3\u8FC7");
7473
7548
  return;
7474
7549
  }
7475
7550
  fs12.mkdirSync(path9.dirname(target), { recursive: true });
7476
7551
  fs12.appendFileSync(target, `
7477
7552
  ${BASH_MARKER}
7478
- ${script}${BASH_MARKER.replace(">>>", "<<<")}
7553
+ ${script}${BASH_END_MARKER}
7479
7554
  `);
7480
7555
  console.log(colors.green("\u5DF2\u8FFD\u52A0\u5230 ~/.bash_completion\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
7481
7556
  return;
7482
7557
  }
7558
+ const fingerprint = productFingerprint(shell);
7559
+ if (fingerprint && fs12.existsSync(target)) {
7560
+ const existing = fs12.readFileSync(target, "utf8");
7561
+ if (!existing.includes(fingerprint)) {
7562
+ throw new CliError(`${target} \u5DF2\u5B58\u5728\u4E14\u4E0D\u50CF\u662F mihomo-cli \u751F\u6210\u7684\u8865\u5168\uFF0C\u5DF2\u8DF3\u8FC7\u5B89\u88C5`, {
7563
+ label: "\u5B89\u88C5\u4E2D\u6B62",
7564
+ hint: [
7565
+ "\u8BE5\u6587\u4EF6\u53EF\u80FD\u662F\u4F60\u81EA\u5DF1\u6216\u5176\u4ED6\u5DE5\u5177\u5199\u7684\uFF0C\u8986\u76D6\u4F1A\u9020\u6210\u4E0D\u53EF\u6062\u590D\u7684\u4E22\u5931\u3002",
7566
+ "\u786E\u8BA4\u65E0\u7528\u540E\u5148\u624B\u52A8\u5220\u9664\uFF0C\u518D\u91CD\u65B0\u5B89\u88C5:",
7567
+ ` rm ${target}`,
7568
+ ` mihomo completion install ${shell}`,
7569
+ "",
7570
+ "\u6216\u6539\u4E3A\u624B\u52A8\u8F93\u51FA\u5230\u522B\u5904:",
7571
+ ` mihomo completion ${shell} > <\u4F60\u9009\u62E9\u7684\u8DEF\u5F84>`
7572
+ ]
7573
+ });
7574
+ }
7575
+ }
7483
7576
  fs12.mkdirSync(path9.dirname(target), { recursive: true });
7484
7577
  fs12.writeFileSync(target, script, { mode: 420 });
7485
7578
  console.log(colors.green("\u5DF2\u5199\u5165\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
@@ -7499,7 +7592,7 @@ function uninstallCompletion(shell, commands) {
7499
7592
  }
7500
7593
  const target = completionInstallPath(shell);
7501
7594
  if (!target) {
7502
- buildCompletionScript(shell, commands);
7595
+ buildCompletionScript(shell, commands, "uninstall");
7503
7596
  return;
7504
7597
  }
7505
7598
  if (!fs12.existsSync(target)) {
@@ -7510,29 +7603,36 @@ function uninstallCompletion(shell, commands) {
7510
7603
  try {
7511
7604
  if (shell === "bash") {
7512
7605
  const existing2 = fs12.readFileSync(target, "utf8");
7513
- const endMarker = BASH_MARKER.replace(">>>", "<<<");
7514
- const start = existing2.indexOf(BASH_MARKER);
7515
- const end = existing2.indexOf(endMarker);
7516
- if (start === -1 || end === -1 || end < start) {
7606
+ if (!hasBashMarkerBlock(existing2)) {
7517
7607
  console.log(colors.yellow("\u672A\u627E\u5230 mihomo \u8865\u5168\u6807\u8BB0\uFF0C\u672A\u505A\u6539\u52A8"));
7518
7608
  console.log(colors.gray(` \u82E5\u66FE\u624B\u52A8\u5B89\u88C5\uFF0C\u8BF7\u81EA\u884C\u7F16\u8F91 ${target}`));
7519
7609
  return;
7520
7610
  }
7521
- const before = existing2.slice(0, start).replace(/\n+$/, "\n");
7522
- const after = existing2.slice(end + endMarker.length).replace(/^\n/, "");
7523
- const rest = `${before}${after}`;
7611
+ let rest = existing2;
7612
+ let removed = 0;
7613
+ while (hasBashMarkerBlock(rest)) {
7614
+ const start = rest.indexOf(BASH_MARKER);
7615
+ const end = rest.indexOf(BASH_END_MARKER);
7616
+ const before = rest.slice(0, start).replace(/\n+$/, "\n");
7617
+ const after = rest.slice(end + BASH_END_MARKER.length).replace(/^\n/, "");
7618
+ rest = `${before}${after}`;
7619
+ removed++;
7620
+ }
7524
7621
  if (rest.trim() === "") {
7525
7622
  fs12.rmSync(target);
7526
7623
  console.log(colors.green("\u5DF2\u79FB\u9664\uFF08\u6587\u4EF6\u5DF2\u7A7A\uFF0C\u4E00\u5E76\u5220\u9664\uFF1B\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
7527
7624
  return;
7528
7625
  }
7529
7626
  fs12.writeFileSync(target, rest);
7627
+ if (removed > 1) {
7628
+ console.log(colors.gray(` \u53D1\u73B0\u5E76\u79FB\u9664\u4E86 ${removed} \u4EFD\u91CD\u590D\u7684\u8865\u5168\u6BB5`));
7629
+ }
7530
7630
  console.log(colors.green("\u5DF2\u79FB\u9664 mihomo \u8865\u5168\u6BB5\uFF0C\u4FDD\u7559\u6587\u4EF6\u4E2D\u5176\u4F59\u5185\u5BB9\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
7531
7631
  return;
7532
7632
  }
7533
7633
  const existing = fs12.readFileSync(target, "utf8");
7534
- const fingerprint = shell === "zsh" ? "#compdef mihomo mhm mh mihomo-cli" : "for cmd in mihomo mhm mh mihomo-cli";
7535
- if (!existing.includes(fingerprint)) {
7634
+ const fingerprint = productFingerprint(shell);
7635
+ if (!fingerprint || !existing.includes(fingerprint)) {
7536
7636
  throw new CliError(`${target} \u4E0D\u50CF\u662F mihomo-cli \u751F\u6210\u7684\u8865\u5168\uFF0C\u5DF2\u8DF3\u8FC7\u5220\u9664`, {
7537
7637
  label: "\u5378\u8F7D\u4E2D\u6B62",
7538
7638
  hint: ["\u8BE5\u6587\u4EF6\u53EF\u80FD\u662F\u4F60\u81EA\u5DF1\u6216\u5176\u4ED6\u5DE5\u5177\u5199\u7684\u3002\u786E\u8BA4\u65E0\u7528\u540E\u624B\u52A8\u5220\u9664:", ` rm ${target}`]
@@ -7698,6 +7798,7 @@ async function collectChecks() {
7698
7798
  const push = (name, status, detail, fix, notes) => {
7699
7799
  checks.push({ name, status, detail, fix, notes });
7700
7800
  };
7801
+ const latestVersionPromise = getLatestNpmVersion(4e3).catch(() => null);
7701
7802
  if (!hasKernel()) {
7702
7803
  push("\u5185\u6838", "fail", "\u672A\u5B89\u88C5", "mihomo kernel");
7703
7804
  } else {
@@ -7825,7 +7926,7 @@ async function collectChecks() {
7825
7926
  } else {
7826
7927
  push("\u4EE3\u7406\u8FDE\u901A", "skip", "\u672A\u8FD0\u884C");
7827
7928
  }
7828
- const latest = await getLatestNpmVersion(4e3);
7929
+ const latest = await latestVersionPromise;
7829
7930
  if (latest === null) {
7830
7931
  push("CLI \u7248\u672C", "skip", "npm registry \u4E0D\u53EF\u8FBE\uFF0C\u8DF3\u8FC7\u68C0\u67E5");
7831
7932
  } else if (compareVersions(latest, VERSION) > 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mihomo-cli",
3
- "version": "4.11.0",
3
+ "version": "4.13.0",
4
4
  "type": "module",
5
5
  "description": "A terminal-based mihomo (Clash.Meta) client for macOS",
6
6
  "bin": {