unplugin-https-reverse-proxy 1.0.0-beta.14 → 1.0.0-beta.16

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.
@@ -0,0 +1,45 @@
1
+ // src/utils.ts
2
+ import process from "node:process";
3
+ import path from "node:path";
4
+ import { chmod, readdir, stat } from "node:fs/promises";
5
+ import { execSync } from "node:child_process";
6
+ import { createConsola } from "consola";
7
+ var consola = createConsola({
8
+ level: 3
9
+ }).withTag("reverse-proxy");
10
+ async function chmodRecursive(_path, mode) {
11
+ await chmod(_path, mode);
12
+ if ((await stat(_path)).isDirectory()) {
13
+ const children = await readdir(_path);
14
+ for (const child of children)
15
+ await chmodRecursive(path.join(_path, child), mode);
16
+ }
17
+ }
18
+ function once(fn) {
19
+ let called = false;
20
+ return (...args) => {
21
+ if (called)
22
+ return;
23
+ called = true;
24
+ return fn(...args);
25
+ };
26
+ }
27
+ function isAdmin() {
28
+ if (process.platform === "win32") {
29
+ try {
30
+ execSync("net session", { stdio: "ignore" });
31
+ return true;
32
+ } catch {
33
+ return false;
34
+ }
35
+ } else {
36
+ return process.getuid && process.getuid() === 0;
37
+ }
38
+ }
39
+
40
+ export {
41
+ consola,
42
+ chmodRecursive,
43
+ once,
44
+ isAdmin
45
+ };
@@ -0,0 +1,651 @@
1
+ import {
2
+ chmodRecursive,
3
+ consola,
4
+ isAdmin,
5
+ once
6
+ } from "./chunk-2VGRJ3QS.js";
7
+
8
+ // src/index.ts
9
+ import process4 from "node:process";
10
+ import { createUnplugin } from "unplugin";
11
+ import c from "picocolors";
12
+
13
+ // src/caddy/index.ts
14
+ import { platform } from "node:os";
15
+ import process3 from "node:process";
16
+ import { chmodSync as chmodSync2, createWriteStream, existsSync, mkdirSync, unlinkSync, writeFileSync } from "node:fs";
17
+ import { spawn } from "node:child_process";
18
+ import { readFile, unlink, writeFile } from "node:fs/promises";
19
+ import { got } from "got-cjs";
20
+ import { HttpProxyAgent } from "http-proxy-agent";
21
+ import { HttpsProxyAgent } from "https-proxy-agent";
22
+ import kill from "kill-port";
23
+ import * as lockfile from "proper-lockfile";
24
+
25
+ // src/host/index.ts
26
+ import process from "node:process";
27
+ import { exec } from "node:child_process";
28
+ import { chmodSync } from "node:fs";
29
+ import _Hosts from "hosts-so-easy";
30
+ var Hosts = _Hosts.default || _Hosts;
31
+ var hostInstance = new Hosts({
32
+ debounceTime: 50,
33
+ hostsFile: getPathOfSystemHostsPath()
34
+ });
35
+ function getPathOfSystemHostsPath() {
36
+ return process.platform === "win32" ? `${process.env.windir || "C:\\WINDOWS"}\\system32\\drivers\\etc\\hosts` : "/etc/hosts";
37
+ }
38
+ async function syncHost() {
39
+ return new Promise((resolve, reject) => {
40
+ exec(
41
+ process.platform === "win32" ? "ipconfig /flushdns" : "sudo -E killall -HUP mDNSResponder",
42
+ (error, stdout, stderr) => {
43
+ if (error) {
44
+ consola.error(`exec error: ${error}`);
45
+ return resolve(false);
46
+ }
47
+ return resolve(true);
48
+ }
49
+ );
50
+ });
51
+ }
52
+ async function addHost(ip, host) {
53
+ if (process.platform !== "win32")
54
+ chmodSync(getPathOfSystemHostsPath(), 511);
55
+ hostInstance.add("127.0.0.1", "localhost");
56
+ hostInstance.add(ip, host);
57
+ if (ip === "localhost")
58
+ hostInstance.add("127.0.0.1", host);
59
+ await hostInstance.updateFinish();
60
+ return await syncHost();
61
+ }
62
+ async function removeHost(ip, host) {
63
+ if (process.platform !== "win32")
64
+ chmodSync(getPathOfSystemHostsPath(), 511);
65
+ hostInstance.remove(ip, host);
66
+ if (ip === "localhost")
67
+ hostInstance.remove("127.0.0.1", host);
68
+ await hostInstance.updateFinish();
69
+ return await syncHost();
70
+ }
71
+
72
+ // src/caddy/constants.ts
73
+ import { join } from "node:path";
74
+ import os from "node:os";
75
+ import process2 from "node:process";
76
+ import dotenvFlow from "dotenv-flow";
77
+ dotenvFlow.config({
78
+ silent: true
79
+ });
80
+ function resolvePath(path) {
81
+ if (path.startsWith("~"))
82
+ return join(os.homedir() || "", path.slice(1));
83
+ return path;
84
+ }
85
+ var TEMP_DIR = resolvePath(process2.env.UHRP_CADDY_PATH || process2.env.TEMP || process2.env.TMPDIR || "/tmp");
86
+ var caddyPath = join(TEMP_DIR, `caddy${process2.platform === "win32" ? ".exe" : ""}`);
87
+ var caddyFilePath = join(TEMP_DIR, "CADDYFILE");
88
+ var caddyLockFilePath = join(TEMP_DIR, "caddylock");
89
+ var supportList = [
90
+ {
91
+ platform: "dragonfly",
92
+ arch: "amd64"
93
+ },
94
+ {
95
+ platform: "freebsd",
96
+ arch: "amd64"
97
+ },
98
+ {
99
+ platform: "freebsd",
100
+ arch: "arm-6"
101
+ },
102
+ {
103
+ platform: "freebsd",
104
+ arch: "arm-7"
105
+ },
106
+ {
107
+ platform: "freebsd",
108
+ arch: "arm64"
109
+ },
110
+ {
111
+ platform: "linux",
112
+ arch: "amd64"
113
+ },
114
+ {
115
+ platform: "linux",
116
+ arch: "arm-5"
117
+ },
118
+ {
119
+ platform: "linux",
120
+ arch: "arm-6"
121
+ },
122
+ {
123
+ platform: "linux",
124
+ arch: "arm-7"
125
+ },
126
+ {
127
+ platform: "linux",
128
+ arch: "arm64"
129
+ },
130
+ {
131
+ platform: "linux",
132
+ arch: "mips"
133
+ },
134
+ {
135
+ platform: "linux",
136
+ arch: "mips64"
137
+ },
138
+ {
139
+ platform: "linux",
140
+ arch: "mips64le"
141
+ },
142
+ {
143
+ platform: "linux",
144
+ arch: "mipsle"
145
+ },
146
+ {
147
+ platform: "linux",
148
+ arch: "ppc64"
149
+ },
150
+ {
151
+ platform: "linux",
152
+ arch: "ppc64le"
153
+ },
154
+ {
155
+ platform: "linux",
156
+ arch: "s390x"
157
+ },
158
+ {
159
+ platform: "darwin",
160
+ arch: "amd64"
161
+ },
162
+ {
163
+ platform: "darwin",
164
+ arch: "arm64"
165
+ },
166
+ {
167
+ platform: "openbsd",
168
+ arch: "amd64"
169
+ },
170
+ {
171
+ platform: "openbsd",
172
+ arch: "arm-6"
173
+ },
174
+ {
175
+ platform: "openbsd",
176
+ arch: "arm-7"
177
+ },
178
+ {
179
+ platform: "openbsd",
180
+ arch: "arm64"
181
+ },
182
+ {
183
+ platform: "windows",
184
+ arch: "amd64"
185
+ },
186
+ {
187
+ platform: "windows",
188
+ arch: "arm-6"
189
+ },
190
+ {
191
+ platform: "windows",
192
+ arch: "arm-7"
193
+ },
194
+ {
195
+ platform: "windows",
196
+ arch: "arm64"
197
+ }
198
+ ];
199
+
200
+ // src/caddy/utils.ts
201
+ import { createServer } from "node:net";
202
+ import ora from "ora";
203
+ var spinner;
204
+ function tryPort(port) {
205
+ return new Promise((resolve, reject) => {
206
+ try {
207
+ const server = createServer().listen(port);
208
+ server.on("listening", () => {
209
+ server.close();
210
+ resolve(false);
211
+ });
212
+ server.on("error", (err) => {
213
+ if (err.code === "EADDRINUSE")
214
+ resolve(true);
215
+ server.close();
216
+ });
217
+ } catch (e) {
218
+ resolve(true);
219
+ }
220
+ });
221
+ }
222
+ function getNumber(number) {
223
+ if (number <= 0)
224
+ return "0%";
225
+ else if (number < 100)
226
+ return `${number.toFixed(2)}%`;
227
+ else
228
+ return "100%";
229
+ }
230
+ function logProgress(percent) {
231
+ if (!spinner) {
232
+ consola.log("");
233
+ spinner = ora({
234
+ text: "Start Download Caddy: 0%",
235
+ indent: 2
236
+ });
237
+ spinner.start();
238
+ } else {
239
+ spinner.text = `Download Caddy: ${getNumber(Number(percent) * 100)}`;
240
+ }
241
+ }
242
+ function logProgressOver() {
243
+ if (!spinner) {
244
+ spinner = ora({
245
+ text: "Start Download Caddy: 100%",
246
+ indent: 2
247
+ });
248
+ spinner.start();
249
+ } else {
250
+ spinner.succeed();
251
+ consola.log("");
252
+ }
253
+ }
254
+
255
+ // src/caddy/index.ts
256
+ async function download() {
257
+ if (await testCaddy())
258
+ return caddyPath;
259
+ return new Promise((resolve, reject) => {
260
+ if (!existsSync(TEMP_DIR)) {
261
+ mkdirSync(TEMP_DIR, { recursive: true });
262
+ chmodSync2(TEMP_DIR, 511);
263
+ }
264
+ const file = createWriteStream(caddyPath);
265
+ let _platform = platform().toString();
266
+ _platform === "win32" && (_platform = "windows");
267
+ let _arch = process3.arch.toString();
268
+ _arch === "x64" && (_arch = "amd64");
269
+ const support = supportList.find((item) => item.platform === _platform && item.arch === _arch);
270
+ if (!support)
271
+ return reject(new Error("not support"));
272
+ const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}`;
273
+ existsSync(caddyPath) && unlinkSync(caddyPath);
274
+ const httpProxy = process3.env.HTTP_PROXY || process3.env.http_proxy;
275
+ const httpsProxy = process3.env.HTTPS_PROXY || process3.env.https_proxy;
276
+ const httpAgent = httpProxy ? new HttpProxyAgent(httpProxy) : void 0;
277
+ const httpsAgent = httpsProxy ? new HttpsProxyAgent(httpsProxy) : void 0;
278
+ const chmodCaddyOnce = once(() => {
279
+ chmodSync2(caddyPath, 511);
280
+ });
281
+ got.stream(dowmloadLink, {
282
+ agent: {
283
+ http: httpAgent,
284
+ https: httpsAgent
285
+ }
286
+ }).on("downloadProgress", (progress) => {
287
+ logProgress(progress.percent);
288
+ chmodCaddyOnce();
289
+ }).pipe(file).on("finish", () => {
290
+ logProgressOver();
291
+ if (process3.platform === "win32")
292
+ return resolve(caddyPath);
293
+ chmodSync2(caddyPath, 511);
294
+ resolve(caddyPath);
295
+ }).on("error", (err) => {
296
+ reject(err);
297
+ });
298
+ });
299
+ }
300
+ function testCaddy() {
301
+ return new Promise((resolve, reject) => {
302
+ if (!existsSync(caddyPath))
303
+ return resolve(false);
304
+ chmodSync2(caddyPath, 511);
305
+ const child = process3.platform === "win32" ? spawn(caddyPath, []) : spawn("sudo", ["-E", caddyPath]);
306
+ child.on("close", () => {
307
+ return resolve(false);
308
+ });
309
+ child.on("error", (err) => {
310
+ return reject(err);
311
+ });
312
+ child.stdout.on("data", (_data) => {
313
+ return resolve(true);
314
+ });
315
+ });
316
+ }
317
+ var CaddyInstant = class {
318
+ constructor() {
319
+ this.inited = false;
320
+ this.stoped = false;
321
+ /** has locked */
322
+ this.locked = false;
323
+ testCaddy().then(async () => {
324
+ await this.getCaddyfile();
325
+ this.inited = true;
326
+ });
327
+ this.locked = this.checkLock();
328
+ }
329
+ checkLock() {
330
+ if (!existsSync(caddyLockFilePath))
331
+ writeFileSync(caddyLockFilePath, "");
332
+ return lockfile.checkSync(caddyLockFilePath);
333
+ }
334
+ async getCaddyfile() {
335
+ if (!existsSync(caddyFilePath))
336
+ await this.initCaddyfile();
337
+ this.caddyfile = await readFile(caddyFilePath, "utf-8");
338
+ return this.caddyfile;
339
+ }
340
+ async initCaddyfile() {
341
+ const contet = `
342
+ {
343
+ debug
344
+ auto_https disable_redirects
345
+ }
346
+
347
+ `;
348
+ await writeFile(caddyFilePath, contet);
349
+ this.caddyfile = contet;
350
+ }
351
+ async writeCaddyfile() {
352
+ return await writeFile(caddyFilePath, this.caddyfile || "");
353
+ }
354
+ async deleteCaddyfile() {
355
+ return await unlink(caddyFilePath);
356
+ }
357
+ async init() {
358
+ await download();
359
+ this.inited = true;
360
+ }
361
+ /**
362
+ * @param source like `127.0.0.1:8080`
363
+ * @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
364
+ * @returns
365
+ */
366
+ async run(source, target, options) {
367
+ source = source.replace("0.0.0.0", "127.0.0.1");
368
+ const {
369
+ restore = true,
370
+ base = "/",
371
+ showCaddyLog = false,
372
+ https = false
373
+ } = options || {};
374
+ if (!this.inited)
375
+ await this.init();
376
+ if (!await addHost(source.split(":")[0], target.split(":")[0]))
377
+ throw new Error("update host failed");
378
+ consola.success("update host success\n");
379
+ await this.getCaddyfile();
380
+ if (!(this.caddyfile || "").includes(`${target.split(":")[0]}${https ? "" : ":80"}`)) {
381
+ this.caddyfile = `${this.caddyfile}
382
+ ${target.split(":")[0]}${https ? "" : ":80"} {
383
+ ${https ? "tls internal" : ""}
384
+ reverse_proxy http://${source}
385
+ }
386
+
387
+ `;
388
+ await this.writeCaddyfile();
389
+ }
390
+ if (!existsSync(caddyLockFilePath))
391
+ writeFileSync(caddyLockFilePath, "");
392
+ if (!this.locked) {
393
+ if (await tryPort(443))
394
+ await kill(443, "tcp");
395
+ if ((process3.platform === "win32" || !https) && await tryPort(80))
396
+ await kill(80, "tcp");
397
+ }
398
+ return new Promise((resolve, reject) => {
399
+ const setupCleanup = () => {
400
+ process3.on("SIGINT", async () => {
401
+ if (!restore || this.stoped)
402
+ return;
403
+ await this.baseCleanup();
404
+ try {
405
+ if (await removeHost(source.split(":")[0], target.split(":")[0]))
406
+ consola.success("Restore host success.\n");
407
+ else
408
+ consola.fail("Restore host failed.\n");
409
+ } catch (e) {
410
+ consola.error(e);
411
+ consola.fail("Restore host failed.\n");
412
+ } finally {
413
+ this.stoped = true;
414
+ process3.nextTick(() => {
415
+ process3.exit();
416
+ });
417
+ }
418
+ });
419
+ const originalExit = process3.exit.bind(process3);
420
+ process3.exit = async (code) => {
421
+ const port = Number(source.split(":")[1]);
422
+ if (!Number.isNaN(port) && await tryPort(port))
423
+ await kill(port, "tcp");
424
+ const pwd = process3.cwd();
425
+ const viteCacheDir = `${pwd}/node_modules/.vite`;
426
+ if (existsSync(viteCacheDir))
427
+ chmodRecursive(viteCacheDir, 511);
428
+ const nuxtCacheDir = `${pwd}/.nuxt`;
429
+ if (existsSync(nuxtCacheDir))
430
+ await chmodRecursive(nuxtCacheDir, 511);
431
+ const webpackCacheDir = `${pwd}/node_modules/.cache`;
432
+ if (existsSync(webpackCacheDir))
433
+ chmodRecursive(webpackCacheDir, 511);
434
+ if (!restore || this.stoped)
435
+ return originalExit(code);
436
+ await this.baseCleanup();
437
+ try {
438
+ if (await removeHost(source.split(":")[0], target.split(":")[0]))
439
+ consola.success("Restore host success.\n");
440
+ else
441
+ consola.fail("Restore host failed.\n");
442
+ } catch (e) {
443
+ consola.error(e);
444
+ consola.fail("Restore host failed.\n");
445
+ } finally {
446
+ this.stoped = true;
447
+ process3.nextTick(() => {
448
+ originalExit(code);
449
+ });
450
+ }
451
+ };
452
+ };
453
+ if (!this.locked) {
454
+ const child = process3.platform !== "win32" ? spawn("sudo", ["-E", caddyPath, "run", "--config", caddyFilePath, "--watch"]) : spawn(caddyPath, ["run", "--config", caddyFilePath, "--watch"]);
455
+ lockfile.lockSync(caddyLockFilePath);
456
+ child.on("error", (err) => {
457
+ return reject(err);
458
+ });
459
+ child.stderr.on("data", (data) => {
460
+ const lines = data.toString().split("\n").map((line) => line.trim());
461
+ for (const line of lines) {
462
+ showCaddyLog && line && console.info(line);
463
+ if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
464
+ consola.error(`${line}
465
+ `);
466
+ return reject(line);
467
+ }
468
+ if (line.includes("config file changed"))
469
+ consola.success("Detect added a new reverse proxy config, restarted.\n");
470
+ if (line.includes("caddy proxying") || line.includes("serving initial"))
471
+ return resolve();
472
+ }
473
+ });
474
+ child.stdout.on("data", (_data) => {
475
+ consola.info(_data.toString());
476
+ resolve();
477
+ });
478
+ setupCleanup();
479
+ } else {
480
+ consola.info("Caddy is running in another process.");
481
+ setupCleanup();
482
+ return resolve();
483
+ }
484
+ });
485
+ }
486
+ async baseCleanup() {
487
+ if (!this.locked) {
488
+ try {
489
+ await lockfile.unlock(caddyLockFilePath);
490
+ await unlink(caddyFilePath);
491
+ await unlink(caddyLockFilePath);
492
+ } catch (e) {
493
+ }
494
+ }
495
+ }
496
+ };
497
+
498
+ // src/index.ts
499
+ var config;
500
+ var caddy;
501
+ var cwd = process4.cwd();
502
+ var vitePrintUrls = once((options, source, target, base = "/", _printUrls) => {
503
+ _printUrls == null ? void 0 : _printUrls();
504
+ if (caddy)
505
+ return;
506
+ caddy = new CaddyInstant();
507
+ caddy.run(source, target, {
508
+ base,
509
+ ...options
510
+ }).then(() => {
511
+ const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
512
+ consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
513
+ }).catch((e) => {
514
+ throw e;
515
+ });
516
+ });
517
+ var unpluginFactory = (options) => ({
518
+ name: "unplugin-https-reverse-proxy",
519
+ enforce: "pre",
520
+ vite: {
521
+ configResolved(_config) {
522
+ config = _config;
523
+ },
524
+ configureServer(server) {
525
+ var _a;
526
+ if (config.command !== "serve")
527
+ return;
528
+ const {
529
+ enable = true,
530
+ target = ""
531
+ } = options;
532
+ if (!enable)
533
+ return;
534
+ if (!isAdmin()) {
535
+ consola.warn("please run as administrator");
536
+ return;
537
+ }
538
+ if (!target) {
539
+ consola.fail("please provide target");
540
+ return;
541
+ }
542
+ const _printUrls = server.printUrls.bind(server);
543
+ let source = `localhost:${config.server.port || 5173}`;
544
+ const url = (_a = server.resolvedUrls) == null ? void 0 : _a.local[0];
545
+ if (url) {
546
+ const u = new URL(url);
547
+ source = u.host;
548
+ }
549
+ const base = server.config.base || "/";
550
+ server.printUrls = () => vitePrintUrls(options, source, target, base, _printUrls);
551
+ }
552
+ },
553
+ webpack(compiler) {
554
+ var _a, _b;
555
+ if (process4.env.NODE_ENV !== "development")
556
+ return;
557
+ const {
558
+ enable = true,
559
+ target = ""
560
+ } = options;
561
+ if (!enable)
562
+ return;
563
+ if (!isAdmin()) {
564
+ consola.warn("please run as administrator");
565
+ return;
566
+ }
567
+ if (!target) {
568
+ consola.fail("please provide target");
569
+ return;
570
+ }
571
+ const devServer = {
572
+ host: "localhost",
573
+ port: 8080,
574
+ ...compiler.options.devServer,
575
+ // @ts-expect-error vuecli
576
+ ...(_a = process4.VUE_CLI_SERVICE) == null ? void 0 : _a.projectOptions.devServer
577
+ };
578
+ const source = `${devServer.host}:${devServer.port}`;
579
+ if (caddy)
580
+ return;
581
+ const _close = (_b = compiler.close) == null ? void 0 : _b.bind(compiler);
582
+ if (_close) {
583
+ compiler.close = async (callback) => {
584
+ process4.on("exit", () => {
585
+ _close && _close(callback);
586
+ });
587
+ };
588
+ } else {
589
+ options.https = false;
590
+ }
591
+ caddy = new CaddyInstant();
592
+ caddy.run(source, target, {
593
+ ...options
594
+ }).then(() => {
595
+ const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
596
+ compiler.hooks.done.tap("unplugin-https-reverse-proxy", () => {
597
+ consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
598
+ });
599
+ }).catch((e) => {
600
+ throw e;
601
+ });
602
+ },
603
+ async rspack(compiler) {
604
+ var _a, _b, _c;
605
+ if (process4.env.NODE_ENV !== "development")
606
+ return;
607
+ const {
608
+ enable = true,
609
+ target = ""
610
+ } = options;
611
+ if (!enable)
612
+ return;
613
+ if (!isAdmin()) {
614
+ consola.warn("please run as administrator");
615
+ return;
616
+ }
617
+ if (!target) {
618
+ consola.fail("please provide target");
619
+ return;
620
+ }
621
+ const devServer = {
622
+ host: "localhost",
623
+ port: 8080,
624
+ ...compiler.options.devServer,
625
+ ...(_c = (_b = await ((_a = await import("@rsbuild/core")) == null ? void 0 : _a.loadConfig({
626
+ cwd
627
+ }))) == null ? void 0 : _b.content) == null ? void 0 : _c.server
628
+ };
629
+ const source = `${devServer.host}:${devServer.port}`;
630
+ if (caddy)
631
+ return;
632
+ caddy = new CaddyInstant();
633
+ caddy.run(source, target, {
634
+ ...options
635
+ }).then(() => {
636
+ const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
637
+ consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
638
+ }).catch((e) => {
639
+ throw e;
640
+ });
641
+ }
642
+ });
643
+ var unplugin = /* @__PURE__ */ createUnplugin(unpluginFactory);
644
+ var src_default = unplugin;
645
+
646
+ export {
647
+ vitePrintUrls,
648
+ unpluginFactory,
649
+ unplugin,
650
+ src_default
651
+ };