unplugin-https-reverse-proxy 1.0.0-beta.8 → 1.0.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.
package/dist/nuxt.cjs CHANGED
@@ -3,22 +3,8 @@ var __create = Object.create;
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
6
  var __getProtoOf = Object.getPrototypeOf;
8
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
- var __spreadValues = (a, b) => {
12
- for (var prop in b || (b = {}))
13
- if (__hasOwnProp.call(b, prop))
14
- __defNormalProp(a, prop, b[prop]);
15
- if (__getOwnPropSymbols)
16
- for (var prop of __getOwnPropSymbols(b)) {
17
- if (__propIsEnum.call(b, prop))
18
- __defNormalProp(a, prop, b[prop]);
19
- }
20
- return a;
21
- };
22
8
  var __export = (target, all) => {
23
9
  for (var name in all)
24
10
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -82,7 +68,7 @@ function isAdmin() {
82
68
  try {
83
69
  (0, import_node_child_process.execSync)("net session", { stdio: "ignore" });
84
70
  return true;
85
- } catch (e) {
71
+ } catch {
86
72
  return false;
87
73
  }
88
74
  } else {
@@ -99,22 +85,21 @@ var import_picocolors = __toESM(require("picocolors"), 1);
99
85
  var import_node_os2 = require("os");
100
86
  var import_node_process4 = __toESM(require("process"), 1);
101
87
  var import_node_fs2 = require("fs");
102
- var import_node_child_process3 = require("child_process");
88
+ var import_node_child_process4 = require("child_process");
89
+ var import_promises2 = require("fs/promises");
103
90
  var import_got_cjs = require("got-cjs");
104
91
  var import_http_proxy_agent = require("http-proxy-agent");
105
92
  var import_https_proxy_agent = require("https-proxy-agent");
106
- var import_kill_port = __toESM(require("kill-port"), 1);
93
+ var lockfile = __toESM(require("proper-lockfile"), 1);
107
94
 
108
95
  // src/host/index.ts
109
96
  var import_node_process2 = __toESM(require("process"), 1);
110
97
  var import_node_child_process2 = require("child_process");
111
98
  var import_node_fs = require("fs");
112
- var import_hosts_so_easy = __toESM(require("hosts-so-easy"), 1);
113
- var Hosts = import_hosts_so_easy.default.default || import_hosts_so_easy.default;
114
- var hostInstance = new Hosts({
115
- debounceTime: 50,
116
- hostsFile: getPathOfSystemHostsPath()
117
- });
99
+ var import_node_util = require("util");
100
+ var import_hostile = __toESM(require("hostile"), 1);
101
+ var _setHost = (0, import_node_util.promisify)(import_hostile.default.set);
102
+ var _removeHost = (0, import_node_util.promisify)(import_hostile.default.remove);
118
103
  function getPathOfSystemHostsPath() {
119
104
  return import_node_process2.default.platform === "win32" ? `${import_node_process2.default.env.windir || "C:\\WINDOWS"}\\system32\\drivers\\etc\\hosts` : "/etc/hosts";
120
105
  }
@@ -135,20 +120,18 @@ async function syncHost() {
135
120
  async function addHost(ip, host) {
136
121
  if (import_node_process2.default.platform !== "win32")
137
122
  (0, import_node_fs.chmodSync)(getPathOfSystemHostsPath(), 511);
138
- hostInstance.add("127.0.0.1", "localhost");
139
- hostInstance.add(ip, host);
123
+ await _setHost("127.0.0.1", "localhost");
124
+ await _setHost(ip, host);
140
125
  if (ip === "localhost")
141
- hostInstance.add("127.0.0.1", host);
142
- await hostInstance.updateFinish();
126
+ await _setHost("127.0.0.1", host);
143
127
  return await syncHost();
144
128
  }
145
129
  async function removeHost(ip, host) {
146
130
  if (import_node_process2.default.platform !== "win32")
147
131
  (0, import_node_fs.chmodSync)(getPathOfSystemHostsPath(), 511);
148
- hostInstance.remove(ip, host);
132
+ await _removeHost(ip, host);
149
133
  if (ip === "localhost")
150
- hostInstance.remove("127.0.0.1", host);
151
- await hostInstance.updateFinish();
134
+ await _removeHost("127.0.0.1", host);
152
135
  return await syncHost();
153
136
  }
154
137
 
@@ -168,6 +151,7 @@ function resolvePath(path2) {
168
151
  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");
169
152
  var caddyPath = (0, import_node_path2.join)(TEMP_DIR, `caddy${import_node_process3.default.platform === "win32" ? ".exe" : ""}`);
170
153
  var caddyFilePath = (0, import_node_path2.join)(TEMP_DIR, "CADDYFILE");
154
+ var caddyLockFilePath = (0, import_node_path2.join)(TEMP_DIR, "caddylock");
171
155
  var supportList = [
172
156
  {
173
157
  platform: "dragonfly",
@@ -281,6 +265,7 @@ var supportList = [
281
265
 
282
266
  // src/caddy/utils.ts
283
267
  var import_node_net = require("net");
268
+ var import_node_child_process3 = require("child_process");
284
269
  var import_ora = __toESM(require("ora"), 1);
285
270
  var spinner;
286
271
  function tryPort(port) {
@@ -301,6 +286,18 @@ function tryPort(port) {
301
286
  }
302
287
  });
303
288
  }
289
+ async function kill(port) {
290
+ return new Promise((resolve, reject) => {
291
+ (0, import_node_child_process3.exec)(`npx @maxbo/free-port ${port} -s`, (err, stdout, stderr) => {
292
+ if (err) {
293
+ reject(err);
294
+ } else {
295
+ consola.log(stdout);
296
+ resolve();
297
+ }
298
+ });
299
+ });
300
+ }
304
301
  function getNumber(number) {
305
302
  if (number <= 0)
306
303
  return "0%";
@@ -384,7 +381,7 @@ function testCaddy() {
384
381
  if (!(0, import_node_fs2.existsSync)(caddyPath))
385
382
  return resolve(false);
386
383
  (0, import_node_fs2.chmodSync)(caddyPath, 511);
387
- const child = import_node_process4.default.platform === "win32" ? (0, import_node_child_process3.spawn)(caddyPath, []) : (0, import_node_child_process3.spawn)("sudo", ["-E", caddyPath]);
384
+ const child = import_node_process4.default.platform === "win32" ? (0, import_node_child_process4.spawn)(caddyPath, []) : (0, import_node_child_process4.spawn)("sudo", ["-E", caddyPath]);
388
385
  child.on("close", () => {
389
386
  return resolve(false);
390
387
  });
@@ -400,9 +397,41 @@ var CaddyInstant = class {
400
397
  constructor() {
401
398
  this.inited = false;
402
399
  this.stoped = false;
403
- testCaddy().then(() => {
400
+ /** has locked */
401
+ this.locked = false;
402
+ testCaddy().then(async () => {
403
+ await this.getCaddyfile();
404
404
  this.inited = true;
405
405
  });
406
+ this.locked = this.checkLock();
407
+ }
408
+ checkLock() {
409
+ if (!(0, import_node_fs2.existsSync)(caddyLockFilePath))
410
+ (0, import_node_fs2.writeFileSync)(caddyLockFilePath, "");
411
+ return lockfile.checkSync(caddyLockFilePath);
412
+ }
413
+ async getCaddyfile() {
414
+ if (!(0, import_node_fs2.existsSync)(caddyFilePath))
415
+ await this.initCaddyfile();
416
+ this.caddyfile = await (0, import_promises2.readFile)(caddyFilePath, "utf-8");
417
+ return this.caddyfile;
418
+ }
419
+ async initCaddyfile() {
420
+ const contet = `
421
+ {
422
+ debug
423
+ auto_https disable_redirects
424
+ }
425
+
426
+ `;
427
+ await (0, import_promises2.writeFile)(caddyFilePath, contet);
428
+ this.caddyfile = contet;
429
+ }
430
+ async writeCaddyfile() {
431
+ return await (0, import_promises2.writeFile)(caddyFilePath, this.caddyfile || "");
432
+ }
433
+ async deleteCaddyfile() {
434
+ return await (0, import_promises2.unlink)(caddyFilePath);
406
435
  }
407
436
  async init() {
408
437
  await download();
@@ -421,99 +450,183 @@ var CaddyInstant = class {
421
450
  showCaddyLog = false,
422
451
  https = false
423
452
  } = options || {};
453
+ this._source = source;
454
+ this._target = target;
424
455
  if (!this.inited)
425
456
  await this.init();
426
- if (https && await tryPort(443))
427
- await (0, import_kill_port.default)(443, "tcp");
428
- if ((import_node_process4.default.platform === "win32" || !https) && await tryPort(80))
429
- await (0, import_kill_port.default)(80, "tcp");
430
457
  if (!await addHost(source.split(":")[0], target.split(":")[0]))
431
458
  throw new Error("update host failed");
432
459
  consola.success("update host success\n");
460
+ await this.getCaddyfile();
461
+ if (!(this.caddyfile || "").includes(`${target.split(":")[0]}${https ? "" : ":80"}`)) {
462
+ this.caddyfile = `${this.caddyfile}
463
+ ${target.split(":")[0]}${https ? "" : ":80"} {
464
+ ${https ? "tls internal" : ""}
465
+ reverse_proxy http://${source} {
466
+ health_uri ${base}
467
+ health_interval 2s
468
+ health_timeout 5s
469
+ fail_duration 2s
470
+ unhealthy_status 502 503 504 404
471
+ lb_try_duration 3s
472
+ lb_try_interval 300ms
473
+ health_headers {
474
+ Accept text/html
475
+ Accept-Encoding gzip, deflate, br
476
+ User-Agent Caddy-Health-Check
477
+ }
478
+
479
+ @error status 502 503 504 404
480
+ handle_response @error {
481
+ respond * 503 {
482
+ body "Service Unavailable"
483
+ close
484
+ }
485
+ }
486
+ }
487
+ }
488
+
489
+ `;
490
+ await this.writeCaddyfile();
491
+ }
492
+ if (!(0, import_node_fs2.existsSync)(caddyLockFilePath))
493
+ (0, import_node_fs2.writeFileSync)(caddyLockFilePath, "");
494
+ if (!this.locked) {
495
+ if (await tryPort(443))
496
+ await kill(443);
497
+ if ((import_node_process4.default.platform === "win32" || !https) && await tryPort(80))
498
+ await kill(80);
499
+ }
433
500
  return new Promise((resolve, reject) => {
434
- const child = import_node_process4.default.platform !== "win32" ? (0, import_node_child_process3.spawn)("sudo", ["-E", caddyPath, "reverse-proxy", "--from", `${target.split(":")[0]}${https ? "" : ":80"}`, "--to", `${source}`, "--internal-certs", "--insecure", "--disable-redirects"]) : (0, import_node_child_process3.spawn)(caddyPath, ["reverse-proxy", "--from", `${target.split(":")[0]}`, "--to", `${source}`, "--internal-certs"]);
435
- child.on("error", (err) => {
436
- return reject(err);
437
- });
438
- import_node_process4.default.on("SIGINT", async () => {
439
- if (!restore || this.stoped)
440
- return;
441
- try {
442
- if (await removeHost(source.split(":")[0], target.split(":")[0]))
443
- consola.success("restore host success\n");
444
- else
445
- consola.fail("restore host failed\n");
446
- } catch (e) {
447
- consola.error(e);
448
- consola.fail("restore host failed\n");
449
- } finally {
450
- this.stoped = true;
451
- import_node_process4.default.nextTick(() => {
452
- import_node_process4.default.exit();
453
- });
454
- }
455
- });
456
- const originalExit = import_node_process4.default.exit.bind(import_node_process4.default);
457
- import_node_process4.default.exit = async (code) => {
458
- const port = Number(source.split(":")[1]);
459
- if (!Number.isNaN(port) && await tryPort(port))
460
- await (0, import_kill_port.default)(port, "tcp");
461
- const pwd2 = import_node_process4.default.cwd();
462
- const viteCacheDir = `${pwd2}/node_modules/.vite`;
463
- if ((0, import_node_fs2.existsSync)(viteCacheDir))
464
- chmodRecursive(viteCacheDir, 511);
465
- const nuxtCacheDir = `${pwd2}/.nuxt`;
466
- if ((0, import_node_fs2.existsSync)(nuxtCacheDir))
467
- await chmodRecursive(nuxtCacheDir, 511);
468
- const webpackCacheDir = `${pwd2}/node_modules/.cache`;
469
- if ((0, import_node_fs2.existsSync)(webpackCacheDir))
470
- chmodRecursive(webpackCacheDir, 511);
471
- if (!restore || this.stoped)
472
- return originalExit(code);
473
- try {
474
- if (await removeHost(source.split(":")[0], target.split(":")[0]))
475
- consola.success("restore host success\n");
476
- else
477
- consola.fail("restore host failed\n");
478
- } catch (e) {
479
- consola.error(e);
480
- consola.fail("restore host failed\n");
481
- } finally {
482
- this.stoped = true;
483
- import_node_process4.default.nextTick(() => {
484
- originalExit(code);
485
- });
486
- }
501
+ var _a, _b;
502
+ const setupCleanup = () => {
503
+ import_node_process4.default.on("SIGINT", async () => {
504
+ if (this.stoped)
505
+ return;
506
+ import_node_process4.default.stdin.resume();
507
+ try {
508
+ await this.baseCleanup(restore);
509
+ } finally {
510
+ this.stoped = true;
511
+ import_node_process4.default.nextTick(() => {
512
+ import_node_process4.default.exit();
513
+ });
514
+ }
515
+ });
516
+ const originalExit = import_node_process4.default.exit.bind(import_node_process4.default);
517
+ import_node_process4.default.exit = async (code) => {
518
+ const port = Number(source.split(":")[1]);
519
+ if (!Number.isNaN(port) && await tryPort(port))
520
+ await kill(port);
521
+ const pwd = import_node_process4.default.cwd();
522
+ const viteCacheDir = `${pwd}/node_modules/.vite`;
523
+ if ((0, import_node_fs2.existsSync)(viteCacheDir))
524
+ await chmodRecursive(viteCacheDir, 511).catch(() => {
525
+ });
526
+ const nuxtCacheDir = `${pwd}/.nuxt`;
527
+ if ((0, import_node_fs2.existsSync)(nuxtCacheDir))
528
+ await chmodRecursive(nuxtCacheDir, 511).catch(() => {
529
+ });
530
+ const webpackCacheDir = `${pwd}/node_modules/.cache`;
531
+ if ((0, import_node_fs2.existsSync)(webpackCacheDir))
532
+ await chmodRecursive(webpackCacheDir, 511).catch(() => {
533
+ });
534
+ if (this.stoped)
535
+ return originalExit(code);
536
+ import_node_process4.default.stdin.resume();
537
+ try {
538
+ await this.baseCleanup();
539
+ } finally {
540
+ this.stoped = true;
541
+ import_node_process4.default.nextTick(() => {
542
+ originalExit(code);
543
+ });
544
+ }
545
+ };
487
546
  };
488
- child.stderr.on("data", (data) => {
489
- const lines = data.toString().split("\n").map((line) => line.trim());
490
- for (const line of lines) {
491
- showCaddyLog && line && console.info(line);
492
- if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
493
- consola.error(line);
494
- return reject(line);
547
+ if (!this.locked) {
548
+ 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"]);
549
+ lockfile.lockSync(caddyLockFilePath);
550
+ this._caddyChild.on("error", (err) => {
551
+ return reject(err);
552
+ });
553
+ (_a = this._caddyChild.stderr) == null ? void 0 : _a.on("data", async (data) => {
554
+ const lines = data.toString().split("\n").map((line) => line.trim());
555
+ for (const line of lines) {
556
+ showCaddyLog && line && console.info(line);
557
+ if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
558
+ if (line.includes("parsing caddyfile tokens")) {
559
+ consola.error("Caddyfile syntax error, please contact the author:\n", `${this.caddyfile}
560
+
561
+ ${line}
562
+ `);
563
+ await this.baseCleanup();
564
+ import_node_process4.default.exit();
565
+ } else {
566
+ consola.error(`${line}
567
+ `);
568
+ return reject(line);
569
+ }
570
+ }
571
+ if (line.includes("config file changed"))
572
+ consola.success("Detect added a new reverse proxy config, restarted.\n");
573
+ if (line.includes("caddy proxying") || line.includes("serving initial"))
574
+ return resolve();
495
575
  }
496
- }
497
- });
498
- child.stdout.on("data", (_data) => {
499
- consola.info(_data.toString());
500
- resolve();
501
- });
576
+ });
577
+ (_b = this._caddyChild.stdout) == null ? void 0 : _b.on("data", (_data) => {
578
+ consola.info(_data.toString());
579
+ resolve();
580
+ });
581
+ setupCleanup();
582
+ } else {
583
+ consola.info("Caddy is running in another process.");
584
+ setupCleanup();
585
+ return resolve();
586
+ }
502
587
  });
503
588
  }
589
+ async baseCleanup(restore = true) {
590
+ var _a;
591
+ try {
592
+ if (restore && this._source && this._target) {
593
+ if (await removeHost(this._source.split(":")[0], this._target.split(":")[0]))
594
+ consola.success("Restore host success.\n");
595
+ else
596
+ consola.fail("Restore host failed.\n");
597
+ }
598
+ } catch (e) {
599
+ consola.error(e);
600
+ consola.fail("Restore host failed.\n");
601
+ }
602
+ if (!this.locked && !this.stoped) {
603
+ (_a = this._caddyChild) == null ? void 0 : _a.kill();
604
+ try {
605
+ await lockfile.unlock(caddyLockFilePath).catch(() => {
606
+ });
607
+ await (0, import_promises2.unlink)(caddyFilePath).catch(() => {
608
+ });
609
+ await (0, import_promises2.unlink)(caddyLockFilePath).catch(() => {
610
+ });
611
+ } catch (e) {
612
+ consola.error(e);
613
+ }
614
+ }
615
+ }
504
616
  };
505
617
 
506
618
  // src/index.ts
507
619
  var caddy;
508
- var pwd = import_node_process5.default.cwd();
620
+ var cwd = import_node_process5.default.cwd();
509
621
  var vitePrintUrls = once((options, source, target, base = "/", _printUrls) => {
510
622
  _printUrls == null ? void 0 : _printUrls();
511
623
  if (caddy)
512
624
  return;
513
625
  caddy = new CaddyInstant();
514
- caddy.run(source, target, __spreadValues({
515
- base
516
- }, options)).then(() => {
626
+ caddy.run(source, target, {
627
+ base,
628
+ ...options
629
+ }).then(() => {
517
630
  const colorUrl = (url) => import_picocolors.default.green(url.replace(/:(\d+)\//, (_, port) => `:${import_picocolors.default.bold(port)}/`));
518
631
  consola.success(` ${import_picocolors.default.green("\u279C")} ${import_picocolors.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
519
632
  }).catch((e) => {
@@ -530,16 +643,16 @@ var nuxt_default = (0, import_kit.defineNuxtModule)({
530
643
  setup(options, _nuxt) {
531
644
  if (import_node_process6.default.env.NODE_ENV !== "development")
532
645
  return;
533
- if (!isAdmin()) {
534
- consola.warn("please run as administrator");
535
- return;
536
- }
537
646
  const {
538
647
  enable = true,
539
648
  target = ""
540
649
  } = options;
541
650
  if (!enable)
542
651
  return;
652
+ if (!isAdmin()) {
653
+ consola.warn("please run as administrator");
654
+ return;
655
+ }
543
656
  if (!target) {
544
657
  consola.fail("please provide target");
545
658
  return;
@@ -552,4 +665,4 @@ var nuxt_default = (0, import_kit.defineNuxtModule)({
552
665
  });
553
666
  }
554
667
  });
555
- exports.default = module.exports;
668
+ module.exports = module.exports;exports.default = module.exports;
package/dist/nuxt.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  vitePrintUrls
3
- } from "./chunk-AYUGOY4B.js";
3
+ } from "./chunk-KVE7AVSI.js";
4
4
  import {
5
5
  consola,
6
6
  isAdmin
7
- } from "./chunk-RUJE3YFB.js";
7
+ } from "./chunk-2VGRJ3QS.js";
8
8
 
9
9
  // src/nuxt.ts
10
- import process from "process";
10
+ import process from "node:process";
11
11
  import { defineNuxtModule } from "@nuxt/kit";
12
12
  import "@nuxt/schema";
13
13
  var nuxt_default = defineNuxtModule({
@@ -18,16 +18,16 @@ var nuxt_default = defineNuxtModule({
18
18
  setup(options, _nuxt) {
19
19
  if (process.env.NODE_ENV !== "development")
20
20
  return;
21
- if (!isAdmin()) {
22
- consola.warn("please run as administrator");
23
- return;
24
- }
25
21
  const {
26
22
  enable = true,
27
23
  target = ""
28
24
  } = options;
29
25
  if (!enable)
30
26
  return;
27
+ if (!isAdmin()) {
28
+ consola.warn("please run as administrator");
29
+ return;
30
+ }
31
31
  if (!target) {
32
32
  consola.fail("please provide target");
33
33
  return;