unplugin-https-reverse-proxy 4.1.0-beta.8 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,21 +3,78 @@ import {
3
3
  } from "./chunk-RKHJN6KY.js";
4
4
 
5
5
  // src/privileged-helper.ts
6
- import process3 from "node:process";
6
+ import { writeFileSync as writeFileSync2 } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { basename, dirname as dirname2, resolve } from "node:path";
9
+ import process4 from "node:process";
7
10
 
8
11
  // src/privileged/bootstrap.ts
9
12
  import { Buffer } from "node:buffer";
10
13
  import { chmodSync, chownSync, existsSync, readFileSync as readFileSync2, rmSync } from "node:fs";
11
14
  import { createServer } from "node:net";
12
15
  import { dirname, join as join2 } from "node:path";
13
- import process2 from "node:process";
16
+ import process3 from "node:process";
17
+
18
+ // src/privileged/path-guard.ts
19
+ import { lstatSync } from "node:fs";
20
+ import process from "node:process";
21
+ function describe(stats) {
22
+ return `uid=${stats.uid} mode=${(stats.mode & 511).toString(8)}`;
23
+ }
24
+ function checkPrivilegedPath(path, options) {
25
+ let stats;
26
+ try {
27
+ stats = lstatSync(path);
28
+ } catch (error) {
29
+ return {
30
+ path,
31
+ reason: `${options.label} is not readable: ${error.message}`,
32
+ guidance: "Check that this path exists and that you can access its parent directories. Fix access manually; do not make the path group- or world-writable."
33
+ };
34
+ }
35
+ if (stats.isSymbolicLink()) {
36
+ return {
37
+ path,
38
+ reason: `${options.label} is a symbolic link (${describe(stats)})`,
39
+ guidance: "Replace this symlink with a regular file manually or reinstall the affected file; do not bypass the safety check."
40
+ };
41
+ }
42
+ if (!stats.isFile() && !stats.isDirectory()) {
43
+ return {
44
+ path,
45
+ reason: `${options.label} is neither a file nor a directory`,
46
+ guidance: "Provide a regular file or directory at this path manually."
47
+ };
48
+ }
49
+ if (process.platform === "win32")
50
+ return void 0;
51
+ const allowedOwner = stats.uid === 0 || options.ownerUid !== void 0 && stats.uid === options.ownerUid;
52
+ if (!allowedOwner) {
53
+ return {
54
+ path,
55
+ reason: `${options.label} is owned by another user (${describe(stats)})`,
56
+ guidance: "Check ownership manually. This path must be owned by root or the user running the dev server."
57
+ };
58
+ }
59
+ if (stats.mode & 18) {
60
+ return {
61
+ path,
62
+ reason: `${options.label} is group- or world-writable (${describe(stats)})`,
63
+ guidance: "Remove group and world write access manually; do not use chmod 777."
64
+ };
65
+ }
66
+ return void 0;
67
+ }
68
+ function describeRejection(rejection) {
69
+ return `refusing to start: ${rejection.reason} (${rejection.path}). ${rejection.guidance}`;
70
+ }
14
71
 
15
72
  // src/privileged/server.ts
16
73
  import { execFile, spawn } from "node:child_process";
17
- import { lchownSync, lstatSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
74
+ import { lchownSync, lstatSync as lstatSync2, readdirSync, readFileSync, writeFileSync } from "node:fs";
18
75
  import { platform } from "node:os";
19
76
  import { join } from "node:path";
20
- import process from "node:process";
77
+ import process2 from "node:process";
21
78
  import { promisify } from "node:util";
22
79
 
23
80
  // src/privileged/hosts-file.ts
@@ -162,8 +219,8 @@ function isAllowedFreePort(port) {
162
219
  // src/privileged/server.ts
163
220
  var execFileAsync = promisify(execFile);
164
221
  function execFileQuiet(file, args) {
165
- return new Promise((resolve) => {
166
- execFile(file, args, (error, stdout) => resolve({ stdout: error && !stdout ? "" : stdout }));
222
+ return new Promise((resolve2) => {
223
+ execFile(file, args, (error, stdout) => resolve2({ stdout: error && !stdout ? "" : stdout }));
167
224
  });
168
225
  }
169
226
  var HOSTS_PATH = platform() === "win32" ? "C:\\Windows\\System32\\drivers\\etc\\hosts" : "/etc/hosts";
@@ -274,7 +331,7 @@ function createHelperRuntime(deps) {
274
331
  try {
275
332
  switch (request.method) {
276
333
  case "ping":
277
- return { id: request.id, ok: true, result: { pid: process.pid } };
334
+ return { id: request.id, ok: true, result: { pid: process2.pid } };
278
335
  case "hosts.add": {
279
336
  const { ip, host } = request.params;
280
337
  if (!isSafeIp(ip) || !isSafeHost(host))
@@ -355,7 +412,8 @@ function createHelperRuntime(deps) {
355
412
  await dispose();
356
413
  },
357
414
  dispose,
358
- sweepStaleEntries
415
+ sweepStaleEntries,
416
+ clientCount: () => clients.size
359
417
  };
360
418
  }
361
419
  async function reclaimTree(target, uid, gid) {
@@ -363,7 +421,7 @@ async function reclaimTree(target, uid, gid) {
363
421
  const walk = (path) => {
364
422
  let stats;
365
423
  try {
366
- stats = lstatSync(path);
424
+ stats = lstatSync2(path);
367
425
  } catch {
368
426
  return;
369
427
  }
@@ -386,11 +444,12 @@ async function reclaimTree(target, uid, gid) {
386
444
  walk(target);
387
445
  return reclaimed;
388
446
  }
389
- async function trustLocalCaWithSystemTools(caddyBin) {
447
+ async function trustLocalCaWithSystemTools(caddyBin, adminSocket) {
448
+ const address = adminSocket ? `unix/${adminSocket}` : "127.0.0.1:2019";
390
449
  try {
391
450
  const { stdout, stderr } = await execFileAsync(
392
451
  caddyBin,
393
- ["trust", "--ca", "local", "--address", "127.0.0.1:2019"],
452
+ ["trust", "--ca", "local", "--address", address],
394
453
  { timeout: 12e4 }
395
454
  );
396
455
  return { trusted: true, output: `${stdout}${stderr}`.trim() };
@@ -403,9 +462,17 @@ async function trustLocalCaWithSystemTools(caddyBin) {
403
462
  }
404
463
  function createNodeHelperDeps(options) {
405
464
  const hostsPath = options.hostsPath ?? HOSTS_PATH;
406
- const log = options.log ?? ((message) => process.stdout.write(`${message}
465
+ const log = options.log ?? ((message) => process2.stdout.write(`${message}
407
466
  `));
408
467
  let caddy;
468
+ process2.on("exit", () => {
469
+ if ((caddy == null ? void 0 : caddy.pid) === void 0)
470
+ return;
471
+ try {
472
+ process2.kill(caddy.pid, "SIGTERM");
473
+ } catch {
474
+ }
475
+ });
409
476
  return {
410
477
  readHosts: () => readFileSync(hostsPath, "utf8"),
411
478
  writeHosts: (content) => {
@@ -428,10 +495,10 @@ function createNodeHelperDeps(options) {
428
495
  const pids = platform() === "win32" ? parseWindowsListeningPids((await execFileAsync("netstat", ["-ano"])).stdout, port) : parseListeningPids((await execFileQuiet("lsof", [`-ti:${port}`, "-sTCP:LISTEN"])).stdout);
429
496
  const killed = [];
430
497
  for (const pid of pids) {
431
- if (pid === process.pid || keepPid !== void 0 && pid === keepPid)
498
+ if (pid === process2.pid || keepPid !== void 0 && pid === keepPid)
432
499
  continue;
433
500
  try {
434
- process.kill(pid, "SIGTERM");
501
+ process2.kill(pid, "SIGTERM");
435
502
  killed.push(pid);
436
503
  } catch {
437
504
  }
@@ -440,17 +507,18 @@ function createNodeHelperDeps(options) {
440
507
  },
441
508
  caddyBin: options.caddyBin,
442
509
  caddyConfigPath: options.caddyConfigPath,
443
- caddyCwd: options.caddyCwd ?? process.cwd(),
510
+ caddyCwd: options.caddyCwd ?? process2.cwd(),
444
511
  caddyEnv: options.caddyEnv ?? {},
445
- trustLocalCa: () => trustLocalCaWithSystemTools(options.caddyBin),
512
+ trustLocalCa: () => trustLocalCaWithSystemTools(options.caddyBin, options.caddyAdminSocket),
446
513
  caddyStoragePath: options.caddyStoragePath,
447
514
  storageOwner: options.storageOwner,
448
515
  startCaddy: (emit) => {
449
516
  var _a, _b;
450
517
  const child = spawn(options.caddyBin, ["run", "--adapter", "caddyfile", "--config", options.caddyConfigPath, "--watch"], {
451
- cwd: options.caddyCwd ?? process.cwd(),
452
- env: { ...process.env, ...options.caddyEnv },
453
- stdio: ["ignore", "pipe", "pipe"]
518
+ cwd: options.caddyCwd ?? process2.cwd(),
519
+ env: { ...process2.env, ...options.caddyEnv },
520
+ stdio: ["ignore", "pipe", "pipe"],
521
+ detached: platform() !== "win32"
454
522
  });
455
523
  const handle = {
456
524
  pid: child.pid,
@@ -517,13 +585,23 @@ var HANDSHAKE_TIMEOUT_MS = 12e4;
517
585
  var DEFAULT_IDLE_TIMEOUT_MS = 3e4;
518
586
  async function startHelper(options) {
519
587
  const { socketPath, token } = options;
520
- const log = options.log ?? ((message) => process2.stdout.write(`[uhrp-helper] ${message}
588
+ const log = options.log ?? ((message) => process3.stdout.write(`[uhrp-helper] ${message}
521
589
  `));
590
+ for (const check of [
591
+ checkPrivilegedPath(options.caddyBin, { label: "Caddy binary", ownerUid: options.ownerUid }),
592
+ checkPrivilegedPath(options.caddyConfigPath, { label: "Caddyfile", ownerUid: options.ownerUid })
593
+ ]) {
594
+ if (check) {
595
+ log(describeRejection(check));
596
+ throw new Error(describeRejection(check));
597
+ }
598
+ }
522
599
  const deps = options.deps ?? createNodeHelperDeps({
523
600
  hostsPath: options.hostsPath,
524
601
  log,
525
602
  caddyBin: options.caddyBin,
526
603
  caddyConfigPath: options.caddyConfigPath,
604
+ caddyAdminSocket: options.caddyAdminSocket,
527
605
  caddyCwd: options.caddyCwd,
528
606
  caddyEnv: options.caddyEnv,
529
607
  caddyStoragePath: options.caddyStoragePath,
@@ -588,7 +666,7 @@ async function startHelper(options) {
588
666
  return;
589
667
  }
590
668
  authenticated = true;
591
- socket.write(`${JSON.stringify({ type: "handshake", ok: true, pid: process2.pid })}
669
+ socket.write(`${JSON.stringify({ type: "handshake", ok: true, pid: process3.pid })}
592
670
  `);
593
671
  attachSocket(socket, runtime, log);
594
672
  if (rest.trim() !== "")
@@ -613,21 +691,21 @@ async function startHelper(options) {
613
691
  server.close();
614
692
  return;
615
693
  }
616
- server.close(() => process2.exit(0));
617
- (_b = (_a2 = setTimeout(() => process2.exit(0), 1e3)).unref) == null ? void 0 : _b.call(_a2);
694
+ server.close(() => process3.exit(0));
695
+ (_b = (_a2 = setTimeout(() => process3.exit(0), 1e3)).unref) == null ? void 0 : _b.call(_a2);
618
696
  }, idleTimeoutMs);
619
697
  (_a = idleTimer.unref) == null ? void 0 : _a.call(idleTimer);
620
698
  }
621
- await new Promise((resolve, reject) => {
699
+ await new Promise((resolve2, reject) => {
622
700
  server.once("error", reject);
623
- server.listen(socketPath, () => resolve());
701
+ const shareWithUser = process3.platform === "win32";
702
+ server.listen({ path: socketPath, readableAll: shareWithUser, writableAll: shareWithUser }, () => resolve2());
624
703
  });
625
704
  scheduleIdleExit();
626
705
  try {
627
- if (typeof options.ownerUid === "number") {
628
- chownSync(socketPath, options.ownerUid, options.ownerGid ?? options.ownerUid);
629
- chmodSync(socketPath, 384);
630
- } else {
706
+ if (process3.platform !== "win32") {
707
+ if (typeof options.ownerUid === "number")
708
+ chownSync(socketPath, options.ownerUid, options.ownerGid ?? options.ownerUid);
631
709
  chmodSync(socketPath, 384);
632
710
  }
633
711
  } catch (error) {
@@ -639,14 +717,14 @@ async function startHelper(options) {
639
717
  for (const socket of connections)
640
718
  socket.destroy();
641
719
  connections.clear();
642
- await new Promise((resolve) => {
643
- server.close(() => resolve());
720
+ await new Promise((resolve2) => {
721
+ server.close(() => resolve2());
644
722
  });
645
723
  }
646
724
  };
647
725
  }
648
726
  function removeOwnSocket(socketPath, token) {
649
- if (process2.platform === "win32")
727
+ if (process3.platform === "win32")
650
728
  return;
651
729
  try {
652
730
  const tokensDir = dirname(socketPath);
@@ -672,6 +750,7 @@ function parseArgs(argv) {
672
750
  let ownerUid;
673
751
  let ownerGid;
674
752
  let caddyStorage;
753
+ let caddyAdmin;
675
754
  for (let index = 0; index < argv.length; index++) {
676
755
  const current = argv[index];
677
756
  if (current === "--socket")
@@ -690,6 +769,8 @@ function parseArgs(argv) {
690
769
  ownerGid = Number(argv[++index]);
691
770
  else if (current === "--caddy-storage")
692
771
  caddyStorage = argv[++index] ?? void 0;
772
+ else if (current === "--caddy-admin")
773
+ caddyAdmin = argv[++index] ?? void 0;
693
774
  }
694
775
  if (!socket || !token)
695
776
  throw new Error("usage: privileged-helper --socket <path> --token <token> --caddy <bin> --caddy-config <path>");
@@ -703,11 +784,12 @@ function parseArgs(argv) {
703
784
  caddyConfig,
704
785
  ownerUid: Number.isInteger(ownerUid) ? ownerUid : void 0,
705
786
  ownerGid: Number.isInteger(ownerGid) ? ownerGid : void 0,
706
- caddyStorage
787
+ caddyStorage,
788
+ caddyAdmin
707
789
  };
708
790
  }
709
791
  async function main() {
710
- const args = parseArgs(process3.argv.slice(2));
792
+ const args = parseArgs(process4.argv.slice(2));
711
793
  const helper = await startHelper({
712
794
  socketPath: args.socket,
713
795
  token: args.token,
@@ -717,27 +799,43 @@ async function main() {
717
799
  ownerUid: args.ownerUid,
718
800
  ownerGid: args.ownerGid,
719
801
  caddyStoragePath: args.caddyStorage,
802
+ caddyAdminSocket: args.caddyAdmin,
720
803
  caddyEnv: {
721
- HOME: process3.env.HOME ?? "",
804
+ HOME: process4.env.HOME ?? "",
722
805
  // Keep Caddy's storage next to the invoking user's home even though the
723
806
  // process runs as root.
724
- XDG_DATA_HOME: process3.env.XDG_DATA_HOME ?? ""
807
+ XDG_DATA_HOME: process4.env.XDG_DATA_HOME ?? ""
725
808
  }
726
809
  });
727
- process3.on("SIGINT", () => {
810
+ for (const signal of ["SIGINT", "SIGQUIT", "SIGTSTP", "SIGHUP"])
811
+ process4.on(signal, () => {
812
+ });
813
+ process4.on("SIGTERM", () => {
814
+ if (helper.runtime.clientCount() > 0)
815
+ return;
816
+ void helper.runtime.dispose().finally(() => process4.exit(0));
728
817
  });
729
- const shutdown = () => {
730
- void helper.runtime.dispose().finally(() => process3.exit(0));
731
- };
732
- process3.on("SIGTERM", shutdown);
733
- process3.on("SIGHUP", shutdown);
734
- process3.stdout.on("error", () => {
818
+ process4.stdout.on("error", () => {
735
819
  });
736
- process3.stderr.on("error", () => {
820
+ process4.stderr.on("error", () => {
737
821
  });
738
822
  }
739
823
  main().catch((error) => {
740
- process3.stderr.write(`[uhrp-helper] fatal: ${error.message}
824
+ process4.stderr.write(`[uhrp-helper] fatal: ${error.message}
741
825
  `);
742
- process3.exit(1);
826
+ const errorFile = errorFileFrom(process4.argv.slice(2));
827
+ if (errorFile) {
828
+ try {
829
+ writeFileSync2(errorFile, error.message, { flag: "wx" });
830
+ } catch {
831
+ }
832
+ }
833
+ process4.exit(1);
743
834
  });
835
+ function errorFileFrom(argv) {
836
+ const index = argv.indexOf("--error-file");
837
+ const path = index >= 0 ? argv[index + 1] : void 0;
838
+ if (!path || !/^uhrp-helper-[0-9a-f]+\.log$/.test(basename(path)))
839
+ return void 0;
840
+ return resolve(dirname2(path)) === resolve(tmpdir()) ? path : void 0;
841
+ }