unplugin-https-reverse-proxy 1.0.0-beta.2 → 1.0.0-beta.21

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.
@@ -1,516 +0,0 @@
1
- import {
2
- __spreadValues,
3
- chmodRecursive,
4
- consola,
5
- isAdmin
6
- } from "./chunk-RUJE3YFB.js";
7
-
8
- // src/index.ts
9
- import process4 from "process";
10
- import { existsSync as existsSync2 } from "fs";
11
- import { createUnplugin } from "unplugin";
12
- import c from "picocolors";
13
-
14
- // src/caddy/index.ts
15
- import { platform } from "os";
16
- import process3 from "process";
17
- import { chmodSync as chmodSync2, createWriteStream, existsSync, unlinkSync } from "fs";
18
- import { spawn } from "child_process";
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
-
24
- // src/host/index.ts
25
- import process from "process";
26
- import { exec } from "child_process";
27
- import { chmodSync } from "fs";
28
- import _Hosts from "hosts-so-easy";
29
- var Hosts = _Hosts.default || _Hosts;
30
- var hostInstance = new Hosts({
31
- debounceTime: 50,
32
- hostsFile: getPathOfSystemHostsPath()
33
- });
34
- function getPathOfSystemHostsPath() {
35
- return process.platform === "win32" ? `${process.env.windir || "C:\\WINDOWS"}\\system32\\drivers\\etc\\hosts` : "/etc/hosts";
36
- }
37
- async function syncHost() {
38
- return new Promise((resolve, reject) => {
39
- exec(
40
- process.platform === "win32" ? "ipconfig /flushdns" : "sudo -E killall -HUP mDNSResponder",
41
- (error, stdout, stderr) => {
42
- if (error) {
43
- consola.error(`exec error: ${error}`);
44
- return resolve(false);
45
- }
46
- return resolve(true);
47
- }
48
- );
49
- });
50
- }
51
- async function addHost(ip, host) {
52
- if (process.platform !== "win32")
53
- chmodSync(getPathOfSystemHostsPath(), 511);
54
- hostInstance.add("127.0.0.1", "localhost");
55
- hostInstance.add(ip, host);
56
- if (ip === "localhost")
57
- hostInstance.add("127.0.0.1", host);
58
- await hostInstance.updateFinish();
59
- return await syncHost();
60
- }
61
- async function removeHost(ip, host) {
62
- if (process.platform !== "win32")
63
- chmodSync(getPathOfSystemHostsPath(), 511);
64
- hostInstance.remove(ip, host);
65
- if (ip === "localhost")
66
- hostInstance.remove("127.0.0.1", host);
67
- await hostInstance.updateFinish();
68
- return await syncHost();
69
- }
70
-
71
- // src/caddy/constants.ts
72
- import { join } from "path";
73
- import process2 from "process";
74
- var TEMP_DIR = process2.env.TEMP || process2.env.TMPDIR || "/tmp";
75
- var caddyPath = join(TEMP_DIR, `caddy${process2.platform === "win32" ? ".exe" : ""}`);
76
- var caddyFilePath = join(TEMP_DIR, "CADDYFILE");
77
- var supportList = [
78
- {
79
- platform: "dragonfly",
80
- arch: "amd64"
81
- },
82
- {
83
- platform: "freebsd",
84
- arch: "amd64"
85
- },
86
- {
87
- platform: "freebsd",
88
- arch: "arm-6"
89
- },
90
- {
91
- platform: "freebsd",
92
- arch: "arm-7"
93
- },
94
- {
95
- platform: "freebsd",
96
- arch: "arm64"
97
- },
98
- {
99
- platform: "linux",
100
- arch: "amd64"
101
- },
102
- {
103
- platform: "linux",
104
- arch: "arm-5"
105
- },
106
- {
107
- platform: "linux",
108
- arch: "arm-6"
109
- },
110
- {
111
- platform: "linux",
112
- arch: "arm-7"
113
- },
114
- {
115
- platform: "linux",
116
- arch: "arm64"
117
- },
118
- {
119
- platform: "linux",
120
- arch: "mips"
121
- },
122
- {
123
- platform: "linux",
124
- arch: "mips64"
125
- },
126
- {
127
- platform: "linux",
128
- arch: "mips64le"
129
- },
130
- {
131
- platform: "linux",
132
- arch: "mipsle"
133
- },
134
- {
135
- platform: "linux",
136
- arch: "ppc64"
137
- },
138
- {
139
- platform: "linux",
140
- arch: "ppc64le"
141
- },
142
- {
143
- platform: "linux",
144
- arch: "s390x"
145
- },
146
- {
147
- platform: "darwin",
148
- arch: "amd64"
149
- },
150
- {
151
- platform: "darwin",
152
- arch: "arm64"
153
- },
154
- {
155
- platform: "openbsd",
156
- arch: "amd64"
157
- },
158
- {
159
- platform: "openbsd",
160
- arch: "arm-6"
161
- },
162
- {
163
- platform: "openbsd",
164
- arch: "arm-7"
165
- },
166
- {
167
- platform: "openbsd",
168
- arch: "arm64"
169
- },
170
- {
171
- platform: "windows",
172
- arch: "amd64"
173
- },
174
- {
175
- platform: "windows",
176
- arch: "arm-6"
177
- },
178
- {
179
- platform: "windows",
180
- arch: "arm-7"
181
- },
182
- {
183
- platform: "windows",
184
- arch: "arm64"
185
- }
186
- ];
187
-
188
- // src/caddy/utils.ts
189
- import { createServer } from "net";
190
- import ora from "ora";
191
- var spinner;
192
- function tryPort(port) {
193
- return new Promise((resolve, reject) => {
194
- try {
195
- const server = createServer().listen(port);
196
- server.on("listening", () => {
197
- server.close();
198
- resolve(false);
199
- });
200
- server.on("error", (err) => {
201
- if (err.code === "EADDRINUSE")
202
- resolve(true);
203
- server.close();
204
- });
205
- } catch (e) {
206
- resolve(true);
207
- }
208
- });
209
- }
210
- function getNumber(number) {
211
- if (number <= 0)
212
- return "0%";
213
- else if (number < 100)
214
- return `${number.toFixed(2)}%`;
215
- else
216
- return "100%";
217
- }
218
- function logProgress(percent) {
219
- if (!spinner) {
220
- consola.log("");
221
- spinner = ora({
222
- text: "Start Download Caddy: 0%",
223
- indent: 2
224
- });
225
- spinner.start();
226
- } else {
227
- spinner.text = `Download Caddy: ${getNumber(Number(percent) * 100)}`;
228
- }
229
- }
230
- function logProgressOver() {
231
- if (!spinner) {
232
- spinner = ora({
233
- text: "Start Download Caddy: 100%",
234
- indent: 2
235
- });
236
- spinner.start();
237
- } else {
238
- spinner.succeed();
239
- consola.log("");
240
- }
241
- }
242
-
243
- // src/caddy/index.ts
244
- async function download() {
245
- if (await testCaddy())
246
- return caddyPath;
247
- return new Promise((resolve, reject) => {
248
- const file = createWriteStream(caddyPath);
249
- let _platform = platform().toString();
250
- _platform === "win32" && (_platform = "windows");
251
- let _arch = process3.arch.toString();
252
- _arch === "x64" && (_arch = "amd64");
253
- const support = supportList.find((item) => item.platform === _platform && item.arch === _arch);
254
- if (!support)
255
- return reject(new Error("not support"));
256
- const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}`;
257
- existsSync(caddyPath) && unlinkSync(caddyPath);
258
- const httpProxy = process3.env.HTTP_PROXY || process3.env.http_proxy;
259
- const httpsProxy = process3.env.HTTPS_PROXY || process3.env.https_proxy;
260
- const httpAgent = httpProxy ? new HttpProxyAgent(httpProxy) : void 0;
261
- const httpsAgent = httpsProxy ? new HttpsProxyAgent(httpsProxy) : void 0;
262
- got.stream(dowmloadLink, {
263
- agent: {
264
- http: httpAgent,
265
- https: httpsAgent
266
- }
267
- }).on("downloadProgress", (progress) => {
268
- logProgress(progress.percent);
269
- }).pipe(file).on("finish", () => {
270
- logProgressOver();
271
- if (process3.platform === "win32")
272
- return resolve(caddyPath);
273
- chmodSync2(caddyPath, 493);
274
- resolve(caddyPath);
275
- }).on("error", (err) => {
276
- reject(err);
277
- });
278
- });
279
- }
280
- function testCaddy() {
281
- return new Promise((resolve, reject) => {
282
- if (!existsSync(caddyPath))
283
- return resolve(false);
284
- chmodSync2(caddyPath, 493);
285
- const child = process3.platform === "win32" ? spawn(caddyPath, []) : spawn("sudo", ["-E", caddyPath]);
286
- child.on("close", () => {
287
- return resolve(false);
288
- });
289
- child.on("error", (err) => {
290
- return reject(err);
291
- });
292
- child.stdout.on("data", (_data) => {
293
- return resolve(true);
294
- });
295
- });
296
- }
297
- var CaddyInstant = class {
298
- constructor() {
299
- this.inited = false;
300
- this.stoped = false;
301
- testCaddy().then(() => {
302
- this.inited = true;
303
- });
304
- }
305
- async init() {
306
- await download();
307
- this.inited = true;
308
- }
309
- /**
310
- * @param source like `127.0.0.1:8080`
311
- * @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
312
- * @returns
313
- */
314
- async run(source, target, options) {
315
- source = source.replace("0.0.0.0", "127.0.0.1");
316
- const {
317
- restore = true,
318
- base = "/",
319
- showCaddyLog = false,
320
- https = false
321
- } = options || {};
322
- if (!this.inited)
323
- await this.init();
324
- if (https && await tryPort(443))
325
- await kill(443, "tcp");
326
- if ((process3.platform === "win32" || !https) && await tryPort(80))
327
- await kill(80, "tcp");
328
- if (!await addHost(source.split(":")[0], target.split(":")[0]))
329
- throw new Error("update host failed");
330
- consola.success("update host success\n");
331
- return new Promise((resolve, reject) => {
332
- const child = process3.platform !== "win32" ? spawn("sudo", ["-E", caddyPath, "reverse-proxy", "--from", `${target.split(":")[0]}${https ? "" : ":80"}`, "--to", `${source}`, "--internal-certs", "--insecure", "--disable-redirects"]) : spawn(caddyPath, ["reverse-proxy", "--from", `${target.split(":")[0]}`, "--to", `${source}`, "--internal-certs"]);
333
- child.on("error", (err) => {
334
- return reject(err);
335
- });
336
- process3.on("SIGINT", async () => {
337
- if (!restore || this.stoped)
338
- return;
339
- try {
340
- if (await removeHost(source.split(":")[0], target.split(":")[0]))
341
- consola.success("restore host success\n");
342
- else
343
- consola.fail("restore host failed\n");
344
- } catch (e) {
345
- consola.error(e);
346
- consola.fail("restore host failed\n");
347
- } finally {
348
- this.stoped = true;
349
- process3.nextTick(() => {
350
- process3.exit();
351
- });
352
- }
353
- });
354
- const originalExit = process3.exit.bind(process3);
355
- process3.exit = async (code) => {
356
- if (!restore || this.stoped)
357
- return originalExit(code);
358
- try {
359
- if (await removeHost(source.split(":")[0], target.split(":")[0]))
360
- consola.success("restore host success\n");
361
- else
362
- consola.fail("restore host failed\n");
363
- } catch (e) {
364
- consola.error(e);
365
- consola.fail("restore host failed\n");
366
- } finally {
367
- this.stoped = true;
368
- process3.nextTick(() => {
369
- originalExit(code);
370
- });
371
- }
372
- };
373
- child.stderr.on("data", (data) => {
374
- const lines = data.toString().split("\n").map((line) => line.trim());
375
- for (const line of lines) {
376
- showCaddyLog && line && console.info(line);
377
- if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
378
- consola.error(line);
379
- return reject(line);
380
- }
381
- }
382
- });
383
- child.stdout.on("data", (_data) => {
384
- consola.info(_data.toString());
385
- resolve();
386
- });
387
- });
388
- }
389
- };
390
-
391
- // src/index.ts
392
- var config;
393
- var caddy;
394
- var pwd = process4.cwd();
395
- function vitePrintUrls(server, options, source, target, base = "/", _printUrls) {
396
- _printUrls == null ? void 0 : _printUrls();
397
- const viteCacheDir = `${pwd}/node_modules/.vite`;
398
- if (existsSync2(viteCacheDir))
399
- chmodRecursive(viteCacheDir, 511);
400
- const nuxtCacheDir = `${pwd}/.nuxt`;
401
- if (existsSync2(nuxtCacheDir))
402
- chmodRecursive(nuxtCacheDir, 511);
403
- try {
404
- if (caddy)
405
- return;
406
- caddy = new CaddyInstant();
407
- caddy.run(source, target, __spreadValues({
408
- base
409
- }, options)).then(() => {
410
- const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
411
- consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
412
- }).catch((e) => {
413
- throw e;
414
- });
415
- } catch (e) {
416
- consola.error(e);
417
- }
418
- }
419
- var unpluginFactory = (options) => ({
420
- name: "unplugin-https-reverse-proxy",
421
- enforce: "pre",
422
- vite: {
423
- configResolved(_config) {
424
- config = _config;
425
- },
426
- configureServer(server) {
427
- var _a;
428
- if (!isAdmin()) {
429
- consola.warn("please run as administrator");
430
- return;
431
- }
432
- if (config.command === "build")
433
- return;
434
- const {
435
- enable = true,
436
- target = ""
437
- } = options;
438
- if (!enable)
439
- return;
440
- if (!target) {
441
- consola.fail("please provide target");
442
- return;
443
- }
444
- const _printUrls = server.printUrls.bind(server);
445
- let source = `localhost:${config.server.port || 5173}`;
446
- const url = (_a = server.resolvedUrls) == null ? void 0 : _a.local[0];
447
- if (url) {
448
- const u = new URL(url);
449
- source = u.host;
450
- }
451
- const base = server.config.base || "/";
452
- server.printUrls = () => vitePrintUrls(server, options, source, target, base, _printUrls);
453
- }
454
- },
455
- webpack(compiler) {
456
- var _a;
457
- if (!isAdmin()) {
458
- consola.warn("please run as administrator");
459
- return;
460
- }
461
- if (process4.env.NODE_ENV !== "development")
462
- return;
463
- const {
464
- enable = true,
465
- target = ""
466
- } = options;
467
- if (!enable)
468
- return;
469
- if (!target) {
470
- consola.fail("please provide target");
471
- return;
472
- }
473
- const nuxtCacheDir = `${pwd}/node_modules/.cache`;
474
- if (existsSync2(nuxtCacheDir))
475
- chmodRecursive(nuxtCacheDir, 511);
476
- try {
477
- const devServer = __spreadValues(__spreadValues({
478
- host: "localhost",
479
- port: 8080
480
- }, compiler.options.devServer), process4.VUE_CLI_SERVICE.projectOptions.devServer);
481
- const source = `${devServer.host}:${devServer.port}`;
482
- if (caddy)
483
- return;
484
- const _close = (_a = compiler.close) == null ? void 0 : _a.bind(compiler);
485
- if (_close) {
486
- compiler.close = async (callback) => {
487
- process4.on("exit", () => {
488
- _close && _close(callback);
489
- });
490
- };
491
- } else {
492
- options.https = false;
493
- }
494
- caddy = new CaddyInstant();
495
- caddy.run(source, target, __spreadValues({}, options)).then(() => {
496
- const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
497
- compiler.hooks.done.tap("unplugin-https-reverse-proxy", () => {
498
- consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
499
- });
500
- }).catch((e) => {
501
- throw e;
502
- });
503
- } catch (e) {
504
- consola.error(e);
505
- }
506
- }
507
- });
508
- var unplugin = /* @__PURE__ */ createUnplugin(unpluginFactory);
509
- var src_default = unplugin;
510
-
511
- export {
512
- vitePrintUrls,
513
- unpluginFactory,
514
- unplugin,
515
- src_default
516
- };
@@ -1,63 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
- var __hasOwnProp = Object.prototype.hasOwnProperty;
4
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
- var __spreadValues = (a, b) => {
7
- for (var prop in b || (b = {}))
8
- if (__hasOwnProp.call(b, prop))
9
- __defNormalProp(a, prop, b[prop]);
10
- if (__getOwnPropSymbols)
11
- for (var prop of __getOwnPropSymbols(b)) {
12
- if (__propIsEnum.call(b, prop))
13
- __defNormalProp(a, prop, b[prop]);
14
- }
15
- return a;
16
- };
17
-
18
- // src/utils.ts
19
- import process from "process";
20
- import path from "path";
21
- import { chmod, readdir, stat } from "fs/promises";
22
- import { execSync } from "child_process";
23
- import { createConsola } from "consola";
24
- var consola = createConsola({
25
- level: 3
26
- }).withTag("reverse-proxy");
27
- async function chmodRecursive(_path, mode) {
28
- await chmod(_path, mode);
29
- if ((await stat(_path)).isDirectory()) {
30
- const children = await readdir(_path);
31
- for (const child of children)
32
- await chmodRecursive(path.join(_path, child), mode);
33
- }
34
- }
35
- function once(fn) {
36
- let called = false;
37
- return (...args) => {
38
- if (called)
39
- return;
40
- called = true;
41
- return fn(...args);
42
- };
43
- }
44
- function isAdmin() {
45
- if (process.platform === "win32") {
46
- try {
47
- execSync("net session", { stdio: "ignore" });
48
- return true;
49
- } catch (e) {
50
- return false;
51
- }
52
- } else {
53
- return process.getuid && process.getuid() === 0;
54
- }
55
- }
56
-
57
- export {
58
- __spreadValues,
59
- consola,
60
- chmodRecursive,
61
- once,
62
- isAdmin
63
- };
@@ -1,11 +0,0 @@
1
- import {
2
- unpluginFactory
3
- } from "./chunk-N6ZBBGYD.js";
4
-
5
- // src/webpack.ts
6
- import { createWebpackPlugin } from "unplugin";
7
- var webpack_default = createWebpackPlugin(unpluginFactory);
8
-
9
- export {
10
- webpack_default
11
- };
@@ -1,19 +0,0 @@
1
- import { existsSync, unlinkSync } from 'node:fs'
2
- import process from 'node:process'
3
- import { consola } from '../src/utils'
4
- import { download } from '../src/caddy'
5
- import { caddyPath } from '../src/caddy/constants'
6
-
7
- async function run() {
8
- try {
9
- if (process.env.UHRP_AUTO_INSTALL_CADDY) {
10
- existsSync(caddyPath) && unlinkSync(caddyPath)
11
- await download()
12
- }
13
- }
14
- catch (e: any) {
15
- consola.error(e.code)
16
- }
17
- }
18
-
19
- run()