unplugin-https-reverse-proxy 4.1.0-beta.11 → 4.1.0-beta.13

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");
@@ -13295,7 +13295,7 @@ function isCaddyReloadCancellation(line) {
13295
13295
  // src/caddy/privileged.ts
13296
13296
  var import_node_buffer2 = require("buffer");
13297
13297
  var import_node_events = require("events");
13298
- var import_node_path4 = require("path");
13298
+ var import_node_path5 = require("path");
13299
13299
  var import_node_process7 = __toESM(require("process"), 1);
13300
13300
  var import_node_url = require("url");
13301
13301
 
@@ -13331,16 +13331,18 @@ function findUp(from, relative, exists2) {
13331
13331
 
13332
13332
  // src/privileged/session.ts
13333
13333
  var import_node_buffer = require("buffer");
13334
- var import_node_fs3 = require("fs");
13334
+ var import_node_fs4 = require("fs");
13335
13335
  var import_promises = require("fs/promises");
13336
13336
  var import_node_os4 = require("os");
13337
- var import_node_path3 = require("path");
13337
+ var import_node_path4 = require("path");
13338
13338
  var lockfile2 = __toESM(require("proper-lockfile"), 1);
13339
13339
 
13340
13340
  // src/privileged/launch.ts
13341
13341
  var import_node_child_process2 = require("child_process");
13342
13342
  var import_node_crypto = require("crypto");
13343
+ var import_node_fs3 = require("fs");
13343
13344
  var import_node_os3 = require("os");
13345
+ var import_node_path3 = require("path");
13344
13346
  var import_node_process6 = __toESM(require("process"), 1);
13345
13347
 
13346
13348
  // src/privileged/client.ts
@@ -13454,7 +13456,7 @@ async function connectClient(options) {
13454
13456
  } catch (error) {
13455
13457
  lastError = error;
13456
13458
  const code = lastError.code;
13457
- if (code === "EACCES" || lastError instanceof HelperConnectionError)
13459
+ if (code === "EACCES" || code === "EPERM" || lastError instanceof HelperConnectionError)
13458
13460
  throw lastError;
13459
13461
  await new Promise((resolve2) => setTimeout(resolve2, retryIntervalMs));
13460
13462
  }
@@ -13586,39 +13588,78 @@ function createClient(socket, initialBuffer, callTimeoutMs) {
13586
13588
  // src/privileged/windows-elevation.ts
13587
13589
  var import_node_child_process = require("child_process");
13588
13590
  var import_node_process5 = __toESM(require("process"), 1);
13591
+ var ERROR_CANCELLED = 1223;
13589
13592
  function quotePowerShell(value2) {
13590
13593
  return `'${value2.replace(/'/g, "''")}'`;
13591
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
+ }
13592
13612
  function buildElevationCommand(options) {
13593
- const argumentList = options.args.map(quotePowerShell).join(",");
13594
- const parts = [
13595
- "Start-Process",
13596
- "-FilePath",
13597
- 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(" "))}`
13598
13619
  ];
13599
- if (argumentList)
13600
- parts.push("-ArgumentList", argumentList);
13601
13620
  if (options.cwd)
13602
- parts.push("-WorkingDirectory", quotePowerShell(options.cwd));
13603
- parts.push("-Verb", "RunAs");
13604
- parts.push("-WindowStyle", "Hidden");
13605
- 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");
13606
13630
  }
13607
13631
  function spawnElevatedOnWindows(options) {
13608
- return new Promise((resolve2, reject2) => {
13609
- const script = buildElevationCommand(options);
13632
+ return new Promise((resolve2) => {
13610
13633
  const child = (0, import_node_child_process.spawn)(
13611
13634
  "powershell.exe",
13612
- ["-NoProfile", "-NonInteractive", "-Command", script],
13613
- { stdio: "ignore", windowsHide: true }
13635
+ ["-NoProfile", "-NonInteractive", "-Command", buildElevationCommand(options)],
13636
+ { stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
13614
13637
  );
13615
- child.once("error", reject2);
13616
- child.once("exit", (code) => {
13617
- if (code === 0)
13618
- return resolve2(child);
13619
- reject2(new Error(
13620
- `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.`
13621
- ));
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
+ });
13622
13663
  });
13623
13664
  });
13624
13665
  }
@@ -13749,8 +13790,18 @@ async function startPrivilegedHelper(options) {
13749
13790
  ...options.caddyAdminSocket ? ["--caddy-admin", options.caddyAdminSocket] : []
13750
13791
  ];
13751
13792
  let child;
13793
+ let helperExited;
13752
13794
  if (!direct && (0, import_node_os3.platform)() === "win32") {
13753
- 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);
13754
13805
  } else {
13755
13806
  const command = direct ? helperEntry : sudoCommand;
13756
13807
  const spawnArgs = direct ? childArgv : ["-n", "env", ...forwardedArgs, helperEntry, ...childArgv];
@@ -13784,7 +13835,10 @@ async function startPrivilegedHelper(options) {
13784
13835
  }
13785
13836
  }
13786
13837
  try {
13787
- 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);
13788
13842
  return {
13789
13843
  client,
13790
13844
  async close() {
@@ -13799,6 +13853,42 @@ async function startPrivilegedHelper(options) {
13799
13853
  } catch {
13800
13854
  }
13801
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";
13802
13892
  }
13803
13893
  }
13804
13894
  async function connectExistingHelper(socketPath, token, timeoutMs = 1500) {
@@ -13811,12 +13901,12 @@ async function connectExistingHelper(socketPath, token, timeoutMs = 1500) {
13811
13901
 
13812
13902
  // src/privileged/session.ts
13813
13903
  function tokenPath(runtimeDir) {
13814
- return (0, import_node_path3.join)(runtimeDir, "helper.token");
13904
+ return (0, import_node_path4.join)(runtimeDir, "helper.token");
13815
13905
  }
13816
13906
  function sessionSocketPath(runtimeDir) {
13817
13907
  if ((0, import_node_os4.platform)() === "win32")
13818
13908
  return `\\\\.\\pipe\\uhrp-${import_node_buffer.Buffer.from(runtimeDir).toString("hex").slice(0, 40)}`;
13819
- return (0, import_node_path3.join)(runtimeDir, "helper.sock");
13909
+ return (0, import_node_path4.join)(runtimeDir, "helper.sock");
13820
13910
  }
13821
13911
  async function openHelperSession(scope2) {
13822
13912
  const socketPath = sessionSocketPath(scope2.runtimeDir);
@@ -13831,7 +13921,7 @@ async function openHelperSession(scope2) {
13831
13921
  }
13832
13922
  }
13833
13923
  async function tryReuse(socketPath, scope2) {
13834
- 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")
13835
13925
  return void 0;
13836
13926
  const token = await readToken(scope2.runtimeDir);
13837
13927
  if (!token)
@@ -13875,7 +13965,7 @@ async function startNew(socketPath, scope2) {
13875
13965
  };
13876
13966
  }
13877
13967
  async function acquireStartLock(runtimeDir) {
13878
- const lockPath = (0, import_node_path3.join)(runtimeDir, "helper.start.lock");
13968
+ const lockPath = (0, import_node_path4.join)(runtimeDir, "helper.start.lock");
13879
13969
  try {
13880
13970
  await (0, import_promises.writeFile)(lockPath, "", { flag: "a" });
13881
13971
  } catch {
@@ -13909,7 +13999,7 @@ async function writeToken(runtimeDir, token) {
13909
13999
  // src/caddy/privileged.ts
13910
14000
  var import_meta = {};
13911
14001
  function resolvePrivilegedEnv() {
13912
- 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));
13913
14003
  const resolved = resolveHelperEntry({ moduleDir });
13914
14004
  return { helperEntry: resolved.entry, helperArgs: resolved.args };
13915
14005
  }
@@ -13949,7 +14039,7 @@ var HelperCaddyProcess = class extends import_node_events.EventEmitter {
13949
14039
  }
13950
14040
  };
13951
14041
  function caddyStoragePath() {
13952
- 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");
13953
14043
  }
13954
14044
  function openPrivilegedSession(runtimeDir, options) {
13955
14045
  const env2 = resolvePrivilegedEnv();
@@ -14093,11 +14183,11 @@ async function download() {
14093
14183
  if (await testCaddy())
14094
14184
  return caddyPath;
14095
14185
  return new Promise((resolve2, reject2) => {
14096
- if (!(0, import_node_fs4.existsSync)(TEMP_DIR)) {
14097
- (0, import_node_fs4.mkdirSync)(TEMP_DIR, { recursive: true });
14098
- (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);
14099
14189
  }
14100
- const file = (0, import_node_fs4.createWriteStream)(caddyPath);
14190
+ const file = (0, import_node_fs5.createWriteStream)(caddyPath);
14101
14191
  let _platform = (0, import_node_os5.platform)().toString();
14102
14192
  _platform === "win32" && (_platform = "windows");
14103
14193
  let _arch = import_node_process8.default.arch.toString();
@@ -14106,13 +14196,13 @@ async function download() {
14106
14196
  if (!support)
14107
14197
  return reject2(new Error("not support"));
14108
14198
  const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}&p=github.com%2Fcaddyserver%2Fforwardproxy`;
14109
- (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);
14110
14200
  const httpProxy = import_node_process8.default.env.HTTP_PROXY || import_node_process8.default.env.http_proxy;
14111
14201
  const httpsProxy = import_node_process8.default.env.HTTPS_PROXY || import_node_process8.default.env.https_proxy;
14112
14202
  const httpAgent = httpProxy ? new import_http_proxy_agent.HttpProxyAgent(httpProxy) : void 0;
14113
14203
  const httpsAgent = httpsProxy ? new import_https_proxy_agent.HttpsProxyAgent(httpsProxy) : void 0;
14114
14204
  const chmodCaddyOnce = once(() => {
14115
- (0, import_node_fs4.chmodSync)(caddyPath, 493);
14205
+ (0, import_node_fs5.chmodSync)(caddyPath, 493);
14116
14206
  });
14117
14207
  import_got_cjs.got.stream(dowmloadLink, {
14118
14208
  agent: {
@@ -14126,7 +14216,7 @@ async function download() {
14126
14216
  logProgressOver();
14127
14217
  if (import_node_process8.default.platform === "win32")
14128
14218
  return resolve2(caddyPath);
14129
- (0, import_node_fs4.chmodSync)(caddyPath, 493);
14219
+ (0, import_node_fs5.chmodSync)(caddyPath, 493);
14130
14220
  resolve2(caddyPath);
14131
14221
  }).on("error", (err) => {
14132
14222
  reject2(err);
@@ -14135,10 +14225,10 @@ async function download() {
14135
14225
  }
14136
14226
  function testCaddy() {
14137
14227
  return new Promise((resolve2) => {
14138
- if (!(0, import_node_fs4.existsSync)(caddyPath))
14228
+ if (!(0, import_node_fs5.existsSync)(caddyPath))
14139
14229
  return resolve2(false);
14140
14230
  try {
14141
- (0, import_node_fs4.chmodSync)(caddyPath, 493);
14231
+ (0, import_node_fs5.chmodSync)(caddyPath, 493);
14142
14232
  } catch {
14143
14233
  }
14144
14234
  (0, import_node_child_process3.execFile)(caddyPath, [], { timeout: 1e4 }, (error, stdout) => {
@@ -14149,7 +14239,7 @@ function testCaddy() {
14149
14239
  });
14150
14240
  }
14151
14241
  function caddyRootPath() {
14152
- return (0, import_node_path5.join)(
14242
+ return (0, import_node_path6.join)(
14153
14243
  import_node_process8.default.platform === "win32" ? `${import_node_process8.default.env.AppData}/Caddy` : `${import_node_process8.default.env.HOME}/Library/Application Support/Caddy`,
14154
14244
  "./pki/authorities/local"
14155
14245
  );
@@ -14212,12 +14302,14 @@ var CaddyInstant = class {
14212
14302
  async session(reason) {
14213
14303
  if (this._session && !this._session.client.connected)
14214
14304
  this._session = void 0;
14215
- if (!this._session)
14305
+ if (!this._session) {
14306
+ await this.deps.config().writeCaddyConfig([], this.proxyKey);
14216
14307
  this._session = await this.deps.openSession(TEMP_DIR, reason);
14308
+ }
14217
14309
  return this._session;
14218
14310
  }
14219
14311
  async getCaddyfile() {
14220
- if (!(0, import_node_fs4.existsSync)(caddyFilePath)) {
14312
+ if (!(0, import_node_fs5.existsSync)(caddyFilePath)) {
14221
14313
  this.caddyfile = "";
14222
14314
  return "";
14223
14315
  }
@@ -14782,6 +14874,8 @@ var unpluginFactory = (options) => ({
14782
14874
  return;
14783
14875
  }
14784
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.");
14785
14879
  let source = `localhost:${config.server.port || 5173}`;
14786
14880
  const url2 = (_a4 = server.resolvedUrls) == null ? void 0 : _a4.local[0];
14787
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-AQLHWJ4E.js";
6
+ } from "./chunk-U6J2RMIR.js";
7
7
  import "./chunk-EY3HXBJ4.js";
8
8
  import "./chunk-C5A7XLKL.js";
9
9
  import "./chunk-WOMR3ZLM.js";