mihomo-cli 4.7.6 → 4.7.7

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,27 @@
1
1
  # Changelog
2
2
 
3
+ ## [4.7.7] - 2026-09-07
4
+
5
+ 收尾 v4.7.6 修复留下的残留缺口:并发判据换成停止计数,与 launchd 的 disable 位解耦。单测 319(+5)。
6
+
7
+ ### 修复
8
+
9
+ - **并发的 `stop` 在「上次也 stop 过」时会被 `start` 覆盖**:v4.7.6 把判据从「当前是否 disabled」改成「disable 位的前后快照比对」,修好了「stop 之后 start 永远起不来」,但留了个反向的洞——**两边快照都是 `true` 时判为「非并发」**。可达序列:A 跑慢速 start(上次 stop 过,故快照 `disabledBefore=true`)→ B 在订阅更新那约 10s 里跑完整个 `mihomo stop` → A 锁内查到仍是 `true` → 判为「无人 stop」→ enable + bootstrap,把 B 的 stop 覆盖掉。用户最后一条命令是 stop,终态却是运行中,而两个终端都拿到了成功回执。
10
+
11
+ 根因是 **launchd 只提供 disable 位的当前值,给不出「它是何时被写的」**——任何基于位的判据都区分不了「上次留下的」与「刚刚新置的」。改用 CLI 自己维护的单调计数(`~/.mihomo-cli/service-stop-epoch`):`start` 在慢速阶段之前取快照、锁内复读,值变了就说明期间有人 stop 过,与位的当前值完全解耦。递增**收口在 `disableServiceAutoStart` 内**(五个调用点,任一漏 bump 就是那条路径上的防线空洞),并放在「位已确认生效」之后——位没生效就记「停止过」,会让并发的 start 白白中止。
12
+
13
+ 同族路径 `installService` 的 `wasRunning` 恢复分支共用该判据(它同样在锁内 enable+bootstrap,同样会反噬并发 stop),被取消时返回 `restoreSkipped: true`,`cmdInstall` 据此跳过健康确认并单独提示——否则会把用户自己的 stop 报成「恢复运行失败」。
14
+
15
+ `bootout` 刻意仍留在锁外:`withFileLock` 要求 fn 同步(持锁期间 await 会让另一进程等到强夺陈旧锁),而 bootout 后必须 `waitUntilUnloaded`(最多 5s)。这是安全的——并发 stop 落在该窗口时,start 侧的 bootout 只是幂等空操作,计数变化仍会在锁内被检出。这正是计数判据相对「扩大临界区」的价值。
16
+
17
+ **教训**:这个判据两版都错在同一件事上——拿一个**状态**去推断一个**事件**。disable 位是状态,「有没有人 stop 过」是事件;状态没有历史,事件才有。发现自己在用「读一下当前值」回答「期间发生过什么」时,就该换判据而不是换比较方式。
18
+
19
+ ### 测试
20
+
21
+ - `shouldAbortStartOnDisable` 五条组合(含 v4.7.6 漏掉的「基线非 0 且期间又 stop」)+ 三条走**真实** `readStopEpoch` 的用例(经 `MIHOMO_CLI_DIR` 指向 tmpdir,不碰 launchctl 故系统无痕迹)。测试调的是 `service.ts` 导出的实现而非另抄一份——抄一份等于在验副本
22
+ - `paths.spec.ts` 补一条:停止计数文件同样不能落在会被 `rmrf` 的目录(它命名刻意不带 `Lock` 后缀,不进锁枚举,故单独点名)。被删后读作 0,「期间发生过 stop」的记录就丢了
23
+ - **反向验证过**:v4.7.6 的判据在「基线非 0 且期间又 stop」下返回 `false`(放行 → 覆盖并发 stop),计数判据返回 `true`。另跑四场景端到端脚本,两代缺陷各自的失效点都覆盖到
24
+
3
25
  ## [4.7.6] - 2026-09-07
4
26
 
5
27
  用户实测报告的单点修复:`mihomo stop` 或 `mihomo tun` 之后,`mihomo start` **再也起不来**。单测 314(+4)。
package/dist/index.js CHANGED
@@ -3211,6 +3211,19 @@ var PATHS = {
3211
3211
  settingsLock: path.join(USER_DATA_DIR, "settings.lock"),
3212
3212
  subscriptionCacheLock: path.join(USER_DATA_DIR, "subscription-cache.lock"),
3213
3213
  serviceLock: path.join(USER_DATA_DIR, "service.lock"),
3214
+ /**
3215
+ * 「服务被要求停止」的单调计数(`service.ts` 的 `bumpStopEpoch`/`readStopEpoch`)。
3216
+ *
3217
+ * 为什么需要它:判断「本次 start 执行**期间**是否有人 stop 过」,launchd 自身给不出答案——
3218
+ * disable 位只有当前值,没有写入时间,而它又是**持久**的(上次 stop 留下的与刚刚新置的
3219
+ * 完全同形)。只比对 disable 位的前后快照,在「上次也 stop 过」时两边都是 true,
3220
+ * 并发 stop 就此隐形(v4.7.6 的残留缺口)。计数值变了则一定有人 stop 过,与位的当前值无关。
3221
+ *
3222
+ * 与锁同放 USER_DATA_DIR 根下,理由相同:`runtime/` 等目录会被 `rmrf`,
3223
+ * 文件消失即读作 0,会让「期间发生过 stop」丢失。命名**刻意不以 `Lock` 结尾**——
3224
+ * 它不是锁,不该进 `paths.spec.ts` 那条锁位置断言的枚举。
3225
+ */
3226
+ serviceStopEpoch: path.join(USER_DATA_DIR, "service-stop-epoch"),
3214
3227
  configStage1Subscription: path.join(DIRS.runtime, "1.subscription.yaml"),
3215
3228
  configStage2Overwrite: path.join(DIRS.runtime, "2.overwrite.yaml"),
3216
3229
  configStage3System: path.join(DIRS.runtime, "3.system.yaml"),
@@ -5033,6 +5046,7 @@ async function installService(wasRunning) {
5033
5046
  assertServiceLabelSafe();
5034
5047
  ensureDirs();
5035
5048
  ensureServiceSymlink();
5049
+ let restoreSkipped = false;
5036
5050
  const stagePath = path6.join(DIRS.runtime, "service.plist.stage");
5037
5051
  atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
5038
5052
  try {
@@ -5048,7 +5062,12 @@ async function installService(wasRunning) {
5048
5062
  fs8.copyFileSync(stagePath, PATHS.userAgentPlist);
5049
5063
  fs8.chmodSync(PATHS.userAgentPlist, 420);
5050
5064
  if (wasRunning) {
5065
+ const stopEpochBefore = readStopEpoch();
5051
5066
  withFileLock(PATHS.serviceLock, () => {
5067
+ if (shouldAbortStartOnDisable(stopEpochBefore, readStopEpoch())) {
5068
+ restoreSkipped = true;
5069
+ return;
5070
+ }
5052
5071
  runLaunchctlOrThrow(["enable", serviceTarget()], "\u542F\u7528\u670D\u52A1");
5053
5072
  runLaunchctlOrThrow(["bootstrap", bootstrapDomain(), PATHS.userAgentPlist], "\u88C5\u8F7D\u670D\u52A1");
5054
5073
  });
@@ -5062,11 +5081,27 @@ async function installService(wasRunning) {
5062
5081
  if (!wasRunning) {
5063
5082
  disableServiceAutoStart();
5064
5083
  }
5084
+ return { restoreSkipped };
5085
+ }
5086
+ function readStopEpoch() {
5087
+ try {
5088
+ const n = Number.parseInt(fs8.readFileSync(PATHS.serviceStopEpoch, "utf8").trim(), 10);
5089
+ return Number.isSafeInteger(n) && n >= 0 ? n : 0;
5090
+ } catch {
5091
+ return 0;
5092
+ }
5065
5093
  }
5066
- function shouldAbortStartOnDisable(disabledBefore, disabledNow) {
5067
- return !disabledBefore && disabledNow;
5094
+ function bumpStopEpoch() {
5095
+ try {
5096
+ ensureDirs();
5097
+ atomicWriteFileSync(PATHS.serviceStopEpoch, String(readStopEpoch() + 1));
5098
+ } catch {
5099
+ }
5068
5100
  }
5069
- async function startService(disabledBefore) {
5101
+ function shouldAbortStartOnDisable(stopEpochBefore, stopEpochNow) {
5102
+ return stopEpochNow !== stopEpochBefore;
5103
+ }
5104
+ async function startService(stopEpochBefore) {
5070
5105
  assertServiceLabelSafe();
5071
5106
  ensureServiceSymlink();
5072
5107
  if (!isServiceInstalled()) {
@@ -5092,7 +5127,7 @@ async function startService(disabledBefore) {
5092
5127
  rotateAndCleanupLogs();
5093
5128
  let started = true;
5094
5129
  withFileLock(PATHS.serviceLock, () => {
5095
- if (shouldAbortStartOnDisable(disabledBefore, isServiceDisabledInLaunchd())) {
5130
+ if (shouldAbortStartOnDisable(stopEpochBefore, readStopEpoch())) {
5096
5131
  started = false;
5097
5132
  return;
5098
5133
  }
@@ -5109,6 +5144,7 @@ function disableServiceAutoStart() {
5109
5144
  hint: [`\u624B\u52A8\u786E\u8BA4: launchctl print-disabled ${bootstrapDomain()}`, "", "\u4E0D\u5173\u95ED\u81EA\u542F\u7684\u8BDD\uFF0C\u91CD\u542F\u540E\u670D\u52A1\u4F1A\u62FF TUN \u914D\u7F6E\u53CD\u590D\u62C9\u8D77\u5FC5\u7136\u5931\u8D25\u7684\u5185\u6838\u3002"]
5110
5145
  });
5111
5146
  }
5147
+ bumpStopEpoch();
5112
5148
  }
5113
5149
  async function stopService() {
5114
5150
  assertServiceLabelSafe();
@@ -5502,7 +5538,7 @@ function getRunningState(serviceStatus) {
5502
5538
  function isRestartNeededOnChange() {
5503
5539
  return getRunningState().running;
5504
5540
  }
5505
- async function launchOrRestart(mode, disabledBefore = false) {
5541
+ async function launchOrRestart(mode, stopEpochBefore) {
5506
5542
  if (mode === "tun") {
5507
5543
  const result = await startTun();
5508
5544
  return result.pid;
@@ -5512,7 +5548,7 @@ async function launchOrRestart(mode, disabledBefore = false) {
5512
5548
  const { hotReloaded } = await restartService();
5513
5549
  if (hotReloaded) return getServiceStatus().pid;
5514
5550
  } else {
5515
- const { started } = await startService(disabledBefore);
5551
+ const { started } = await startService(stopEpochBefore ?? readStopEpoch());
5516
5552
  if (!started) {
5517
5553
  throw new CliError("\u542F\u52A8\u5DF2\u53D6\u6D88\uFF1A\u671F\u95F4\u68C0\u6D4B\u5230 stop", {
5518
5554
  label: "\u542F\u52A8\u5931\u8D25",
@@ -6172,6 +6208,7 @@ async function cmdStart(args) {
6172
6208
  const skipUpdate = hasFlag(args, "-s", "--no-update");
6173
6209
  const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
6174
6210
  const serviceBefore = getServiceStatus();
6211
+ const stopEpochBefore = readStopEpoch();
6175
6212
  if (targetMode === "tun") {
6176
6213
  if (detectLegacySystemInstall()) {
6177
6214
  console.log(colors.yellow("\u68C0\u6D4B\u5230\u65E7\u7248\u672C\u5B89\u88C5\u7684\u7CFB\u7EDF\u7EA7\u670D\u52A1\uFF08root LaunchDaemon\uFF09\uFF0C\u542F\u52A8 TUN \u524D\u9700\u6E05\u7406"));
@@ -6216,7 +6253,7 @@ async function cmdStart(args) {
6216
6253
  const modeLabel = targetMode === "tun" ? "TUN" : "Mixed";
6217
6254
  console.log([colors.cyan(modeLabel), sub.name, formatProxySummary(configInfo)].join(" \xB7 "));
6218
6255
  try {
6219
- const pid = await launchOrRestart(targetMode, serviceBefore.disabled);
6256
+ const pid = await launchOrRestart(targetMode, stopEpochBefore);
6220
6257
  console.log(`${colors.green("\u5DF2\u542F\u52A8")}${pid ? ` (PID ${pid})` : ""}`);
6221
6258
  } catch (e) {
6222
6259
  if (e instanceof CliError) throw e;
@@ -8033,11 +8070,18 @@ async function cmdInstall(_args) {
8033
8070
  }
8034
8071
  await handleLegacyInstall();
8035
8072
  const wasRunning = getServiceStatus().running;
8036
- await installService(wasRunning);
8073
+ const { restoreSkipped } = await installService(wasRunning);
8037
8074
  console.log(`${colors.green("\u5DF2\u5B89\u88C5\u670D\u52A1")}`);
8038
8075
  console.log(colors.gray(` plist: ${PATHS.userAgentPlist}`));
8039
8076
  console.log(colors.gray(` \u767B\u5F55\u9879\u4E0E\u6269\u5C55\u4E2D\u663E\u793A\u4E3A: ${SERVICE_BINARY_NAME}`));
8040
8077
  console.log("");
8078
+ if (restoreSkipped) {
8079
+ console.log(colors.yellow("\u672A\u6062\u590D\u8FD0\u884C\uFF1A\u5B89\u88C5\u671F\u95F4\u68C0\u6D4B\u5230 stop"));
8080
+ console.log(colors.gray(" \u53E6\u4E00\u4E2A\u7EC8\u7AEF\u6267\u884C\u4E86 mihomo stop\uFF0C\u5DF2\u6309\u6700\u540E\u4E00\u6761\u547D\u4EE4\u4FDD\u6301\u505C\u6B62"));
8081
+ console.log(colors.gray(" \u542F\u52A8: mihomo start"));
8082
+ console.log("");
8083
+ return;
8084
+ }
8041
8085
  if (wasRunning) {
8042
8086
  try {
8043
8087
  await assertServiceHealthy("\u6062\u590D\u8FD0\u884C\u5931\u8D25");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mihomo-cli",
3
- "version": "4.7.6",
3
+ "version": "4.7.7",
4
4
  "type": "module",
5
5
  "description": "A terminal-based mihomo (Clash.Meta) client for macOS",
6
6
  "bin": {