mihomo-cli 26.11.116 → 26.11.118

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,21 @@
1
1
  # Changelog
2
2
 
3
+ ## [26.11.118] - 2026-11-21
4
+
5
+ ### 变更
6
+
7
+ - 本次发布无用户可见行为变化
8
+
9
+ ## [26.11.117] - 2026-11-19
10
+
11
+ ### 修复
12
+
13
+ - 以 root 身份运行 `version`、`-v` 或 `--version` 时只显示 CLI 版本,避免以管理员权限执行用户数据目录里的内核
14
+ - `doctor` 给出的暂存目录和备份目录删除命令会正确引用路径,目录名含空格或单引号时也能安全复制执行
15
+ - `kernel --mirror direct` 和 `kernel --proxy` 使用指定通道检查更新,本机服务状态查询失败也能开始查询版本
16
+ - Mixed 服务热重载成功后,即使暂时查不到自启状态,也能显示当前服务的进程号
17
+ - 订阅下载失败时,错误提示只显示一次 HTTP 状态码
18
+
3
19
  ## [26.11.116] - 2026-11-09
4
20
 
5
21
  ### 移除
@@ -103,30 +119,3 @@
103
119
  ### 变更(内部清理,无用户可见变化)
104
120
 
105
121
  - uninstall 无服务分支少一次重复的进程探测;残留分档用例归位 process-stop.spec、service.ts 拆除 process-stop 转发 re-export、StatusJson 公开契约改回显式声明。956 用例全绿
106
-
107
- ## [26.10.108] - 2026-10-04
108
-
109
- ### 修复
110
-
111
- - **`ui -c` 写剪贴板加 3 秒超时**:剪贴板服务(pboard)短暂无响应时 pbcopy 不再让命令无限挂死、Ctrl+C 前无任何输出,与读剪贴板侧既有超时对称
112
-
113
- ### 变更(内部加固,无用户可见变化)
114
-
115
- - **手改 cache.json 的坏条目按无缓存处理**:单条被写成字符串/数字时不再展开成数字键垃圾对象,与 saveSubscriptionCache 同判据(新增不变量用例锁住);`lsofListenPids` 注释如实写明 null/[] 三态不可达(lsof 对「无匹配」与 fatal 同退 1,消费方不得假设二者之别);覆写文件排序键改为每文件只构建一次。961 用例全绿
116
-
117
- ## [26.10.107] - 2026-10-04
118
-
119
- ### 修复
120
-
121
- - **curl 代理通道不再被 no_proxy 例外表静默改写**:shell 里 export 过 `no_proxy='*'` 或含目标域条目时,curl 会绕过显式 `-x` 直连——版本查询、内核下载、连通性探测三处 spawn 统一置空 per-spawn env 的 no_proxy/NO_PROXY(`curl-spawn.ts` 唯一出口,新增加 curl 必须经此);direct 通道显式 `--noproxy '*'` 堵住另一类分叉——curl 默认读 `https_proxy` 等 env 代理,此前 `--mirror direct` 的「强制直连」实际会经 shell 代理出网,两条出网路径分叉、故障时还把原因误诊成直连被墙
122
- - **订阅下载重定向逐跳校验 https**:改手动逐跳跟随、每一跳校验协议并设 20 跳上限,堵「先降 http 再跳回 https」的中间明文 hop——订阅 URL 的 token 常被服务器保留在重定向查询串里,旧守卫只看最终地址挡不住;错误消息对降级地址脱敏
123
- - **启动 TUN 失败的恢复指引扩面**:关掉服务自启后任何一步失败(订阅校验/自动更新/配置构建/启动本身)都在错误里带「恢复 Mixed: `mihomo-cli start`」,此前只有启动失败分支带——只报「配置错误」会让用户以为一切照旧,下次开机才发现代理没回来
124
- - **status/doctor 对坏状态容错**:手改 settings.json 写入非法订阅名不再击穿 status 整屏报错;doctor 内核版本检查失败带真实原因(「全部是预发行版」「未找到 curl」不再一律渲染成「GitHub 不可达」);start 成功后的系统代理提示撞上坏 ports 配置时降级默认端口提示,不再把成功命令翻成 exit 1
125
- - **`sub remove` 删最后一个订阅保留运行中提示**:此前按「切换目标」判定会把提示整个吞掉;没有可切换的新订阅时提示改为「(订阅已全部删除),重新添加订阅后执行 mihomo-cli start tun」
126
- - **`reset service` 补残留进程提示**:纯重置服务此前把卸载透传的残留进程丢弃、「已重置: 服务」成了谎报,现在与 uninstall 同款式黄字列出 PID
127
- - **覆写键 `++key` 加载即报错**:`++rules`/`rules++` 这类笔误此前静默落成字面顶层键不生效(内核对未知键宽容),`++secret` 还绕过锁定键告警;与 `key!+` 同口径报「操作符位置矛盾」
128
- - **其余并发与容错修正**:内核配置校验的临时 stage 迁出会被整目录删除的 runtime/(并发 stop/reset 曾把校验配置一起删掉,把误诊指向毫无问题的订阅/覆写);sudo 脚本名加 pid 后缀,双终端并发跑同一动作不再互踩「密码正确却报已取消」;启动过程中订阅被并发移除时给「已被移除」分档报错,不再指引必败的 `sub update <已删除名>`;热重载的控制器端口与密钥改同一份快照读取(settings 被原子替换时不再发新端口带旧密钥);`-h` 提示文案与实际命令级帮助行为对齐
129
-
130
- ### 变更(内部清理,无用户可见变化)
131
-
132
- - **/simplify 三轮收尾**:`firstLine` 收编全仓 12 处 `split('\n')[0]` 副本;卸载/重置残留提示与 bootout 未装载容忍码(3/113)收单点(TS 判定与 legacy bash 脚本生成共用一份码表);控制器端口+密钥快照读收 `getControllerEndpoint`;CliError 再包装收 `relabelCliError`(exitCode 透传在结构上不可能丢);「桩 curl 记录 no_proxy」端到端夹具收 test-support 新模块(三份逐字骨架合一);http 手动跟随重定收单循环。960 用例全绿
package/LICENSE CHANGED
@@ -2,6 +2,10 @@ MIT License
2
2
 
3
3
  Copyright (c) 2026 mihomo-cli contributors
4
4
 
5
+ Bundled software covered by the same MIT license:
6
+ compare-versions: Copyright (c) 2015-2021 Ole Michelsen
7
+ js-yaml: Copyright (C) 2011-2015 by Vitaly Puzrin
8
+
5
9
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
10
  of this software and associated documentation files (the "Software"), to deal
7
11
  in the Software without restriction, including without limitation the rights
package/README.md CHANGED
@@ -28,7 +28,7 @@
28
28
 
29
29
  ## 安装
30
30
 
31
- **前置要求:Node.js >= 24.20.0**。入口有版本守卫,低版本会直接报错并给出升级指引
31
+ **前置要求:Node.js >= 24.20.0**
32
32
 
33
33
  ### 方式一:npm 全局安装
34
34
 
@@ -149,7 +149,7 @@ mihomo-cli ui yacd # YACD
149
149
 
150
150
  `ow on/off` 是全局总开关。只停用某一个 YAML 文件时,在该文件中写 `enabled: false`;单个 JS 脚本通过改扩展名停用,见[覆写配置](#覆写配置)
151
151
 
152
- `config` 不写盘、不重启,也不执行内核原生校验;校验由 `start` / `doctor` 完成。默认脱敏只是降低展示泄漏概率,`--reveal` 会明文输出节点密码、UUID、私钥、控制器密钥及 provider URL,不要在录屏、管道或求助文本中未经检查使用
152
+ `config` 只预览候选配置。`start` 和 `doctor` 会调用内核校验配置,`start` 校验通过后才写入 `runtime/config.yaml` 并应用。默认脱敏只是降低展示泄漏概率,`--reveal` 会明文输出节点密码、UUID、私钥、控制器密钥及 provider URL,不要在录屏、管道或求助文本中未经检查使用
153
153
 
154
154
  ### 其他命令
155
155
 
@@ -294,7 +294,7 @@ TUN 会劫持 53 端口流量,因此 `dns.enable` 恒为 `true`;订阅或覆
294
294
 
295
295
  ### 不要用 sudo 运行整个 CLI
296
296
 
297
- `sudo mihomo-cli …` 会被拒绝。服务属于当前用户的 `gui/<uid>` 域,TUN 所需权限由 CLI 内部按需申请,无需也不能在外层加 `sudo`
297
+ 用普通用户身份运行 CLI。服务属于当前用户的 `gui/<uid>` 域,TUN 需要管理员权限时会单独提示输入密码。命令的权限检查范围见[安全说明](SECURITY.md#提权与代理设置范围)
298
298
 
299
299
  ### 日志
300
300
 
@@ -457,7 +457,7 @@ mihomo-cli start --update-timeout=30000
457
457
 
458
458
  ## 覆写配置
459
459
 
460
- 覆写在订阅配置基础上做自定义修改,原始订阅文件保持独立。支持 YAML 声明式合并和 JS 同步脚本,默认启用;修改文件后执行 `mihomo-cli start` 应用
460
+ 覆写在订阅配置基础上做自定义修改,原始订阅文件保持独立。支持 YAML 声明式合并和 JS 同步脚本,默认启用。修改文件后,使用 Mixed 的用户执行 `mihomo-cli start` 应用,使用 TUN 的用户执行 `mihomo-cli start tun`
461
461
 
462
462
  - `mihomo-cli ow` 查看文件与加载状态,`ow on/off` 控制全局开关
463
463
  - 单个 YAML 文件用 `enabled: false` 停用,单个 JS 脚本通过改扩展名停用
@@ -561,7 +561,7 @@ Mixed 端口和控制器由 CLI 统一管理,订阅与覆写不能修改,默
561
561
  }
562
562
  ```
563
563
 
564
- 修改后执行 `mihomo-cli start` 才会应用。Web UI 控制器地址以及你手动配置的具体应用代理都要使用新值,`status` 会显示实际端口
564
+ 修改后按使用的模式执行 `mihomo-cli start`(Mixed)或 `mihomo-cli start tun`(TUN)。Web UI 控制器地址以及你手动配置的具体应用代理都要使用新值,`status` 会显示实际端口
565
565
 
566
566
  ## 安全特性
567
567
 
package/SECURITY.md CHANGED
@@ -52,11 +52,11 @@ CLI 下载 [MetaCubeX/mihomo](https://github.com/MetaCubeX/mihomo) 的 release
52
52
 
53
53
  ### 提权与代理设置范围
54
54
 
55
- - CLI 本身**拒绝以 root 运行**(`sudo mihomo-cli …` 会直接报错)
55
+ - 除顶层 `help` 和 `version`(含别名)外,CLI 拒绝以 root 运行。root 运行 `version` 时只显示 CLI 版本。用普通用户身份运行才能查询已安装的内核版本
56
56
  - Mixed 由用户级 LaunchAgent(`gui/<uid>`)托管,正常服务操作免密;清理 root 属主的 TUN 残留时可能按需请求管理员密码
57
57
  - TUN 按需 `sudo` 启动临时进程,用 `mihomo-cli stop` 清理
58
58
  - CLI **从不读取或修改 macOS 系统代理**,也不提供全局 `proxy on/off`;需要代理的具体浏览器或应用自行配置 Mixed 地址
59
59
 
60
60
  ### 平台
61
61
 
62
- 仅支持 macOS。非 macOS 上直接报错退出,不提供部分可用的降级路径
62
+ 仅支持 macOS。默认情况下,非 macOS 平台只放行顶层 `help` 和 `version`(含别名);开发用的平台检查开关不代表支持其他系统
package/dist/index.js CHANGED
@@ -168,6 +168,7 @@ var pkg = require2("../package.json");
168
168
  var YAML_MAX_ALIASES = 200;
169
169
  var VERSION = pkg.version;
170
170
  var PKG_NAME = pkg.name;
171
+ var CLI_ALIASES = Object.keys(pkg.bin).filter((name) => name !== PKG_NAME);
171
172
  var NODE_ENGINES = typeof pkg.engines?.node === "string" ? pkg.engines.node : null;
172
173
  var MIRROR_HOST = "gh-proxy.org";
173
174
  var MIRROR_ALIASES = {
@@ -3716,7 +3717,7 @@ var PATHS = {
3716
3717
  userAgentPlist: path.join(os.homedir(), "Library/LaunchAgents", `${SERVICE_LABEL}.plist`)
3717
3718
  };
3718
3719
  var DIRECTORY_TARGETS = {
3719
- root: { path: null, label: "\u6839\u76EE\u5F55" },
3720
+ root: { path: USER_DATA_DIR, label: "\u6839\u76EE\u5F55" },
3720
3721
  subs: { path: DIRS.subscriptions, label: "\u8BA2\u9605\u76EE\u5F55" },
3721
3722
  logs: { path: DIRS.logs, label: "\u65E5\u5FD7\u76EE\u5F55" },
3722
3723
  data: { path: DIRS.data, label: "\u8FD0\u884C\u6570\u636E\u76EE\u5F55" },
@@ -4263,20 +4264,7 @@ function protoKeyInOverwriteError() {
4263
4264
  });
4264
4265
  }
4265
4266
  function mergeConfigLevel(target, override, parseOperators) {
4266
- let t = target;
4267
- if (t === null || t === void 0) {
4268
- t = Array.isArray(override) ? [] : {};
4269
- }
4270
- if (override === null || override === void 0) {
4271
- return t;
4272
- }
4273
- if (typeof override !== "object") {
4274
- return override;
4275
- }
4276
- if (Array.isArray(override)) {
4277
- return override;
4278
- }
4279
- const result = { ...t };
4267
+ const result = { ...target };
4280
4268
  for (const [rawKey, value] of Object.entries(override)) {
4281
4269
  let key = rawKey;
4282
4270
  let forceOverwrite = false;
@@ -4310,7 +4298,7 @@ function mergeConfigLevel(target, override, parseOperators) {
4310
4298
  result[key] = value;
4311
4299
  continue;
4312
4300
  }
4313
- if (value !== null && typeof value === "object" && !Array.isArray(value) && existingValue !== null && typeof existingValue === "object" && !Array.isArray(existingValue)) {
4301
+ if (isPlainObject(value) && isPlainObject(existingValue)) {
4314
4302
  result[key] = mergeConfigLevel(existingValue, value, false);
4315
4303
  continue;
4316
4304
  }
@@ -4318,8 +4306,7 @@ function mergeConfigLevel(target, override, parseOperators) {
4318
4306
  }
4319
4307
  return result;
4320
4308
  }
4321
- function isOverwriteEnabled() {
4322
- const settings = readSettings();
4309
+ function isOverwriteEnabled(settings = readSettings()) {
4323
4310
  return settings.overwrite_enabled !== false;
4324
4311
  }
4325
4312
  function setOverwriteEnabled(enabled) {
@@ -4368,13 +4355,12 @@ function normalizeMatch(raw, fileName) {
4368
4355
  hint: ["match: \u540E\u9762\u8981\u8DDF\u6761\u4EF6\u5757\uFF08\u68C0\u67E5\u7F29\u8FDB\uFF09\uFF0C\u5982:", " match:", " name: edu*"]
4369
4356
  });
4370
4357
  }
4371
- if (typeof raw !== "object" || Array.isArray(raw)) {
4358
+ if (!isPlainObject(raw)) {
4372
4359
  throw new CliError(`\u8986\u5199\u6587\u4EF6 "${fileName}" \u7684 match \u5FC5\u987B\u662F\u5BF9\u8C61\uFF08name / url-domain\uFF09`, { label: "\u8986\u5199\u914D\u7F6E\u9519\u8BEF" });
4373
4360
  }
4374
- const rawEntries = raw;
4375
4361
  const result = {};
4376
4362
  const problems = [];
4377
- for (const [key, value] of Object.entries(rawEntries)) {
4363
+ for (const [key, value] of Object.entries(raw)) {
4378
4364
  if (!MATCH_KEYS.has(key)) {
4379
4365
  problems.push(`\u672A\u77E5\u952E "${key}"`);
4380
4366
  continue;
@@ -4584,7 +4570,7 @@ function readOverwriteFiles() {
4584
4570
  if (isBlankYamlDocument(content)) continue;
4585
4571
  const parsed = load(content, { maxAliases: YAML_MAX_ALIASES });
4586
4572
  assertConfigGraphSafe(parsed, `\u8986\u5199\u6587\u4EF6 "${file}"`);
4587
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
4573
+ if (isPlainObject(parsed)) {
4588
4574
  const { match, enabled, ...config } = parsed;
4589
4575
  assertNoMetadataKeyLookalikes(config, file);
4590
4576
  assertFileLevelOperatorRules(config, file);
@@ -4603,10 +4589,14 @@ function readOverwriteFiles() {
4603
4589
  return { ok, broken };
4604
4590
  }
4605
4591
  function isBlankYamlDocument(content) {
4606
- return content.split("\n").every((line) => {
4607
- const t = line.trim();
4608
- return t === "" || t.startsWith("#");
4609
- });
4592
+ for (let start = 0; start < content.length; ) {
4593
+ const end = content.indexOf("\n", start);
4594
+ const line = content.slice(start, end === -1 ? void 0 : end).trimStart();
4595
+ if (line && !line.startsWith("#")) return false;
4596
+ if (end === -1) break;
4597
+ start = end + 1;
4598
+ }
4599
+ return true;
4610
4600
  }
4611
4601
  function overwriteSortKey(filename) {
4612
4602
  const segment = isScriptOverwriteFilename(filename) ? "0" : "1";
@@ -4777,7 +4767,7 @@ function assertConfigShape(config) {
4777
4767
  function buildConfig(subRawContent, mode, scope) {
4778
4768
  const subscriptionConfig = parseConfigContent(subRawContent, "\u8BA2\u9605\u5185\u5BB9");
4779
4769
  const settings = readSettings();
4780
- const allFiles = settings.overwrite_enabled !== false ? loadOverwriteFile() : [];
4770
+ const allFiles = isOverwriteEnabled(settings) ? loadOverwriteFile() : [];
4781
4771
  const overwriteFiles = selectActiveOverwriteFiles(allFiles, scope);
4782
4772
  const {
4783
4773
  config: withOverwrites,
@@ -5206,6 +5196,58 @@ async function waitUntilUnloaded(target = serviceTarget(), options = {}) {
5206
5196
  });
5207
5197
  }
5208
5198
 
5199
+ // src/sudo.ts
5200
+ import { spawnSync as spawnSync3 } from "child_process";
5201
+ import fs6 from "fs";
5202
+ import path5 from "path";
5203
+ var SUDO_TIMEOUT_MS = 6e4;
5204
+ function isRoot() {
5205
+ return process.getuid?.() === 0 || process.geteuid?.() === 0;
5206
+ }
5207
+ var SudoAuthError = class extends Error {
5208
+ constructor() {
5209
+ super("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
5210
+ this.name = "SudoAuthError";
5211
+ }
5212
+ };
5213
+ function describeSudoFailure(e) {
5214
+ return e instanceof SudoAuthError ? "sudo \u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF" : e.message;
5215
+ }
5216
+ function sudoResultToError(action, result, codeMessages) {
5217
+ if (result.error) {
5218
+ if (result.error.code === "ETIMEDOUT") return sudoTimeoutError(action);
5219
+ return result.error;
5220
+ }
5221
+ const { status } = result;
5222
+ if (status === 0) return null;
5223
+ if (status === 1) return new SudoAuthError();
5224
+ if (status === null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
5225
+ const custom = codeMessages?.[status];
5226
+ return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
5227
+ }
5228
+ function sudoTimeoutError(action) {
5229
+ return new Error(`${action}\u8D85\u65F6\uFF08${SUDO_TIMEOUT_MS / 1e3}s \u672A\u5B8C\u6210\uFF09\uFF1A\u5BC6\u7801\u8F93\u5165\u6216\u811A\u672C\u6267\u884C\u8D85\u8FC7\u65F6\u9650\uFF0C\u64CD\u4F5C\u53EF\u80FD\u53EA\u5B8C\u6210\u4E86\u4E00\u90E8\u5206\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u8BD5`);
5230
+ }
5231
+ function runSudoScript(scriptBody, opts) {
5232
+ if (!process.stdin.isTTY) {
5233
+ throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
5234
+ }
5235
+ ensureDirs();
5236
+ const scriptPath = path5.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
5237
+ fs6.writeFileSync(scriptPath, scriptBody, { mode: 448 });
5238
+ fs6.chmodSync(scriptPath, 448);
5239
+ try {
5240
+ const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
5241
+ const error = sudoResultToError(opts.action, result, opts.codeMessages);
5242
+ if (error) throw error;
5243
+ } finally {
5244
+ try {
5245
+ fs6.unlinkSync(scriptPath);
5246
+ } catch {
5247
+ }
5248
+ }
5249
+ }
5250
+
5209
5251
  // src/suggest.ts
5210
5252
  function levenshtein(a, b) {
5211
5253
  if (a === b) return 0;
@@ -5275,8 +5317,15 @@ var GROUP_TITLES = [
5275
5317
  ["system", "\u7CFB\u7EDF:"]
5276
5318
  ];
5277
5319
  function printHelp(commands) {
5278
- const lines = [`
5279
- ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\u540D: mh", "", "\u7528\u6CD5:", " mihomo-cli <\u547D\u4EE4> [\u9009\u9879]"];
5320
+ const lines = [
5321
+ `
5322
+ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`,
5323
+ "",
5324
+ `\u547D\u4EE4\u522B\u540D: ${CLI_ALIASES.join(", ")}`,
5325
+ "",
5326
+ "\u7528\u6CD5:",
5327
+ " mihomo-cli <\u547D\u4EE4> [\u9009\u9879]"
5328
+ ];
5280
5329
  const allUsage = commands.flatMap((c) => c.usage);
5281
5330
  const signatureWidth = Math.max(...allUsage.map((u) => displayWidth(u.signature)));
5282
5331
  const formatUsage = (u) => ` ${colors.bold(padEndDisplay(u.signature, signatureWidth))} ${u.description}`;
@@ -5353,9 +5402,9 @@ function printHelpEntry(args, commands, finder) {
5353
5402
  printCommandHelp(command);
5354
5403
  }
5355
5404
  function printVersion() {
5356
- const kv = getKernelVersion() || "\u672A\u5B89\u88C5";
5357
5405
  console.log(colors.cyan(colors.bold(`mihomo-cli v${VERSION}`)));
5358
- console.log(`${colors.gray("\u5185\u6838: ")}${kv}`);
5406
+ if (isRoot()) return;
5407
+ console.log(`${colors.gray("\u5185\u6838: ")}${getKernelVersion() || "\u672A\u5B89\u88C5"}`);
5359
5408
  console.log(`${colors.gray("\u6570\u636E\u76EE\u5F55: ")}${USER_DATA_DIR}`);
5360
5409
  }
5361
5410
 
@@ -5398,6 +5447,7 @@ function redactConfigSecrets(config) {
5398
5447
  }
5399
5448
 
5400
5449
  // src/http.ts
5450
+ import { StringDecoder } from "string_decoder";
5401
5451
  var MAX_RESPONSE_BYTES = 50 * 1024 * 1024;
5402
5452
  var MAX_REDIRECTS = 20;
5403
5453
  var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
@@ -5475,7 +5525,8 @@ function createHttpClient(options = {}) {
5475
5525
  async function readBodyWithLimit(response, controller, limit) {
5476
5526
  if (!response.body) return response.text();
5477
5527
  const reader = response.body.getReader();
5478
- const chunks = [];
5528
+ const decoder = new StringDecoder("utf8");
5529
+ let text = "";
5479
5530
  let total = 0;
5480
5531
  try {
5481
5532
  while (true) {
@@ -5487,13 +5538,13 @@ async function readBodyWithLimit(response, controller, limit) {
5487
5538
  controller.abort();
5488
5539
  throw new Error(`\u54CD\u5E94\u4F53\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650\uFF08${formatBytes(limit)}\uFF09`);
5489
5540
  }
5490
- chunks.push(value);
5541
+ text += decoder.write(value);
5491
5542
  }
5492
5543
  }
5493
5544
  } finally {
5494
5545
  reader.releaseLock();
5495
5546
  }
5496
- return Buffer.concat(chunks).toString("utf8");
5547
+ return text + decoder.end();
5497
5548
  }
5498
5549
 
5499
5550
  // src/spinner.ts
@@ -5677,15 +5728,8 @@ async function downloadSubscription(url, subName, signal) {
5677
5728
  try {
5678
5729
  response = await HTTP_CLIENT.get(url, { signal });
5679
5730
  } catch (e) {
5680
- const maskedUrl = maskUrl(url);
5681
- let errorMsg = `\u83B7\u53D6\u8BA2\u9605\u5931\u8D25: ${e.message}`;
5682
- const err = e;
5683
- if (err.response) {
5684
- errorMsg += ` (HTTP ${err.response.status})`;
5685
- }
5686
- errorMsg += `
5687
- URL: ${maskedUrl}`;
5688
- throw new Error(errorMsg);
5731
+ throw new Error(`\u83B7\u53D6\u8BA2\u9605\u5931\u8D25: ${errorMessage(e)}
5732
+ URL: ${maskUrl(url)}`);
5689
5733
  }
5690
5734
  const content = response.data;
5691
5735
  if (!content?.trim()) {
@@ -5736,15 +5780,14 @@ async function prepareConfigForStart(mode, subName) {
5736
5780
  throw e;
5737
5781
  }
5738
5782
  const subUrl = getSubscriptions().find((s) => s.name === subName)?.url;
5739
- const buildResult = buildConfig(rawContent, mode, { subName, subUrl });
5740
- const candidateContent = dumpYaml(buildResult.config);
5741
- await validateConfigWithKernel(candidateContent, buildResult.overwriteSummaries);
5742
- return { buildResult, candidateContent, info: countConfigNodes(buildResult.config) };
5783
+ const { config, warnings, overwriteSummaries } = buildConfig(rawContent, mode, { subName, subUrl });
5784
+ const candidateContent = dumpYaml(config);
5785
+ await validateConfigWithKernel(candidateContent, overwriteSummaries);
5786
+ return { warnings, candidateContent, info: countConfigNodes(config) };
5743
5787
  }
5744
5788
  function commitPreparedConfig(prepared) {
5745
- const { buildResult } = prepared;
5746
- if (buildResult.warnings.length > 0) {
5747
- for (const warning of buildResult.warnings) {
5789
+ if (prepared.warnings.length > 0) {
5790
+ for (const warning of prepared.warnings) {
5748
5791
  console.log(`${colors.yellow("\u914D\u7F6E\u63D0\u793A:")} ${warning}`);
5749
5792
  }
5750
5793
  console.log("");
@@ -5927,8 +5970,8 @@ import fs12 from "fs";
5927
5970
  import { setTimeout as sleep4 } from "timers/promises";
5928
5971
 
5929
5972
  // src/log-files.ts
5930
- import fs6 from "fs";
5931
- import path5 from "path";
5973
+ import fs7 from "fs";
5974
+ import path6 from "path";
5932
5975
  var DEFAULT_LOG_RETENTION_DAYS = 7;
5933
5976
  var LOG_TAIL_LINES = 15;
5934
5977
  var ARCHIVE_LOG_RE = /^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})(?:\.\d+)?\.log$/;
@@ -5943,20 +5986,20 @@ function readLogTail() {
5943
5986
  const TAIL_BYTES = 64 * 1024;
5944
5987
  let fd = null;
5945
5988
  try {
5946
- const size = fs6.statSync(PATHS.logFile).size;
5989
+ const size = fs7.statSync(PATHS.logFile).size;
5947
5990
  if (size === 0) return [];
5948
5991
  const start = Math.max(0, size - TAIL_BYTES);
5949
5992
  const length = size - start;
5950
5993
  const buf = Buffer.alloc(length);
5951
- fd = fs6.openSync(PATHS.logFile, "r");
5952
- const bytesRead = fs6.readSync(fd, buf, 0, length, start);
5994
+ fd = fs7.openSync(PATHS.logFile, "r");
5995
+ const bytesRead = fs7.readSync(fd, buf, 0, length, start);
5953
5996
  return buf.subarray(0, bytesRead).toString("utf8").split("\n").map((l) => l.trimEnd()).filter((l) => l.length > 0).slice(-LOG_TAIL_LINES);
5954
5997
  } catch {
5955
5998
  return [];
5956
5999
  } finally {
5957
6000
  if (fd !== null) {
5958
6001
  try {
5959
- fs6.closeSync(fd);
6002
+ fs7.closeSync(fd);
5960
6003
  } catch {
5961
6004
  }
5962
6005
  }
@@ -5967,16 +6010,16 @@ function allocateArchivePath() {
5967
6010
  const timestamp = formatLocalTimestamp();
5968
6011
  for (let seq = 0; seq <= MAX_ARCHIVE_SEQ; seq++) {
5969
6012
  const name = seq === 0 ? `mihomo.${timestamp}.log` : `mihomo.${timestamp}.${seq}.log`;
5970
- const archivePath = path5.join(DIRS.logs, name);
6013
+ const archivePath = path6.join(DIRS.logs, name);
5971
6014
  let fd = null;
5972
6015
  try {
5973
- fd = fs6.openSync(archivePath, "wx");
6016
+ fd = fs7.openSync(archivePath, "wx");
5974
6017
  } catch (e) {
5975
6018
  if (e.code === "EEXIST") continue;
5976
6019
  throw e;
5977
6020
  }
5978
6021
  try {
5979
- fs6.closeSync(fd);
6022
+ fs7.closeSync(fd);
5980
6023
  } catch {
5981
6024
  }
5982
6025
  return archivePath;
@@ -5989,7 +6032,7 @@ function allocateArchivePath() {
5989
6032
  function rotateLog() {
5990
6033
  let stat;
5991
6034
  try {
5992
- stat = fs6.statSync(PATHS.logFile);
6035
+ stat = fs7.statSync(PATHS.logFile);
5993
6036
  } catch (e) {
5994
6037
  if (e.code === "ENOENT") return;
5995
6038
  throw e;
@@ -5997,10 +6040,10 @@ function rotateLog() {
5997
6040
  if (stat.size === 0) return;
5998
6041
  const rotatedPath = allocateArchivePath();
5999
6042
  try {
6000
- fs6.renameSync(PATHS.logFile, rotatedPath);
6043
+ fs7.renameSync(PATHS.logFile, rotatedPath);
6001
6044
  } catch (e) {
6002
6045
  try {
6003
- fs6.unlinkSync(rotatedPath);
6046
+ fs7.unlinkSync(rotatedPath);
6004
6047
  } catch {
6005
6048
  }
6006
6049
  if (e.code === "ENOENT") return;
@@ -6009,17 +6052,17 @@ function rotateLog() {
6009
6052
  }
6010
6053
  function cleanupOldLogs() {
6011
6054
  const logsDir = DIRS.logs;
6012
- if (!fs6.existsSync(logsDir)) return;
6013
- const files = fs6.readdirSync(logsDir);
6055
+ if (!fs7.existsSync(logsDir)) return;
6056
+ const files = fs7.readdirSync(logsDir);
6014
6057
  const now = Date.now();
6015
6058
  const maxAgeMs = DEFAULT_LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
6016
6059
  for (const file of files) {
6017
6060
  if (!isArchiveLogFilename(file)) continue;
6018
6061
  try {
6019
- const filePath = path5.join(logsDir, file);
6020
- const stat = fs6.statSync(filePath);
6062
+ const filePath = path6.join(logsDir, file);
6063
+ const stat = fs7.statSync(filePath);
6021
6064
  if (now - stat.mtimeMs > maxAgeMs) {
6022
- fs6.unlinkSync(filePath);
6065
+ fs7.unlinkSync(filePath);
6023
6066
  }
6024
6067
  } catch {
6025
6068
  }
@@ -6028,29 +6071,27 @@ function cleanupOldLogs() {
6028
6071
  function listLogs() {
6029
6072
  const logsDir = DIRS.logs;
6030
6073
  const result = { current: null, archives: [] };
6031
- if (fs6.existsSync(PATHS.logFile)) {
6032
- const stat = fs6.statSync(PATHS.logFile);
6074
+ if (fs7.existsSync(PATHS.logFile)) {
6075
+ const stat = fs7.statSync(PATHS.logFile);
6033
6076
  result.current = {
6034
- name: "mihomo.log (\u5F53\u524D)",
6077
+ name: path6.basename(PATHS.logFile),
6035
6078
  path: PATHS.logFile,
6036
6079
  size: stat.size,
6037
- mtime: stat.mtime,
6038
- isCurrent: true
6080
+ mtime: stat.mtime
6039
6081
  };
6040
6082
  }
6041
- if (!fs6.existsSync(logsDir)) return result;
6042
- const files = fs6.readdirSync(logsDir);
6083
+ if (!fs7.existsSync(logsDir)) return result;
6084
+ const files = fs7.readdirSync(logsDir);
6043
6085
  for (const file of files) {
6044
6086
  if (!isArchiveLogFilename(file)) continue;
6045
6087
  try {
6046
- const filePath = path5.join(logsDir, file);
6047
- const stat = fs6.statSync(filePath);
6088
+ const filePath = path6.join(logsDir, file);
6089
+ const stat = fs7.statSync(filePath);
6048
6090
  result.archives.push({
6049
6091
  name: file,
6050
6092
  path: filePath,
6051
6093
  size: stat.size,
6052
- mtime: stat.mtime,
6053
- isCurrent: false
6094
+ mtime: stat.mtime
6054
6095
  });
6055
6096
  } catch {
6056
6097
  }
@@ -6060,14 +6101,14 @@ function listLogs() {
6060
6101
  }
6061
6102
 
6062
6103
  // src/process-probe.ts
6063
- import { spawnSync as spawnSync3 } from "child_process";
6064
- import fs7 from "fs";
6104
+ import { spawnSync as spawnSync4 } from "child_process";
6105
+ import fs8 from "fs";
6065
6106
  var PS_TIMEOUT_MS = 5e3;
6066
6107
  var NOT_RUNNING = { alive: false, uid: null, rss: null, command: "" };
6067
6108
  function probeProcess(pid) {
6068
6109
  if (!pid) return NOT_RUNNING;
6069
6110
  try {
6070
- const result = spawnSync3("ps", ["-ww", "-p", String(pid), "-o", "pid=,uid=,rss=,command="], {
6111
+ const result = spawnSync4("ps", ["-ww", "-p", String(pid), "-o", "pid=,uid=,rss=,command="], {
6071
6112
  encoding: "utf8",
6072
6113
  timeout: PS_TIMEOUT_MS
6073
6114
  });
@@ -6084,9 +6125,9 @@ function isProbedMihomo(p) {
6084
6125
  var BINARY_ALTERNATION = `(${escapeRegExp(PATHS.serviceBinary)}|${escapeRegExp(PATHS.mihomoBinary)})`;
6085
6126
  var MAIN_INSTANCE_PATTERN = `${BINARY_ALTERNATION}.*${escapeRegExp(PATHS.configFile)}`;
6086
6127
  function getPid() {
6087
- if (!fs7.existsSync(PATHS.pidFile)) return null;
6128
+ if (!fs8.existsSync(PATHS.pidFile)) return null;
6088
6129
  try {
6089
- const pid = parseInt(fs7.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
6130
+ const pid = parseInt(fs8.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
6090
6131
  return pid > 0 ? pid : null;
6091
6132
  } catch {
6092
6133
  return null;
@@ -6101,7 +6142,7 @@ function isMihomoProcess(pid) {
6101
6142
  return isProbedMihomo(probeProcess(pid));
6102
6143
  }
6103
6144
  function getMihomoPids() {
6104
- const result = spawnSync3("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
6145
+ const result = spawnSync4("pgrep", ["-f", MAIN_INSTANCE_PATTERN], { encoding: "utf8", timeout: 1e4 });
6105
6146
  if (result.error || result.status === null) {
6106
6147
  throw new CliError("\u65E0\u6CD5\u63A2\u6D4B\u5185\u6838\u8FDB\u7A0B\uFF08pgrep \u6267\u884C\u5931\u8D25\uFF09", {
6107
6148
  hint: ["\u8FD9\u4E0D\u4EE3\u8868\u5185\u6838\u672A\u8FD0\u884C\uFF0C\u53EA\u8868\u793A\u67E5\u4E0D\u5230\u3002", "\u8BF7\u624B\u52A8\u786E\u8BA4: pgrep -fl mihomo-cli"]
@@ -6120,9 +6161,9 @@ function parsePidList(stdout) {
6120
6161
  return output.split("\n").filter(Boolean).map((p) => parseInt(p, 10)).filter((p) => Number.isInteger(p) && p > 0);
6121
6162
  }
6122
6163
  function isPidFileOwnedByRoot() {
6123
- if (!fs7.existsSync(PATHS.pidFile)) return false;
6164
+ if (!fs8.existsSync(PATHS.pidFile)) return false;
6124
6165
  try {
6125
- const stat = fs7.statSync(PATHS.pidFile);
6166
+ const stat = fs8.statSync(PATHS.pidFile);
6126
6167
  return stat.uid === 0;
6127
6168
  } catch {
6128
6169
  return false;
@@ -6144,57 +6185,6 @@ function getStatus() {
6144
6185
  import { spawnSync as spawnSync5 } from "child_process";
6145
6186
  import fs9 from "fs";
6146
6187
  import { setTimeout as sleep2 } from "timers/promises";
6147
-
6148
- // src/sudo.ts
6149
- import { spawnSync as spawnSync4 } from "child_process";
6150
- import fs8 from "fs";
6151
- import path6 from "path";
6152
- var SUDO_TIMEOUT_MS = 6e4;
6153
- var SudoAuthError = class extends Error {
6154
- constructor() {
6155
- super("\u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF");
6156
- this.name = "SudoAuthError";
6157
- }
6158
- };
6159
- function describeSudoFailure(e) {
6160
- return e instanceof SudoAuthError ? "sudo \u5DF2\u53D6\u6D88\u6216\u5BC6\u7801\u9519\u8BEF" : e.message;
6161
- }
6162
- function sudoResultToError(action, result, codeMessages) {
6163
- if (result.error) {
6164
- if (result.error.code === "ETIMEDOUT") return sudoTimeoutError(action);
6165
- return result.error;
6166
- }
6167
- const { status } = result;
6168
- if (status === 0) return null;
6169
- if (status === 1) return new SudoAuthError();
6170
- if (status === null) return new Error(`${action}\u88AB\u4E2D\u65AD\uFF08sudo \u8FDB\u7A0B\u88AB\u4FE1\u53F7\u7EC8\u6B62\uFF09`);
6171
- const custom = codeMessages?.[status];
6172
- return new Error(custom ?? `${action}\u5931\u8D25\uFF08\u9000\u51FA\u7801 ${status}\uFF09`);
6173
- }
6174
- function sudoTimeoutError(action) {
6175
- return new Error(`${action}\u8D85\u65F6\uFF08${SUDO_TIMEOUT_MS / 1e3}s \u672A\u5B8C\u6210\uFF09\uFF1A\u5BC6\u7801\u8F93\u5165\u6216\u811A\u672C\u6267\u884C\u8D85\u8FC7\u65F6\u9650\uFF0C\u64CD\u4F5C\u53EF\u80FD\u53EA\u5B8C\u6210\u4E86\u4E00\u90E8\u5206\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u8BD5`);
6176
- }
6177
- function runSudoScript(scriptBody, opts) {
6178
- if (!process.stdin.isTTY) {
6179
- throw new Error("\u5F53\u524D\u73AF\u5883\u65E0\u6CD5\u8F93\u5165\u7BA1\u7406\u5458\u5BC6\u7801\uFF08\u9700\u8981\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u8FD0\u884C sudo\uFF09");
6180
- }
6181
- ensureDirs();
6182
- const scriptPath = path6.join(USER_DATA_DIR, `${opts.file}.${process.pid}.tmp`);
6183
- fs8.writeFileSync(scriptPath, scriptBody, { mode: 448 });
6184
- fs8.chmodSync(scriptPath, 448);
6185
- try {
6186
- const result = spawnSync4("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
6187
- const error = sudoResultToError(opts.action, result, opts.codeMessages);
6188
- if (error) throw error;
6189
- } finally {
6190
- try {
6191
- fs8.unlinkSync(scriptPath);
6192
- } catch {
6193
- }
6194
- }
6195
- }
6196
-
6197
- // src/process-stop.ts
6198
6188
  var PROCESS_WAIT_ATTEMPTS = 50;
6199
6189
  var PROCESS_WAIT_INTERVAL = 100;
6200
6190
  var BATCH_KILL_THRESHOLD = 3;
@@ -6397,13 +6387,9 @@ function readStopEpoch() {
6397
6387
  return 0;
6398
6388
  }
6399
6389
  }
6400
- var stopEpochBaselineCaptured = null;
6390
+ var stopEpochBaseline = null;
6401
6391
  function captureStopEpochBaseline() {
6402
- stopEpochBaselineCaptured = readStopEpoch();
6403
- return stopEpochBaselineCaptured;
6404
- }
6405
- function stopEpochBaseline() {
6406
- return stopEpochBaselineCaptured ?? readStopEpoch();
6392
+ stopEpochBaseline = readStopEpoch();
6407
6393
  }
6408
6394
  function bumpStopEpoch() {
6409
6395
  try {
@@ -6416,7 +6402,7 @@ function epochChanged(before, now) {
6416
6402
  return now !== before;
6417
6403
  }
6418
6404
  function startAbortedByConcurrentStop() {
6419
- return epochChanged(stopEpochBaseline(), readStopEpoch());
6405
+ return stopEpochBaseline !== null && epochChanged(stopEpochBaseline, readStopEpoch());
6420
6406
  }
6421
6407
 
6422
6408
  // src/service.ts
@@ -6755,11 +6741,11 @@ function getRunningState(serviceStatus) {
6755
6741
  return { running: false, pid: null, kind: null, memory: null };
6756
6742
  }
6757
6743
  function restartModeFor(state, fallbackMode) {
6758
- return state.kind === "tun" ? "tun" : fallbackMode;
6744
+ return state.kind === "tun" ? "tun" : fallbackMode();
6759
6745
  }
6760
6746
  function restartModeOnChange() {
6761
6747
  const state = getRunningState();
6762
- return state.running ? restartModeFor(state, getRuntimeMode()) : null;
6748
+ return state.running ? restartModeFor(state, getRuntimeMode) : null;
6763
6749
  }
6764
6750
  async function launchOrRestart(mode) {
6765
6751
  if (mode === "tun") {
@@ -6785,7 +6771,7 @@ async function launchOrRestart(mode) {
6785
6771
  if (!started) throw cancelledByConcurrentStop();
6786
6772
  if (hotReloaded) {
6787
6773
  try {
6788
- return getServiceStatus().pid;
6774
+ return getServiceStatus({ withDisabled: false }).pid;
6789
6775
  } catch {
6790
6776
  return null;
6791
6777
  }
@@ -7327,18 +7313,12 @@ async function restartToApply(args) {
7327
7313
  // src/commands/directory.ts
7328
7314
  function openDirectory(args) {
7329
7315
  assertPositionalCount(args, 1, 2, "mihomo-cli dir open [root|subs|logs|data|runtime|kernel]");
7330
- const target = args[2];
7331
- if (target === void 0 || target === "root") {
7332
- console.log(`\u6B63\u5728\u6253\u5F00: \u6839\u76EE\u5F55 (${USER_DATA_DIR})`);
7333
- openUrl(USER_DATA_DIR);
7334
- return;
7335
- }
7316
+ const target = args[2] ?? "root";
7336
7317
  const key = target.toLowerCase();
7337
7318
  const targetInfo = Object.hasOwn(DIRECTORY_TARGETS, key) ? DIRECTORY_TARGETS[key] : void 0;
7338
7319
  if (targetInfo) {
7339
- const targetPath = targetInfo.path || USER_DATA_DIR;
7340
- console.log(`\u6B63\u5728\u6253\u5F00: ${targetInfo.label} (${targetPath})`);
7341
- openUrl(targetPath);
7320
+ console.log(`\u6B63\u5728\u6253\u5F00: ${targetInfo.label} (${targetInfo.path})`);
7321
+ openUrl(targetInfo.path);
7342
7322
  return;
7343
7323
  }
7344
7324
  const hint = ["", "\u53EF\u7528\u76EE\u6807:", " root (\u9ED8\u8BA4) \u6839\u76EE\u5F55"];
@@ -7369,10 +7349,8 @@ async function cmdDirectory(args) {
7369
7349
  assertKnownFlags(args.slice(1), [], "dir");
7370
7350
  await dispatchSubcommand(args, SUBCOMMANDS, {
7371
7351
  fallback: printDirectoryInfo,
7372
- // 裸 dir 只展示目录信息(选项由分发前的白名单统一拦);守卫收口在 shared
7373
7352
  onUnknown: (action) => unknownSubcommandError(action, SUBCOMMANDS, {
7374
7353
  what: "\u76EE\u5F55\u5B50\u547D\u4EE4",
7375
- optionHint: ["\u88F8 dir \u53EA\u5C55\u793A\u76EE\u5F55\u4FE1\u606F\uFF0C\u4E0D\u63A5\u53D7\u9009\u9879", "", "\u7528\u6CD5: mihomo-cli dir open [root|subs|logs|data|runtime|kernel]"],
7376
7354
  unknownHint: ["", "\u53EF\u7528\u5B50\u547D\u4EE4: open", "\u6253\u5F00\u6307\u5B9A\u76EE\u5F55: mihomo-cli dir open <target>"]
7377
7355
  })
7378
7356
  });
@@ -7421,7 +7399,7 @@ function resolveDownloadChannels(input) {
7421
7399
  return [input.proxyOverride ? { kind: "mirror", mirror: input.mirror, proxy: input.proxyOverride } : { kind: "mirror", mirror: input.mirror }];
7422
7400
  }
7423
7401
  if (input.proxyOverride) return [{ kind: "proxy", proxy: input.proxyOverride }];
7424
- if (input.proxyRunning && input.proxyPort !== null) {
7402
+ if (input.proxyPort !== null) {
7425
7403
  const proxyUrl = loopbackHttpUrl(input.proxyPort);
7426
7404
  const channels = [{ kind: "proxy", proxy: proxyUrl }];
7427
7405
  if (input.ghAvailable) channels.push({ kind: "gh", proxy: proxyUrl });
@@ -7432,12 +7410,9 @@ function resolveDownloadChannels(input) {
7432
7410
  }
7433
7411
  function resolveReleaseQuery(input) {
7434
7412
  const forceDirect = input.isOverride && !input.mirror;
7435
- const proxy = input.proxyOverride ?? (!forceDirect && input.proxyRunning && input.proxyPort !== null ? loopbackHttpUrl(input.proxyPort) : null);
7413
+ const proxy = input.proxyOverride ?? (!forceDirect && input.proxyPort !== null ? loopbackHttpUrl(input.proxyPort) : null);
7436
7414
  return { proxy, useGh: proxy === null && !forceDirect && input.ghAvailable };
7437
7415
  }
7438
- function ghProbeNeeded(input) {
7439
- return !input.forceDirect && input.proxyOverride === null;
7440
- }
7441
7416
  function hasGh() {
7442
7417
  const result = spawnSync8("gh", ["--version"], { stdio: "ignore", timeout: 3e3 });
7443
7418
  return !result.error && result.status === 0;
@@ -7527,10 +7502,9 @@ async function getLatestReleaseViaGh(repo, signal) {
7527
7502
  async function getLatestRelease(repo, opts) {
7528
7503
  if (opts.useGh) {
7529
7504
  try {
7530
- return await getLatestReleaseViaGh(repo, opts.signal);
7505
+ return { release: await getLatestReleaseViaGh(repo, opts.signal), ghFallbackToDirect: false };
7531
7506
  } catch (e) {
7532
7507
  if (opts.signal?.aborted) throw e;
7533
- opts.onGhFallback?.();
7534
7508
  }
7535
7509
  }
7536
7510
  const url = `https://api.github.com/repos/${repo}/releases`;
@@ -7559,16 +7533,11 @@ async function getLatestRelease(repo, opts) {
7559
7533
  } catch {
7560
7534
  throw new Error("\u7248\u672C\u67E5\u8BE2\u5931\u8D25: \u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF08\u4EE3\u7406\u53EF\u80FD\u8FD4\u56DE\u4E86\u9519\u8BEF\u9875\u9762\uFF09");
7561
7535
  }
7562
- return pickLatestRelease(releases);
7536
+ return { release: pickLatestRelease(releases), ghFallbackToDirect: opts.useGh && !opts.proxy };
7563
7537
  }
7564
7538
  async function checkUpdate(opts) {
7565
7539
  const currentVersion = opts.currentVersion !== void 0 ? opts.currentVersion : getKernelVersion();
7566
- let ghFallbackToDirect = false;
7567
- const optsWithFallbackNote = {
7568
- ...opts,
7569
- onGhFallback: opts.useGh && !opts.proxy ? () => ghFallbackToDirect = true : void 0
7570
- };
7571
- const latest = await getLatestRelease(GITHUB_REPO, optsWithFallbackNote);
7540
+ const { release: latest, ghFallbackToDirect } = await getLatestRelease(GITHUB_REPO, opts);
7572
7541
  const latestVersion = latest.tag_name;
7573
7542
  let needsUpdate = false;
7574
7543
  const currentDisplay = currentVersion || "\u672A\u5B89\u88C5";
@@ -8014,8 +7983,7 @@ async function collectChecks() {
8014
7983
  const releaseQuery = resolveReleaseQuery({
8015
7984
  mirror: null,
8016
7985
  isOverride: false,
8017
- ghAvailable: kernelProxyPort === null && hasGh(),
8018
- proxyRunning: earlyState.running,
7986
+ ghAvailable: kernelProbe !== null && kernelProxyPort === null && hasGh(),
8019
7987
  proxyPort: kernelProxyPort,
8020
7988
  proxyOverride: null
8021
7989
  });
@@ -8038,10 +8006,10 @@ async function collectChecks() {
8038
8006
  push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${kernelProbe.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo-cli kernel");
8039
8007
  }
8040
8008
  if (fs14.existsSync(KERNEL_SELF_UPDATE_DIR)) {
8041
- push("\u5185\u6838\u81EA\u5347\u7EA7\u6B8B\u7559", "warn", `\u4E2D\u65AD\u7684\u4E0B\u8F7D\u6682\u5B58: ${KERNEL_SELF_UPDATE_DIR}`, `rm -rf ${KERNEL_SELF_UPDATE_DIR}`);
8009
+ push("\u5185\u6838\u81EA\u5347\u7EA7\u6B8B\u7559", "warn", `\u4E2D\u65AD\u7684\u4E0B\u8F7D\u6682\u5B58: ${KERNEL_SELF_UPDATE_DIR}`, `rm -rf -- ${shellQuote(KERNEL_SELF_UPDATE_DIR)}`);
8042
8010
  }
8043
8011
  if (fs14.existsSync(KERNEL_SELF_BACKUP_DIR)) {
8044
- push("\u5185\u6838\u81EA\u5347\u7EA7\u5907\u4EFD", "ok", `\u65E7\u5185\u6838\u526F\u672C\uFF08\u9762\u677F\u5347\u7EA7\u81EA\u52A8\u4FDD\u7559\uFF0C\u4F9B\u56DE\u6EDA\uFF1B\u786E\u8BA4\u65B0\u7248\u7A33\u5B9A\u540E\u53EF\u5220: rm -rf ${KERNEL_SELF_BACKUP_DIR}\uFF09`);
8012
+ push("\u5185\u6838\u81EA\u5347\u7EA7\u5907\u4EFD", "ok", `\u65E7\u5185\u6838\u526F\u672C\uFF08\u9762\u677F\u5347\u7EA7\u81EA\u52A8\u4FDD\u7559\uFF0C\u4F9B\u56DE\u6EDA\uFF1B\u786E\u8BA4\u65B0\u7248\u7A33\u5B9A\u540E\u53EF\u5220: rm -rf -- ${shellQuote(KERNEL_SELF_BACKUP_DIR)}\uFF09`);
8045
8013
  }
8046
8014
  try {
8047
8015
  fs14.accessSync(USER_DATA_DIR, fs14.constants.W_OK);
@@ -8125,8 +8093,7 @@ async function collectChecks() {
8125
8093
  if (active && hasKernel()) {
8126
8094
  try {
8127
8095
  const mode = deriveRuntimeMode(info);
8128
- const prepared = await prepareConfigForStart(mode, active.name);
8129
- const warnings = prepared.buildResult.warnings;
8096
+ const { warnings } = await prepareConfigForStart(mode, active.name);
8130
8097
  if (warnings.length > 0) {
8131
8098
  push(
8132
8099
  "\u914D\u7F6E\u6784\u5EFA",
@@ -8396,21 +8363,20 @@ async function cmdKernel(args) {
8396
8363
  const mirrorInfo = parseMirrorArg(args);
8397
8364
  const proxyInfo = parseProxyArg(args);
8398
8365
  assertPositionalCount(args, 0, 1, "mihomo-cli kernel [--mirror [\u955C\u50CF]] [--proxy <\u7AEF\u53E3|\u5730\u5740>]");
8399
- if (proxyInfo.proxy && mirrorInfo.isOverride && !mirrorInfo.mirror) {
8366
+ const forceDirect = mirrorInfo.isOverride && !mirrorInfo.mirror;
8367
+ if (proxyInfo.proxy && forceDirect) {
8400
8368
  throw new CliError("--mirror direct \u4E0E --proxy \u4E0D\u80FD\u540C\u65F6\u4F7F\u7528", {
8401
8369
  label: "\u53C2\u6570\u9519\u8BEF",
8402
8370
  hint: ["--mirror direct \u5F3A\u5236\u4E0D\u7ECF\u4EE3\u7406\u76F4\u8FDE\uFF0C\u9700\u8D70\u4EE3\u7406\u65F6\u53BB\u6389\u5B83:", " mihomo-cli kernel --proxy <\u7AEF\u53E3|\u5730\u5740>"]
8403
8371
  });
8404
8372
  }
8405
- const proxyRunning = getRunningState().running;
8406
- const proxyPort = proxyRunning ? getPortsOrNull()?.mixed ?? null : null;
8407
- const forceDirect = mirrorInfo.isOverride && !mirrorInfo.mirror;
8408
- const ghAvailable = ghProbeNeeded({ forceDirect, proxyOverride: proxyInfo.proxy }) && hasGh();
8373
+ const probeLocalChannels = !forceDirect && proxyInfo.proxy === null;
8374
+ const proxyPort = probeLocalChannels && getRunningState().running ? getPortsOrNull()?.mixed ?? null : null;
8375
+ const ghAvailable = probeLocalChannels && (!mirrorInfo.isOverride || proxyPort === null) && hasGh();
8409
8376
  const channelInput = {
8410
8377
  mirror: mirrorInfo.mirror,
8411
8378
  isOverride: mirrorInfo.isOverride,
8412
8379
  ghAvailable,
8413
- proxyRunning,
8414
8380
  proxyPort,
8415
8381
  proxyOverride: proxyInfo.proxy
8416
8382
  };
@@ -8499,12 +8465,11 @@ function cmdLogs(args) {
8499
8465
  const lines = parseIntArg(args, "-n", "--lines", 100);
8500
8466
  const openInViewer = hasFlag(args, "-o", "--open");
8501
8467
  const follow = hasFlag(args, "-f", "--follow");
8502
- const hasLinesFlag = args.some((a) => matchValueFlagToken(a)?.spec.forms.includes("-n") === true);
8503
8468
  const positional = getNonFlagArg(args, 1);
8504
8469
  if (positional === "") {
8505
8470
  throw new CliError('\u65E0\u6548\u7684\u65E5\u5FD7\u7F16\u53F7 ""', { hint: INVALID_INDEX_HINT });
8506
8471
  }
8507
- const targetName = positional ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
8472
+ const targetName = positional ?? (args.length > 1 ? "0" : null);
8508
8473
  if (targetName) {
8509
8474
  let logPath;
8510
8475
  if (targetName === "0") {
@@ -8533,33 +8498,21 @@ function cmdLogs(args) {
8533
8498
  viewLogWithTail(logPath, { follow, lines });
8534
8499
  return;
8535
8500
  }
8536
- const logs = listLogs();
8537
- const all = [];
8538
- if (logs.current) all.push(logs.current);
8539
- all.push(...logs.archives);
8540
- if (all.length === 0) {
8501
+ const { current, archives } = listLogs();
8502
+ if (!current && archives.length === 0) {
8541
8503
  console.log("\u6682\u65E0\u5185\u6838\u65E5\u5FD7");
8542
8504
  return;
8543
8505
  }
8544
8506
  console.log("");
8545
8507
  console.log("\u65E5\u5FD7\u5217\u8868:");
8546
8508
  console.log("");
8547
- let archiveCounter = 0;
8548
- for (const log of all) {
8549
- let num;
8550
- if (log.isCurrent) {
8551
- num = " 0";
8552
- } else {
8553
- archiveCounter++;
8554
- num = String(archiveCounter).padStart(2);
8555
- }
8556
- const time = formatDate(log.mtime);
8557
- const size = formatBytes(log.size);
8558
- const name = log.isCurrent ? "mihomo.log (\u5F53\u524D\u8FD0\u884C\u4E2D)" : log.name;
8559
- console.log(` ${num}. ${name}`);
8560
- console.log(` \u65F6\u95F4: ${time} \u5927\u5C0F: ${size}`);
8509
+ const printEntry = (log, index) => {
8510
+ console.log(` ${String(index).padStart(2)}. ${log.name}${index === 0 ? " (\u5F53\u524D\u8FD0\u884C\u4E2D)" : ""}`);
8511
+ console.log(` \u65F6\u95F4: ${formatDate(log.mtime)} \u5927\u5C0F: ${formatBytes(log.size)}`);
8561
8512
  console.log("");
8562
- }
8513
+ };
8514
+ if (current) printEntry(current, 0);
8515
+ for (const [i, log] of archives.entries()) printEntry(log, i + 1);
8563
8516
  console.log("\u7528\u6CD5:");
8564
8517
  console.log(" mihomo-cli logs 0 # \u67E5\u770B\u5F53\u524D\u65E5\u5FD7 (\u6700\u540E 100 \u884C)");
8565
8518
  console.log(" mihomo-cli logs 0 -f # \u5B9E\u65F6\u8DDF\u968F\u5F53\u524D\u65E5\u5FD7");
@@ -9414,9 +9367,7 @@ function clearProxyEnv() {
9414
9367
  }
9415
9368
  var GUARD_EXEMPT_COMMANDS = /* @__PURE__ */ new Set(["help", "version"]);
9416
9369
  function assertNotRoot(commandName) {
9417
- const uid = process.getuid?.();
9418
- if (uid !== 0) return;
9419
- if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
9370
+ if (!isRoot()) return;
9420
9371
  throw new CliError("\u8BF7\u4E0D\u8981\u7528 sudo \u8FD0\u884C mihomo-cli", {
9421
9372
  label: "\u8EAB\u4EFD\u9519\u8BEF",
9422
9373
  hint: [
@@ -9430,9 +9381,8 @@ function assertNotRoot(commandName) {
9430
9381
  ]
9431
9382
  });
9432
9383
  }
9433
- function assertSupportedNodeVersion(commandName) {
9384
+ function assertSupportedNodeVersion() {
9434
9385
  if (!NODE_ENGINES) return;
9435
- if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
9436
9386
  const current = process.versions.node;
9437
9387
  if (satisfies(current, NODE_ENGINES)) return;
9438
9388
  throw new CliError(`Node \u7248\u672C\u8FC7\u4F4E\uFF08\u5F53\u524D ${current}\uFF0C\u9700\u8981 ${NODE_ENGINES}\uFF09`, {
@@ -9440,9 +9390,8 @@ function assertSupportedNodeVersion(commandName) {
9440
9390
  hint: ["\u5347\u7EA7 Node \u540E\u91CD\u8BD5\uFF0C\u4F8B\u5982:", " brew upgrade node", " \u6216\u7528 nvm: nvm install --lts && nvm use --lts", "", `\u5F53\u524D\u89E3\u91CA\u5668: ${process.execPath}`]
9441
9391
  });
9442
9392
  }
9443
- function assertSupportedPlatform(commandName) {
9393
+ function assertSupportedPlatform() {
9444
9394
  if (process.platform === "darwin") return;
9445
- if (GUARD_EXEMPT_COMMANDS.has(commandName)) return;
9446
9395
  if (process.env.MIHOMO_CLI_ALLOW_ANY_PLATFORM === "1") return;
9447
9396
  throw new CliError(`mihomo-cli \u76EE\u524D\u4EC5\u652F\u6301 macOS\uFF08\u5F53\u524D\u5E73\u53F0: ${process.platform}\uFF09`, {
9448
9397
  label: "\u5E73\u53F0\u4E0D\u652F\u6301",
@@ -9456,17 +9405,7 @@ function assertSupportedPlatform(commandName) {
9456
9405
  async function main() {
9457
9406
  clearProxyEnv();
9458
9407
  const args = process.argv.slice(2);
9459
- if (args.length === 0) {
9460
- assertSupportedNodeVersion("status");
9461
- assertSupportedPlatform("status");
9462
- assertNotRoot("status");
9463
- ensureDirs();
9464
- cleanupStaleTmpFiles();
9465
- await printStatus();
9466
- printShortHelp();
9467
- return;
9468
- }
9469
- const token = args[0].toLowerCase();
9408
+ const token = (args[0] ?? "status").toLowerCase();
9470
9409
  const command = findCommand(token);
9471
9410
  if (!command) {
9472
9411
  const suggestion = suggestSimilar(token, allCommandTokens());
@@ -9474,13 +9413,13 @@ async function main() {
9474
9413
  hint: [suggestion.length > 0 ? `\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?` : '\u4F7F\u7528 "mihomo-cli help" \u67E5\u770B\u5E2E\u52A9']
9475
9414
  });
9476
9415
  }
9477
- assertSupportedNodeVersion(command.name);
9478
- assertSupportedPlatform(command.name);
9479
- assertNotRoot(command.name);
9480
9416
  if (!GUARD_EXEMPT_COMMANDS.has(command.name)) {
9417
+ assertSupportedNodeVersion();
9418
+ assertSupportedPlatform();
9419
+ assertNotRoot(command.name);
9481
9420
  ensureDirs();
9482
9421
  cleanupStaleTmpFiles();
9483
- captureStopEpochBaseline();
9422
+ if (args.length > 0) captureStopEpochBaseline();
9484
9423
  }
9485
9424
  if (command.group === "meta") {
9486
9425
  assertKnownFlags(args.slice(1), [], command.name);
@@ -9491,6 +9430,7 @@ async function main() {
9491
9430
  return;
9492
9431
  }
9493
9432
  await command.handler(command.rewrite ? command.rewrite(args) : args);
9433
+ if (args.length === 0) printShortHelp();
9494
9434
  }
9495
9435
  main().catch((e) => {
9496
9436
  if (e instanceof CliError) {
package/docs/overwrite.md CHANGED
@@ -15,7 +15,7 @@
15
15
 
16
16
  加载顺序为:全部 JS 脚本 → 全部 YAML。各段内主文件优先,扩展文件按文件名码点排序;`ow` 列表与合并使用同一顺序。脚本先做程序化结构变换,YAML 再做声明式微调
17
17
 
18
- 覆写默认启用。放好文件后执行 `mihomo-cli start` 应用;曾执行 `ow off` 时需先 `ow on`
18
+ 覆写默认启用。修改文件后,按当前模式应用,具体命令见 [README 的覆写配置](../README.md#覆写配置)。若曾执行 `mihomo-cli ow off`,用 `mihomo-cli ow on` 重新启用;已有实例运行时会自动应用
19
19
 
20
20
  ## YAML 合并语法
21
21
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mihomo-cli",
3
- "version": "26.11.116",
3
+ "version": "26.11.118",
4
4
  "type": "module",
5
5
  "description": "A terminal-based mihomo (Clash.Meta) client for macOS",
6
6
  "bin": {
@@ -46,10 +46,6 @@
46
46
  "os": [
47
47
  "darwin"
48
48
  ],
49
- "dependencies": {
50
- "compare-versions": "^6.1.0",
51
- "js-yaml": "^5.2.1"
52
- },
53
49
  "lint-staged": {
54
50
  "*.{ts,json,md}": "biome check --fix --no-errors-on-unmatched"
55
51
  },
@@ -59,7 +55,9 @@
59
55
  "devDependencies": {
60
56
  "@biomejs/biome": "^2.5.4",
61
57
  "@types/node": "24.19.2",
58
+ "compare-versions": "^6.1.0",
62
59
  "husky": "^9.1.7",
60
+ "js-yaml": "^5.2.1",
63
61
  "lint-staged": "^17.0.8",
64
62
  "tsup": "^8.5.1",
65
63
  "tsx": "^4.23.1",