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.
@@ -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))
@@ -364,7 +421,7 @@ async function reclaimTree(target, uid, gid) {
364
421
  const walk = (path) => {
365
422
  let stats;
366
423
  try {
367
- stats = lstatSync(path);
424
+ stats = lstatSync2(path);
368
425
  } catch {
369
426
  return;
370
427
  }
@@ -387,11 +444,12 @@ async function reclaimTree(target, uid, gid) {
387
444
  walk(target);
388
445
  return reclaimed;
389
446
  }
390
- async function trustLocalCaWithSystemTools(caddyBin) {
447
+ async function trustLocalCaWithSystemTools(caddyBin, adminSocket) {
448
+ const address = adminSocket ? `unix/${adminSocket}` : "127.0.0.1:2019";
391
449
  try {
392
450
  const { stdout, stderr } = await execFileAsync(
393
451
  caddyBin,
394
- ["trust", "--ca", "local", "--address", "127.0.0.1:2019"],
452
+ ["trust", "--ca", "local", "--address", address],
395
453
  { timeout: 12e4 }
396
454
  );
397
455
  return { trusted: true, output: `${stdout}${stderr}`.trim() };
@@ -404,14 +462,14 @@ async function trustLocalCaWithSystemTools(caddyBin) {
404
462
  }
405
463
  function createNodeHelperDeps(options) {
406
464
  const hostsPath = options.hostsPath ?? HOSTS_PATH;
407
- const log = options.log ?? ((message) => process.stdout.write(`${message}
465
+ const log = options.log ?? ((message) => process2.stdout.write(`${message}
408
466
  `));
409
467
  let caddy;
410
- process.on("exit", () => {
468
+ process2.on("exit", () => {
411
469
  if ((caddy == null ? void 0 : caddy.pid) === void 0)
412
470
  return;
413
471
  try {
414
- process.kill(caddy.pid, "SIGTERM");
472
+ process2.kill(caddy.pid, "SIGTERM");
415
473
  } catch {
416
474
  }
417
475
  });
@@ -437,10 +495,10 @@ function createNodeHelperDeps(options) {
437
495
  const pids = platform() === "win32" ? parseWindowsListeningPids((await execFileAsync("netstat", ["-ano"])).stdout, port) : parseListeningPids((await execFileQuiet("lsof", [`-ti:${port}`, "-sTCP:LISTEN"])).stdout);
438
496
  const killed = [];
439
497
  for (const pid of pids) {
440
- if (pid === process.pid || keepPid !== void 0 && pid === keepPid)
498
+ if (pid === process2.pid || keepPid !== void 0 && pid === keepPid)
441
499
  continue;
442
500
  try {
443
- process.kill(pid, "SIGTERM");
501
+ process2.kill(pid, "SIGTERM");
444
502
  killed.push(pid);
445
503
  } catch {
446
504
  }
@@ -449,16 +507,16 @@ function createNodeHelperDeps(options) {
449
507
  },
450
508
  caddyBin: options.caddyBin,
451
509
  caddyConfigPath: options.caddyConfigPath,
452
- caddyCwd: options.caddyCwd ?? process.cwd(),
510
+ caddyCwd: options.caddyCwd ?? process2.cwd(),
453
511
  caddyEnv: options.caddyEnv ?? {},
454
- trustLocalCa: () => trustLocalCaWithSystemTools(options.caddyBin),
512
+ trustLocalCa: () => trustLocalCaWithSystemTools(options.caddyBin, options.caddyAdminSocket),
455
513
  caddyStoragePath: options.caddyStoragePath,
456
514
  storageOwner: options.storageOwner,
457
515
  startCaddy: (emit) => {
458
516
  var _a, _b;
459
517
  const child = spawn(options.caddyBin, ["run", "--adapter", "caddyfile", "--config", options.caddyConfigPath, "--watch"], {
460
- cwd: options.caddyCwd ?? process.cwd(),
461
- env: { ...process.env, ...options.caddyEnv },
518
+ cwd: options.caddyCwd ?? process2.cwd(),
519
+ env: { ...process2.env, ...options.caddyEnv },
462
520
  stdio: ["ignore", "pipe", "pipe"],
463
521
  detached: platform() !== "win32"
464
522
  });
@@ -527,13 +585,23 @@ var HANDSHAKE_TIMEOUT_MS = 12e4;
527
585
  var DEFAULT_IDLE_TIMEOUT_MS = 3e4;
528
586
  async function startHelper(options) {
529
587
  const { socketPath, token } = options;
530
- const log = options.log ?? ((message) => process2.stdout.write(`[uhrp-helper] ${message}
588
+ const log = options.log ?? ((message) => process3.stdout.write(`[uhrp-helper] ${message}
531
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
+ }
532
599
  const deps = options.deps ?? createNodeHelperDeps({
533
600
  hostsPath: options.hostsPath,
534
601
  log,
535
602
  caddyBin: options.caddyBin,
536
603
  caddyConfigPath: options.caddyConfigPath,
604
+ caddyAdminSocket: options.caddyAdminSocket,
537
605
  caddyCwd: options.caddyCwd,
538
606
  caddyEnv: options.caddyEnv,
539
607
  caddyStoragePath: options.caddyStoragePath,
@@ -598,7 +666,7 @@ async function startHelper(options) {
598
666
  return;
599
667
  }
600
668
  authenticated = true;
601
- socket.write(`${JSON.stringify({ type: "handshake", ok: true, pid: process2.pid })}
669
+ socket.write(`${JSON.stringify({ type: "handshake", ok: true, pid: process3.pid })}
602
670
  `);
603
671
  attachSocket(socket, runtime, log);
604
672
  if (rest.trim() !== "")
@@ -623,21 +691,21 @@ async function startHelper(options) {
623
691
  server.close();
624
692
  return;
625
693
  }
626
- server.close(() => process2.exit(0));
627
- (_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);
628
696
  }, idleTimeoutMs);
629
697
  (_a = idleTimer.unref) == null ? void 0 : _a.call(idleTimer);
630
698
  }
631
- await new Promise((resolve, reject) => {
699
+ await new Promise((resolve2, reject) => {
632
700
  server.once("error", reject);
633
- server.listen(socketPath, () => resolve());
701
+ const shareWithUser = process3.platform === "win32";
702
+ server.listen({ path: socketPath, readableAll: shareWithUser, writableAll: shareWithUser }, () => resolve2());
634
703
  });
635
704
  scheduleIdleExit();
636
705
  try {
637
- if (typeof options.ownerUid === "number") {
638
- chownSync(socketPath, options.ownerUid, options.ownerGid ?? options.ownerUid);
639
- chmodSync(socketPath, 384);
640
- } else {
706
+ if (process3.platform !== "win32") {
707
+ if (typeof options.ownerUid === "number")
708
+ chownSync(socketPath, options.ownerUid, options.ownerGid ?? options.ownerUid);
641
709
  chmodSync(socketPath, 384);
642
710
  }
643
711
  } catch (error) {
@@ -649,14 +717,14 @@ async function startHelper(options) {
649
717
  for (const socket of connections)
650
718
  socket.destroy();
651
719
  connections.clear();
652
- await new Promise((resolve) => {
653
- server.close(() => resolve());
720
+ await new Promise((resolve2) => {
721
+ server.close(() => resolve2());
654
722
  });
655
723
  }
656
724
  };
657
725
  }
658
726
  function removeOwnSocket(socketPath, token) {
659
- if (process2.platform === "win32")
727
+ if (process3.platform === "win32")
660
728
  return;
661
729
  try {
662
730
  const tokensDir = dirname(socketPath);
@@ -682,6 +750,7 @@ function parseArgs(argv) {
682
750
  let ownerUid;
683
751
  let ownerGid;
684
752
  let caddyStorage;
753
+ let caddyAdmin;
685
754
  for (let index = 0; index < argv.length; index++) {
686
755
  const current = argv[index];
687
756
  if (current === "--socket")
@@ -700,6 +769,8 @@ function parseArgs(argv) {
700
769
  ownerGid = Number(argv[++index]);
701
770
  else if (current === "--caddy-storage")
702
771
  caddyStorage = argv[++index] ?? void 0;
772
+ else if (current === "--caddy-admin")
773
+ caddyAdmin = argv[++index] ?? void 0;
703
774
  }
704
775
  if (!socket || !token)
705
776
  throw new Error("usage: privileged-helper --socket <path> --token <token> --caddy <bin> --caddy-config <path>");
@@ -713,11 +784,12 @@ function parseArgs(argv) {
713
784
  caddyConfig,
714
785
  ownerUid: Number.isInteger(ownerUid) ? ownerUid : void 0,
715
786
  ownerGid: Number.isInteger(ownerGid) ? ownerGid : void 0,
716
- caddyStorage
787
+ caddyStorage,
788
+ caddyAdmin
717
789
  };
718
790
  }
719
791
  async function main() {
720
- const args = parseArgs(process3.argv.slice(2));
792
+ const args = parseArgs(process4.argv.slice(2));
721
793
  const helper = await startHelper({
722
794
  socketPath: args.socket,
723
795
  token: args.token,
@@ -727,28 +799,43 @@ async function main() {
727
799
  ownerUid: args.ownerUid,
728
800
  ownerGid: args.ownerGid,
729
801
  caddyStoragePath: args.caddyStorage,
802
+ caddyAdminSocket: args.caddyAdmin,
730
803
  caddyEnv: {
731
- HOME: process3.env.HOME ?? "",
804
+ HOME: process4.env.HOME ?? "",
732
805
  // Keep Caddy's storage next to the invoking user's home even though the
733
806
  // process runs as root.
734
- XDG_DATA_HOME: process3.env.XDG_DATA_HOME ?? ""
807
+ XDG_DATA_HOME: process4.env.XDG_DATA_HOME ?? ""
735
808
  }
736
809
  });
737
810
  for (const signal of ["SIGINT", "SIGQUIT", "SIGTSTP", "SIGHUP"])
738
- process3.on(signal, () => {
811
+ process4.on(signal, () => {
739
812
  });
740
- process3.on("SIGTERM", () => {
813
+ process4.on("SIGTERM", () => {
741
814
  if (helper.runtime.clientCount() > 0)
742
815
  return;
743
- void helper.runtime.dispose().finally(() => process3.exit(0));
816
+ void helper.runtime.dispose().finally(() => process4.exit(0));
744
817
  });
745
- process3.stdout.on("error", () => {
818
+ process4.stdout.on("error", () => {
746
819
  });
747
- process3.stderr.on("error", () => {
820
+ process4.stderr.on("error", () => {
748
821
  });
749
822
  }
750
823
  main().catch((error) => {
751
- process3.stderr.write(`[uhrp-helper] fatal: ${error.message}
824
+ process4.stderr.write(`[uhrp-helper] fatal: ${error.message}
752
825
  `);
753
- 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);
754
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
+ }