unplugin-https-reverse-proxy 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 huali <https://github.com/zcf0508>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,76 @@
1
+ # unplugin-https-reverse-proxy
2
+
3
+ [![NPM version](https://img.shields.io/npm/v/unplugin-https-reverse-proxy?color=a1b858&label=)](https://www.npmjs.com/package/unplugin-https-reverse-proxy)
4
+
5
+ A plugin for https reverse proxy, support `vite` and `webpack`.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm i unplugin-https-reverse-proxy
11
+ ```
12
+
13
+ <details>
14
+ <summary>Vite</summary><br>
15
+
16
+ ```ts
17
+ // vite.config.ts
18
+ import Starter from 'unplugin-https-reverse-proxy/vite'
19
+
20
+ export default defineConfig({
21
+ plugins: [
22
+ Starter({ /* options */ }),
23
+ ],
24
+ })
25
+ ```
26
+
27
+ Example: [`playground/`](./playground/)
28
+
29
+ <br></details>
30
+
31
+ <details>
32
+ <summary>Webpack</summary><br>
33
+
34
+ ```ts
35
+ // webpack.config.js
36
+ module.exports = {
37
+ /* ... */
38
+ plugins: [
39
+ require('unplugin-https-reverse-proxy/webpack')({ /* options */ })
40
+ ]
41
+ }
42
+ ```
43
+
44
+ <br></details>
45
+
46
+ <details>
47
+ <summary>Nuxt</summary><br>
48
+
49
+ ```ts
50
+ // nuxt.config.js
51
+ export default defineNuxtConfig({
52
+ modules: [
53
+ ['unplugin-https-reverse-proxy/nuxt', { /* options */ }],
54
+ ],
55
+ })
56
+ ```
57
+
58
+ > This module works for both Nuxt 2 and [Nuxt Vite](https://github.com/nuxt/vite)
59
+
60
+ <br></details>
61
+
62
+ <details>
63
+ <summary>Vue CLI</summary><br>
64
+
65
+ ```ts
66
+ // vue.config.js
67
+ module.exports = {
68
+ configureWebpack: {
69
+ plugins: [
70
+ require('unplugin-https-reverse-proxy/webpack')({ /* options */ }),
71
+ ],
72
+ },
73
+ }
74
+ ```
75
+
76
+ <br>
@@ -0,0 +1,348 @@
1
+ // src/index.ts
2
+ import process3 from "process";
3
+ import { createUnplugin } from "unplugin";
4
+ import c from "picocolors";
5
+
6
+ // src/caddy/index.ts
7
+ import { platform } from "os";
8
+ import process2 from "process";
9
+ import { chmodSync, createWriteStream, existsSync, unlinkSync } from "fs";
10
+ import { spawn } from "child_process";
11
+ import got from "got";
12
+ import * as hostile from "hostile";
13
+ import kill from "kill-port";
14
+
15
+ // src/caddy/constants.ts
16
+ import { join } from "path";
17
+ import process from "process";
18
+ var TEMP_DIR = process.env.TEMP || process.env.TMPDIR || "/tmp";
19
+ var caddyPath = join(TEMP_DIR, "caddy");
20
+ var caddyFilePath = join(TEMP_DIR, "CADDYFILE");
21
+ var supportList = [
22
+ {
23
+ platform: "dragonfly",
24
+ arch: "amd64"
25
+ },
26
+ {
27
+ platform: "freebsd",
28
+ arch: "amd64"
29
+ },
30
+ {
31
+ platform: "freebsd",
32
+ arch: "arm-6"
33
+ },
34
+ {
35
+ platform: "freebsd",
36
+ arch: "arm-7"
37
+ },
38
+ {
39
+ platform: "freebsd",
40
+ arch: "arm64"
41
+ },
42
+ {
43
+ platform: "linux",
44
+ arch: "amd64"
45
+ },
46
+ {
47
+ platform: "linux",
48
+ arch: "arm-5"
49
+ },
50
+ {
51
+ platform: "linux",
52
+ arch: "arm-6"
53
+ },
54
+ {
55
+ platform: "linux",
56
+ arch: "arm-7"
57
+ },
58
+ {
59
+ platform: "linux",
60
+ arch: "arm64"
61
+ },
62
+ {
63
+ platform: "linux",
64
+ arch: "mips"
65
+ },
66
+ {
67
+ platform: "linux",
68
+ arch: "mips64"
69
+ },
70
+ {
71
+ platform: "linux",
72
+ arch: "mips64le"
73
+ },
74
+ {
75
+ platform: "linux",
76
+ arch: "mipsle"
77
+ },
78
+ {
79
+ platform: "linux",
80
+ arch: "ppc64"
81
+ },
82
+ {
83
+ platform: "linux",
84
+ arch: "ppc64le"
85
+ },
86
+ {
87
+ platform: "linux",
88
+ arch: "s390x"
89
+ },
90
+ {
91
+ platform: "darwin",
92
+ arch: "amd64"
93
+ },
94
+ {
95
+ platform: "darwin",
96
+ arch: "arm64"
97
+ },
98
+ {
99
+ platform: "openbsd",
100
+ arch: "amd64"
101
+ },
102
+ {
103
+ platform: "openbsd",
104
+ arch: "arm-6"
105
+ },
106
+ {
107
+ platform: "openbsd",
108
+ arch: "arm-7"
109
+ },
110
+ {
111
+ platform: "openbsd",
112
+ arch: "arm64"
113
+ },
114
+ {
115
+ platform: "windows",
116
+ arch: "amd64"
117
+ },
118
+ {
119
+ platform: "windows",
120
+ arch: "arm-6"
121
+ },
122
+ {
123
+ platform: "windows",
124
+ arch: "arm-7"
125
+ },
126
+ {
127
+ platform: "windows",
128
+ arch: "arm64"
129
+ }
130
+ ];
131
+
132
+ // src/caddy/index.ts
133
+ async function download() {
134
+ if (await testCaddy())
135
+ return caddyPath;
136
+ return new Promise((resolve, reject) => {
137
+ const file = createWriteStream(caddyPath);
138
+ let _platform = platform().toString();
139
+ _platform === "win32" && (_platform = "windows");
140
+ let _arch = process2.arch.toString();
141
+ _arch === "x64" && (_arch = "amd64");
142
+ const support = supportList.find((item) => item.platform === _platform && item.arch === _arch);
143
+ if (!support)
144
+ return reject(new Error("not support"));
145
+ const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}`;
146
+ existsSync(caddyPath) && unlinkSync(caddyPath);
147
+ got.stream(dowmloadLink).pipe(file).on("finish", () => {
148
+ if (process2.platform === "win32")
149
+ return resolve(caddyPath);
150
+ chmodSync(caddyPath, 493);
151
+ resolve(caddyPath);
152
+ }).on("error", (err) => {
153
+ reject(err);
154
+ });
155
+ });
156
+ }
157
+ function testCaddy() {
158
+ return new Promise((resolve, reject) => {
159
+ if (!existsSync(caddyPath))
160
+ return resolve(false);
161
+ chmodSync(caddyPath, 493);
162
+ const child = spawn("sudo", [caddyPath]);
163
+ child.on("error", (err) => {
164
+ reject(err);
165
+ });
166
+ child.stdout.on("data", (_data) => {
167
+ resolve(true);
168
+ });
169
+ });
170
+ }
171
+ var CaddyInstant = class {
172
+ constructor() {
173
+ this.inited = false;
174
+ testCaddy().then(() => {
175
+ this.inited = true;
176
+ });
177
+ }
178
+ async init() {
179
+ await download();
180
+ this.inited = true;
181
+ }
182
+ async updateHost(ip, host) {
183
+ ["localhost", "0.0.0.0"].includes(ip) && (ip = "127.0.0.1");
184
+ return new Promise((resolve, reject) => {
185
+ hostile.set(ip, host, (err) => {
186
+ if (err) {
187
+ return reject(err);
188
+ } else {
189
+ if (process2.platform === "win32") {
190
+ spawn("ipconfig", ["/flushdns"]).on("error", (err2) => {
191
+ return reject(err2);
192
+ }).on("close", () => {
193
+ resolve(true);
194
+ });
195
+ } else {
196
+ spawn("sudo", ["killall", "-HUP", "mDNSResponder"]).on("error", (err2) => {
197
+ return reject(err2);
198
+ }).on("close", () => {
199
+ resolve(true);
200
+ });
201
+ }
202
+ }
203
+ });
204
+ });
205
+ }
206
+ async restoreHost(ip, host) {
207
+ ["localhost", "0.0.0.0"].includes(ip) && (ip = "127.0.0.1");
208
+ return new Promise((resolve, reject) => {
209
+ hostile.remove(ip, host, (err) => {
210
+ if (err) {
211
+ return reject(err);
212
+ } else {
213
+ if (process2.platform === "win32") {
214
+ spawn("ipconfig", ["/flushdns"]).on("error", (err2) => {
215
+ return reject(err2);
216
+ }).on("close", () => {
217
+ resolve(true);
218
+ });
219
+ } else {
220
+ spawn("sudo", ["killall", "-HUP", "mDNSResponder"]).on("error", (err2) => {
221
+ return reject(err2);
222
+ }).on("close", () => {
223
+ resolve(true);
224
+ });
225
+ }
226
+ }
227
+ });
228
+ });
229
+ }
230
+ /**
231
+ * @param source like `127.0.0.1:8080`
232
+ * @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
233
+ * @returns
234
+ */
235
+ async run(source, target, options) {
236
+ const {
237
+ restore = false,
238
+ base = "/"
239
+ } = options || {};
240
+ if (!this.inited)
241
+ await this.init();
242
+ if (!await this.updateHost(source.split(":")[0], target.split(":")[0]))
243
+ throw new Error("update host failed");
244
+ await kill(443, "tcp");
245
+ return new Promise((resolve, reject) => {
246
+ const child = spawn("sudo", [caddyPath, "reverse-proxy", "--from", `${target.split(":")[0]}`, "--to", `${source}`, "--internal-certs"]);
247
+ child.on("error", (err) => {
248
+ return reject(err);
249
+ });
250
+ child.stderr.on("data", (data) => {
251
+ if (data.toString().includes("Error")) {
252
+ child.kill();
253
+ return reject(data.toString());
254
+ }
255
+ });
256
+ child.stdout.on("data", (_data) => {
257
+ resolve(async () => {
258
+ if (!restore)
259
+ return;
260
+ if (await this.restoreHost(source.split(":")[0], target.split(":")[0])) {
261
+ console.log("restore host success\n");
262
+ } else {
263
+ console.error("restore host failed\n");
264
+ }
265
+ child.kill();
266
+ });
267
+ });
268
+ });
269
+ }
270
+ };
271
+
272
+ // src/index.ts
273
+ var config;
274
+ var unpluginFactory = (options) => ({
275
+ name: "unplugin-https-reverse-proxy",
276
+ vite: {
277
+ configResolved(_config) {
278
+ config = _config;
279
+ },
280
+ configureServer(server) {
281
+ const {
282
+ target = ""
283
+ } = options;
284
+ if (!target) {
285
+ console.log("please provide target");
286
+ return;
287
+ }
288
+ server.printUrls = () => {
289
+ var _a;
290
+ let source = `localhost:${config.server.port}`;
291
+ const url = (_a = server.resolvedUrls) == null ? void 0 : _a.local[0];
292
+ if (url) {
293
+ const u = new URL(url);
294
+ source = u.host;
295
+ }
296
+ const base = server.config.base || "/";
297
+ try {
298
+ const caddy = new CaddyInstant();
299
+ caddy.run(source, target, {
300
+ base
301
+ }).then((stop) => {
302
+ const colorUrl = (url2) => c.green(url2.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
303
+ console.log(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`https://${target}${base}`)}`);
304
+ process3.on("SIGINT", async () => {
305
+ await stop();
306
+ server.close();
307
+ process3.exit();
308
+ });
309
+ });
310
+ } catch (e) {
311
+ console.error(e);
312
+ }
313
+ };
314
+ }
315
+ },
316
+ webpack(compiler) {
317
+ var _a, _b;
318
+ const {
319
+ target = ""
320
+ } = options;
321
+ if (!target) {
322
+ console.log("please provide target");
323
+ return;
324
+ }
325
+ const source = `${((_a = compiler.options.devServer) == null ? void 0 : _a.host) || "127.0.0.1"}:${((_b = compiler.options.devServer) == null ? void 0 : _b.port) || "8080"}`;
326
+ try {
327
+ const caddy = new CaddyInstant();
328
+ caddy.run(source, target).then((stop) => {
329
+ const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
330
+ console.log(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`https://${target}`)}`);
331
+ process3.on("SIGINT", async () => {
332
+ await stop();
333
+ process3.exit();
334
+ });
335
+ });
336
+ } catch (e) {
337
+ console.error(e);
338
+ }
339
+ }
340
+ });
341
+ var unplugin = /* @__PURE__ */ createUnplugin(unpluginFactory);
342
+ var src_default = unplugin;
343
+
344
+ export {
345
+ unpluginFactory,
346
+ unplugin,
347
+ src_default
348
+ };
@@ -0,0 +1,11 @@
1
+ import {
2
+ unpluginFactory
3
+ } from "./chunk-QYHKWM3K.js";
4
+
5
+ // src/webpack.ts
6
+ import { createWebpackPlugin } from "unplugin";
7
+ var webpack_default = createWebpackPlugin(unpluginFactory);
8
+
9
+ export {
10
+ webpack_default
11
+ };
@@ -0,0 +1,11 @@
1
+ import {
2
+ unpluginFactory
3
+ } from "./chunk-QYHKWM3K.js";
4
+
5
+ // src/vite.ts
6
+ import { createVitePlugin } from "unplugin";
7
+ var vite_default = createVitePlugin(unpluginFactory);
8
+
9
+ export {
10
+ vite_default
11
+ };