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.
@@ -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))
@@ -381,7 +438,8 @@ function createHelperRuntime(deps) {
381
438
  await dispose();
382
439
  },
383
440
  dispose,
384
- sweepStaleEntries
441
+ sweepStaleEntries,
442
+ clientCount: () => clients.size
385
443
  };
386
444
  }
387
445
  async function reclaimTree(target, uid, gid) {
@@ -389,12 +447,12 @@ async function reclaimTree(target, uid, gid) {
389
447
  const walk = (path) => {
390
448
  let stats;
391
449
  try {
392
- stats = (0, import_node_fs.lstatSync)(path);
450
+ stats = (0, import_node_fs2.lstatSync)(path);
393
451
  } catch {
394
452
  return;
395
453
  }
396
454
  try {
397
- (0, import_node_fs.lchownSync)(path, uid, gid);
455
+ (0, import_node_fs2.lchownSync)(path, uid, gid);
398
456
  reclaimed.push(path);
399
457
  } catch {
400
458
  }
@@ -402,7 +460,7 @@ async function reclaimTree(target, uid, gid) {
402
460
  return;
403
461
  let entries;
404
462
  try {
405
- entries = (0, import_node_fs.readdirSync)(path);
463
+ entries = (0, import_node_fs2.readdirSync)(path);
406
464
  } catch {
407
465
  return;
408
466
  }
@@ -412,11 +470,12 @@ async function reclaimTree(target, uid, gid) {
412
470
  walk(target);
413
471
  return reclaimed;
414
472
  }
415
- async function trustLocalCaWithSystemTools(caddyBin) {
473
+ async function trustLocalCaWithSystemTools(caddyBin, adminSocket) {
474
+ const address = adminSocket ? `unix/${adminSocket}` : "127.0.0.1:2019";
416
475
  try {
417
476
  const { stdout, stderr } = await execFileAsync(
418
477
  caddyBin,
419
- ["trust", "--ca", "local", "--address", "127.0.0.1:2019"],
478
+ ["trust", "--ca", "local", "--address", address],
420
479
  { timeout: 12e4 }
421
480
  );
422
481
  return { trusted: true, output: `${stdout}${stderr}`.trim() };
@@ -429,13 +488,21 @@ async function trustLocalCaWithSystemTools(caddyBin) {
429
488
  }
430
489
  function createNodeHelperDeps(options) {
431
490
  const hostsPath = options.hostsPath ?? HOSTS_PATH;
432
- 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}
433
492
  `));
434
493
  let caddy;
494
+ import_node_process2.default.on("exit", () => {
495
+ if ((caddy == null ? void 0 : caddy.pid) === void 0)
496
+ return;
497
+ try {
498
+ import_node_process2.default.kill(caddy.pid, "SIGTERM");
499
+ } catch {
500
+ }
501
+ });
435
502
  return {
436
- readHosts: () => (0, import_node_fs.readFileSync)(hostsPath, "utf8"),
503
+ readHosts: () => (0, import_node_fs2.readFileSync)(hostsPath, "utf8"),
437
504
  writeHosts: (content) => {
438
- (0, import_node_fs.writeFileSync)(hostsPath, content);
505
+ (0, import_node_fs2.writeFileSync)(hostsPath, content);
439
506
  },
440
507
  flushDns: async () => {
441
508
  const candidates = FLUSH_COMMANDS[(0, import_node_os.platform)()] ?? [...FLUSH_FALLBACK];
@@ -454,10 +521,10 @@ function createNodeHelperDeps(options) {
454
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);
455
522
  const killed = [];
456
523
  for (const pid of pids) {
457
- 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)
458
525
  continue;
459
526
  try {
460
- import_node_process.default.kill(pid, "SIGTERM");
527
+ import_node_process2.default.kill(pid, "SIGTERM");
461
528
  killed.push(pid);
462
529
  } catch {
463
530
  }
@@ -466,17 +533,18 @@ function createNodeHelperDeps(options) {
466
533
  },
467
534
  caddyBin: options.caddyBin,
468
535
  caddyConfigPath: options.caddyConfigPath,
469
- caddyCwd: options.caddyCwd ?? import_node_process.default.cwd(),
536
+ caddyCwd: options.caddyCwd ?? import_node_process2.default.cwd(),
470
537
  caddyEnv: options.caddyEnv ?? {},
471
- trustLocalCa: () => trustLocalCaWithSystemTools(options.caddyBin),
538
+ trustLocalCa: () => trustLocalCaWithSystemTools(options.caddyBin, options.caddyAdminSocket),
472
539
  caddyStoragePath: options.caddyStoragePath,
473
540
  storageOwner: options.storageOwner,
474
541
  startCaddy: (emit) => {
475
542
  var _a, _b;
476
543
  const child = (0, import_node_child_process.spawn)(options.caddyBin, ["run", "--adapter", "caddyfile", "--config", options.caddyConfigPath, "--watch"], {
477
- cwd: options.caddyCwd ?? import_node_process.default.cwd(),
478
- env: { ...import_node_process.default.env, ...options.caddyEnv },
479
- stdio: ["ignore", "pipe", "pipe"]
544
+ cwd: options.caddyCwd ?? import_node_process2.default.cwd(),
545
+ env: { ...import_node_process2.default.env, ...options.caddyEnv },
546
+ stdio: ["ignore", "pipe", "pipe"],
547
+ detached: (0, import_node_os.platform)() !== "win32"
480
548
  });
481
549
  const handle = {
482
550
  pid: child.pid,
@@ -543,13 +611,23 @@ var HANDSHAKE_TIMEOUT_MS = 12e4;
543
611
  var DEFAULT_IDLE_TIMEOUT_MS = 3e4;
544
612
  async function startHelper(options) {
545
613
  const { socketPath, token } = options;
546
- 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}
547
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
+ }
548
625
  const deps = options.deps ?? createNodeHelperDeps({
549
626
  hostsPath: options.hostsPath,
550
627
  log,
551
628
  caddyBin: options.caddyBin,
552
629
  caddyConfigPath: options.caddyConfigPath,
630
+ caddyAdminSocket: options.caddyAdminSocket,
553
631
  caddyCwd: options.caddyCwd,
554
632
  caddyEnv: options.caddyEnv,
555
633
  caddyStoragePath: options.caddyStoragePath,
@@ -559,7 +637,7 @@ async function startHelper(options) {
559
637
  await runtime.sweepStaleEntries().catch(() => {
560
638
  });
561
639
  try {
562
- (0, import_node_fs2.rmSync)(socketPath, { force: true });
640
+ (0, import_node_fs3.rmSync)(socketPath, { force: true });
563
641
  } catch {
564
642
  }
565
643
  const connections = /* @__PURE__ */ new Set();
@@ -614,7 +692,7 @@ async function startHelper(options) {
614
692
  return;
615
693
  }
616
694
  authenticated = true;
617
- 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 })}
618
696
  `);
619
697
  attachSocket(socket, runtime, log);
620
698
  if (rest.trim() !== "")
@@ -639,22 +717,22 @@ async function startHelper(options) {
639
717
  server.close();
640
718
  return;
641
719
  }
642
- server.close(() => import_node_process2.default.exit(0));
643
- (_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);
644
722
  }, idleTimeoutMs);
645
723
  (_a = idleTimer.unref) == null ? void 0 : _a.call(idleTimer);
646
724
  }
647
- await new Promise((resolve, reject) => {
725
+ await new Promise((resolve2, reject) => {
648
726
  server.once("error", reject);
649
- server.listen(socketPath, () => resolve());
727
+ const shareWithUser = import_node_process3.default.platform === "win32";
728
+ server.listen({ path: socketPath, readableAll: shareWithUser, writableAll: shareWithUser }, () => resolve2());
650
729
  });
651
730
  scheduleIdleExit();
652
731
  try {
653
- if (typeof options.ownerUid === "number") {
654
- (0, import_node_fs2.chownSync)(socketPath, options.ownerUid, options.ownerGid ?? options.ownerUid);
655
- (0, import_node_fs2.chmodSync)(socketPath, 384);
656
- } else {
657
- (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);
658
736
  }
659
737
  } catch (error) {
660
738
  log(`could not set socket ownership: ${error.message}`);
@@ -665,25 +743,25 @@ async function startHelper(options) {
665
743
  for (const socket of connections)
666
744
  socket.destroy();
667
745
  connections.clear();
668
- await new Promise((resolve) => {
669
- server.close(() => resolve());
746
+ await new Promise((resolve2) => {
747
+ server.close(() => resolve2());
670
748
  });
671
749
  }
672
750
  };
673
751
  }
674
752
  function removeOwnSocket(socketPath, token) {
675
- if (import_node_process2.default.platform === "win32")
753
+ if (import_node_process3.default.platform === "win32")
676
754
  return;
677
755
  try {
678
756
  const tokensDir = (0, import_node_path2.dirname)(socketPath);
679
757
  const tokenFile = (0, import_node_path2.join)(tokensDir, "helper.token");
680
- 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;
681
759
  if (current === token)
682
- (0, import_node_fs2.rmSync)(tokenFile, { force: true });
760
+ (0, import_node_fs3.rmSync)(tokenFile, { force: true });
683
761
  } catch {
684
762
  }
685
763
  try {
686
- (0, import_node_fs2.rmSync)(socketPath, { force: true });
764
+ (0, import_node_fs3.rmSync)(socketPath, { force: true });
687
765
  } catch {
688
766
  }
689
767
  }
@@ -698,6 +776,7 @@ function parseArgs(argv) {
698
776
  let ownerUid;
699
777
  let ownerGid;
700
778
  let caddyStorage;
779
+ let caddyAdmin;
701
780
  for (let index = 0; index < argv.length; index++) {
702
781
  const current = argv[index];
703
782
  if (current === "--socket")
@@ -716,6 +795,8 @@ function parseArgs(argv) {
716
795
  ownerGid = Number(argv[++index]);
717
796
  else if (current === "--caddy-storage")
718
797
  caddyStorage = argv[++index] ?? void 0;
798
+ else if (current === "--caddy-admin")
799
+ caddyAdmin = argv[++index] ?? void 0;
719
800
  }
720
801
  if (!socket || !token)
721
802
  throw new Error("usage: privileged-helper --socket <path> --token <token> --caddy <bin> --caddy-config <path>");
@@ -729,11 +810,12 @@ function parseArgs(argv) {
729
810
  caddyConfig,
730
811
  ownerUid: Number.isInteger(ownerUid) ? ownerUid : void 0,
731
812
  ownerGid: Number.isInteger(ownerGid) ? ownerGid : void 0,
732
- caddyStorage
813
+ caddyStorage,
814
+ caddyAdmin
733
815
  };
734
816
  }
735
817
  async function main() {
736
- const args = parseArgs(import_node_process3.default.argv.slice(2));
818
+ const args = parseArgs(import_node_process4.default.argv.slice(2));
737
819
  const helper = await startHelper({
738
820
  socketPath: args.socket,
739
821
  token: args.token,
@@ -743,28 +825,44 @@ async function main() {
743
825
  ownerUid: args.ownerUid,
744
826
  ownerGid: args.ownerGid,
745
827
  caddyStoragePath: args.caddyStorage,
828
+ caddyAdminSocket: args.caddyAdmin,
746
829
  caddyEnv: {
747
- HOME: import_node_process3.default.env.HOME ?? "",
830
+ HOME: import_node_process4.default.env.HOME ?? "",
748
831
  // Keep Caddy's storage next to the invoking user's home even though the
749
832
  // process runs as root.
750
- XDG_DATA_HOME: import_node_process3.default.env.XDG_DATA_HOME ?? ""
833
+ XDG_DATA_HOME: import_node_process4.default.env.XDG_DATA_HOME ?? ""
751
834
  }
752
835
  });
753
- import_node_process3.default.on("SIGINT", () => {
836
+ for (const signal of ["SIGINT", "SIGQUIT", "SIGTSTP", "SIGHUP"])
837
+ import_node_process4.default.on(signal, () => {
838
+ });
839
+ import_node_process4.default.on("SIGTERM", () => {
840
+ if (helper.runtime.clientCount() > 0)
841
+ return;
842
+ void helper.runtime.dispose().finally(() => import_node_process4.default.exit(0));
754
843
  });
755
- const shutdown = () => {
756
- void helper.runtime.dispose().finally(() => import_node_process3.default.exit(0));
757
- };
758
- import_node_process3.default.on("SIGTERM", shutdown);
759
- import_node_process3.default.on("SIGHUP", shutdown);
760
- import_node_process3.default.stdout.on("error", () => {
844
+ import_node_process4.default.stdout.on("error", () => {
761
845
  });
762
- import_node_process3.default.stderr.on("error", () => {
846
+ import_node_process4.default.stderr.on("error", () => {
763
847
  });
764
848
  }
765
849
  main().catch((error) => {
766
- import_node_process3.default.stderr.write(`[uhrp-helper] fatal: ${error.message}
850
+ import_node_process4.default.stderr.write(`[uhrp-helper] fatal: ${error.message}
767
851
  `);
768
- 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);
769
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
+ }
770
868
  exports.default = module.exports;