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.
@@ -23,21 +23,78 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  ));
24
24
 
25
25
  // src/privileged-helper.ts
26
- var import_node_process3 = __toESM(require("process"), 1);
26
+ var import_node_fs4 = require("fs");
27
+ var import_node_os2 = require("os");
28
+ var import_node_path3 = require("path");
29
+ var import_node_process4 = __toESM(require("process"), 1);
27
30
 
28
31
  // src/privileged/bootstrap.ts
29
32
  var import_node_buffer = require("buffer");
30
- var import_node_fs2 = require("fs");
33
+ var import_node_fs3 = require("fs");
31
34
  var import_node_net3 = require("net");
32
35
  var import_node_path2 = require("path");
33
- var import_node_process2 = __toESM(require("process"), 1);
36
+ var import_node_process3 = __toESM(require("process"), 1);
37
+
38
+ // src/privileged/path-guard.ts
39
+ var import_node_fs = require("fs");
40
+ var import_node_process = __toESM(require("process"), 1);
41
+ function describe(stats) {
42
+ return `uid=${stats.uid} mode=${(stats.mode & 511).toString(8)}`;
43
+ }
44
+ function checkPrivilegedPath(path, options) {
45
+ let stats;
46
+ try {
47
+ stats = (0, import_node_fs.lstatSync)(path);
48
+ } catch (error) {
49
+ return {
50
+ path,
51
+ reason: `${options.label} is not readable: ${error.message}`,
52
+ 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."
53
+ };
54
+ }
55
+ if (stats.isSymbolicLink()) {
56
+ return {
57
+ path,
58
+ reason: `${options.label} is a symbolic link (${describe(stats)})`,
59
+ guidance: "Replace this symlink with a regular file manually or reinstall the affected file; do not bypass the safety check."
60
+ };
61
+ }
62
+ if (!stats.isFile() && !stats.isDirectory()) {
63
+ return {
64
+ path,
65
+ reason: `${options.label} is neither a file nor a directory`,
66
+ guidance: "Provide a regular file or directory at this path manually."
67
+ };
68
+ }
69
+ if (import_node_process.default.platform === "win32")
70
+ return void 0;
71
+ const allowedOwner = stats.uid === 0 || options.ownerUid !== void 0 && stats.uid === options.ownerUid;
72
+ if (!allowedOwner) {
73
+ return {
74
+ path,
75
+ reason: `${options.label} is owned by another user (${describe(stats)})`,
76
+ guidance: "Check ownership manually. This path must be owned by root or the user running the dev server."
77
+ };
78
+ }
79
+ if (stats.mode & 18) {
80
+ return {
81
+ path,
82
+ reason: `${options.label} is group- or world-writable (${describe(stats)})`,
83
+ guidance: "Remove group and world write access manually; do not use chmod 777."
84
+ };
85
+ }
86
+ return void 0;
87
+ }
88
+ function describeRejection(rejection) {
89
+ return `refusing to start: ${rejection.reason} (${rejection.path}). ${rejection.guidance}`;
90
+ }
34
91
 
35
92
  // src/privileged/server.ts
36
93
  var import_node_child_process = require("child_process");
37
- var import_node_fs = require("fs");
94
+ var import_node_fs2 = require("fs");
38
95
  var import_node_os = require("os");
39
96
  var import_node_path = require("path");
40
- var import_node_process = __toESM(require("process"), 1);
97
+ var import_node_process2 = __toESM(require("process"), 1);
41
98
  var import_node_util = require("util");
42
99
 
43
100
  // src/privileged/hosts-file.ts
@@ -188,8 +245,8 @@ function isAllowedFreePort(port) {
188
245
  // src/privileged/server.ts
189
246
  var execFileAsync = (0, import_node_util.promisify)(import_node_child_process.execFile);
190
247
  function execFileQuiet(file, args) {
191
- return new Promise((resolve) => {
192
- (0, import_node_child_process.execFile)(file, args, (error, stdout) => resolve({ stdout: error && !stdout ? "" : stdout }));
248
+ return new Promise((resolve2) => {
249
+ (0, import_node_child_process.execFile)(file, args, (error, stdout) => resolve2({ stdout: error && !stdout ? "" : stdout }));
193
250
  });
194
251
  }
195
252
  var HOSTS_PATH = (0, import_node_os.platform)() === "win32" ? "C:\\Windows\\System32\\drivers\\etc\\hosts" : "/etc/hosts";
@@ -300,7 +357,7 @@ function createHelperRuntime(deps) {
300
357
  try {
301
358
  switch (request.method) {
302
359
  case "ping":
303
- return { id: request.id, ok: true, result: { pid: import_node_process.default.pid } };
360
+ return { id: request.id, ok: true, result: { pid: import_node_process2.default.pid } };
304
361
  case "hosts.add": {
305
362
  const { ip, host } = request.params;
306
363
  if (!isSafeIp(ip) || !isSafeHost(host))
@@ -390,12 +447,12 @@ async function reclaimTree(target, uid, gid) {
390
447
  const walk = (path) => {
391
448
  let stats;
392
449
  try {
393
- stats = (0, import_node_fs.lstatSync)(path);
450
+ stats = (0, import_node_fs2.lstatSync)(path);
394
451
  } catch {
395
452
  return;
396
453
  }
397
454
  try {
398
- (0, import_node_fs.lchownSync)(path, uid, gid);
455
+ (0, import_node_fs2.lchownSync)(path, uid, gid);
399
456
  reclaimed.push(path);
400
457
  } catch {
401
458
  }
@@ -403,7 +460,7 @@ async function reclaimTree(target, uid, gid) {
403
460
  return;
404
461
  let entries;
405
462
  try {
406
- entries = (0, import_node_fs.readdirSync)(path);
463
+ entries = (0, import_node_fs2.readdirSync)(path);
407
464
  } catch {
408
465
  return;
409
466
  }
@@ -413,11 +470,12 @@ async function reclaimTree(target, uid, gid) {
413
470
  walk(target);
414
471
  return reclaimed;
415
472
  }
416
- async function trustLocalCaWithSystemTools(caddyBin) {
473
+ async function trustLocalCaWithSystemTools(caddyBin, adminSocket) {
474
+ const address = adminSocket ? `unix/${adminSocket}` : "127.0.0.1:2019";
417
475
  try {
418
476
  const { stdout, stderr } = await execFileAsync(
419
477
  caddyBin,
420
- ["trust", "--ca", "local", "--address", "127.0.0.1:2019"],
478
+ ["trust", "--ca", "local", "--address", address],
421
479
  { timeout: 12e4 }
422
480
  );
423
481
  return { trusted: true, output: `${stdout}${stderr}`.trim() };
@@ -430,21 +488,21 @@ async function trustLocalCaWithSystemTools(caddyBin) {
430
488
  }
431
489
  function createNodeHelperDeps(options) {
432
490
  const hostsPath = options.hostsPath ?? HOSTS_PATH;
433
- const log = options.log ?? ((message) => import_node_process.default.stdout.write(`${message}
491
+ const log = options.log ?? ((message) => import_node_process2.default.stdout.write(`${message}
434
492
  `));
435
493
  let caddy;
436
- import_node_process.default.on("exit", () => {
494
+ import_node_process2.default.on("exit", () => {
437
495
  if ((caddy == null ? void 0 : caddy.pid) === void 0)
438
496
  return;
439
497
  try {
440
- import_node_process.default.kill(caddy.pid, "SIGTERM");
498
+ import_node_process2.default.kill(caddy.pid, "SIGTERM");
441
499
  } catch {
442
500
  }
443
501
  });
444
502
  return {
445
- readHosts: () => (0, import_node_fs.readFileSync)(hostsPath, "utf8"),
503
+ readHosts: () => (0, import_node_fs2.readFileSync)(hostsPath, "utf8"),
446
504
  writeHosts: (content) => {
447
- (0, import_node_fs.writeFileSync)(hostsPath, content);
505
+ (0, import_node_fs2.writeFileSync)(hostsPath, content);
448
506
  },
449
507
  flushDns: async () => {
450
508
  const candidates = FLUSH_COMMANDS[(0, import_node_os.platform)()] ?? [...FLUSH_FALLBACK];
@@ -463,10 +521,10 @@ function createNodeHelperDeps(options) {
463
521
  const pids = (0, import_node_os.platform)() === "win32" ? parseWindowsListeningPids((await execFileAsync("netstat", ["-ano"])).stdout, port) : parseListeningPids((await execFileQuiet("lsof", [`-ti:${port}`, "-sTCP:LISTEN"])).stdout);
464
522
  const killed = [];
465
523
  for (const pid of pids) {
466
- if (pid === import_node_process.default.pid || keepPid !== void 0 && pid === keepPid)
524
+ if (pid === import_node_process2.default.pid || keepPid !== void 0 && pid === keepPid)
467
525
  continue;
468
526
  try {
469
- import_node_process.default.kill(pid, "SIGTERM");
527
+ import_node_process2.default.kill(pid, "SIGTERM");
470
528
  killed.push(pid);
471
529
  } catch {
472
530
  }
@@ -475,16 +533,16 @@ function createNodeHelperDeps(options) {
475
533
  },
476
534
  caddyBin: options.caddyBin,
477
535
  caddyConfigPath: options.caddyConfigPath,
478
- caddyCwd: options.caddyCwd ?? import_node_process.default.cwd(),
536
+ caddyCwd: options.caddyCwd ?? import_node_process2.default.cwd(),
479
537
  caddyEnv: options.caddyEnv ?? {},
480
- trustLocalCa: () => trustLocalCaWithSystemTools(options.caddyBin),
538
+ trustLocalCa: () => trustLocalCaWithSystemTools(options.caddyBin, options.caddyAdminSocket),
481
539
  caddyStoragePath: options.caddyStoragePath,
482
540
  storageOwner: options.storageOwner,
483
541
  startCaddy: (emit) => {
484
542
  var _a, _b;
485
543
  const child = (0, import_node_child_process.spawn)(options.caddyBin, ["run", "--adapter", "caddyfile", "--config", options.caddyConfigPath, "--watch"], {
486
- cwd: options.caddyCwd ?? import_node_process.default.cwd(),
487
- env: { ...import_node_process.default.env, ...options.caddyEnv },
544
+ cwd: options.caddyCwd ?? import_node_process2.default.cwd(),
545
+ env: { ...import_node_process2.default.env, ...options.caddyEnv },
488
546
  stdio: ["ignore", "pipe", "pipe"],
489
547
  detached: (0, import_node_os.platform)() !== "win32"
490
548
  });
@@ -553,13 +611,23 @@ var HANDSHAKE_TIMEOUT_MS = 12e4;
553
611
  var DEFAULT_IDLE_TIMEOUT_MS = 3e4;
554
612
  async function startHelper(options) {
555
613
  const { socketPath, token } = options;
556
- const log = options.log ?? ((message) => import_node_process2.default.stdout.write(`[uhrp-helper] ${message}
614
+ const log = options.log ?? ((message) => import_node_process3.default.stdout.write(`[uhrp-helper] ${message}
557
615
  `));
616
+ for (const check of [
617
+ checkPrivilegedPath(options.caddyBin, { label: "Caddy binary", ownerUid: options.ownerUid }),
618
+ checkPrivilegedPath(options.caddyConfigPath, { label: "Caddyfile", ownerUid: options.ownerUid })
619
+ ]) {
620
+ if (check) {
621
+ log(describeRejection(check));
622
+ throw new Error(describeRejection(check));
623
+ }
624
+ }
558
625
  const deps = options.deps ?? createNodeHelperDeps({
559
626
  hostsPath: options.hostsPath,
560
627
  log,
561
628
  caddyBin: options.caddyBin,
562
629
  caddyConfigPath: options.caddyConfigPath,
630
+ caddyAdminSocket: options.caddyAdminSocket,
563
631
  caddyCwd: options.caddyCwd,
564
632
  caddyEnv: options.caddyEnv,
565
633
  caddyStoragePath: options.caddyStoragePath,
@@ -569,7 +637,7 @@ async function startHelper(options) {
569
637
  await runtime.sweepStaleEntries().catch(() => {
570
638
  });
571
639
  try {
572
- (0, import_node_fs2.rmSync)(socketPath, { force: true });
640
+ (0, import_node_fs3.rmSync)(socketPath, { force: true });
573
641
  } catch {
574
642
  }
575
643
  const connections = /* @__PURE__ */ new Set();
@@ -624,7 +692,7 @@ async function startHelper(options) {
624
692
  return;
625
693
  }
626
694
  authenticated = true;
627
- socket.write(`${JSON.stringify({ type: "handshake", ok: true, pid: import_node_process2.default.pid })}
695
+ socket.write(`${JSON.stringify({ type: "handshake", ok: true, pid: import_node_process3.default.pid })}
628
696
  `);
629
697
  attachSocket(socket, runtime, log);
630
698
  if (rest.trim() !== "")
@@ -649,22 +717,22 @@ async function startHelper(options) {
649
717
  server.close();
650
718
  return;
651
719
  }
652
- server.close(() => import_node_process2.default.exit(0));
653
- (_b = (_a2 = setTimeout(() => import_node_process2.default.exit(0), 1e3)).unref) == null ? void 0 : _b.call(_a2);
720
+ server.close(() => import_node_process3.default.exit(0));
721
+ (_b = (_a2 = setTimeout(() => import_node_process3.default.exit(0), 1e3)).unref) == null ? void 0 : _b.call(_a2);
654
722
  }, idleTimeoutMs);
655
723
  (_a = idleTimer.unref) == null ? void 0 : _a.call(idleTimer);
656
724
  }
657
- await new Promise((resolve, reject) => {
725
+ await new Promise((resolve2, reject) => {
658
726
  server.once("error", reject);
659
- server.listen(socketPath, () => resolve());
727
+ const shareWithUser = import_node_process3.default.platform === "win32";
728
+ server.listen({ path: socketPath, readableAll: shareWithUser, writableAll: shareWithUser }, () => resolve2());
660
729
  });
661
730
  scheduleIdleExit();
662
731
  try {
663
- if (typeof options.ownerUid === "number") {
664
- (0, import_node_fs2.chownSync)(socketPath, options.ownerUid, options.ownerGid ?? options.ownerUid);
665
- (0, import_node_fs2.chmodSync)(socketPath, 384);
666
- } else {
667
- (0, import_node_fs2.chmodSync)(socketPath, 384);
732
+ if (import_node_process3.default.platform !== "win32") {
733
+ if (typeof options.ownerUid === "number")
734
+ (0, import_node_fs3.chownSync)(socketPath, options.ownerUid, options.ownerGid ?? options.ownerUid);
735
+ (0, import_node_fs3.chmodSync)(socketPath, 384);
668
736
  }
669
737
  } catch (error) {
670
738
  log(`could not set socket ownership: ${error.message}`);
@@ -675,25 +743,25 @@ async function startHelper(options) {
675
743
  for (const socket of connections)
676
744
  socket.destroy();
677
745
  connections.clear();
678
- await new Promise((resolve) => {
679
- server.close(() => resolve());
746
+ await new Promise((resolve2) => {
747
+ server.close(() => resolve2());
680
748
  });
681
749
  }
682
750
  };
683
751
  }
684
752
  function removeOwnSocket(socketPath, token) {
685
- if (import_node_process2.default.platform === "win32")
753
+ if (import_node_process3.default.platform === "win32")
686
754
  return;
687
755
  try {
688
756
  const tokensDir = (0, import_node_path2.dirname)(socketPath);
689
757
  const tokenFile = (0, import_node_path2.join)(tokensDir, "helper.token");
690
- const current = (0, import_node_fs2.existsSync)(tokenFile) ? (0, import_node_fs2.readFileSync)(tokenFile, "utf8").trim() : void 0;
758
+ const current = (0, import_node_fs3.existsSync)(tokenFile) ? (0, import_node_fs3.readFileSync)(tokenFile, "utf8").trim() : void 0;
691
759
  if (current === token)
692
- (0, import_node_fs2.rmSync)(tokenFile, { force: true });
760
+ (0, import_node_fs3.rmSync)(tokenFile, { force: true });
693
761
  } catch {
694
762
  }
695
763
  try {
696
- (0, import_node_fs2.rmSync)(socketPath, { force: true });
764
+ (0, import_node_fs3.rmSync)(socketPath, { force: true });
697
765
  } catch {
698
766
  }
699
767
  }
@@ -708,6 +776,7 @@ function parseArgs(argv) {
708
776
  let ownerUid;
709
777
  let ownerGid;
710
778
  let caddyStorage;
779
+ let caddyAdmin;
711
780
  for (let index = 0; index < argv.length; index++) {
712
781
  const current = argv[index];
713
782
  if (current === "--socket")
@@ -726,6 +795,8 @@ function parseArgs(argv) {
726
795
  ownerGid = Number(argv[++index]);
727
796
  else if (current === "--caddy-storage")
728
797
  caddyStorage = argv[++index] ?? void 0;
798
+ else if (current === "--caddy-admin")
799
+ caddyAdmin = argv[++index] ?? void 0;
729
800
  }
730
801
  if (!socket || !token)
731
802
  throw new Error("usage: privileged-helper --socket <path> --token <token> --caddy <bin> --caddy-config <path>");
@@ -739,11 +810,12 @@ function parseArgs(argv) {
739
810
  caddyConfig,
740
811
  ownerUid: Number.isInteger(ownerUid) ? ownerUid : void 0,
741
812
  ownerGid: Number.isInteger(ownerGid) ? ownerGid : void 0,
742
- caddyStorage
813
+ caddyStorage,
814
+ caddyAdmin
743
815
  };
744
816
  }
745
817
  async function main() {
746
- const args = parseArgs(import_node_process3.default.argv.slice(2));
818
+ const args = parseArgs(import_node_process4.default.argv.slice(2));
747
819
  const helper = await startHelper({
748
820
  socketPath: args.socket,
749
821
  token: args.token,
@@ -753,29 +825,44 @@ async function main() {
753
825
  ownerUid: args.ownerUid,
754
826
  ownerGid: args.ownerGid,
755
827
  caddyStoragePath: args.caddyStorage,
828
+ caddyAdminSocket: args.caddyAdmin,
756
829
  caddyEnv: {
757
- HOME: import_node_process3.default.env.HOME ?? "",
830
+ HOME: import_node_process4.default.env.HOME ?? "",
758
831
  // Keep Caddy's storage next to the invoking user's home even though the
759
832
  // process runs as root.
760
- XDG_DATA_HOME: import_node_process3.default.env.XDG_DATA_HOME ?? ""
833
+ XDG_DATA_HOME: import_node_process4.default.env.XDG_DATA_HOME ?? ""
761
834
  }
762
835
  });
763
836
  for (const signal of ["SIGINT", "SIGQUIT", "SIGTSTP", "SIGHUP"])
764
- import_node_process3.default.on(signal, () => {
837
+ import_node_process4.default.on(signal, () => {
765
838
  });
766
- import_node_process3.default.on("SIGTERM", () => {
839
+ import_node_process4.default.on("SIGTERM", () => {
767
840
  if (helper.runtime.clientCount() > 0)
768
841
  return;
769
- void helper.runtime.dispose().finally(() => import_node_process3.default.exit(0));
842
+ void helper.runtime.dispose().finally(() => import_node_process4.default.exit(0));
770
843
  });
771
- import_node_process3.default.stdout.on("error", () => {
844
+ import_node_process4.default.stdout.on("error", () => {
772
845
  });
773
- import_node_process3.default.stderr.on("error", () => {
846
+ import_node_process4.default.stderr.on("error", () => {
774
847
  });
775
848
  }
776
849
  main().catch((error) => {
777
- import_node_process3.default.stderr.write(`[uhrp-helper] fatal: ${error.message}
850
+ import_node_process4.default.stderr.write(`[uhrp-helper] fatal: ${error.message}
778
851
  `);
779
- import_node_process3.default.exit(1);
852
+ const errorFile = errorFileFrom(import_node_process4.default.argv.slice(2));
853
+ if (errorFile) {
854
+ try {
855
+ (0, import_node_fs4.writeFileSync)(errorFile, error.message, { flag: "wx" });
856
+ } catch {
857
+ }
858
+ }
859
+ import_node_process4.default.exit(1);
780
860
  });
861
+ function errorFileFrom(argv) {
862
+ const index = argv.indexOf("--error-file");
863
+ const path = index >= 0 ? argv[index + 1] : void 0;
864
+ if (!path || !/^uhrp-helper-[0-9a-f]+\.log$/.test((0, import_node_path3.basename)(path)))
865
+ return void 0;
866
+ return (0, import_node_path3.resolve)((0, import_node_path3.dirname)(path)) === (0, import_node_path3.resolve)((0, import_node_os2.tmpdir)()) ? path : void 0;
867
+ }
781
868
  exports.default = module.exports;