-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
78 lines (66 loc) · 2.45 KB
/
index.js
File metadata and controls
78 lines (66 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
require('dotenv').config()
const express = require('express');
const http = require('http');
const https = require('https');
const httpProxy = require('http-proxy');
const fs = require('fs');
var cors = require('cors')
const { createProxyMiddleware } = require('http-proxy-middleware')
const app = express();
const proxy = httpProxy.createProxyServer();
const localUseHttps = process.env.LOCAL_USE_HTTPS === 'true'
const localHost = process.env.LOCAL_HOST || 'localhost'
const localPort = process.env.LOCAL_PORT || 443
const remoteUseHttps = process.env.REMOTE_USE_HTTPS === 'true'
const remoteHost = process.env.REMOTE_HOST || 'localhost'
const remotePort = process.env.REMOTE_PORT || 443
const remoteSecurity = process.env.REMOTE_SECURITY === 'true'
const useCors = process.env.USE_CORS === 'true'
const corsOrigin = process.env.CORS_ORIGIN || ''
const corsAllowCredentials = process.env.CORS_ALLOW_CREDENTIALS === 'true'
const localServer = `${localUseHttps ? 'https' : 'http'}://${localHost}:${localPort}`;
const targetServer = `${remoteUseHttps ? 'https' : 'http'}://${remoteHost}:${remotePort}`;
if (useCors) {
app.use(cors({
origin: corsOrigin,
credentials: corsAllowCredentials,
}))
}
// Загрузка SSL-сертификата и ключа
const privateKey = fs.readFileSync('cert/key.pem', 'utf8');
const certificate = fs.readFileSync('cert/cert.pem', 'utf8');
const credentials = {
key: privateKey,
cert: certificate,
passphrase: '1234',
}
const wsProxy = createProxyMiddleware({
target: `ws://${remoteHost}:${remotePort}`,
changeOrigin: true,
secure: remoteUseHttps,
ws: true,
})
app.use(wsProxy)
app.use((req, res) => {
// Проксирование запросов на целевой сервер
proxy.web(req, res, {
target: targetServer,
secure: remoteSecurity,
headers: {
Host: remoteHost,
}
});
});
// Обработка события ошибки прокси
proxy.on('error', (err, req, res) => {
console.error('Proxy error:', err);
res.status(500).send('Proxy error');
});
// Создание сервера HTTPS или HTTP
const httpsServer = (localUseHttps ? https : http).createServer(credentials, app);
httpsServer.on("upgrade", wsProxy.upgrade)
// Запуск сервера
httpsServer.listen(localPort, localHost, () => {
console.log(`Proxy server is running on ${localServer}`);
console.log(`Forwarding to ${targetServer}`)
});