mihomo-cli 4.5.0 → 4.6.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.
Files changed (3) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/index.js +300 -180
  3. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,51 @@
1
1
  # Changelog
2
2
 
3
+ ## [4.6.0] - 2026-09-05
4
+
5
+ 全面审查修复:内核更新安全、服务操作并发、订阅下载防降级、补全死代码、循环依赖等 30 项。单测 234(无新增,本轮以修复为主)。
6
+
7
+ ### 修复(中高)
8
+
9
+ - **内核更新先自检再替换**:此前 `.gz` 路径先删旧内核再自检,自检失败时系统无内核可用(KeepAlive 崩溃循环);且 `findBinaryInDir` 扫描整个 kernel 目录,归档不含二进制时会选中旧内核自检通过、报「已更新」但二进制没变。现改为解压到临时目录 → 自检 → 版本对账 → 原子替换,旧内核在新内核验证通过前不受影响
10
+ - **订阅下载防 https→http 降级**:Node fetch 默认静默跟随协议降级重定向,恶意 WiFi/路由器可 MITM 替换订阅配置。内核下载有 `curl --proto =https` 防线,订阅下载没有。现 fetch 后检查 `response.url` 协议,降级即报错
11
+ - **zsh 补全 `dir open <TAB>` 死代码**:group 循环生成的 directory 分支与硬编码分支同名,zsh 取第一个匹配,硬编码的目标补全(`root/subs/logs/...`)永不可达,`dir open <TAB>` 补的是本地文件。bash/fish 正常,只有 zsh 坏
12
+ - **`shared.ts` ↔ `start.ts` 循环依赖**:`cleanupLegacyInstallOrThrow` 在 shared.ts 造成 shared ↔ start 运行时循环,注释声称「无循环」已过期。移至 service.ts(`cleanupLegacySystemInstall` 所在地),依赖方向恢复单向
13
+ - **`maskUrl` 黑名单改启发式**:黑名单只有 8 个参数名,`uuid`/`sid`/`id` 等常见 token 参数不遮蔽。改为「值长度 ≥16 的 query 参数一律遮蔽」+ 扩充黑名单,误伤率低、token 几乎都是长串
14
+
15
+ ### 修复(中)
16
+
17
+ - **服务操作跨进程锁**:慢速 `start`(订阅更新 ~10s)期间另一终端 `stop`,start 随后的 `enable` 会把自启位又打开,终态与用户最后一条命令相反。`startService`/`stopService`/`installService`/`uninstallService` 的 enable/bootstrap/bootout/disable 现共持 `service.lock`;start 在锁内再查一次 disabled,若 stop 已跑完则跳过启动
18
+ - **`sub add` 补重启提示**:成功切换订阅后运行中实例仍用旧配置,`subUpdate`/`subUse` 都有提示,唯独 `subAdd` 漏了
19
+ - **`update` 防静默降级**:当前版本领先 registry(预发/源码安装)时 `npm install -g` 会静默降级。现用 `compareVersions` 比对,领先时跳过并提示
20
+ - **未知 flag 校验**:`start`/`logs`/`ow`/`sub`/`status` 此前不校验未知 flag,拼错(`logs -F`)被静默跳过。新增 `assertKnownFlags` 通用校验,白名单外的 flag 一律报错
21
+ - **`--no-ssh` 全局检查**:此前只在 `start`/`stop` 报错,其他命令静默忽略。移至 `index.ts` 守卫后、分发前统一检查
22
+ - **attached 短选项**:`logs -n200`、`start -u5000` 此前被静默忽略(`parseIntArg` 只认 `-n 200` 和 `--lines=200`)。现支持 `-n200` 形式
23
+ - **日志轮转撞名**:同一秒内两次轮转(start 失败后立即重试)会互相覆盖归档。`rotateLog` 和 `restartService` 的 copy-truncate 都加了序号后缀
24
+ - **`tryHotReload` pid 校验**:`/version` 探针只确认「端口上是个 mihomo」,挡不住「另一个 mihomo」。新增 `lsof` 取监听 pid 与服务 pid 比对
25
+ - **`cleanupLegacySystemInstall` 不再 `|| true`**:`launchctl bootout` 的 `|| true` 吞掉所有错误,daemon 仍在跑却继续 rm plist 并报「已清理」。现只容忍退出码 113(未装载),其余按失败处理
26
+ - **ANSI 转义消毒**:服务器返回的字符串(订阅名、错误信息、Content-Disposition)可能含 `\x1b[2J` 等转义序列伪造 CLI 输出。新增 `sanitizeTerminal`,在入口点消毒
27
+ - **`parseYamlOrJson` 校验非对象**:JSON 回退路径此前不校验结果类型,标量/数组也能返回。现与 YAML 路径同构,只接受对象
28
+ - **`buildConfig` 深拷贝**:`applyOverwrite` 只做浅拷贝,`excludeOverwriteProxiesFromIncludeAll`/`validateConfig` 原地改嵌套对象,污染 `subscriptionConfig` 导致 debug stage1 失真。现深拷贝后再传
29
+ - **`saveSubscriptionCache` 防展开垃圾**:损坏的非对象条目(字符串)被 `{...}` 展开成字符键垃圾。现检查类型后再合并
30
+ - **`removeSubscription` 锁内删文件**:原始配置的 rm 此前在锁外,与并发 `sub add` 同名存在 TOCTOU。现挪进 `updateSettings` mutator(锁内)
31
+
32
+ ### 修复(低)
33
+
34
+ - **`sub use -s foo` flag 顺序**:`args[2]` 直取改为 `getNonFlagArg`,flag 写在名字前不再报「未找到订阅」
35
+ - **`completion install` 落盘失败包 CliError**:此前抛裸 Error 带完整堆栈,现包成友好提示
36
+ - **doctor 内核自检区分 spawn 错误**:`spawnSync` 失败(EACCES/ENOENT)时显示「退出码 null」,现区分 spawn 错误与非零退出
37
+ - **`reset` 多目标空目标不报成功**:多目标时空目标(如内核未安装)无删除却出现在成功文案里。现跟踪实际删除的目标
38
+ - **`reset overwrites` 关闭覆写开关**:删了覆写文件却留着 `overwrite_enabled=true`,ow/status 显示「已启用 (无文件)」。现重置开关
39
+ - **`reset logs` 运行中先停服务**:`needsStop` 从 false 改为 true,避免内核继续写已删 inode
40
+ - **补全词表补别名**:顶层补全此前只建议命令主名,不建议 `sub`/`ow`/`dir`/`restart` 等别名。bash `logs` 补全建议不存在的 `--help`,改为 `--lines`/`--follow`/`--open`。三 shell 的 `completion` 分支补 shell 名
41
+ - **`mihomo log 1` 尊重编号**:隐藏别名 `log` 的 rewrite 硬编码 `'0'`,`log 1` 跟随当前日志而非归档 1。现尊重用户传的编号
42
+ - **startTun 文案**:仅有 root pid 文件无进程时不再打印「清理 0 个残留进程」,改为「清理残留的 root pid 文件」
43
+
44
+ ### 文档
45
+
46
+ - **TODO.md**:删除「Mixed 模式系统代理开关」条目——该功能已被 owner 在 v4.5.0 明确否决(CLAUDE.md 决策记录),TODO 条目会误导后续实现
47
+ - **CLAUDE.md 架构表**:补 `proxy-probe.ts` 和 `spinner.ts` 两个模块(v4.3.0 新增,文档未同步)
48
+
3
49
  ## [4.5.0] - 2026-09-05
4
50
 
5
51
  产品面打磨:补齐「服务常驻」与「用户会回来敲命令」假设之间的缺口。单测 229 → 234。
package/dist/index.js CHANGED
@@ -3185,6 +3185,8 @@ var PATHS = {
3185
3185
  configFile: path.join(DIRS.runtime, "config.yaml"),
3186
3186
  logFile: path.join(DIRS.logs, "mihomo.log"),
3187
3187
  pidFile: path.join(DIRS.runtime, "pid"),
3188
+ /** 服务操作跨进程锁:start/stop/install/uninstall 的 enable/bootstrap/bootout/disable 串行化 */
3189
+ serviceLock: path.join(DIRS.runtime, "service.lock"),
3188
3190
  configStage1Subscription: path.join(DIRS.runtime, "1.subscription.yaml"),
3189
3191
  configStage2Overwrite: path.join(DIRS.runtime, "2.overwrite.yaml"),
3190
3192
  configStage3System: path.join(DIRS.runtime, "3.system.yaml"),
@@ -3388,9 +3390,28 @@ function getPorts() {
3388
3390
  function maskSingleUrl(url) {
3389
3391
  try {
3390
3392
  const parsed = new URL(url);
3391
- const tokenKeys = ["token", "key", "secret", "pass", "password", "auth", "access_token", "api_key"];
3392
- for (const key of tokenKeys) {
3393
- if (parsed.searchParams.has(key)) {
3393
+ const tokenKeys = /* @__PURE__ */ new Set([
3394
+ "token",
3395
+ "key",
3396
+ "secret",
3397
+ "pass",
3398
+ "password",
3399
+ "auth",
3400
+ "access_token",
3401
+ "api_key",
3402
+ "uuid",
3403
+ "sid",
3404
+ "id",
3405
+ "sub",
3406
+ "user",
3407
+ "email",
3408
+ "passwd",
3409
+ "apikey",
3410
+ "api_key",
3411
+ "access"
3412
+ ]);
3413
+ for (const [key, value] of parsed.searchParams) {
3414
+ if (tokenKeys.has(key.toLowerCase()) || value.length >= 16) {
3394
3415
  parsed.searchParams.set(key, "***");
3395
3416
  }
3396
3417
  }
@@ -3438,7 +3459,8 @@ function saveSubscriptionCache(subName, data) {
3438
3459
  ensureDirs();
3439
3460
  withFileLock(PATHS.subscriptionsCacheFile, () => {
3440
3461
  const cache = readSubscriptionCache();
3441
- cache[subName] = { ...cache[subName], ...data };
3462
+ const old = cache[subName];
3463
+ cache[subName] = { ...old && typeof old === "object" && !Array.isArray(old) ? old : {}, ...data };
3442
3464
  writeSubscriptionCache(cache);
3443
3465
  });
3444
3466
  }
@@ -3512,14 +3534,14 @@ function removeSubscription(name) {
3512
3534
  switchedTo = subs.length > 0 ? subs[0].name : null;
3513
3535
  updates.active_subscription = switchedTo ?? void 0;
3514
3536
  }
3537
+ try {
3538
+ fs2.rmSync(getSubscriptionRawConfigPath(name), { force: true });
3539
+ } catch {
3540
+ }
3515
3541
  return updates;
3516
3542
  });
3517
3543
  if (!found) return null;
3518
3544
  deleteSubscriptionCache(name);
3519
- try {
3520
- fs2.rmSync(getSubscriptionRawConfigPath(name), { force: true });
3521
- } catch {
3522
- }
3523
3545
  return switchedTo;
3524
3546
  }
3525
3547
  function setDefaultSubscription(name) {
@@ -3826,6 +3848,11 @@ function sleep(ms) {
3826
3848
  function escapeRegExp(s) {
3827
3849
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3828
3850
  }
3851
+ function sanitizeTerminal(s) {
3852
+ const ansiEscape = /\x1b\[[0-9;]*[a-zA-Z]/g;
3853
+ const controlChars = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g;
3854
+ return s.replace(ansiEscape, "").replace(controlChars, "");
3855
+ }
3829
3856
  function shellQuote(s) {
3830
3857
  return `'${s.replace(/'/g, "'\\''")}'`;
3831
3858
  }
@@ -3922,6 +3949,21 @@ function subscriptionUrgency(entry, nowMs = Date.now()) {
3922
3949
  function hasFlag(args, short, long) {
3923
3950
  return !!args && (args.includes(short) || long !== void 0 && args.includes(long));
3924
3951
  }
3952
+ function assertKnownFlags(args, known, command) {
3953
+ if (!args) return;
3954
+ const knownSet = new Set(known);
3955
+ for (const a of args) {
3956
+ if (!a.startsWith("-") || a === "-") continue;
3957
+ if (knownSet.has(a)) continue;
3958
+ const eqIdx = a.indexOf("=");
3959
+ if (eqIdx > 0 && knownSet.has(a.slice(0, eqIdx))) continue;
3960
+ if (a.length > 2 && a.startsWith("-") && !a.startsWith("--") && knownSet.has(a.slice(0, 2))) continue;
3961
+ throw new CliError(`\u672A\u77E5\u7684\u9009\u9879: ${a}`, {
3962
+ label: "\u53C2\u6570\u9519\u8BEF",
3963
+ hint: [`\u53EF\u7528\u9009\u9879: ${known.join(", ")}`, "", `\u7528\u6CD5: mihomo ${command}`]
3964
+ });
3965
+ }
3966
+ }
3925
3967
  function parseIntArg(args, short, long, defaultValue) {
3926
3968
  if (!args) return defaultValue;
3927
3969
  const parse = (raw, flag) => {
@@ -3944,6 +3986,9 @@ function parseIntArg(args, short, long, defaultValue) {
3944
3986
  if (args[i].startsWith(`${long}=`)) {
3945
3987
  return parse(args[i].slice(long.length + 1), long);
3946
3988
  }
3989
+ if (args[i].startsWith(short) && args[i].length > short.length && /^\d+$/.test(args[i].slice(short.length))) {
3990
+ return parse(args[i].slice(short.length), short);
3991
+ }
3947
3992
  }
3948
3993
  return defaultValue;
3949
3994
  }
@@ -4083,8 +4128,11 @@ function parseYamlOrJson(content, errorMsg) {
4083
4128
  } catch {
4084
4129
  }
4085
4130
  try {
4086
- return JSON.parse(content);
4087
- } catch {
4131
+ const result = JSON.parse(content);
4132
+ if (result != null && typeof result === "object" && !Array.isArray(result)) return result;
4133
+ throw new Error(`${errorMsg || "\u5185\u5BB9"}\u4E0D\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61`);
4134
+ } catch (e) {
4135
+ if (e instanceof Error && e.message.includes("\u4E0D\u662F\u6709\u6548\u7684\u914D\u7F6E\u5BF9\u8C61")) throw e;
4088
4136
  throw new Error(`${errorMsg || "\u5185\u5BB9"}\u683C\u5F0F\u9519\u8BEF\uFF0C\u65E0\u6CD5\u89E3\u6790\u4E3A YAML \u6216 JSON`);
4089
4137
  }
4090
4138
  }
@@ -4293,7 +4341,8 @@ function buildConfig(subRawContent, mode, scope) {
4293
4341
  const overwriteEnabled = isOverwriteEnabled();
4294
4342
  const allFiles = overwriteEnabled ? loadOverwriteFile() : [];
4295
4343
  const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
4296
- const withOverwrites = applyOverwrite(subscriptionConfig, overwriteFiles);
4344
+ const working = structuredClone(subscriptionConfig);
4345
+ const withOverwrites = applyOverwrite(working, overwriteFiles);
4297
4346
  if (overwriteFiles.length > 0) {
4298
4347
  const baseProxies = Array.isArray(subscriptionConfig.proxies) ? subscriptionConfig.proxies : [];
4299
4348
  const baseProxyNames = new Set(
@@ -4476,8 +4525,15 @@ function rotateLog() {
4476
4525
  if (!fs5.existsSync(logFile)) return null;
4477
4526
  const stat = fs5.statSync(logFile);
4478
4527
  if (stat.size === 0) return null;
4479
- const rotatedName = `mihomo.${formatLocalTimestamp()}.log`;
4480
- const rotatedPath = path4.join(DIRS.logs, rotatedName);
4528
+ const timestamp = formatLocalTimestamp();
4529
+ let rotatedName = `mihomo.${timestamp}.log`;
4530
+ let rotatedPath = path4.join(DIRS.logs, rotatedName);
4531
+ let seq = 1;
4532
+ while (fs5.existsSync(rotatedPath)) {
4533
+ rotatedName = `mihomo.${timestamp}.${seq}.log`;
4534
+ rotatedPath = path4.join(DIRS.logs, rotatedName);
4535
+ seq++;
4536
+ }
4481
4537
  fs5.renameSync(logFile, rotatedPath);
4482
4538
  return rotatedPath;
4483
4539
  }
@@ -4490,7 +4546,7 @@ function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
4490
4546
  let deleted = 0;
4491
4547
  let errors = 0;
4492
4548
  for (const file of files) {
4493
- if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.log$/)) continue;
4549
+ if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(\.\d+)?\.log$/)) continue;
4494
4550
  try {
4495
4551
  const filePath = path4.join(logsDir, file);
4496
4552
  const stat = fs5.statSync(filePath);
@@ -4927,8 +4983,10 @@ async function installService(wasRunning) {
4927
4983
  fs8.copyFileSync(stagePath, PATHS.userAgentPlist);
4928
4984
  fs8.chmodSync(PATHS.userAgentPlist, 420);
4929
4985
  if (wasRunning) {
4930
- runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
4931
- runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u88C5\u8F7D\u670D\u52A1");
4986
+ withFileLock(PATHS.serviceLock, () => {
4987
+ runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
4988
+ runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u88C5\u8F7D\u670D\u52A1");
4989
+ });
4932
4990
  }
4933
4991
  } finally {
4934
4992
  try {
@@ -4964,8 +5022,13 @@ async function startService() {
4964
5022
  await bootoutService();
4965
5023
  await waitUntilUnloaded();
4966
5024
  rotateAndCleanupLogs();
4967
- runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
4968
- runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u542F\u52A8\u670D\u52A1");
5025
+ withFileLock(PATHS.serviceLock, () => {
5026
+ if (isServiceDisabledInLaunchd()) {
5027
+ return;
5028
+ }
5029
+ runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
5030
+ runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u542F\u52A8\u670D\u52A1");
5031
+ });
4969
5032
  }
4970
5033
  function disableServiceAutoStart() {
4971
5034
  assertServiceLabelSafe();
@@ -4978,14 +5041,19 @@ function disableServiceAutoStart() {
4978
5041
  }
4979
5042
  async function stopService() {
4980
5043
  assertServiceLabelSafe();
4981
- await bootoutService();
5044
+ await withFileLock(PATHS.serviceLock, () => {
5045
+ bootoutService();
5046
+ disableServiceAutoStart();
5047
+ });
4982
5048
  await waitUntilUnloaded();
4983
- disableServiceAutoStart();
4984
5049
  killResidualKernels();
4985
5050
  }
4986
5051
  async function uninstallService() {
4987
5052
  assertServiceLabelSafe();
4988
- await bootoutService();
5053
+ await withFileLock(PATHS.serviceLock, () => {
5054
+ bootoutService();
5055
+ disableServiceAutoStart();
5056
+ });
4989
5057
  await waitUntilUnloaded();
4990
5058
  try {
4991
5059
  fs8.rmSync(PATHS.userAgentPlist, { force: true });
@@ -5003,7 +5071,14 @@ function cleanupLegacySystemInstall() {
5003
5071
  assertServiceLabelSafe();
5004
5072
  const script = [
5005
5073
  "#!/bin/bash",
5006
- `launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || true`,
5074
+ // bootout 退出码分级:113=未装载(daemon 已不在,正常),其余是真实失败。
5075
+ // 此前 || true 吞掉所有错误,daemon 仍在跑却继续 rm plist 并报「已清理」
5076
+ `bootout_code=0`,
5077
+ `launchctl bootout ${shellQuote(`system/${SERVICE_LABEL}`)} 2>/dev/null || bootout_code=$?`,
5078
+ `if [ $bootout_code -ne 0 ] && [ $bootout_code -ne 113 ]; then`,
5079
+ ` echo "launchctl bootout \u5931\u8D25\uFF08\u9000\u51FA\u7801 $bootout_code\uFF09" >&2`,
5080
+ ` exit 1`,
5081
+ `fi`,
5007
5082
  `rm -f ${shellQuote(PATHS.systemDaemonPlist)}`,
5008
5083
  `chown "$SUDO_UID:$SUDO_GID" ${shellQuote(PATHS.logFile)} 2>/dev/null || true`,
5009
5084
  `chown -R "$SUDO_UID:$SUDO_GID" ${shellQuote(DIRS.data)} 2>/dev/null || true`,
@@ -5013,6 +5088,17 @@ function cleanupLegacySystemInstall() {
5013
5088
  ].join("\n");
5014
5089
  runSudoScript(script, { action: "\u6E05\u7406\u9057\u7559\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1", file: "legacy-cleanup.sh" });
5015
5090
  }
5091
+ function cleanupLegacyInstallOrThrow() {
5092
+ try {
5093
+ cleanupLegacySystemInstall();
5094
+ } catch (e) {
5095
+ if (e instanceof CliError) throw e;
5096
+ throw new CliError(e.message, {
5097
+ label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
5098
+ hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
5099
+ });
5100
+ }
5101
+ }
5016
5102
  function logOversized() {
5017
5103
  try {
5018
5104
  return fs8.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
@@ -5034,6 +5120,11 @@ async function tryHotReload() {
5034
5120
  if (!probe.ok) return false;
5035
5121
  const info = await probe.json();
5036
5122
  if (typeof info?.version !== "string") return false;
5123
+ const port = getPorts().controller;
5124
+ const lsofResult = spawnSync4("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"], { encoding: "utf8", timeout: 5e3 });
5125
+ if (lsofResult.status !== 0) return false;
5126
+ const listenerPid = Number.parseInt(lsofResult.stdout.trim(), 10);
5127
+ if (!Number.isFinite(listenerPid) || listenerPid !== status.pid) return false;
5037
5128
  const res = await fetch(`${baseUrl}/configs?force=true`, {
5038
5129
  method: "PUT",
5039
5130
  headers,
@@ -5053,7 +5144,13 @@ async function restartService() {
5053
5144
  }
5054
5145
  if (!logOversized() && await tryHotReload()) return { hotReloaded: true };
5055
5146
  if (logOversized()) {
5056
- const archiveFile = path6.join(DIRS.logs, `mihomo.${formatLocalTimestamp()}.log`);
5147
+ const timestamp = formatLocalTimestamp();
5148
+ let archiveFile = path6.join(DIRS.logs, `mihomo.${timestamp}.log`);
5149
+ let seq = 1;
5150
+ while (fs8.existsSync(archiveFile)) {
5151
+ archiveFile = path6.join(DIRS.logs, `mihomo.${timestamp}.${seq}.log`);
5152
+ seq++;
5153
+ }
5057
5154
  try {
5058
5155
  fs8.copyFileSync(PATHS.logFile, archiveFile);
5059
5156
  fs8.writeFileSync(PATHS.logFile, "");
@@ -5303,7 +5400,11 @@ async function startTun() {
5303
5400
  }
5304
5401
  const staleState = checkStaleState();
5305
5402
  if (staleState.needsCleanup) {
5306
- console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
5403
+ if (staleState.allPids.length > 0) {
5404
+ console.log(`\u6E05\u7406 ${staleState.allPids.length} \u4E2A\u6B8B\u7559\u8FDB\u7A0B...`);
5405
+ } else {
5406
+ console.log("\u6E05\u7406\u6B8B\u7559\u7684 root pid \u6587\u4EF6...");
5407
+ }
5307
5408
  }
5308
5409
  console.log("TUN \u6A21\u5F0F\u9700\u8981 sudo \u6743\u9650...");
5309
5410
  runSudoScript(buildTunLaunchScript(), {
@@ -5386,6 +5487,9 @@ function createHttpClient(options = {}) {
5386
5487
  signal,
5387
5488
  headers: { "User-Agent": `mihomo-cli/${VERSION}` }
5388
5489
  });
5490
+ if (url.startsWith("https://") && !response.url.startsWith("https://")) {
5491
+ throw new Error(`\u8BF7\u6C42\u88AB\u91CD\u5B9A\u5411\u5230\u975E https \u5730\u5740\uFF08${response.url}\uFF09\uFF0C\u5DF2\u62D2\u7EDD`);
5492
+ }
5389
5493
  if (!response.ok) {
5390
5494
  const error = new Error(`HTTP ${response.status}`);
5391
5495
  error.response = { status: response.status };
@@ -5511,8 +5615,9 @@ function extractSubscriptionMeta(headers) {
5511
5615
  return {
5512
5616
  userInfo: parseUserInfo(headers?.get("subscription-userinfo") ?? null),
5513
5617
  updateInterval: parsePositiveInterval(headers?.get("profile-update-interval")),
5514
- webPageUrl: headers?.get("profile-web-page-url") || null,
5515
- username: parseUsernameFromContentDisposition(headers?.get("content-disposition") ?? null)
5618
+ // 服务器返回的字符串可能含 ANSI 转义/控制字符,展示前消毒(防终端输出伪造)
5619
+ webPageUrl: sanitizeTerminal(headers?.get("profile-web-page-url") || "") || null,
5620
+ username: sanitizeTerminal(parseUsernameFromContentDisposition(headers?.get("content-disposition") ?? null) || "") || null
5516
5621
  };
5517
5622
  }
5518
5623
  function saveSubscriptionMeta(subName, meta) {
@@ -5590,7 +5695,9 @@ function assertLooksLikeSubscription(parsed, maskedUrl) {
5590
5695
  const providers = parsed["proxy-providers"];
5591
5696
  const hasProviders = providers != null && typeof providers === "object" && Object.keys(providers).length > 0;
5592
5697
  if (hasProxies || hasGroups || hasProviders) return;
5593
- const serverMsg = ["error", "message", "msg", "info"].map((k) => parsed[k]).find((v) => typeof v === "string" && v.length > 0);
5698
+ const serverMsg = sanitizeTerminal(
5699
+ ["error", "message", "msg", "info"].map((k) => parsed[k]).find((v) => typeof v === "string" && v.length > 0) ?? ""
5700
+ );
5594
5701
  throw new CliError("\u8BA2\u9605\u5185\u5BB9\u4E0D\u542B\u4EFB\u4F55\u8282\u70B9\u6765\u6E90\uFF08proxies / proxy-groups / proxy-providers \u5747\u4E3A\u7A7A\uFF09", {
5595
5702
  label: "\u8BA2\u9605\u65E0\u6548",
5596
5703
  hint: [
@@ -5837,6 +5944,7 @@ function buildStatusJson(args) {
5837
5944
  };
5838
5945
  }
5839
5946
  async function printStatus(args = []) {
5947
+ assertKnownFlags(args, ["-j", "--json", "--no-probe"], "status [--json] [--no-probe]");
5840
5948
  const asJson = hasFlag(args, "-j", "--json");
5841
5949
  const skipProbe = hasFlag(args, "--no-probe");
5842
5950
  const service = getServiceStatus();
@@ -5987,7 +6095,7 @@ function resolveStartMode(args) {
5987
6095
  return modeToken === "tun" ? "tun" : "mixed";
5988
6096
  }
5989
6097
  async function cmdStart(args) {
5990
- assertNoRemovedSshFlag(args);
6098
+ assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "start [tun|mixed]");
5991
6099
  const targetMode = resolveStartMode(args);
5992
6100
  if (!hasKernel()) {
5993
6101
  throw new CliError("\u672A\u627E\u5230\u5185\u6838", { hint: "\u4E0B\u8F7D\u5185\u6838: mihomo kernel" });
@@ -6087,17 +6195,6 @@ async function restartToApply(args) {
6087
6195
  await cmdStart(["start", currentMode, ...extractStartOptions(args)]);
6088
6196
  return true;
6089
6197
  }
6090
- function cleanupLegacyInstallOrThrow() {
6091
- try {
6092
- cleanupLegacySystemInstall();
6093
- } catch (e) {
6094
- if (e instanceof CliError) throw e;
6095
- throw new CliError(e.message, {
6096
- label: "\u6E05\u7406\u9057\u7559\u670D\u52A1\u5931\u8D25",
6097
- hint: ["\u4E5F\u53EF\u624B\u52A8\u6E05\u7406:", ` sudo launchctl bootout system/$(basename ${PATHS.systemDaemonPlist} .plist)`, ` sudo rm -f ${PATHS.systemDaemonPlist}`]
6098
- });
6099
- }
6100
- }
6101
6198
 
6102
6199
  // src/commands/directory.ts
6103
6200
  function openDirectory(args) {
@@ -6209,6 +6306,7 @@ var SUBCOMMANDS2 = [
6209
6306
  { name: "off", aliases: ["disable"], description: "\u7981\u7528\u8986\u5199", handler: (args) => setOverwrite(false, args) }
6210
6307
  ];
6211
6308
  async function cmdOverwrite(args) {
6309
+ assertKnownFlags(args, ["-s", "--no-update", "-u", "--update-timeout"], "ow [on|off]");
6212
6310
  await dispatchSubcommand(args, SUBCOMMANDS2, {
6213
6311
  // 无子命令 → 列表;未知子命令 → 报错(与 sub/dir 同构,避免 `ow onn` 静默当成 list)
6214
6312
  fallback: () => {
@@ -6328,10 +6426,11 @@ async function subAdd(args) {
6328
6426
  throw new CliError(e.message, { label: "\u6DFB\u52A0\u5931\u8D25" });
6329
6427
  }
6330
6428
  console.log("");
6429
+ printRestartHintIfRunning();
6331
6430
  printSubscriptionList();
6332
6431
  }
6333
6432
  async function subUpdate(args) {
6334
- const name = args[2];
6433
+ const name = getNonFlagArg(args, 2);
6335
6434
  const subs = getSubscriptions();
6336
6435
  if (subs.length === 0) {
6337
6436
  throw new CliError("\u6CA1\u6709\u8BA2\u9605");
@@ -6362,7 +6461,7 @@ async function subUpdate(args) {
6362
6461
  printSubscriptionList();
6363
6462
  }
6364
6463
  async function subUse(args) {
6365
- const name = args[2];
6464
+ const name = getNonFlagArg(args, 2);
6366
6465
  const subs = getSubscriptions();
6367
6466
  if (subs.length === 0) {
6368
6467
  throw new CliError("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605", { hint: "mihomo sub add <url> [name]" });
@@ -6426,6 +6525,7 @@ var SUBCOMMANDS3 = [
6426
6525
  { name: "remove", aliases: ["rm", "delete"], description: "\u5220\u9664\u8BA2\u9605", handler: subRemove }
6427
6526
  ];
6428
6527
  async function cmdSubscription(args) {
6528
+ assertKnownFlags(args, ["-y", "--yes", "-s", "--no-update", "-u", "--update-timeout"], "sub [add|update|use|remove]");
6429
6529
  await dispatchSubcommand(args, SUBCOMMANDS3, {
6430
6530
  // 无子命令 → 列表;未知子命令 → 报错
6431
6531
  fallback: printSubscriptionList,
@@ -6441,7 +6541,7 @@ async function cmdSubscription(args) {
6441
6541
 
6442
6542
  // src/commands/completion.ts
6443
6543
  function commandWords(commands) {
6444
- return commands.filter((c) => !c.hidden).map((c) => ({ word: c.name, desc: c.usage[0]?.description ?? "" }));
6544
+ return commands.filter((c) => !c.hidden).flatMap((c) => [{ word: c.name, desc: c.usage[0]?.description ?? "" }, ...c.aliases.map((a) => ({ word: a, desc: c.usage[0]?.description ?? "" }))]);
6445
6545
  }
6446
6546
  function subWords(subs) {
6447
6547
  return subs.flatMap((s) => [{ word: s.name, desc: s.description ?? "" }, ...(s.aliases ?? []).map((a) => ({ word: a, desc: s.description ?? "" }))]);
@@ -6481,23 +6581,26 @@ function buildZsh(commands, groups) {
6481
6581
  ];
6482
6582
  for (const group of groups) {
6483
6583
  const aliases = group.tokens.join("|");
6584
+ const isDirectory = group.tokens.includes("directory");
6484
6585
  lines.push(` ${aliases})`);
6485
6586
  lines.push(" subcmds=(");
6486
6587
  for (const s of group.words) lines.push(` '${s.word}:${s.desc.replace(/'/g, "''")}'`);
6487
6588
  lines.push(" )");
6488
6589
  lines.push(" if (( CURRENT == 2 )); then");
6489
6590
  lines.push(" _describe 'subcommand' subcmds");
6490
- lines.push(" else");
6491
- lines.push(" _files");
6591
+ if (isDirectory) {
6592
+ lines.push(" elif (( CURRENT == 3 )) && [[ ${words[2]} == open ]]; then");
6593
+ lines.push(` _values 'target' ${DIR_TARGETS.join(" ")}`);
6594
+ lines.push(" else");
6595
+ lines.push(" _files");
6596
+ } else {
6597
+ lines.push(" else");
6598
+ lines.push(" _files");
6599
+ }
6492
6600
  lines.push(" fi");
6493
6601
  lines.push(" ;;");
6494
6602
  }
6495
6603
  lines.push(
6496
- " directory|dir|dirs|directories)",
6497
- " if (( CURRENT == 3 )); then",
6498
- ` _values 'target' ${DIR_TARGETS.join(" ")}`,
6499
- " fi",
6500
- " ;;",
6501
6604
  " logs)",
6502
6605
  " _arguments '-f[\u5B9E\u65F6\u8DDF\u968F]' '-n[\u663E\u793A\u884C\u6570]:\u884C\u6570:' '-o[\u7CFB\u7EDF\u9ED8\u8BA4\u7A0B\u5E8F\u6253\u5F00]' '1::\u7F16\u53F7:'",
6503
6606
  " ;;",
@@ -6513,7 +6616,7 @@ function buildZsh(commands, groups) {
6513
6616
  " ;;",
6514
6617
  " completion)",
6515
6618
  " if (( CURRENT == 2 )); then",
6516
- " _values 'action' install",
6619
+ ` _values 'action' install ${SHELLS.join(" ")}`,
6517
6620
  " elif (( CURRENT == 3 )) && [[ ${words[2]} == install ]]; then",
6518
6621
  ` _values 'shell' ${SHELLS.join(" ")}`,
6519
6622
  " fi",
@@ -6566,7 +6669,7 @@ _mihomo_completions() {
6566
6669
  case "\${COMP_WORDS[1]}" in
6567
6670
  ${subCase}
6568
6671
  logs)
6569
- COMPREPLY=( $(compgen -W "-f -n -o --help" -- "\${cur}") )
6672
+ COMPREPLY=( $(compgen -W "-f -n -o --lines --follow --open" -- "\${cur}") )
6570
6673
  ;;
6571
6674
  ui)
6572
6675
  COMPREPLY=( $(compgen -W "${UI_NAMES.join(" ")}" -- "\${cur}") )
@@ -6579,7 +6682,7 @@ ${subCase}
6579
6682
  ;;
6580
6683
  completion)
6581
6684
  if [[ \${COMP_CWORD} -eq 2 ]]; then
6582
- COMPREPLY=( $(compgen -W "install" -- "\${cur}") )
6685
+ COMPREPLY=( $(compgen -W "install ${SHELLS.join(" ")}" -- "\${cur}") )
6583
6686
  elif [[ \${COMP_CWORD} -eq 3 ]] && [[ "\${COMP_WORDS[2]}" == install ]]; then
6584
6687
  COMPREPLY=( $(compgen -W "${SHELLS.join(" ")}" -- "\${cur}") )
6585
6688
  fi
@@ -6606,7 +6709,7 @@ function buildFish(commands, groups) {
6606
6709
  }
6607
6710
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from directory dir dirs directories open" -a '${DIR_TARGETS.join(" ")}'`);
6608
6711
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from ui" -a '${UI_NAMES.join(" ")}'`);
6609
- lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install' -d '\u5B89\u88C5\u8865\u5168\u5230\u9ED8\u8BA4\u4F4D\u7F6E'`);
6712
+ lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion" -a 'install ${SHELLS.join(" ")}' -d '\u5B89\u88C5\u8865\u5168\u5230\u9ED8\u8BA4\u4F4D\u7F6E'`);
6610
6713
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from completion; and __fish_seen_subcommand_from install" -a '${SHELLS.join(" ")}'`);
6611
6714
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--mirror' -d '\u8D70\u955C\u50CF\u4E0B\u8F7D'`);
6612
6715
  lines.push(` complete -c $cmd -n "__fish_seen_subcommand_from kernel" -a '\\--no-mirror' -d '\u76F4\u8FDE\u4E0B\u8F7D'`);
@@ -6656,23 +6759,30 @@ function installCompletion(shell, commands) {
6656
6759
  }
6657
6760
  const script = buildCompletionScript(shell, commands);
6658
6761
  console.log(`\u5B89\u88C5 ${shell} \u8865\u5168: ${target}`);
6659
- if (shell === "bash") {
6660
- const existing = fs10.existsSync(target) ? fs10.readFileSync(target, "utf8") : "";
6661
- if (existing.includes(BASH_MARKER)) {
6662
- console.log("\u5DF2\u5B89\u88C5\u8FC7\uFF08~/.bash_completion \u5DF2\u5305\u542B mihomo \u8865\u5168\uFF09\uFF0C\u8DF3\u8FC7");
6663
- return;
6664
- }
6665
- fs10.mkdirSync(path8.dirname(target), { recursive: true });
6666
- fs10.appendFileSync(target, `
6762
+ try {
6763
+ if (shell === "bash") {
6764
+ const existing = fs10.existsSync(target) ? fs10.readFileSync(target, "utf8") : "";
6765
+ if (existing.includes(BASH_MARKER)) {
6766
+ console.log("\u5DF2\u5B89\u88C5\u8FC7\uFF08~/.bash_completion \u5DF2\u5305\u542B mihomo \u8865\u5168\uFF09\uFF0C\u8DF3\u8FC7");
6767
+ return;
6768
+ }
6769
+ fs10.mkdirSync(path8.dirname(target), { recursive: true });
6770
+ fs10.appendFileSync(target, `
6667
6771
  ${BASH_MARKER}
6668
6772
  ${script}${BASH_MARKER.replace(">>>", "<<<")}
6669
6773
  `);
6670
- console.log(colors.green("\u5DF2\u8FFD\u52A0\u5230 ~/.bash_completion\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
6671
- return;
6774
+ console.log(colors.green("\u5DF2\u8FFD\u52A0\u5230 ~/.bash_completion\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
6775
+ return;
6776
+ }
6777
+ fs10.mkdirSync(path8.dirname(target), { recursive: true });
6778
+ fs10.writeFileSync(target, script, { mode: 420 });
6779
+ console.log(colors.green("\u5DF2\u5199\u5165\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
6780
+ } catch (e) {
6781
+ throw new CliError(`\u8865\u5168\u5B89\u88C5\u5931\u8D25: ${e.message}`, {
6782
+ label: "\u5B89\u88C5\u5931\u8D25",
6783
+ hint: ["\u8BF7\u68C0\u67E5\u76EE\u6807\u76EE\u5F55\u7684\u5199\u6743\u9650\uFF0C\u6216\u624B\u52A8\u91CD\u5B9A\u5411\u8865\u5168\u811A\u672C:", ` mihomo completion ${shell} >> ${target}`]
6784
+ });
6672
6785
  }
6673
- fs10.mkdirSync(path8.dirname(target), { recursive: true });
6674
- fs10.writeFileSync(target, script, { mode: 420 });
6675
- console.log(colors.green("\u5DF2\u5199\u5165\uFF08\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF\u751F\u6548\uFF09"));
6676
6786
  if (shell === "zsh") {
6677
6787
  console.log(colors.gray("\u82E5\u8865\u5168\u4E0D\u751F\u6548\uFF0C\u5728 ~/.zshrc \u4E2D\u52A0\u4E00\u884C: fpath=(~/.zsh/completions $fpath)"));
6678
6788
  }
@@ -6772,11 +6882,20 @@ async function cmdUpdate() {
6772
6882
  console.log(`\u5F53\u524D\u7248\u672C: ${colors.cyan(VERSION)}`);
6773
6883
  console.log("");
6774
6884
  const latest = await withSpinner("\u67E5\u8BE2 npm \u6700\u65B0\u7248\u672C", getLatestNpmVersion);
6775
- if (latest && latest === VERSION) {
6776
- console.log(`\u5DF2\u662F\u6700\u65B0\u7248\u672C (${colors.green(VERSION)})\uFF0C\u65E0\u9700\u66F4\u65B0`);
6777
- return;
6778
- }
6779
6885
  if (latest) {
6886
+ try {
6887
+ const cmp = compareVersions(VERSION, latest);
6888
+ if (cmp > 0) {
6889
+ console.log(colors.yellow(`\u5F53\u524D\u7248\u672C (${VERSION}) \u9886\u5148\u4E8E npm \u6700\u65B0\u7248 (${latest})\uFF0C\u8DF3\u8FC7\u66F4\u65B0\uFF08\u907F\u514D\u964D\u7EA7\uFF09`));
6890
+ console.log(colors.gray("\u5982\u9700\u5F3A\u5236\u91CD\u88C5: npm install -g mihomo-cli"));
6891
+ return;
6892
+ }
6893
+ if (cmp === 0) {
6894
+ console.log(`\u5DF2\u662F\u6700\u65B0\u7248\u672C (${colors.green(VERSION)})\uFF0C\u65E0\u9700\u66F4\u65B0`);
6895
+ return;
6896
+ }
6897
+ } catch {
6898
+ }
6780
6899
  console.log(`\u6700\u65B0\u7248\u672C: ${colors.cyan(latest)}`);
6781
6900
  } else {
6782
6901
  console.log(colors.yellow("\u65E0\u6CD5\u67E5\u8BE2\u6700\u65B0\u7248\u672C\uFF08\u7F51\u7EDC\u95EE\u9898\uFF1F\uFF09\uFF0C\u5C06\u76F4\u63A5\u5C1D\u8BD5\u91CD\u65B0\u5B89\u88C5"));
@@ -6835,6 +6954,8 @@ async function collectChecks() {
6835
6954
  const r = spawnSync6(PATHS.mihomoBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
6836
6955
  if (r.status === 0 && /v?\d+\.\d+\.\d+/.test(`${r.stdout}${r.stderr}`)) {
6837
6956
  push("\u5185\u6838", "ok", v || "\u53EF\u6267\u884C");
6957
+ } else if (r.error) {
6958
+ push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08${r.error.message}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
6838
6959
  } else {
6839
6960
  push("\u5185\u6838", "fail", `\u4E8C\u8FDB\u5236\u65E0\u6CD5\u6267\u884C\uFF08\u9000\u51FA\u7801 ${r.status}\uFF09`, "\u91CD\u65B0\u4E0B\u8F7D: mihomo kernel");
6840
6961
  }
@@ -7090,71 +7211,63 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
7090
7211
  }
7091
7212
  assertTrustedAssetUrl(asset.browser_download_url);
7092
7213
  const downloadUrl = withMirror(asset.browser_download_url, mirror);
7093
- const tempPath = path9.join(DIRS.kernel, path9.basename(asset.name));
7214
+ const tempDir = fs12.mkdtempSync(path9.join(DIRS.kernel, ".tmp-"));
7215
+ const tempPath = path9.join(tempDir, path9.basename(asset.name));
7094
7216
  const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
7095
- if (mirror && progressCallback) {
7096
- progressCallback("\u63D0\u793A: \u7ECF\u7B2C\u4E09\u65B9\u955C\u50CF\u4E2D\u8F6C\u4E0B\u8F7D\uFF0C\u65E0\u6CD5\u9A8C\u8BC1\u6765\u6E90\u5B8C\u6574\u6027\uFF0C\u5EFA\u8BAE\u76F4\u8FDE\u6216\u81EA\u884C\u6821\u9A8C\u4EA7\u7269");
7097
- }
7098
- if (progressCallback) {
7099
- progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
7100
- }
7101
- const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
7102
- const curlResult = spawnSync7(
7103
- "curl",
7104
- [
7105
- "-L",
7106
- "--proto",
7107
- "=https",
7108
- "--proto-redir",
7109
- "=https",
7110
- "--max-filesize",
7111
- String(maxBytes),
7112
- "--progress-bar",
7113
- "--connect-timeout",
7114
- "30",
7115
- "--max-time",
7116
- String(Math.floor(KERNEL_DOWNLOAD_TIMEOUT / 1e3)),
7117
- "-o",
7118
- tempPath,
7119
- downloadUrl
7120
- ],
7121
- { stdio: "inherit" }
7122
- );
7123
- if (curlResult.error) {
7124
- if (curlResult.error.code === "ENOENT") {
7125
- throw new Error("\u672A\u627E\u5230 curl \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 curl \u540E\u91CD\u8BD5");
7217
+ try {
7218
+ if (mirror && progressCallback) {
7219
+ progressCallback("\u63D0\u793A: \u7ECF\u7B2C\u4E09\u65B9\u955C\u50CF\u4E2D\u8F6C\u4E0B\u8F7D\uFF0C\u65E0\u6CD5\u9A8C\u8BC1\u6765\u6E90\u5B8C\u6574\u6027\uFF0C\u5EFA\u8BAE\u76F4\u8FDE\u6216\u81EA\u884C\u6821\u9A8C\u4EA7\u7269");
7126
7220
  }
7127
- throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${curlResult.error.message}`);
7128
- }
7129
- if (curlResult.status !== 0) {
7130
- try {
7131
- fs12.unlinkSync(tempPath);
7132
- } catch {
7221
+ if (progressCallback) {
7222
+ progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
7133
7223
  }
7134
- throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
7135
- }
7136
- if (!fs12.existsSync(tempPath)) {
7137
- throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
7138
- }
7139
- if (Number.isFinite(asset.size) && asset.size > 0) {
7140
- const actual = fs12.statSync(tempPath).size;
7141
- if (actual !== asset.size) {
7142
- try {
7143
- fs12.unlinkSync(tempPath);
7144
- } catch {
7224
+ const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
7225
+ const curlResult = spawnSync7(
7226
+ "curl",
7227
+ [
7228
+ "-L",
7229
+ "--proto",
7230
+ "=https",
7231
+ "--proto-redir",
7232
+ "=https",
7233
+ "--max-filesize",
7234
+ String(maxBytes),
7235
+ "--progress-bar",
7236
+ "--connect-timeout",
7237
+ "30",
7238
+ "--max-time",
7239
+ String(Math.floor(KERNEL_DOWNLOAD_TIMEOUT / 1e3)),
7240
+ "-o",
7241
+ tempPath,
7242
+ downloadUrl
7243
+ ],
7244
+ { stdio: "inherit" }
7245
+ );
7246
+ if (curlResult.error) {
7247
+ if (curlResult.error.code === "ENOENT") {
7248
+ throw new Error("\u672A\u627E\u5230 curl \u547D\u4EE4\uFF0C\u8BF7\u5148\u5B89\u88C5 curl \u540E\u91CD\u8BD5");
7145
7249
  }
7146
- throw new Error(
7147
- `\u4E0B\u8F7D\u7684\u6587\u4EF6\u5927\u5C0F\u4E0E release \u5143\u6570\u636E\u4E0D\u7B26\uFF08\u671F\u671B ${asset.size} \u5B57\u8282\uFF0C\u5B9E\u9645 ${actual} \u5B57\u8282\uFF09
7250
+ throw new Error(`\u4E0B\u8F7D\u5931\u8D25: ${curlResult.error.message}`);
7251
+ }
7252
+ if (curlResult.status !== 0) {
7253
+ throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
7254
+ }
7255
+ if (!fs12.existsSync(tempPath)) {
7256
+ throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
7257
+ }
7258
+ if (Number.isFinite(asset.size) && asset.size > 0) {
7259
+ const actual = fs12.statSync(tempPath).size;
7260
+ if (actual !== asset.size) {
7261
+ throw new Error(
7262
+ `\u4E0B\u8F7D\u7684\u6587\u4EF6\u5927\u5C0F\u4E0E release \u5143\u6570\u636E\u4E0D\u7B26\uFF08\u671F\u671B ${asset.size} \u5B57\u8282\uFF0C\u5B9E\u9645 ${actual} \u5B57\u8282\uFF09
7148
7263
  \u53EF\u80FD\u662F\u4E0B\u8F7D\u88AB\u622A\u65AD\u6216\u5185\u5BB9\u88AB\u66FF\u6362\uFF0C\u8BF7\u91CD\u8BD5\u6216\u6539\u7528 --no-mirror \u76F4\u8FDE`
7149
- );
7264
+ );
7265
+ }
7150
7266
  }
7151
- }
7152
- if (progressCallback) {
7153
- progressCallback("\u89E3\u538B\u5185\u6838...");
7154
- }
7155
- const extractPath = DIRS.kernel;
7156
- let extractedBinary = null;
7157
- try {
7267
+ if (progressCallback) {
7268
+ progressCallback("\u89E3\u538B\u5185\u6838...");
7269
+ }
7270
+ let extractedBinary = null;
7158
7271
  if (tempPath.endsWith(".tar.gz") || tempPath.endsWith(".tgz")) {
7159
7272
  const listResult = spawnSync7("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
7160
7273
  if (listResult.error) throw listResult.error;
@@ -7173,7 +7286,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
7173
7286
  throw new Error(`\u5F52\u6863\u542B\u975E\u666E\u901A\u6587\u4EF6\u6761\u76EE\uFF08\u7C7B\u578B "${typeChar}"\uFF09: ${line}`);
7174
7287
  }
7175
7288
  }
7176
- const tarResult = spawnSync7("tar", ["--no-same-owner", "-xzf", tempPath, "-C", extractPath], {
7289
+ const tarResult = spawnSync7("tar", ["--no-same-owner", "-xzf", tempPath, "-C", tempDir], {
7177
7290
  stdio: ["ignore", "ignore", "inherit"],
7178
7291
  timeout: 6e4
7179
7292
  });
@@ -7181,64 +7294,47 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
7181
7294
  if (tarResult.status !== 0) throw new Error(`tar \u9000\u51FA\u7801 ${tarResult.status}`);
7182
7295
  } else if (tempPath.endsWith(".gz")) {
7183
7296
  const baseName = path9.basename(tempPath, ".gz");
7184
- const outputPath = path9.join(extractPath, baseName);
7297
+ const outputPath = path9.join(tempDir, baseName);
7185
7298
  const gzipResult = spawnSync7("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
7186
7299
  if (gzipResult.error) throw gzipResult.error;
7187
7300
  if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
7188
7301
  fs12.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
7189
7302
  extractedBinary = outputPath;
7190
7303
  }
7191
- } catch (e) {
7192
- try {
7193
- fs12.unlinkSync(tempPath);
7194
- } catch {
7304
+ const foundBinary = extractedBinary || findBinaryInDir(tempDir);
7305
+ if (!foundBinary) {
7306
+ throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
7195
7307
  }
7196
- throw new Error(`\u89E3\u538B\u5931\u8D25: ${e.message}`);
7197
- }
7198
- const foundBinary = extractedBinary || findBinaryInDir(extractPath);
7199
- if (!foundBinary) {
7200
- try {
7201
- fs12.unlinkSync(tempPath);
7202
- } catch {
7308
+ if (progressCallback) {
7309
+ progressCallback("\u6821\u9A8C\u5185\u6838...");
7203
7310
  }
7204
- throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
7205
- }
7206
- const targetPath = PATHS.mihomoBinary;
7207
- if (foundBinary !== targetPath) {
7208
- if (fs12.existsSync(targetPath)) {
7209
- fs12.chmodSync(targetPath, 493);
7210
- try {
7211
- fs12.unlinkSync(targetPath);
7212
- } catch {
7311
+ fs12.chmodSync(foundBinary, 493);
7312
+ const check = spawnSync7(foundBinary, ["-v"], { encoding: "utf8", timeout: 5e3 });
7313
+ const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
7314
+ if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
7315
+ throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD
7316
+ \u9000\u51FA\u7801: ${check.status}
7317
+ \u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
7318
+ }
7319
+ const versionMatch = checkOutput.match(/v?(\d+\.\d+\.\d+)/);
7320
+ if (versionMatch && latest.tag_name) {
7321
+ const binaryVersion = versionMatch[1];
7322
+ const expectedVersion = latest.tag_name.replace(/^v/, "");
7323
+ if (binaryVersion !== expectedVersion) {
7324
+ throw new Error(`\u5185\u6838\u7248\u672C\u4E0D\u5339\u914D\uFF08\u671F\u671B ${expectedVersion}\uFF0C\u5B9E\u9645 ${binaryVersion}\uFF09\uFF0C\u65E7\u5185\u6838\u672A\u53D7\u5F71\u54CD`);
7213
7325
  }
7214
7326
  }
7327
+ const targetPath = PATHS.mihomoBinary;
7215
7328
  fs12.renameSync(foundBinary, targetPath);
7216
- }
7217
- fs12.chmodSync(targetPath, 493);
7218
- if (progressCallback) {
7219
- progressCallback("\u6821\u9A8C\u5185\u6838...");
7220
- }
7221
- const check = spawnSync7(targetPath, ["-v"], { encoding: "utf8", timeout: 5e3 });
7222
- const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
7223
- if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
7224
- try {
7225
- fs12.unlinkSync(targetPath);
7226
- } catch {
7227
- }
7329
+ fs12.chmodSync(targetPath, 493);
7330
+ clearKernelVersionCache();
7331
+ return { version: latest.tag_name, path: targetPath };
7332
+ } finally {
7228
7333
  try {
7229
- fs12.unlinkSync(tempPath);
7334
+ fs12.rmSync(tempDir, { recursive: true, force: true });
7230
7335
  } catch {
7231
7336
  }
7232
- throw new Error(`\u5185\u6838\u81EA\u68C0\u5931\u8D25\uFF08\u53EF\u80FD\u4E0B\u8F7D\u635F\u574F\u6216\u67B6\u6784\u4E0D\u5339\u914D\uFF09\uFF0C\u5DF2\u5220\u9664
7233
- \u9000\u51FA\u7801: ${check.status}
7234
- \u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
7235
- }
7236
- try {
7237
- fs12.unlinkSync(tempPath);
7238
- } catch {
7239
7337
  }
7240
- clearKernelVersionCache();
7241
- return { version: latest.tag_name, path: targetPath };
7242
7338
  }
7243
7339
 
7244
7340
  // src/commands/kernel.ts
@@ -7315,10 +7411,13 @@ async function cmdKernel(args) {
7315
7411
 
7316
7412
  // src/commands/log.ts
7317
7413
  function cmdLogs(args) {
7414
+ assertKnownFlags(args, ["-f", "--follow", "-n", "--lines", "-o", "--open"], "logs [-f] [-n N] [\u7F16\u53F7] [-o]");
7318
7415
  const lines = parseIntArg(args, "-n", "--lines", 100);
7319
7416
  const openInViewer = hasFlag(args, "-o", "--open");
7320
7417
  const follow = hasFlag(args, "-f", "--follow");
7321
- const hasLinesFlag = args.some((a) => a === "-n" || a === "--lines" || a.startsWith("--lines="));
7418
+ const hasLinesFlag = args.some(
7419
+ (a) => a === "-n" || a === "--lines" || a.startsWith("--lines=") || a.startsWith("-n") && a.length > 2 && /^\d+$/.test(a.slice(2))
7420
+ );
7322
7421
  const targetName = getNonFlagArg(args, 1) ?? (follow || openInViewer || hasLinesFlag ? "0" : null);
7323
7422
  if (targetName) {
7324
7423
  let logPath;
@@ -7516,7 +7615,8 @@ var RESET_TARGETS = [
7516
7615
  aliases: ["log", "logs"],
7517
7616
  label: "\u65E5\u5FD7",
7518
7617
  paths: () => [DIRS.logs],
7519
- needsStop: false
7618
+ // 内核运行时持有日志 fd,删文件后内核继续写已删 inode,logs 0 会 tail 不存在的路径
7619
+ needsStop: true
7520
7620
  },
7521
7621
  {
7522
7622
  id: "data",
@@ -7562,7 +7662,10 @@ var RESET_TARGETS = [
7562
7662
  if (!fs14.existsSync(dir)) return [];
7563
7663
  return fs14.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
7564
7664
  },
7565
- needsStop: false
7665
+ needsStop: false,
7666
+ onAfter: () => {
7667
+ writeSettings({ overwrite_enabled: false });
7668
+ }
7566
7669
  },
7567
7670
  {
7568
7671
  id: "service",
@@ -7699,9 +7802,12 @@ async function cmdReset(args) {
7699
7802
  });
7700
7803
  }
7701
7804
  }
7805
+ const deleted = [];
7702
7806
  for (const t of targets) {
7807
+ let hadContent = false;
7703
7808
  for (const p of t.paths()) {
7704
7809
  if (fs14.existsSync(p)) {
7810
+ hadContent = true;
7705
7811
  try {
7706
7812
  rmrf(p);
7707
7813
  } catch (e) {
@@ -7710,12 +7816,19 @@ async function cmdReset(args) {
7710
7816
  }
7711
7817
  }
7712
7818
  await t.onAfter?.();
7819
+ if (hadContent || !t.checkEmpty) {
7820
+ deleted.push(t.label);
7821
+ }
7713
7822
  }
7714
7823
  ensureDirs();
7715
7824
  if (targets.some((t) => t.id === "settings")) {
7716
7825
  invalidateSettingsCache();
7717
7826
  }
7718
- console.log(colors.green(`\u5DF2\u91CD\u7F6E: ${targets.map((t) => t.label).join("\u3001")}`));
7827
+ if (deleted.length > 0) {
7828
+ console.log(colors.green(`\u5DF2\u91CD\u7F6E: ${deleted.join("\u3001")}`));
7829
+ } else {
7830
+ console.log("\u6CA1\u6709\u9700\u8981\u91CD\u7F6E\u7684\u5185\u5BB9");
7831
+ }
7719
7832
  }
7720
7833
 
7721
7834
  // src/commands/service.ts
@@ -7800,8 +7913,7 @@ function handleStopResult(result) {
7800
7913
  throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint: "\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo" });
7801
7914
  }
7802
7915
  }
7803
- async function cmdStop(args) {
7804
- assertNoRemovedSshFlag(args);
7916
+ async function cmdStop(_args) {
7805
7917
  if (detectLegacySystemInstall()) {
7806
7918
  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"));
7807
7919
  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"));
@@ -7957,7 +8069,14 @@ var COMMANDS = [
7957
8069
  name: "log",
7958
8070
  aliases: [],
7959
8071
  handler: cmdLogs,
7960
- rewrite: (args) => ["logs", "0", "-f", ...args.slice(1)],
8072
+ // 隐藏别名:log = logs 0 -f。用户传了编号时尊重编号(log 1 = logs 1 -f),
8073
+ // 而非恒为 0——此前编号被 '0' 顶掉,log 1 跟随的是当前日志而非归档 1
8074
+ rewrite: (args) => {
8075
+ const hasNum = args[1] !== void 0 && /^\d+$/.test(args[1]);
8076
+ const num = hasNum ? args[1] : "0";
8077
+ const rest = hasNum ? args.slice(2) : args.slice(1);
8078
+ return ["logs", num, "-f", ...rest];
8079
+ },
7961
8080
  group: "interface",
7962
8081
  usage: [],
7963
8082
  hidden: true
@@ -8172,6 +8291,7 @@ async function main() {
8172
8291
  assertSupportedPlatform(command.name);
8173
8292
  assertNotRoot(command.name);
8174
8293
  ensureDirs();
8294
+ assertNoRemovedSshFlag(args);
8175
8295
  await command.handler(command.rewrite ? command.rewrite(args) : args);
8176
8296
  }
8177
8297
  main().catch((e) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mihomo-cli",
3
- "version": "4.5.0",
3
+ "version": "4.6.0",
4
4
  "type": "module",
5
5
  "description": "A terminal-based mihomo (Clash.Meta) client for macOS",
6
6
  "bin": {