forked from Freeboard/thingproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
204 lines (165 loc) · 4.32 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
var http = require('http');
var config = require("./config");
var url = require("url");
var request = require("request");
var throttle = require("tokenthrottle")({rate: config.max_requests_per_second});
var publicAddressFinder = require("public-address");
var publicIP;
// Get our public IP address
publicAddressFinder(function(err, data){
if(!err && data)
{
publicIP = data.address;
}
});
function addCORSHeaders(req, res)
{
if (req.method.toUpperCase() === "OPTIONS")
{
if(req.headers["access-control-request-headers"])
{
res.setHeader("Access-Control-Allow-Headers", req.headers["access-control-request-headers"]);
}
if(req.headers["access-control-request-method"])
{
res.setHeader("Access-Control-Allow-Methods", req.headers["access-control-request-method"]);
}
}
if(req.headers["origin"])
{
res.setHeader("Access-Control-Allow-Origin", req.headers["origin"]);
}
else
{
res.setHeader("Access-Control-Allow-Origin", "*");
}
}
function writeResponse(res, httpCode, body) {
res.statusCode = httpCode;
res.end(body);
}
function sendInvalidURLResponse(res) {
return writeResponse(res, 404, "url must be in the form of /fetch/{some_url_here}");
}
function sendTooBigResponse(res) {
return writeResponse(res, 413, "the content in the request or response cannot exceed " + config.max_request_length + " characters.");
}
function getClientAddress(req) {
return (req.headers['x-forwarded-for'] || '').split(',')[0]
|| req.connection.remoteAddress;
}
function processRequest(req, res)
{
addCORSHeaders(req, res);
// Return options pre-flight requests right away
if (req.method.toUpperCase() === "OPTIONS")
{
return writeResponse(res, 204);
}
var result = config.fetch_regex.exec(req.url);
if (result && result.length == 2 && result[1]) {
var remoteURL;
try {
remoteURL = url.parse(decodeURI(result[1]));
}
catch (e) {
return sendInvalidURLResponse(res);
}
// We don't support relative links
if(!remoteURL.host)
{
return writeResponse(res, 404, "relative URLS are not supported");
}
// Naughty, naughty— deny requests to blacklisted hosts
if(config.blacklist_hostname_regex.test(remoteURL.hostname))
{
return writeResponse(res, 400, "naughty, naughty...");
}
// We only support http and https
if (remoteURL.protocol != "http:" && remoteURL.protocol !== "https:") {
return writeResponse(res, 400, "only http and https are supported");
}
if(publicIP)
{
// Add an X-Forwarded-For header
if(req.headers["x-forwarded-for"])
{
req.headers["x-forwarded-for"] += ", " + publicIP;
}
else
{
req.headers["x-forwarded-for"] = req.clientIP + ", " + publicIP;
}
}
//Set host header to remote host
req.headers["host"] = remoteURL.host;
var proxyRequest = request({
url: remoteURL,
headers: req.headers,
method: req.method,
timeout: config.proxy_request_timeout_ms,
strictSSL : false
});
proxyRequest.on('error', function(err){
if(err.code === "ENOTFOUND")
{
return writeResponse(res, 502, "host cannot be found.")
}
else
{
console.log("Proxy Request Error: " + err.toString());
return writeResponse(res, 500);
}
});
var requestSize = 0;
var proxyResponseSize = 0;
req.pipe(proxyRequest).on('data', function(data){
requestSize += data.length;
if(requestSize >= config.max_request_length)
{
proxyRequest.end();
return sendTooBigResponse(res);
}
});
proxyRequest.pipe(res).on('data', function (data) {
proxyResponseSize += data.length;
if(proxyResponseSize >= config.max_request_length)
{
proxyRequest.end();
return sendTooBigResponse(res);
}
});
}
else {
return sendInvalidURLResponse(res);
}
}
http.createServer(function (req, res) {
// Process AWS health checks
if(req.url === "/health")
{
return writeResponse(res, 200);
}
var clientIP = getClientAddress(req);
req.clientIP = clientIP;
// Log our request
if(config.enable_logging)
{
console.log("%s %s %s", (new Date()).toJSON(), clientIP, req.method, req.url);
}
if(config.enable_rate_limiting)
{
throttle.rateLimit(clientIP, function(err, limited) {
if (limited)
{
return writeResponse(res, 429, "enhance your calm");
}
processRequest(req, res);
})
}
else
{
processRequest(req, res);
}
}).listen(config.port);
console.log("thingproxy.freeboard.io started");