-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
64 lines (55 loc) · 1.75 KB
/
server.js
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
var fs = require('fs'),
http = require('http'),
https = require('https'),
proxy = require('http-proxy');
var proxies = [ ];
proxies.index = { };
function register(entry) {
var index = proxies.length;
proxies.push({
id: entry.id,
match: entry.match,
proxy: proxy.createProxyServer({ target: entry.target })
});
proxies.index[entry.id] = { index: index, value: entry };
}
function unregister(id) {
if (!proxies.index[id]) return;
proxies.splice(proxies.index[id].index, 1);
delete proxies.index[id];
}
function find(req) {
return proxies.filter(function(proxy) {
if (!proxy.match) return false;
if (proxy.match.path && !req.url.test(proxy.match.path)) return false;
if (proxy.match.host && !req.headers['host'].test(proxy.match.host)) return false;
return true;
}).map(function(proxy) {
return proxy.proxy;
});
}
// Redirect anything on a non-secure channel to something on a secure one
http.createServer(function(req, res) {
res.writeHead(302, { 'Location': 'https://'+req.headers['host']+req.url });
res.end();
}).listen(80);
// Proxy requests to the backends
https.createServer({
key: fs.readFileSync('/etc/ssl/private/innovate.cs.surrey.sfu.ca.key', 'utf8'),
cert: fs.readFileSync('/etc/ssl/private/innovate.cs.surrey.sfu.ca.crt', 'utf8')
}).on('request', function(req, res) {
var proxies = find(req);
if (proxies.length === 1)
return proxies[0].web(req, res);
res.writeHead(500);
res.end();
}).on('upgrade', function (req, socket, head) {
var proxies = find(req);
if (proxies.length === 1)
return proxy.ws(req, socket, head);
socket.close();
}).listen(443);
// Drop privileges after listening on 80 and 443 and reading the SSL certificates
process.initgroups('innovate', 'innovate');
process.setgid('innovate');
process.setuid('innovate');