-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
292 lines (244 loc) · 7.53 KB
/
index.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
const fs = require('fs');
const express = require('express');
const proxy = require('express-http-proxy');
const serveIndex = require('serve-index');
const micromatch = require('micromatch');
const parseUrl = require('parseurl');
const HOST_TYPE =
{
static: 1,
proxy: 2,
alias: 3,
redirect: 4
};
const CONFIG_FILE = './config.json';
const LOG_PATH = './logs/';
const LOG_FILES_AMOUNT = 14;
let hosts = {};
let hostKeys = [];
let config = {};
// ******************** logging ********************
function pad(input, amount=2, fill='0')
{
return (input+'').padStart(amount, fill);
}
function log(type, message)
{
let date = new Date();
date = date.getFullYear() + '-' + pad(date.getMonth()+1) + '-' + pad(date.getDate()) + ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds());
message = date + ': ' + message + '\n';
process.stdout.write(message);
fs.appendFile(LOG_PATH + type + '.log',message, 'utf8', (error) =>
{
if (error)
console.error(error)
});
}
const logging =
{
sys: (message) => { log('sys', message) },
error: (message) => { log('error', message) },
access: (message) => { log('access', message) },
}
function logRotate()
{
logging.sys("rotating logs..");
for(let logType in logging)
{
for(let i=LOG_FILES_AMOUNT-1;i>=0;--i)
{
let oldFilePath = LOG_PATH + logType + (i>0 ? pad(i) : '') + '.log'
let newFilePath = LOG_PATH + logType + pad(i+1) + '.log' ;
//if it's the last file -> delete it
if (i == LOG_FILES_AMOUNT)
{
if (fs.existsSync(newFilePath))
fs.unlinkSync(newFilePath)
}
//move
if (fs.existsSync(oldFilePath))
fs.renameSync(oldFilePath, newFilePath)
}
}
}
setTimeout(logRotate, 1000 * 60 * 60 * 24);
// ******************** helpers ********************
function loadJSONfromFile(file)
{
try
{
return JSON.parse(fs.readFileSync(file));
}
catch(error)
{
console.error(error);
return null;
}
}
function resolveHost(host, depth=1, maxDepth=5)
{
if (depth >= maxDepth)
return null;
if (host.target in hosts)
{
if (hosts[host.target].type == HOST_TYPE.alias)
return resolveHost(hosts[host.target], ++depth, maxDepth);
else
return hosts[host.target];
}
return null;
}
function loadConfig(json)
{
conf = json;
// config
hosts = {};
conf.hosts.forEach(host =>
{
if (host.type == 'proxy')
host.type = HOST_TYPE.proxy;
else if (host.type == 'alias')
host.type = HOST_TYPE.alias;
else if (host.type == 'redirect')
host.type = HOST_TYPE.redirect;
else
host.type = HOST_TYPE.static;
hosts[host.domain] = host;
});
for(let hostKey in hosts)
{
if (hosts[hostKey].type == HOST_TYPE.alias)
{
let resolvedHost = resolveHost(hosts[hostKey]);
if (resolvedHost)
{
logging.sys(hosts[hostKey].domain + ' alias resolved to ' + resolvedHost.domain)
hosts[hostKey] = resolvedHost;
}
}
else
logging.sys(hosts[hostKey].domain + ' listening on port ' + conf.port + '...');
}
hostKeys = Object.keys(hosts);
logging.sys('domains: '+hostKeys);
return conf;
}
function isFiltered(req, filter)
{
let path = parseUrl(req).pathname;
let shouldBeFiltered = false;
if (filter && filter.length > 0)
shouldBeFiltered = micromatch.isMatch(path, filter);
return shouldBeFiltered;
}
// ******************** load config ********************
logging.sys('start... ');
config = loadConfig(loadJSONfromFile(CONFIG_FILE));
if (config.watchConfig)
{
fs.watchFile(CONFIG_FILE, (curr, prev) =>
{
logging.sys('reloading config...');
logging.sys('listening on '+config.port);
let json = loadJSONfromFile(CONFIG_FILE);
if (!json)
logging.error('can not reload json - parse error')
else
config = loadConfig(json);
});
}
logging.sys('listening on ' + config.port + '...');
// ******************** listen ********************
express().use((req, res, next) =>
{
//apply header
res.setHeader('x-powered-by', 'Expressy');
let hostname = req.hostname || '';
let url = req.originalUrl || '';
logging.access('[' + req.connection.remoteAddress + '] ' + '[' + req.method + '] ' + req.protocol + '://' + hostname + url);
//check host
let host = hosts[hostname] || null;
if (!host)
{
//go through all domains
for(let domain in hosts)
{
if (micromatch.isMatch(hostname, domain))
{
host = hosts[domain];
break;
}
}
}
if (!host)
return res.status(404).send('not found');
if (host.type == HOST_TYPE.alias)
return res.status(500).send('alias cannot be resolved');
// ******************** basic auth
if (host.basicAuth)
{
if (!req.headers["authorization"])
{
res.set('WWW-Authenticate', 'Basic realm="' + host.domain + '", charset="UTF-8"');
return res.status(401).send('access denied');
}
else
{
let loginAllowed = false;
try
{
// parse login and password from headers
const b64auth = (req.headers.authorization || '').split(' ')[1] || '';
const [login, password] = Buffer.from(b64auth, 'base64').toString().split(':');
if (login && password && login in host.basicAuth && password === host.basicAuth[login].password)
loginAllowed = true;
}
catch(e)
{
console.log(error);
}
if (!loginAllowed)
{
res.set('WWW-Authenticate', 'Basic realm="' + host.domain + '", charset="UTF-8"');
return res.status(401).send('access denied');
}
}
}
// ******************** static
if (host.type == HOST_TYPE.static && !host.index)
{
if (isFiltered(req,host.filter))
return res.status(404).send('not found');
else
return express.static(host.target, { dotfiles: 'deny' })(req, res, next);
}
// ******************** static with index
else if (host.type == HOST_TYPE.static && host.index)
{
return serveIndex(host.target, {'icons': true, 'view': 'details'})(req, res, () =>
{
if (isFiltered(req,host.filter))
return res.status(404).send('not found');
else
return express.static(host.target, { dotfiles: 'deny' })(req, res, next);
});
}
// ******************** proxy
else if (host.type == HOST_TYPE.proxy)
{
return proxy(host.target,
{
proxyReqOptDecorator: (proxyReqOpts, srcReq) =>
{
let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
proxyReqOpts.headers['x-forwarded-for'] = ip;
return proxyReqOpts;
}
})(req, res, next);
}
// ******************** redirect
else if (host.type == HOST_TYPE.redirect)
return res.redirect(host.target);
// ******************** error
return res.status(500).send('server error');
}).listen(config.port);