-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
219 lines (199 loc) · 6.24 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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
"use strict";
var PORT = 10000;
require('dotenv-safe').load();
let CF = require('cloudflare');
let client = new CF({
email: process.env.CF_EMAIL,
key: process.env.CF_KEY
});
var fs = require('fs');
var Promise = require('bluebird');
const ROUTERDIR = '/home/www/.router'; //hardcoded because this is being run as root
const SAVEFILE = ROUTERDIR + "/save.json";
//Check that ~/.router and savefile exist
require('mkdirp')(require('path').dirname(SAVEFILE), function(err){
if(err){
console.error('Unable to access savefile: mkdirp error');
process.exit(1);
}else try{
fs.closeSync(fs.openSync(SAVEFILE, 'a'));
fs.accessSync(SAVEFILE, fs.R_OK | fs.W_OK);
}catch(e){
console.error('Unable to access savefile: ' + e);
process.exit(1);
}
});
var sslDefault = {
port: 9443,
key: ROUTERDIR + "/certs/default.key",
cert: ROUTERDIR + "/certs/default.crt",
ca: [ROUTERDIR + "/certs/default.ca"]
};
if(!checkSSL(sslDefault)){
console.error("inaccessible default SSL config");
process.exit(1);
}
var proxy = require('redbird')({
port: 9080,
ssl: sslDefault,
bunyan: false
});
var express = require('express');
var app = express();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
app.use(bodyParser.json());
function checkSSL(obj, cb){
if(!cb) cb = console.error;
if(typeof obj.key !== "string" || typeof obj.cert !== "string"){
cb("key and cert paths must be valid strings!");
return false;
}
else try{
fs.accessSync(obj.key, fs.R_OK);
fs.accessSync(obj.cert, fs.R_OK);
if(typeof obj.ca === "undefined")
cb("WARNING: Certificate has no CAs associated with it.");
else{
if(typeof obj.ca === "string")
obj.ca = [obj.ca];
if(typeof obj.ca !== "object"){
cb("CA variable type is wrong");
return false;
}
for(var i = 0; i < obj.ca.length; i++)
fs.accessSync(obj.ca[i], fs.R_OK);
}
}catch(e){
cb(e);
return false;
}
return true;
}
function exportJSON(){
var routes = {};
Object.keys(proxy.routing).forEach(function(route){
for(var i = 0; i < proxy.routing[route].length; i++)
for(var j = 0; j < proxy.routing[route][i].urls.length; j++)
routes[route] = proxy.routing[route][i].urls[j].port;
});
return routes;
}
function importJSON(routes){
for(var route in routes)
if(routes.hasOwnProperty(route)
&& /^[a-zA-Z0-9\.\-]+$/.test(route) //Test it against the same regexes as /register
&& /^[0-9]+$/.test(routes[route]))
proxy.register(route, 'http://localhost:' + routes[route]);
}
//save() will log stuff.
//save(cb) will callback on success or failure.
//save(error, success) will callback error on failure, success on success.
function save(error, success){
if(typeof error !== "function" && typeof success !== "function"){ error = console.error; success = console.log; }
else if(typeof error === "function" && typeof success !== "function"){ success = error; }
var str = JSON.stringify(exportJSON());
fs.writeFile(SAVEFILE, str, function(err){
if(err) error('save: writefile error: ' + err);
else success('Saved: ' + str);
});
}
function load(){
return new Promise((res,rej) => {
fs.readFile(SAVEFILE, function(err, data){
var obj;
if(err){
rej('load: readfile error: ' + err);
return;
}else try{
obj = JSON.parse(data);
importJSON(obj);
}catch(e){
rej('load: JSON parse error');
return;
}
res(obj);
});
});
}
app.get(['/', '/export'], function(req, res){
res.send(JSON.stringify(exportJSON(), null, 2));
});
app.post('/import', function(req, res){
//`curl -H "Content-Type: application/json" --data @FILEPATH localhost:10000/import`
importJSON(req.body);
save(function(r){res.write(r);}, function(){
res.send('Imported.');
});
});
app.get('/save', function(req, res){
save(res.send);
});
app.get('/load', function(req, res){
save(res.send);
});
app.get(/^\/register\/([a-zA-Z0-9\.\-]+)\/([0-9]+)/, function(req, res){
proxy.unregister(req.params[0]);
proxy.register(req.params[0], 'http://localhost:' + req.params[1]);
save(function(r){res.write(r);}, function(){
res.send('Registered: http://' + req.params[0] + ' => ' + 'http://localhost:' + req.params[1] + '\r\n');
});
});
app.post(/^\/register\/([a-zA-Z0-9\.\-]+)\/([0-9]+)/, function(req, res){
if(typeof req.body !== "object" || Object.keys(req.body).length === 0){
proxy.unregister(req.params[0]);
proxy.register(req.params[0], 'http://localhost:' + req.params[1], { ssl: true });
}else if(!checkSSL(req.body)){
res.send('Failure: provided SSL key or cert not accessible\r\n');
return;
}else{
proxy.unregister(req.params[0]);
proxy.register(req.params[0], 'http://localhost:' + req.params[1], {
ssl: {
key: req.body.key,
cert: req.body.cert,
ca: req.body.ca
}
});
}
save(function(r){res.write(r);}, function(){
res.send('Registered: https://' + req.params[0] + ' => ' + 'http://localhost:' + req.params[1] + '\r\n');
});
});
app.get(/^\/unregister\/([a-zA-Z0-9\.\-]+)/, function(req, res){
proxy.unregister(req.params[0]);
save(function(r){res.write(r);}, function(){
res.send('Unregistered: ' + req.params[0] + '\r\n');
});
});
app.get(/^\/register\/([a-zA-Z0-9\.\-]+)/, function(req, res){
var portfinder = require('portfinder');
portfinder.getPort(function(err, port){
if(err)
res.send(500, 'Failed to find an open port for ' + req.params[0]);
else{
proxy.unregister(req.params[0]);
proxy.register(req.params[0], 'http://localhost:' + port);
save(function(r){res.write(r);}, function(){
res.send("" + port);
});
}
});
});
app.get(/^\/https\/([a-zA-Z0-9\-]+)/, function(req, res){
let rr = CF.DNSRecord.create({
zone_id: process.env.CF_ZONE,
type: 'CNAME',
name: req.params[0],
content: 'clive.io',
proxied: true
});
client.addDNS(rr).then(function(){
res.send(200, 'Successfully registered ');
});;
});
http.on('listening', function(){
console.log('listening on %s:%s', http.address().address, http.address().port);
});
load().then(console.log).catch(console.error); //Initial load
http.listen(PORT, '127.0.0.1'); //and start the server