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