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/webpack.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/webpack.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  unpluginFactory
3
- } from "./chunk-AQLHWJ4E.js";
3
+ } from "./chunk-U6J2RMIR.js";
4
4
  import "./chunk-EY3HXBJ4.js";
5
5
  import "./chunk-C5A7XLKL.js";
6
6
  import "./chunk-WOMR3ZLM.js";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "unplugin-https-reverse-proxy",
3
3
  "type": "module",
4
- "version": "4.1.0-beta.11",
4
+ "version": "4.1.0-beta.13",
5
5
  "description": "",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/zcf0508/unplugin-https-reverse-proxy#readme",
@@ -212,8 +212,10 @@ export class CaddyInstant {
212
212
  if (this._session && !this._session.client.connected)
213
213
  this._session = undefined
214
214
 
215
- if (!this._session)
215
+ if (!this._session) {
216
+ await this.deps.config().writeCaddyConfig([], this.proxyKey)
216
217
  this._session = await this.deps.openSession(TEMP_DIR, reason)
218
+ }
217
219
  return this._session
218
220
  }
219
221
 
package/src/index.ts CHANGED
@@ -125,6 +125,11 @@ export const unpluginFactory: UnpluginFactory<Options> = options => ({
125
125
 
126
126
  const _printUrls = server.printUrls.bind(server)
127
127
 
128
+ // Hosts like Nuxt run Vite in middleware mode and never call
129
+ // `printUrls`, so the proxy would silently never start.
130
+ if (server.config.server.middlewareMode)
131
+ 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.')
132
+
128
133
  let source = `localhost:${config.server.port || 5173}`
129
134
  const url = server.resolvedUrls?.local[0]
130
135
  if (url) {
@@ -215,7 +215,11 @@ export async function startHelper(options: HelperBootstrapOptions): Promise<Runn
215
215
 
216
216
  await new Promise<void>((resolve, reject) => {
217
217
  server.once('error', reject)
218
- server.listen(socketPath, () => resolve())
218
+ // On Windows the pipe gets the elevated token's default ACL, which leaves
219
+ // the non-elevated dev server read-only access, so `connect()` fails with
220
+ // EPERM. The token handshake is what authenticates a client there.
221
+ const shareWithUser = process.platform === 'win32'
222
+ server.listen({ path: socketPath, readableAll: shareWithUser, writableAll: shareWithUser }, () => resolve())
219
223
  })
220
224
 
221
225
  // A helper nobody ever connects to is as useless as one whose clients left:
@@ -225,12 +229,11 @@ export async function startHelper(options: HelperBootstrapOptions): Promise<Runn
225
229
  try {
226
230
  // The client is not root: hand the socket back to the developer and keep it
227
231
  // private to them. Without the chown, `connect()` fails with EACCES and the
228
- // client only sees a silent retry loop.
229
- if (typeof options.ownerUid === 'number') {
230
- chownSync(socketPath, options.ownerUid, options.ownerGid ?? options.ownerUid)
231
- chmodSync(socketPath, 0o600)
232
- }
233
- else {
232
+ // client only sees a silent retry loop. Named pipes have no file mode; their
233
+ // access was set at listen time.
234
+ if (process.platform !== 'win32') {
235
+ if (typeof options.ownerUid === 'number')
236
+ chownSync(socketPath, options.ownerUid, options.ownerGid ?? options.ownerUid)
234
237
  chmodSync(socketPath, 0o600)
235
238
  }
236
239
  }
@@ -129,7 +129,7 @@ export async function connectClient(options: ConnectOptions): Promise<Privileged
129
129
  // A permission or protocol error will not resolve by waiting, and
130
130
  // retrying hides the real cause behind a silent hang.
131
131
  const code = (lastError as NodeJS.ErrnoException).code
132
- if (code === 'EACCES' || lastError instanceof HelperConnectionError)
132
+ if (code === 'EACCES' || code === 'EPERM' || lastError instanceof HelperConnectionError)
133
133
  throw lastError
134
134
 
135
135
  await new Promise(resolve => setTimeout(resolve, retryIntervalMs))
@@ -2,7 +2,9 @@ import type { Buffer } from 'node:buffer'
2
2
  import type { PrivilegedClient } from './client'
3
3
  import { spawn, spawnSync } from 'node:child_process'
4
4
  import { randomBytes } from 'node:crypto'
5
- import { platform } from 'node:os'
5
+ import { readFileSync, rmSync } from 'node:fs'
6
+ import { platform, tmpdir } from 'node:os'
7
+ import { join } from 'node:path'
6
8
  import process from 'node:process'
7
9
  import { collectForwardedEnv, connectClient } from './client'
8
10
  import { spawnElevatedOnWindows } from './windows-elevation'
@@ -257,12 +259,23 @@ export async function startPrivilegedHelper(options: LaunchOptions): Promise<Pri
257
259
  ]
258
260
 
259
261
  let child: ReturnType<typeof spawn> | undefined
262
+ let helperExited: { promise: Promise<never>, stop: () => void } | undefined
260
263
 
261
264
  if (!direct && platform() === 'win32') {
262
265
  // UAC: the elevated helper is a separate process and cannot inherit stdio,
263
266
  // so it reports through the named pipe instead. The user's environment is
264
267
  // recovered by the helper from its own process env, which Windows keeps.
265
- await spawnElevatedOnWindows({ file: helperEntry, args: childArgv, cwd: process.cwd() })
268
+ // A helper that dies before listening leaves its error in this file.
269
+ const errorFile = join(tmpdir(), `uhrp-helper-${randomBytes(6).toString('hex')}.log`)
270
+ const elevated = await spawnElevatedOnWindows({
271
+ file: helperEntry,
272
+ args: [...childArgv, '--error-file', errorFile],
273
+ cwd: process.cwd(),
274
+ })
275
+ if (!elevated.ok)
276
+ throw elevated.denied ? new PrivilegeDeniedError(elevated.message) : new Error(elevated.message)
277
+ if (elevated.pid !== undefined)
278
+ helperExited = watchWindowsHelper(elevated.pid, errorFile)
266
279
  }
267
280
  else {
268
281
  const command = direct ? helperEntry : sudoCommand
@@ -311,7 +324,10 @@ export async function startPrivilegedHelper(options: LaunchOptions): Promise<Pri
311
324
  }
312
325
 
313
326
  try {
314
- const client = await connectClient({ socketPath, token, timeoutMs: connectTimeoutMs })
327
+ const connecting = connectClient({ socketPath, token, timeoutMs: connectTimeoutMs })
328
+ // Losing the race to a dead helper leaves this retrying in the background.
329
+ connecting.catch(() => {})
330
+ const client = await (helperExited ? Promise.race([connecting, helperExited.promise]) : connecting)
315
331
  return {
316
332
  client,
317
333
  async close() {
@@ -327,6 +343,59 @@ export async function startPrivilegedHelper(options: LaunchOptions): Promise<Pri
327
343
  catch {}
328
344
  throw error
329
345
  }
346
+ finally {
347
+ helperExited?.stop()
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Fails as soon as the elevated helper is gone, with the error it left behind.
353
+ *
354
+ * Without this, a helper that refused to start on Windows only shows up as the
355
+ * pipe never appearing, after the whole connect timeout.
356
+ */
357
+ function watchWindowsHelper(pid: number, errorFile: string): { promise: Promise<never>, stop: () => void } {
358
+ let timer: ReturnType<typeof setInterval> | undefined
359
+
360
+ const promise = new Promise<never>((_, reject) => {
361
+ timer = setInterval(() => {
362
+ if (isProcessRunning(pid))
363
+ return
364
+
365
+ clearInterval(timer)
366
+ let detail = ''
367
+ try {
368
+ detail = readFileSync(errorFile, 'utf8').trim().slice(-4096)
369
+ }
370
+ catch {}
371
+ reject(new Error(`privileged helper exited before accepting connections.${detail ? ` ${detail}` : ' No diagnostic output from the helper.'}`))
372
+ }, 250)
373
+ })
374
+
375
+ return {
376
+ promise,
377
+ stop() {
378
+ clearInterval(timer)
379
+ try {
380
+ rmSync(errorFile, { force: true })
381
+ }
382
+ catch {}
383
+ },
384
+ }
385
+ }
386
+
387
+ /**
388
+ * The elevated helper cannot be signalled from a non-elevated process, so
389
+ * `kill(pid, 0)` reports EPERM while it runs; only ESRCH means it is gone.
390
+ */
391
+ function isProcessRunning(pid: number): boolean {
392
+ try {
393
+ process.kill(pid, 0)
394
+ return true
395
+ }
396
+ catch (error) {
397
+ return (error as NodeJS.ErrnoException).code !== 'ESRCH'
398
+ }
330
399
  }
331
400
 
332
401
  /** Reuses a helper that is already running for this runtime directory. */
@@ -1,5 +1,6 @@
1
1
  import type { Stats } from 'node:fs'
2
2
  import { lstatSync } from 'node:fs'
3
+ import process from 'node:process'
3
4
 
4
5
  /**
5
6
  * Why a path is refused before the helper runs it.
@@ -71,6 +72,12 @@ export function checkPrivilegedPath(
71
72
  }
72
73
  }
73
74
 
75
+ // Windows has no uid or mode bits: Node reports uid 0 and mode 666 for every
76
+ // writable path, so these checks would refuse everything. Access there is
77
+ // decided by ACLs, and the runtime directory is the per-user `%TEMP%`.
78
+ if (process.platform === 'win32')
79
+ return undefined
80
+
74
81
  const allowedOwner = stats.uid === 0 || (options.ownerUid !== undefined && stats.uid === options.ownerUid)
75
82
  if (!allowedOwner) {
76
83
  return {