unplugin-https-reverse-proxy 4.1.0-beta.9 → 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,21 +13154,22 @@ 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);
13161
+ renameSync(temp, path);
13151
13162
  }
13152
13163
  function useCaddyConfig(options = {}) {
13153
13164
  const lock3 = options.lock ?? createFileLock();
13165
+ const configPath = options.configPath ?? caddyConfigPath;
13154
13166
  async function mutate(apply) {
13155
13167
  var _a4;
13156
13168
  const release = await lock3.acquire();
13157
13169
  try {
13158
- const proxies = readConfig();
13170
+ const proxies = readConfig(configPath);
13159
13171
  apply(proxies);
13160
- writeConfig(proxies);
13172
+ writeConfig(proxies, configPath);
13161
13173
  await ((_a4 = options.renderCaddyfile) == null ? void 0 : _a4.call(options, proxies));
13162
13174
  return proxies;
13163
13175
  } finally {
@@ -13165,7 +13177,7 @@ function useCaddyConfig(options = {}) {
13165
13177
  }
13166
13178
  }
13167
13179
  return {
13168
- configJsonRef: () => existsSync2(caddyConfigPath) ? readConfig() : void 0,
13180
+ configJsonRef: () => existsSync2(configPath) ? readConfig(configPath) : void 0,
13169
13181
  async writeCaddyConfig(_proxies, key) {
13170
13182
  await mutate((proxies) => {
13171
13183
  for (const p of _proxies)
@@ -13173,25 +13185,23 @@ function useCaddyConfig(options = {}) {
13173
13185
  });
13174
13186
  },
13175
13187
  async removeProxy(key) {
13176
- const proxies = await mutate((current) => {
13188
+ await mutate((current) => {
13177
13189
  for (const route of Object.keys(current)) {
13178
13190
  if (route.endsWith(`#${key}`))
13179
13191
  delete current[route];
13180
13192
  }
13181
13193
  });
13182
- if (Object.keys(proxies).length === 0)
13183
- removeConfigFile();
13184
13194
  },
13185
- readProxies: () => readConfig(),
13195
+ readProxies: () => readConfig(configPath),
13186
13196
  async cleanUp() {
13187
- removeConfigFile();
13197
+ removeConfigFile(configPath);
13188
13198
  }
13189
13199
  };
13190
13200
  }
13191
- function removeConfigFile() {
13201
+ function removeConfigFile(path = caddyConfigPath) {
13192
13202
  try {
13193
- if (existsSync2(caddyConfigPath))
13194
- unlinkSync(caddyConfigPath);
13203
+ if (existsSync2(path))
13204
+ unlinkSync(path);
13195
13205
  } catch {
13196
13206
  }
13197
13207
  }
@@ -13237,7 +13247,7 @@ function isCaddyReloadCancellation(line) {
13237
13247
  // src/caddy/privileged.ts
13238
13248
  import { Buffer as Buffer2 } from "node:buffer";
13239
13249
  import { EventEmitter } from "node:events";
13240
- import { dirname as dirname3, join as join5 } from "node:path";
13250
+ import { dirname as dirname3, join as join6 } from "node:path";
13241
13251
  import process7 from "node:process";
13242
13252
  import { fileURLToPath } from "node:url";
13243
13253
 
@@ -13276,13 +13286,15 @@ import { Buffer } from "node:buffer";
13276
13286
  import { existsSync as existsSync4 } from "node:fs";
13277
13287
  import { readFile as readFile2, writeFile } from "node:fs/promises";
13278
13288
  import { platform as platform2 } from "node:os";
13279
- import { join as join4 } from "node:path";
13289
+ import { join as join5 } from "node:path";
13280
13290
  import * as lockfile2 from "proper-lockfile";
13281
13291
 
13282
13292
  // src/privileged/launch.ts
13283
13293
  import { spawn as spawn2, spawnSync } from "node:child_process";
13284
13294
  import { randomBytes } from "node:crypto";
13285
- 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";
13286
13298
  import process6 from "node:process";
13287
13299
 
13288
13300
  // src/privileged/client.ts
@@ -13346,7 +13358,7 @@ async function connectClient(options) {
13346
13358
  } catch (error) {
13347
13359
  lastError = error;
13348
13360
  const code = lastError.code;
13349
- if (code === "EACCES" || lastError instanceof HelperConnectionError)
13361
+ if (code === "EACCES" || code === "EPERM" || lastError instanceof HelperConnectionError)
13350
13362
  throw lastError;
13351
13363
  await new Promise((resolve2) => setTimeout(resolve2, retryIntervalMs));
13352
13364
  }
@@ -13477,39 +13489,78 @@ function createClient(socket, initialBuffer, callTimeoutMs) {
13477
13489
 
13478
13490
  // src/privileged/windows-elevation.ts
13479
13491
  import { spawn } from "node:child_process";
13492
+ var ERROR_CANCELLED = 1223;
13480
13493
  function quotePowerShell(value2) {
13481
13494
  return `'${value2.replace(/'/g, "''")}'`;
13482
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
+ }
13483
13513
  function buildElevationCommand(options) {
13484
- const argumentList = options.args.map(quotePowerShell).join(",");
13485
- const parts = [
13486
- "Start-Process",
13487
- "-FilePath",
13488
- 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(" "))}`
13489
13520
  ];
13490
- if (argumentList)
13491
- parts.push("-ArgumentList", argumentList);
13492
13521
  if (options.cwd)
13493
- parts.push("-WorkingDirectory", quotePowerShell(options.cwd));
13494
- parts.push("-Verb", "RunAs");
13495
- parts.push("-WindowStyle", "Hidden");
13496
- 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");
13497
13531
  }
13498
13532
  function spawnElevatedOnWindows(options) {
13499
- return new Promise((resolve2, reject2) => {
13500
- const script = buildElevationCommand(options);
13533
+ return new Promise((resolve2) => {
13501
13534
  const child = spawn(
13502
13535
  "powershell.exe",
13503
- ["-NoProfile", "-NonInteractive", "-Command", script],
13504
- { stdio: "ignore", windowsHide: true }
13536
+ ["-NoProfile", "-NonInteractive", "-Command", buildElevationCommand(options)],
13537
+ { stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
13505
13538
  );
13506
- child.once("error", reject2);
13507
- child.once("exit", (code) => {
13508
- if (code === 0)
13509
- return resolve2(child);
13510
- reject2(new Error(
13511
- `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.`
13512
- ));
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
+ });
13513
13564
  });
13514
13565
  });
13515
13566
  }
@@ -13636,11 +13687,22 @@ async function startPrivilegedHelper(options) {
13636
13687
  "--caddy",
13637
13688
  options.caddyBin,
13638
13689
  "--caddy-config",
13639
- options.caddyConfigPath
13690
+ options.caddyConfigPath,
13691
+ ...options.caddyAdminSocket ? ["--caddy-admin", options.caddyAdminSocket] : []
13640
13692
  ];
13641
13693
  let child;
13694
+ let helperExited;
13642
13695
  if (!direct && platform() === "win32") {
13643
- 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);
13644
13706
  } else {
13645
13707
  const command = direct ? helperEntry : sudoCommand;
13646
13708
  const spawnArgs = direct ? childArgv : ["-n", "env", ...forwardedArgs, helperEntry, ...childArgv];
@@ -13648,20 +13710,36 @@ async function startPrivilegedHelper(options) {
13648
13710
  stdio: ["ignore", "pipe", "pipe"]
13649
13711
  });
13650
13712
  (_a4 = child.stdout) == null ? void 0 : _a4.on("data", (data) => log == null ? void 0 : log(data.toString().trimEnd()));
13651
- (_b3 = child.stderr) == null ? void 0 : _b3.on("data", (data) => log == null ? void 0 : log(data.toString().trimEnd()));
13652
- 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
+ });
13653
13724
  const earlyExit = await Promise.race([
13654
13725
  exited,
13655
13726
  new Promise((resolve2) => setTimeout(() => resolve2(void 0), 500))
13656
13727
  ]);
13657
13728
  if (earlyExit !== void 0 && earlyExit !== 0) {
13658
- throw new Error(
13659
- `privileged helper exited with code ${earlyExit}. Administrator permission was refused, or sudo is not available.`
13660
- );
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."}`);
13661
13736
  }
13662
13737
  }
13663
13738
  try {
13664
- 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);
13665
13743
  return {
13666
13744
  client,
13667
13745
  async close() {
@@ -13676,6 +13754,42 @@ async function startPrivilegedHelper(options) {
13676
13754
  } catch {
13677
13755
  }
13678
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";
13679
13793
  }
13680
13794
  }
13681
13795
  async function connectExistingHelper(socketPath, token, timeoutMs = 1500) {
@@ -13688,12 +13802,12 @@ async function connectExistingHelper(socketPath, token, timeoutMs = 1500) {
13688
13802
 
13689
13803
  // src/privileged/session.ts
13690
13804
  function tokenPath(runtimeDir) {
13691
- return join4(runtimeDir, "helper.token");
13805
+ return join5(runtimeDir, "helper.token");
13692
13806
  }
13693
13807
  function sessionSocketPath(runtimeDir) {
13694
13808
  if (platform2() === "win32")
13695
13809
  return `\\\\.\\pipe\\uhrp-${Buffer.from(runtimeDir).toString("hex").slice(0, 40)}`;
13696
- return join4(runtimeDir, "helper.sock");
13810
+ return join5(runtimeDir, "helper.sock");
13697
13811
  }
13698
13812
  async function openHelperSession(scope2) {
13699
13813
  const socketPath = sessionSocketPath(scope2.runtimeDir);
@@ -13738,6 +13852,7 @@ async function startNew(socketPath, scope2) {
13738
13852
  caddyStoragePath: scope2.caddyStoragePath,
13739
13853
  caddyBin: scope2.caddyBin,
13740
13854
  caddyConfigPath: scope2.caddyConfigPath,
13855
+ caddyAdminSocket: scope2.caddyAdminSocket,
13741
13856
  reason: scope2.reason,
13742
13857
  log: scope2.log
13743
13858
  });
@@ -13751,7 +13866,7 @@ async function startNew(socketPath, scope2) {
13751
13866
  };
13752
13867
  }
13753
13868
  async function acquireStartLock(runtimeDir) {
13754
- const lockPath = join4(runtimeDir, "helper.start.lock");
13869
+ const lockPath = join5(runtimeDir, "helper.start.lock");
13755
13870
  try {
13756
13871
  await writeFile(lockPath, "", { flag: "a" });
13757
13872
  } catch {
@@ -13824,7 +13939,7 @@ var HelperCaddyProcess = class extends EventEmitter {
13824
13939
  }
13825
13940
  };
13826
13941
  function caddyStoragePath() {
13827
- 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");
13828
13943
  }
13829
13944
  function openPrivilegedSession(runtimeDir, options) {
13830
13945
  const env2 = resolvePrivilegedEnv();
@@ -13840,6 +13955,7 @@ function openPrivilegedSession(runtimeDir, options) {
13840
13955
  // execute a path supplied over the socket.
13841
13956
  caddyBin: options.caddyBin,
13842
13957
  caddyConfigPath: options.caddyConfigPath,
13958
+ caddyAdminSocket: options.caddyAdminSocket,
13843
13959
  reason: options.reason,
13844
13960
  log: options.log
13845
13961
  });
@@ -14023,7 +14139,7 @@ function testCaddy() {
14023
14139
  });
14024
14140
  }
14025
14141
  function caddyRootPath() {
14026
- return join6(
14142
+ return join7(
14027
14143
  process8.platform === "win32" ? `${process8.env.AppData}/Caddy` : `${process8.env.HOME}/Library/Application Support/Caddy`,
14028
14144
  "./pki/authorities/local"
14029
14145
  );
@@ -14031,9 +14147,13 @@ function caddyRootPath() {
14031
14147
  async function renderCaddyfile(proxies) {
14032
14148
  const ctx = validateTemplateContext({
14033
14149
  caddy_root: caddyRootPath(),
14150
+ admin_socket: caddyAdminSocketPath,
14034
14151
  proxies: Object.values(proxies)
14035
14152
  });
14036
- await writeFile2(caddyFilePath, await genCaddyfile(ctx));
14153
+ const content = await genCaddyfile(ctx);
14154
+ const temp = `${caddyFilePath}.${process8.pid}.tmp`;
14155
+ await writeFile2(temp, content);
14156
+ await rename(temp, caddyFilePath);
14037
14157
  }
14038
14158
  var caddyConfig;
14039
14159
  function getCaddyConfig() {
@@ -14060,6 +14180,7 @@ var defaultDependencies = {
14060
14180
  // helper must never execute something named in a request.
14061
14181
  caddyBin: caddyPath,
14062
14182
  caddyConfigPath: caddyFilePath,
14183
+ caddyAdminSocket: caddyAdminSocketPath,
14063
14184
  reason
14064
14185
  }),
14065
14186
  config: () => getCaddyConfig()
@@ -14081,8 +14202,10 @@ var CaddyInstant = class {
14081
14202
  async session(reason) {
14082
14203
  if (this._session && !this._session.client.connected)
14083
14204
  this._session = void 0;
14084
- if (!this._session)
14205
+ if (!this._session) {
14206
+ await this.deps.config().writeCaddyConfig([], this.proxyKey);
14085
14207
  this._session = await this.deps.openSession(TEMP_DIR, reason);
14208
+ }
14086
14209
  return this._session;
14087
14210
  }
14088
14211
  async getCaddyfile() {
@@ -14138,40 +14261,6 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14138
14261
  if (!health.healthy)
14139
14262
  throw new Error(formatTlsHealthFailure(targetHost, health));
14140
14263
  }
14141
- /**
14142
- * Regenerates the Caddyfile from the config on disk.
14143
- *
14144
- * Reading the file rather than a cached view matters here: another project
14145
- * may have added its route since this instance last looked.
14146
- */
14147
- async updateCaddyfile() {
14148
- const { readProxies } = this.deps.config();
14149
- const proxies = Object.values(readProxies());
14150
- const ctx = validateTemplateContext({
14151
- caddy_root: this.caddyRoot,
14152
- proxies
14153
- });
14154
- this.caddyfile = await genCaddyfile(ctx);
14155
- await this.writeCaddyfile();
14156
- }
14157
- async stopCaddy() {
14158
- var _a4;
14159
- try {
14160
- await got.post("http://127.0.0.1:2019/stop", {
14161
- headers: {
14162
- Origin: "http://localhost:2019"
14163
- },
14164
- retry: {
14165
- limit: 0
14166
- },
14167
- timeout: {
14168
- request: 2e3
14169
- }
14170
- });
14171
- } catch {
14172
- }
14173
- (_a4 = this._caddyChild) == null ? void 0 : _a4.kill();
14174
- }
14175
14264
  /**
14176
14265
  * @param source like `127.0.0.1:8080`
14177
14266
  * @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
@@ -14216,7 +14305,6 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14216
14305
  ];
14217
14306
  const { writeCaddyConfig } = this.deps.config();
14218
14307
  await writeCaddyConfig(proxies, this.proxyKey);
14219
- await this.updateCaddyfile();
14220
14308
  await session.client.call("port.free", { port: 443 });
14221
14309
  if (process8.platform === "win32" || !https)
14222
14310
  await session.client.call("port.free", { port: 80 });
@@ -14443,6 +14531,8 @@ var unpluginFactory = (options) => ({
14443
14531
  return;
14444
14532
  }
14445
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.");
14446
14536
  let source = `localhost:${config.server.port || 5173}`;
14447
14537
  const url2 = (_a4 = server.resolvedUrls) == null ? void 0 : _a4.local[0];
14448
14538
  if (url2) {