This repository has been archived by the owner on Apr 1, 2023. It is now read-only.
forked from HandyOSS/HandyHost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
357 lines (332 loc) · 11.3 KB
/
app.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import http from 'http';
import https from 'https';
import url from 'url';
import path from 'path';
import fs from 'fs';
import {APIHelper} from './api.js';
import {spawn} from 'child_process';
import {CommonUtils} from './CommonUtils.js';
const api = new APIHelper();
const utils = new CommonUtils();
const port = process.env.HANDYHOST_PORT || 8008;
const httpsPort = process.env.HANDYHOST_SSL_PORT || 58008;
let badAttempts = 0;
let lastBadAttempt = Math.floor(new Date().getTime()/1000);
let lastBadAttemptTimeout;
if(!fs.existsSync(process.env.HOME+'/.HandyHost/handyhost_server.key')){
//generate certs
//utils.getIPForDisplay().then(ipData=>{
const args = [
'req',
'-x509',
'-out',
process.env.HOME+'/.HandyHost/handyhost_server.crt',
'-keyout',
process.env.HOME+'/.HandyHost/handyhost_server.key',
'-newkey',
'rsa:2048',
'-nodes',
'-sha256',
'-extensions',
'EXT',
'-subj',
'/CN=HandyHost',
'-config',
'handyhost_server.cnf'
];
const gencert = spawn('openssl',args)
gencert.on('close',()=>{
startHttpsServer();
})
//});
}
else{
//start ssl server
startHttpsServer();
}
utils.initKeystore();
utils.initJWTKey();
const httpServer = http.createServer(function(request, response) {
handleServerRequest(request,response);
}).listen(parseInt(port, 10));
api.initSocketConnection(httpServer,'http');
function startHttpsServer(){
const options = {
key: fs.readFileSync(process.env.HOME+'/.HandyHost/handyhost_server.key'),
cert: fs.readFileSync(process.env.HOME+'/.HandyHost/handyhost_server.crt')
};
const httpsServer = https.createServer(options,function(request, response) {
handleServerRequest(request,response);
}).listen(parseInt(httpsPort, 10));
api.initSocketConnection(httpsServer,'https');
}
var get_cookies = function(request) {
var cookies = {};
request.headers && request.headers.cookie.split(';').forEach(function(cookie) {
var parts = cookie.match(/(.*?)=(.*)$/)
cookies[ parts[1].trim() ] = (parts[2] || '').trim();
});
return cookies;
};
function handleServerRequest(request,response){
let authTokenCookies = {};
try{
authTokenCookies = get_cookies(request);
}
catch(e){
//console.log('error with cookies',e);
}
const authToken = typeof authTokenCookies['handyhostToken'] == "undefined" ? "bust" : authTokenCookies['handyhostToken'];
const unsafe = url.parse(request.url).pathname;
const safe = path.normalize(unsafe).replace(/^(\.\.(\/|\\|$))+/, '');
//ok check if we enabled auth for the server
const isAuthEnabled = utils.isAuthEnabled();
let isAuthValid = true;
if(isAuthEnabled){
//and if we did, is our token valid
isAuthValid = utils.checkAuthToken(authToken);
}
if(isAuthValid){
if(safe.indexOf('/api/login') == 0){
//document.cookie and fetch cookie are out of fn sync for whatever reason, let them know for a bump
response.setHeader('Set-Cookie', ["handyhostToken="+authToken]);
response.write('{"success":true,"token":"'+authToken+'"}');
response.end();
badAttempts = 0;
return;
}
//proceed
let filename = path.resolve()+'/client'+safe;
const contentTypesByExtension = {
//whitelist things here
'.html': "text/html",
'.css': "text/css",
'.js': "text/javascript",
'.png': "image/png",
'.svg': 'image/svg+xml',
'.mjs': 'text/javascript',
'.ttf': 'font/ttf'
};
fs.exists(filename, function(exists) {
if(!exists) {
//might be a request for us to get some data, lets see here..
let body = "";
request.on('data', function (chunk) {
body += chunk;
});
request.on('end', function () {
api.get(safe,body).then(data=>{
if(typeof data == 'string'){
response.end(data);
}
else{
response.end(JSON.stringify(data));
}
}).catch(err=>{
response.writeHead(404, {"Content-Type": "text/plain"});
let out = '{}';
try{
out = JSON.stringify(err);
}
catch(e){
out = JSON.stringify({error:err});
}
response.write(out);
response.end();
});
});
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
const headers = {};
const contentType = contentTypesByExtension[path.extname(filename)];
if (contentType) headers["Content-Type"] = contentType;
response.writeHead(200, headers);
response.write(file, "binary");
response.end();
});
});
}
else{
//no valid auth token and auth is valid
const now = Math.floor(new Date().getTime()/1000);
if( (now - lastBadAttempt > 60) || badAttempts >= 6){
badAttempts = 0;
}
console.log('bad login attempts',badAttempts, 'seconds since last attempt', now - lastBadAttempt,safe);
if(badAttempts >= 5){
if(typeof lastBadAttemptTimeout != "undefined"){
clearTimeout(lastBadAttemptTimeout);
}
}
lastBadAttemptTimeout = setTimeout(()=>{
if(safe.indexOf('/api') == 0){
//first check if this is a login or change password
if(safe.indexOf('/api/login') == 0 || safe.indexOf('/api/passwordreset') == 0){
//do login
let body = "";
request.on('data', function (chunk) {
body += chunk;
});
request.on('end', function () {
let creds = {};
try{
creds = JSON.parse(body);
}
catch(e){
console.log('eror parsing creds',e);
}
if(safe.indexOf('/api/passwordreset') == 0){
//its a reset or init
utils.changeAuth(creds.newpw,creds.oldpw).then(wasSuccessful=>{
console.log('password was reset successful',wasSuccessful);
if(wasSuccessful){
//respond
utils.bumpToken().then(token=>{
response.setHeader('Set-Cookie', ["handyhostToken="+token]);
response.write('{"success":true,"token":"'+token+'"}');
response.end();
badAttempts = 0;
return;
})
}
else{
//fail
response.writeHead(401, {"Content-Type": "application/json"});
response.write('{"success":false,"message":"incorrect password"}');
response.end();
}
})
}
else{
//its login
utils.checkAuth(creds.pw).then(wasSuccessful=>{
if(wasSuccessful){
//respond
utils.bumpToken().then(token=>{
response.setHeader('Set-Cookie', ["handyhostToken="+token]);
response.write('{"success":true,"token":"'+token+'"}');
response.end();
badAttempts = 0;
return;
})
}
else{
//fail
response.writeHead(401, {"Content-Type": "application/json"});
response.write('{"success":false,"message":"incorrect password"}');
response.end();
}
})
}
});
}
else if(safe.indexOf('/api/akt/getRandomHostname') == 0){
const token = safe.split('/')[5];
if(typeof token == "undefined"){
console.log('token is undefined')
response.writeHead(401, {"Content-Type": "text/plain"});
response.write("unauthorized\n");
response.end();
return;
}
else{
const localAuthToken = fs.readFileSync(process.env.HOME+'/.HandyHost/aktData/usbAuthToken','utf8').trim();
if(localAuthToken == token.trim()){
//ok the usb for ubuntu auto installer is valid, pass them thru
api.get(safe,'').then(data=>{
if(typeof data == 'string'){
response.end(data);
}
else{
response.end(JSON.stringify(data));
}
}).catch(err=>{
response.writeHead(404, {"Content-Type": "text/plain"});
let out = '{}';
try{
out = JSON.stringify(err);
}
catch(e){
out = JSON.stringify({error:err});
}
response.write(out);
response.end();
});
}
}
}
else{
response.writeHead(401, {"Content-Type": "text/plain"});
response.write("unauthorized\n");
response.end();
return;
}
//is an api request, throw a 401
}
else{
fs.readFile(path.resolve()+'/client/login.html', "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
const headers = {};
const isNew = utils.hasDefaultAuth();
if(isNew){
file = file.replace(/__FORMMODE__/gi,'new');
}
else{
file = file.replace(/__FORMMODE__/gi,'login')
}
const contentType = 'text/html';
if (contentType) headers["Content-Type"] = contentType;
response.writeHead(200, headers);
response.write(file, "binary");
response.end();
});
}
},2500 * badAttempts);
lastBadAttempt = now;
badAttempts += 1;
}
}
//console.log("NOTIFICATION: HandyHost Running at: http://localhost:" + port + "/\n");
utils.getIPForDisplay().then(data=>{
if(process.platform == 'darwin'){
fs.writeFileSync(process.env.HOME+'/.HandyHost/handyhost.pid',process.pid.toString(),'utf8');
const startupLog = process.env.HOME+'/.HandyHost/startup.log';
fs.writeFileSync(startupLog,data.ip,'utf8');
}
console.log("HandyHost Daemon Running at: http://"+data.ip+":" + data.port + "/, and https://"+data.ip+":"+httpsPort+'/ (self-signed cert)');
})
process.on('uncaughtException', function(err) {
if(typeof err.code != "undefined"){
if(err.code.indexOf('EADDRINUSE') >= 0){
utils.getIPForDisplay().then(data=>{
if(process.platform == 'darwin'){
const startupLog = process.env.HOME+'/.HandyHost/startup.log';
fs.writeFileSync(startupLog,data.ip,'utf8');
}
console.log("HandyHost Daemon Already Running at: http://"+data.ip+":" + data.port + "/ and https://"+data.ip+":"+httpsPort+' (self-signed cert)');
process.exit(1);
})
}
else{
console.log('Caught exception: ' + err);
process.exit(1);
}
}
else{
console.log('Caught exception: ' + err);
process.exit(1);
}
});