mihomo-cli 3.8.0 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -17,9 +17,9 @@ var colors = {
17
17
 
18
18
  // src/config.ts
19
19
  import { spawnSync } from "child_process";
20
- import fs4 from "fs";
20
+ import fs5 from "fs";
21
21
 
22
- // node_modules/js-yaml/dist/js-yaml.mjs
22
+ // ../../../node_modules/js-yaml/dist/js-yaml.mjs
23
23
  var NOT_RESOLVED = /* @__PURE__ */ Symbol("NOT_RESOLVED");
24
24
  function defineScalarTag(tagName, options) {
25
25
  return {
@@ -3183,10 +3183,10 @@ var DIRS = {
3183
3183
  logs: path.join(USER_DATA_DIR, "logs"),
3184
3184
  data: path.join(USER_DATA_DIR, "data"),
3185
3185
  runtime: path.join(USER_DATA_DIR, "runtime"),
3186
- // 隧道运行态。刻意独立于 runtime/:clearRuntime() 会在 stop() 成功路径 rmrf 整个
3186
+ // ssh 隧道运行态。刻意独立于 runtime/:clearRuntime() 会在 stop() 成功路径 rmrf 整个
3187
3187
  // runtime 目录,隧道状态放那里会被 `mihomo stop` 连同 config.yaml 一起抹掉,
3188
3188
  // 于是「谁起的」标记丢失、手动起的隧道再也无法被识别
3189
- tunnel: path.join(USER_DATA_DIR, "tunnel")
3189
+ ssh: path.join(USER_DATA_DIR, "ssh")
3190
3190
  };
3191
3191
  var PATHS = {
3192
3192
  mihomoBinary: path.join(DIRS.kernel, "mihomo"),
@@ -3198,6 +3198,9 @@ var PATHS = {
3198
3198
  configStage1Subscription: path.join(DIRS.runtime, "1.subscription.yaml"),
3199
3199
  configStage2Overwrite: path.join(DIRS.runtime, "2.overwrite.yaml"),
3200
3200
  configStage3System: path.join(DIRS.runtime, "3.system.yaml"),
3201
+ // ssh 单列一个 stage:它不受 overwrite 开关约束,混进 2.overwrite.yaml 会让
3202
+ // `ow off` 时的调试输出自相矛盾(覆写已禁用,文件里却有内容)
3203
+ configStage4Ssh: path.join(DIRS.runtime, "4.ssh.yaml"),
3201
3204
  // launchd LaunchDaemon plist 位于系统级 /Library/LaunchDaemons/,root:wheel 拥有,与 homedir / MIHOMO_CLI_DIR 无关
3202
3205
  launchDaemonPlist: path.join("/Library/LaunchDaemons", `${LAUNCH_DAEMON_LABEL}.plist`)
3203
3206
  };
@@ -3233,6 +3236,55 @@ function atomicWriteFileSync(filePath, content, options) {
3233
3236
  function rmrf(dir) {
3234
3237
  fs.rmSync(dir, { recursive: true, force: true });
3235
3238
  }
3239
+ var LOCK_STALE_MS = 1e4;
3240
+ var LOCK_RETRY_MS = 20;
3241
+ function withFileLock(filePath, fn) {
3242
+ const lockPath = `${filePath}.lock`;
3243
+ const deadline = Date.now() + LOCK_STALE_MS;
3244
+ let fd = null;
3245
+ while (fd === null) {
3246
+ try {
3247
+ fd = fs.openSync(lockPath, "wx");
3248
+ } catch (e) {
3249
+ if (e.code !== "EEXIST") throw e;
3250
+ let stale = false;
3251
+ try {
3252
+ stale = Date.now() - fs.statSync(lockPath).mtimeMs > LOCK_STALE_MS;
3253
+ } catch {
3254
+ }
3255
+ if (stale) {
3256
+ try {
3257
+ fs.rmSync(lockPath, { force: true });
3258
+ } catch {
3259
+ }
3260
+ continue;
3261
+ }
3262
+ if (Date.now() > deadline) {
3263
+ try {
3264
+ fs.rmSync(lockPath, { force: true });
3265
+ } catch {
3266
+ }
3267
+ continue;
3268
+ }
3269
+ sleepSyncMs(LOCK_RETRY_MS);
3270
+ }
3271
+ }
3272
+ try {
3273
+ return fn();
3274
+ } finally {
3275
+ try {
3276
+ fs.closeSync(fd);
3277
+ } catch {
3278
+ }
3279
+ try {
3280
+ fs.rmSync(lockPath, { force: true });
3281
+ } catch {
3282
+ }
3283
+ }
3284
+ }
3285
+ function sleepSyncMs(ms) {
3286
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
3287
+ }
3236
3288
 
3237
3289
  // src/settings.ts
3238
3290
  import fs2 from "fs";
@@ -3269,6 +3321,10 @@ function recoverCorruptedSettings() {
3269
3321
  }
3270
3322
  function writeSettings(settings) {
3271
3323
  ensureDirs();
3324
+ return withFileLock(PATHS.settingsFile, () => writeSettingsUnlocked(settings));
3325
+ }
3326
+ function writeSettingsUnlocked(settings) {
3327
+ settingsCache = null;
3272
3328
  const existing = readSettings();
3273
3329
  const merged = { ...existing, ...settings };
3274
3330
  for (const key of Object.keys(settings)) {
@@ -3278,6 +3334,14 @@ function writeSettings(settings) {
3278
3334
  settingsCache = merged;
3279
3335
  return settingsCache;
3280
3336
  }
3337
+ function updateSettings(mutate) {
3338
+ ensureDirs();
3339
+ return withFileLock(PATHS.settingsFile, () => {
3340
+ settingsCache = null;
3341
+ const current = readSettings();
3342
+ return writeSettingsUnlocked(mutate(current));
3343
+ });
3344
+ }
3281
3345
  function invalidateSettingsCache() {
3282
3346
  settingsCache = null;
3283
3347
  }
@@ -3323,10 +3387,13 @@ function maskUrl(url) {
3323
3387
  }
3324
3388
  function readSubscriptionCache() {
3325
3389
  ensureDirs();
3390
+ const empty = () => /* @__PURE__ */ Object.create(null);
3326
3391
  if (fs2.existsSync(PATHS.subscriptionsCacheFile)) {
3327
3392
  try {
3328
3393
  const content = fs2.readFileSync(PATHS.subscriptionsCacheFile, "utf8");
3329
- return JSON.parse(content);
3394
+ const parsed = JSON.parse(content);
3395
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return empty();
3396
+ return Object.assign(empty(), parsed);
3330
3397
  } catch {
3331
3398
  try {
3332
3399
  fs2.copyFileSync(PATHS.subscriptionsCacheFile, `${PATHS.subscriptionsCacheFile}.bak`);
@@ -3334,10 +3401,10 @@ function readSubscriptionCache() {
3334
3401
  } catch {
3335
3402
  console.warn("\u8B66\u544A: \u8BA2\u9605\u7F13\u5B58\u683C\u5F0F\u635F\u574F\uFF0C\u5DF2\u5FFD\u7565");
3336
3403
  }
3337
- return {};
3404
+ return empty();
3338
3405
  }
3339
3406
  }
3340
- return {};
3407
+ return empty();
3341
3408
  }
3342
3409
  function writeSubscriptionCache(cache) {
3343
3410
  ensureDirs();
@@ -3368,6 +3435,22 @@ function getSubscriptionsWithCache() {
3368
3435
  }));
3369
3436
  }
3370
3437
  var SAFE_NAME_RE = /^[\w\-\p{Unified_Ideograph}]{1,64}$/u;
3438
+ function getSshTunnels() {
3439
+ const settings = readSettings();
3440
+ const tunnels = settings.ssh;
3441
+ if (!Array.isArray(tunnels)) {
3442
+ if (tunnels !== void 0) {
3443
+ console.warn("\u8B66\u544A: settings.json \u7684 ssh \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08\u53EF\u7528 mihomo ssh add \u91CD\u65B0\u6DFB\u52A0\uFF09");
3444
+ }
3445
+ return [];
3446
+ }
3447
+ return tunnels.filter((t) => t != null && typeof t === "object" && typeof t.name === "string" && typeof t.host === "string" && Number.isInteger(t.port));
3448
+ }
3449
+ function validateSshName(name) {
3450
+ if (!name || !SAFE_NAME_RE.test(name)) {
3451
+ throw new CliError(`\u96A7\u9053\u540D\u79F0\u65E0\u6548: "${name}"\uFF0C\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\u548C\u4E2D\u6587\uFF08\u6700\u957F 64 \u5B57\u7B26\uFF09`);
3452
+ }
3453
+ }
3371
3454
  function validateSubscriptionName(name) {
3372
3455
  if (!name || !SAFE_NAME_RE.test(name)) {
3373
3456
  throw new CliError(`\u8BA2\u9605\u540D\u79F0\u65E0\u6548: "${name}"\uFF0C\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\u548C\u4E2D\u6587\uFF08\u6700\u957F 64 \u5B57\u7B26\uFF09`);
@@ -3375,31 +3458,41 @@ function validateSubscriptionName(name) {
3375
3458
  }
3376
3459
  function addSubscription(url, name = "default") {
3377
3460
  validateSubscriptionName(name);
3378
- const settings = readSettings();
3379
- const subs = [...getSubscriptions()];
3380
- if (subs.some((s) => s.name === name)) {
3461
+ let duplicate = false;
3462
+ updateSettings((settings) => {
3463
+ const subs = [...getSubscriptions()];
3464
+ if (subs.some((s) => s.name === name)) {
3465
+ duplicate = true;
3466
+ return {};
3467
+ }
3468
+ subs.push({ name, url });
3469
+ const updates = { subscriptions: subs };
3470
+ if (!settings.active_subscription && subs.length === 1) {
3471
+ updates.active_subscription = name;
3472
+ }
3473
+ return updates;
3474
+ });
3475
+ if (duplicate) {
3381
3476
  throw new CliError(`\u8BA2\u9605 "${name}" \u5DF2\u5B58\u5728\uFF0C\u8BF7\u6362\u4E2A\u540D\u79F0\uFF08mihomo sub add <url> <\u540D\u79F0>\uFF09\uFF0C\u6216\u5148\u5220\u9664\uFF08mihomo sub remove ${name}\uFF09`);
3382
3477
  }
3383
- subs.push({ name, url });
3384
- const updates = { subscriptions: subs };
3385
- if (!settings.active_subscription && subs.length === 1) {
3386
- updates.active_subscription = name;
3387
- }
3388
- writeSettings(updates);
3389
3478
  }
3390
3479
  function removeSubscription(name) {
3391
- const settings = readSettings();
3392
- const subs = [...getSubscriptions()];
3393
- const idx = subs.findIndex((s) => s.name === name);
3394
- if (idx < 0) return null;
3395
- subs.splice(idx, 1);
3396
- const updates = { subscriptions: subs };
3397
3480
  let switchedTo = null;
3398
- if (settings.active_subscription === name) {
3399
- switchedTo = subs.length > 0 ? subs[0].name : null;
3400
- updates.active_subscription = switchedTo ?? void 0;
3401
- }
3402
- writeSettings(updates);
3481
+ let found = false;
3482
+ updateSettings((settings) => {
3483
+ const subs = [...getSubscriptions()];
3484
+ const idx = subs.findIndex((s) => s.name === name);
3485
+ if (idx < 0) return {};
3486
+ found = true;
3487
+ subs.splice(idx, 1);
3488
+ const updates = { subscriptions: subs };
3489
+ if (settings.active_subscription === name) {
3490
+ switchedTo = subs.length > 0 ? subs[0].name : null;
3491
+ updates.active_subscription = switchedTo ?? void 0;
3492
+ }
3493
+ return updates;
3494
+ });
3495
+ if (!found) return null;
3403
3496
  const cache = readSubscriptionCache();
3404
3497
  if (cache[name]) {
3405
3498
  delete cache[name];
@@ -3693,6 +3786,100 @@ function listOverwriteFile() {
3693
3786
  };
3694
3787
  }
3695
3788
 
3789
+ // src/ssh-config.ts
3790
+ import fs4 from "fs";
3791
+ import path4 from "path";
3792
+ var SSH_FILENAME_RE = /^ssh\.(.+)\.ya?ml$/;
3793
+ function isSshFilename(filename) {
3794
+ return SSH_FILENAME_RE.test(filename);
3795
+ }
3796
+ function getSshConfigPath(name) {
3797
+ validateSshName(name);
3798
+ return path4.join(USER_DATA_DIR, `ssh.${name}.yaml`);
3799
+ }
3800
+ function getSshProxyName(name) {
3801
+ return `Ssh-${name}-Host`;
3802
+ }
3803
+ function getSshGroupName(name) {
3804
+ return `Ssh-${name}`;
3805
+ }
3806
+ function renderSshProxy(tunnel) {
3807
+ return {
3808
+ name: getSshProxyName(tunnel.name),
3809
+ type: "socks5",
3810
+ server: "127.0.0.1",
3811
+ port: tunnel.port
3812
+ };
3813
+ }
3814
+ function collectSshProxyNames(tunnels) {
3815
+ return tunnels.map((t) => getSshProxyName(t.name));
3816
+ }
3817
+ function loadSshConfigFiles() {
3818
+ if (!fs4.existsSync(USER_DATA_DIR)) return [];
3819
+ const files = fs4.readdirSync(USER_DATA_DIR).filter(isSshFilename).sort();
3820
+ const results = [];
3821
+ for (const file of files) {
3822
+ const filePath = path4.join(USER_DATA_DIR, file);
3823
+ try {
3824
+ const parsed = load(fs4.readFileSync(filePath, "utf8"), { maxAliases: 200 });
3825
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
3826
+ if ("match" in parsed) {
3827
+ console.warn(`\u8B66\u544A: ssh \u914D\u7F6E "${file}" \u7684 match \u5757\u4E0D\u751F\u6548\uFF08ssh \u96A7\u9053\u6052\u5168\u5C40\uFF09\uFF0C\u5DF2\u5FFD\u7565`);
3828
+ delete parsed.match;
3829
+ }
3830
+ results.push({ name: file, path: filePath, config: parsed });
3831
+ } else if (parsed !== null) {
3832
+ console.warn(`\u8B66\u544A: ssh \u914D\u7F6E "${file}" \u9876\u5C42\u5FC5\u987B\u662F\u5BF9\u8C61\uFF0C\u5DF2\u8DF3\u8FC7`);
3833
+ }
3834
+ } catch (e) {
3835
+ console.warn(`\u8B66\u544A: ssh \u914D\u7F6E "${file}" \u89E3\u6790\u5931\u8D25: ${e.message}`);
3836
+ }
3837
+ }
3838
+ return results;
3839
+ }
3840
+ function applySshConfig(baseConfig, sshFiles, tunnels) {
3841
+ let result = { ...baseConfig };
3842
+ for (const file of sshFiles) {
3843
+ result = deepMergeWithOverrides(result, file.config);
3844
+ }
3845
+ if (tunnels.length > 0) {
3846
+ result = deepMergeWithOverrides(result, { "~proxies": tunnels.map(renderSshProxy) });
3847
+ }
3848
+ return result;
3849
+ }
3850
+ function renderSshConfigTemplate(tunnel) {
3851
+ const proxyName = getSshProxyName(tunnel.name);
3852
+ const groupName = getSshGroupName(tunnel.name);
3853
+ return `# mihomo-cli ssh \u96A7\u9053\u914D\u7F6E\uFF08ssh: ${tunnel.name}\uFF09
3854
+ # \u672C\u6587\u4EF6\u7531 mihomo-cli \u9996\u6B21\u521B\u5EFA\uFF0C\u4E4B\u540E\u5B8C\u5168\u7531\u4F60\u7EF4\u62A4\u2014\u2014CLI \u4E0D\u4F1A\u518D\u6539\u5199\u6216\u5220\u9664\u5B83\u3002
3855
+ #
3856
+ # \u8282\u70B9 ${proxyName} \u7531 CLI \u4F9D\u636E settings \u91CC\u7684 host/port \u81EA\u52A8\u6CE8\u5165\uFF0C
3857
+ # \u65E0\u9700\u4E5F\u4E0D\u8981\u5728\u6B64\u58F0\u660E\uFF1A\u7AEF\u53E3\u4EE5 \`mihomo ssh\` \u663E\u793A\u7684\u4E3A\u51C6\uFF0C\u6539\u7AEF\u53E3\u7528 \`mihomo ssh add\`\u3002
3858
+ #
3859
+ # \u672C\u6587\u4EF6\u4E0D\u53D7 \`mihomo ow off\` \u5F71\u54CD\uFF08ssh \u5206\u6D41\u662F\u521A\u9700\uFF0C\u8986\u5199\u662F\u53EF\u9009\u8C03\u4F18\uFF09\u3002
3860
+ # ~ \u662F\u300C\u6309 name \u5C31\u5730\u5408\u5E76\u300D\u8BED\u4E49\uFF0C\u4E0D\u4F9D\u8D56\u6587\u4EF6\u52A0\u8F7D\u987A\u5E8F\u3002
3861
+
3862
+ ~proxy-groups:
3863
+ - name: ${groupName}
3864
+ type: select
3865
+ proxies:
3866
+ - ${proxyName}
3867
+ - DIRECT
3868
+
3869
+ # \u53D6\u6D88\u6CE8\u91CA\u5E76\u586B\u5165\u9700\u8981\u8D70\u96A7\u9053\u7684\u5185\u7F51\u57DF\u540D/\u7F51\u6BB5\uFF08CLI \u65E0\u4ECE\u77E5\u9053\u4F60\u7684\u5185\u7F51\u5730\u5740\uFF09\uFF1A
3870
+ # +rules:
3871
+ # - DOMAIN-SUFFIX,example.internal,${groupName}
3872
+ # - IP-CIDR,10.0.0.0/8,${groupName}
3873
+ `;
3874
+ }
3875
+ function ensureSshConfigFile(tunnel) {
3876
+ const filePath = getSshConfigPath(tunnel.name);
3877
+ if (fs4.existsSync(filePath)) return false;
3878
+ fs4.mkdirSync(USER_DATA_DIR, { recursive: true, mode: 448 });
3879
+ fs4.writeFileSync(filePath, renderSshConfigTemplate(tunnel), { mode: 384 });
3880
+ return true;
3881
+ }
3882
+
3696
3883
  // src/utils.ts
3697
3884
  var sleepBuf = new Int32Array(new SharedArrayBuffer(4));
3698
3885
  function sleepSync(ms) {
@@ -3801,7 +3988,7 @@ var VALUE_FLAGS = /* @__PURE__ */ new Set([
3801
3988
  ]);
3802
3989
  function extractStartOptions(args) {
3803
3990
  if (!args) return [];
3804
- const BOOL_FLAGS = /* @__PURE__ */ new Set(["-s", "--no-update", "--no-clean", "--no-tunnel"]);
3991
+ const BOOL_FLAGS = /* @__PURE__ */ new Set(["-s", "--no-update", "--no-clean", "--no-ssh"]);
3805
3992
  const out = [];
3806
3993
  for (let i = 0; i < args.length; i++) {
3807
3994
  const a = args[i];
@@ -3859,14 +4046,24 @@ function suggestSimilar(input, candidates) {
3859
4046
  function normalizeMirrorUrl(val) {
3860
4047
  if (!val) return null;
3861
4048
  if (val === "direct" || val === "no" || val === "none") return null;
3862
- let url = val;
3863
- if (!url.startsWith("http")) {
3864
- url = `https://${url}`;
4049
+ const withScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(val) ? val : `https://${val}`;
4050
+ let parsed;
4051
+ try {
4052
+ parsed = new URL(withScheme);
4053
+ } catch {
4054
+ throw new CliError(`\u955C\u50CF\u5730\u5740\u65E0\u6548: "${val}"`, {
4055
+ label: "\u53C2\u6570\u9519\u8BEF",
4056
+ hint: ["\u683C\u5F0F\u5982: --mirror https://gh-proxy.org/ \u6216 --mirror gh-proxy.org", "\u4E0D\u4F7F\u7528\u955C\u50CF: --no-mirror"]
4057
+ });
3865
4058
  }
3866
- if (!url.endsWith("/")) {
3867
- url += "/";
4059
+ if (parsed.protocol !== "https:") {
4060
+ throw new CliError(`\u955C\u50CF\u5730\u5740\u5FC5\u987B\u4F7F\u7528 https: "${val}"`, {
4061
+ label: "\u53C2\u6570\u9519\u8BEF",
4062
+ hint: ["\u955C\u50CF\u4F1A\u4E2D\u8F6C\u5185\u6838\u4E8C\u8FDB\u5236\uFF0C\u8BE5\u4EA7\u7269\u968F\u540E\u4EE5 root \u8FD0\u884C\uFF0C\u4E0D\u5141\u8BB8\u660E\u6587\u4F20\u8F93\u3002"]
4063
+ });
3868
4064
  }
3869
- return url;
4065
+ const url = parsed.toString();
4066
+ return url.endsWith("/") ? url : `${url}/`;
3870
4067
  }
3871
4068
  function parseMirrorArg(args) {
3872
4069
  if (!args || args.length < 2) {
@@ -3937,8 +4134,8 @@ function collectOverwriteProxyNames(overwriteFiles) {
3937
4134
  }
3938
4135
  return names;
3939
4136
  }
3940
- function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles) {
3941
- const injectedNames = collectOverwriteProxyNames(overwriteFiles);
4137
+ function excludeOverwriteProxiesFromIncludeAll(config, overwriteFiles, extraNames = []) {
4138
+ const injectedNames = [...collectOverwriteProxyNames(overwriteFiles), ...extraNames];
3942
4139
  if (injectedNames.length === 0) return;
3943
4140
  const groups = config["proxy-groups"];
3944
4141
  if (!groups) return;
@@ -4045,6 +4242,14 @@ function validateConfig(config) {
4045
4242
  warnings.push(`\u79FB\u9664\u4E86 ${groupDedup.duplicates.length} \u4E2A\u91CD\u540D\u5206\u7EC4: ${groupDedup.duplicates.map((n) => `"${n}"`).join(", ")}`);
4046
4243
  }
4047
4244
  const validNames = /* @__PURE__ */ new Set([...BUILTIN_PROXY_NAMES, ...proxyDedup.names, ...groupDedup.names]);
4245
+ for (const name of groupDedup.names) {
4246
+ if (proxyDedup.names.has(name)) {
4247
+ warnings.push(`\u540D\u79F0\u51B2\u7A81: "${name}" \u540C\u65F6\u662F\u8282\u70B9\u548C\u5206\u7EC4\u540D\uFF0Cmihomo \u4F1A\u62D2\u7EDD\u52A0\u8F7D\uFF08\u8BF7\u91CD\u547D\u540D\u5176\u4E00\uFF09`);
4248
+ }
4249
+ }
4250
+ const providerNames = new Set(
4251
+ config["proxy-providers"] && typeof config["proxy-providers"] === "object" && !Array.isArray(config["proxy-providers"]) ? Object.keys(config["proxy-providers"]) : []
4252
+ );
4048
4253
  const activeGroups = groupDedup.result;
4049
4254
  const removedGroups = /* @__PURE__ */ new Set();
4050
4255
  let changed = true;
@@ -4052,12 +4257,32 @@ function validateConfig(config) {
4052
4257
  changed = false;
4053
4258
  for (const group of activeGroups) {
4054
4259
  if (removedGroups.has(group.name)) continue;
4260
+ if (group.proxies !== void 0 && !Array.isArray(group.proxies)) {
4261
+ if (typeof group.proxies === "string") {
4262
+ warnings.push(`proxy-group "${group.name}": proxies \u5E94\u4E3A\u5217\u8868\uFF0C\u5DF2\u6309\u5355\u5143\u7D20\u5904\u7406\uFF08"${group.proxies}"\uFF09`);
4263
+ group.proxies = [group.proxies];
4264
+ } else {
4265
+ warnings.push(`proxy-group "${group.name}": proxies \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\u8BE5\u5B57\u6BB5`);
4266
+ group.proxies = [];
4267
+ }
4268
+ }
4055
4269
  if (!Array.isArray(group.proxies)) continue;
4270
+ if (Array.isArray(group.use)) {
4271
+ const ghosts = group.use.filter((u) => typeof u === "string" && !providerNames.has(u));
4272
+ if (ghosts.length > 0) {
4273
+ group.use = group.use.filter((u) => providerNames.has(u));
4274
+ warnings.push(`proxy-group "${group.name}": \u79FB\u9664\u4E86\u4E0D\u5B58\u5728\u7684 provider \u5F15\u7528 ${ghosts.map((n) => `"${n}"`).join(", ")}`);
4275
+ }
4276
+ }
4056
4277
  const invalid = group.proxies.filter((name) => !validNames.has(name));
4057
- if (invalid.length === 0) continue;
4058
- group.proxies = group.proxies.filter((name) => validNames.has(name));
4059
- warnings.push(`proxy-group "${group.name}": \u79FB\u9664\u4E86\u4E0D\u5B58\u5728\u7684\u5F15\u7528 ${invalid.map((n) => `"${n}"`).join(", ")}`);
4060
- const hasOtherSource = group.use || group["include-all"] || group["include-all-proxies"];
4278
+ if (invalid.length > 0) {
4279
+ group.proxies = group.proxies.filter((name) => validNames.has(name));
4280
+ warnings.push(`proxy-group "${group.name}": \u79FB\u9664\u4E86\u4E0D\u5B58\u5728\u7684\u5F15\u7528 ${invalid.map((n) => `"${n}"`).join(", ")}`);
4281
+ }
4282
+ const hasUse = Array.isArray(group.use) ? group.use.length > 0 : Boolean(group.use);
4283
+ const includesAll = Boolean(group["include-all"] || group["include-all-proxies"]);
4284
+ const includeAllUsable = includesAll && proxyDedup.result.length > 0;
4285
+ const hasOtherSource = hasUse || includeAllUsable;
4061
4286
  if (group.proxies.length === 0 && !hasOtherSource) {
4062
4287
  removedGroups.add(group.name);
4063
4288
  validNames.delete(group.name);
@@ -4094,31 +4319,35 @@ function buildConfig(subRawContent, mode, scope) {
4094
4319
  const allFiles = overwriteEnabled ? loadOverwriteFile() : [];
4095
4320
  const overwriteFiles = filterOverwriteFilesByScope(allFiles, scope);
4096
4321
  const withOverwrites = applyOverwrite(subscriptionConfig, overwriteFiles);
4097
- if (overwriteFiles.length > 0) {
4098
- excludeOverwriteProxiesFromIncludeAll(withOverwrites, overwriteFiles);
4322
+ const sshTunnels = getSshTunnels();
4323
+ const sshFiles = sshTunnels.length > 0 ? loadSshConfigFiles() : [];
4324
+ const withSsh = applySshConfig(withOverwrites, sshFiles, sshTunnels);
4325
+ const sshProxyNames = collectSshProxyNames(sshTunnels);
4326
+ if (overwriteFiles.length > 0 || sshProxyNames.length > 0) {
4327
+ excludeOverwriteProxiesFromIncludeAll(withSsh, overwriteFiles, sshProxyNames);
4099
4328
  }
4100
4329
  const systemConfig = {};
4101
4330
  for (const [key, value] of Object.entries(BASE_CONFIG)) {
4102
- if (!(key in withOverwrites)) {
4331
+ if (!(key in withSsh)) {
4103
4332
  systemConfig[key] = value;
4104
4333
  }
4105
4334
  }
4106
4335
  systemConfig["external-controller"] = BASE_CONFIG["external-controller"];
4107
4336
  systemConfig["mixed-port"] = BASE_CONFIG["mixed-port"];
4108
- delete withOverwrites["mixed-port"];
4109
- delete withOverwrites.port;
4110
- delete withOverwrites["socks-port"];
4111
- delete withOverwrites["external-ui"];
4112
- delete withOverwrites["external-ui-name"];
4113
- delete withOverwrites["external-ui-url"];
4114
- delete withOverwrites.secret;
4337
+ delete withSsh["mixed-port"];
4338
+ delete withSsh.port;
4339
+ delete withSsh["socks-port"];
4340
+ delete withSsh["external-ui"];
4341
+ delete withSsh["external-ui-name"];
4342
+ delete withSsh["external-ui-url"];
4343
+ delete withSsh.secret;
4115
4344
  const controllerSecret = readSettings().controller_secret;
4116
4345
  if (controllerSecret) {
4117
4346
  systemConfig.secret = controllerSecret;
4118
4347
  }
4119
4348
  if (mode === "tun") {
4120
4349
  systemConfig.tun = TUN_CONFIG.tun;
4121
- const subDns = withOverwrites.dns || {};
4350
+ const subDns = withSsh.dns || {};
4122
4351
  const dns = {};
4123
4352
  if (!("enable" in subDns)) dns.enable = true;
4124
4353
  if (!("enhanced-mode" in subDns)) dns["enhanced-mode"] = "fake-ip";
@@ -4127,14 +4356,14 @@ function buildConfig(subRawContent, mode, scope) {
4127
4356
  systemConfig.dns = dns;
4128
4357
  }
4129
4358
  } else {
4130
- delete withOverwrites.tun;
4359
+ delete withSsh.tun;
4131
4360
  }
4132
- const merged = { ...withOverwrites, ...systemConfig };
4361
+ const merged = { ...withSsh, ...systemConfig };
4133
4362
  if (systemConfig.dns) {
4134
- merged.dns = { ...withOverwrites.dns || {}, ...systemConfig.dns };
4363
+ merged.dns = { ...withSsh.dns || {}, ...systemConfig.dns };
4135
4364
  }
4136
4365
  const mergedDns = merged.dns || {};
4137
- if (mergedDns["enhanced-mode"] === "fake-ip" && !("sniffer" in withOverwrites)) {
4366
+ if (mergedDns["enhanced-mode"] === "fake-ip" && !("sniffer" in withSsh)) {
4138
4367
  merged.sniffer = {
4139
4368
  enable: true,
4140
4369
  sniff: {
@@ -4146,7 +4375,7 @@ function buildConfig(subRawContent, mode, scope) {
4146
4375
  };
4147
4376
  }
4148
4377
  const warnings = validateConfig(merged);
4149
- return { config: merged, subscriptionConfig, overwriteFiles, systemConfig, warnings };
4378
+ return { config: merged, subscriptionConfig, overwriteFiles, sshFiles, systemConfig, warnings };
4150
4379
  }
4151
4380
  function writeMihomoConfig(configObj) {
4152
4381
  ensureDirs();
@@ -4155,22 +4384,32 @@ function writeMihomoConfig(configObj) {
4155
4384
  }
4156
4385
  function writeDebugConfig(buildResult) {
4157
4386
  ensureDirs();
4158
- fs4.writeFileSync(PATHS.configStage1Subscription, dumpYaml(buildResult.subscriptionConfig), { mode: 384 });
4387
+ fs5.writeFileSync(PATHS.configStage1Subscription, dumpYaml(buildResult.subscriptionConfig), { mode: 384 });
4159
4388
  const overwriteMerged = {};
4160
4389
  for (const f of buildResult.overwriteFiles) {
4161
4390
  Object.assign(overwriteMerged, f.config);
4162
4391
  }
4163
4392
  const overwriteContent = buildResult.overwriteFiles.length > 0 ? dumpYaml(overwriteMerged) : "# overwrite \u5DF2\u7981\u7528\u6216\u65E0\u8986\u5199\u6587\u4EF6\n";
4164
- fs4.writeFileSync(PATHS.configStage2Overwrite, overwriteContent, { mode: 384 });
4165
- fs4.writeFileSync(PATHS.configStage3System, dumpYaml(buildResult.systemConfig), { mode: 384 });
4393
+ fs5.writeFileSync(PATHS.configStage2Overwrite, overwriteContent, { mode: 384 });
4394
+ fs5.writeFileSync(PATHS.configStage3System, dumpYaml(buildResult.systemConfig), { mode: 384 });
4395
+ const sshMerged = {};
4396
+ for (const f of buildResult.sshFiles) {
4397
+ Object.assign(sshMerged, f.config);
4398
+ }
4399
+ const sshTunnels = getSshTunnels();
4400
+ if (sshTunnels.length > 0) {
4401
+ sshMerged["~proxies"] = sshTunnels.map(renderSshProxy);
4402
+ }
4403
+ const sshContent = Object.keys(sshMerged).length > 0 ? dumpYaml(sshMerged) : "# \u672A\u914D\u7F6E ssh \u96A7\u9053\n";
4404
+ fs5.writeFileSync(PATHS.configStage4Ssh, sshContent, { mode: 384 });
4166
4405
  }
4167
4406
  function hasConfig() {
4168
- return fs4.existsSync(PATHS.configFile);
4407
+ return fs5.existsSync(PATHS.configFile);
4169
4408
  }
4170
4409
  function getConfigInfo() {
4171
4410
  if (!hasConfig()) return null;
4172
4411
  try {
4173
- const content = fs4.readFileSync(PATHS.configFile, "utf8");
4412
+ const content = fs5.readFileSync(PATHS.configFile, "utf8");
4174
4413
  const cfg = loadYamlSafe(content);
4175
4414
  if (!cfg) return null;
4176
4415
  const proxies = cfg.proxies;
@@ -4190,7 +4429,7 @@ function getConfigInfo() {
4190
4429
  }
4191
4430
  }
4192
4431
  function hasKernel() {
4193
- return fs4.existsSync(PATHS.mihomoBinary);
4432
+ return fs5.existsSync(PATHS.mihomoBinary);
4194
4433
  }
4195
4434
  var kernelVersionCache = null;
4196
4435
  var kernelVersionCached = false;
@@ -4266,13 +4505,13 @@ ${colors.cyan(colors.bold(`mihomo-cli v${VERSION}`))}`, "", "\u547D\u4EE4\u522B\
4266
4505
  " mihomo start -s # \u8DF3\u8FC7\u81EA\u52A8\u66F4\u65B0\u8BA2\u9605",
4267
4506
  " mihomo start -u 30000 # \u81EA\u52A8\u66F4\u65B0\u8D85\u65F6 30 \u79D2 (\u9ED8\u8BA4 10s)",
4268
4507
  " mihomo daemon on # \u5F00\u542F\u4FDD\u6D3B\uFF08\u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F\uFF09",
4269
- " mihomo tunnel add work --host m4 --port 1080 # \u52A0 ssh \u96A7\u9053\u51FA\u53E3",
4508
+ " mihomo ssh add work --host m4 --port 1080 # \u52A0 ssh \u96A7\u9053\u51FA\u53E3",
4270
4509
  " mihomo sub add <url> # \u6DFB\u52A0\u8BA2\u9605 (sub \u662F subscription \u522B\u540D)",
4271
4510
  " mihomo ui # \u6253\u5F00 Web UI",
4272
4511
  "",
4273
4512
  `${colors.cyan("\u5FEB\u6377\u547D\u4EE4:")}`,
4274
4513
  " tun = start tun use = sub use on/off = ow on/off open = dir open",
4275
- " up = start down = stop upd/upgrade = update ssh = tunnel",
4514
+ " up = start down = stop upd/upgrade = update",
4276
4515
  "",
4277
4516
  `${colors.cyan("\u6A21\u5F0F\u8BF4\u660E:")}`,
4278
4517
  " mixed HTTP + SOCKS5 \u6DF7\u5408\u7AEF\u53E3 (\u9ED8\u8BA4)",
@@ -4298,13 +4537,13 @@ function printVersion() {
4298
4537
 
4299
4538
  // src/daemon.ts
4300
4539
  import { spawnSync as spawnSync3 } from "child_process";
4301
- import fs6 from "fs";
4302
- import path5 from "path";
4540
+ import fs7 from "fs";
4541
+ import path6 from "path";
4303
4542
 
4304
4543
  // src/process.ts
4305
4544
  import { spawn, spawnSync as spawnSync2 } from "child_process";
4306
- import fs5 from "fs";
4307
- import path4 from "path";
4545
+ import fs6 from "fs";
4546
+ import path5 from "path";
4308
4547
 
4309
4548
  // src/lifecycle.ts
4310
4549
  var cleanupFns = /* @__PURE__ */ new Set();
@@ -4369,15 +4608,15 @@ function isProcessRoot(pid) {
4369
4608
  }
4370
4609
  var MAIN_INSTANCE_PATTERN = `${escapeRegExp(PATHS.mihomoBinary)}.*${escapeRegExp(PATHS.configFile)}`;
4371
4610
  function clearRuntime() {
4372
- if (fs5.existsSync(DIRS.runtime)) {
4611
+ if (fs6.existsSync(DIRS.runtime)) {
4373
4612
  rmrf(DIRS.runtime);
4374
4613
  }
4375
4614
  ensureDirs();
4376
4615
  }
4377
4616
  function getPid() {
4378
- if (!fs5.existsSync(PATHS.pidFile)) return null;
4617
+ if (!fs6.existsSync(PATHS.pidFile)) return null;
4379
4618
  try {
4380
- const pid = parseInt(fs5.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
4619
+ const pid = parseInt(fs6.readFileSync(PATHS.pidFile, "utf8").trim(), 10);
4381
4620
  return pid > 0 ? pid : null;
4382
4621
  } catch {
4383
4622
  return null;
@@ -4399,9 +4638,9 @@ function getMihomoPids() {
4399
4638
  }
4400
4639
  }
4401
4640
  function isPidFileOwnedByRoot() {
4402
- if (!fs5.existsSync(PATHS.pidFile)) return false;
4641
+ if (!fs6.existsSync(PATHS.pidFile)) return false;
4403
4642
  try {
4404
- const stat = fs5.statSync(PATHS.pidFile);
4643
+ const stat = fs6.statSync(PATHS.pidFile);
4405
4644
  return stat.uid === 0;
4406
4645
  } catch {
4407
4646
  return false;
@@ -4424,10 +4663,10 @@ function hasRootResidue() {
4424
4663
  }
4425
4664
  function savePid(pid) {
4426
4665
  ensureDirs();
4427
- fs5.writeFileSync(PATHS.pidFile, pid.toString(), { mode: 384 });
4666
+ fs6.writeFileSync(PATHS.pidFile, pid.toString(), { mode: 384 });
4428
4667
  }
4429
4668
  function clearPid() {
4430
- if (!fs5.existsSync(PATHS.pidFile)) return;
4669
+ if (!fs6.existsSync(PATHS.pidFile)) return;
4431
4670
  if (isPidFileOwnedByRoot()) {
4432
4671
  try {
4433
4672
  spawnSync2("sudo", ["rm", "-f", PATHS.pidFile], { stdio: "inherit", timeout: 1e4 });
@@ -4435,7 +4674,7 @@ function clearPid() {
4435
4674
  }
4436
4675
  } else {
4437
4676
  try {
4438
- fs5.unlinkSync(PATHS.pidFile);
4677
+ fs6.unlinkSync(PATHS.pidFile);
4439
4678
  } catch {
4440
4679
  }
4441
4680
  }
@@ -4549,8 +4788,9 @@ echo "--- \u65E5\u5FD7 ---"
4549
4788
  tail -25 "\${LOG_FILE}" 2>/dev/null
4550
4789
  exit 2
4551
4790
  `;
4552
- const scriptPath = path4.join(DIRS.runtime, "launch-tun.sh");
4553
- fs5.writeFileSync(scriptPath, scriptContent, { mode: 448 });
4791
+ const scriptPath = path5.join(DIRS.runtime, "launch-tun.sh");
4792
+ fs6.writeFileSync(scriptPath, scriptContent, { mode: 448 });
4793
+ fs6.chmodSync(scriptPath, 448);
4554
4794
  return scriptPath;
4555
4795
  }
4556
4796
  function getProcessInfo(pid) {
@@ -4588,11 +4828,11 @@ async function start(mode = "mixed") {
4588
4828
  ensureDirs();
4589
4829
  rotateAndCleanupLogs();
4590
4830
  const binary = PATHS.mihomoBinary;
4591
- if (!fs5.existsSync(binary)) {
4831
+ if (!fs6.existsSync(binary)) {
4592
4832
  throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
4593
4833
  }
4594
4834
  const configFile = PATHS.configFile;
4595
- if (!fs5.existsSync(configFile)) {
4835
+ if (!fs6.existsSync(configFile)) {
4596
4836
  throw new CliError("\u672A\u627E\u5230\u914D\u7F6E\u6587\u4EF6\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605\u5E76\u542F\u52A8");
4597
4837
  }
4598
4838
  const staleState = checkStaleState();
@@ -4621,24 +4861,24 @@ async function startMixedMode(staleState) {
4621
4861
  const configFile = PATHS.configFile;
4622
4862
  const logFile = PATHS.logFile;
4623
4863
  const args = ["-d", DIRS.data, "-f", configFile];
4624
- if (fs5.existsSync(logFile)) {
4864
+ if (fs6.existsSync(logFile)) {
4625
4865
  try {
4626
- fs5.accessSync(logFile, fs5.constants.W_OK);
4866
+ fs6.accessSync(logFile, fs6.constants.W_OK);
4627
4867
  } catch {
4628
4868
  try {
4629
- fs5.unlinkSync(logFile);
4869
+ fs6.unlinkSync(logFile);
4630
4870
  } catch {
4631
4871
  }
4632
4872
  }
4633
4873
  }
4634
- const logFd = fs5.openSync(logFile, "a");
4874
+ const logFd = fs6.openSync(logFile, "a");
4635
4875
  const child = spawn(PATHS.mihomoBinary, args, {
4636
4876
  detached: true,
4637
4877
  stdio: ["ignore", logFd, logFd]
4638
4878
  });
4639
4879
  child.on("error", () => {
4640
4880
  });
4641
- fs5.closeSync(logFd);
4881
+ fs6.closeSync(logFd);
4642
4882
  child.unref();
4643
4883
  const pid = child.pid;
4644
4884
  if (!pid) {
@@ -4650,9 +4890,9 @@ async function startMixedMode(staleState) {
4650
4890
  if (!isRunning()) {
4651
4891
  clearPid();
4652
4892
  let errorMsg = "\u542F\u52A8\u5931\u8D25";
4653
- if (fs5.existsSync(logFile)) {
4893
+ if (fs6.existsSync(logFile)) {
4654
4894
  try {
4655
- const logs = fs5.readFileSync(logFile, "utf8").slice(-3e3);
4895
+ const logs = fs6.readFileSync(logFile, "utf8").slice(-3e3);
4656
4896
  if (logs.trim()) {
4657
4897
  errorMsg += "\n\u6700\u8FD1\u7684\u65E5\u5FD7:\n" + logs.split("\n").map((l) => ` ${l}`).join("\n");
4658
4898
  }
@@ -4679,7 +4919,7 @@ async function startTunMode(staleState) {
4679
4919
  }
4680
4920
  } catch (e) {
4681
4921
  try {
4682
- fs5.unlinkSync(launchScript);
4922
+ fs6.unlinkSync(launchScript);
4683
4923
  } catch {
4684
4924
  }
4685
4925
  if (e.status === 1) {
@@ -4691,7 +4931,7 @@ async function startTunMode(staleState) {
4691
4931
  throw new Error(e.message);
4692
4932
  }
4693
4933
  try {
4694
- fs5.unlinkSync(launchScript);
4934
+ fs6.unlinkSync(launchScript);
4695
4935
  } catch {
4696
4936
  }
4697
4937
  await new Promise((resolve) => setTimeout(resolve, TUN_MODE_POST_WAIT_MS));
@@ -4730,18 +4970,18 @@ function getLogPath() {
4730
4970
  }
4731
4971
  function rotateLog() {
4732
4972
  const logFile = PATHS.logFile;
4733
- if (!fs5.existsSync(logFile)) return null;
4734
- const stat = fs5.statSync(logFile);
4973
+ if (!fs6.existsSync(logFile)) return null;
4974
+ const stat = fs6.statSync(logFile);
4735
4975
  if (stat.size === 0) return null;
4736
4976
  const rotatedName = `mihomo.${formatLocalTimestamp()}.log`;
4737
- const rotatedPath = path4.join(DIRS.logs, rotatedName);
4738
- fs5.renameSync(logFile, rotatedPath);
4977
+ const rotatedPath = path5.join(DIRS.logs, rotatedName);
4978
+ fs6.renameSync(logFile, rotatedPath);
4739
4979
  return rotatedPath;
4740
4980
  }
4741
4981
  function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
4742
4982
  const logsDir = DIRS.logs;
4743
- if (!fs5.existsSync(logsDir)) return { deleted: 0, errors: 0 };
4744
- const files = fs5.readdirSync(logsDir);
4983
+ if (!fs6.existsSync(logsDir)) return { deleted: 0, errors: 0 };
4984
+ const files = fs6.readdirSync(logsDir);
4745
4985
  const now = Date.now();
4746
4986
  const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
4747
4987
  let deleted = 0;
@@ -4749,10 +4989,10 @@ function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
4749
4989
  for (const file of files) {
4750
4990
  if (!file.match(/^mihomo\.\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.log$/)) continue;
4751
4991
  try {
4752
- const filePath = path4.join(logsDir, file);
4753
- const stat = fs5.statSync(filePath);
4992
+ const filePath = path5.join(logsDir, file);
4993
+ const stat = fs6.statSync(filePath);
4754
4994
  if (now - stat.mtimeMs > maxAgeMs) {
4755
- fs5.unlinkSync(filePath);
4995
+ fs6.unlinkSync(filePath);
4756
4996
  deleted++;
4757
4997
  }
4758
4998
  } catch {
@@ -4764,8 +5004,8 @@ function cleanupOldLogs(maxAgeDays = DEFAULT_LOG_RETENTION_DAYS) {
4764
5004
  function listLogs() {
4765
5005
  const logsDir = DIRS.logs;
4766
5006
  const result = { current: null, archives: [] };
4767
- if (fs5.existsSync(PATHS.logFile)) {
4768
- const stat = fs5.statSync(PATHS.logFile);
5007
+ if (fs6.existsSync(PATHS.logFile)) {
5008
+ const stat = fs6.statSync(PATHS.logFile);
4769
5009
  result.current = {
4770
5010
  name: "mihomo.log (\u5F53\u524D)",
4771
5011
  path: PATHS.logFile,
@@ -4774,14 +5014,14 @@ function listLogs() {
4774
5014
  isCurrent: true
4775
5015
  };
4776
5016
  }
4777
- if (!fs5.existsSync(logsDir)) return result;
4778
- const files = fs5.readdirSync(logsDir);
5017
+ if (!fs6.existsSync(logsDir)) return result;
5018
+ const files = fs6.readdirSync(logsDir);
4779
5019
  for (const file of files) {
4780
5020
  const match = file.match(/^mihomo\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})\.log$/);
4781
5021
  if (!match) continue;
4782
5022
  try {
4783
- const filePath = path4.join(logsDir, file);
4784
- const stat = fs5.statSync(filePath);
5023
+ const filePath = path5.join(logsDir, file);
5024
+ const stat = fs6.statSync(filePath);
4785
5025
  result.archives.push({
4786
5026
  name: file,
4787
5027
  path: filePath,
@@ -4796,22 +5036,22 @@ function listLogs() {
4796
5036
  return result;
4797
5037
  }
4798
5038
  function isPathUnderDir(filePath, baseDir) {
4799
- const resolvedPath = path4.resolve(filePath);
4800
- const resolvedBase = path4.resolve(baseDir);
4801
- return resolvedPath === resolvedBase || resolvedPath.startsWith(resolvedBase + path4.sep);
5039
+ const resolvedPath = path5.resolve(filePath);
5040
+ const resolvedBase = path5.resolve(baseDir);
5041
+ return resolvedPath === resolvedBase || resolvedPath.startsWith(resolvedBase + path5.sep);
4802
5042
  }
4803
5043
  function getLogPathByName(name) {
4804
5044
  const logsDir = DIRS.logs;
4805
5045
  let targetName = name;
4806
5046
  if (!name.endsWith(".log")) targetName = `mihomo.${name}.log`;
4807
5047
  if (!targetName.startsWith("mihomo.")) targetName = `mihomo.${targetName}`;
4808
- const filePath = path4.join(logsDir, targetName);
4809
- if (fs5.existsSync(filePath) && isPathUnderDir(filePath, logsDir)) return filePath;
4810
- if (fs5.existsSync(logsDir)) {
4811
- const files = fs5.readdirSync(logsDir);
5048
+ const filePath = path5.join(logsDir, targetName);
5049
+ if (fs6.existsSync(filePath) && isPathUnderDir(filePath, logsDir)) return filePath;
5050
+ if (fs6.existsSync(logsDir)) {
5051
+ const files = fs6.readdirSync(logsDir);
4812
5052
  for (const file of files) {
4813
5053
  if (file.includes(name)) {
4814
- const candidatePath = path4.join(logsDir, file);
5054
+ const candidatePath = path5.join(logsDir, file);
4815
5055
  if (isPathUnderDir(candidatePath, logsDir)) return candidatePath;
4816
5056
  }
4817
5057
  }
@@ -4878,7 +5118,7 @@ var DAEMON_BOOT_WAIT_MS = 500;
4878
5118
  var LOG_ROTATE_MAX_BYTES = 10 * 1024 * 1024;
4879
5119
  function logOversized() {
4880
5120
  try {
4881
- return fs6.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
5121
+ return fs7.statSync(PATHS.logFile).size > LOG_ROTATE_MAX_BYTES;
4882
5122
  } catch {
4883
5123
  return false;
4884
5124
  }
@@ -4918,8 +5158,9 @@ function runSudoScript(scriptBody, opts) {
4918
5158
  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");
4919
5159
  }
4920
5160
  ensureDirs();
4921
- const scriptPath = path5.join(DIRS.runtime, opts.file);
4922
- fs6.writeFileSync(scriptPath, scriptBody, { mode: 448 });
5161
+ const scriptPath = path6.join(DIRS.runtime, opts.file);
5162
+ fs7.writeFileSync(scriptPath, scriptBody, { mode: 448 });
5163
+ fs7.chmodSync(scriptPath, 448);
4923
5164
  try {
4924
5165
  const result = spawnSync3("sudo", [scriptPath], { stdio: "inherit", timeout: SUDO_TIMEOUT_MS });
4925
5166
  if (result.error) throw result.error;
@@ -4935,13 +5176,13 @@ function runSudoScript(scriptBody, opts) {
4935
5176
  }
4936
5177
  } finally {
4937
5178
  try {
4938
- fs6.unlinkSync(scriptPath);
5179
+ fs7.unlinkSync(scriptPath);
4939
5180
  } catch {
4940
5181
  }
4941
5182
  }
4942
5183
  }
4943
5184
  function isDaemonEnabled() {
4944
- return fs6.existsSync(PATHS.launchDaemonPlist);
5185
+ return fs7.existsSync(PATHS.launchDaemonPlist);
4945
5186
  }
4946
5187
  function getDaemonStatus() {
4947
5188
  if (!isDaemonEnabled()) {
@@ -4955,23 +5196,28 @@ function isDaemonRunning(status) {
4955
5196
  }
4956
5197
  function enableDaemon() {
4957
5198
  assertDaemonLabelSafe();
4958
- if (!fs6.existsSync(PATHS.mihomoBinary)) {
5199
+ if (!fs7.existsSync(PATHS.mihomoBinary)) {
4959
5200
  throw new CliError("\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u4E0B\u8F7D\u5185\u6838");
4960
5201
  }
4961
- if (!fs6.existsSync(PATHS.configFile)) {
5202
+ if (!fs7.existsSync(PATHS.configFile)) {
4962
5203
  throw new CliError("\u672A\u627E\u5230\u8FD0\u884C\u65F6\u914D\u7F6E\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
4963
5204
  }
4964
5205
  ensureDirs();
4965
- const stagePath = path5.join(DIRS.runtime, "daemon.plist.stage");
5206
+ const stagePath = path6.join(DIRS.runtime, "daemon.plist.stage");
4966
5207
  atomicWriteFileSync(stagePath, buildPlist(), { mode: 384 });
4967
5208
  const target = shellQuote(SERVICE_TARGET);
4968
5209
  const plistDest = shellQuote(PATHS.launchDaemonPlist);
4969
5210
  const stage = shellQuote(stagePath);
4970
5211
  const pattern = shellQuote(MAIN_INSTANCE_PATTERN);
5212
+ const pidFile = shellQuote(PATHS.pidFile);
4971
5213
  const script = [
4972
5214
  "#!/bin/bash",
4973
5215
  `launchctl bootout ${target} 2>/dev/null || true`,
4974
5216
  `pkill -9 -f ${pattern} 2>/dev/null || true`,
5217
+ // 一并清掉 pid 文件:`start tun` 留下的是 **root 属主**的 pid 文件,普通用户删不掉。
5218
+ // 不删会让后续 `daemon off` → `start` 撞上 hasRootResidue() 的拒绝启动,
5219
+ // 而这个死胡同完全由 CLI 自身的 on/off 循环造成
5220
+ `rm -f ${pidFile}`,
4975
5221
  "sleep 0.2",
4976
5222
  `install -m 644 -o root -g wheel ${stage} ${plistDest} || exit 2`,
4977
5223
  `launchctl bootstrap system ${plistDest} || { launchctl bootout ${target} 2>/dev/null; rm -f ${plistDest}; exit 3; }`,
@@ -4989,14 +5235,20 @@ function enableDaemon() {
4989
5235
  });
4990
5236
  } finally {
4991
5237
  try {
4992
- fs6.unlinkSync(stagePath);
5238
+ fs7.unlinkSync(stagePath);
4993
5239
  } catch {
4994
5240
  }
4995
5241
  }
4996
5242
  }
4997
5243
  function disableDaemon() {
4998
5244
  assertDaemonLabelSafe();
4999
- if (!isDaemonEnabled()) return;
5245
+ const plistExists = isDaemonEnabled();
5246
+ const rootKernelRunning = getMihomoPids().some(isProcessRoot);
5247
+ if (!plistExists && !rootKernelRunning) return;
5248
+ if (!plistExists) {
5249
+ console.log("\u672A\u627E\u5230 plist\uFF0C\u4F46\u68C0\u6D4B\u5230 root \u5185\u6838\u5728\u8FD0\u884C\uFF08\u53EF\u80FD plist \u88AB\u624B\u52A8\u5220\u9664\u800C\u4EFB\u52A1\u4ECD\u88C5\u8F7D\uFF09");
5250
+ console.log("\u5C06\u6267\u884C launchctl bootout \u5378\u8F7D\u6B8B\u7559\u4EFB\u52A1");
5251
+ }
5000
5252
  const target = shellQuote(SERVICE_TARGET);
5001
5253
  const plistDest = shellQuote(PATHS.launchDaemonPlist);
5002
5254
  const logFile = shellQuote(PATHS.logFile);
@@ -5019,12 +5271,17 @@ function disableDaemon() {
5019
5271
  }
5020
5272
  }
5021
5273
  async function tryHotReload() {
5274
+ if (!isDaemonRunning(getDaemonStatus())) return false;
5022
5275
  const controller = new AbortController();
5023
5276
  const timer = setTimeout(() => controller.abort(), HOT_RELOAD_TIMEOUT_MS);
5024
5277
  const secret = readSettings().controller_secret;
5025
5278
  const headers = { "Content-Type": "application/json" };
5026
5279
  if (secret) headers.Authorization = `Bearer ${secret}`;
5027
5280
  try {
5281
+ const probe = await fetch(`${CONTROLLER_BASE_URL}/version`, { headers, signal: controller.signal });
5282
+ if (!probe.ok) return false;
5283
+ const info = await probe.json();
5284
+ if (typeof info?.version !== "string") return false;
5028
5285
  const res = await fetch(`${CONTROLLER_BASE_URL}/configs?force=true`, {
5029
5286
  method: "PUT",
5030
5287
  headers,
@@ -5039,14 +5296,14 @@ async function tryHotReload() {
5039
5296
  }
5040
5297
  }
5041
5298
  async function restartDaemon() {
5042
- if (!fs6.existsSync(PATHS.launchDaemonPlist)) {
5299
+ if (!fs7.existsSync(PATHS.launchDaemonPlist)) {
5043
5300
  throw new CliError("\u4FDD\u6D3B\u672A\u542F\u7528\uFF0C\u65E0\u6CD5\u91CD\u542F", { hint: "\u542F\u7528\u4FDD\u6D3B: mihomo daemon on" });
5044
5301
  }
5045
5302
  if (!logOversized() && await tryHotReload()) return;
5046
5303
  const target = shellQuote(SERVICE_TARGET);
5047
5304
  const plistDest = shellQuote(PATHS.launchDaemonPlist);
5048
5305
  const logFile = shellQuote(PATHS.logFile);
5049
- const archiveFile = shellQuote(path5.join(DIRS.logs, `mihomo.${formatLocalTimestamp()}.log`));
5306
+ const archiveFile = shellQuote(path6.join(DIRS.logs, `mihomo.${formatLocalTimestamp()}.log`));
5050
5307
  const script = [
5051
5308
  "#!/bin/bash",
5052
5309
  `if [ -f ${logFile} ] && [ "$(stat -f%z ${logFile} 2>/dev/null || echo 0)" -gt ${LOG_ROTATE_MAX_BYTES} ]; then`,
@@ -5181,15 +5438,18 @@ function saveSubscriptionConfig(subName, parsed) {
5181
5438
  function parseUserInfo(header) {
5182
5439
  if (!header) return null;
5183
5440
  const info = {};
5184
- const parts = header.split(";").map((p) => p.trim());
5185
- for (const part of parts) {
5186
- const [key, val] = part.split("=").map((s) => s.trim());
5187
- if (key && val !== void 0) {
5188
- const numVal = parseFloat(val);
5189
- info[key] = Number.isNaN(numVal) ? 0 : numVal;
5190
- }
5191
- }
5192
- return info;
5441
+ let hasAny = false;
5442
+ for (const part of header.split(";")) {
5443
+ const [rawKey, rawVal] = part.split("=");
5444
+ const key = rawKey?.trim();
5445
+ const val = rawVal?.trim();
5446
+ if (!key || val === void 0 || val === "") continue;
5447
+ const numVal = Number(val);
5448
+ if (!Number.isFinite(numVal) || numVal < 0) continue;
5449
+ info[key] = numVal;
5450
+ hasAny = true;
5451
+ }
5452
+ return hasAny ? info : null;
5193
5453
  }
5194
5454
  function parsePositiveInterval(header) {
5195
5455
  if (!header) return null;
@@ -5215,10 +5475,11 @@ function extractSubscriptionMeta(headers) {
5215
5475
  function saveSubscriptionMeta(subName, meta) {
5216
5476
  const cacheData = { updated_at: (/* @__PURE__ */ new Date()).toISOString() };
5217
5477
  if (meta.userInfo) {
5218
- cacheData.upload = meta.userInfo.upload;
5219
- cacheData.download = meta.userInfo.download;
5220
- cacheData.total = meta.userInfo.total;
5221
- cacheData.expire = meta.userInfo.expire;
5478
+ const { upload, download, total, expire } = meta.userInfo;
5479
+ if (upload !== void 0) cacheData.upload = upload;
5480
+ if (download !== void 0) cacheData.download = download;
5481
+ if (total !== void 0) cacheData.total = total;
5482
+ if (expire !== void 0) cacheData.expire = expire;
5222
5483
  }
5223
5484
  if (meta.updateInterval) cacheData.update_interval = meta.updateInterval;
5224
5485
  if (meta.webPageUrl) cacheData.web_page_url = meta.webPageUrl;
@@ -5422,6 +5683,7 @@ function needsAutoUpdate(sub) {
5422
5683
  if (!sub.updated_at) return true;
5423
5684
  const lastUpdate = new Date(sub.updated_at).getTime();
5424
5685
  if (Number.isNaN(lastUpdate)) return true;
5686
+ if (lastUpdate > Date.now()) return true;
5425
5687
  const intervalHours = resolveUpdateInterval(sub.url, sub.update_interval);
5426
5688
  const intervalMs = intervalHours * 60 * 60 * 1e3;
5427
5689
  return Date.now() - lastUpdate > intervalMs;
@@ -5769,11 +6031,11 @@ function formatTestSummary(summary) {
5769
6031
  return `\u7ED3\u679C: ${colors.green(`${summary.alive} \u5B58\u6D3B`)} / ${colors.red(`${summary.dead} \u5931\u8D25`)} / ${summary.total} \u603B\u8BA1`;
5770
6032
  }
5771
6033
 
5772
- // src/tunnel.ts
6034
+ // src/ssh.ts
5773
6035
  import { spawn as spawn2 } from "child_process";
5774
- import fs7 from "fs";
6036
+ import fs8 from "fs";
5775
6037
  import net from "net";
5776
- import path6 from "path";
6038
+ import path7 from "path";
5777
6039
  var PORT_PROBE_TIMEOUT_MS = 300;
5778
6040
  var STOP_WAIT_ATTEMPTS = 20;
5779
6041
  var STOP_WAIT_INTERVAL = 100;
@@ -5790,15 +6052,10 @@ function getReservedPorts() {
5790
6052
  if (Number.isInteger(testController)) reserved.set(testController, "\u6D4B\u901F\u5B9E\u4F8B\u63A7\u5236\u5668\u7AEF\u53E3");
5791
6053
  return reserved;
5792
6054
  }
5793
- function validateTunnelName(name) {
5794
- if (!name || !SAFE_NAME_RE.test(name)) {
5795
- throw new CliError(`\u96A7\u9053\u540D\u79F0\u65E0\u6548: "${name}"\uFF0C\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\u548C\u4E2D\u6587\uFF08\u6700\u957F 64 \u5B57\u7B26\uFF09`);
5796
- }
5797
- }
5798
6055
  var SAFE_HOST_RE = /^[A-Za-z0-9][A-Za-z0-9._@-]*$/;
5799
- function validateTunnelHost(host) {
6056
+ function validateSshHost(host) {
5800
6057
  if (!host) {
5801
- throw new CliError("\u7F3A\u5C11 --host", { hint: ["\u4F8B\u5982: mihomo tunnel add work --host m4 --port 1080"] });
6058
+ throw new CliError("\u7F3A\u5C11 --host", { hint: ["\u4F8B\u5982: mihomo ssh add work --host m4 --port 1080"] });
5802
6059
  }
5803
6060
  if (host.startsWith("-")) {
5804
6061
  throw new CliError(`\u4E3B\u673A\u540D\u65E0\u6548: "${host}"`, {
@@ -5813,7 +6070,7 @@ function validateTunnelHost(host) {
5813
6070
  });
5814
6071
  }
5815
6072
  }
5816
- function validateTunnelPort(port, exclude) {
6073
+ function validateSshPort(port, exclude) {
5817
6074
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
5818
6075
  throw new CliError(`\u7AEF\u53E3\u65E0\u6548: ${port}\uFF0C\u9700\u4E3A 1-65535 \u7684\u6574\u6570`);
5819
6076
  }
@@ -5824,52 +6081,53 @@ function validateTunnelPort(port, exclude) {
5824
6081
  hint: ["\u8BF7\u6362\u4E00\u4E2A\u7AEF\u53E3\uFF0C\u4F8B\u5982 1080\u3002"]
5825
6082
  });
5826
6083
  }
5827
- const conflict = getTunnels().find((t) => t.port === port && t.name !== exclude);
6084
+ const conflict = getSshTunnels().find((t) => t.port === port && t.name !== exclude);
5828
6085
  if (conflict) {
5829
6086
  throw new CliError(`\u7AEF\u53E3 ${port} \u5DF2\u88AB\u96A7\u9053 "${conflict.name}" \u4F7F\u7528`, { label: "\u7AEF\u53E3\u51B2\u7A81" });
5830
6087
  }
5831
6088
  }
5832
- function getTunnels() {
5833
- const settings = readSettings();
5834
- const tunnels = settings.tunnels;
5835
- if (!Array.isArray(tunnels)) {
5836
- if (tunnels !== void 0) {
5837
- console.warn("\u8B66\u544A: settings.json \u7684 tunnels \u4E0D\u662F\u5217\u8868\uFF0C\u5DF2\u5FFD\u7565\uFF08\u53EF\u7528 mihomo tunnel add \u91CD\u65B0\u6DFB\u52A0\uFF09");
5838
- }
5839
- return [];
5840
- }
5841
- return tunnels.filter((t) => t != null && typeof t === "object" && typeof t.name === "string" && typeof t.host === "string" && Number.isInteger(t.port));
5842
- }
5843
- function findTunnel(name) {
5844
- return getTunnels().find((t) => t.name === name);
6089
+ function findSshTunnel(name) {
6090
+ return getSshTunnels().find((t) => t.name === name);
5845
6091
  }
5846
- function addTunnel(config) {
5847
- validateTunnelName(config.name);
5848
- validateTunnelHost(config.host);
5849
- validateTunnelPort(config.port);
5850
- const tunnels = [...getTunnels()];
5851
- if (tunnels.some((t) => t.name === config.name)) {
5852
- throw new CliError(`\u96A7\u9053 "${config.name}" \u5DF2\u5B58\u5728\uFF0C\u8BF7\u6362\u4E2A\u540D\u79F0\uFF0C\u6216\u5148\u5220\u9664\uFF08mihomo tunnel rm ${config.name}\uFF09`);
5853
- }
5854
- tunnels.push(config);
5855
- writeSettings({ tunnels });
5856
- }
5857
- function removeTunnel(name) {
5858
- const tunnels = [...getTunnels()];
5859
- const idx = tunnels.findIndex((t) => t.name === name);
5860
- if (idx < 0) return false;
5861
- tunnels.splice(idx, 1);
5862
- writeSettings({ tunnels });
5863
- clearTunnelRuntime(name);
6092
+ function addSshTunnel(config) {
6093
+ validateSshName(config.name);
6094
+ validateSshHost(config.host);
6095
+ validateSshPort(config.port);
6096
+ let duplicate = false;
6097
+ updateSettings(() => {
6098
+ const tunnels = [...getSshTunnels()];
6099
+ if (tunnels.some((t) => t.name === config.name)) {
6100
+ duplicate = true;
6101
+ return {};
6102
+ }
6103
+ tunnels.push(config);
6104
+ return { ssh: tunnels };
6105
+ });
6106
+ if (duplicate) {
6107
+ throw new CliError(`\u96A7\u9053 "${config.name}" \u5DF2\u5B58\u5728\uFF0C\u8BF7\u6362\u4E2A\u540D\u79F0\uFF0C\u6216\u5148\u5220\u9664\uFF08mihomo ssh rm ${config.name}\uFF09`);
6108
+ }
6109
+ }
6110
+ function removeSshTunnel(name) {
6111
+ let found = false;
6112
+ updateSettings(() => {
6113
+ const tunnels = [...getSshTunnels()];
6114
+ const idx = tunnels.findIndex((t) => t.name === name);
6115
+ if (idx < 0) return {};
6116
+ found = true;
6117
+ tunnels.splice(idx, 1);
6118
+ return { ssh: tunnels };
6119
+ });
6120
+ if (!found) return false;
6121
+ clearSshRuntime(name);
5864
6122
  return true;
5865
6123
  }
5866
- function getTunnelRuntimePath(name) {
5867
- validateTunnelName(name);
5868
- return path6.join(DIRS.tunnel, `${name}.json`);
6124
+ function getSshRuntimePath(name) {
6125
+ validateSshName(name);
6126
+ return path7.join(DIRS.ssh, `${name}.json`);
5869
6127
  }
5870
- function readTunnelRuntime(name) {
6128
+ function readSshRuntime(name) {
5871
6129
  try {
5872
- const raw = fs7.readFileSync(getTunnelRuntimePath(name), "utf8");
6130
+ const raw = fs8.readFileSync(getSshRuntimePath(name), "utf8");
5873
6131
  const parsed = JSON.parse(raw);
5874
6132
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
5875
6133
  const r = parsed;
@@ -5884,13 +6142,13 @@ function readTunnelRuntime(name) {
5884
6142
  return null;
5885
6143
  }
5886
6144
  }
5887
- function writeTunnelRuntime(name, runtime) {
6145
+ function writeSshRuntime(name, runtime) {
5888
6146
  ensureDirs();
5889
- atomicWriteFileSync(getTunnelRuntimePath(name), JSON.stringify(runtime, null, 2), { mode: 384 });
6147
+ atomicWriteFileSync(getSshRuntimePath(name), JSON.stringify(runtime, null, 2), { mode: 384 });
5890
6148
  }
5891
- function clearTunnelRuntime(name) {
6149
+ function clearSshRuntime(name) {
5892
6150
  try {
5893
- fs7.rmSync(getTunnelRuntimePath(name), { force: true });
6151
+ fs8.rmSync(getSshRuntimePath(name), { force: true });
5894
6152
  } catch {
5895
6153
  }
5896
6154
  }
@@ -5915,11 +6173,11 @@ function buildSshArgs(tunnel) {
5915
6173
  function commandNeedle(port) {
5916
6174
  return `-D 127.0.0.1:${port}`;
5917
6175
  }
5918
- function getTunnelLogPath(name) {
5919
- validateTunnelName(name);
5920
- return path6.join(DIRS.logs, `tunnel-${name}.log`);
6176
+ function getSshLogPath(name) {
6177
+ validateSshName(name);
6178
+ return path7.join(DIRS.logs, `ssh-${name}.log`);
5921
6179
  }
5922
- function isTunnelProcessAlive(pid, port) {
6180
+ function isSshProcessAlive(pid, port) {
5923
6181
  return isProcessRunning(pid) && isProcessCommandMatching(pid, commandNeedle(port));
5924
6182
  }
5925
6183
  function isPortListening(port, timeoutMs = PORT_PROBE_TIMEOUT_MS) {
@@ -5939,9 +6197,9 @@ function isPortListening(port, timeoutMs = PORT_PROBE_TIMEOUT_MS) {
5939
6197
  socket.connect(port, "127.0.0.1");
5940
6198
  });
5941
6199
  }
5942
- async function getTunnelStatus(config) {
5943
- const runtime = readTunnelRuntime(config.name);
5944
- const alive = runtime !== null && isTunnelProcessAlive(runtime.pid, runtime.port || config.port);
6200
+ async function getSshStatus(config) {
6201
+ const runtime = readSshRuntime(config.name);
6202
+ const alive = runtime !== null && isSshProcessAlive(runtime.pid, runtime.port || config.port);
5945
6203
  if (!alive) {
5946
6204
  return { config, state: "stopped", pid: null, started_by: null, started_at: null };
5947
6205
  }
@@ -5954,22 +6212,22 @@ async function getTunnelStatus(config) {
5954
6212
  started_at: runtime.started_at || null
5955
6213
  };
5956
6214
  }
5957
- async function getAllTunnelStatus() {
5958
- return Promise.all(getTunnels().map(getTunnelStatus));
6215
+ async function getAllSshStatus() {
6216
+ return Promise.all(getSshTunnels().map(getSshStatus));
5959
6217
  }
5960
- async function startTunnel(name, options) {
5961
- const config = findTunnel(name);
6218
+ async function startSshTunnel(name, options) {
6219
+ const config = findSshTunnel(name);
5962
6220
  if (!config) {
5963
- throw new CliError(`\u672A\u627E\u5230\u96A7\u9053 "${name}"`, { hint: ["\u67E5\u770B\u5168\u90E8\u96A7\u9053: mihomo tunnel"] });
6221
+ throw new CliError(`\u672A\u627E\u5230\u96A7\u9053 "${name}"`, { hint: ["\u67E5\u770B\u5168\u90E8\u96A7\u9053: mihomo ssh"] });
5964
6222
  }
5965
- const existing = readTunnelRuntime(name);
5966
- if (existing && isTunnelProcessAlive(existing.pid, existing.port || config.port)) {
6223
+ const existing = readSshRuntime(name);
6224
+ if (existing && isSshProcessAlive(existing.pid, existing.port || config.port)) {
5967
6225
  if (options.startedBy === "manual" && existing.started_by === "auto") {
5968
- writeTunnelRuntime(name, { ...existing, started_by: "manual" });
6226
+ writeSshRuntime(name, { ...existing, started_by: "manual" });
5969
6227
  }
5970
6228
  return { alreadyRunning: true, pid: existing.pid };
5971
6229
  }
5972
- if (existing) clearTunnelRuntime(name);
6230
+ if (existing) clearSshRuntime(name);
5973
6231
  if (await isPortListening(config.port)) {
5974
6232
  throw new CliError(`\u7AEF\u53E3 ${config.port} \u5DF2\u88AB\u5360\u7528`, {
5975
6233
  label: "\u65E0\u6CD5\u542F\u52A8\u96A7\u9053",
@@ -5977,34 +6235,46 @@ async function startTunnel(name, options) {
5977
6235
  });
5978
6236
  }
5979
6237
  ensureDirs();
5980
- const logPath = getTunnelLogPath(name);
5981
- const logFd = fs7.openSync(logPath, "w");
6238
+ const logPath = getSshLogPath(name);
6239
+ const logFd = fs8.openSync(logPath, "w");
5982
6240
  const child = spawn2("ssh", buildSshArgs(config), {
5983
6241
  detached: true,
5984
6242
  stdio: ["ignore", logFd, logFd]
5985
6243
  });
5986
6244
  child.on("error", () => {
5987
6245
  });
5988
- fs7.closeSync(logFd);
6246
+ fs8.closeSync(logFd);
5989
6247
  child.unref();
5990
6248
  const pid = child.pid;
5991
6249
  if (!pid) {
5992
6250
  throw new CliError("\u65E0\u6CD5\u521B\u5EFA ssh \u8FDB\u7A0B", { label: "\u542F\u52A8\u96A7\u9053\u5931\u8D25", hint: ["\u8BF7\u786E\u8BA4\u5DF2\u5B89\u88C5 ssh \u5BA2\u6237\u7AEF\u3002"] });
5993
6251
  }
5994
- writeTunnelRuntime(name, {
6252
+ writeSshRuntime(name, {
5995
6253
  pid,
5996
6254
  started_by: options.startedBy,
5997
6255
  started_at: (/* @__PURE__ */ new Date()).toISOString(),
5998
6256
  port: config.port
5999
6257
  });
6000
- for (let i = 0; i < START_WAIT_ATTEMPTS; i++) {
6001
- if (!isProcessRunning(pid)) break;
6002
- if (await isPortListening(config.port)) {
6003
- return { alreadyRunning: false, pid };
6258
+ const unregisterCleanup = registerCleanup(() => {
6259
+ try {
6260
+ process.kill(pid, "SIGKILL");
6261
+ } catch {
6262
+ }
6263
+ clearSshRuntime(name);
6264
+ });
6265
+ try {
6266
+ for (let i = 0; i < START_WAIT_ATTEMPTS; i++) {
6267
+ if (!isProcessRunning(pid)) break;
6268
+ if (await isPortListening(config.port)) {
6269
+ unregisterCleanup();
6270
+ return { alreadyRunning: false, pid };
6271
+ }
6272
+ await new Promise((resolve) => setTimeout(resolve, START_WAIT_INTERVAL));
6004
6273
  }
6005
- await new Promise((resolve) => setTimeout(resolve, START_WAIT_INTERVAL));
6274
+ } finally {
6275
+ unregisterCleanup();
6006
6276
  }
6007
- clearTunnelRuntime(name);
6277
+ clearSshRuntime(name);
6008
6278
  if (isProcessRunning(pid)) {
6009
6279
  try {
6010
6280
  process.kill(pid, "SIGKILL");
@@ -6018,24 +6288,24 @@ async function startTunnel(name, options) {
6018
6288
  }
6019
6289
  function readLogTail(logPath, maxLines = 5) {
6020
6290
  try {
6021
- const content = fs7.readFileSync(logPath, "utf8").trim();
6291
+ const content = fs8.readFileSync(logPath, "utf8").trim();
6022
6292
  if (!content) return [];
6023
6293
  return content.split("\n").slice(-maxLines).map((line) => ` ${line.trim()}`);
6024
6294
  } catch {
6025
6295
  return [];
6026
6296
  }
6027
6297
  }
6028
- function stopTunnel(name) {
6029
- const config = findTunnel(name);
6030
- const runtime = readTunnelRuntime(name);
6298
+ function stopSshTunnel(name) {
6299
+ const config = findSshTunnel(name);
6300
+ const runtime = readSshRuntime(name);
6031
6301
  if (!runtime) {
6032
- clearTunnelRuntime(name);
6302
+ clearSshRuntime(name);
6033
6303
  return { notRunning: true, pid: null };
6034
6304
  }
6035
6305
  const port = runtime.port || config?.port || 0;
6036
6306
  const { pid } = runtime;
6037
- if (!isTunnelProcessAlive(pid, port)) {
6038
- clearTunnelRuntime(name);
6307
+ if (!isSshProcessAlive(pid, port)) {
6308
+ clearSshRuntime(name);
6039
6309
  return { notRunning: true, pid: null };
6040
6310
  }
6041
6311
  try {
@@ -6056,15 +6326,15 @@ function stopTunnel(name) {
6056
6326
  sleepSync(STOP_WAIT_INTERVAL);
6057
6327
  }
6058
6328
  }
6059
- clearTunnelRuntime(name);
6329
+ clearSshRuntime(name);
6060
6330
  return { notRunning: false, pid };
6061
6331
  }
6062
- async function startAutoTunnels() {
6332
+ async function startAutoSshTunnels() {
6063
6333
  const outcomes = [];
6064
- for (const tunnel of getTunnels()) {
6334
+ for (const tunnel of getSshTunnels()) {
6065
6335
  if (!tunnel.auto) continue;
6066
6336
  try {
6067
- const result = await startTunnel(tunnel.name, { startedBy: "auto" });
6337
+ const result = await startSshTunnel(tunnel.name, { startedBy: "auto" });
6068
6338
  outcomes.push({ name: tunnel.name, ok: true, alreadyRunning: result.alreadyRunning });
6069
6339
  } catch (e) {
6070
6340
  outcomes.push({
@@ -6076,63 +6346,24 @@ async function startAutoTunnels() {
6076
6346
  }
6077
6347
  return outcomes;
6078
6348
  }
6079
- function stopAutoTunnels() {
6349
+ function stopAutoSshTunnels() {
6080
6350
  const stopped = [];
6081
- for (const tunnel of getTunnels()) {
6082
- const runtime = readTunnelRuntime(tunnel.name);
6351
+ for (const tunnel of getSshTunnels()) {
6352
+ const runtime = readSshRuntime(tunnel.name);
6083
6353
  if (runtime?.started_by !== "auto") continue;
6084
- const result = stopTunnel(tunnel.name);
6354
+ const result = stopSshTunnel(tunnel.name);
6085
6355
  if (!result.notRunning) stopped.push(tunnel.name);
6086
6356
  }
6087
6357
  return stopped;
6088
6358
  }
6089
- function stopAllTunnels() {
6359
+ function stopAllSshTunnels() {
6090
6360
  const stopped = [];
6091
- for (const tunnel of getTunnels()) {
6092
- const result = stopTunnel(tunnel.name);
6361
+ for (const tunnel of getSshTunnels()) {
6362
+ const result = stopSshTunnel(tunnel.name);
6093
6363
  if (!result.notRunning) stopped.push(tunnel.name);
6094
6364
  }
6095
6365
  return stopped;
6096
6366
  }
6097
- function getTunnelOverwritePath(name) {
6098
- validateTunnelName(name);
6099
- return path6.join(USER_DATA_DIR, `overwrite.tunnel-${name}.yaml`);
6100
- }
6101
- function renderTunnelOverwrite(tunnel) {
6102
- const proxyName = `Tunnel-${tunnel.name}-Host`;
6103
- const groupName = `Tunnel-${tunnel.name}`;
6104
- return `# mihomo-cli \u96A7\u9053\u8986\u5199\uFF08tunnel: ${tunnel.name}\uFF09
6105
- # \u672C\u6587\u4EF6\u7531 mihomo-cli \u9996\u6B21\u521B\u5EFA\uFF0C\u4E4B\u540E\u5B8C\u5168\u7531\u4F60\u7EF4\u62A4\u2014\u2014CLI \u4E0D\u4F1A\u518D\u6539\u5199\u6216\u5220\u9664\u5B83\u3002
6106
- #
6107
- # ~ \u662F\u300C\u6309 name \u5C31\u5730\u5408\u5E76\u300D\u8BED\u4E49\uFF1A\u4E0E\u5176\u4ED6\u8986\u5199\u6587\u4EF6\u4E2D\u7684\u540C\u540D\u8282\u70B9/\u5206\u7EC4\u5408\u5E76\uFF0C
6108
- # \u4E0D\u4F9D\u8D56\u6587\u4EF6\u52A0\u8F7D\u987A\u5E8F\uFF08+proxies \u5219\u4F9D\u8D56\u5B57\u6BCD\u5E8F\uFF0C\u4F1A\u88AB\u540E\u6765\u7684\u6587\u4EF6\u538B\u8FC7\u53BB\uFF09\u3002
6109
-
6110
- ~proxies:
6111
- - name: ${proxyName}
6112
- type: socks5
6113
- server: 127.0.0.1
6114
- port: ${tunnel.port}
6115
-
6116
- ~proxy-groups:
6117
- - name: ${groupName}
6118
- type: select
6119
- proxies:
6120
- - ${proxyName}
6121
- - DIRECT
6122
-
6123
- # \u53D6\u6D88\u6CE8\u91CA\u5E76\u586B\u5165\u9700\u8981\u8D70\u96A7\u9053\u7684\u5185\u7F51\u57DF\u540D/\u7F51\u6BB5\uFF08CLI \u65E0\u4ECE\u77E5\u9053\u4F60\u7684\u5185\u7F51\u5730\u5740\uFF09\uFF1A
6124
- # +rules:
6125
- # - DOMAIN-SUFFIX,example.internal,${groupName}
6126
- # - IP-CIDR,10.0.0.0/8,${groupName}
6127
- `;
6128
- }
6129
- function ensureTunnelOverwriteFile(tunnel) {
6130
- const filePath = getTunnelOverwritePath(tunnel.name);
6131
- if (fs7.existsSync(filePath)) return false;
6132
- ensureDirs();
6133
- atomicWriteFileSync(filePath, renderTunnelOverwrite(tunnel), { mode: 384 });
6134
- return true;
6135
- }
6136
6367
 
6137
6368
  // src/commands/status.ts
6138
6369
  async function printStatus() {
@@ -6202,9 +6433,9 @@ async function printStatus() {
6202
6433
  if (isDaemonEnabled()) {
6203
6434
  console.log(`${colors.gray("\u4FDD\u6D3B: ")}${colors.green("\u5DF2\u542F\u7528")} ${colors.gray("(\u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F)")}`);
6204
6435
  }
6205
- const tunnels = getTunnels();
6436
+ const tunnels = getSshTunnels();
6206
6437
  if (tunnels.length > 0) {
6207
- const statuses = await getAllTunnelStatus();
6438
+ const statuses = await getAllSshStatus();
6208
6439
  const parts = statuses.map((s) => {
6209
6440
  const label = `${s.config.name}:${s.config.port}`;
6210
6441
  if (s.state === "running") return colors.green(label);
@@ -6222,8 +6453,8 @@ function handleStopResult(result) {
6222
6453
  throw new CliError(result.remaining.join(", "), { label: "\u90E8\u5206\u8FDB\u7A0B\u672A\u7EC8\u6B62", hint: "\u8BF7\u624B\u52A8\u8FD0\u884C: sudo pkill -9 mihomo" });
6223
6454
  }
6224
6455
  }
6225
- function stopAutoTunnelsWithLog() {
6226
- const stopped = stopAutoTunnels();
6456
+ function stopAutoSshTunnelsWithLog() {
6457
+ const stopped = stopAutoSshTunnels();
6227
6458
  if (stopped.length > 0) {
6228
6459
  console.log(`${colors.green("\u5DF2\u505C\u6B62\u96A7\u9053")}: ${stopped.join(", ")}`);
6229
6460
  }
@@ -6234,22 +6465,22 @@ async function cmdStop(args) {
6234
6465
  console.log("\u76F4\u63A5\u505C\u6B62\u4F1A\u88AB\u81EA\u52A8\u91CD\u65B0\u62C9\u8D77\uFF0C\u8BF7\u7528: mihomo daemon off");
6235
6466
  return;
6236
6467
  }
6237
- const skipTunnel = hasFlag(args, "--no-tunnel");
6468
+ const skipSsh = hasFlag(args, "--no-ssh");
6238
6469
  const pids = getMihomoPids();
6239
6470
  if (pids.length === 0) {
6240
6471
  console.log(colors.yellow("\u4E0D\u5728\u8FD0\u884C"));
6241
- if (!skipTunnel) stopAutoTunnelsWithLog();
6472
+ if (!skipSsh) stopAutoSshTunnelsWithLog();
6242
6473
  return;
6243
6474
  }
6244
6475
  console.log(`\u505C\u6B62 ${pids.length} \u4E2A\u8FDB\u7A0B...`);
6245
6476
  handleStopResult(stop());
6246
6477
  console.log(colors.green("\u5DF2\u505C\u6B62\u8FDB\u7A0B"));
6247
- if (!skipTunnel) stopAutoTunnelsWithLog();
6478
+ if (!skipSsh) stopAutoSshTunnelsWithLog();
6248
6479
  }
6249
6480
 
6250
6481
  // src/commands/start.ts
6251
- async function startAutoTunnelsWithWarning() {
6252
- const outcomes = await startAutoTunnels();
6482
+ async function startAutoSshTunnelsWithWarning() {
6483
+ const outcomes = await startAutoSshTunnels();
6253
6484
  if (outcomes.length === 0) return;
6254
6485
  const started = outcomes.filter((o) => o.ok && !o.alreadyRunning);
6255
6486
  if (started.length > 0) {
@@ -6263,7 +6494,7 @@ async function startAutoTunnelsWithWarning() {
6263
6494
  if (line.trim()) console.log(colors.gray(line.startsWith(" ") ? line : ` ${line}`));
6264
6495
  }
6265
6496
  console.log(colors.gray(" \u5185\u7F51\u5206\u6D41\u89C4\u5219\u5C06\u4E0D\u53EF\u7528\uFF0C\u5176\u4F59\u6D41\u91CF\u6B63\u5E38"));
6266
- console.log(colors.gray(` \u6392\u67E5: mihomo tunnel status ${failed.name}`));
6497
+ console.log(colors.gray(` \u6392\u67E5: mihomo ssh status ${failed.name}`));
6267
6498
  console.log("");
6268
6499
  }
6269
6500
  }
@@ -6285,7 +6516,7 @@ async function cmdStart(args) {
6285
6516
  const concurrency = parseIntArg(args, "-j", "--concurrency", DEFAULT_TEST_CONCURRENCY);
6286
6517
  const skipUpdate = hasFlag(args, "-s", "--no-update");
6287
6518
  const skipClean = hasFlag(args, "--no-clean");
6288
- const skipTunnel = hasFlag(args, "--no-tunnel");
6519
+ const skipSsh = hasFlag(args, "--no-ssh");
6289
6520
  const updateTimeout = parseIntArg(args, "-u", "--update-timeout", DEFAULT_AUTO_UPDATE_TIMEOUT);
6290
6521
  const sub = requireActiveSubscription("\u6CA1\u6709\u8BA2\u9605\uFF0C\u8BF7\u5148\u6DFB\u52A0\u8BA2\u9605");
6291
6522
  if (!skipUpdate) {
@@ -6327,8 +6558,8 @@ async function cmdStart(args) {
6327
6558
  const lines = e.message.split("\n");
6328
6559
  throw new CliError(lines[0], { label: "\u542F\u52A8\u5931\u8D25", hint: lines.slice(1) });
6329
6560
  }
6330
- if (!skipTunnel) {
6331
- await startAutoTunnelsWithWarning();
6561
+ if (!skipSsh) {
6562
+ await startAutoSshTunnelsWithWarning();
6332
6563
  }
6333
6564
  const cleanThreshold = isGithubUrl(sub.url) ? AUTO_CLEAN_THRESHOLD_GITHUB : AUTO_CLEAN_THRESHOLD;
6334
6565
  if (!skipClean && configInfo.proxies > cleanThreshold) {
@@ -6453,7 +6684,8 @@ async function daemonOn() {
6453
6684
  printDaemonStatus();
6454
6685
  }
6455
6686
  function daemonOff() {
6456
- if (!isDaemonEnabled()) {
6687
+ const residualRootKernel = getMihomoPids().some(isProcessRoot);
6688
+ if (!isDaemonEnabled() && !residualRootKernel) {
6457
6689
  console.log("\u4FDD\u6D3B\u5DF2\u662F\u5173\u95ED\u72B6\u6001");
6458
6690
  console.log("");
6459
6691
  printDaemonStatus();
@@ -6576,10 +6808,10 @@ async function cmdDirectory(args) {
6576
6808
 
6577
6809
  // src/kernel.ts
6578
6810
  import { spawnSync as spawnSync4 } from "child_process";
6579
- import fs8 from "fs";
6580
- import path7 from "path";
6811
+ import fs9 from "fs";
6812
+ import path8 from "path";
6581
6813
 
6582
- // node_modules/compare-versions/lib/esm/utils.js
6814
+ // ../../../node_modules/compare-versions/lib/esm/utils.js
6583
6815
  var semver = /^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;
6584
6816
  var validateAndParse = (version) => {
6585
6817
  if (typeof version !== "string") {
@@ -6617,7 +6849,7 @@ var compareSegments = (a, b) => {
6617
6849
  return 0;
6618
6850
  };
6619
6851
 
6620
- // node_modules/compare-versions/lib/esm/compareVersions.js
6852
+ // ../../../node_modules/compare-versions/lib/esm/compareVersions.js
6621
6853
  var compareVersions = (v1, v2) => {
6622
6854
  const n1 = validateAndParse(v1);
6623
6855
  const n2 = validateAndParse(v2);
@@ -6645,6 +6877,23 @@ function withMirror(url, mirror) {
6645
6877
  }
6646
6878
  return url;
6647
6879
  }
6880
+ var ALLOWED_ASSET_HOSTS = /* @__PURE__ */ new Set(["github.com", "api.github.com", "objects.githubusercontent.com", "release-assets.githubusercontent.com"]);
6881
+ function assertTrustedAssetUrl(rawUrl) {
6882
+ let parsed;
6883
+ try {
6884
+ parsed = new URL(rawUrl);
6885
+ } catch {
6886
+ throw new Error(`\u5185\u6838\u4E0B\u8F7D\u5730\u5740\u65E0\u6CD5\u89E3\u6790: ${rawUrl}`);
6887
+ }
6888
+ if (parsed.protocol !== "https:") {
6889
+ throw new Error(`\u5185\u6838\u4E0B\u8F7D\u5730\u5740\u5FC5\u987B\u662F https: ${rawUrl}`);
6890
+ }
6891
+ const host = parsed.hostname.toLowerCase();
6892
+ if (!ALLOWED_ASSET_HOSTS.has(host)) {
6893
+ throw new Error(`\u5185\u6838\u4E0B\u8F7D\u5730\u5740\u7684\u4E3B\u673A\u4E0D\u5728\u767D\u540D\u5355\u5185: ${host}
6894
+ \u4EC5\u5141\u8BB8: ${[...ALLOWED_ASSET_HOSTS].join(", ")}`);
6895
+ }
6896
+ }
6648
6897
  function getArch() {
6649
6898
  const arch = process.arch;
6650
6899
  if (arch === "arm64") return "arm64";
@@ -6703,15 +6952,16 @@ async function checkUpdate(mirror) {
6703
6952
  }
6704
6953
  function findBinaryInDir(dir, maxDepth = 4) {
6705
6954
  if (maxDepth <= 0) return null;
6706
- const files = fs8.readdirSync(dir);
6955
+ const files = fs9.readdirSync(dir);
6707
6956
  for (const f of files) {
6708
- const fullPath = path7.join(dir, f);
6709
- const stat = fs8.statSync(fullPath);
6957
+ const fullPath = path8.join(dir, f);
6958
+ const stat = fs9.lstatSync(fullPath);
6710
6959
  if (stat.isDirectory()) {
6711
6960
  const found = findBinaryInDir(fullPath, maxDepth - 1);
6712
6961
  if (found) return found;
6713
6962
  continue;
6714
6963
  }
6964
+ if (!stat.isFile()) continue;
6715
6965
  if (f === "mihomo") return fullPath;
6716
6966
  if (f.includes("mihomo") && !f.endsWith(".gz")) return fullPath;
6717
6967
  }
@@ -6731,8 +6981,9 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6731
6981
  throw new Error(`\u672A\u627E\u5230\u5339\u914D\u7684\u5185\u6838\u6587\u4EF6
6732
6982
  \u5E73\u53F0: ${platform}, \u67B6\u6784: ${arch}${hint}`);
6733
6983
  }
6984
+ assertTrustedAssetUrl(asset.browser_download_url);
6734
6985
  const downloadUrl = withMirror(asset.browser_download_url, mirror);
6735
- const tempPath = path7.join(DIRS.kernel, path7.basename(asset.name));
6986
+ const tempPath = path8.join(DIRS.kernel, path8.basename(asset.name));
6736
6987
  const sizeMB = (asset.size / 1024 / 1024).toFixed(2);
6737
6988
  if (mirror && progressCallback) {
6738
6989
  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");
@@ -6740,9 +6991,26 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6740
6991
  if (progressCallback) {
6741
6992
  progressCallback(`\u4E0B\u8F7D\u5185\u6838: ${asset.name} (${sizeMB} MB)`);
6742
6993
  }
6994
+ const maxBytes = Number.isFinite(asset.size) && asset.size > 0 ? Math.floor(asset.size * 2 + 1024 * 1024) : 512 * 1024 * 1024;
6743
6995
  const curlResult = spawnSync4(
6744
6996
  "curl",
6745
- ["-L", "--progress-bar", "--connect-timeout", "30", "--max-time", String(Math.floor(KERNEL_DOWNLOAD_TIMEOUT / 1e3)), "-o", tempPath, downloadUrl],
6997
+ [
6998
+ "-L",
6999
+ "--proto",
7000
+ "=https",
7001
+ "--proto-redir",
7002
+ "=https",
7003
+ "--max-filesize",
7004
+ String(maxBytes),
7005
+ "--progress-bar",
7006
+ "--connect-timeout",
7007
+ "30",
7008
+ "--max-time",
7009
+ String(Math.floor(KERNEL_DOWNLOAD_TIMEOUT / 1e3)),
7010
+ "-o",
7011
+ tempPath,
7012
+ downloadUrl
7013
+ ],
6746
7014
  { stdio: "inherit" }
6747
7015
  );
6748
7016
  if (curlResult.error) {
@@ -6753,14 +7021,27 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6753
7021
  }
6754
7022
  if (curlResult.status !== 0) {
6755
7023
  try {
6756
- fs8.unlinkSync(tempPath);
7024
+ fs9.unlinkSync(tempPath);
6757
7025
  } catch {
6758
7026
  }
6759
7027
  throw new Error(`\u4E0B\u8F7D\u5931\u8D25 (curl \u9000\u51FA\u7801 ${curlResult.status})`);
6760
7028
  }
6761
- if (!fs8.existsSync(tempPath)) {
7029
+ if (!fs9.existsSync(tempPath)) {
6762
7030
  throw new Error("\u4E0B\u8F7D\u5931\u8D25: \u6587\u4EF6\u672A\u751F\u6210");
6763
7031
  }
7032
+ if (Number.isFinite(asset.size) && asset.size > 0) {
7033
+ const actual = fs9.statSync(tempPath).size;
7034
+ if (actual !== asset.size) {
7035
+ try {
7036
+ fs9.unlinkSync(tempPath);
7037
+ } catch {
7038
+ }
7039
+ throw new Error(
7040
+ `\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
7041
+ \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`
7042
+ );
7043
+ }
7044
+ }
6764
7045
  if (progressCallback) {
6765
7046
  progressCallback("\u89E3\u538B\u5185\u6838...");
6766
7047
  }
@@ -6771,27 +7052,38 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6771
7052
  const listResult = spawnSync4("tar", ["-tzf", tempPath], { encoding: "utf8", timeout: 6e4 });
6772
7053
  if (listResult.error) throw listResult.error;
6773
7054
  if (listResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${listResult.status}`);
6774
- const entries = (listResult.stdout || "").split("\n").filter(Boolean);
6775
- for (const entry of entries) {
7055
+ for (const entry of (listResult.stdout || "").split("\n").filter(Boolean)) {
6776
7056
  if (entry.startsWith("/") || entry.split("/").includes("..")) {
6777
7057
  throw new Error(`\u5F52\u6863\u542B\u975E\u6CD5\u8DEF\u5F84\u6761\u76EE: ${entry}`);
6778
7058
  }
6779
7059
  }
6780
- const tarResult = spawnSync4("tar", ["-xzf", tempPath, "-C", extractPath], { stdio: ["ignore", "ignore", "inherit"], timeout: 6e4 });
7060
+ const typeResult = spawnSync4("tar", ["-tvzf", tempPath], { encoding: "utf8", timeout: 6e4 });
7061
+ if (typeResult.error) throw typeResult.error;
7062
+ if (typeResult.status !== 0) throw new Error(`tar \u5217\u8868\u9000\u51FA\u7801 ${typeResult.status}`);
7063
+ for (const line of (typeResult.stdout || "").split("\n").filter(Boolean)) {
7064
+ const typeChar = line[0];
7065
+ if (typeChar !== "-" && typeChar !== "d") {
7066
+ throw new Error(`\u5F52\u6863\u542B\u975E\u666E\u901A\u6587\u4EF6\u6761\u76EE\uFF08\u7C7B\u578B "${typeChar}"\uFF09: ${line}`);
7067
+ }
7068
+ }
7069
+ const tarResult = spawnSync4("tar", ["--no-same-owner", "-xzf", tempPath, "-C", extractPath], {
7070
+ stdio: ["ignore", "ignore", "inherit"],
7071
+ timeout: 6e4
7072
+ });
6781
7073
  if (tarResult.error) throw tarResult.error;
6782
7074
  if (tarResult.status !== 0) throw new Error(`tar \u9000\u51FA\u7801 ${tarResult.status}`);
6783
7075
  } else if (tempPath.endsWith(".gz")) {
6784
- const baseName = path7.basename(tempPath, ".gz");
6785
- const outputPath = path7.join(extractPath, baseName);
7076
+ const baseName = path8.basename(tempPath, ".gz");
7077
+ const outputPath = path8.join(extractPath, baseName);
6786
7078
  const gzipResult = spawnSync4("gzip", ["-dc", tempPath], { maxBuffer: 256 * 1024 * 1024, timeout: 6e4 });
6787
7079
  if (gzipResult.error) throw gzipResult.error;
6788
7080
  if (gzipResult.status !== 0) throw new Error(`gzip \u9000\u51FA\u7801 ${gzipResult.status}`);
6789
- fs8.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
7081
+ fs9.writeFileSync(outputPath, gzipResult.stdout, { mode: 493 });
6790
7082
  extractedBinary = outputPath;
6791
7083
  }
6792
7084
  } catch (e) {
6793
7085
  try {
6794
- fs8.unlinkSync(tempPath);
7086
+ fs9.unlinkSync(tempPath);
6795
7087
  } catch {
6796
7088
  }
6797
7089
  throw new Error(`\u89E3\u538B\u5931\u8D25: ${e.message}`);
@@ -6799,23 +7091,23 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6799
7091
  const foundBinary = extractedBinary || findBinaryInDir(extractPath);
6800
7092
  if (!foundBinary) {
6801
7093
  try {
6802
- fs8.unlinkSync(tempPath);
7094
+ fs9.unlinkSync(tempPath);
6803
7095
  } catch {
6804
7096
  }
6805
7097
  throw new Error("\u89E3\u538B\u540E\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6");
6806
7098
  }
6807
7099
  const targetPath = PATHS.mihomoBinary;
6808
7100
  if (foundBinary !== targetPath) {
6809
- if (fs8.existsSync(targetPath)) {
6810
- fs8.chmodSync(targetPath, 493);
7101
+ if (fs9.existsSync(targetPath)) {
7102
+ fs9.chmodSync(targetPath, 493);
6811
7103
  try {
6812
- fs8.unlinkSync(targetPath);
7104
+ fs9.unlinkSync(targetPath);
6813
7105
  } catch {
6814
7106
  }
6815
7107
  }
6816
- fs8.renameSync(foundBinary, targetPath);
7108
+ fs9.renameSync(foundBinary, targetPath);
6817
7109
  }
6818
- fs8.chmodSync(targetPath, 493);
7110
+ fs9.chmodSync(targetPath, 493);
6819
7111
  if (progressCallback) {
6820
7112
  progressCallback("\u6821\u9A8C\u5185\u6838...");
6821
7113
  }
@@ -6823,11 +7115,11 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6823
7115
  const checkOutput = `${check.stdout || ""}${check.stderr || ""}`.trim();
6824
7116
  if (check.error || check.status !== 0 || !/v?\d+\.\d+\.\d+/.test(checkOutput)) {
6825
7117
  try {
6826
- fs8.unlinkSync(targetPath);
7118
+ fs9.unlinkSync(targetPath);
6827
7119
  } catch {
6828
7120
  }
6829
7121
  try {
6830
- fs8.unlinkSync(tempPath);
7122
+ fs9.unlinkSync(tempPath);
6831
7123
  } catch {
6832
7124
  }
6833
7125
  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
@@ -6835,7 +7127,7 @@ async function downloadKernel(progressCallback, mirror, releaseInfo) {
6835
7127
  \u8F93\u51FA: ${checkOutput || "(\u7A7A)"}`);
6836
7128
  }
6837
7129
  try {
6838
- fs8.unlinkSync(tempPath);
7130
+ fs9.unlinkSync(tempPath);
6839
7131
  } catch {
6840
7132
  }
6841
7133
  clearKernelVersionCache();
@@ -6970,7 +7262,7 @@ function cmdLogs(args) {
6970
7262
  }
6971
7263
 
6972
7264
  // src/commands/overwrite.ts
6973
- import path8 from "path";
7265
+ import path9 from "path";
6974
7266
  function printOverwriteList() {
6975
7267
  const info = listOverwriteFile();
6976
7268
  const statusText = info.enabled ? colors.green("\u5DF2\u542F\u7528") : colors.yellow("\u5DF2\u7981\u7528");
@@ -6980,8 +7272,8 @@ function printOverwriteList() {
6980
7272
  if (info.files.length === 0) {
6981
7273
  console.log("\u6682\u65E0\u8986\u5199\u6587\u4EF6");
6982
7274
  console.log("");
6983
- console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path8.join(info.dir, "overwrite.yaml")}`);
6984
- console.log(` \u6216 ${path8.join(info.dir, "overwrite.dns.yaml")}`);
7275
+ console.log(`\u7528\u6CD5\u793A\u4F8B: \u521B\u5EFA\u6587\u4EF6 ${path9.join(info.dir, "overwrite.yaml")}`);
7276
+ console.log(` \u6216 ${path9.join(info.dir, "overwrite.dns.yaml")}`);
6985
7277
  console.log("");
6986
7278
  } else {
6987
7279
  console.log(`${colors.cyan("\u8986\u5199\u6587\u4EF6")} (${info.files.length} \u4E2A\uFF0C\u6309\u987A\u5E8F\u52A0\u8F7D):`);
@@ -7045,7 +7337,7 @@ async function cmdOverwrite(args) {
7045
7337
  }
7046
7338
 
7047
7339
  // src/commands/reset.ts
7048
- import fs9 from "fs";
7340
+ import fs10 from "fs";
7049
7341
  var RESET_TARGETS = [
7050
7342
  {
7051
7343
  id: "subs",
@@ -7083,15 +7375,20 @@ var RESET_TARGETS = [
7083
7375
  // 它们会继续占着端口跑下去,且 CLI 无任何路径能停掉。
7084
7376
  // **必须排在 settings 之前**:onAfter 会 writeSettings 重建 settings.json,
7085
7377
  // 排在 settings 之后会让 `reset --full` 留下一个 {}(同 subs 的处理,见执行顺序注释)
7086
- id: "tunnel",
7087
- aliases: ["tunnel", "tunnels", "ssh"],
7378
+ id: "ssh",
7379
+ aliases: ["ssh"],
7088
7380
  label: "\u96A7\u9053",
7089
- paths: () => [DIRS.tunnel],
7381
+ // 连 ssh.*.yaml 一并删:它们既不匹配 isOverwriteFilename(不归 overwrites 目标),
7382
+ // 本目标又只管运行态的话,`reset --full` 会留下配置文件,与「删全部」的承诺不符。
7383
+ // 单条 `ssh rm` 则刻意不删该文件(用户手写的分流规则不可恢复),两者语义不同
7384
+ paths: () => {
7385
+ const files = fs10.existsSync(USER_DATA_DIR) ? fs10.readdirSync(USER_DATA_DIR).filter(isSshFilename).map((f) => `${USER_DATA_DIR}/${f}`) : [];
7386
+ return [DIRS.ssh, ...files];
7387
+ },
7090
7388
  needsStop: false,
7091
- onBefore: () => stopAllTunnels(),
7092
- // 同步清空 settings 里的隧道列表:只删运行态会留下「列表在但状态没了」的半重置状态。
7093
- // 覆写文件不动——那是用户维护的资产,由 overwrites target 负责
7094
- onAfter: () => writeSettings({ tunnels: void 0 })
7389
+ onBefore: () => stopAllSshTunnels(),
7390
+ // 同步清空 settings 里的隧道列表:只删运行态会留下「列表在但状态没了」的半重置状态
7391
+ onAfter: () => writeSettings({ ssh: void 0 })
7095
7392
  },
7096
7393
  {
7097
7394
  id: "settings",
@@ -7120,8 +7417,8 @@ var RESET_TARGETS = [
7120
7417
  label: "\u8986\u5199",
7121
7418
  paths: () => {
7122
7419
  const dir = USER_DATA_DIR;
7123
- if (!fs9.existsSync(dir)) return [];
7124
- return fs9.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
7420
+ if (!fs10.existsSync(dir)) return [];
7421
+ return fs10.readdirSync(dir).filter(isOverwriteFilename).map((f) => `${dir}/${f}`);
7125
7422
  },
7126
7423
  needsStop: false
7127
7424
  },
@@ -7184,7 +7481,7 @@ async function cmdReset(args) {
7184
7481
  }
7185
7482
  targets = matched;
7186
7483
  } else {
7187
- targets = RESET_TARGETS.filter((t) => !["settings", "kernel", "overwrites", "daemon", "tunnel"].includes(t.id));
7484
+ targets = RESET_TARGETS.filter((t) => !["settings", "kernel", "overwrites", "daemon", "ssh"].includes(t.id));
7188
7485
  }
7189
7486
  for (const t of targets) {
7190
7487
  if (t.checkEmpty?.()) {
@@ -7246,7 +7543,7 @@ async function cmdReset(args) {
7246
7543
  for (const t of targets) {
7247
7544
  t.onBefore?.();
7248
7545
  for (const p of t.paths()) {
7249
- if (fs9.existsSync(p)) {
7546
+ if (fs10.existsSync(p)) {
7250
7547
  try {
7251
7548
  rmrf(p);
7252
7549
  } catch (e) {
@@ -7263,41 +7560,258 @@ async function cmdReset(args) {
7263
7560
  console.log(colors.green(`\u5DF2\u91CD\u7F6E: ${targets.map((t) => t.label).join("\u3001")}`));
7264
7561
  }
7265
7562
 
7266
- // src/test-instance.ts
7267
- import { spawn as spawn3 } from "child_process";
7268
- import fs10 from "fs";
7269
- import path9 from "path";
7270
- function isProxyValid(proxy) {
7271
- if (proxy === null || typeof proxy !== "object") return false;
7272
- if (!proxy.name || !proxy.server || !proxy.port) return false;
7273
- if (!proxy.type) return false;
7274
- if (proxy.type === "ss" && typeof proxy.cipher === "string" && proxy.cipher.startsWith("2022-blake3")) {
7275
- const pw = String(proxy.password || "");
7276
- if (!/^[A-Za-z0-9+/\-_]+=*$/.test(pw) || pw.length < 20) return false;
7563
+ // src/commands/ssh.ts
7564
+ function formatState(status) {
7565
+ switch (status.state) {
7566
+ case "running":
7567
+ return colors.green(`\u8FD0\u884C\u4E2D (PID ${status.pid})`);
7568
+ case "dead-port":
7569
+ return colors.yellow(`\u5047\u6D3B (PID ${status.pid}\uFF0C\u7AEF\u53E3 ${status.config.port} \u4E0D\u901A)`);
7570
+ default:
7571
+ return colors.yellow("\u672A\u8FD0\u884C");
7277
7572
  }
7278
- return true;
7279
7573
  }
7280
- var TEST_DIR = path9.join(USER_DATA_DIR, "test");
7281
- var TEST_DIRS = {
7282
- data: path9.join(TEST_DIR, "data"),
7283
- runtime: path9.join(TEST_DIR, "runtime")
7284
- };
7285
- var TEST_PATHS = {
7286
- configFile: path9.join(TEST_DIRS.runtime, "config.yaml"),
7287
- pidFile: path9.join(TEST_DIRS.runtime, "pid"),
7288
- logFile: path9.join(TEST_DIR, "test.log")
7289
- };
7290
- var TEST_API = `http://${TEST_CONFIG["external-controller"]}`;
7291
- function ensureTestDirs() {
7292
- for (const dir of Object.values(TEST_DIRS)) {
7293
- fs10.mkdirSync(dir, { recursive: true, mode: 448 });
7294
- }
7574
+ function getSshNameArg(args) {
7575
+ return getNonFlagArg(args, 2);
7295
7576
  }
7296
- function cleanupTestDir() {
7297
- rmrf(TEST_DIR);
7577
+ function requireSshNameArg(args, usage) {
7578
+ const name = getSshNameArg(args);
7579
+ if (!name) {
7580
+ const tunnels = getSshTunnels();
7581
+ throw new CliError("\u8BF7\u6307\u5B9A\u96A7\u9053\u540D\u79F0", {
7582
+ hint: [usage, ...tunnels.length > 0 ? ["", "\u53EF\u7528\u96A7\u9053:", ...tunnels.map((t) => ` ${t.name}`)] : []]
7583
+ });
7584
+ }
7585
+ return name;
7298
7586
  }
7299
- function buildTestConfig(subName) {
7300
- ensureTestDirs();
7587
+ async function printSshList() {
7588
+ const tunnels = getSshTunnels();
7589
+ console.log("");
7590
+ if (tunnels.length === 0) {
7591
+ console.log("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053");
7592
+ console.log("");
7593
+ console.log("\u6DFB\u52A0\u96A7\u9053: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>");
7594
+ console.log(colors.gray(" \u4F8B\u5982: mihomo ssh add work --host m4 --port 1080"));
7595
+ console.log(colors.gray(" \u96A7\u9053\u628A\u5185\u7F51\u51FA\u53E3\u66B4\u9732\u4E3A\u672C\u5730 SOCKS5\uFF0C\u914D\u5408 ssh.<\u540D\u5B57>.yaml \u5206\u6D41\u5185\u7F51\u57DF\u540D"));
7596
+ console.log("");
7597
+ return;
7598
+ }
7599
+ const statuses = await getAllSshStatus();
7600
+ console.log(colors.cyan("\u96A7\u9053\u5217\u8868:"));
7601
+ console.log("");
7602
+ for (const status of statuses) {
7603
+ const { config } = status;
7604
+ const autoLabel = config.auto ? colors.gray(" [auto]") : "";
7605
+ console.log(` ${colors.bold(config.name)}${autoLabel}`);
7606
+ console.log(` ${colors.gray("\u51FA\u53E3: ")}${config.host} \u2192 127.0.0.1:${config.port}`);
7607
+ console.log(` ${colors.gray("\u72B6\u6001: ")}${formatState(status)}`);
7608
+ console.log(` ${colors.gray("\u914D\u7F6E: ")}${getSshConfigPath(config.name)}`);
7609
+ if (status.started_by) {
7610
+ console.log(` ${colors.gray("\u6765\u6E90: ")}${status.started_by === "auto" ? "\u968F start \u62C9\u8D77" : "\u624B\u52A8\u542F\u52A8"}`);
7611
+ }
7612
+ }
7613
+ console.log("");
7614
+ console.log("\u542F\u52A8: mihomo ssh up [\u540D\u5B57] \u505C\u6B62: mihomo ssh down [\u540D\u5B57]");
7615
+ console.log("\u72B6\u6001: mihomo ssh status \u5220\u9664: mihomo ssh rm <\u540D\u5B57>");
7616
+ console.log("");
7617
+ }
7618
+ async function sshAdd(args) {
7619
+ const name = requireSshNameArg(args, "\u7528\u6CD5: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]");
7620
+ const host = parseStringArg(args, "--host");
7621
+ if (!host) {
7622
+ throw new CliError("\u7F3A\u5C11 --host", {
7623
+ hint: ["\u7528\u6CD5: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>", "", "\u4E3B\u673A\u53EF\u7528 ~/.ssh/config \u91CC\u7684\u522B\u540D\uFF0C\u4F8B\u5982 --host m4"]
7624
+ });
7625
+ }
7626
+ const portRaw = parseStringArg(args, "--port");
7627
+ if (!portRaw) {
7628
+ throw new CliError("\u7F3A\u5C11 --port", { hint: ["\u7528\u6CD5: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"] });
7629
+ }
7630
+ if (!/^\d+$/.test(portRaw.trim())) {
7631
+ throw new CliError(`\u7AEF\u53E3\u65E0\u6548: "${portRaw}"\uFF0C\u9700\u4E3A 1-65535 \u7684\u6574\u6570`);
7632
+ }
7633
+ const port = Number(portRaw.trim());
7634
+ const auto = !hasFlag(args, "--no-auto");
7635
+ const config = { name, host, port, auto };
7636
+ addSshTunnel(config);
7637
+ const created = ensureSshConfigFile(config);
7638
+ const configPath = getSshConfigPath(name);
7639
+ console.log(`${colors.green("\u5DF2\u6DFB\u52A0\u96A7\u9053")} ${name} \xB7 ${host} \u2192 127.0.0.1:${port}${auto ? " \xB7 auto" : ""}`);
7640
+ console.log("");
7641
+ if (created) {
7642
+ console.log(`\u5DF2\u751F\u6210\u914D\u7F6E\u6A21\u677F: ${configPath}`);
7643
+ console.log(colors.gray(" socks5 \u8282\u70B9\u7531 CLI \u81EA\u52A8\u6CE8\u5165\uFF0C\u6A21\u677F\u53EA\u5EFA\u597D\u5206\u7EC4\uFF0C\u5206\u6D41\u89C4\u5219\u9700\u4F60\u586B\u5199\uFF08CLI \u65E0\u4ECE\u77E5\u9053\u4F60\u7684\u5185\u7F51\u57DF\u540D\uFF09"));
7644
+ console.log(colors.gray(" \u7F16\u8F91\u540E\u6267\u884C mihomo start \u751F\u6548"));
7645
+ } else {
7646
+ console.log(`\u914D\u7F6E\u6587\u4EF6\u5DF2\u5B58\u5728\uFF0C\u672A\u6539\u52A8: ${configPath}`);
7647
+ }
7648
+ console.log("");
7649
+ console.log(`\u542F\u52A8\u96A7\u9053: mihomo ssh up ${name}`);
7650
+ await restartToApply(args);
7651
+ }
7652
+ async function sshUp(args) {
7653
+ const name = getSshNameArg(args);
7654
+ const targets = name ? [resolveSshTunnel(name)] : getSshTunnels();
7655
+ if (targets.length === 0) {
7656
+ throw new CliError("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053", { hint: ["\u6DFB\u52A0\u96A7\u9053: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"] });
7657
+ }
7658
+ for (const config of targets) {
7659
+ if (ensureSshConfigFile(config)) {
7660
+ console.log(colors.gray(`\u5DF2\u8865\u5EFA\u914D\u7F6E\u6A21\u677F: ${getSshConfigPath(config.name)}`));
7661
+ }
7662
+ const result = await startSshTunnel(config.name, { startedBy: "manual" });
7663
+ if (result.alreadyRunning) {
7664
+ console.log(`${colors.gray("\u5DF2\u5728\u8FD0\u884C")} ${config.name} (PID ${result.pid})`);
7665
+ } else {
7666
+ console.log(`${colors.green("\u5DF2\u542F\u52A8\u96A7\u9053")} ${config.name} \xB7 ${config.host} \u2192 127.0.0.1:${config.port} (PID ${result.pid})`);
7667
+ }
7668
+ }
7669
+ }
7670
+ function sshDown(args) {
7671
+ const name = getSshNameArg(args);
7672
+ const targets = name ? [resolveSshTunnel(name)] : getSshTunnels();
7673
+ if (targets.length === 0) {
7674
+ throw new CliError("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053");
7675
+ }
7676
+ let stopped = 0;
7677
+ for (const config of targets) {
7678
+ const result = stopSshTunnel(config.name);
7679
+ if (result.notRunning) {
7680
+ console.log(`${colors.yellow("\u4E0D\u5728\u8FD0\u884C")} ${config.name}`);
7681
+ } else {
7682
+ console.log(`${colors.green("\u5DF2\u505C\u6B62\u96A7\u9053")} ${config.name} (PID ${result.pid})`);
7683
+ stopped++;
7684
+ }
7685
+ }
7686
+ if (stopped > 0) {
7687
+ console.log("");
7688
+ console.log(colors.gray("\u6CE8\u610F: \u914D\u7F6E\u91CC\u7684\u96A7\u9053\u8282\u70B9\u4ECD\u5728\uFF0C\u73B0\u5728\u6307\u5411\u672A\u76D1\u542C\u7684\u7AEF\u53E3"));
7689
+ }
7690
+ }
7691
+ async function sshStatus(args) {
7692
+ const name = getSshNameArg(args);
7693
+ if (!name) {
7694
+ await printSshList();
7695
+ return;
7696
+ }
7697
+ const config = resolveSshTunnel(name);
7698
+ const status = await getSshStatus(config);
7699
+ console.log("");
7700
+ console.log(`${colors.gray("\u96A7\u9053: ")}${config.name}${config.auto ? colors.gray(" [auto]") : ""}`);
7701
+ console.log(`${colors.gray("\u51FA\u53E3: ")}${config.host} \u2192 127.0.0.1:${config.port}`);
7702
+ console.log(`${colors.gray("\u72B6\u6001: ")}${formatState(status)}`);
7703
+ if (status.started_by) {
7704
+ console.log(`${colors.gray("\u6765\u6E90: ")}${status.started_by === "auto" ? "\u968F start \u62C9\u8D77" : "\u624B\u52A8\u542F\u52A8"}`);
7705
+ }
7706
+ console.log("");
7707
+ if (status.state === "dead-port") {
7708
+ console.log(colors.yellow("ssh \u8FDB\u7A0B\u8FD8\u5728\uFF0C\u4F46\u7AEF\u53E3\u6CA1\u6709\u76D1\u542C\u2014\u2014\u5185\u7F51\u5206\u6D41\u5F53\u524D\u4E0D\u53EF\u7528"));
7709
+ console.log(`\u91CD\u542F\u96A7\u9053: mihomo ssh down ${config.name} && mihomo ssh up ${config.name}`);
7710
+ console.log(colors.gray(` \u65E5\u5FD7: ${getSshLogPath(config.name)}`));
7711
+ console.log("");
7712
+ } else if (status.state === "stopped") {
7713
+ console.log(`\u542F\u52A8\u96A7\u9053: mihomo ssh up ${config.name}`);
7714
+ console.log("");
7715
+ }
7716
+ }
7717
+ async function sshRemove(args) {
7718
+ const name = requireSshNameArg(args, "\u7528\u6CD5: mihomo ssh rm <\u540D\u5B57> [-y]");
7719
+ const config = resolveSshTunnel(name);
7720
+ const skipConfirm = hasFlag(args, "-y", "--yes");
7721
+ if (!skipConfirm) {
7722
+ if (!process.stdin.isTTY) {
7723
+ throw new CliError("\u5220\u9664\u96A7\u9053\u9700\u8981\u786E\u8BA4", {
7724
+ label: "\u5DF2\u53D6\u6D88",
7725
+ hint: [`\u8DF3\u8FC7\u786E\u8BA4: mihomo ssh rm ${config.name} -y`]
7726
+ });
7727
+ }
7728
+ const confirmed = await confirmPrompt(`\u786E\u8BA4\u5220\u9664\u96A7\u9053 "${config.name}"?`);
7729
+ if (!confirmed) {
7730
+ console.log("\u5DF2\u53D6\u6D88");
7731
+ return;
7732
+ }
7733
+ }
7734
+ stopSshTunnel(config.name);
7735
+ removeSshTunnel(config.name);
7736
+ console.log(`${colors.green("\u5DF2\u5220\u9664\u96A7\u9053")} ${config.name}`);
7737
+ console.log("");
7738
+ console.log(`\u914D\u7F6E\u6587\u4EF6\u672A\u5220\u9664: ${getSshConfigPath(config.name)}`);
7739
+ console.log(colors.gray(" \u5176\u4E2D\u7684\u5206\u7EC4\u5DF2\u5F15\u7528\u4E0D\u5230\u8282\u70B9\uFF0C\u4E0B\u6B21 start \u4F1A\u88AB\u81EA\u52A8\u79FB\u9664\uFF0C\u5982\u4E0D\u518D\u9700\u8981\u8BF7\u81EA\u884C\u5220\u9664\u8BE5\u6587\u4EF6"));
7740
+ }
7741
+ function resolveSshTunnel(name) {
7742
+ const config = findSshTunnel(name);
7743
+ if (!config) {
7744
+ const tunnels = getSshTunnels();
7745
+ const suggestion = suggestSimilar(
7746
+ name,
7747
+ tunnels.map((t) => t.name)
7748
+ );
7749
+ throw new CliError(`\u672A\u627E\u5230\u96A7\u9053 "${name}"`, {
7750
+ hint: [
7751
+ ...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
7752
+ ...tunnels.length > 0 ? ["", "\u53EF\u7528\u96A7\u9053:", ...tunnels.map((t) => ` ${t.name}`)] : ["", "\u6DFB\u52A0\u96A7\u9053: mihomo ssh add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"]
7753
+ ]
7754
+ });
7755
+ }
7756
+ return config;
7757
+ }
7758
+ var SUBCOMMANDS4 = [
7759
+ { name: "list", handler: printSshList },
7760
+ { name: "add", handler: sshAdd },
7761
+ { name: "up", aliases: ["start"], handler: sshUp },
7762
+ { name: "down", aliases: ["stop"], handler: sshDown },
7763
+ { name: "status", handler: sshStatus },
7764
+ { name: "remove", aliases: ["rm", "delete"], handler: sshRemove }
7765
+ ];
7766
+ async function cmdSsh(args) {
7767
+ await dispatchSubcommand(args, SUBCOMMANDS4, {
7768
+ // 无 action → 列表;未知 action → 报错(不静默回落,否则 `ssh upp` 会看似成功)
7769
+ fallback: printSshList,
7770
+ onUnknown: (action) => {
7771
+ const names = SUBCOMMANDS4.flatMap((c) => [c.name, ...c.aliases ?? []]);
7772
+ const suggestion = suggestSimilar(action, names);
7773
+ throw new CliError(`\u672A\u77E5\u7684 ssh \u5B50\u547D\u4EE4: ${action}`, {
7774
+ hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: list, add, up, down, status, rm"]
7775
+ });
7776
+ }
7777
+ });
7778
+ }
7779
+
7780
+ // src/test-instance.ts
7781
+ import { spawn as spawn3 } from "child_process";
7782
+ import fs11 from "fs";
7783
+ import path10 from "path";
7784
+ function isProxyValid(proxy) {
7785
+ if (proxy === null || typeof proxy !== "object") return false;
7786
+ if (!proxy.name || !proxy.server || !proxy.port) return false;
7787
+ if (!proxy.type) return false;
7788
+ if (proxy.type === "ss" && typeof proxy.cipher === "string" && proxy.cipher.startsWith("2022-blake3")) {
7789
+ const pw = String(proxy.password || "");
7790
+ if (!/^[A-Za-z0-9+/\-_]+=*$/.test(pw) || pw.length < 20) return false;
7791
+ }
7792
+ return true;
7793
+ }
7794
+ var TEST_DIR = path10.join(USER_DATA_DIR, "test");
7795
+ var TEST_DIRS = {
7796
+ data: path10.join(TEST_DIR, "data"),
7797
+ runtime: path10.join(TEST_DIR, "runtime")
7798
+ };
7799
+ var TEST_PATHS = {
7800
+ configFile: path10.join(TEST_DIRS.runtime, "config.yaml"),
7801
+ pidFile: path10.join(TEST_DIRS.runtime, "pid"),
7802
+ logFile: path10.join(TEST_DIR, "test.log")
7803
+ };
7804
+ var TEST_API = `http://${TEST_CONFIG["external-controller"]}`;
7805
+ function ensureTestDirs() {
7806
+ for (const dir of Object.values(TEST_DIRS)) {
7807
+ fs11.mkdirSync(dir, { recursive: true, mode: 448 });
7808
+ }
7809
+ }
7810
+ function cleanupTestDir() {
7811
+ rmrf(TEST_DIR);
7812
+ }
7813
+ function buildTestConfig(subName) {
7814
+ ensureTestDirs();
7301
7815
  const rawContent = readSubscriptionRawConfig(subName);
7302
7816
  if (!rawContent) {
7303
7817
  throw new CliError(`\u672A\u627E\u5230\u8BA2\u9605\u914D\u7F6E "${subName}"\uFF0C\u8BF7\u5148\u66F4\u65B0\u8BA2\u9605\uFF08mihomo sub update ${subName}\uFF09`);
@@ -7328,25 +7842,25 @@ function buildTestConfig(subName) {
7328
7842
  rules: ["MATCH,PROXY"]
7329
7843
  };
7330
7844
  const content = dumpYaml(config);
7331
- fs10.writeFileSync(TEST_PATHS.configFile, content, { mode: 384 });
7845
+ fs11.writeFileSync(TEST_PATHS.configFile, content, { mode: 384 });
7332
7846
  }
7333
7847
  async function startTestInstance() {
7334
7848
  const binary = PATHS.mihomoBinary;
7335
- if (!fs10.existsSync(binary)) throw new CliError('\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u8FD0\u884C "mihomo kernel" \u4E0B\u8F7D');
7849
+ if (!fs11.existsSync(binary)) throw new CliError('\u672A\u627E\u5230 mihomo \u5185\u6838\uFF0C\u8BF7\u5148\u8FD0\u884C "mihomo kernel" \u4E0B\u8F7D');
7336
7850
  stopTestInstance();
7337
- const logFd = fs10.openSync(TEST_PATHS.logFile, "a");
7851
+ const logFd = fs11.openSync(TEST_PATHS.logFile, "a");
7338
7852
  const child = spawn3(binary, ["-d", TEST_DIRS.data, "-f", TEST_PATHS.configFile], {
7339
7853
  detached: true,
7340
7854
  stdio: ["ignore", logFd, logFd]
7341
7855
  });
7342
7856
  child.on("error", () => {
7343
7857
  });
7344
- fs10.closeSync(logFd);
7858
+ fs11.closeSync(logFd);
7345
7859
  child.unref();
7346
7860
  const pid = child.pid;
7347
7861
  if (!pid) throw new CliError("\u6D4B\u8BD5\u5B9E\u4F8B\u542F\u52A8\u5931\u8D25\uFF1A\u65E0\u6CD5\u521B\u5EFA\u8FDB\u7A0B\uFF08\u5185\u6838\u4E8C\u8FDB\u5236\u53EF\u80FD\u4E0D\u53EF\u6267\u884C\uFF09");
7348
7862
  spawnedTestPid = pid;
7349
- fs10.writeFileSync(TEST_PATHS.pidFile, pid.toString(), { mode: 384 });
7863
+ fs11.writeFileSync(TEST_PATHS.pidFile, pid.toString(), { mode: 384 });
7350
7864
  const client = createHttpClient({ timeout: 2e3 });
7351
7865
  let ready = false;
7352
7866
  for (let i = 0; i < 60; i++) {
@@ -7362,7 +7876,7 @@ async function startTestInstance() {
7362
7876
  if (!isProcessRunning(pid)) {
7363
7877
  let errorDetail = "";
7364
7878
  try {
7365
- errorDetail = fs10.readFileSync(TEST_PATHS.logFile, "utf8").slice(-1e3);
7879
+ errorDetail = fs11.readFileSync(TEST_PATHS.logFile, "utf8").slice(-1e3);
7366
7880
  } catch {
7367
7881
  }
7368
7882
  throw new CliError(`\u6D4B\u8BD5\u5B9E\u4F8B\u542F\u52A8\u5931\u8D25${errorDetail ? `
@@ -7376,7 +7890,7 @@ var spawnedTestPid = null;
7376
7890
  function stopTestInstance() {
7377
7891
  let pid = null;
7378
7892
  try {
7379
- const fromFile = parseInt(fs10.readFileSync(TEST_PATHS.pidFile, "utf8").trim(), 10);
7893
+ const fromFile = parseInt(fs11.readFileSync(TEST_PATHS.pidFile, "utf8").trim(), 10);
7380
7894
  if (fromFile > 0) pid = fromFile;
7381
7895
  } catch {
7382
7896
  }
@@ -7391,7 +7905,7 @@ function stopTestInstance() {
7391
7905
  }
7392
7906
  spawnedTestPid = null;
7393
7907
  try {
7394
- fs10.unlinkSync(TEST_PATHS.pidFile);
7908
+ fs11.unlinkSync(TEST_PATHS.pidFile);
7395
7909
  } catch {
7396
7910
  }
7397
7911
  }
@@ -7711,7 +8225,7 @@ async function subTest(args) {
7711
8225
  progress.finish();
7712
8226
  console.log(formatTestSummary(summary));
7713
8227
  }
7714
- var SUBCOMMANDS4 = [
8228
+ var SUBCOMMANDS5 = [
7715
8229
  { name: "list", handler: printSubscriptionList },
7716
8230
  { name: "add", handler: subAdd },
7717
8231
  { name: "update", handler: subUpdate },
@@ -7722,11 +8236,11 @@ var SUBCOMMANDS4 = [
7722
8236
  { name: "test", handler: subTest }
7723
8237
  ];
7724
8238
  async function cmdSubscription(args) {
7725
- await dispatchSubcommand(args, SUBCOMMANDS4, {
8239
+ await dispatchSubcommand(args, SUBCOMMANDS5, {
7726
8240
  // 无子命令 → 列表;未知子命令 → 报错
7727
8241
  fallback: printSubscriptionList,
7728
8242
  onUnknown: (action) => {
7729
- const names = SUBCOMMANDS4.flatMap((c) => [c.name, ...c.aliases ?? []]);
8243
+ const names = SUBCOMMANDS5.flatMap((c) => [c.name, ...c.aliases ?? []]);
7730
8244
  const suggestion = suggestSimilar(action, names);
7731
8245
  throw new CliError(`\u672A\u77E5\u7684\u8BA2\u9605\u547D\u4EE4: ${action}`, {
7732
8246
  hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "\u7528\u6CD5: mihomo sub [list|use|add|update|remove|web|test|clean]"]
@@ -7801,224 +8315,6 @@ async function cmdClean(args) {
7801
8315
  }
7802
8316
  }
7803
8317
 
7804
- // src/commands/tunnel.ts
7805
- function formatState(status) {
7806
- switch (status.state) {
7807
- case "running":
7808
- return colors.green(`\u8FD0\u884C\u4E2D (PID ${status.pid})`);
7809
- case "dead-port":
7810
- return colors.yellow(`\u5047\u6D3B (PID ${status.pid}\uFF0C\u7AEF\u53E3 ${status.config.port} \u4E0D\u901A)`);
7811
- default:
7812
- return colors.yellow("\u672A\u8FD0\u884C");
7813
- }
7814
- }
7815
- function getTunnelNameArg(args) {
7816
- return getNonFlagArg(args, 2);
7817
- }
7818
- function requireTunnelNameArg(args, usage) {
7819
- const name = getTunnelNameArg(args);
7820
- if (!name) {
7821
- const tunnels = getTunnels();
7822
- throw new CliError("\u8BF7\u6307\u5B9A\u96A7\u9053\u540D\u79F0", {
7823
- hint: [usage, ...tunnels.length > 0 ? ["", "\u53EF\u7528\u96A7\u9053:", ...tunnels.map((t) => ` ${t.name}`)] : []]
7824
- });
7825
- }
7826
- return name;
7827
- }
7828
- async function printTunnelList() {
7829
- const tunnels = getTunnels();
7830
- console.log("");
7831
- if (tunnels.length === 0) {
7832
- console.log("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053");
7833
- console.log("");
7834
- console.log("\u6DFB\u52A0\u96A7\u9053: mihomo tunnel add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>");
7835
- console.log(colors.gray(" \u4F8B\u5982: mihomo tunnel add work --host m4 --port 1080"));
7836
- console.log(colors.gray(" \u96A7\u9053\u628A\u5185\u7F51\u51FA\u53E3\u66B4\u9732\u4E3A\u672C\u5730 SOCKS5\uFF0C\u914D\u5408\u8986\u5199\u6587\u4EF6\u5206\u6D41\u5185\u7F51\u57DF\u540D"));
7837
- console.log("");
7838
- return;
7839
- }
7840
- const statuses = await getAllTunnelStatus();
7841
- console.log(colors.cyan("\u96A7\u9053\u5217\u8868:"));
7842
- console.log("");
7843
- for (const status of statuses) {
7844
- const { config } = status;
7845
- const autoLabel = config.auto ? colors.gray(" [auto]") : "";
7846
- console.log(` ${colors.bold(config.name)}${autoLabel}`);
7847
- console.log(` ${colors.gray("\u51FA\u53E3: ")}${config.host} \u2192 127.0.0.1:${config.port}`);
7848
- console.log(` ${colors.gray("\u72B6\u6001: ")}${formatState(status)}`);
7849
- if (status.started_by) {
7850
- console.log(` ${colors.gray("\u6765\u6E90: ")}${status.started_by === "auto" ? "\u968F start \u62C9\u8D77" : "\u624B\u52A8\u542F\u52A8"}`);
7851
- }
7852
- }
7853
- console.log("");
7854
- console.log("\u542F\u52A8: mihomo tunnel up [\u540D\u5B57] \u505C\u6B62: mihomo tunnel down [\u540D\u5B57]");
7855
- console.log("\u72B6\u6001: mihomo tunnel status \u5220\u9664: mihomo tunnel rm <\u540D\u5B57>");
7856
- console.log("");
7857
- }
7858
- async function tunnelAdd(args) {
7859
- const name = requireTunnelNameArg(args, "\u7528\u6CD5: mihomo tunnel add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]");
7860
- const host = parseStringArg(args, "--host");
7861
- if (!host) {
7862
- throw new CliError("\u7F3A\u5C11 --host", {
7863
- hint: ["\u7528\u6CD5: mihomo tunnel add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>", "", "\u4E3B\u673A\u53EF\u7528 ~/.ssh/config \u91CC\u7684\u522B\u540D\uFF0C\u4F8B\u5982 --host m4"]
7864
- });
7865
- }
7866
- const portRaw = parseStringArg(args, "--port");
7867
- if (!portRaw) {
7868
- throw new CliError("\u7F3A\u5C11 --port", { hint: ["\u7528\u6CD5: mihomo tunnel add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"] });
7869
- }
7870
- if (!/^\d+$/.test(portRaw.trim())) {
7871
- throw new CliError(`\u7AEF\u53E3\u65E0\u6548: "${portRaw}"\uFF0C\u9700\u4E3A 1-65535 \u7684\u6574\u6570`);
7872
- }
7873
- const port = Number(portRaw.trim());
7874
- const auto = !hasFlag(args, "--no-auto");
7875
- const config = { name, host, port, auto };
7876
- addTunnel(config);
7877
- const created = ensureTunnelOverwriteFile(config);
7878
- const overwritePath = getTunnelOverwritePath(name);
7879
- console.log(`${colors.green("\u5DF2\u6DFB\u52A0\u96A7\u9053")} ${name} \xB7 ${host} \u2192 127.0.0.1:${port}${auto ? " \xB7 auto" : ""}`);
7880
- console.log("");
7881
- if (created) {
7882
- console.log(`\u5DF2\u751F\u6210\u8986\u5199\u6A21\u677F: ${overwritePath}`);
7883
- console.log(colors.gray(" \u6A21\u677F\u53EA\u5EFA\u597D socks5 \u8282\u70B9\u4E0E\u5206\u7EC4\uFF0C\u5206\u6D41\u89C4\u5219\u9700\u4F60\u586B\u5199\uFF08CLI \u65E0\u4ECE\u77E5\u9053\u4F60\u7684\u5185\u7F51\u57DF\u540D\uFF09"));
7884
- console.log(colors.gray(" \u7F16\u8F91\u540E\u6267\u884C mihomo start \u751F\u6548"));
7885
- } else {
7886
- console.log(`\u8986\u5199\u6587\u4EF6\u5DF2\u5B58\u5728\uFF0C\u672A\u6539\u52A8: ${overwritePath}`);
7887
- }
7888
- console.log("");
7889
- console.log(`\u542F\u52A8\u96A7\u9053: mihomo tunnel up ${name}`);
7890
- if (created) {
7891
- await restartToApply(args);
7892
- }
7893
- }
7894
- async function tunnelUp(args) {
7895
- const name = getTunnelNameArg(args);
7896
- const targets = name ? [resolveTunnel(name)] : getTunnels();
7897
- if (targets.length === 0) {
7898
- throw new CliError("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053", { hint: ["\u6DFB\u52A0\u96A7\u9053: mihomo tunnel add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"] });
7899
- }
7900
- for (const config of targets) {
7901
- if (ensureTunnelOverwriteFile(config)) {
7902
- console.log(colors.gray(`\u5DF2\u8865\u5EFA\u8986\u5199\u6A21\u677F: ${getTunnelOverwritePath(config.name)}`));
7903
- }
7904
- const result = await startTunnel(config.name, { startedBy: "manual" });
7905
- if (result.alreadyRunning) {
7906
- console.log(`${colors.gray("\u5DF2\u5728\u8FD0\u884C")} ${config.name} (PID ${result.pid})`);
7907
- } else {
7908
- console.log(`${colors.green("\u5DF2\u542F\u52A8\u96A7\u9053")} ${config.name} \xB7 ${config.host} \u2192 127.0.0.1:${config.port} (PID ${result.pid})`);
7909
- }
7910
- }
7911
- }
7912
- function tunnelDown(args) {
7913
- const name = getTunnelNameArg(args);
7914
- const targets = name ? [resolveTunnel(name)] : getTunnels();
7915
- if (targets.length === 0) {
7916
- throw new CliError("\u6CA1\u6709\u914D\u7F6E\u96A7\u9053");
7917
- }
7918
- let stopped = 0;
7919
- for (const config of targets) {
7920
- const result = stopTunnel(config.name);
7921
- if (result.notRunning) {
7922
- console.log(`${colors.yellow("\u4E0D\u5728\u8FD0\u884C")} ${config.name}`);
7923
- } else {
7924
- console.log(`${colors.green("\u5DF2\u505C\u6B62\u96A7\u9053")} ${config.name} (PID ${result.pid})`);
7925
- stopped++;
7926
- }
7927
- }
7928
- if (stopped > 0) {
7929
- console.log("");
7930
- console.log(colors.gray("\u6CE8\u610F: \u8986\u5199\u6587\u4EF6\u4ECD\u5728\uFF0C\u914D\u7F6E\u91CC\u7684\u96A7\u9053\u8282\u70B9\u73B0\u5728\u6307\u5411\u672A\u76D1\u542C\u7684\u7AEF\u53E3"));
7931
- }
7932
- }
7933
- async function tunnelStatus(args) {
7934
- const name = getTunnelNameArg(args);
7935
- if (!name) {
7936
- await printTunnelList();
7937
- return;
7938
- }
7939
- const config = resolveTunnel(name);
7940
- const status = await getTunnelStatus(config);
7941
- console.log("");
7942
- console.log(`${colors.gray("\u96A7\u9053: ")}${config.name}${config.auto ? colors.gray(" [auto]") : ""}`);
7943
- console.log(`${colors.gray("\u51FA\u53E3: ")}${config.host} \u2192 127.0.0.1:${config.port}`);
7944
- console.log(`${colors.gray("\u72B6\u6001: ")}${formatState(status)}`);
7945
- if (status.started_by) {
7946
- console.log(`${colors.gray("\u6765\u6E90: ")}${status.started_by === "auto" ? "\u968F start \u62C9\u8D77" : "\u624B\u52A8\u542F\u52A8"}`);
7947
- }
7948
- console.log("");
7949
- if (status.state === "dead-port") {
7950
- console.log(colors.yellow("ssh \u8FDB\u7A0B\u8FD8\u5728\uFF0C\u4F46\u7AEF\u53E3\u6CA1\u6709\u76D1\u542C\u2014\u2014\u5185\u7F51\u5206\u6D41\u5F53\u524D\u4E0D\u53EF\u7528"));
7951
- console.log(`\u91CD\u542F\u96A7\u9053: mihomo tunnel down ${config.name} && mihomo tunnel up ${config.name}`);
7952
- console.log(colors.gray(` \u65E5\u5FD7: ${getTunnelLogPath(config.name)}`));
7953
- console.log("");
7954
- } else if (status.state === "stopped") {
7955
- console.log(`\u542F\u52A8\u96A7\u9053: mihomo tunnel up ${config.name}`);
7956
- console.log("");
7957
- }
7958
- }
7959
- async function tunnelRemove(args) {
7960
- const name = requireTunnelNameArg(args, "\u7528\u6CD5: mihomo tunnel rm <\u540D\u5B57> [-y]");
7961
- const config = resolveTunnel(name);
7962
- const skipConfirm = hasFlag(args, "-y", "--yes");
7963
- if (!skipConfirm) {
7964
- if (!process.stdin.isTTY) {
7965
- throw new CliError("\u5220\u9664\u96A7\u9053\u9700\u8981\u786E\u8BA4", {
7966
- label: "\u5DF2\u53D6\u6D88",
7967
- hint: [`\u8DF3\u8FC7\u786E\u8BA4: mihomo tunnel rm ${config.name} -y`]
7968
- });
7969
- }
7970
- const confirmed = await confirmPrompt(`\u786E\u8BA4\u5220\u9664\u96A7\u9053 "${config.name}"?`);
7971
- if (!confirmed) {
7972
- console.log("\u5DF2\u53D6\u6D88");
7973
- return;
7974
- }
7975
- }
7976
- stopTunnel(config.name);
7977
- removeTunnel(config.name);
7978
- console.log(`${colors.green("\u5DF2\u5220\u9664\u96A7\u9053")} ${config.name}`);
7979
- console.log("");
7980
- console.log(`\u8986\u5199\u6587\u4EF6\u672A\u5220\u9664: ${getTunnelOverwritePath(config.name)}`);
7981
- console.log(colors.gray(" \u5B83\u4ECD\u4F1A\u5411\u914D\u7F6E\u6CE8\u5165\u6307\u5411\u8BE5\u7AEF\u53E3\u7684\u8282\u70B9\uFF0C\u5982\u4E0D\u518D\u9700\u8981\u8BF7\u81EA\u884C\u5220\u9664"));
7982
- }
7983
- function resolveTunnel(name) {
7984
- const config = findTunnel(name);
7985
- if (!config) {
7986
- const tunnels = getTunnels();
7987
- const suggestion = suggestSimilar(
7988
- name,
7989
- tunnels.map((t) => t.name)
7990
- );
7991
- throw new CliError(`\u672A\u627E\u5230\u96A7\u9053 "${name}"`, {
7992
- hint: [
7993
- ...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [],
7994
- ...tunnels.length > 0 ? ["", "\u53EF\u7528\u96A7\u9053:", ...tunnels.map((t) => ` ${t.name}`)] : ["", "\u6DFB\u52A0\u96A7\u9053: mihomo tunnel add <\u540D\u5B57> --host <ssh\u4E3B\u673A> --port <\u7AEF\u53E3>"]
7995
- ]
7996
- });
7997
- }
7998
- return config;
7999
- }
8000
- var SUBCOMMANDS5 = [
8001
- { name: "list", handler: printTunnelList },
8002
- { name: "add", handler: tunnelAdd },
8003
- { name: "up", aliases: ["start"], handler: tunnelUp },
8004
- { name: "down", aliases: ["stop"], handler: tunnelDown },
8005
- { name: "status", handler: tunnelStatus },
8006
- { name: "remove", aliases: ["rm", "delete"], handler: tunnelRemove }
8007
- ];
8008
- async function cmdTunnel(args) {
8009
- await dispatchSubcommand(args, SUBCOMMANDS5, {
8010
- // 无 action → 列表;未知 action → 报错(不静默回落,否则 `tunnel upp` 会看似成功)
8011
- fallback: printTunnelList,
8012
- onUnknown: (action) => {
8013
- const names = SUBCOMMANDS5.flatMap((c) => [c.name, ...c.aliases ?? []]);
8014
- const suggestion = suggestSimilar(action, names);
8015
- throw new CliError(`\u672A\u77E5\u7684 tunnel \u5B50\u547D\u4EE4: ${action}`, {
8016
- hint: [...suggestion.length > 0 ? [`\u662F\u5426\u60F3\u8F93\u5165: ${suggestion.join(" / ")}?`] : [], "", "\u53EF\u7528\u5B50\u547D\u4EE4: list, add, up, down, status, rm"]
8017
- });
8018
- }
8019
- });
8020
- }
8021
-
8022
8318
  // src/commands/ui.ts
8023
8319
  function cmdUI(args) {
8024
8320
  const uiName = args[1] || "zash";
@@ -8251,17 +8547,18 @@ var COMMANDS = [
8251
8547
  usage: ["daemon on|off \u5F00\u673A\u81EA\u542F + \u5D29\u6E83\u91CD\u542F\uFF08\u4EC5 Mixed\uFF0C\u9700\u7BA1\u7406\u5458\u5BC6\u7801\uFF09", "daemon status \u67E5\u770B\u4FDD\u6D3B\u72B6\u6001"]
8252
8548
  },
8253
8549
  {
8254
- // 别名不能用 tun——已被 TUN 模式快捷命令占用(注册表重复 token 会在模块加载期直接抛错)
8255
- name: "tunnel",
8256
- aliases: ["ssh", "tunnels"],
8257
- handler: cmdTunnel,
8550
+ // 无别名:`tun` 被 TUN 模式快捷命令占用,`ssh` 本身已够短。
8551
+ // (注册表重复 token 会在模块加载期直接抛错)
8552
+ name: "ssh",
8553
+ aliases: [],
8554
+ handler: cmdSsh,
8258
8555
  group: "system",
8259
8556
  usage: [
8260
- "tunnel \u5217\u51FA ssh \u96A7\u9053\uFF08\u522B\u540D ssh\uFF09",
8261
- "tunnel add <\u540D\u5B57> --host <\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]",
8262
- "tunnel up|down [\u540D\u5B57] \u542F\u52A8/\u505C\u6B62\u96A7\u9053\uFF08\u65E0\u53C2\u5373\u5168\u90E8\uFF09",
8263
- "tunnel status [\u540D\u5B57] \u67E5\u770B\u96A7\u9053\u72B6\u6001\uFF08\u771F\u5B9E\u63A2\u6D4B\u7AEF\u53E3\uFF09",
8264
- "tunnel rm <\u540D\u5B57> [-y] \u5220\u9664\u96A7\u9053\uFF08\u4E0D\u5220\u8986\u5199\u6587\u4EF6\uFF09"
8557
+ "ssh \u5217\u51FA ssh \u96A7\u9053",
8558
+ "ssh add <\u540D\u5B57> --host <\u4E3B\u673A> --port <\u7AEF\u53E3> [--no-auto]",
8559
+ "ssh up|down [\u540D\u5B57] \u542F\u52A8/\u505C\u6B62\u96A7\u9053\uFF08\u65E0\u53C2\u5373\u5168\u90E8\uFF09",
8560
+ "ssh status [\u540D\u5B57] \u67E5\u770B\u96A7\u9053\u72B6\u6001\uFF08\u771F\u5B9E\u63A2\u6D4B\u7AEF\u53E3\uFF09",
8561
+ "ssh rm <\u540D\u5B57> [-y] \u5220\u9664\u96A7\u9053\uFF08\u4E0D\u5220\u914D\u7F6E\u6587\u4EF6\uFF09"
8265
8562
  ]
8266
8563
  },
8267
8564
  {