-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1211 lines (605 loc) · 23.7 KB
/
server.js
File metadata and controls
1211 lines (605 loc) · 23.7 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
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Core Modules
import readline from "readline";
import fs from "fs";
import crypto from "crypto";
import { EventEmitter } from "events";
import path from "path";
import { workerData, Worker, isMainThread, parentPort } from "worker_threads";
// Third party Modules
import { config } from "dotenv";
config({path: "./.config.env"});
import os from "os";
import QRcode from "qrcode";
import DeviceDetector from "node-device-detector";
// Local Modules
import {app, express} from "./app.js";
import FilesRouter from "./Routes/FilesRoute.js";
import configRouter from "./Routes/configRoute.js";
import fileOperationsRouter from "./Routes/fileOperationsRoute.js"
///////////////////////////
// Inheriting from the events module
class MyEvents extends EventEmitter {
constructor () {
super ();
}
}
export const Emitter = new MyEvents();
Emitter.setMaxListeners(Infinity);
let clientId = 0;
// For decryption
function decryptData(data, key, iv) {
const cipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
let decryptedText = cipher.update(data.toString(), "hex", "utf-8");
decryptedText += cipher.final("utf-8");
return decryptedText;
}
// Gets the authentication file
let authenticationFile;
try {
authenticationFile = fs.readFileSync("./Assets/authentication.html");
} catch (err) {
console.error("\nAuthentication File not found. Make sure the 'authentication.html' is in the 'Assets' folder and type in 'rs' to restart the server.");
process.exit(0)
}
// Gets the confirmation file
let confirmationFile;
try {
confirmationFile = fs.readFileSync("./Assets/confirmationFile.html");
} catch (err) {
console.error("\nAn HTML File was not found. Make sure the 'confirmationFile.html' is in the 'Assets' folder and type in 'rs' to restart the server.");
process.exit(0)
}
//. Configuration file
let configFile;
try {
configFile = fs.readFileSync("./Assets/config.html");
} catch (err) {
console.error("\nConfiguration File not found. Make sure the 'config.html' is in the 'Assets' folder and type in 'rs' to restart the server.");
process.exit(0)
}
export let PORT;
export let netInt = "";
export let domainName = "";
export let rootDir = "";
let serverText = "";
// Variable for checking if server is configured properly
let configVal = true;
// Creates a readline interface
const details = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Custom error handler
const errHandler = (req,res,next) => {
throw new Error();
next(err);
}
// Error handling middleware
const errHandlerMiddleware = (err,req,res,next) => {
return res.status(404).send(`<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="The Godfather">
<title>File Server</title>
</head>
<body>
<span style="color: red;font-size: 1.2rem;"><b>Please enter a valid url!</b></span>
</body>
</html>`)
}
// Event handler for the "second" event
Emitter.on("second", () => {
// Check if a default directory was set
try {
const defaultInt = decryptData(atob(process.env.NETINTERFACE.toString()), Buffer.from(process.env.NETINTERFACEENCRYPTIONKEY, "hex"), Buffer.from(process.env.NETINTERFACEINITIALIZATIONVECTOR, "hex"));
if(!defaultInt || (defaultInt.toString().trim() == "none")) {
askForInterface();
} else {
const proxyNetInt = parseInt(defaultInt.toString());
if(proxyNetInt == 1) {
// Gets the ip address
const {wlan0} = os.networkInterfaces();
if(!wlan0) {
console.log(`\n> Please Connect to a Wi-fi network to use your default network interface.`);
netInt = "localhost";
console.log(`Your network interface is "${netInt}".`);
} else {
netInt = "WLAN";
console.log(`\n> Your default network interface "${netInt}" is been used. Leave the network interface input in the configuration file blank if you don't want to use `);
}
} else if(proxyNetInt == 2) {
netInt = "localhost";
console.log(`\n> Your default network interface "${netInt}" is been used. Leave the network interface input in the configuration file blank if you don't want to use `);
} else {
netInt = "localhost";
console.log(`\n> Your default network interface "${netInt}" is been used. Leave the network interface input in the configuration file blank if you don't want to use `);
}
if(netInt == "localhost") {
domainName = "127.0.0.1";
} else if(netInt == "WLAN") {
domainName = os.networkInterfaces().wlan0[1].address;
}
Emitter.emit("third");
}
} catch (err) {
askForInterface();
}
})
// Event handler for the "third" event
Emitter.on("third", async () => {
try {
const defaultDir = decryptData(atob(process.env.ROOTDIRECTORY.toString()), Buffer.from(process.env.ROOTDIRECTORYENCRYPTIONKEY, "hex"), Buffer.from(process.env.ROOTDIRECTORYINITIALIZATIONVECTOR, "hex"));
let dirExists = fs.existsSync(`${defaultDir}`);
if(!dirExists) {
throw new Error ("Not Found");
}
if(!defaultDir || (defaultDir.toString().trim() == "")) {
askForDirectory();
} else {
rootDir = defaultDir;
console.log(`\n> Your default root directory "${rootDir}" is being used. Leave the root directory input in the configuration file blank if you don't want to use it.\n`)
details.close("temporary");
startServer();
}
} catch (err) {
if(err.message == "Not Found") {
console.log('\n> The root directory you provided in the configuration file does not exist.\n');
}
askForDirectory();
}
})
// Validates the input port number
function checkPort(port) {
const portNum = parseInt(port);
if((portNum < 1024) || (portNum > 65535) || (portNum.toString() == "NaN")) {
console.log(`\n${port} is not a valid port number.`)
return 6543;
} else {
return portNum;
}
}
// Validates the input network interface
function checkInterface(int) {
const netInt = parseInt(int);
if(netInt == 1) {
// Gets the ip address
const {wlan0} = os.networkInterfaces();
if(!wlan0) {
console.log(`\nPlease Connect to a Wi-fi network to use this interface.`);
return "localhost";
}
return "WLAN";
} else if(netInt == 2) {
return "localhost";
} else {
return "localhost";
}
}
// Asks the user for the port number
function askForPort() {
details.question(`\nWhat Port number do you want your server to run in:\nPort number must be between "1024" and "65535" - `, port => {
// assigns the answer to the PORT variable
PORT = checkPort(port);
// sets the configVal to false
configVal = false;
console.log(`\n> Your port number is ${PORT}`)
Emitter.emit("second");
})
}
// Asks the user for the network interface
function askForInterface() {
details.question(`\nThe Network Interface:\n(1) WLAN - You can view your files from other devices that are connected to the same Wi-fi network.\n(2) Localhost - You can only view your files in this device.\nChoose "1" or "2".\n`, int => {
// assigns the answer to the netInt variable
netInt = checkInterface(int);
// sets the configVal to false
configVal = false;
// assigns the domainName variable
if(netInt == "localhost") {
domainName = "127.0.0.1";
} else if(netInt == "WLAN") {
domainName = os.networkInterfaces().wlan0[1].address;
}
console.log(`\n> Your network interface is "${netInt}".`);
Emitter.emit("third");
})
}
// Asks the user for the root directory
function askForDirectory() {
details.question("\nThe root directory:\nAll the files and folders inside this directory will be accessible - \n", (dir) => {
// assigns the rootDir variable to the answer
rootDir = dir;
// sets the configVal to false
configVal = false;
console.log(`\n> Your root directory is "${dir}"`);
// Closes the readline interface
details.close()
});
}
// Check if a default port number was set
try {
const defaultPort = decryptData(atob(process.env.PORT), Buffer.from(process.env.PORTENCRYPTIONKEY, "hex"), Buffer.from(process.env.PORTINITIALIZATIONVECTOR, "hex"));
if(!defaultPort || (defaultPort.toString().trim() == "")) {
askForPort();
} else {
PORT = parseInt(defaultPort);
console.log(`\n> Your default Port number "${PORT}" is being used. Leave the Port number input in the configuration file blank if you don't want to use it.`)
Emitter.emit("second");
}
} catch (err) {
askForPort();
}
// Checks if a password is set for authentication
try {
app.locals.password = decryptData(atob(process.env.CONNECTIONPASSWORD.toString()), Buffer.from(process.env.CONNECTIONPASSWORDENCRYPTIONKEY, "hex"), Buffer.from(process.env.CONNECTIONPASSWORDINITIALIZATIONVECTOR, "hex"));
} catch (err) {
app.locals.password = "";
}
// For the authentication
authenticationFile = authenticationFile.toString(). replace("{{%URL%}}", `http://${domainName}:${PORT}/login`).replace("{{%SERVERNAME%}}", `${app.locals.serverName}`).replace("{{%EVENTURL%}}", `http://${domainName}:${PORT}/confirmConnection`).replace("{{%ICON%}}", `http://${domainName}:${PORT}/Icon.png`).replaceAll("{{DETAILSURL}}", `http://${domainName}:${PORT}/details`);
// For the confirmation
confirmationFile = confirmationFile.toString().replaceAll("{{%URLPREFIX%}}", `http://${domainName}:${PORT}`).replace("{{%ICON%}}", `"http://${domainName}:${PORT}/Icon.png"`).replaceAll("{{DETAILSURL}}", `http://${domainName}:${PORT}/details`);
// Event handler for the interface close event
details.on("close", (val) => {
if(val == "temporary") {
return;
} else {
// Middleware for Configuration file
app.use("/config", configRouter);
// Middleware for denied list
app.use((req,res,next) => {
let clientIp = req.ip || req.socket.remoteAddress;
if(!req.app.locals.confirmConnection && (req.app.locals.confirmConnection.toString() != "")) {
next();
} else if(req.app.locals.deniedList.has(clientIp)) {
return res.status(403).send(`<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="The Godfather">
<title>File Server</title>
</head>
<body>
<span><b style="color: red; font-size: 1.2rem;"> You were denied access to the server.</b></span>
</body>
</html>`)
} else {
next();
}
})
// middleware for connection limit
app.use((req,res, next) => {
let clientIp = req.ip || req.socket.remoteAddress;
if (req.app.locals.connectionLimit && (req.app.locals.connectionLimit.toString() != "")) {
if(clientIp.toString() == domainName.toString()) {
next();
} else if (parseInt(req.app.locals.connectionList.size) == parseInt(req.app.locals.connectionLimit) ) {
if(req.app.locals.connectionList.has(clientIp)) {
next();
} else {
return res.status(429).send(`<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="The Godfather">
<title>File Server</title>
</head>
<body>
<span style="color:red;font-size: 1.2rem;"><b> You are unable to connect as the maximum number of connections has been reached. </b></span>
</body>
</html>`);
}
} else {
next();
}
} else {
next();
}
});
// Middleware for authentication
app.use((req,res,next) => {
let clientIp = req.ip || req.socket.remoteAddress;
if (req.app.locals.whiteList.has(clientIp)) {
next();
} else if(req.app.locals.password && (req.app.locals.password.toString() != "")) {
if (domainName.toString() == req.ip.toString()) {
authenticationFile = authenticationFile.toString().replace("{{%OWNER%}}", true).replaceAll("{{%URLPREFIX%}}", `http://${domainName}:${PORT}`);
} else {
authenticationFile = authenticationFile.toString().replace("{{%OWNER%}}", false);
}
return res.status(511).send(`${authenticationFile}`);
} else {
next();
}
});
// Middleware for confirmation
app.use((req,res,next) => {
let clientIp = req.ip || req.socket.remoteAddress;
if(req.app.locals.confirmedList.has(clientIp)) {
next();
} else if (req.ip.toString() == domainName.toString()) {
req.app.locals.confirmedList.add(clientIp);
next();
} else if(req.app.locals.confirmConnection && (req.app.locals.confirmConnection.toString() != "")) {
res.send(`${confirmationFile}`);
} else {
next();
}
})
// Adds the ip address to the connection list
app.use((req,res,next) => {
let clientIp = req.ip || req.socket.remoteAddress;
let userAgent = req.get("user-agent");
if (clientIp.toString() === domainName.toString()) {
req.app.locals.ownerConnected = true;
} else if(!(req.app.locals.connectionList.has(clientIp))) {
Emitter.emit("newip", userAgent, clientIp);
}
req.app.locals.connectionList.add(clientIp);
next();
})
// Handles file operations
app.use("/fileOperations", fileOperationsRouter);
// checks for invalid characters
app.use((req,res,next) => {
let url = req.url.toString();
try {
url = decodeURIComponent(req.url).toString().replace("/files/", "");
} catch (err) {
let path = url.split("/");
let invalidCharacters = path.map(el => {
let invalidCharacter = el.toString().match(/\%[^\dABCDEFabcdef]+/);
if(invalidCharacter) {
let index = invalidCharacter.index;
let otherPath = el.slice(0, index);
let wrongCharacter = el.slice(index);
let encodedCharacter = encodeURIComponent(wrongCharacter);
return `${otherPath}${encodedCharacter}`;
} else {
return el;
}
})
req.url = invalidCharacters.join("/");
}
next();
})
// Handle all files
app.use("/files/", express.static(`${rootDir}`, {index:false, dotfiles: "allow"}));
// Handle the folders
app.use("/", FilesRouter);
// Custom error middleware
app.use(errHandler)
// Error handling middleware
app.use(errHandlerMiddleware)
// Starts the server and listen for requests
let server = app.listen(PORT, `${domainName}`, (err) => {
if(err) {
console.log(`\nServer Error: ${err}.\nType in "rs" to restart the server.`)
process.exit(0);
}
if(domainName == "127.0.0.1") {
serverText = `Enter the address below to a web browser on this device to access your files. You can also scan the qrcode below to see the url.`
} else {
serverText = `Enter the address below to a web browser on any device on the same network to access your files. You can also scan the qrcode below to see the url.`
}
console.log(`\n${serverText}`);
console.log(`\nURL - `, `http://${domainName}:${PORT}/files/\n`);
if(configVal == false) {
console.warn(`It's advisable you configure your server appropriately for better experience and also for security reasons. Click on the icon at the bottom right corner of the web pages to view the configuration file or enter the url below in a browser.\n\nConfig URL - http://${domainName}:${2005}/config\n`)
}
const options = {
type: "terminal",
errorCorrectionLevel: "l",
}
QRcode.toString(`http://${domainName}:${PORT}/files/`, options, (err, url) => {
if(err) {
}
console.log("\n")
console.log(url);
})
})
server.on("error", () => {
if(domainName == "127.0.0.1") {
console.log(`\n> Your server has been disconnected because an unknown error occurred.\nType in "rs" to restart your server and view your files.\n`);
process.exit(0);
} else {
console.log(`\n> Your server has been disconnected because the Wi-fi connection was switched off.\nConnect to a Wi-fi connection and type in "rs" to restart your server and view your files.\n`);
process.exit(0)
}
return;
})
}
})
Emitter.on("newip", (ag, ip) => {
if(isMainThread) {
let filePath = path.join(process.env.PWD, "Workers/connectionWorker.js");
const worker = new Worker(`${filePath}`, {
workerData: {userAgent: ag, ip}
});
worker.on("message", (data) => {
let deviceName = `${data.device.brand} ${data.device.model}`;
if(deviceName.trim() == "") {
deviceName = "Not Detected"
}
let clientText = `\n(${clientId + 1}) A new device connected to your server\n Device Name: ${deviceName}\n Ip Address: ${ip}\n`;
console.log("\x1b[32m", `${clientText}`, "\x1b[0m")
})
worker.on("error", (err) => {
return;
})
worker.on("exit", () => {
return;
})
}
})
// Function called after the third event
function startServer() {
// Middleware for Configuration file
app.use("/config", configRouter);
// Middleware for denied list
app.use((req,res,next) => {
let clientIp = req.ip || req.socket.remoteAddress;
if(!req.app.locals.confirmConnection && (req.app.locals.confirmConnection.toString() != "")) {
next();
} else if(req.app.locals.deniedList.has(clientIp)) {
return res.status(403).send(`<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="The Godfather">
<title>File Server</title>
</head>
<body>
<span><b style="color: red; font-size: 1.2rem;"> You were denied access to the server.</b></span>
</body>
</html>`)
} else {
next();
}
})
// middleware for connection limit
app.use((req,res, next) => {
let clientIp = req.ip || req.socket.remoteAddress;
if (req.app.locals.connectionLimit && (req.app.locals.connectionLimit.toString() != "")) {
if(clientIp.toString() == domainName.toString()) {
next();
} else if (parseInt(req.app.locals.connectionList.size) == parseInt(req.app.locals.connectionLimit) ) {
if(req.app.locals.connectionList.has(clientIp)) {
next();
} else {
return res.status(429).send(`<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="The Godfather">
<title>File Server</title>
</head>
<body>
<span style="color:red;font-size: 1.2rem;"><b> You are unable to connect as the maximum number of connections has been reached. </b></span>
</body>
</html>`);
}
} else {
next();
}
} else {
next();
}
});
// Middleware for authentication
app.use((req,res,next) => {
let clientIp = req.ip || req.socket.remoteAddress;
if (req.app.locals.whiteList.has(clientIp)) {
next();
} else if(req.app.locals.password && (req.app.locals.password.toString() != "")) {
if (domainName.toString() == req.ip.toString()) {
authenticationFile = authenticationFile.toString().replace("{{%OWNER%}}", true).replaceAll("{{%URLPREFIX%}}", `http://${domainName}:${PORT}`);
} else {
authenticationFile = authenticationFile.toString().replace("{{%OWNER%}}", false);
}
return res.status(511).send(`${authenticationFile}`);
} else {
next();
}