-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.js
More file actions
91 lines (81 loc) · 2.57 KB
/
index.js
File metadata and controls
91 lines (81 loc) · 2.57 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
79
80
81
82
83
84
85
86
87
88
89
90
91
class GreenlockProxy {
maintainerEmail
rules = []
proxy
greenlock
constructor(opts) {
this.maintainerEmail = opts.maintainerEmail;
var staging = opts.staging || false;
var pkg = require('./package.json');
var Greenlock = require('@root/greenlock');
this.greenlock = Greenlock.create({
packageRoot: __dirname,
configDir: "../../greenlock.d/",
packageAgent: pkg.name + '/' + pkg.version,
maintainerEmail: this.maintainerEmail,
staging: staging
});
this.greenlock.manager
.defaults({
agreeToTerms: true,
subscriberEmail: this.maintainerEmail
})
}
register(domains, targets) {
if (!Array.isArray(domains)) {
domains = [domains];
}
if (!Array.isArray(targets)) {
targets = [targets];
}
this.rules.push({
domains: domains,
targets: targets
})
this.greenlock.add({
subject: domains[0],
altnames: domains
})
}
start() {
require('greenlock-express')
.init({
packageRoot: __dirname,
// contact for security and critical bug notices
maintainerEmail: this.maintainerEmail,
// where to look for configuration
configDir: '../../greenlock.d',
// whether or not to run at cloudscale
cluster: false
})
// Serves on 80 and 443
// Get's SSL certificates magically!
.ready(this.httpsWorker.bind(this));
}
httpsWorker(glx) {
this.proxy = require("http-proxy").createProxyServer({ xfwd: true });
// catches error events during proxying
this.proxy.on("error", function (err, req, res) {
console.error(err);
res.statusCode = 500;
res.end();
return;
})
// servers a node app that proxies requests to a localhost
glx.serveApp(this.serveFcn.bind(this))
}
serveFcn(req, res) {
this.rules.forEach(rule => {
this.bindTarget(req, res, this.proxy, rule.domains, rule.targets);
})
}
bindTarget(req, res, proxy, domains, targets) {
if (domains.includes(req.headers.host)) {
let i = (Math.floor(Math.random() * targets.length));
proxy.web(req, res, {
target: targets[i]
})
}
}
}
module.exports = GreenlockProxy;