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/dist/vite.cjs CHANGED
@@ -43,10 +43,10 @@ var import_unplugin = require("unplugin");
43
43
 
44
44
  // src/caddy/index.ts
45
45
  var import_node_child_process3 = require("child_process");
46
- var import_node_fs4 = require("fs");
46
+ var import_node_fs5 = require("fs");
47
47
  var import_promises2 = require("fs/promises");
48
48
  var import_node_os5 = require("os");
49
- var import_node_path5 = require("path");
49
+ var import_node_path6 = require("path");
50
50
  var import_node_process8 = __toESM(require("process"), 1);
51
51
  var import_got_cjs = require("got-cjs");
52
52
  var import_http_proxy_agent = require("http-proxy-agent");
@@ -12939,6 +12939,7 @@ var ProxyType = type({
12939
12939
  });
12940
12940
  var CaddyContext = type({
12941
12941
  caddy_root: "string",
12942
+ admin_socket: "string",
12942
12943
  proxies: ProxyType.array()
12943
12944
  });
12944
12945
  function validateTemplateContext(ctx) {
@@ -12951,6 +12952,7 @@ var caddyTemplate = `{
12951
12952
  debug
12952
12953
  auto_https disable_redirects ignore_loaded_certs
12953
12954
  skip_install_trust
12955
+ admin unix/{{ admin_socket }}
12954
12956
  }
12955
12957
 
12956
12958
  :7601 {
@@ -13048,11 +13050,20 @@ function resolvePath(path) {
13048
13050
  return (0, import_node_path.join)(import_node_os2.default.homedir() || "", path.slice(1));
13049
13051
  return path;
13050
13052
  }
13051
- var TEMP_DIR = resolvePath(import_node_process.default.env.UHRP_CADDY_PATH || import_node_process.default.env.TEMP || import_node_process.default.env.TMPDIR || "/tmp");
13053
+ function defaultTempDir() {
13054
+ const fromEnv = import_node_process.default.env.TEMP || import_node_process.default.env.TMPDIR;
13055
+ if (fromEnv)
13056
+ return resolvePath(fromEnv);
13057
+ if (import_node_process.default.platform === "linux")
13058
+ return (0, import_node_path.join)(import_node_process.default.env.XDG_CACHE_HOME || (0, import_node_path.join)(import_node_os2.default.homedir(), ".cache"), "uhrp");
13059
+ return "/tmp";
13060
+ }
13061
+ var TEMP_DIR = resolvePath(import_node_process.default.env.UHRP_CADDY_PATH || defaultTempDir());
13052
13062
  var caddyPath = (0, import_node_path.join)(TEMP_DIR, `caddy${import_node_process.default.platform === "win32" ? ".exe" : ""}`);
13053
13063
  var caddyFilePath = (0, import_node_path.join)(TEMP_DIR, "CADDYFILE");
13054
13064
  var caddyConfigPath = (0, import_node_path.join)(TEMP_DIR, ".CADDYFILE.config.json");
13055
13065
  var caddyLockFilePath = (0, import_node_path.join)(TEMP_DIR, "caddylock");
13066
+ var caddyAdminSocketPath = (0, import_node_path.join)(TEMP_DIR, "caddy-admin.sock");
13056
13067
  var supportList = [
13057
13068
  {
13058
13069
  platform: "dragonfly",
@@ -13175,12 +13186,12 @@ function isAlive(pid) {
13175
13186
  return false;
13176
13187
  }
13177
13188
  }
13178
- function readConfig() {
13179
- if (!(0, import_node_fs.existsSync)(caddyConfigPath))
13189
+ function readConfig(path = caddyConfigPath) {
13190
+ if (!(0, import_node_fs.existsSync)(path))
13180
13191
  return {};
13181
13192
  let parsed2;
13182
13193
  try {
13183
- parsed2 = JSON.parse((0, import_node_fs.readFileSync)(caddyConfigPath, "utf-8"));
13194
+ parsed2 = JSON.parse((0, import_node_fs.readFileSync)(path, "utf-8"));
13184
13195
  } catch {
13185
13196
  return {};
13186
13197
  }
@@ -13191,53 +13202,54 @@ function readConfig() {
13191
13202
  }
13192
13203
  return alive;
13193
13204
  }
13194
- function writeConfig(proxies) {
13205
+ function writeConfig(proxies, path = caddyConfigPath) {
13195
13206
  const content = JSON.stringify(proxies, null, 2);
13196
- const temp = `${caddyConfigPath}.${import_node_process2.default.pid}.tmp`;
13207
+ const temp = `${path}.${import_node_process2.default.pid}.tmp`;
13197
13208
  (0, import_node_fs.writeFileSync)(temp, content);
13198
- (0, import_node_fs.renameSync)(temp, caddyConfigPath);
13199
- }
13200
- async function mutateConfig(lock3, mutate) {
13201
- const release = await lock3.acquire();
13202
- try {
13203
- const proxies = readConfig();
13204
- mutate(proxies);
13205
- writeConfig(proxies);
13206
- return proxies;
13207
- } finally {
13208
- release();
13209
- }
13209
+ (0, import_node_fs.renameSync)(temp, path);
13210
13210
  }
13211
13211
  function useCaddyConfig(options = {}) {
13212
13212
  const lock3 = options.lock ?? createFileLock();
13213
+ const configPath = options.configPath ?? caddyConfigPath;
13214
+ async function mutate(apply) {
13215
+ var _a4;
13216
+ const release = await lock3.acquire();
13217
+ try {
13218
+ const proxies = readConfig(configPath);
13219
+ apply(proxies);
13220
+ writeConfig(proxies, configPath);
13221
+ await ((_a4 = options.renderCaddyfile) == null ? void 0 : _a4.call(options, proxies));
13222
+ return proxies;
13223
+ } finally {
13224
+ release();
13225
+ }
13226
+ }
13213
13227
  return {
13214
- configJsonRef: () => (0, import_node_fs.existsSync)(caddyConfigPath) ? readConfig() : void 0,
13228
+ configJsonRef: () => (0, import_node_fs.existsSync)(configPath) ? readConfig(configPath) : void 0,
13215
13229
  async writeCaddyConfig(_proxies, key) {
13216
- await mutateConfig(lock3, (proxies) => {
13230
+ await mutate((proxies) => {
13217
13231
  for (const p of _proxies)
13218
13232
  proxies[routeKey(p, key)] = { ...p, base: normalizeBase(p.base), ownerPid: import_node_process2.default.pid };
13219
13233
  });
13220
13234
  },
13221
13235
  async removeProxy(key) {
13222
- const proxies = await mutateConfig(lock3, (current) => {
13236
+ await mutate((current) => {
13223
13237
  for (const route of Object.keys(current)) {
13224
13238
  if (route.endsWith(`#${key}`))
13225
13239
  delete current[route];
13226
13240
  }
13227
13241
  });
13228
- if (Object.keys(proxies).length === 0)
13229
- removeConfigFile();
13230
13242
  },
13231
- readProxies: () => readConfig(),
13243
+ readProxies: () => readConfig(configPath),
13232
13244
  async cleanUp() {
13233
- removeConfigFile();
13245
+ removeConfigFile(configPath);
13234
13246
  }
13235
13247
  };
13236
13248
  }
13237
- function removeConfigFile() {
13249
+ function removeConfigFile(path = caddyConfigPath) {
13238
13250
  try {
13239
- if ((0, import_node_fs.existsSync)(caddyConfigPath))
13240
- (0, import_node_fs.unlinkSync)(caddyConfigPath);
13251
+ if ((0, import_node_fs.existsSync)(path))
13252
+ (0, import_node_fs.unlinkSync)(path);
13241
13253
  } catch {
13242
13254
  }
13243
13255
  }
@@ -13283,7 +13295,7 @@ function isCaddyReloadCancellation(line) {
13283
13295
  // src/caddy/privileged.ts
13284
13296
  var import_node_buffer2 = require("buffer");
13285
13297
  var import_node_events = require("events");
13286
- var import_node_path4 = require("path");
13298
+ var import_node_path5 = require("path");
13287
13299
  var import_node_process7 = __toESM(require("process"), 1);
13288
13300
  var import_node_url = require("url");
13289
13301
 
@@ -13319,16 +13331,18 @@ function findUp(from, relative, exists2) {
13319
13331
 
13320
13332
  // src/privileged/session.ts
13321
13333
  var import_node_buffer = require("buffer");
13322
- var import_node_fs3 = require("fs");
13334
+ var import_node_fs4 = require("fs");
13323
13335
  var import_promises = require("fs/promises");
13324
13336
  var import_node_os4 = require("os");
13325
- var import_node_path3 = require("path");
13337
+ var import_node_path4 = require("path");
13326
13338
  var lockfile2 = __toESM(require("proper-lockfile"), 1);
13327
13339
 
13328
13340
  // src/privileged/launch.ts
13329
13341
  var import_node_child_process2 = require("child_process");
13330
13342
  var import_node_crypto = require("crypto");
13343
+ var import_node_fs3 = require("fs");
13331
13344
  var import_node_os3 = require("os");
13345
+ var import_node_path3 = require("path");
13332
13346
  var import_node_process6 = __toESM(require("process"), 1);
13333
13347
 
13334
13348
  // src/privileged/client.ts
@@ -13442,7 +13456,7 @@ async function connectClient(options) {
13442
13456
  } catch (error) {
13443
13457
  lastError = error;
13444
13458
  const code = lastError.code;
13445
- if (code === "EACCES" || lastError instanceof HelperConnectionError)
13459
+ if (code === "EACCES" || code === "EPERM" || lastError instanceof HelperConnectionError)
13446
13460
  throw lastError;
13447
13461
  await new Promise((resolve2) => setTimeout(resolve2, retryIntervalMs));
13448
13462
  }
@@ -13574,39 +13588,78 @@ function createClient(socket, initialBuffer, callTimeoutMs) {
13574
13588
  // src/privileged/windows-elevation.ts
13575
13589
  var import_node_child_process = require("child_process");
13576
13590
  var import_node_process5 = __toESM(require("process"), 1);
13591
+ var ERROR_CANCELLED = 1223;
13577
13592
  function quotePowerShell(value2) {
13578
13593
  return `'${value2.replace(/'/g, "''")}'`;
13579
13594
  }
13595
+ function quoteWindowsArg(arg) {
13596
+ if (arg === "")
13597
+ return '""';
13598
+ if (!/[\s"]/.test(arg))
13599
+ return arg;
13600
+ let quoted = '"';
13601
+ let backslashes = 0;
13602
+ for (const char of arg) {
13603
+ if (char === "\\") {
13604
+ backslashes++;
13605
+ continue;
13606
+ }
13607
+ quoted += char === '"' ? `${"\\".repeat(backslashes * 2 + 1)}"` : `${"\\".repeat(backslashes)}${char}`;
13608
+ backslashes = 0;
13609
+ }
13610
+ return `${quoted}${"\\".repeat(backslashes * 2)}"`;
13611
+ }
13580
13612
  function buildElevationCommand(options) {
13581
- const argumentList = options.args.map(quotePowerShell).join(",");
13582
- const parts = [
13583
- "Start-Process",
13584
- "-FilePath",
13585
- quotePowerShell(options.file)
13613
+ const lines = [
13614
+ // The message read back on failure is localized; keep it readable as UTF-8.
13615
+ "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8",
13616
+ "$psi = New-Object System.Diagnostics.ProcessStartInfo",
13617
+ `$psi.FileName = ${quotePowerShell(options.file)}`,
13618
+ `$psi.Arguments = ${quotePowerShell(options.args.map(quoteWindowsArg).join(" "))}`
13586
13619
  ];
13587
- if (argumentList)
13588
- parts.push("-ArgumentList", argumentList);
13589
13620
  if (options.cwd)
13590
- parts.push("-WorkingDirectory", quotePowerShell(options.cwd));
13591
- parts.push("-Verb", "RunAs");
13592
- parts.push("-WindowStyle", "Hidden");
13593
- return parts.join(" ");
13621
+ lines.push(`$psi.WorkingDirectory = ${quotePowerShell(options.cwd)}`);
13622
+ lines.push(
13623
+ "$psi.Verb = 'runas'",
13624
+ "$psi.UseShellExecute = $true",
13625
+ "$psi.WindowStyle = 'Hidden'",
13626
+ "try { $p = [System.Diagnostics.Process]::Start($psi); if ($p) { [Console]::Out.Write($p.Id) } }",
13627
+ `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 }`
13628
+ );
13629
+ return lines.join("\n");
13594
13630
  }
13595
13631
  function spawnElevatedOnWindows(options) {
13596
- return new Promise((resolve2, reject2) => {
13597
- const script = buildElevationCommand(options);
13632
+ return new Promise((resolve2) => {
13598
13633
  const child = (0, import_node_child_process.spawn)(
13599
13634
  "powershell.exe",
13600
- ["-NoProfile", "-NonInteractive", "-Command", script],
13601
- { stdio: "ignore", windowsHide: true }
13635
+ ["-NoProfile", "-NonInteractive", "-Command", buildElevationCommand(options)],
13636
+ { stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
13602
13637
  );
13603
- child.once("error", reject2);
13604
- child.once("exit", (code) => {
13605
- if (code === 0)
13606
- return resolve2(child);
13607
- reject2(new Error(
13608
- `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.`
13609
- ));
13638
+ let stdout = "";
13639
+ let stderr = "";
13640
+ child.stdout.on("data", (data) => {
13641
+ stdout += data.toString();
13642
+ });
13643
+ child.stderr.on("data", (data) => {
13644
+ stderr = (stderr + data.toString()).slice(-4096);
13645
+ });
13646
+ child.once("error", (error) => resolve2({
13647
+ ok: false,
13648
+ denied: false,
13649
+ message: `could not start PowerShell to request administrator permission: ${error.message}`
13650
+ }));
13651
+ child.once("close", (code) => {
13652
+ if (code === 0) {
13653
+ const pid = Number(stdout.trim());
13654
+ return resolve2({ ok: true, pid: Number.isSafeInteger(pid) && pid > 0 ? pid : void 0 });
13655
+ }
13656
+ if (code === ERROR_CANCELLED)
13657
+ return resolve2({ ok: false, denied: true, message: "administrator permission was cancelled" });
13658
+ resolve2({
13659
+ ok: false,
13660
+ denied: false,
13661
+ message: `could not start the privileged helper as administrator (PowerShell exited with ${code}).${stderr.trim() ? ` ${stderr.trim()}` : ""}`
13662
+ });
13610
13663
  });
13611
13664
  });
13612
13665
  }
@@ -13733,11 +13786,22 @@ async function startPrivilegedHelper(options) {
13733
13786
  "--caddy",
13734
13787
  options.caddyBin,
13735
13788
  "--caddy-config",
13736
- options.caddyConfigPath
13789
+ options.caddyConfigPath,
13790
+ ...options.caddyAdminSocket ? ["--caddy-admin", options.caddyAdminSocket] : []
13737
13791
  ];
13738
13792
  let child;
13793
+ let helperExited;
13739
13794
  if (!direct && (0, import_node_os3.platform)() === "win32") {
13740
- await spawnElevatedOnWindows({ file: helperEntry, args: childArgv, cwd: import_node_process6.default.cwd() });
13795
+ const errorFile = (0, import_node_path3.join)((0, import_node_os3.tmpdir)(), `uhrp-helper-${(0, import_node_crypto.randomBytes)(6).toString("hex")}.log`);
13796
+ const elevated = await spawnElevatedOnWindows({
13797
+ file: helperEntry,
13798
+ args: [...childArgv, "--error-file", errorFile],
13799
+ cwd: import_node_process6.default.cwd()
13800
+ });
13801
+ if (!elevated.ok)
13802
+ throw elevated.denied ? new PrivilegeDeniedError(elevated.message) : new Error(elevated.message);
13803
+ if (elevated.pid !== void 0)
13804
+ helperExited = watchWindowsHelper(elevated.pid, errorFile);
13741
13805
  } else {
13742
13806
  const command = direct ? helperEntry : sudoCommand;
13743
13807
  const spawnArgs = direct ? childArgv : ["-n", "env", ...forwardedArgs, helperEntry, ...childArgv];
@@ -13745,20 +13809,36 @@ async function startPrivilegedHelper(options) {
13745
13809
  stdio: ["ignore", "pipe", "pipe"]
13746
13810
  });
13747
13811
  (_a4 = child.stdout) == null ? void 0 : _a4.on("data", (data) => log == null ? void 0 : log(data.toString().trimEnd()));
13748
- (_b3 = child.stderr) == null ? void 0 : _b3.on("data", (data) => log == null ? void 0 : log(data.toString().trimEnd()));
13749
- const exited = new Promise((resolve2) => child.once("exit", (code) => resolve2(code)));
13812
+ let stderr = "";
13813
+ (_b3 = child.stderr) == null ? void 0 : _b3.on("data", (data) => {
13814
+ stderr = (stderr + data.toString()).slice(-4096);
13815
+ log == null ? void 0 : log(data.toString().trimEnd());
13816
+ });
13817
+ const exited = new Promise((resolve2) => {
13818
+ child.once("error", (error) => {
13819
+ stderr = error.message;
13820
+ });
13821
+ child.once("close", (code) => resolve2(code));
13822
+ });
13750
13823
  const earlyExit = await Promise.race([
13751
13824
  exited,
13752
13825
  new Promise((resolve2) => setTimeout(() => resolve2(void 0), 500))
13753
13826
  ]);
13754
13827
  if (earlyExit !== void 0 && earlyExit !== 0) {
13755
- throw new Error(
13756
- `privileged helper exited with code ${earlyExit}. Administrator permission was refused, or sudo is not available.`
13757
- );
13828
+ const detail = stderr.trim();
13829
+ let guidance = "";
13830
+ if (/\b(?:EACCES|EPERM)\b/.test(detail))
13831
+ guidance = " Check the path named above and its parent directories. Fix ownership or access manually; do not use chmod 777.";
13832
+ else if (!direct && /^sudo:/m.test(detail))
13833
+ guidance = " Retry from a terminal where sudo can request permission, or ask an administrator to grant access.";
13834
+ throw new Error(`privileged helper exited with code ${earlyExit}.${detail ? ` ${detail}${guidance}` : " No diagnostic output from the helper or sudo."}`);
13758
13835
  }
13759
13836
  }
13760
13837
  try {
13761
- const client = await connectClient({ socketPath, token, timeoutMs: connectTimeoutMs });
13838
+ const connecting = connectClient({ socketPath, token, timeoutMs: connectTimeoutMs });
13839
+ connecting.catch(() => {
13840
+ });
13841
+ const client = await (helperExited ? Promise.race([connecting, helperExited.promise]) : connecting);
13762
13842
  return {
13763
13843
  client,
13764
13844
  async close() {
@@ -13773,6 +13853,42 @@ async function startPrivilegedHelper(options) {
13773
13853
  } catch {
13774
13854
  }
13775
13855
  throw error;
13856
+ } finally {
13857
+ helperExited == null ? void 0 : helperExited.stop();
13858
+ }
13859
+ }
13860
+ function watchWindowsHelper(pid, errorFile) {
13861
+ let timer;
13862
+ const promise = new Promise((_, reject2) => {
13863
+ timer = setInterval(() => {
13864
+ if (isProcessRunning(pid))
13865
+ return;
13866
+ clearInterval(timer);
13867
+ let detail = "";
13868
+ try {
13869
+ detail = (0, import_node_fs3.readFileSync)(errorFile, "utf8").trim().slice(-4096);
13870
+ } catch {
13871
+ }
13872
+ reject2(new Error(`privileged helper exited before accepting connections.${detail ? ` ${detail}` : " No diagnostic output from the helper."}`));
13873
+ }, 250);
13874
+ });
13875
+ return {
13876
+ promise,
13877
+ stop() {
13878
+ clearInterval(timer);
13879
+ try {
13880
+ (0, import_node_fs3.rmSync)(errorFile, { force: true });
13881
+ } catch {
13882
+ }
13883
+ }
13884
+ };
13885
+ }
13886
+ function isProcessRunning(pid) {
13887
+ try {
13888
+ import_node_process6.default.kill(pid, 0);
13889
+ return true;
13890
+ } catch (error) {
13891
+ return error.code !== "ESRCH";
13776
13892
  }
13777
13893
  }
13778
13894
  async function connectExistingHelper(socketPath, token, timeoutMs = 1500) {
@@ -13785,12 +13901,12 @@ async function connectExistingHelper(socketPath, token, timeoutMs = 1500) {
13785
13901
 
13786
13902
  // src/privileged/session.ts
13787
13903
  function tokenPath(runtimeDir) {
13788
- return (0, import_node_path3.join)(runtimeDir, "helper.token");
13904
+ return (0, import_node_path4.join)(runtimeDir, "helper.token");
13789
13905
  }
13790
13906
  function sessionSocketPath(runtimeDir) {
13791
13907
  if ((0, import_node_os4.platform)() === "win32")
13792
13908
  return `\\\\.\\pipe\\uhrp-${import_node_buffer.Buffer.from(runtimeDir).toString("hex").slice(0, 40)}`;
13793
- return (0, import_node_path3.join)(runtimeDir, "helper.sock");
13909
+ return (0, import_node_path4.join)(runtimeDir, "helper.sock");
13794
13910
  }
13795
13911
  async function openHelperSession(scope2) {
13796
13912
  const socketPath = sessionSocketPath(scope2.runtimeDir);
@@ -13805,7 +13921,7 @@ async function openHelperSession(scope2) {
13805
13921
  }
13806
13922
  }
13807
13923
  async function tryReuse(socketPath, scope2) {
13808
- if (!(0, import_node_fs3.existsSync)(socketPath) && (0, import_node_os4.platform)() !== "win32")
13924
+ if (!(0, import_node_fs4.existsSync)(socketPath) && (0, import_node_os4.platform)() !== "win32")
13809
13925
  return void 0;
13810
13926
  const token = await readToken(scope2.runtimeDir);
13811
13927
  if (!token)
@@ -13835,6 +13951,7 @@ async function startNew(socketPath, scope2) {
13835
13951
  caddyStoragePath: scope2.caddyStoragePath,
13836
13952
  caddyBin: scope2.caddyBin,
13837
13953
  caddyConfigPath: scope2.caddyConfigPath,
13954
+ caddyAdminSocket: scope2.caddyAdminSocket,
13838
13955
  reason: scope2.reason,
13839
13956
  log: scope2.log
13840
13957
  });
@@ -13848,7 +13965,7 @@ async function startNew(socketPath, scope2) {
13848
13965
  };
13849
13966
  }
13850
13967
  async function acquireStartLock(runtimeDir) {
13851
- const lockPath = (0, import_node_path3.join)(runtimeDir, "helper.start.lock");
13968
+ const lockPath = (0, import_node_path4.join)(runtimeDir, "helper.start.lock");
13852
13969
  try {
13853
13970
  await (0, import_promises.writeFile)(lockPath, "", { flag: "a" });
13854
13971
  } catch {
@@ -13882,7 +13999,7 @@ async function writeToken(runtimeDir, token) {
13882
13999
  // src/caddy/privileged.ts
13883
14000
  var import_meta = {};
13884
14001
  function resolvePrivilegedEnv() {
13885
- const moduleDir = typeof __dirname === "string" ? __dirname : (0, import_node_path4.dirname)((0, import_node_url.fileURLToPath)(import_meta.url));
14002
+ const moduleDir = typeof __dirname === "string" ? __dirname : (0, import_node_path5.dirname)((0, import_node_url.fileURLToPath)(import_meta.url));
13886
14003
  const resolved = resolveHelperEntry({ moduleDir });
13887
14004
  return { helperEntry: resolved.entry, helperArgs: resolved.args };
13888
14005
  }
@@ -13922,7 +14039,7 @@ var HelperCaddyProcess = class extends import_node_events.EventEmitter {
13922
14039
  }
13923
14040
  };
13924
14041
  function caddyStoragePath() {
13925
- return import_node_process7.default.platform === "win32" ? (0, import_node_path4.join)(import_node_process7.default.env.AppData ?? "", "Caddy") : (0, import_node_path4.join)(import_node_process7.default.env.HOME ?? "", "Library/Application Support/Caddy");
14042
+ return import_node_process7.default.platform === "win32" ? (0, import_node_path5.join)(import_node_process7.default.env.AppData ?? "", "Caddy") : (0, import_node_path5.join)(import_node_process7.default.env.HOME ?? "", "Library/Application Support/Caddy");
13926
14043
  }
13927
14044
  function openPrivilegedSession(runtimeDir, options) {
13928
14045
  const env2 = resolvePrivilegedEnv();
@@ -13938,6 +14055,7 @@ function openPrivilegedSession(runtimeDir, options) {
13938
14055
  // execute a path supplied over the socket.
13939
14056
  caddyBin: options.caddyBin,
13940
14057
  caddyConfigPath: options.caddyConfigPath,
14058
+ caddyAdminSocket: options.caddyAdminSocket,
13941
14059
  reason: options.reason,
13942
14060
  log: options.log
13943
14061
  });
@@ -14065,11 +14183,11 @@ async function download() {
14065
14183
  if (await testCaddy())
14066
14184
  return caddyPath;
14067
14185
  return new Promise((resolve2, reject2) => {
14068
- if (!(0, import_node_fs4.existsSync)(TEMP_DIR)) {
14069
- (0, import_node_fs4.mkdirSync)(TEMP_DIR, { recursive: true });
14070
- (0, import_node_fs4.chmodSync)(TEMP_DIR, 448);
14186
+ if (!(0, import_node_fs5.existsSync)(TEMP_DIR)) {
14187
+ (0, import_node_fs5.mkdirSync)(TEMP_DIR, { recursive: true });
14188
+ (0, import_node_fs5.chmodSync)(TEMP_DIR, 448);
14071
14189
  }
14072
- const file = (0, import_node_fs4.createWriteStream)(caddyPath);
14190
+ const file = (0, import_node_fs5.createWriteStream)(caddyPath);
14073
14191
  let _platform = (0, import_node_os5.platform)().toString();
14074
14192
  _platform === "win32" && (_platform = "windows");
14075
14193
  let _arch = import_node_process8.default.arch.toString();
@@ -14078,13 +14196,13 @@ async function download() {
14078
14196
  if (!support)
14079
14197
  return reject2(new Error("not support"));
14080
14198
  const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}&p=github.com%2Fcaddyserver%2Fforwardproxy`;
14081
- (0, import_node_fs4.existsSync)(caddyPath) && (0, import_node_fs4.unlinkSync)(caddyPath);
14199
+ (0, import_node_fs5.existsSync)(caddyPath) && (0, import_node_fs5.unlinkSync)(caddyPath);
14082
14200
  const httpProxy = import_node_process8.default.env.HTTP_PROXY || import_node_process8.default.env.http_proxy;
14083
14201
  const httpsProxy = import_node_process8.default.env.HTTPS_PROXY || import_node_process8.default.env.https_proxy;
14084
14202
  const httpAgent = httpProxy ? new import_http_proxy_agent.HttpProxyAgent(httpProxy) : void 0;
14085
14203
  const httpsAgent = httpsProxy ? new import_https_proxy_agent.HttpsProxyAgent(httpsProxy) : void 0;
14086
14204
  const chmodCaddyOnce = once(() => {
14087
- (0, import_node_fs4.chmodSync)(caddyPath, 493);
14205
+ (0, import_node_fs5.chmodSync)(caddyPath, 493);
14088
14206
  });
14089
14207
  import_got_cjs.got.stream(dowmloadLink, {
14090
14208
  agent: {
@@ -14098,7 +14216,7 @@ async function download() {
14098
14216
  logProgressOver();
14099
14217
  if (import_node_process8.default.platform === "win32")
14100
14218
  return resolve2(caddyPath);
14101
- (0, import_node_fs4.chmodSync)(caddyPath, 493);
14219
+ (0, import_node_fs5.chmodSync)(caddyPath, 493);
14102
14220
  resolve2(caddyPath);
14103
14221
  }).on("error", (err) => {
14104
14222
  reject2(err);
@@ -14107,10 +14225,10 @@ async function download() {
14107
14225
  }
14108
14226
  function testCaddy() {
14109
14227
  return new Promise((resolve2) => {
14110
- if (!(0, import_node_fs4.existsSync)(caddyPath))
14228
+ if (!(0, import_node_fs5.existsSync)(caddyPath))
14111
14229
  return resolve2(false);
14112
14230
  try {
14113
- (0, import_node_fs4.chmodSync)(caddyPath, 493);
14231
+ (0, import_node_fs5.chmodSync)(caddyPath, 493);
14114
14232
  } catch {
14115
14233
  }
14116
14234
  (0, import_node_child_process3.execFile)(caddyPath, [], { timeout: 1e4 }, (error, stdout) => {
@@ -14120,10 +14238,27 @@ function testCaddy() {
14120
14238
  });
14121
14239
  });
14122
14240
  }
14241
+ function caddyRootPath() {
14242
+ return (0, import_node_path6.join)(
14243
+ import_node_process8.default.platform === "win32" ? `${import_node_process8.default.env.AppData}/Caddy` : `${import_node_process8.default.env.HOME}/Library/Application Support/Caddy`,
14244
+ "./pki/authorities/local"
14245
+ );
14246
+ }
14247
+ async function renderCaddyfile(proxies) {
14248
+ const ctx = validateTemplateContext({
14249
+ caddy_root: caddyRootPath(),
14250
+ admin_socket: caddyAdminSocketPath,
14251
+ proxies: Object.values(proxies)
14252
+ });
14253
+ const content = await genCaddyfile(ctx);
14254
+ const temp = `${caddyFilePath}.${import_node_process8.default.pid}.tmp`;
14255
+ await (0, import_promises2.writeFile)(temp, content);
14256
+ await (0, import_promises2.rename)(temp, caddyFilePath);
14257
+ }
14123
14258
  var caddyConfig;
14124
14259
  function getCaddyConfig() {
14125
14260
  if (!caddyConfig) {
14126
- caddyConfig = useCaddyConfig();
14261
+ caddyConfig = useCaddyConfig({ renderCaddyfile });
14127
14262
  }
14128
14263
  return caddyConfig;
14129
14264
  }
@@ -14145,6 +14280,7 @@ var defaultDependencies = {
14145
14280
  // helper must never execute something named in a request.
14146
14281
  caddyBin: caddyPath,
14147
14282
  caddyConfigPath: caddyFilePath,
14283
+ caddyAdminSocket: caddyAdminSocketPath,
14148
14284
  reason
14149
14285
  }),
14150
14286
  config: () => getCaddyConfig()
@@ -14166,12 +14302,14 @@ var CaddyInstant = class {
14166
14302
  async session(reason) {
14167
14303
  if (this._session && !this._session.client.connected)
14168
14304
  this._session = void 0;
14169
- if (!this._session)
14305
+ if (!this._session) {
14306
+ await this.deps.config().writeCaddyConfig([], this.proxyKey);
14170
14307
  this._session = await this.deps.openSession(TEMP_DIR, reason);
14308
+ }
14171
14309
  return this._session;
14172
14310
  }
14173
14311
  async getCaddyfile() {
14174
- if (!(0, import_node_fs4.existsSync)(caddyFilePath)) {
14312
+ if (!(0, import_node_fs5.existsSync)(caddyFilePath)) {
14175
14313
  this.caddyfile = "";
14176
14314
  return "";
14177
14315
  }
@@ -14179,10 +14317,7 @@ var CaddyInstant = class {
14179
14317
  return this.caddyfile;
14180
14318
  }
14181
14319
  get caddyRoot() {
14182
- return (0, import_node_path5.join)(
14183
- import_node_process8.default.platform === "win32" ? `${import_node_process8.default.env.AppData}/Caddy` : `${import_node_process8.default.env.HOME}/Library/Application Support/Caddy`,
14184
- "./pki/authorities/local"
14185
- );
14320
+ return caddyRootPath();
14186
14321
  }
14187
14322
  async writeCaddyfile() {
14188
14323
  return await (0, import_promises2.writeFile)(caddyFilePath, this.caddyfile || "");
@@ -14226,40 +14361,6 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14226
14361
  if (!health.healthy)
14227
14362
  throw new Error(formatTlsHealthFailure(targetHost, health));
14228
14363
  }
14229
- /**
14230
- * Regenerates the Caddyfile from the config on disk.
14231
- *
14232
- * Reading the file rather than a cached view matters here: another project
14233
- * may have added its route since this instance last looked.
14234
- */
14235
- async updateCaddyfile() {
14236
- const { readProxies } = this.deps.config();
14237
- const proxies = Object.values(readProxies());
14238
- const ctx = validateTemplateContext({
14239
- caddy_root: this.caddyRoot,
14240
- proxies
14241
- });
14242
- this.caddyfile = await genCaddyfile(ctx);
14243
- await this.writeCaddyfile();
14244
- }
14245
- async stopCaddy() {
14246
- var _a4;
14247
- try {
14248
- await import_got_cjs.got.post("http://127.0.0.1:2019/stop", {
14249
- headers: {
14250
- Origin: "http://localhost:2019"
14251
- },
14252
- retry: {
14253
- limit: 0
14254
- },
14255
- timeout: {
14256
- request: 2e3
14257
- }
14258
- });
14259
- } catch {
14260
- }
14261
- (_a4 = this._caddyChild) == null ? void 0 : _a4.kill();
14262
- }
14263
14364
  /**
14264
14365
  * @param source like `127.0.0.1:8080`
14265
14366
  * @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
@@ -14304,7 +14405,6 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14304
14405
  ];
14305
14406
  const { writeCaddyConfig } = this.deps.config();
14306
14407
  await writeCaddyConfig(proxies, this.proxyKey);
14307
- await this.updateCaddyfile();
14308
14408
  await session.client.call("port.free", { port: 443 });
14309
14409
  if (import_node_process8.default.platform === "win32" || !https)
14310
14410
  await session.client.call("port.free", { port: 80 });
@@ -14774,6 +14874,8 @@ var unpluginFactory = (options) => ({
14774
14874
  return;
14775
14875
  }
14776
14876
  const _printUrls = server.printUrls.bind(server);
14877
+ if (server.config.server.middlewareMode)
14878
+ 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.");
14777
14879
  let source = `localhost:${config.server.port || 5173}`;
14778
14880
  const url2 = (_a4 = server.resolvedUrls) == null ? void 0 : _a4.local[0];
14779
14881
  if (url2) {
package/dist/vite.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  unpluginFactory
3
- } from "./chunk-ICH7VY4H.js";
3
+ } from "./chunk-U6J2RMIR.js";
4
4
  import "./chunk-EY3HXBJ4.js";
5
5
  import "./chunk-C5A7XLKL.js";
6
6
  import "./chunk-WOMR3ZLM.js";