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/dist/index.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,21 +13202,22 @@ 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);
13209
+ (0, import_node_fs.renameSync)(temp, path);
13199
13210
  }
13200
13211
  function useCaddyConfig(options = {}) {
13201
13212
  const lock3 = options.lock ?? createFileLock();
13213
+ const configPath = options.configPath ?? caddyConfigPath;
13202
13214
  async function mutate(apply) {
13203
13215
  var _a4;
13204
13216
  const release = await lock3.acquire();
13205
13217
  try {
13206
- const proxies = readConfig();
13218
+ const proxies = readConfig(configPath);
13207
13219
  apply(proxies);
13208
- writeConfig(proxies);
13220
+ writeConfig(proxies, configPath);
13209
13221
  await ((_a4 = options.renderCaddyfile) == null ? void 0 : _a4.call(options, proxies));
13210
13222
  return proxies;
13211
13223
  } finally {
@@ -13213,7 +13225,7 @@ function useCaddyConfig(options = {}) {
13213
13225
  }
13214
13226
  }
13215
13227
  return {
13216
- configJsonRef: () => (0, import_node_fs.existsSync)(caddyConfigPath) ? readConfig() : void 0,
13228
+ configJsonRef: () => (0, import_node_fs.existsSync)(configPath) ? readConfig(configPath) : void 0,
13217
13229
  async writeCaddyConfig(_proxies, key) {
13218
13230
  await mutate((proxies) => {
13219
13231
  for (const p of _proxies)
@@ -13221,25 +13233,23 @@ function useCaddyConfig(options = {}) {
13221
13233
  });
13222
13234
  },
13223
13235
  async removeProxy(key) {
13224
- const proxies = await mutate((current) => {
13236
+ await mutate((current) => {
13225
13237
  for (const route of Object.keys(current)) {
13226
13238
  if (route.endsWith(`#${key}`))
13227
13239
  delete current[route];
13228
13240
  }
13229
13241
  });
13230
- if (Object.keys(proxies).length === 0)
13231
- removeConfigFile();
13232
13242
  },
13233
- readProxies: () => readConfig(),
13243
+ readProxies: () => readConfig(configPath),
13234
13244
  async cleanUp() {
13235
- removeConfigFile();
13245
+ removeConfigFile(configPath);
13236
13246
  }
13237
13247
  };
13238
13248
  }
13239
- function removeConfigFile() {
13249
+ function removeConfigFile(path = caddyConfigPath) {
13240
13250
  try {
13241
- if ((0, import_node_fs.existsSync)(caddyConfigPath))
13242
- (0, import_node_fs.unlinkSync)(caddyConfigPath);
13251
+ if ((0, import_node_fs.existsSync)(path))
13252
+ (0, import_node_fs.unlinkSync)(path);
13243
13253
  } catch {
13244
13254
  }
13245
13255
  }
@@ -13285,7 +13295,7 @@ function isCaddyReloadCancellation(line) {
13285
13295
  // src/caddy/privileged.ts
13286
13296
  var import_node_buffer2 = require("buffer");
13287
13297
  var import_node_events = require("events");
13288
- var import_node_path4 = require("path");
13298
+ var import_node_path5 = require("path");
13289
13299
  var import_node_process7 = __toESM(require("process"), 1);
13290
13300
  var import_node_url = require("url");
13291
13301
 
@@ -13321,16 +13331,18 @@ function findUp(from, relative, exists2) {
13321
13331
 
13322
13332
  // src/privileged/session.ts
13323
13333
  var import_node_buffer = require("buffer");
13324
- var import_node_fs3 = require("fs");
13334
+ var import_node_fs4 = require("fs");
13325
13335
  var import_promises = require("fs/promises");
13326
13336
  var import_node_os4 = require("os");
13327
- var import_node_path3 = require("path");
13337
+ var import_node_path4 = require("path");
13328
13338
  var lockfile2 = __toESM(require("proper-lockfile"), 1);
13329
13339
 
13330
13340
  // src/privileged/launch.ts
13331
13341
  var import_node_child_process2 = require("child_process");
13332
13342
  var import_node_crypto = require("crypto");
13343
+ var import_node_fs3 = require("fs");
13333
13344
  var import_node_os3 = require("os");
13345
+ var import_node_path3 = require("path");
13334
13346
  var import_node_process6 = __toESM(require("process"), 1);
13335
13347
 
13336
13348
  // src/privileged/client.ts
@@ -13444,7 +13456,7 @@ async function connectClient(options) {
13444
13456
  } catch (error) {
13445
13457
  lastError = error;
13446
13458
  const code = lastError.code;
13447
- if (code === "EACCES" || lastError instanceof HelperConnectionError)
13459
+ if (code === "EACCES" || code === "EPERM" || lastError instanceof HelperConnectionError)
13448
13460
  throw lastError;
13449
13461
  await new Promise((resolve2) => setTimeout(resolve2, retryIntervalMs));
13450
13462
  }
@@ -13576,39 +13588,78 @@ function createClient(socket, initialBuffer, callTimeoutMs) {
13576
13588
  // src/privileged/windows-elevation.ts
13577
13589
  var import_node_child_process = require("child_process");
13578
13590
  var import_node_process5 = __toESM(require("process"), 1);
13591
+ var ERROR_CANCELLED = 1223;
13579
13592
  function quotePowerShell(value2) {
13580
13593
  return `'${value2.replace(/'/g, "''")}'`;
13581
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
+ }
13582
13612
  function buildElevationCommand(options) {
13583
- const argumentList = options.args.map(quotePowerShell).join(",");
13584
- const parts = [
13585
- "Start-Process",
13586
- "-FilePath",
13587
- 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(" "))}`
13588
13619
  ];
13589
- if (argumentList)
13590
- parts.push("-ArgumentList", argumentList);
13591
13620
  if (options.cwd)
13592
- parts.push("-WorkingDirectory", quotePowerShell(options.cwd));
13593
- parts.push("-Verb", "RunAs");
13594
- parts.push("-WindowStyle", "Hidden");
13595
- 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");
13596
13630
  }
13597
13631
  function spawnElevatedOnWindows(options) {
13598
- return new Promise((resolve2, reject2) => {
13599
- const script = buildElevationCommand(options);
13632
+ return new Promise((resolve2) => {
13600
13633
  const child = (0, import_node_child_process.spawn)(
13601
13634
  "powershell.exe",
13602
- ["-NoProfile", "-NonInteractive", "-Command", script],
13603
- { stdio: "ignore", windowsHide: true }
13635
+ ["-NoProfile", "-NonInteractive", "-Command", buildElevationCommand(options)],
13636
+ { stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
13604
13637
  );
13605
- child.once("error", reject2);
13606
- child.once("exit", (code) => {
13607
- if (code === 0)
13608
- return resolve2(child);
13609
- reject2(new Error(
13610
- `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.`
13611
- ));
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
+ });
13612
13663
  });
13613
13664
  });
13614
13665
  }
@@ -13735,11 +13786,22 @@ async function startPrivilegedHelper(options) {
13735
13786
  "--caddy",
13736
13787
  options.caddyBin,
13737
13788
  "--caddy-config",
13738
- options.caddyConfigPath
13789
+ options.caddyConfigPath,
13790
+ ...options.caddyAdminSocket ? ["--caddy-admin", options.caddyAdminSocket] : []
13739
13791
  ];
13740
13792
  let child;
13793
+ let helperExited;
13741
13794
  if (!direct && (0, import_node_os3.platform)() === "win32") {
13742
- 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);
13743
13805
  } else {
13744
13806
  const command = direct ? helperEntry : sudoCommand;
13745
13807
  const spawnArgs = direct ? childArgv : ["-n", "env", ...forwardedArgs, helperEntry, ...childArgv];
@@ -13747,20 +13809,36 @@ async function startPrivilegedHelper(options) {
13747
13809
  stdio: ["ignore", "pipe", "pipe"]
13748
13810
  });
13749
13811
  (_a4 = child.stdout) == null ? void 0 : _a4.on("data", (data) => log == null ? void 0 : log(data.toString().trimEnd()));
13750
- (_b3 = child.stderr) == null ? void 0 : _b3.on("data", (data) => log == null ? void 0 : log(data.toString().trimEnd()));
13751
- 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
+ });
13752
13823
  const earlyExit = await Promise.race([
13753
13824
  exited,
13754
13825
  new Promise((resolve2) => setTimeout(() => resolve2(void 0), 500))
13755
13826
  ]);
13756
13827
  if (earlyExit !== void 0 && earlyExit !== 0) {
13757
- throw new Error(
13758
- `privileged helper exited with code ${earlyExit}. Administrator permission was refused, or sudo is not available.`
13759
- );
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."}`);
13760
13835
  }
13761
13836
  }
13762
13837
  try {
13763
- 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);
13764
13842
  return {
13765
13843
  client,
13766
13844
  async close() {
@@ -13775,6 +13853,42 @@ async function startPrivilegedHelper(options) {
13775
13853
  } catch {
13776
13854
  }
13777
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";
13778
13892
  }
13779
13893
  }
13780
13894
  async function connectExistingHelper(socketPath, token, timeoutMs = 1500) {
@@ -13787,12 +13901,12 @@ async function connectExistingHelper(socketPath, token, timeoutMs = 1500) {
13787
13901
 
13788
13902
  // src/privileged/session.ts
13789
13903
  function tokenPath(runtimeDir) {
13790
- return (0, import_node_path3.join)(runtimeDir, "helper.token");
13904
+ return (0, import_node_path4.join)(runtimeDir, "helper.token");
13791
13905
  }
13792
13906
  function sessionSocketPath(runtimeDir) {
13793
13907
  if ((0, import_node_os4.platform)() === "win32")
13794
13908
  return `\\\\.\\pipe\\uhrp-${import_node_buffer.Buffer.from(runtimeDir).toString("hex").slice(0, 40)}`;
13795
- return (0, import_node_path3.join)(runtimeDir, "helper.sock");
13909
+ return (0, import_node_path4.join)(runtimeDir, "helper.sock");
13796
13910
  }
13797
13911
  async function openHelperSession(scope2) {
13798
13912
  const socketPath = sessionSocketPath(scope2.runtimeDir);
@@ -13807,7 +13921,7 @@ async function openHelperSession(scope2) {
13807
13921
  }
13808
13922
  }
13809
13923
  async function tryReuse(socketPath, scope2) {
13810
- 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")
13811
13925
  return void 0;
13812
13926
  const token = await readToken(scope2.runtimeDir);
13813
13927
  if (!token)
@@ -13837,6 +13951,7 @@ async function startNew(socketPath, scope2) {
13837
13951
  caddyStoragePath: scope2.caddyStoragePath,
13838
13952
  caddyBin: scope2.caddyBin,
13839
13953
  caddyConfigPath: scope2.caddyConfigPath,
13954
+ caddyAdminSocket: scope2.caddyAdminSocket,
13840
13955
  reason: scope2.reason,
13841
13956
  log: scope2.log
13842
13957
  });
@@ -13850,7 +13965,7 @@ async function startNew(socketPath, scope2) {
13850
13965
  };
13851
13966
  }
13852
13967
  async function acquireStartLock(runtimeDir) {
13853
- const lockPath = (0, import_node_path3.join)(runtimeDir, "helper.start.lock");
13968
+ const lockPath = (0, import_node_path4.join)(runtimeDir, "helper.start.lock");
13854
13969
  try {
13855
13970
  await (0, import_promises.writeFile)(lockPath, "", { flag: "a" });
13856
13971
  } catch {
@@ -13884,7 +13999,7 @@ async function writeToken(runtimeDir, token) {
13884
13999
  // src/caddy/privileged.ts
13885
14000
  var import_meta = {};
13886
14001
  function resolvePrivilegedEnv() {
13887
- 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));
13888
14003
  const resolved = resolveHelperEntry({ moduleDir });
13889
14004
  return { helperEntry: resolved.entry, helperArgs: resolved.args };
13890
14005
  }
@@ -13924,7 +14039,7 @@ var HelperCaddyProcess = class extends import_node_events.EventEmitter {
13924
14039
  }
13925
14040
  };
13926
14041
  function caddyStoragePath() {
13927
- 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");
13928
14043
  }
13929
14044
  function openPrivilegedSession(runtimeDir, options) {
13930
14045
  const env2 = resolvePrivilegedEnv();
@@ -13940,6 +14055,7 @@ function openPrivilegedSession(runtimeDir, options) {
13940
14055
  // execute a path supplied over the socket.
13941
14056
  caddyBin: options.caddyBin,
13942
14057
  caddyConfigPath: options.caddyConfigPath,
14058
+ caddyAdminSocket: options.caddyAdminSocket,
13943
14059
  reason: options.reason,
13944
14060
  log: options.log
13945
14061
  });
@@ -14067,11 +14183,11 @@ async function download() {
14067
14183
  if (await testCaddy())
14068
14184
  return caddyPath;
14069
14185
  return new Promise((resolve2, reject2) => {
14070
- if (!(0, import_node_fs4.existsSync)(TEMP_DIR)) {
14071
- (0, import_node_fs4.mkdirSync)(TEMP_DIR, { recursive: true });
14072
- (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);
14073
14189
  }
14074
- const file = (0, import_node_fs4.createWriteStream)(caddyPath);
14190
+ const file = (0, import_node_fs5.createWriteStream)(caddyPath);
14075
14191
  let _platform = (0, import_node_os5.platform)().toString();
14076
14192
  _platform === "win32" && (_platform = "windows");
14077
14193
  let _arch = import_node_process8.default.arch.toString();
@@ -14080,13 +14196,13 @@ async function download() {
14080
14196
  if (!support)
14081
14197
  return reject2(new Error("not support"));
14082
14198
  const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}&p=github.com%2Fcaddyserver%2Fforwardproxy`;
14083
- (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);
14084
14200
  const httpProxy = import_node_process8.default.env.HTTP_PROXY || import_node_process8.default.env.http_proxy;
14085
14201
  const httpsProxy = import_node_process8.default.env.HTTPS_PROXY || import_node_process8.default.env.https_proxy;
14086
14202
  const httpAgent = httpProxy ? new import_http_proxy_agent.HttpProxyAgent(httpProxy) : void 0;
14087
14203
  const httpsAgent = httpsProxy ? new import_https_proxy_agent.HttpsProxyAgent(httpsProxy) : void 0;
14088
14204
  const chmodCaddyOnce = once(() => {
14089
- (0, import_node_fs4.chmodSync)(caddyPath, 493);
14205
+ (0, import_node_fs5.chmodSync)(caddyPath, 493);
14090
14206
  });
14091
14207
  import_got_cjs.got.stream(dowmloadLink, {
14092
14208
  agent: {
@@ -14100,7 +14216,7 @@ async function download() {
14100
14216
  logProgressOver();
14101
14217
  if (import_node_process8.default.platform === "win32")
14102
14218
  return resolve2(caddyPath);
14103
- (0, import_node_fs4.chmodSync)(caddyPath, 493);
14219
+ (0, import_node_fs5.chmodSync)(caddyPath, 493);
14104
14220
  resolve2(caddyPath);
14105
14221
  }).on("error", (err) => {
14106
14222
  reject2(err);
@@ -14109,10 +14225,10 @@ async function download() {
14109
14225
  }
14110
14226
  function testCaddy() {
14111
14227
  return new Promise((resolve2) => {
14112
- if (!(0, import_node_fs4.existsSync)(caddyPath))
14228
+ if (!(0, import_node_fs5.existsSync)(caddyPath))
14113
14229
  return resolve2(false);
14114
14230
  try {
14115
- (0, import_node_fs4.chmodSync)(caddyPath, 493);
14231
+ (0, import_node_fs5.chmodSync)(caddyPath, 493);
14116
14232
  } catch {
14117
14233
  }
14118
14234
  (0, import_node_child_process3.execFile)(caddyPath, [], { timeout: 1e4 }, (error, stdout) => {
@@ -14123,7 +14239,7 @@ function testCaddy() {
14123
14239
  });
14124
14240
  }
14125
14241
  function caddyRootPath() {
14126
- return (0, import_node_path5.join)(
14242
+ return (0, import_node_path6.join)(
14127
14243
  import_node_process8.default.platform === "win32" ? `${import_node_process8.default.env.AppData}/Caddy` : `${import_node_process8.default.env.HOME}/Library/Application Support/Caddy`,
14128
14244
  "./pki/authorities/local"
14129
14245
  );
@@ -14131,9 +14247,13 @@ function caddyRootPath() {
14131
14247
  async function renderCaddyfile(proxies) {
14132
14248
  const ctx = validateTemplateContext({
14133
14249
  caddy_root: caddyRootPath(),
14250
+ admin_socket: caddyAdminSocketPath,
14134
14251
  proxies: Object.values(proxies)
14135
14252
  });
14136
- await (0, import_promises2.writeFile)(caddyFilePath, await genCaddyfile(ctx));
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);
14137
14257
  }
14138
14258
  var caddyConfig;
14139
14259
  function getCaddyConfig() {
@@ -14160,6 +14280,7 @@ var defaultDependencies = {
14160
14280
  // helper must never execute something named in a request.
14161
14281
  caddyBin: caddyPath,
14162
14282
  caddyConfigPath: caddyFilePath,
14283
+ caddyAdminSocket: caddyAdminSocketPath,
14163
14284
  reason
14164
14285
  }),
14165
14286
  config: () => getCaddyConfig()
@@ -14181,12 +14302,14 @@ var CaddyInstant = class {
14181
14302
  async session(reason) {
14182
14303
  if (this._session && !this._session.client.connected)
14183
14304
  this._session = void 0;
14184
- if (!this._session)
14305
+ if (!this._session) {
14306
+ await this.deps.config().writeCaddyConfig([], this.proxyKey);
14185
14307
  this._session = await this.deps.openSession(TEMP_DIR, reason);
14308
+ }
14186
14309
  return this._session;
14187
14310
  }
14188
14311
  async getCaddyfile() {
14189
- if (!(0, import_node_fs4.existsSync)(caddyFilePath)) {
14312
+ if (!(0, import_node_fs5.existsSync)(caddyFilePath)) {
14190
14313
  this.caddyfile = "";
14191
14314
  return "";
14192
14315
  }
@@ -14238,40 +14361,6 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14238
14361
  if (!health.healthy)
14239
14362
  throw new Error(formatTlsHealthFailure(targetHost, health));
14240
14363
  }
14241
- /**
14242
- * Regenerates the Caddyfile from the config on disk.
14243
- *
14244
- * Reading the file rather than a cached view matters here: another project
14245
- * may have added its route since this instance last looked.
14246
- */
14247
- async updateCaddyfile() {
14248
- const { readProxies } = this.deps.config();
14249
- const proxies = Object.values(readProxies());
14250
- const ctx = validateTemplateContext({
14251
- caddy_root: this.caddyRoot,
14252
- proxies
14253
- });
14254
- this.caddyfile = await genCaddyfile(ctx);
14255
- await this.writeCaddyfile();
14256
- }
14257
- async stopCaddy() {
14258
- var _a4;
14259
- try {
14260
- await import_got_cjs.got.post("http://127.0.0.1:2019/stop", {
14261
- headers: {
14262
- Origin: "http://localhost:2019"
14263
- },
14264
- retry: {
14265
- limit: 0
14266
- },
14267
- timeout: {
14268
- request: 2e3
14269
- }
14270
- });
14271
- } catch {
14272
- }
14273
- (_a4 = this._caddyChild) == null ? void 0 : _a4.kill();
14274
- }
14275
14364
  /**
14276
14365
  * @param source like `127.0.0.1:8080`
14277
14366
  * @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
@@ -14316,7 +14405,6 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14316
14405
  ];
14317
14406
  const { writeCaddyConfig } = this.deps.config();
14318
14407
  await writeCaddyConfig(proxies, this.proxyKey);
14319
- await this.updateCaddyfile();
14320
14408
  await session.client.call("port.free", { port: 443 });
14321
14409
  if (import_node_process8.default.platform === "win32" || !https)
14322
14410
  await session.client.call("port.free", { port: 80 });
@@ -14786,6 +14874,8 @@ var unpluginFactory = (options) => ({
14786
14874
  return;
14787
14875
  }
14788
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.");
14789
14879
  let source = `localhost:${config.server.port || 5173}`;
14790
14880
  const url2 = (_a4 = server.resolvedUrls) == null ? void 0 : _a4.local[0];
14791
14881
  if (url2) {
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  unplugin,
4
4
  unpluginFactory,
5
5
  vitePrintUrls
6
- } from "./chunk-3NHJSYFO.js";
6
+ } from "./chunk-U6J2RMIR.js";
7
7
  import "./chunk-EY3HXBJ4.js";
8
8
  import "./chunk-C5A7XLKL.js";
9
9
  import "./chunk-WOMR3ZLM.js";