unplugin-https-reverse-proxy 4.0.4 → 4.1.0-beta.3

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.
Files changed (53) hide show
  1. package/README.md +30 -6
  2. package/dist/{chunk-2P7SUCQ3.js → chunk-EY3HXBJ4.js} +0 -26
  3. package/dist/{chunk-5R33PUJP.js → chunk-HBXMM25C.js} +765 -229
  4. package/dist/chunk-RKHJN6KY.js +53 -0
  5. package/dist/chunk-WOMR3ZLM.js +17 -0
  6. package/dist/esbuild.cjs +870 -306
  7. package/dist/esbuild.js +4 -2
  8. package/dist/index.cjs +870 -306
  9. package/dist/index.js +4 -2
  10. package/dist/nuxt.cjs +842 -292
  11. package/dist/nuxt.js +6 -9
  12. package/dist/privilege-state.cjs +44 -0
  13. package/dist/privilege-state.d.cts +7 -0
  14. package/dist/privilege-state.d.ts +7 -0
  15. package/dist/privilege-state.js +10 -0
  16. package/dist/privileged-helper.cjs +668 -0
  17. package/dist/privileged-helper.d.cts +2 -0
  18. package/dist/privileged-helper.d.ts +2 -0
  19. package/dist/privileged-helper.js +641 -0
  20. package/dist/rollup.cjs +870 -306
  21. package/dist/rollup.js +4 -2
  22. package/dist/rspack.cjs +870 -306
  23. package/dist/rspack.js +4 -2
  24. package/dist/utils.cjs +0 -28
  25. package/dist/utils.d.cts +1 -3
  26. package/dist/utils.d.ts +1 -3
  27. package/dist/utils.js +1 -5
  28. package/dist/vite.cjs +870 -306
  29. package/dist/vite.js +4 -2
  30. package/dist/webpack.cjs +870 -306
  31. package/dist/webpack.js +4 -2
  32. package/package.json +1 -4
  33. package/src/caddy/caddyfile.ts +1 -0
  34. package/src/caddy/index.ts +184 -110
  35. package/src/caddy/privileged.ts +121 -0
  36. package/src/caddy/utils.ts +0 -43
  37. package/src/index.ts +49 -22
  38. package/src/nuxt.ts +1 -6
  39. package/src/privilege-state.ts +23 -0
  40. package/src/privileged/bootstrap.ts +174 -0
  41. package/src/privileged/client.ts +287 -0
  42. package/src/privileged/entry.ts +73 -0
  43. package/src/privileged/hosts-file.ts +142 -0
  44. package/src/privileged/launch.ts +235 -0
  45. package/src/privileged/ports.ts +45 -0
  46. package/src/privileged/protocol.ts +111 -0
  47. package/src/privileged/server.ts +465 -0
  48. package/src/privileged/session.ts +117 -0
  49. package/src/privileged/validation.ts +38 -0
  50. package/src/privileged/windows-elevation.ts +80 -0
  51. package/src/privileged-helper.ts +109 -0
  52. package/src/utils.ts +0 -28
  53. package/src/host/index.ts +0 -52
package/dist/nuxt.cjs CHANGED
@@ -33,22 +33,22 @@ __export(nuxt_exports, {
33
33
  default: () => nuxt_default
34
34
  });
35
35
  module.exports = __toCommonJS(nuxt_exports);
36
- var import_node_process6 = __toESM(require("process"), 1);
36
+ var import_node_process9 = __toESM(require("process"), 1);
37
37
  var import_kit = require("@nuxt/kit");
38
38
 
39
39
  // src/index.ts
40
- var import_node_process5 = __toESM(require("process"), 1);
40
+ var import_node_process8 = __toESM(require("process"), 1);
41
41
  var import_console_table_printer = require("console-table-printer");
42
42
  var import_picocolors2 = __toESM(require("picocolors"), 1);
43
43
  var import_unplugin = require("unplugin");
44
44
 
45
45
  // src/caddy/index.ts
46
- var import_node_child_process4 = require("child_process");
47
- var import_node_fs3 = require("fs");
46
+ var import_node_child_process3 = require("child_process");
47
+ var import_node_fs4 = require("fs");
48
48
  var import_promises3 = require("fs/promises");
49
- var import_node_os3 = require("os");
50
- var import_node_path3 = require("path");
51
- var import_node_process4 = __toESM(require("process"), 1);
49
+ var import_node_os5 = require("os");
50
+ var import_node_path5 = require("path");
51
+ var import_node_process7 = __toESM(require("process"), 1);
52
52
 
53
53
  // node_modules/.pnpm/alien-signals@2.0.7/node_modules/alien-signals/esm/system.mjs
54
54
  var ReactiveFlags;
@@ -490,33 +490,14 @@ var import_http_proxy_agent = require("http-proxy-agent");
490
490
  var import_https_proxy_agent = require("https-proxy-agent");
491
491
  var lockfile = __toESM(require("proper-lockfile"), 1);
492
492
 
493
- // src/host/index.ts
494
- var import_node_child_process2 = require("child_process");
495
- var import_node_fs = require("fs");
496
- var import_node_process2 = __toESM(require("process"), 1);
497
- var import_node_util = require("util");
498
- var import_hostile = __toESM(require("hostile"), 1);
499
-
500
493
  // src/utils.ts
501
- var import_node_child_process = require("child_process");
502
- var import_promises = require("fs/promises");
503
494
  var import_node_os = require("os");
504
- var import_node_path = __toESM(require("path"), 1);
505
- var import_node_process = __toESM(require("process"), 1);
506
495
  var import_consola = require("consola");
507
496
  var import_picocolors = __toESM(require("picocolors"), 1);
508
497
  var import_qrcode_terminal = __toESM(require("qrcode-terminal"), 1);
509
498
  var consola = (0, import_consola.createConsola)({
510
499
  level: 3
511
500
  }).withTag("reverse-proxy");
512
- async function chmodRecursive(_path, mode) {
513
- await (0, import_promises.chmod)(_path, mode);
514
- if ((await (0, import_promises.stat)(_path)).isDirectory()) {
515
- const children = await (0, import_promises.readdir)(_path);
516
- for (const child of children)
517
- await chmodRecursive(import_node_path.default.join(_path, child), mode);
518
- }
519
- }
520
501
  function once(fn) {
521
502
  let called = false;
522
503
  return (...args2) => {
@@ -526,18 +507,6 @@ function once(fn) {
526
507
  return fn(...args2);
527
508
  };
528
509
  }
529
- function isAdmin() {
530
- if (import_node_process.default.platform === "win32") {
531
- try {
532
- (0, import_node_child_process.execSync)("net session", { stdio: "ignore" });
533
- return true;
534
- } catch {
535
- return false;
536
- }
537
- } else {
538
- return !!(import_node_process.default.getuid && import_node_process.default.getuid() === 0);
539
- }
540
- }
541
510
  function getIpv4List() {
542
511
  const interfaces = (0, import_node_os.networkInterfaces)();
543
512
  return Object.values(interfaces).flatMap((nInterface) => nInterface ?? []).filter(
@@ -552,44 +521,6 @@ async function generateQrcode(input) {
552
521
  });
553
522
  }
554
523
 
555
- // src/host/index.ts
556
- var _setHost = (0, import_node_util.promisify)(import_hostile.default.set);
557
- var _removeHost = (0, import_node_util.promisify)(import_hostile.default.remove);
558
- function getPathOfSystemHostsPath() {
559
- return import_node_process2.default.platform === "win32" ? `${import_node_process2.default.env.windir || "C:\\WINDOWS"}\\system32\\drivers\\etc\\hosts` : "/etc/hosts";
560
- }
561
- async function syncHost() {
562
- return new Promise((resolve2, _reject) => {
563
- (0, import_node_child_process2.exec)(
564
- import_node_process2.default.platform === "win32" ? "ipconfig /flushdns" : "sudo -E killall -HUP mDNSResponder",
565
- (error, _stdout, _stderr) => {
566
- if (error) {
567
- consola.error(`exec error: ${error}`);
568
- return resolve2(false);
569
- }
570
- return resolve2(true);
571
- }
572
- );
573
- });
574
- }
575
- async function addHost(ip2, host) {
576
- if (import_node_process2.default.platform !== "win32")
577
- (0, import_node_fs.chmodSync)(getPathOfSystemHostsPath(), 511);
578
- await _setHost("127.0.0.1", "localhost");
579
- await _setHost(ip2, host);
580
- if (ip2 === "localhost")
581
- await _setHost("127.0.0.1", host);
582
- return await syncHost();
583
- }
584
- async function removeHost(ip2, host) {
585
- if (import_node_process2.default.platform !== "win32")
586
- (0, import_node_fs.chmodSync)(getPathOfSystemHostsPath(), 511);
587
- await _removeHost(ip2, host);
588
- if (ip2 === "localhost")
589
- await _removeHost("127.0.0.1", host);
590
- return await syncHost();
591
- }
592
-
593
524
  // node_modules/.pnpm/@ark+util@0.46.0/node_modules/@ark/util/out/arrays.js
594
525
  var liftArray = (data) => Array.isArray(data) ? data : [data];
595
526
  var spliterate = (arr, predicate) => {
@@ -1217,29 +1148,29 @@ var timeWithUnnecessarySeconds = /:\d\d:00$/;
1217
1148
  var pad = (value2, length) => String(value2).padStart(length, "0");
1218
1149
 
1219
1150
  // node_modules/.pnpm/@ark+util@0.46.0/node_modules/@ark/util/out/path.js
1220
- var appendStringifiedKey = (path2, prop, ...[opts]) => {
1151
+ var appendStringifiedKey = (path, prop, ...[opts]) => {
1221
1152
  const stringifySymbol = (opts == null ? void 0 : opts.stringifySymbol) ?? printable;
1222
- let propAccessChain = path2;
1153
+ let propAccessChain = path;
1223
1154
  switch (typeof prop) {
1224
1155
  case "string":
1225
- propAccessChain = isDotAccessible(prop) ? path2 === "" ? prop : `${path2}.${prop}` : `${path2}[${JSON.stringify(prop)}]`;
1156
+ propAccessChain = isDotAccessible(prop) ? path === "" ? prop : `${path}.${prop}` : `${path}[${JSON.stringify(prop)}]`;
1226
1157
  break;
1227
1158
  case "number":
1228
- propAccessChain = `${path2}[${prop}]`;
1159
+ propAccessChain = `${path}[${prop}]`;
1229
1160
  break;
1230
1161
  case "symbol":
1231
- propAccessChain = `${path2}[${stringifySymbol(prop)}]`;
1162
+ propAccessChain = `${path}[${stringifySymbol(prop)}]`;
1232
1163
  break;
1233
1164
  default:
1234
1165
  if (opts == null ? void 0 : opts.stringifyNonKey)
1235
- propAccessChain = `${path2}[${opts.stringifyNonKey(prop)}]`;
1166
+ propAccessChain = `${path}[${opts.stringifyNonKey(prop)}]`;
1236
1167
  else {
1237
1168
  throwParseError(`${printable(prop)} must be a PropertyKey or stringifyNonKey must be passed to options`);
1238
1169
  }
1239
1170
  }
1240
1171
  return propAccessChain;
1241
1172
  };
1242
- var stringifyPath = (path2, ...opts) => path2.reduce((s, k) => appendStringifiedKey(s, k, ...opts), "");
1173
+ var stringifyPath = (path, ...opts) => path.reduce((s, k) => appendStringifiedKey(s, k, ...opts), "");
1243
1174
  var ReadonlyPath = class extends ReadonlyArray {
1244
1175
  // alternate strategy for caching since the base object is frozen
1245
1176
  cache = {};
@@ -1266,8 +1197,8 @@ var ReadonlyPath = class extends ReadonlyArray {
1266
1197
  return this.cache.stringifyAncestors;
1267
1198
  let propString = "";
1268
1199
  const result = [propString];
1269
- for (const path2 of this) {
1270
- propString = appendStringifiedKey(propString, path2);
1200
+ for (const path of this) {
1201
+ propString = appendStringifiedKey(propString, path);
1271
1202
  result.push(propString);
1272
1203
  }
1273
1204
  return this.cache.stringifyAncestors = result;
@@ -1860,15 +1791,15 @@ var ArkErrors = class _ArkErrors extends ReadonlyArray {
1860
1791
  /**
1861
1792
  * @internal
1862
1793
  */
1863
- affectsPath(path2) {
1794
+ affectsPath(path) {
1864
1795
  if (this.length === 0)
1865
1796
  return false;
1866
1797
  return (
1867
1798
  // this would occur if there is an existing error at a prefix of path
1868
1799
  // e.g. the path is ["foo", "bar"] and there is an error at ["foo"]
1869
- path2.stringifyAncestors().some((s) => s in this.byPath) || // this would occur if there is an existing error at a suffix of path
1800
+ path.stringifyAncestors().some((s) => s in this.byPath) || // this would occur if there is an existing error at a suffix of path
1870
1801
  // e.g. the path is ["foo"] and there is an error at ["foo", "bar"]
1871
- path2.stringify() in this.byAncestorPath
1802
+ path.stringify() in this.byAncestorPath
1872
1803
  );
1873
1804
  }
1874
1805
  /**
@@ -2075,22 +2006,22 @@ var Traversal = class {
2075
2006
  while (this.queuedMorphs.length) {
2076
2007
  const queuedMorphs = this.queuedMorphs;
2077
2008
  this.queuedMorphs = [];
2078
- for (const { path: path2, morphs } of queuedMorphs) {
2079
- if (this.errors.affectsPath(path2))
2009
+ for (const { path, morphs } of queuedMorphs) {
2010
+ if (this.errors.affectsPath(path))
2080
2011
  continue;
2081
- this.applyMorphsAtPath(path2, morphs);
2012
+ this.applyMorphsAtPath(path, morphs);
2082
2013
  }
2083
2014
  }
2084
2015
  }
2085
- applyMorphsAtPath(path2, morphs) {
2086
- const key = path2.at(-1);
2016
+ applyMorphsAtPath(path, morphs) {
2017
+ const key = path.at(-1);
2087
2018
  let parent;
2088
2019
  if (key !== void 0) {
2089
2020
  parent = this.root;
2090
- for (let pathIndex = 0; pathIndex < path2.length - 1; pathIndex++)
2091
- parent = parent[path2[pathIndex]];
2021
+ for (let pathIndex = 0; pathIndex < path.length - 1; pathIndex++)
2022
+ parent = parent[path[pathIndex]];
2092
2023
  }
2093
- this.path = [...path2];
2024
+ this.path = [...path];
2094
2025
  for (const morph of morphs) {
2095
2026
  const morphIsNode = isNode(morph);
2096
2027
  const result = morph(parent === void 0 ? this.root : parent[key], this);
@@ -2460,15 +2391,15 @@ var NodeSelector = {
2460
2391
  normalize: (selector) => typeof selector === "function" ? { boundary: "references", method: "filter", where: selector } : typeof selector === "string" ? isKeyOf(selector, NodeSelector.applyBoundary) ? { method: "filter", boundary: selector } : { boundary: "references", method: "filter", kind: selector } : { boundary: "references", method: "filter", ...selector }
2461
2392
  };
2462
2393
  var writeSelectAssertionMessage = (from, selector) => `${from} had no references matching ${printable(selector)}.`;
2463
- var typePathToPropString = (path2) => stringifyPath(path2, {
2394
+ var typePathToPropString = (path) => stringifyPath(path, {
2464
2395
  stringifyNonKey: (node2) => node2.expression
2465
2396
  });
2466
2397
  var referenceMatcher = /"(\$ark\.[^"]+)"/g;
2467
2398
  var compileMeta = (metaJson) => JSON.stringify(metaJson).replaceAll(referenceMatcher, "$1");
2468
- var flatRef = (path2, node2) => ({
2469
- path: path2,
2399
+ var flatRef = (path, node2) => ({
2400
+ path,
2470
2401
  node: node2,
2471
- propString: typePathToPropString(path2)
2402
+ propString: typePathToPropString(path)
2472
2403
  });
2473
2404
  var flatRefsAreEqual = (l, r) => l.propString === r.propString && l.node.equals(r.node);
2474
2405
  var appendUniqueFlatRefs = (existing, refs) => appendUnique(existing, refs, {
@@ -2504,12 +2435,12 @@ var Disjoint = class _Disjoint extends Array {
2504
2435
  }
2505
2436
  describeReasons() {
2506
2437
  if (this.length === 1) {
2507
- const { path: path2, l, r } = this[0];
2508
- const pathString = stringifyPath(path2);
2438
+ const { path, l, r } = this[0];
2439
+ const pathString = stringifyPath(path);
2509
2440
  return writeUnsatisfiableExpressionError(`Intersection${pathString && ` at ${pathString}`} of ${describeReasons(l, r)}`);
2510
2441
  }
2511
2442
  return `The following intersections result in unsatisfiable types:
2512
- \u2022 ${this.map(({ path: path2, l, r }) => `${path2}: ${describeReasons(l, r)}`).join("\n\u2022 ")}`;
2443
+ \u2022 ${this.map(({ path, l, r }) => `${path}: ${describeReasons(l, r)}`).join("\n\u2022 ")}`;
2513
2444
  }
2514
2445
  throw() {
2515
2446
  return throwParseError(this.describeReasons());
@@ -3869,10 +3800,10 @@ var BaseRoot = class extends BaseNode {
3869
3800
  });
3870
3801
  });
3871
3802
  }
3872
- get(...path2) {
3873
- if (path2[0] === void 0)
3803
+ get(...path) {
3804
+ if (path[0] === void 0)
3874
3805
  return this;
3875
- return this.$.schema(this.applyStructuralOperation("get", path2));
3806
+ return this.$.schema(this.applyStructuralOperation("get", path));
3876
3807
  }
3877
3808
  extract(r) {
3878
3809
  const rNode = this.$.parseDefinition(r);
@@ -4807,13 +4738,13 @@ var implementation17 = implementNode({
4807
4738
  description: (node2) => node2.distribute((branch) => branch.description, describeBranches),
4808
4739
  expected: (ctx) => {
4809
4740
  const byPath = groupBy(ctx.errors, "propString");
4810
- const pathDescriptions = Object.entries(byPath).map(([path2, errors]) => {
4741
+ const pathDescriptions = Object.entries(byPath).map(([path, errors]) => {
4811
4742
  const branchesAtPath = [];
4812
4743
  for (const errorAtPath of errors)
4813
4744
  appendUnique(branchesAtPath, errorAtPath.expected);
4814
4745
  const expected = describeBranches(branchesAtPath);
4815
4746
  const actual = errors.every((e) => e.actual === errors[0].actual) ? errors[0].actual : printable(errors[0].data);
4816
- return `${path2 && `${path2} `}must be ${expected}${actual && ` (was ${actual})`}`;
4747
+ return `${path && `${path} `}must be ${expected}${actual && ` (was ${actual})`}`;
4817
4748
  });
4818
4749
  return describeBranches(pathDescriptions);
4819
4750
  },
@@ -5177,10 +5108,10 @@ var orderCandidates = (candidates, originalBranches) => {
5177
5108
  });
5178
5109
  return viableCandidates;
5179
5110
  };
5180
- var discriminantCaseToNode = (caseDiscriminant, path2, $) => {
5111
+ var discriminantCaseToNode = (caseDiscriminant, path, $) => {
5181
5112
  let node2 = caseDiscriminant === "undefined" ? $.node("unit", { unit: void 0 }) : caseDiscriminant === "null" ? $.node("unit", { unit: null }) : caseDiscriminant === "boolean" ? $.units([true, false]) : caseDiscriminant;
5182
- for (let i = path2.length - 1; i >= 0; i--) {
5183
- const key = path2[i];
5113
+ for (let i = path.length - 1; i >= 0; i--) {
5114
+ const key = path[i];
5184
5115
  node2 = $.node("intersection", typeof key === "number" ? {
5185
5116
  proto: "Array",
5186
5117
  // create unknown for preceding elements (could be optimized with safe imports)
@@ -5192,7 +5123,7 @@ var discriminantCaseToNode = (caseDiscriminant, path2, $) => {
5192
5123
  }
5193
5124
  return node2;
5194
5125
  };
5195
- var optionallyChainPropString = (path2) => path2.reduce((acc, k) => acc + compileLiteralPropAccess(k, true), "data");
5126
+ var optionallyChainPropString = (path) => path.reduce((acc, k) => acc + compileLiteralPropAccess(k, true), "data");
5196
5127
  var serializedTypeOfDescriptions = registeredReference(jsTypeOfDescriptions);
5197
5128
  var serializedPrintable = registeredReference(printable);
5198
5129
  var Union = {
@@ -6150,7 +6081,7 @@ var StructureNode = class extends BaseConstraint {
6150
6081
  return throwParseError(writeInvalidKeysMessage(this.expression, invalidKeys));
6151
6082
  }
6152
6083
  }
6153
- get(indexer, ...path2) {
6084
+ get(indexer, ...path) {
6154
6085
  var _a4;
6155
6086
  let value2;
6156
6087
  let required = false;
@@ -6187,7 +6118,7 @@ var StructureNode = class extends BaseConstraint {
6187
6118
  }
6188
6119
  return throwParseError(writeInvalidKeysMessage(this.expression, [key]));
6189
6120
  }
6190
- const result = value2.get(...path2);
6121
+ const result = value2.get(...path);
6191
6122
  return required ? result : result.or($ark.intrinsic.undefined);
6192
6123
  }
6193
6124
  pick(...keys) {
@@ -8913,7 +8844,7 @@ function isIterator(val) {
8913
8844
  function escapeRegex(str) {
8914
8845
  return str.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
8915
8846
  }
8916
- function promisify2(fn) {
8847
+ function promisify(fn) {
8917
8848
  return function(...args2) {
8918
8849
  return new Promise((resolve2, reject2) => {
8919
8850
  fn(...args2, (err, result) => {
@@ -10249,8 +10180,8 @@ function requireResolve(file) {
10249
10180
  const require2 = (0, import_module3.createRequire)(process.cwd() + "/");
10250
10181
  return require2.resolve(file);
10251
10182
  }
10252
- var statAsync = promisify2(import_fs.stat);
10253
- var readFileAsync = promisify2(import_fs.readFile);
10183
+ var statAsync = promisify(import_fs.stat);
10184
+ var readFileAsync = promisify(import_fs.readFile);
10254
10185
  function exists(filepath) {
10255
10186
  return __awaiter(this, void 0, void 0, function* () {
10256
10187
  try {
@@ -11492,10 +11423,10 @@ var Loader = class {
11492
11423
  yield filepath;
11493
11424
  }
11494
11425
  }
11495
- dirname(path2) {
11426
+ dirname(path) {
11496
11427
  const fs2 = this.options.fs;
11497
11428
  assert(fs2.dirname, "`fs.dirname` is required for relative reference");
11498
- return fs2.dirname(path2);
11429
+ return fs2.dirname(path);
11499
11430
  }
11500
11431
  lookupError(file, roots) {
11501
11432
  const err = new Error("ENOENT");
@@ -13457,6 +13388,7 @@ function validateTemplateContext(ctx) {
13457
13388
  var caddyTemplate = `{
13458
13389
  debug
13459
13390
  auto_https disable_redirects ignore_loaded_certs
13391
+ skip_install_trust
13460
13392
  }
13461
13393
 
13462
13394
  :7601 {
@@ -13537,27 +13469,27 @@ async function genCaddyfile(ctx) {
13537
13469
  }
13538
13470
 
13539
13471
  // src/caddy/config.ts
13540
- var import_node_fs2 = require("fs");
13541
- var import_promises2 = require("fs/promises");
13472
+ var import_node_fs = require("fs");
13473
+ var import_promises = require("fs/promises");
13542
13474
 
13543
13475
  // src/caddy/constants.ts
13544
13476
  var import_node_os2 = __toESM(require("os"), 1);
13545
- var import_node_path2 = require("path");
13546
- var import_node_process3 = __toESM(require("process"), 1);
13477
+ var import_node_path = require("path");
13478
+ var import_node_process = __toESM(require("process"), 1);
13547
13479
  var import_dotenv_flow = __toESM(require("dotenv-flow"), 1);
13548
13480
  import_dotenv_flow.default.config({
13549
13481
  silent: true
13550
13482
  });
13551
- function resolvePath(path2) {
13552
- if (path2.startsWith("~"))
13553
- return (0, import_node_path2.join)(import_node_os2.default.homedir() || "", path2.slice(1));
13554
- return path2;
13555
- }
13556
- var TEMP_DIR = resolvePath(import_node_process3.default.env.UHRP_CADDY_PATH || import_node_process3.default.env.TEMP || import_node_process3.default.env.TMPDIR || "/tmp");
13557
- var caddyPath = (0, import_node_path2.join)(TEMP_DIR, `caddy${import_node_process3.default.platform === "win32" ? ".exe" : ""}`);
13558
- var caddyFilePath = (0, import_node_path2.join)(TEMP_DIR, "CADDYFILE");
13559
- var caddyConfigPath = (0, import_node_path2.join)(TEMP_DIR, ".CADDYFILE.config.json");
13560
- var caddyLockFilePath = (0, import_node_path2.join)(TEMP_DIR, "caddylock");
13483
+ function resolvePath(path) {
13484
+ if (path.startsWith("~"))
13485
+ return (0, import_node_path.join)(import_node_os2.default.homedir() || "", path.slice(1));
13486
+ return path;
13487
+ }
13488
+ var TEMP_DIR = resolvePath(import_node_process.default.env.UHRP_CADDY_PATH || import_node_process.default.env.TEMP || import_node_process.default.env.TMPDIR || "/tmp");
13489
+ var caddyPath = (0, import_node_path.join)(TEMP_DIR, `caddy${import_node_process.default.platform === "win32" ? ".exe" : ""}`);
13490
+ var caddyFilePath = (0, import_node_path.join)(TEMP_DIR, "CADDYFILE");
13491
+ var caddyConfigPath = (0, import_node_path.join)(TEMP_DIR, ".CADDYFILE.config.json");
13492
+ var caddyLockFilePath = (0, import_node_path.join)(TEMP_DIR, "caddylock");
13561
13493
  var supportList = [
13562
13494
  {
13563
13495
  platform: "dragonfly",
@@ -13680,19 +13612,19 @@ function useCaddyConfig() {
13680
13612
  }
13681
13613
  });
13682
13614
  function setConfigContent() {
13683
- if (!(0, import_node_fs2.existsSync)(caddyConfigPath)) {
13684
- (0, import_node_fs2.writeFileSync)(caddyConfigPath, "{}");
13615
+ if (!(0, import_node_fs.existsSync)(caddyConfigPath)) {
13616
+ (0, import_node_fs.writeFileSync)(caddyConfigPath, "{}");
13685
13617
  }
13686
13618
  try {
13687
- configContentRef((0, import_node_fs2.readFileSync)(caddyConfigPath, "utf-8"));
13619
+ configContentRef((0, import_node_fs.readFileSync)(caddyConfigPath, "utf-8"));
13688
13620
  } catch {
13689
13621
  configContentRef("");
13690
13622
  }
13691
13623
  }
13692
- if (!(0, import_node_fs2.existsSync)(caddyConfigPath)) {
13693
- (0, import_node_fs2.writeFileSync)(caddyConfigPath, "{}");
13624
+ if (!(0, import_node_fs.existsSync)(caddyConfigPath)) {
13625
+ (0, import_node_fs.writeFileSync)(caddyConfigPath, "{}");
13694
13626
  }
13695
- const watchCaddyConfig = (0, import_node_fs2.watch)(caddyConfigPath, () => {
13627
+ const watchCaddyConfig = (0, import_node_fs.watch)(caddyConfigPath, () => {
13696
13628
  setConfigContent();
13697
13629
  });
13698
13630
  function writeCaddyConfig(_proxies) {
@@ -13708,10 +13640,10 @@ function useCaddyConfig() {
13708
13640
  });
13709
13641
  const content = JSON.stringify(proxies, null, 2);
13710
13642
  configContentRef(content);
13711
- return (0, import_node_fs2.writeFileSync)(caddyConfigPath, content);
13643
+ return (0, import_node_fs.writeFileSync)(caddyConfigPath, content);
13712
13644
  }
13713
13645
  async function cleanUp() {
13714
- await (0, import_promises2.unlink)(caddyConfigPath).catch(() => {
13646
+ await (0, import_promises.unlink)(caddyConfigPath).catch(() => {
13715
13647
  });
13716
13648
  configContentRef("{}");
13717
13649
  watchCaddyConfig.close();
@@ -13733,6 +13665,592 @@ function isCaddyReloadCancellation(line) {
13733
13665
  }
13734
13666
  }
13735
13667
 
13668
+ // src/caddy/privileged.ts
13669
+ var import_node_buffer2 = require("buffer");
13670
+ var import_node_events = require("events");
13671
+ var import_node_path4 = require("path");
13672
+ var import_node_process6 = __toESM(require("process"), 1);
13673
+ var import_node_url = require("url");
13674
+
13675
+ // src/privileged/entry.ts
13676
+ var import_node_fs2 = require("fs");
13677
+ var import_node_path2 = require("path");
13678
+ var import_node_process2 = __toESM(require("process"), 1);
13679
+ function resolveHelperEntry(options) {
13680
+ const { moduleDir, nodeBin = import_node_process2.default.execPath, exists: exists2 = import_node_fs2.existsSync } = options;
13681
+ for (const name of ["privileged-helper.js", "privileged-helper.cjs", "privileged-helper.mjs"]) {
13682
+ const candidate = findUp(moduleDir, name, exists2);
13683
+ if (candidate)
13684
+ return { entry: nodeBin, args: [candidate] };
13685
+ }
13686
+ const source = findUp(moduleDir, "privileged-helper.ts", exists2);
13687
+ const tsxCli = findUp(moduleDir, "node_modules/tsx/dist/cli.mjs", exists2);
13688
+ if (source && tsxCli)
13689
+ return { entry: nodeBin, args: [tsxCli, source] };
13690
+ throw new Error(`privileged helper entry not found in ${moduleDir}. Build the package first.`);
13691
+ }
13692
+ function findUp(from, relative, exists2) {
13693
+ let current = from;
13694
+ while (true) {
13695
+ const candidate = (0, import_node_path2.join)(current, relative);
13696
+ if (exists2(candidate))
13697
+ return candidate;
13698
+ const parent = (0, import_node_path2.dirname)(current);
13699
+ if (parent === current)
13700
+ return void 0;
13701
+ current = parent;
13702
+ }
13703
+ }
13704
+
13705
+ // src/privileged/session.ts
13706
+ var import_node_buffer = require("buffer");
13707
+ var import_node_fs3 = require("fs");
13708
+ var import_promises2 = require("fs/promises");
13709
+ var import_node_os4 = require("os");
13710
+ var import_node_path3 = require("path");
13711
+
13712
+ // src/privileged/launch.ts
13713
+ var import_node_child_process2 = require("child_process");
13714
+ var import_node_crypto = require("crypto");
13715
+ var import_node_os3 = require("os");
13716
+ var import_node_process5 = __toESM(require("process"), 1);
13717
+
13718
+ // src/privileged/client.ts
13719
+ var import_node_net = require("net");
13720
+ var import_node_process3 = __toESM(require("process"), 1);
13721
+
13722
+ // src/privileged/protocol.ts
13723
+ function serializeMessage(message) {
13724
+ return `${JSON.stringify(message)}
13725
+ `;
13726
+ }
13727
+ function splitLines(buffer, chunk) {
13728
+ const parts = (buffer + chunk).split("\n");
13729
+ const rest = parts.pop() ?? "";
13730
+ return { lines: parts.filter((line) => line.trim() !== ""), rest };
13731
+ }
13732
+ function isRecord(value2) {
13733
+ return typeof value2 === "object" && value2 !== null;
13734
+ }
13735
+ function decodeMessage(line) {
13736
+ let parsed2;
13737
+ try {
13738
+ parsed2 = JSON.parse(line);
13739
+ } catch (error) {
13740
+ return { ok: false, error: `invalid JSON: ${error.message}` };
13741
+ }
13742
+ if (!isRecord(parsed2))
13743
+ return { ok: false, error: "message must be an object" };
13744
+ if (parsed2.type === "event") {
13745
+ if (typeof parsed2.kind !== "string")
13746
+ return { ok: false, error: "event.kind must be a string" };
13747
+ return { ok: true, message: parsed2 };
13748
+ }
13749
+ if (typeof parsed2.id !== "number")
13750
+ return { ok: false, error: "response.id must be a number" };
13751
+ if (parsed2.ok === true)
13752
+ return { ok: true, message: { id: parsed2.id, ok: true, result: parsed2.result } };
13753
+ if (parsed2.ok === false) {
13754
+ const error = isRecord(parsed2.error) ? parsed2.error : {};
13755
+ return {
13756
+ ok: true,
13757
+ message: {
13758
+ id: parsed2.id,
13759
+ ok: false,
13760
+ error: {
13761
+ message: typeof error.message === "string" ? error.message : "helper request failed",
13762
+ code: typeof error.code === "string" ? error.code : void 0
13763
+ }
13764
+ }
13765
+ };
13766
+ }
13767
+ return { ok: false, error: "response.ok must be a boolean" };
13768
+ }
13769
+
13770
+ // src/privileged/client.ts
13771
+ var FORWARDED_ENV_KEYS = [
13772
+ "HOME",
13773
+ "USER",
13774
+ "LOGNAME",
13775
+ "TMPDIR",
13776
+ "HTTP_PROXY",
13777
+ "HTTPS_PROXY",
13778
+ "http_proxy",
13779
+ "https_proxy",
13780
+ "NO_PROXY",
13781
+ "no_proxy"
13782
+ ];
13783
+ function collectForwardedEnv(source = import_node_process3.default.env) {
13784
+ const result = {};
13785
+ for (const key of FORWARDED_ENV_KEYS) {
13786
+ const value2 = source[key];
13787
+ if (typeof value2 === "string" && value2 !== "")
13788
+ result[key] = value2;
13789
+ }
13790
+ return result;
13791
+ }
13792
+ var HelperConnectionError = class extends Error {
13793
+ constructor(message) {
13794
+ super(message);
13795
+ this.name = "HelperConnectionError";
13796
+ }
13797
+ };
13798
+ function openSocket(socketPath) {
13799
+ return new Promise((resolve2, reject2) => {
13800
+ const socket = (0, import_node_net.connect)(socketPath);
13801
+ function onConnect() {
13802
+ socket.removeListener("error", onError);
13803
+ resolve2(socket);
13804
+ }
13805
+ function onError(error) {
13806
+ socket.removeListener("connect", onConnect);
13807
+ reject2(error);
13808
+ }
13809
+ socket.once("error", onError);
13810
+ socket.once("connect", onConnect);
13811
+ });
13812
+ }
13813
+ async function connectClient(options) {
13814
+ const {
13815
+ socketPath,
13816
+ token,
13817
+ timeoutMs = 12e4,
13818
+ retryIntervalMs = 100,
13819
+ callTimeoutMs = 3e4
13820
+ } = options;
13821
+ const deadline = Date.now() + timeoutMs;
13822
+ let lastError;
13823
+ while (Date.now() < deadline) {
13824
+ try {
13825
+ return await handshake(socketPath, token, callTimeoutMs);
13826
+ } catch (error) {
13827
+ lastError = error;
13828
+ const code = lastError.code;
13829
+ if (code === "EACCES" || lastError instanceof HelperConnectionError)
13830
+ throw lastError;
13831
+ await new Promise((resolve2) => setTimeout(resolve2, retryIntervalMs));
13832
+ }
13833
+ }
13834
+ throw new HelperConnectionError(
13835
+ `privileged helper is not reachable at ${socketPath}: ${(lastError == null ? void 0 : lastError.message) ?? "timed out"}`
13836
+ );
13837
+ }
13838
+ function handshake(socketPath, token, callTimeoutMs) {
13839
+ return new Promise((resolve2, reject2) => {
13840
+ void openSocket(socketPath).then((socket) => {
13841
+ let buffer = "";
13842
+ let settled = false;
13843
+ const fail = (error) => {
13844
+ if (settled)
13845
+ return;
13846
+ settled = true;
13847
+ socket.destroy();
13848
+ reject2(error);
13849
+ };
13850
+ const onData = (chunk) => {
13851
+ if (settled)
13852
+ return;
13853
+ const split2 = splitLines(buffer, chunk.toString("utf8"));
13854
+ buffer = split2.rest;
13855
+ const line = split2.lines[0];
13856
+ if (line === void 0)
13857
+ return;
13858
+ let hello;
13859
+ try {
13860
+ hello = JSON.parse(line);
13861
+ } catch (error) {
13862
+ return fail(new HelperConnectionError(`invalid handshake reply: ${error.message}`));
13863
+ }
13864
+ if (hello.type !== "handshake")
13865
+ return fail(new HelperConnectionError("helper did not answer the handshake"));
13866
+ if (!hello.ok)
13867
+ return fail(new HelperConnectionError(hello.reason ?? "helper rejected the handshake"));
13868
+ settled = true;
13869
+ socket.removeListener("data", onData);
13870
+ socket.removeListener("error", onError);
13871
+ const remaining = split2.lines.slice(1);
13872
+ resolve2(createClient(socket, [split2.rest, ...remaining].filter(Boolean).join("\n"), callTimeoutMs));
13873
+ };
13874
+ function onError(error) {
13875
+ fail(error);
13876
+ }
13877
+ socket.on("data", onData);
13878
+ socket.on("error", onError);
13879
+ const greeting = { type: "handshake", token };
13880
+ socket.write(serializeMessage(greeting));
13881
+ }, reject2);
13882
+ });
13883
+ }
13884
+ function createClient(socket, initialBuffer, callTimeoutMs) {
13885
+ let buffer = initialBuffer;
13886
+ let connected = true;
13887
+ let nextId = 1;
13888
+ const pending = /* @__PURE__ */ new Map();
13889
+ const listeners = /* @__PURE__ */ new Set();
13890
+ socket.on("data", (chunk) => {
13891
+ const split2 = splitLines(buffer, chunk.toString("utf8"));
13892
+ buffer = split2.rest;
13893
+ for (const line of split2.lines) {
13894
+ const decoded = decodeMessage(line);
13895
+ if (!decoded.ok)
13896
+ continue;
13897
+ const message = decoded.message;
13898
+ if (!("id" in message)) {
13899
+ for (const listener of listeners)
13900
+ listener(message);
13901
+ continue;
13902
+ }
13903
+ const entry = pending.get(message.id);
13904
+ if (!entry)
13905
+ continue;
13906
+ pending.delete(message.id);
13907
+ clearTimeout(entry.timer);
13908
+ if (message.ok)
13909
+ entry.resolve(message.result);
13910
+ else
13911
+ entry.reject(new Error(message.error.message));
13912
+ }
13913
+ });
13914
+ const disconnect = () => {
13915
+ if (!connected)
13916
+ return;
13917
+ connected = false;
13918
+ for (const [id, entry] of pending) {
13919
+ clearTimeout(entry.timer);
13920
+ pending.delete(id);
13921
+ entry.reject(new HelperConnectionError("privileged helper connection closed"));
13922
+ }
13923
+ };
13924
+ socket.on("close", disconnect);
13925
+ socket.on("error", disconnect);
13926
+ function call(method, params) {
13927
+ if (!connected)
13928
+ return Promise.reject(new HelperConnectionError("privileged helper is not connected"));
13929
+ const id = nextId++;
13930
+ const request = { id, method, params };
13931
+ return new Promise((resolve2, reject2) => {
13932
+ const timer = setTimeout(() => {
13933
+ pending.delete(id);
13934
+ reject2(new HelperConnectionError(`privileged helper did not answer "${method}" in time`));
13935
+ }, callTimeoutMs);
13936
+ pending.set(id, { resolve: resolve2, reject: reject2, timer });
13937
+ socket.write(serializeMessage(request));
13938
+ });
13939
+ }
13940
+ return {
13941
+ get connected() {
13942
+ return connected;
13943
+ },
13944
+ call,
13945
+ onEvent(listener) {
13946
+ listeners.add(listener);
13947
+ return () => {
13948
+ listeners.delete(listener);
13949
+ };
13950
+ },
13951
+ async close() {
13952
+ disconnect();
13953
+ socket.destroy();
13954
+ }
13955
+ };
13956
+ }
13957
+
13958
+ // src/privileged/windows-elevation.ts
13959
+ var import_node_child_process = require("child_process");
13960
+ var import_node_process4 = __toESM(require("process"), 1);
13961
+ function quotePowerShell(value2) {
13962
+ return `'${value2.replace(/'/g, "''")}'`;
13963
+ }
13964
+ function buildElevationCommand(options) {
13965
+ const argumentList = options.args.map(quotePowerShell).join(",");
13966
+ const parts = [
13967
+ "Start-Process",
13968
+ "-FilePath",
13969
+ quotePowerShell(options.file)
13970
+ ];
13971
+ if (argumentList)
13972
+ parts.push("-ArgumentList", argumentList);
13973
+ if (options.cwd)
13974
+ parts.push("-WorkingDirectory", quotePowerShell(options.cwd));
13975
+ parts.push("-Verb", "RunAs");
13976
+ parts.push("-WindowStyle", "Hidden");
13977
+ return parts.join(" ");
13978
+ }
13979
+ function spawnElevatedOnWindows(options) {
13980
+ return new Promise((resolve2, reject2) => {
13981
+ const script = buildElevationCommand(options);
13982
+ const child = (0, import_node_child_process.spawn)(
13983
+ "powershell.exe",
13984
+ ["-NoProfile", "-NonInteractive", "-Command", script],
13985
+ { stdio: "ignore", windowsHide: true }
13986
+ );
13987
+ child.once("error", reject2);
13988
+ child.once("exit", (code) => {
13989
+ if (code === 0)
13990
+ return resolve2(child);
13991
+ reject2(new Error(
13992
+ `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.`
13993
+ ));
13994
+ });
13995
+ });
13996
+ }
13997
+
13998
+ // src/privileged/launch.ts
13999
+ function createHelperToken() {
14000
+ return (0, import_node_crypto.randomBytes)(24).toString("hex");
14001
+ }
14002
+ function describePasswordReason(target, https) {
14003
+ const port = https ? "443" : "80";
14004
+ return [
14005
+ `reverse proxy needs administrator permission for ${target}`,
14006
+ ` \xB7 bind port ${port}${https ? ` for https://${target}` : ""}`,
14007
+ ` \xB7 add ${target} to the hosts file`,
14008
+ "",
14009
+ "This is the only prompt; the rest of the dev server keeps running as you.",
14010
+ "Press Ctrl+C at the prompt to skip the proxy and keep the dev server."
14011
+ ];
14012
+ }
14013
+ function authenticateSudo(sudoCommand = "sudo", options = {}) {
14014
+ if ((0, import_node_os3.platform)() === "win32")
14015
+ return { ok: true };
14016
+ if ((0, import_node_child_process2.spawnSync)(sudoCommand, ["-n", "true"], { stdio: "ignore" }).status === 0)
14017
+ return { ok: true };
14018
+ if (options.target) {
14019
+ for (const line of describePasswordReason(options.target, options.https ?? false))
14020
+ import_node_process5.default.stderr.write(`${line}
14021
+ `);
14022
+ import_node_process5.default.stderr.write("\n");
14023
+ }
14024
+ if ((0, import_node_child_process2.spawnSync)(sudoCommand, ["-v"], { stdio: "inherit" }).status === 0)
14025
+ return { ok: true };
14026
+ return {
14027
+ ok: false,
14028
+ denied: true,
14029
+ message: "administrator permission is required to edit the hosts file and bind ports 80/443"
14030
+ };
14031
+ }
14032
+ var PrivilegeDeniedError = class extends Error {
14033
+ constructor(message) {
14034
+ super(message);
14035
+ this.name = "PrivilegeDeniedError";
14036
+ }
14037
+ };
14038
+ async function startPrivilegedHelper(options) {
14039
+ var _a4, _b3;
14040
+ const {
14041
+ socketPath,
14042
+ token,
14043
+ helperEntry,
14044
+ helperArgs = [],
14045
+ sudoCommand = "sudo",
14046
+ skipAuth = false,
14047
+ direct = false,
14048
+ env: env2 = import_node_process5.default.env,
14049
+ log,
14050
+ connectTimeoutMs = 12e4
14051
+ } = options;
14052
+ if (!skipAuth && !direct) {
14053
+ const auth = authenticateSudo(sudoCommand, options.reason);
14054
+ if (!auth.ok) {
14055
+ const message = auth.message ?? "administrator permission is required";
14056
+ throw auth.denied ? new PrivilegeDeniedError(message) : new Error(message);
14057
+ }
14058
+ }
14059
+ const forwarded = collectForwardedEnv(env2);
14060
+ const forwardedArgs = Object.entries(forwarded).map(([key, value2]) => `${key}=${value2}`);
14061
+ const childArgv = [
14062
+ ...helperArgs,
14063
+ "--socket",
14064
+ socketPath,
14065
+ "--token",
14066
+ token,
14067
+ ...typeof import_node_process5.default.getuid === "function" ? ["--owner-uid", String(import_node_process5.default.getuid())] : [],
14068
+ ...typeof import_node_process5.default.getgid === "function" ? ["--owner-gid", String(import_node_process5.default.getgid())] : [],
14069
+ ...options.caddyStoragePath ? ["--caddy-storage", options.caddyStoragePath] : [],
14070
+ "--caddy",
14071
+ options.caddyBin,
14072
+ "--caddy-config",
14073
+ options.caddyConfigPath
14074
+ ];
14075
+ let child;
14076
+ if (!direct && (0, import_node_os3.platform)() === "win32") {
14077
+ await spawnElevatedOnWindows({ file: helperEntry, args: childArgv, cwd: import_node_process5.default.cwd() });
14078
+ } else {
14079
+ const command = direct ? helperEntry : sudoCommand;
14080
+ const spawnArgs = direct ? childArgv : ["-n", "env", ...forwardedArgs, helperEntry, ...childArgv];
14081
+ child = (0, import_node_child_process2.spawn)(command, spawnArgs, {
14082
+ stdio: ["ignore", "pipe", "pipe"]
14083
+ });
14084
+ (_a4 = child.stdout) == null ? void 0 : _a4.on("data", (data) => log == null ? void 0 : log(data.toString().trimEnd()));
14085
+ (_b3 = child.stderr) == null ? void 0 : _b3.on("data", (data) => log == null ? void 0 : log(data.toString().trimEnd()));
14086
+ const exited = new Promise((resolve2) => child.once("exit", (code) => resolve2(code)));
14087
+ const earlyExit = await Promise.race([
14088
+ exited,
14089
+ new Promise((resolve2) => setTimeout(() => resolve2(void 0), 500))
14090
+ ]);
14091
+ if (earlyExit !== void 0 && earlyExit !== 0) {
14092
+ throw new Error(
14093
+ `privileged helper exited with code ${earlyExit}. Administrator permission was refused, or sudo is not available.`
14094
+ );
14095
+ }
14096
+ }
14097
+ try {
14098
+ const client = await connectClient({ socketPath, token, timeoutMs: connectTimeoutMs });
14099
+ return {
14100
+ client,
14101
+ async close() {
14102
+ await client.close().catch(() => {
14103
+ });
14104
+ child == null ? void 0 : child.unref();
14105
+ }
14106
+ };
14107
+ } catch (error) {
14108
+ try {
14109
+ child == null ? void 0 : child.kill();
14110
+ } catch {
14111
+ }
14112
+ throw error;
14113
+ }
14114
+ }
14115
+ async function connectExistingHelper(socketPath, token, timeoutMs = 1500) {
14116
+ try {
14117
+ return await connectClient({ socketPath, token, timeoutMs });
14118
+ } catch {
14119
+ return void 0;
14120
+ }
14121
+ }
14122
+
14123
+ // src/privileged/session.ts
14124
+ function tokenPath(runtimeDir) {
14125
+ return (0, import_node_path3.join)(runtimeDir, "helper.token");
14126
+ }
14127
+ function sessionSocketPath(runtimeDir) {
14128
+ if ((0, import_node_os4.platform)() === "win32")
14129
+ return `\\\\.\\pipe\\uhrp-${import_node_buffer.Buffer.from(runtimeDir).toString("hex").slice(0, 40)}`;
14130
+ return (0, import_node_path3.join)(runtimeDir, "helper.sock");
14131
+ }
14132
+ async function openHelperSession(scope2) {
14133
+ const socketPath = sessionSocketPath(scope2.runtimeDir);
14134
+ if ((0, import_node_fs3.existsSync)(socketPath) || (0, import_node_os4.platform)() === "win32") {
14135
+ const token2 = await readToken(scope2.runtimeDir);
14136
+ if (token2) {
14137
+ const reused = await connectExistingHelper(socketPath, token2);
14138
+ if (reused) {
14139
+ return {
14140
+ client: reused,
14141
+ reused: true,
14142
+ close: async () => {
14143
+ await reused.close();
14144
+ }
14145
+ };
14146
+ }
14147
+ }
14148
+ }
14149
+ const token = createHelperToken();
14150
+ const started = await startPrivilegedHelper({
14151
+ socketPath,
14152
+ token,
14153
+ helperEntry: scope2.helperEntry,
14154
+ helperArgs: scope2.helperArgs,
14155
+ sudoCommand: scope2.sudoCommand,
14156
+ skipAuth: scope2.skipAuth,
14157
+ direct: scope2.direct,
14158
+ env: scope2.env,
14159
+ caddyStoragePath: scope2.caddyStoragePath,
14160
+ caddyBin: scope2.caddyBin,
14161
+ caddyConfigPath: scope2.caddyConfigPath,
14162
+ reason: scope2.reason,
14163
+ log: scope2.log
14164
+ });
14165
+ await writeToken(scope2.runtimeDir, token);
14166
+ return {
14167
+ client: started.client,
14168
+ reused: false,
14169
+ close: async () => {
14170
+ await started.close();
14171
+ }
14172
+ };
14173
+ }
14174
+ async function readToken(runtimeDir) {
14175
+ try {
14176
+ const content = await (0, import_promises2.readFile)(tokenPath(runtimeDir), "utf8");
14177
+ const token = content.trim();
14178
+ return token === "" ? void 0 : token;
14179
+ } catch {
14180
+ return void 0;
14181
+ }
14182
+ }
14183
+ async function writeToken(runtimeDir, token) {
14184
+ try {
14185
+ await (0, import_promises2.writeFile)(tokenPath(runtimeDir), token, { mode: 384 });
14186
+ } catch {
14187
+ }
14188
+ }
14189
+
14190
+ // src/caddy/privileged.ts
14191
+ var import_meta = {};
14192
+ function resolvePrivilegedEnv() {
14193
+ const moduleDir = typeof __dirname === "string" ? __dirname : (0, import_node_path4.dirname)((0, import_node_url.fileURLToPath)(import_meta.url));
14194
+ const resolved = resolveHelperEntry({ moduleDir });
14195
+ return { helperEntry: resolved.entry, helperArgs: resolved.args };
14196
+ }
14197
+ var HelperCaddyProcess = class extends import_node_events.EventEmitter {
14198
+ constructor(client) {
14199
+ super();
14200
+ this.client = client;
14201
+ this.stdout = new import_node_events.EventEmitter();
14202
+ this.stderr = new import_node_events.EventEmitter();
14203
+ this.finished = false;
14204
+ this.unsubscribe = client.onEvent((event) => this.handleEvent(event));
14205
+ }
14206
+ handleEvent(event) {
14207
+ if (event.type !== "event")
14208
+ return;
14209
+ if (event.kind === "caddy.stdout") {
14210
+ this.stdout.emit("data", import_node_buffer2.Buffer.from(event.data));
14211
+ return;
14212
+ }
14213
+ if (event.kind === "caddy.stderr") {
14214
+ this.stderr.emit("data", import_node_buffer2.Buffer.from(event.data));
14215
+ return;
14216
+ }
14217
+ if (event.kind === "caddy.exit") {
14218
+ this.finished = true;
14219
+ this.emit("exit", event.code, event.signal);
14220
+ }
14221
+ }
14222
+ /** Asks the helper to stop Caddy; the helper also stops it on disconnect. */
14223
+ kill() {
14224
+ this.unsubscribe();
14225
+ if (this.finished)
14226
+ return;
14227
+ this.finished = true;
14228
+ void this.client.call("caddy.stop").catch(() => {
14229
+ });
14230
+ }
14231
+ };
14232
+ function caddyStoragePath() {
14233
+ return import_node_process6.default.platform === "win32" ? (0, import_node_path4.join)(import_node_process6.default.env.AppData ?? "", "Caddy") : (0, import_node_path4.join)(import_node_process6.default.env.HOME ?? "", "Library/Application Support/Caddy");
14234
+ }
14235
+ function openPrivilegedSession(runtimeDir, options) {
14236
+ const env2 = resolvePrivilegedEnv();
14237
+ return openHelperSession({
14238
+ runtimeDir,
14239
+ helperEntry: env2.helperEntry,
14240
+ helperArgs: env2.helperArgs,
14241
+ direct: options.direct,
14242
+ // Caddy keeps its PKI under the user's home; the helper runs it as root, so
14243
+ // it must know which tree to hand back afterwards.
14244
+ caddyStoragePath: caddyStoragePath(),
14245
+ // The binary and Caddyfile are fixed here: the privileged helper must never
14246
+ // execute a path supplied over the socket.
14247
+ caddyBin: options.caddyBin,
14248
+ caddyConfigPath: options.caddyConfigPath,
14249
+ reason: options.reason,
14250
+ log: options.log
14251
+ });
14252
+ }
14253
+
13736
14254
  // src/caddy/tls-health.ts
13737
14255
  var import_node_tls = require("tls");
13738
14256
  function assessTlsCertificate(certificate, hostname, now = Date.now(), verifyHostname = import_node_tls.checkServerIdentity) {
@@ -13815,40 +14333,8 @@ function formatTlsHealthFailure(hostname, result) {
13815
14333
  }
13816
14334
 
13817
14335
  // src/caddy/utils.ts
13818
- var import_node_child_process3 = require("child_process");
13819
- var import_node_net = require("net");
13820
14336
  var import_ora = __toESM(require("ora"), 1);
13821
14337
  var spinner;
13822
- function tryPort(port) {
13823
- return new Promise((resolve2, _reject) => {
13824
- try {
13825
- const server = (0, import_node_net.createServer)().listen(port);
13826
- server.on("listening", () => {
13827
- server.close();
13828
- resolve2(false);
13829
- });
13830
- server.on("error", (err) => {
13831
- if (err.code === "EADDRINUSE")
13832
- resolve2(true);
13833
- server.close();
13834
- });
13835
- } catch {
13836
- resolve2(true);
13837
- }
13838
- });
13839
- }
13840
- async function kill(port) {
13841
- return new Promise((resolve2, reject2) => {
13842
- (0, import_node_child_process3.exec)(`npx @maxbo/free-port ${port} -s`, (err, stdout, _stderr) => {
13843
- if (err) {
13844
- reject2(err);
13845
- } else {
13846
- consola.log(stdout);
13847
- resolve2();
13848
- }
13849
- });
13850
- });
13851
- }
13852
14338
  function getNumber(number2) {
13853
14339
  if (number2 <= 0)
13854
14340
  return "0%";
@@ -13887,26 +14373,26 @@ async function download() {
13887
14373
  if (await testCaddy())
13888
14374
  return caddyPath;
13889
14375
  return new Promise((resolve2, reject2) => {
13890
- if (!(0, import_node_fs3.existsSync)(TEMP_DIR)) {
13891
- (0, import_node_fs3.mkdirSync)(TEMP_DIR, { recursive: true });
13892
- (0, import_node_fs3.chmodSync)(TEMP_DIR, 511);
14376
+ if (!(0, import_node_fs4.existsSync)(TEMP_DIR)) {
14377
+ (0, import_node_fs4.mkdirSync)(TEMP_DIR, { recursive: true });
14378
+ (0, import_node_fs4.chmodSync)(TEMP_DIR, 448);
13893
14379
  }
13894
- const file = (0, import_node_fs3.createWriteStream)(caddyPath);
13895
- let _platform = (0, import_node_os3.platform)().toString();
14380
+ const file = (0, import_node_fs4.createWriteStream)(caddyPath);
14381
+ let _platform = (0, import_node_os5.platform)().toString();
13896
14382
  _platform === "win32" && (_platform = "windows");
13897
- let _arch = import_node_process4.default.arch.toString();
14383
+ let _arch = import_node_process7.default.arch.toString();
13898
14384
  _arch === "x64" && (_arch = "amd64");
13899
14385
  const support = supportList.find((item) => item.platform === _platform && item.arch === _arch);
13900
14386
  if (!support)
13901
14387
  return reject2(new Error("not support"));
13902
14388
  const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}&p=github.com%2Fcaddyserver%2Fforwardproxy`;
13903
- (0, import_node_fs3.existsSync)(caddyPath) && (0, import_node_fs3.unlinkSync)(caddyPath);
13904
- const httpProxy = import_node_process4.default.env.HTTP_PROXY || import_node_process4.default.env.http_proxy;
13905
- const httpsProxy = import_node_process4.default.env.HTTPS_PROXY || import_node_process4.default.env.https_proxy;
14389
+ (0, import_node_fs4.existsSync)(caddyPath) && (0, import_node_fs4.unlinkSync)(caddyPath);
14390
+ const httpProxy = import_node_process7.default.env.HTTP_PROXY || import_node_process7.default.env.http_proxy;
14391
+ const httpsProxy = import_node_process7.default.env.HTTPS_PROXY || import_node_process7.default.env.https_proxy;
13906
14392
  const httpAgent = httpProxy ? new import_http_proxy_agent.HttpProxyAgent(httpProxy) : void 0;
13907
14393
  const httpsAgent = httpsProxy ? new import_https_proxy_agent.HttpsProxyAgent(httpsProxy) : void 0;
13908
14394
  const chmodCaddyOnce = once(() => {
13909
- (0, import_node_fs3.chmodSync)(caddyPath, 511);
14395
+ (0, import_node_fs4.chmodSync)(caddyPath, 493);
13910
14396
  });
13911
14397
  import_got_cjs.got.stream(dowmloadLink, {
13912
14398
  agent: {
@@ -13918,9 +14404,9 @@ async function download() {
13918
14404
  chmodCaddyOnce();
13919
14405
  }).pipe(file).on("finish", () => {
13920
14406
  logProgressOver();
13921
- if (import_node_process4.default.platform === "win32")
14407
+ if (import_node_process7.default.platform === "win32")
13922
14408
  return resolve2(caddyPath);
13923
- (0, import_node_fs3.chmodSync)(caddyPath, 511);
14409
+ (0, import_node_fs4.chmodSync)(caddyPath, 493);
13924
14410
  resolve2(caddyPath);
13925
14411
  }).on("error", (err) => {
13926
14412
  reject2(err);
@@ -13928,19 +14414,17 @@ async function download() {
13928
14414
  });
13929
14415
  }
13930
14416
  function testCaddy() {
13931
- return new Promise((resolve2, reject2) => {
13932
- if (!(0, import_node_fs3.existsSync)(caddyPath))
13933
- return resolve2(false);
13934
- (0, import_node_fs3.chmodSync)(caddyPath, 511);
13935
- const child = import_node_process4.default.platform === "win32" ? (0, import_node_child_process4.spawn)(caddyPath, []) : (0, import_node_child_process4.spawn)("sudo", ["-E", caddyPath]);
13936
- child.on("close", () => {
14417
+ return new Promise((resolve2) => {
14418
+ if (!(0, import_node_fs4.existsSync)(caddyPath))
13937
14419
  return resolve2(false);
13938
- });
13939
- child.on("error", (err) => {
13940
- return reject2(err);
13941
- });
13942
- child.stdout.on("data", (_data) => {
13943
- return resolve2(true);
14420
+ try {
14421
+ (0, import_node_fs4.chmodSync)(caddyPath, 493);
14422
+ } catch {
14423
+ }
14424
+ (0, import_node_child_process3.execFile)(caddyPath, [], { timeout: 1e4 }, (error, stdout) => {
14425
+ if (error && !stdout)
14426
+ return resolve2(false);
14427
+ resolve2(stdout.length > 0);
13944
14428
  });
13945
14429
  });
13946
14430
  }
@@ -13962,25 +14446,49 @@ function splitHostPort(addr) {
13962
14446
  }
13963
14447
  return { host: addr.slice(0, lastColon), port: addr.slice(lastColon + 1) };
13964
14448
  }
14449
+ var defaultDependencies = {
14450
+ openSession: (runtimeDir, reason) => openPrivilegedSession(runtimeDir, {
14451
+ log: (message) => consola.debug(message),
14452
+ // Both paths are fixed here, before any socket traffic: the privileged
14453
+ // helper must never execute something named in a request.
14454
+ caddyBin: caddyPath,
14455
+ caddyConfigPath: caddyFilePath,
14456
+ reason
14457
+ })
14458
+ };
13965
14459
  var CaddyInstant = class {
13966
- constructor() {
14460
+ constructor(deps = {}) {
13967
14461
  this.inited = false;
13968
14462
  this.stoped = false;
13969
14463
  /** has locked when start */
13970
14464
  this.locked = false;
13971
14465
  this._stopEffects = [];
13972
- testCaddy().then(async () => {
13973
- this.inited = true;
13974
- });
14466
+ this.deps = { ...defaultDependencies, ...deps };
13975
14467
  this.locked = this.checkLock();
13976
14468
  }
13977
14469
  checkLock() {
13978
- if (!(0, import_node_fs3.existsSync)(caddyLockFilePath))
13979
- (0, import_node_fs3.writeFileSync)(caddyLockFilePath, "");
13980
- return lockfile.checkSync(caddyLockFilePath);
14470
+ if (!(0, import_node_fs4.existsSync)(caddyLockFilePath))
14471
+ (0, import_node_fs4.writeFileSync)(caddyLockFilePath, "");
14472
+ try {
14473
+ return lockfile.checkSync(caddyLockFilePath);
14474
+ } catch {
14475
+ return false;
14476
+ }
14477
+ }
14478
+ /**
14479
+ * Connects to the privileged helper, starting it once if needed. It is
14480
+ * reused across instances so a second dev server does not ask for a
14481
+ * password again.
14482
+ */
14483
+ async session(reason) {
14484
+ if (this._session && !this._session.client.connected)
14485
+ this._session = void 0;
14486
+ if (!this._session)
14487
+ this._session = await this.deps.openSession(TEMP_DIR, reason);
14488
+ return this._session;
13981
14489
  }
13982
14490
  async getCaddyfile() {
13983
- if (!(0, import_node_fs3.existsSync)(caddyFilePath)) {
14491
+ if (!(0, import_node_fs4.existsSync)(caddyFilePath)) {
13984
14492
  this.caddyfile = "";
13985
14493
  return "";
13986
14494
  }
@@ -13988,8 +14496,8 @@ var CaddyInstant = class {
13988
14496
  return this.caddyfile;
13989
14497
  }
13990
14498
  get caddyRoot() {
13991
- return (0, import_node_path3.join)(
13992
- import_node_process4.default.platform === "win32" ? `${import_node_process4.default.env.AppData}/Caddy` : `${import_node_process4.default.env.HOME}/Library/Application Support/Caddy`,
14499
+ return (0, import_node_path5.join)(
14500
+ import_node_process7.default.platform === "win32" ? `${import_node_process7.default.env.AppData}/Caddy` : `${import_node_process7.default.env.HOME}/Library/Application Support/Caddy`,
13993
14501
  "./pki/authorities/local"
13994
14502
  );
13995
14503
  }
@@ -14003,6 +14511,33 @@ var CaddyInstant = class {
14003
14511
  await download();
14004
14512
  this.inited = true;
14005
14513
  }
14514
+ /**
14515
+ * Hands the Caddy storage directory back to the developer. Local CA data
14516
+ * created by an earlier root-owned run must stay readable for `tls internal`
14517
+ * to keep serving the same certificate the browser already trusts.
14518
+ */
14519
+ /**
14520
+ * Installs Caddy's local root CA so the browser stops warning about
14521
+ * `tls internal` certificates. Generating the CA and trusting it are separate
14522
+ * steps: a new CA appears whenever the previous one expires or the storage is
14523
+ * replaced, so this runs on every start instead of once.
14524
+ *
14525
+ * The helper owns both the binary path and the command, so nothing here can
14526
+ * be turned into an arbitrary root execution.
14527
+ */
14528
+ async trustLocalCa(session) {
14529
+ try {
14530
+ const result = await session.client.call("ca.trust");
14531
+ if (result.trusted)
14532
+ consola.debug(`Caddy local CA is trusted
14533
+ ${result.output}`);
14534
+ } catch (error) {
14535
+ consola.warn(
14536
+ `could not install the Caddy root certificate automatically: ${error.message}
14537
+ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14538
+ );
14539
+ }
14540
+ }
14006
14541
  async ensureTlsReady(targetHost) {
14007
14542
  const health = await waitForLocalTls(targetHost);
14008
14543
  if (!health.healthy)
@@ -14056,8 +14591,8 @@ var CaddyInstant = class {
14056
14591
  await this.init();
14057
14592
  const sourceHost = splitHostPort(source).host;
14058
14593
  const targetHost = splitHostPort(target).host;
14059
- if (!await addHost(sourceHost, targetHost))
14060
- throw new Error("update host failed");
14594
+ const session = await this.session({ target: targetHost, https });
14595
+ await session.client.call("hosts.add", { ip: sourceHost, host: targetHost });
14061
14596
  consola.success("update host success\n");
14062
14597
  const normalizeBase = (b) => {
14063
14598
  let out = b || "/";
@@ -14092,24 +14627,24 @@ var CaddyInstant = class {
14092
14627
  void this.updateCaddyfile();
14093
14628
  })
14094
14629
  );
14095
- if (!(0, import_node_fs3.existsSync)(caddyLockFilePath))
14096
- (0, import_node_fs3.writeFileSync)(caddyLockFilePath, "");
14630
+ if (!(0, import_node_fs4.existsSync)(caddyLockFilePath))
14631
+ (0, import_node_fs4.writeFileSync)(caddyLockFilePath, "");
14097
14632
  if (!this.locked) {
14098
- if (await tryPort(443))
14099
- await kill(443);
14100
- if ((import_node_process4.default.platform === "win32" || !https) && await tryPort(80))
14101
- await kill(80);
14633
+ await session.client.call("port.free", { port: 443 });
14634
+ if (import_node_process7.default.platform === "win32" || !https)
14635
+ await session.client.call("port.free", { port: 80 });
14102
14636
  }
14103
14637
  return new Promise((resolve2, reject2) => {
14104
- var _a4, _b3;
14105
14638
  let startupCheckStarted = false;
14106
14639
  const resolveWhenReady = async () => {
14107
14640
  if (startupCheckStarted)
14108
14641
  return;
14109
14642
  startupCheckStarted = true;
14110
14643
  try {
14111
- if (https)
14644
+ if (https) {
14645
+ await this.trustLocalCa(session);
14112
14646
  await this.ensureTlsReady(targetHost);
14647
+ }
14113
14648
  resolve2();
14114
14649
  } catch (error) {
14115
14650
  if (!this.locked)
@@ -14118,96 +14653,87 @@ var CaddyInstant = class {
14118
14653
  }
14119
14654
  };
14120
14655
  const setupCleanup = () => {
14121
- import_node_process4.default.on("SIGINT", async () => {
14656
+ import_node_process7.default.on("SIGINT", async () => {
14122
14657
  if (this.stoped)
14123
14658
  return;
14124
- import_node_process4.default.stdin.resume();
14659
+ import_node_process7.default.stdin.resume();
14125
14660
  try {
14126
14661
  await this.baseCleanup(restore);
14127
14662
  } finally {
14128
14663
  this.stoped = true;
14129
- import_node_process4.default.nextTick(() => {
14130
- import_node_process4.default.exit();
14664
+ import_node_process7.default.nextTick(() => {
14665
+ import_node_process7.default.exit();
14131
14666
  });
14132
14667
  }
14133
14668
  });
14134
- const originalExit = import_node_process4.default.exit.bind(import_node_process4.default);
14135
- import_node_process4.default.exit = async (code) => {
14136
- const port = Number(splitHostPort(source).port);
14137
- if (!Number.isNaN(port) && await tryPort(port))
14138
- await kill(port);
14139
- const pwd = import_node_process4.default.cwd();
14140
- const viteCacheDir = `${pwd}/node_modules/.vite`;
14141
- if ((0, import_node_fs3.existsSync)(viteCacheDir))
14142
- await chmodRecursive(viteCacheDir, 511).catch(() => {
14143
- });
14144
- const viteTempCacheDir = `${pwd}/node_modules/.vite-temp`;
14145
- if ((0, import_node_fs3.existsSync)(viteTempCacheDir))
14146
- await chmodRecursive(viteTempCacheDir, 511).catch(() => {
14147
- });
14148
- const nuxtCacheDir = `${pwd}/.nuxt`;
14149
- if ((0, import_node_fs3.existsSync)(nuxtCacheDir))
14150
- await chmodRecursive(nuxtCacheDir, 511).catch(() => {
14151
- });
14152
- const webpackCacheDir = `${pwd}/node_modules/.cache`;
14153
- if ((0, import_node_fs3.existsSync)(webpackCacheDir))
14154
- await chmodRecursive(webpackCacheDir, 511).catch(() => {
14155
- });
14669
+ const originalExit = import_node_process7.default.exit.bind(import_node_process7.default);
14670
+ import_node_process7.default.exit = async (code) => {
14156
14671
  if (this.stoped)
14157
14672
  return originalExit(code);
14158
- import_node_process4.default.stdin.resume();
14673
+ import_node_process7.default.stdin.resume();
14159
14674
  try {
14160
14675
  await this.baseCleanup();
14161
14676
  } finally {
14162
14677
  this.stoped = true;
14163
- import_node_process4.default.nextTick(() => {
14678
+ import_node_process7.default.nextTick(() => {
14164
14679
  originalExit(code);
14165
14680
  });
14166
14681
  }
14167
14682
  };
14168
14683
  };
14169
14684
  if (!this.locked) {
14170
- this._caddyChild = import_node_process4.default.platform !== "win32" ? (0, import_node_child_process4.spawn)("sudo", ["-E", caddyPath, "run", "--config", caddyFilePath, "--watch"]) : (0, import_node_child_process4.spawn)(caddyPath, ["run", "--config", caddyFilePath, "--watch"]);
14171
14685
  lockfile.lockSync(caddyLockFilePath);
14172
- this._caddyChild.on("error", (err) => {
14173
- return reject2(err);
14174
- });
14175
- (_a4 = this._caddyChild.stderr) == null ? void 0 : _a4.on("data", async (data) => {
14176
- const lines = data.toString().split("\n").map((line) => line.trim());
14177
- for (const line of lines) {
14178
- showCaddyLog && line && console.info(line);
14179
- if (isCaddyReloadCancellation(line)) {
14180
- consola.info("Caddy restarted before TLS issuance completed; retrying.\n");
14181
- continue;
14182
- }
14183
- try {
14184
- if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
14185
- if (line.includes("parsing caddyfile tokens")) {
14186
- consola.error("Caddyfile syntax error, please contact the author:\n", `${this.caddyfile}
14686
+ setupCleanup();
14687
+ void (async () => {
14688
+ try {
14689
+ const child = new HelperCaddyProcess(session.client);
14690
+ this._caddyChild = child;
14691
+ await session.client.call("caddy.start");
14692
+ child.on("exit", (code) => {
14693
+ if (code !== null && code !== 0)
14694
+ reject2(new Error(`Caddy exited with code ${code}`));
14695
+ });
14696
+ child.stderr.on("data", async (data) => {
14697
+ const lines = data.toString().split("\n").map((line) => line.trim());
14698
+ for (const line of lines) {
14699
+ showCaddyLog && line && console.info(line);
14700
+ if (isCaddyReloadCancellation(line)) {
14701
+ consola.info("Caddy restarted before TLS issuance completed; retrying.\n");
14702
+ continue;
14703
+ }
14704
+ try {
14705
+ if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
14706
+ if (line.includes("parsing caddyfile tokens")) {
14707
+ consola.error("Caddyfile syntax error, please contact the author:\n", `${this.caddyfile}
14187
14708
 
14188
14709
  ${line}
14189
14710
  `);
14190
- await this.baseCleanup();
14191
- import_node_process4.default.exit();
14192
- } else {
14193
- consola.error(`${line}
14711
+ await this.baseCleanup();
14712
+ import_node_process7.default.exit();
14713
+ } else {
14714
+ consola.error(`${line}
14194
14715
  `);
14195
- return reject2(line);
14716
+ return reject2(line);
14717
+ }
14718
+ }
14719
+ } catch {
14196
14720
  }
14721
+ if (line.includes("config file changed"))
14722
+ consola.success("Detect added a new reverse proxy config, restarted.\n");
14723
+ if (line.includes("caddy proxying") || line.includes("serving initial"))
14724
+ void resolveWhenReady();
14197
14725
  }
14198
- } catch {
14199
- }
14200
- if (line.includes("config file changed"))
14201
- consola.success("Detect added a new reverse proxy config, restarted.\n");
14202
- if (line.includes("caddy proxying") || line.includes("serving initial"))
14726
+ });
14727
+ child.stdout.on("data", (data) => {
14728
+ consola.info(data.toString());
14203
14729
  void resolveWhenReady();
14730
+ });
14731
+ } catch (error) {
14732
+ if (!this.locked)
14733
+ await this.baseCleanup(restore);
14734
+ reject2(error);
14204
14735
  }
14205
- });
14206
- (_b3 = this._caddyChild.stdout) == null ? void 0 : _b3.on("data", (_data) => {
14207
- consola.info(_data.toString());
14208
- void resolveWhenReady();
14209
- });
14210
- setupCleanup();
14736
+ })();
14211
14737
  } else {
14212
14738
  consola.info("Caddy is running in another process.");
14213
14739
  void (async () => {
@@ -14224,17 +14750,25 @@ ${line}
14224
14750
  });
14225
14751
  }
14226
14752
  async baseCleanup(restore = true) {
14753
+ var _a4;
14227
14754
  this._stopEffects.forEach((fn) => fn());
14755
+ this._stopEffects.length = 0;
14228
14756
  try {
14229
- if (restore && this._source && this._target) {
14230
- if (await removeHost(splitHostPort(this._source).host, splitHostPort(this._target).host))
14231
- consola.success("Restore host success.\n");
14232
- else
14233
- consola.fail("Restore host failed.\n");
14757
+ if (restore && this._source && this._target && this._session) {
14758
+ const sourceHost = splitHostPort(this._source).host;
14759
+ const targetHost = splitHostPort(this._target).host;
14760
+ await this._session.client.call("hosts.remove", { ip: sourceHost, host: targetHost });
14761
+ if (sourceHost === "localhost")
14762
+ await this._session.client.call("hosts.remove", { ip: "127.0.0.1", host: targetHost });
14763
+ consola.success("Restore host success.\n");
14234
14764
  }
14235
14765
  } catch (e) {
14236
- consola.error(e);
14237
- consola.fail("Restore host failed.\n");
14766
+ if (((_a4 = this._session) == null ? void 0 : _a4.client.connected) === false) {
14767
+ consola.debug("hosts entries are restored by the privileged helper on disconnect");
14768
+ } else {
14769
+ consola.error(e);
14770
+ consola.fail("Restore host failed.\n");
14771
+ }
14238
14772
  }
14239
14773
  if (!this.locked && !this.stoped) {
14240
14774
  await this.stopCaddy();
@@ -14392,9 +14926,18 @@ var hmrSseBridgeClientScript = `
14392
14926
  })();
14393
14927
  `;
14394
14928
 
14929
+ // src/privilege-state.ts
14930
+ var denied = false;
14931
+ function markPrivilegeDenied() {
14932
+ denied = true;
14933
+ }
14934
+ function isPrivilegeDenied() {
14935
+ return denied;
14936
+ }
14937
+
14395
14938
  // src/index.ts
14396
14939
  var caddy;
14397
- var cwd = import_node_process5.default.cwd();
14940
+ var cwd = import_node_process8.default.cwd();
14398
14941
  function colorUrl(url2) {
14399
14942
  return import_picocolors2.default.green(url2.replace(/:(\d+)\//, (_, port) => `:${import_picocolors2.default.bold(port)}/`));
14400
14943
  }
@@ -14429,16 +14972,27 @@ async function printForwardProxy() {
14429
14972
  }
14430
14973
  var vitePrintUrls = once((options, source, target, base = "/", _printUrls) => {
14431
14974
  _printUrls == null ? void 0 : _printUrls();
14975
+ if (isPrivilegeDenied())
14976
+ return;
14432
14977
  if (caddy)
14433
14978
  return;
14434
- caddy = new CaddyInstant();
14435
- caddy.run(source, target, {
14979
+ const instance = new CaddyInstant();
14980
+ caddy = instance;
14981
+ instance.run(source, target, {
14436
14982
  base,
14437
14983
  ...options
14438
14984
  }).then(async () => {
14439
14985
  await printForwardProxy();
14440
14986
  consola.success(` ${import_picocolors2.default.green("\u279C")} ${import_picocolors2.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
14441
14987
  }).catch((e) => {
14988
+ if (caddy === instance)
14989
+ caddy = void 0;
14990
+ if (e instanceof PrivilegeDeniedError) {
14991
+ markPrivilegeDenied();
14992
+ consola.warn("reverse proxy skipped: administrator permission was not granted.");
14993
+ consola.info("Restart the dev server to enable it again.");
14994
+ return;
14995
+ }
14442
14996
  throw e;
14443
14997
  });
14444
14998
  });
@@ -14451,7 +15005,7 @@ var nuxt_default = (0, import_kit.defineNuxtModule)({
14451
15005
  configKey: "unpluginHttpsReverseProxy"
14452
15006
  },
14453
15007
  setup(options, _nuxt) {
14454
- if (import_node_process6.default.env.NODE_ENV !== "development")
15008
+ if (import_node_process9.default.env.NODE_ENV !== "development")
14455
15009
  return;
14456
15010
  const {
14457
15011
  enable = true,
@@ -14459,10 +15013,6 @@ var nuxt_default = (0, import_kit.defineNuxtModule)({
14459
15013
  } = options;
14460
15014
  if (!enable)
14461
15015
  return;
14462
- if (!isAdmin()) {
14463
- consola.warn("please run as administrator");
14464
- return;
14465
- }
14466
15016
  if (!target) {
14467
15017
  consola.fail("please provide target");
14468
15018
  return;