unplugin-https-reverse-proxy 4.1.0-beta.8 → 4.1.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/README.md CHANGED
@@ -219,14 +219,14 @@ export default defineNuxtConfig({
219
219
  })
220
220
  ```
221
221
 
222
- **!important:** You need to update the `nuxt dev` script by adding `--fork=false` to enable host restoration.
222
+ **!important:** You need to update the `nuxt dev` script by adding `--fork=false` to enable host restoration, and `--no-tui` so you can type the administrator password when the proxy asks for it.
223
223
 
224
224
  ```json
225
225
  // package.json
226
226
 
227
227
  {
228
228
  "scripts": {
229
- "dev": "nuxt dev --fork=false"
229
+ "dev": "nuxt dev --fork=false --no-tui"
230
230
  }
231
231
  }
232
232
  ```
@@ -27,9 +27,9 @@ import { createUnplugin } from "unplugin";
27
27
  // src/caddy/index.ts
28
28
  import { execFile } from "node:child_process";
29
29
  import { chmodSync, createWriteStream, existsSync as existsSync5, mkdirSync, unlinkSync as unlinkSync2 } from "node:fs";
30
- import { readFile as readFile3, unlink, writeFile as writeFile2 } from "node:fs/promises";
30
+ import { readFile as readFile3, rename, unlink, writeFile as writeFile2 } from "node:fs/promises";
31
31
  import { platform as platform3 } from "node:os";
32
- import { join as join6 } from "node:path";
32
+ import { join as join7 } from "node:path";
33
33
  import process8 from "node:process";
34
34
  import { got } from "got-cjs";
35
35
  import { HttpProxyAgent } from "http-proxy-agent";
@@ -12891,6 +12891,7 @@ var ProxyType = type({
12891
12891
  });
12892
12892
  var CaddyContext = type({
12893
12893
  caddy_root: "string",
12894
+ admin_socket: "string",
12894
12895
  proxies: ProxyType.array()
12895
12896
  });
12896
12897
  function validateTemplateContext(ctx) {
@@ -12903,6 +12904,7 @@ var caddyTemplate = `{
12903
12904
  debug
12904
12905
  auto_https disable_redirects ignore_loaded_certs
12905
12906
  skip_install_trust
12907
+ admin unix/{{ admin_socket }}
12906
12908
  }
12907
12909
 
12908
12910
  :7601 {
@@ -13000,11 +13002,20 @@ function resolvePath(path) {
13000
13002
  return join2(os.homedir() || "", path.slice(1));
13001
13003
  return path;
13002
13004
  }
13003
- var TEMP_DIR = resolvePath(process2.env.UHRP_CADDY_PATH || process2.env.TEMP || process2.env.TMPDIR || "/tmp");
13005
+ function defaultTempDir() {
13006
+ const fromEnv = process2.env.TEMP || process2.env.TMPDIR;
13007
+ if (fromEnv)
13008
+ return resolvePath(fromEnv);
13009
+ if (process2.platform === "linux")
13010
+ return join2(process2.env.XDG_CACHE_HOME || join2(os.homedir(), ".cache"), "uhrp");
13011
+ return "/tmp";
13012
+ }
13013
+ var TEMP_DIR = resolvePath(process2.env.UHRP_CADDY_PATH || defaultTempDir());
13004
13014
  var caddyPath = join2(TEMP_DIR, `caddy${process2.platform === "win32" ? ".exe" : ""}`);
13005
13015
  var caddyFilePath = join2(TEMP_DIR, "CADDYFILE");
13006
13016
  var caddyConfigPath = join2(TEMP_DIR, ".CADDYFILE.config.json");
13007
13017
  var caddyLockFilePath = join2(TEMP_DIR, "caddylock");
13018
+ var caddyAdminSocketPath = join2(TEMP_DIR, "caddy-admin.sock");
13008
13019
  var supportList = [
13009
13020
  {
13010
13021
  platform: "dragonfly",
@@ -13127,12 +13138,12 @@ function isAlive(pid) {
13127
13138
  return false;
13128
13139
  }
13129
13140
  }
13130
- function readConfig() {
13131
- if (!existsSync2(caddyConfigPath))
13141
+ function readConfig(path = caddyConfigPath) {
13142
+ if (!existsSync2(path))
13132
13143
  return {};
13133
13144
  let parsed2;
13134
13145
  try {
13135
- parsed2 = JSON.parse(readFileSync2(caddyConfigPath, "utf-8"));
13146
+ parsed2 = JSON.parse(readFileSync2(path, "utf-8"));
13136
13147
  } catch {
13137
13148
  return {};
13138
13149
  }
@@ -13143,53 +13154,54 @@ function readConfig() {
13143
13154
  }
13144
13155
  return alive;
13145
13156
  }
13146
- function writeConfig(proxies) {
13157
+ function writeConfig(proxies, path = caddyConfigPath) {
13147
13158
  const content = JSON.stringify(proxies, null, 2);
13148
- const temp = `${caddyConfigPath}.${process3.pid}.tmp`;
13159
+ const temp = `${path}.${process3.pid}.tmp`;
13149
13160
  writeFileSync(temp, content);
13150
- renameSync(temp, caddyConfigPath);
13151
- }
13152
- async function mutateConfig(lock3, mutate) {
13153
- const release = await lock3.acquire();
13154
- try {
13155
- const proxies = readConfig();
13156
- mutate(proxies);
13157
- writeConfig(proxies);
13158
- return proxies;
13159
- } finally {
13160
- release();
13161
- }
13161
+ renameSync(temp, path);
13162
13162
  }
13163
13163
  function useCaddyConfig(options = {}) {
13164
13164
  const lock3 = options.lock ?? createFileLock();
13165
+ const configPath = options.configPath ?? caddyConfigPath;
13166
+ async function mutate(apply) {
13167
+ var _a4;
13168
+ const release = await lock3.acquire();
13169
+ try {
13170
+ const proxies = readConfig(configPath);
13171
+ apply(proxies);
13172
+ writeConfig(proxies, configPath);
13173
+ await ((_a4 = options.renderCaddyfile) == null ? void 0 : _a4.call(options, proxies));
13174
+ return proxies;
13175
+ } finally {
13176
+ release();
13177
+ }
13178
+ }
13165
13179
  return {
13166
- configJsonRef: () => existsSync2(caddyConfigPath) ? readConfig() : void 0,
13180
+ configJsonRef: () => existsSync2(configPath) ? readConfig(configPath) : void 0,
13167
13181
  async writeCaddyConfig(_proxies, key) {
13168
- await mutateConfig(lock3, (proxies) => {
13182
+ await mutate((proxies) => {
13169
13183
  for (const p of _proxies)
13170
13184
  proxies[routeKey(p, key)] = { ...p, base: normalizeBase(p.base), ownerPid: process3.pid };
13171
13185
  });
13172
13186
  },
13173
13187
  async removeProxy(key) {
13174
- const proxies = await mutateConfig(lock3, (current) => {
13188
+ await mutate((current) => {
13175
13189
  for (const route of Object.keys(current)) {
13176
13190
  if (route.endsWith(`#${key}`))
13177
13191
  delete current[route];
13178
13192
  }
13179
13193
  });
13180
- if (Object.keys(proxies).length === 0)
13181
- removeConfigFile();
13182
13194
  },
13183
- readProxies: () => readConfig(),
13195
+ readProxies: () => readConfig(configPath),
13184
13196
  async cleanUp() {
13185
- removeConfigFile();
13197
+ removeConfigFile(configPath);
13186
13198
  }
13187
13199
  };
13188
13200
  }
13189
- function removeConfigFile() {
13201
+ function removeConfigFile(path = caddyConfigPath) {
13190
13202
  try {
13191
- if (existsSync2(caddyConfigPath))
13192
- unlinkSync(caddyConfigPath);
13203
+ if (existsSync2(path))
13204
+ unlinkSync(path);
13193
13205
  } catch {
13194
13206
  }
13195
13207
  }
@@ -13235,7 +13247,7 @@ function isCaddyReloadCancellation(line) {
13235
13247
  // src/caddy/privileged.ts
13236
13248
  import { Buffer as Buffer2 } from "node:buffer";
13237
13249
  import { EventEmitter } from "node:events";
13238
- import { dirname as dirname3, join as join5 } from "node:path";
13250
+ import { dirname as dirname3, join as join6 } from "node:path";
13239
13251
  import process7 from "node:process";
13240
13252
  import { fileURLToPath } from "node:url";
13241
13253
 
@@ -13274,13 +13286,15 @@ import { Buffer } from "node:buffer";
13274
13286
  import { existsSync as existsSync4 } from "node:fs";
13275
13287
  import { readFile as readFile2, writeFile } from "node:fs/promises";
13276
13288
  import { platform as platform2 } from "node:os";
13277
- import { join as join4 } from "node:path";
13289
+ import { join as join5 } from "node:path";
13278
13290
  import * as lockfile2 from "proper-lockfile";
13279
13291
 
13280
13292
  // src/privileged/launch.ts
13281
13293
  import { spawn as spawn2, spawnSync } from "node:child_process";
13282
13294
  import { randomBytes } from "node:crypto";
13283
- import { platform } from "node:os";
13295
+ import { readFileSync as readFileSync3, rmSync } from "node:fs";
13296
+ import { platform, tmpdir } from "node:os";
13297
+ import { join as join4 } from "node:path";
13284
13298
  import process6 from "node:process";
13285
13299
 
13286
13300
  // src/privileged/client.ts
@@ -13344,7 +13358,7 @@ async function connectClient(options) {
13344
13358
  } catch (error) {
13345
13359
  lastError = error;
13346
13360
  const code = lastError.code;
13347
- if (code === "EACCES" || lastError instanceof HelperConnectionError)
13361
+ if (code === "EACCES" || code === "EPERM" || lastError instanceof HelperConnectionError)
13348
13362
  throw lastError;
13349
13363
  await new Promise((resolve2) => setTimeout(resolve2, retryIntervalMs));
13350
13364
  }
@@ -13475,39 +13489,78 @@ function createClient(socket, initialBuffer, callTimeoutMs) {
13475
13489
 
13476
13490
  // src/privileged/windows-elevation.ts
13477
13491
  import { spawn } from "node:child_process";
13492
+ var ERROR_CANCELLED = 1223;
13478
13493
  function quotePowerShell(value2) {
13479
13494
  return `'${value2.replace(/'/g, "''")}'`;
13480
13495
  }
13496
+ function quoteWindowsArg(arg) {
13497
+ if (arg === "")
13498
+ return '""';
13499
+ if (!/[\s"]/.test(arg))
13500
+ return arg;
13501
+ let quoted = '"';
13502
+ let backslashes = 0;
13503
+ for (const char of arg) {
13504
+ if (char === "\\") {
13505
+ backslashes++;
13506
+ continue;
13507
+ }
13508
+ quoted += char === '"' ? `${"\\".repeat(backslashes * 2 + 1)}"` : `${"\\".repeat(backslashes)}${char}`;
13509
+ backslashes = 0;
13510
+ }
13511
+ return `${quoted}${"\\".repeat(backslashes * 2)}"`;
13512
+ }
13481
13513
  function buildElevationCommand(options) {
13482
- const argumentList = options.args.map(quotePowerShell).join(",");
13483
- const parts = [
13484
- "Start-Process",
13485
- "-FilePath",
13486
- quotePowerShell(options.file)
13514
+ const lines = [
13515
+ // The message read back on failure is localized; keep it readable as UTF-8.
13516
+ "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8",
13517
+ "$psi = New-Object System.Diagnostics.ProcessStartInfo",
13518
+ `$psi.FileName = ${quotePowerShell(options.file)}`,
13519
+ `$psi.Arguments = ${quotePowerShell(options.args.map(quoteWindowsArg).join(" "))}`
13487
13520
  ];
13488
- if (argumentList)
13489
- parts.push("-ArgumentList", argumentList);
13490
13521
  if (options.cwd)
13491
- parts.push("-WorkingDirectory", quotePowerShell(options.cwd));
13492
- parts.push("-Verb", "RunAs");
13493
- parts.push("-WindowStyle", "Hidden");
13494
- return parts.join(" ");
13522
+ lines.push(`$psi.WorkingDirectory = ${quotePowerShell(options.cwd)}`);
13523
+ lines.push(
13524
+ "$psi.Verb = 'runas'",
13525
+ "$psi.UseShellExecute = $true",
13526
+ "$psi.WindowStyle = 'Hidden'",
13527
+ "try { $p = [System.Diagnostics.Process]::Start($psi); if ($p) { [Console]::Out.Write($p.Id) } }",
13528
+ `catch { $e = $_.Exception; while ($e.InnerException) { $e = $e.InnerException }; if ($e.NativeErrorCode -eq ${ERROR_CANCELLED}) { exit ${ERROR_CANCELLED} }; [Console]::Error.Write($e.Message); exit 1 }`
13529
+ );
13530
+ return lines.join("\n");
13495
13531
  }
13496
13532
  function spawnElevatedOnWindows(options) {
13497
- return new Promise((resolve2, reject2) => {
13498
- const script = buildElevationCommand(options);
13533
+ return new Promise((resolve2) => {
13499
13534
  const child = spawn(
13500
13535
  "powershell.exe",
13501
- ["-NoProfile", "-NonInteractive", "-Command", script],
13502
- { stdio: "ignore", windowsHide: true }
13536
+ ["-NoProfile", "-NonInteractive", "-Command", buildElevationCommand(options)],
13537
+ { stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
13503
13538
  );
13504
- child.once("error", reject2);
13505
- child.once("exit", (code) => {
13506
- if (code === 0)
13507
- return resolve2(child);
13508
- reject2(new Error(
13509
- `administrator permission was not granted (PowerShell exited with ${code}). Accept the UAC prompt to let the plugin edit the hosts file and bind ports 80/443.`
13510
- ));
13539
+ let stdout = "";
13540
+ let stderr = "";
13541
+ child.stdout.on("data", (data) => {
13542
+ stdout += data.toString();
13543
+ });
13544
+ child.stderr.on("data", (data) => {
13545
+ stderr = (stderr + data.toString()).slice(-4096);
13546
+ });
13547
+ child.once("error", (error) => resolve2({
13548
+ ok: false,
13549
+ denied: false,
13550
+ message: `could not start PowerShell to request administrator permission: ${error.message}`
13551
+ }));
13552
+ child.once("close", (code) => {
13553
+ if (code === 0) {
13554
+ const pid = Number(stdout.trim());
13555
+ return resolve2({ ok: true, pid: Number.isSafeInteger(pid) && pid > 0 ? pid : void 0 });
13556
+ }
13557
+ if (code === ERROR_CANCELLED)
13558
+ return resolve2({ ok: false, denied: true, message: "administrator permission was cancelled" });
13559
+ resolve2({
13560
+ ok: false,
13561
+ denied: false,
13562
+ message: `could not start the privileged helper as administrator (PowerShell exited with ${code}).${stderr.trim() ? ` ${stderr.trim()}` : ""}`
13563
+ });
13511
13564
  });
13512
13565
  });
13513
13566
  }
@@ -13634,11 +13687,22 @@ async function startPrivilegedHelper(options) {
13634
13687
  "--caddy",
13635
13688
  options.caddyBin,
13636
13689
  "--caddy-config",
13637
- options.caddyConfigPath
13690
+ options.caddyConfigPath,
13691
+ ...options.caddyAdminSocket ? ["--caddy-admin", options.caddyAdminSocket] : []
13638
13692
  ];
13639
13693
  let child;
13694
+ let helperExited;
13640
13695
  if (!direct && platform() === "win32") {
13641
- await spawnElevatedOnWindows({ file: helperEntry, args: childArgv, cwd: process6.cwd() });
13696
+ const errorFile = join4(tmpdir(), `uhrp-helper-${randomBytes(6).toString("hex")}.log`);
13697
+ const elevated = await spawnElevatedOnWindows({
13698
+ file: helperEntry,
13699
+ args: [...childArgv, "--error-file", errorFile],
13700
+ cwd: process6.cwd()
13701
+ });
13702
+ if (!elevated.ok)
13703
+ throw elevated.denied ? new PrivilegeDeniedError(elevated.message) : new Error(elevated.message);
13704
+ if (elevated.pid !== void 0)
13705
+ helperExited = watchWindowsHelper(elevated.pid, errorFile);
13642
13706
  } else {
13643
13707
  const command = direct ? helperEntry : sudoCommand;
13644
13708
  const spawnArgs = direct ? childArgv : ["-n", "env", ...forwardedArgs, helperEntry, ...childArgv];
@@ -13646,20 +13710,36 @@ async function startPrivilegedHelper(options) {
13646
13710
  stdio: ["ignore", "pipe", "pipe"]
13647
13711
  });
13648
13712
  (_a4 = child.stdout) == null ? void 0 : _a4.on("data", (data) => log == null ? void 0 : log(data.toString().trimEnd()));
13649
- (_b3 = child.stderr) == null ? void 0 : _b3.on("data", (data) => log == null ? void 0 : log(data.toString().trimEnd()));
13650
- const exited = new Promise((resolve2) => child.once("exit", (code) => resolve2(code)));
13713
+ let stderr = "";
13714
+ (_b3 = child.stderr) == null ? void 0 : _b3.on("data", (data) => {
13715
+ stderr = (stderr + data.toString()).slice(-4096);
13716
+ log == null ? void 0 : log(data.toString().trimEnd());
13717
+ });
13718
+ const exited = new Promise((resolve2) => {
13719
+ child.once("error", (error) => {
13720
+ stderr = error.message;
13721
+ });
13722
+ child.once("close", (code) => resolve2(code));
13723
+ });
13651
13724
  const earlyExit = await Promise.race([
13652
13725
  exited,
13653
13726
  new Promise((resolve2) => setTimeout(() => resolve2(void 0), 500))
13654
13727
  ]);
13655
13728
  if (earlyExit !== void 0 && earlyExit !== 0) {
13656
- throw new Error(
13657
- `privileged helper exited with code ${earlyExit}. Administrator permission was refused, or sudo is not available.`
13658
- );
13729
+ const detail = stderr.trim();
13730
+ let guidance = "";
13731
+ if (/\b(?:EACCES|EPERM)\b/.test(detail))
13732
+ guidance = " Check the path named above and its parent directories. Fix ownership or access manually; do not use chmod 777.";
13733
+ else if (!direct && /^sudo:/m.test(detail))
13734
+ guidance = " Retry from a terminal where sudo can request permission, or ask an administrator to grant access.";
13735
+ throw new Error(`privileged helper exited with code ${earlyExit}.${detail ? ` ${detail}${guidance}` : " No diagnostic output from the helper or sudo."}`);
13659
13736
  }
13660
13737
  }
13661
13738
  try {
13662
- const client = await connectClient({ socketPath, token, timeoutMs: connectTimeoutMs });
13739
+ const connecting = connectClient({ socketPath, token, timeoutMs: connectTimeoutMs });
13740
+ connecting.catch(() => {
13741
+ });
13742
+ const client = await (helperExited ? Promise.race([connecting, helperExited.promise]) : connecting);
13663
13743
  return {
13664
13744
  client,
13665
13745
  async close() {
@@ -13674,6 +13754,42 @@ async function startPrivilegedHelper(options) {
13674
13754
  } catch {
13675
13755
  }
13676
13756
  throw error;
13757
+ } finally {
13758
+ helperExited == null ? void 0 : helperExited.stop();
13759
+ }
13760
+ }
13761
+ function watchWindowsHelper(pid, errorFile) {
13762
+ let timer;
13763
+ const promise = new Promise((_, reject2) => {
13764
+ timer = setInterval(() => {
13765
+ if (isProcessRunning(pid))
13766
+ return;
13767
+ clearInterval(timer);
13768
+ let detail = "";
13769
+ try {
13770
+ detail = readFileSync3(errorFile, "utf8").trim().slice(-4096);
13771
+ } catch {
13772
+ }
13773
+ reject2(new Error(`privileged helper exited before accepting connections.${detail ? ` ${detail}` : " No diagnostic output from the helper."}`));
13774
+ }, 250);
13775
+ });
13776
+ return {
13777
+ promise,
13778
+ stop() {
13779
+ clearInterval(timer);
13780
+ try {
13781
+ rmSync(errorFile, { force: true });
13782
+ } catch {
13783
+ }
13784
+ }
13785
+ };
13786
+ }
13787
+ function isProcessRunning(pid) {
13788
+ try {
13789
+ process6.kill(pid, 0);
13790
+ return true;
13791
+ } catch (error) {
13792
+ return error.code !== "ESRCH";
13677
13793
  }
13678
13794
  }
13679
13795
  async function connectExistingHelper(socketPath, token, timeoutMs = 1500) {
@@ -13686,12 +13802,12 @@ async function connectExistingHelper(socketPath, token, timeoutMs = 1500) {
13686
13802
 
13687
13803
  // src/privileged/session.ts
13688
13804
  function tokenPath(runtimeDir) {
13689
- return join4(runtimeDir, "helper.token");
13805
+ return join5(runtimeDir, "helper.token");
13690
13806
  }
13691
13807
  function sessionSocketPath(runtimeDir) {
13692
13808
  if (platform2() === "win32")
13693
13809
  return `\\\\.\\pipe\\uhrp-${Buffer.from(runtimeDir).toString("hex").slice(0, 40)}`;
13694
- return join4(runtimeDir, "helper.sock");
13810
+ return join5(runtimeDir, "helper.sock");
13695
13811
  }
13696
13812
  async function openHelperSession(scope2) {
13697
13813
  const socketPath = sessionSocketPath(scope2.runtimeDir);
@@ -13736,6 +13852,7 @@ async function startNew(socketPath, scope2) {
13736
13852
  caddyStoragePath: scope2.caddyStoragePath,
13737
13853
  caddyBin: scope2.caddyBin,
13738
13854
  caddyConfigPath: scope2.caddyConfigPath,
13855
+ caddyAdminSocket: scope2.caddyAdminSocket,
13739
13856
  reason: scope2.reason,
13740
13857
  log: scope2.log
13741
13858
  });
@@ -13749,7 +13866,7 @@ async function startNew(socketPath, scope2) {
13749
13866
  };
13750
13867
  }
13751
13868
  async function acquireStartLock(runtimeDir) {
13752
- const lockPath = join4(runtimeDir, "helper.start.lock");
13869
+ const lockPath = join5(runtimeDir, "helper.start.lock");
13753
13870
  try {
13754
13871
  await writeFile(lockPath, "", { flag: "a" });
13755
13872
  } catch {
@@ -13822,7 +13939,7 @@ var HelperCaddyProcess = class extends EventEmitter {
13822
13939
  }
13823
13940
  };
13824
13941
  function caddyStoragePath() {
13825
- return process7.platform === "win32" ? join5(process7.env.AppData ?? "", "Caddy") : join5(process7.env.HOME ?? "", "Library/Application Support/Caddy");
13942
+ return process7.platform === "win32" ? join6(process7.env.AppData ?? "", "Caddy") : join6(process7.env.HOME ?? "", "Library/Application Support/Caddy");
13826
13943
  }
13827
13944
  function openPrivilegedSession(runtimeDir, options) {
13828
13945
  const env2 = resolvePrivilegedEnv();
@@ -13838,6 +13955,7 @@ function openPrivilegedSession(runtimeDir, options) {
13838
13955
  // execute a path supplied over the socket.
13839
13956
  caddyBin: options.caddyBin,
13840
13957
  caddyConfigPath: options.caddyConfigPath,
13958
+ caddyAdminSocket: options.caddyAdminSocket,
13841
13959
  reason: options.reason,
13842
13960
  log: options.log
13843
13961
  });
@@ -14020,10 +14138,27 @@ function testCaddy() {
14020
14138
  });
14021
14139
  });
14022
14140
  }
14141
+ function caddyRootPath() {
14142
+ return join7(
14143
+ process8.platform === "win32" ? `${process8.env.AppData}/Caddy` : `${process8.env.HOME}/Library/Application Support/Caddy`,
14144
+ "./pki/authorities/local"
14145
+ );
14146
+ }
14147
+ async function renderCaddyfile(proxies) {
14148
+ const ctx = validateTemplateContext({
14149
+ caddy_root: caddyRootPath(),
14150
+ admin_socket: caddyAdminSocketPath,
14151
+ proxies: Object.values(proxies)
14152
+ });
14153
+ const content = await genCaddyfile(ctx);
14154
+ const temp = `${caddyFilePath}.${process8.pid}.tmp`;
14155
+ await writeFile2(temp, content);
14156
+ await rename(temp, caddyFilePath);
14157
+ }
14023
14158
  var caddyConfig;
14024
14159
  function getCaddyConfig() {
14025
14160
  if (!caddyConfig) {
14026
- caddyConfig = useCaddyConfig();
14161
+ caddyConfig = useCaddyConfig({ renderCaddyfile });
14027
14162
  }
14028
14163
  return caddyConfig;
14029
14164
  }
@@ -14045,6 +14180,7 @@ var defaultDependencies = {
14045
14180
  // helper must never execute something named in a request.
14046
14181
  caddyBin: caddyPath,
14047
14182
  caddyConfigPath: caddyFilePath,
14183
+ caddyAdminSocket: caddyAdminSocketPath,
14048
14184
  reason
14049
14185
  }),
14050
14186
  config: () => getCaddyConfig()
@@ -14066,8 +14202,10 @@ var CaddyInstant = class {
14066
14202
  async session(reason) {
14067
14203
  if (this._session && !this._session.client.connected)
14068
14204
  this._session = void 0;
14069
- if (!this._session)
14205
+ if (!this._session) {
14206
+ await this.deps.config().writeCaddyConfig([], this.proxyKey);
14070
14207
  this._session = await this.deps.openSession(TEMP_DIR, reason);
14208
+ }
14071
14209
  return this._session;
14072
14210
  }
14073
14211
  async getCaddyfile() {
@@ -14079,10 +14217,7 @@ var CaddyInstant = class {
14079
14217
  return this.caddyfile;
14080
14218
  }
14081
14219
  get caddyRoot() {
14082
- return join6(
14083
- process8.platform === "win32" ? `${process8.env.AppData}/Caddy` : `${process8.env.HOME}/Library/Application Support/Caddy`,
14084
- "./pki/authorities/local"
14085
- );
14220
+ return caddyRootPath();
14086
14221
  }
14087
14222
  async writeCaddyfile() {
14088
14223
  return await writeFile2(caddyFilePath, this.caddyfile || "");
@@ -14126,40 +14261,6 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14126
14261
  if (!health.healthy)
14127
14262
  throw new Error(formatTlsHealthFailure(targetHost, health));
14128
14263
  }
14129
- /**
14130
- * Regenerates the Caddyfile from the config on disk.
14131
- *
14132
- * Reading the file rather than a cached view matters here: another project
14133
- * may have added its route since this instance last looked.
14134
- */
14135
- async updateCaddyfile() {
14136
- const { readProxies } = this.deps.config();
14137
- const proxies = Object.values(readProxies());
14138
- const ctx = validateTemplateContext({
14139
- caddy_root: this.caddyRoot,
14140
- proxies
14141
- });
14142
- this.caddyfile = await genCaddyfile(ctx);
14143
- await this.writeCaddyfile();
14144
- }
14145
- async stopCaddy() {
14146
- var _a4;
14147
- try {
14148
- await got.post("http://127.0.0.1:2019/stop", {
14149
- headers: {
14150
- Origin: "http://localhost:2019"
14151
- },
14152
- retry: {
14153
- limit: 0
14154
- },
14155
- timeout: {
14156
- request: 2e3
14157
- }
14158
- });
14159
- } catch {
14160
- }
14161
- (_a4 = this._caddyChild) == null ? void 0 : _a4.kill();
14162
- }
14163
14264
  /**
14164
14265
  * @param source like `127.0.0.1:8080`
14165
14266
  * @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
@@ -14204,7 +14305,6 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14204
14305
  ];
14205
14306
  const { writeCaddyConfig } = this.deps.config();
14206
14307
  await writeCaddyConfig(proxies, this.proxyKey);
14207
- await this.updateCaddyfile();
14208
14308
  await session.client.call("port.free", { port: 443 });
14209
14309
  if (process8.platform === "win32" || !https)
14210
14310
  await session.client.call("port.free", { port: 80 });
@@ -14431,6 +14531,8 @@ var unpluginFactory = (options) => ({
14431
14531
  return;
14432
14532
  }
14433
14533
  const _printUrls = server.printUrls.bind(server);
14534
+ if (server.config.server.middlewareMode)
14535
+ consola.warn("Vite runs in middleware mode, so the reverse proxy cannot start from the Vite plugin. In Nuxt, add `unplugin-https-reverse-proxy/nuxt` to `modules` instead.");
14434
14536
  let source = `localhost:${config.server.port || 5173}`;
14435
14537
  const url2 = (_a4 = server.resolvedUrls) == null ? void 0 : _a4.local[0];
14436
14538
  if (url2) {