-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.mjs
4302 lines (3481 loc) · 159 KB
/
index.mjs
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
// express und http Module importieren. Sie sind dazu da, die HTML-Dateien
// aus dem Ordner "public" zu veröffentlichen.
console.clear();
import { createRequire } from "module";
const require = createRequire(import.meta.url)
var express = require('express');
export var app = express();
export var https = require('https');
export var http = require('http');
export const fs = require("fs");
import fse from 'fs-extra'; // Use fs-extra for easy directory copying
export const path = require('path');
export const mysql = require("mysql2/promise")
export const sanitizeHtml = require("sanitize-html")
export const bcrypt = require('bcrypt');
// Depending on the SSL setting, this will switch.
// Localhost Implementation
export var server; // = require('http').createServer(app)
var FormData = require('form-data');
export const fetch = require('node-fetch')
const getSize = require('get-folder-size');
import { fileTypeFromBuffer } from 'file-type';
export var XMLHttpRequest = require('xhr2');
export const colors = require('colors');
export var request = require('request');
export var xssFilters = require('xss-filters');
const crypto = require('crypto');
var checkedMediaCacheUrls = {};
export var usersocket = []
export var loginAttempts = [];
var userOldRoom = {}
var peopleInVC = {}
var showedOfflineMessage = [];
export var powVerifiedUsers = [];
var typingMembers = [];
var typingMembersTimeout = [];
export var ratelimit = [];
var socketToIP = [];
export var allowLogging = false;
export var debugmode = false;
export var versionCode = 401;
// config file saving
let fileHandle = null; // File handle for the config file
let savedState = null; // In-memory config state
let writeQueue = Promise.resolve(); // Queue for write operations
let isClosing = false; // Flag to prevent multiple close attempts
// PoW difficulty
let powDifficulty = 7;
// check if needed directories are setup
checkServerDirectories()
// check if config file exists
checkConfigFile()
/*
Holy Server config file.
needs to be above the imports else serverconfig will be undefined
*/
export var serverconfig = JSON.parse(fs.readFileSync("./config.json", { encoding: "utf-8" }));
initConfig("./config.json");
checkConfigAdditions();
// Import functions etc from files (= better organisation)
// Special thanks to Kannustin <3
// Main functions for chat
import {
checkVersionUpdate,
checkConfigAdditions,
handleTerminalCommands,
validateMemberId,
checkRateLimit,
limitString,
generateId,
escapeHtml,
addMinutesToDate,
searchTenor,
sendMessageToUser,
tenorCallback_search,
httpGetAsync,
sanitizeInput,
copyObject,
sanitizeFilename,
checkMemberBan,
hashPassword,
getCastingMemberObject,
findAndVerifyUser,
checkMemberMute
} from "./modules/functions/main.mjs"
// IO related functions
import {
checkConfigFile,
checkServerDirectories,
consolas,
getSavedChatMessage,
saveChatMessage
} from "./modules/functions/io.mjs"
import { checkSSL } from "./modules/functions/http.mjs"
// Chat functions
import {
checkUserChannelPermission,
hasPermission,
getChannelTree,
resolveGroupByChannelId,
muteUser,
resolveCategoryByChannelId,
banUser,
resolveChannelById,
resolveRolesByUserId,
getMemberLastOnlineTime,
getMemberProfile,
getMemberList,
getGroupList,
banIp,
unbanIp,
getNewDate,
formatDateTime,
findInJson
} from "./modules/functions/chat/main.mjs";
import {
getMemberHighestRole,
convertMention,
findEmojiByID,
getUserBadges
} from "./modules/functions/chat/helper.mjs";
import {
getMediaUrlFromCache,
cacheMediaUrl,
checkMediaTypeAsync,
isURL,
deleteChatMessagesFromDb,
getChatMessagesFromDb,
decodeFromBase64,
leaveAllRooms
} from "./modules/functions/mysql/helper.mjs"
import {
checkAndCreateTable,
queryDatabase
} from "./modules/functions/mysql/mysql.mjs";
import { fileURLToPath, pathToFileURL } from "url";
import { channel } from "diagnostics_channel";
/*
Internally used files
*/
// Directory where handler files are located
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const mainHandlersDir = path.join(__dirname, 'modules/sockets');
// Function to dynamically load and register socket event handlers
const registerSocketEvents = async (socket) => {
const files = fs.readdirSync(mainHandlersDir);
for (const file of files) {
if (file.endsWith('.mjs')) {
const filePath = path.join(mainHandlersDir, file);
const fileUrl = pathToFileURL(filePath).href;
const { default: handler } = await import(fileUrl);
handler(socket);
}
}
};
/*
Files for the plugin system
*/
// Directories where plugin files are located
const pluginsDir = path.join(__dirname, 'plugins');
const publicPluginsDir = path.join(__dirname, 'public', 'plugins');
// Function to dynamically load and register socket event handlers
const registerPluginSocketEvents = async (socket, pluginSocketsDir) => {
const files = fs.readdirSync(pluginSocketsDir);
for (const file of files) {
if (file.endsWith('.mjs')) {
const filePath = path.join(pluginSocketsDir, file);
const fileUrl = pathToFileURL(filePath).href;
const { default: handler } = await import(fileUrl);
handler(socket);
}
}
};
// Function to dynamically load and execute plugin functions
const loadAndExecutePluginFunctions = async (pluginFunctionsDir) => {
const files = fs.readdirSync(pluginFunctionsDir);
for (const file of files) {
if (file.endsWith('.mjs')) {
const filePath = path.join(pluginFunctionsDir, file);
const fileUrl = pathToFileURL(filePath).href;
const module = await import(fileUrl);
// Iterate over all exports in the module
for (const [name, func] of Object.entries(module)) {
// Check if the export is a function and its name includes 'onLoad'
if (typeof func === 'function' && name.includes('onLoad')) {
func();
}
}
}
}
};
// Function to move web folders to the public directory
const moveWebFolders = async (pluginWebDir, pluginName) => {
const destinationDir = path.join(publicPluginsDir, pluginName);
await fse.ensureDir(destinationDir); // Ensure the destination directory exists
await fse.copy(pluginWebDir, destinationDir, { overwrite: true });
};
// Iterate over each plugin and process it
const processPlugins = async () => {
const pluginDirs = fs.readdirSync(pluginsDir);
for (const pluginName of pluginDirs) {
const pluginDir = path.join(pluginsDir, pluginName);
const pluginFunctionsDir = path.join(pluginDir, 'functions');
const pluginSocketsDir = path.join(pluginDir, 'sockets');
const pluginWebDir = path.join(pluginDir, 'web');
// Load and execute plugin functions
if (fs.existsSync(pluginFunctionsDir)) {
await loadAndExecutePluginFunctions(pluginFunctionsDir);
}
// Register socket events
if (fs.existsSync(pluginSocketsDir)) {
io.on('connection', (socket) => {
registerPluginSocketEvents(socket, pluginSocketsDir).catch(err => console.error(err));
});
}
// Move web folders to the public directory
if (fs.existsSync(pluginWebDir)) {
await moveWebFolders(pluginWebDir, pluginName);
}
consolas(colors.yellow(`Loaded plugin ${colors.white(pluginName)}`))
}
};
// Check if new version is available
checkVersionUpdate();
// Create a connection pool if sql is enabled
export let pool = null;
if (serverconfig.serverinfo.sql.enabled == true) {
pool = mysql.createPool({
host: serverconfig.serverinfo.sql.host,
user: serverconfig.serverinfo.sql.username,
password: serverconfig.serverinfo.sql.password,
database: serverconfig.serverinfo.sql.database,
waitForConnections: true,
connectionLimit: serverconfig.serverinfo.sql.connectionLimit,
queueLimit: 0
});
// SQL Database Structure needed
// it will create everything if missing (except database)
// +1 convenience
const tables = [
{
name: 'messages',
columns: [
{ name: 'authorId', type: 'varchar(100) NOT NULL' },
{ name: 'messageId', type: 'varchar(100) NOT NULL' },
{ name: 'room', type: 'text NOT NULL' },
{ name: 'message', type: 'longtext NOT NULL' }
],
keys: [
{ name: 'UNIQUE KEY', type: 'messageId (messageId)' }
]
},
{
name: 'url_cache',
columns: [
{ name: 'id', type: 'int(11) NOT NULL' },
{ name: 'url', type: 'longtext NOT NULL' },
{ name: 'media_type', type: 'text NOT NULL' }
],
keys: [
{ name: 'PRIMARY KEY', type: '(id)' },
{ name: 'UNIQUE KEY', type: 'id (id)' },
{ name: 'UNIQUE KEY', type: 'url (url) USING HASH' }
],
autoIncrement: 'id int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=55'
}
];
(async () => {
for (const table of tables) {
await checkAndCreateTable(table);
}
})();
}
consolas(" ",);
consolas(" ",);
consolas(" ",);
consolas(" ",);
consolas(colors.brightGreen(`Welcome to DCTS`));
consolas(colors.brightGreen(`Checkout our subreddit at https://www.reddit.com/r/dcts/hot/`));
consolas(" ");
consolas(colors.cyan(`You're running version ` + versionCode));
// Check if new Version exists
var checkVer = await checkVersionUpdate()
if (checkVer != null) {
consolas(colors.cyan.underline(`New version ${checkVer} is available!`));
consolas(colors.cyan(`Download: https://github.com/hackthedev/dcts-shipping/releases`));
}
consolas(" ");
consolas(" ");
// Check if SSL is used or not
checkSSL();
// Catch uncaught errors
process.on('uncaughtException', function (err) {
// Handle the error safely
consolas("");
consolas("");
consolas("UNEXPECTED ERROR".red);
consolas(" ");
consolas(colors.red(err.message));
console.log(" ");
console.log("Details: ".red);
console.log(colors.grey(err).italic);
// Log Error To File
var date = new Date().toLocaleString();
date = date.replace(", ", "_");
date = date.replaceAll(":", "-");
date = date.replaceAll(".", "-");
// Create the log file
fs.writeFile("./logs/error_" + date + ".txt", err.message + "\n" + err.stack, function (err) {
if (err) {
return console.log(err);
}
consolas("The log file ".cyan + colors.white("./logs/error_" + date + ".txt") + " was saved!".cyan, "Debug");
});
// Create the config backup file
fs.writeFile("./config_backups/config_" + date + ".txt", JSON.stringify(serverconfig, false, 4), function (err) {
if (err) {
return console.log(err);
}
consolas("The config file ".cyan + colors.white("./logs/error_" + date + ".txt") + " was saved!".cyan, "Debug");
});
})
// Ability to enter "commands" into the terminal window
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (text) {
var data = text.trim();
var args = data.split(" ");
var command = args[0];
handleTerminalCommands(command, args);
});
// Setup socket.io
export var io = require('socket.io')(server, {
maxHttpBufferSize: 1e8,
secure: true
});
// Star the app server
var port = process.env.PORT || serverconfig.serverinfo.port;
server.listen(port, function () {
// Wir geben einen Hinweis aus, dass der Webserer läuft.
consolas(colors.brightGreen('Server is running on port ' + port));
if (serverconfig.serverinfo.setup == 0) {
var adminToken = generateId(64);
serverconfig.serverinfo.setup = 1;
serverconfig.serverroles["1111"].token.push(adminToken);
saveConfig(serverconfig);
consolas(colors.brightGreen(`To obtain the admin role in your server, copy the following token.`));
consolas(colors.brightGreen(`You can use it if prompted or if you right click on the server icon and press "Redeem Key"`));
consolas(colors.brightGreen(` `));
consolas(colors.brightGreen(`Server Admin Token:`));
consolas(colors.brightGreen(adminToken));
consolas(colors.brightGreen(` `));
consolas(colors.brightGreen(` `));
}
else if (serverconfig.serverroles["1111"].token.length > 0) {
consolas(colors.brightGreen(` `));
consolas(colors.brightGreen(` `));
consolas(colors.brightGreen(`Welcome to DCTS`));
consolas(colors.brightGreen(`To obtain the admin role in your server, copy the following token.`));
consolas(colors.brightGreen(`You can use it if prompted or if you right click on the server icon and press "Redeem Key"`));
consolas(colors.brightGreen(` `));
consolas(colors.cyan(`Available Server Admin Token(s):`));
serverconfig.serverroles["1111"].token.forEach(token => {
consolas(colors.cyan(token))
})
consolas(colors.brightGreen(` `));
consolas(colors.brightGreen(` `));
allowLogging = true;
}
});
app.use(express.urlencoded({ extended: true })); // Parses URL-encoded data
app.use(express.json()); // Parses JSON bodies
// stupid bs
/*
app.get('*', (req, res) => {
const { group, category, channel } = req.query;
// Determine the file path
let filePath = path.join(__dirname, 'public', req.path);
// Default to index.html for the root path or requests without extensions
if (req.path === '/' || path.extname(req.path) === '') {
filePath = path.join(__dirname, 'public', 'index.html');
}
// Check if the request is for the main HTML template
if (filePath.endsWith('index.html')) {
// Proceed only if at least one query parameter is present
if (!group && !category && !channel) {
console.log("No relevant query parameters found. Ignoring request.");
}
// Define placeholders and their replacements
const placeholders = [
["meta.page.title", () => getMetaTitle(group, category, channel)],
["category", () => category || "No Category Provided"],
["channel", () => channel || "No Channel Provided"],
];
// Template rendering function
function renderTemplate(template) {
return template.replace(/{{\s*([^{}\s]+)\s*}}/g, (match, key) => {
const placeholder = placeholders.find(([name]) => name === key);
return placeholder ? placeholder[1]() : ""; // Replace with function result or empty string
});
}
// Read and render the index.html template
return fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error("Error reading file:", err.message);
return res.status(404).send('File not found');
}
const renderedContent = renderTemplate(data);
res.send(renderedContent);
});
}
// Serve other static files (CSS, JS, images, etc.)
fs.readFile(filePath, (err, data) => {
if (err) {
console.error("Error serving file:", err.message);
return res.status(404).send('File not found');
}
// Set the appropriate content type based on file extension
const ext = path.extname(filePath).toLowerCase();
const mimeTypes = {
// Text files
'.html': 'text/html',
'.css': 'text/css',
'.js': 'application/javascript',
'.json': 'application/json',
'.xml': 'application/xml',
'.csv': 'text/csv',
// Image files
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.webp': 'image/webp',
'.ico': 'image/x-icon',
// Font files
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.otf': 'font/otf',
'.eot': 'application/vnd.ms-fontobject',
// Audio files
'.mp3': 'audio/mpeg',
'.wav': 'audio/wav',
'.ogg': 'audio/ogg',
'.m4a': 'audio/mp4',
// Video files
'.mp4': 'video/mp4',
'.mkv': 'video/x-matroska',
'.webm': 'video/webm',
'.avi': 'video/x-msvideo',
'.mov': 'video/quicktime',
// Document files
'.pdf': 'application/pdf',
'.doc': 'application/msword',
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'.ppt': 'application/vnd.ms-powerpoint',
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'.xls': 'application/vnd.ms-excel',
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
// Archive files
'.zip': 'application/zip',
'.rar': 'application/vnd.rar',
'.7z': 'application/x-7z-compressed',
'.tar': 'application/x-tar',
'.gz': 'application/gzip',
// Other
'.txt': 'text/plain',
'.md': 'text/markdown',
'.yaml': 'text/yaml',
'.yml': 'text/yaml',
'.bin': 'application/octet-stream',
};
const contentType = mimeTypes[ext] || 'application/octet-stream';
res.setHeader('Content-Type', contentType);
res.send(data);
});
});
function getMetaTitle(groupId, categoryId, channelId){
if(groupId && categoryId && channelId){
return `Chat in #${serverconfig.groups[groupId].channels.categories[categoryId].channel[channelId].name}`
}
}
*/
app.use(express.static(__dirname + '/public'));
// Process plugins at server start
processPlugins().catch(err => console.error(err));
// === Ab hier folgt der Code für den Chat-Server
// Hier sagen wir Socket.io, dass wir informiert werden wollen,
// wenn sich etwas bei den Verbindungen ("connections") zu
// den Browsern tut.
io.on('connection', function (socket) {
// Register internal socket event handlers
registerSocketEvents(socket).catch(err => console.error(err));
// For now to ignore proof of work
powVerifiedUsers.push(socket.id);
// Check if user ip is blacklisted
var ip = socket.handshake.address;
socketToIP[socket] = ip;
if (serverconfig.ipblacklist.hasOwnProperty(ip)) {
if(Date.now() <= serverconfig.ipblacklist[ip]){
let detailText = "";
let banListResult = findInJson(serverconfig.banlist, "ip", ip);
if(banListResult != null){
console.log(banListResult)
let bannedUntilDate = new Date(banListResult.until);
bannedUntilDate.getFullYear() == "9999" ? detailText = "permanently banned" : detailText = `banned until: <br>${formatDateTime(bannedUntilDate)}`
detailText += banListResult?.reason !== null ? `<br><br>Reason:<br>${banListResult.reason}` : ""
}
sendMessageToUser(socket.id, JSON.parse(
`{
"title": "IP Blacklisted ${ip}",
"message": "Your IP Address was ${detailText || "banned"}",
"buttons": {
"0": {
"text": "Ok",
"events": "onclick='closeModal()'"
}
},
"type": "error",
"displayTime": 60000
}`));
socket.disconnect();
consolas("Disconnected user because ip is blacklisted", "Debug");
}
else if(Date.now() > serverconfig.ipblacklist[ip]){
unbanIp(socket);
}
}
// Send a PoW challenge to the client
socket.on('requestPow', () => {
const challenge = crypto.randomBytes(16).toString('hex');
socket.emit('powChallenge', { challenge, difficulty: powDifficulty });
});
// Verify the PoW solution
socket.on('verifyPow', ({ challenge, solution }) => {
if (isValidProof(challenge, solution)) {
if (!powVerifiedUsers.includes(socket.id)) {
powVerifiedUsers.push(socket.id);
}
console.log('Client authenticated');
socket.emit('authSuccess', { message: 'Authenticated' });
} else {
console.log('Client failed to authenticate');
socket.emit('authFailure', { message: 'Failed to authenticate' });
}
});
function isValidProof(challenge, solution) {
const hash = crypto.createHash('sha256').update(challenge + solution).digest('hex');
return hash.substring(0, powDifficulty) === Array(powDifficulty + 1).join('0');
}
function getDateDayDifference(timestamp1, timestamp2, mode = null) {
var difference = timestamp1 - timestamp2;
var daysDifference = Math.round(difference / 1000 / 60 / 60 / 24);
return daysDifference;
}
// WebRTC tests
socket.on('join', (roomId) => {
socket.join(roomId);
socket.to(roomId).emit('user-connected', socket.id);
socket.on('disconnect', () => {
if (powVerifiedUsers.includes(socket.id)) {
powVerifiedUsers.pop(socket.id);
}
socket.to(roomId).emit('user-disconnected', socket.id);
});
socket.on('leave', (roomId) => {
socket.leave(roomId);
socket.to(roomId).emit('user-disconnected', socket.id);
});
socket.on('offer', (data) => {
io.to(data.target).emit('offer', {
sender: socket.id,
offer: data.offer
});
});
socket.on('answer', (data) => {
io.to(data.target).emit('answer', {
sender: socket.id,
answer: data.answer
});
});
socket.on('candidate', (data) => {
io.to(data.target).emit('candidate', {
sender: socket.id,
candidate: data.candidate
});
});
socket.on('audio', (data) => {
socket.to(roomId).emit('audio', data);
});
});
socket.on('userConnected', async function (member, response) {
member.id = xssFilters.inHTMLData(member.id)
member.name = xssFilters.inHTMLData(member.name)
member.loginName = xssFilters.inHTMLData(member.loginName)
member.status = xssFilters.inHTMLData(member.status)
member.aboutme = xssFilters.inHTMLData(member.aboutme)
member.icon = xssFilters.inHTMLData(member.icon)
member.banner = xssFilters.inHTMLData(member.banner)
member.token = xssFilters.inHTMLData(member.token)
member.onboarding = xssFilters.inHTMLData(member.onboarding) === "true";
member.password = xssFilters.inHTMLData(member.password) || null;
member.group = xssFilters.inHTMLData(member.group);
member.category = xssFilters.inHTMLData(member.category);
member.channel = xssFilters.inHTMLData(member.channel);
member.room = xssFilters.inHTMLData(member.room);
//var ip = socket.handshake.headers["x-real-ip"];
//var port = socket.handshake.headers["x-real-port"];
// check member ban
let banResult = checkMemberBan(socket, member);
let banText = "";
if(banResult?.timestamp){
if(new Date(banResult.timestamp).getFullYear() == "9999"){
banText = "banned permanently";
}
else{
banText = `banned until <br>${formatDateTime(new Date(banResult.timestamp))}`
}
}
if(banResult?.reason){
banText += `<br><br>Reason:<br>${banResult.reason}`
}
if(banResult.result == true){
response({ error: `You've been ${banText}`, type: "error", msg: `You've been ${banText}`, msgDisplayDuration: 1000 * 60})
socket.disconnect();
return;
}
// call checkMemberMute so it unmutes automatically
checkMemberMute(socket, member);
consolas(`Member connected. User: ${member.name} (${member.id} - ${socketToIP[socket]})`, "Debug");
// Check if member is in default role
if (serverconfig.serverroles["0"].members.includes(member.id) == false) {
serverconfig.serverroles["0"].members.push(member.id);
saveConfig(serverconfig);
}
if (member.id.length == 12 && isNaN(member.id) == false) {
usersocket[member.id] = socket.id;
// if new member
if (serverconfig.servermembers[member.id] == null) {
// New Member joined the server
// handle onboarding
if (member.onboarding === false) {
// cant proceed as the user needs to setup their account with a password
io.to(socket.id).emit("doAccountOnboarding");
response({
error: "Onboarding not completed",
finishedOnboarding: false,
msg: "Welcome!",
text: "Finish your account setup to continue",
type: "success"
})
return;
}
var userToken = generateId(48);
// setup member
serverconfig.servermembers[member.id] = JSON.parse(
`{
"id": ${member.id},
"token": "${userToken}",
"loginName": "${member.loginName}",
"name": "${member.name}",
"nickname": null,
"status": "${member.status}",
"aboutme": "${member.aboutme}",
"icon": "${member.icon}",
"banner": "${member.banner}",
"joined": ${new Date().getTime()},
"isOnline": 1,
"lastOnline": ${new Date().getTime()},
"isBanned": 0,
"isMuted": 0,
"password": "${await hashPassword(member.password)}"
}
`);
saveConfig(serverconfig);
try {
sendMessageToUser(socket.id, JSON.parse(
`{
"title": "Welcome ${serverconfig.servermembers[member.id].name} <3",
"message": "",
"buttons": {
"0": {
"text": "Saved!",
"events": "refreshValues()"
}
},
"action": "register",
"token": "${serverconfig.servermembers[member.id].token}",
"icon": "${serverconfig.servermembers[member.id].icon}",
"banner": "${serverconfig.servermembers[member.id].banner}",
"status": "${serverconfig.servermembers[member.id].status}",
"aboutme": "${serverconfig.servermembers[member.id].aboutme}",
"type": "success"
}`));
}
catch (e) {
consolas("Error on token message sending".red, "Debug");
consolas(e, "Debug");
}
// create copy of server member without token
var castingMember = copyObject(serverconfig.servermembers[member.id]);
delete castingMember.token;
delete castingMember.password;
// Save system message to the default channel
castingMember.group = resolveGroupByChannelId(serverconfig.serverinfo.defaultChannel);
castingMember.category = resolveCategoryByChannelId(serverconfig.serverinfo.defaultChannel);
castingMember.channel = serverconfig.serverinfo.defaultChannel;
castingMember.room = `${resolveGroupByChannelId(serverconfig.serverinfo.defaultChannel)}-${resolveCategoryByChannelId(serverconfig.serverinfo.defaultChannel)}-${serverconfig.serverinfo.defaultChannel}`;
castingMember.timestamp = new Date().getTime();
castingMember.messageId = generateId(12);
castingMember.isSystemMsg = true;
castingMember.message = `${member.name} joined the server!</label>`;
saveChatMessage(castingMember);
io.emit("updateMemberList");
// Save System Message and emit join event
io.emit("newMemberJoined", castingMember);
response({ finishedOnboarding: true })
}
else {
if (member.token == null || member.token.length != 48 ||
serverconfig.servermembers[member.id].token == null ||
serverconfig.servermembers[member.id].token != member.token) {
try {
response({ error: "Invalid login", title: "Invalid Login", msg: "Something went wrong with your login.<br><a onclick='resetAccount();'>Reset Session</a><br>", type: "error", displayTime: 1000*60*60 })
return;
}
catch (e) {
consolas("Error on error message sending".red, "Debug");
consolas(e, "Debug");
}
consolas("User did not have a valid token.", "Debug");
response({ error: "Invalid Token", finishedOnboarding: true })
socket.disconnect();
return;
}
usersocket[member.id] = socket.id;
serverconfig.servermembers[member.id].name = escapeHtml(member.name);
serverconfig.servermembers[member.id].status = escapeHtml(member.status);
serverconfig.servermembers[member.id].aboutme = escapeHtml(member.aboutme);
serverconfig.servermembers[member.id].icon = escapeHtml(member.icon);
serverconfig.servermembers[member.id].banner = escapeHtml(member.banner);
serverconfig.servermembers[member.id].lastOnline = new Date().getTime();
saveConfig(serverconfig);
if (serverconfig.servermembers[member.id].isOnline == 0) {
// Member is back online
serverconfig.servermembers[member.id].isOnline = 1;
var lastOnline = serverconfig.servermembers[member.id].lastOnline / 1000;
var today = new Date().getTime() / 1000;
var diff = today - lastOnline;
var minutesPassed = Math.round(diff / 60);
if (minutesPassed > 5) {
io.emit("updateMemberList");
io.emit("memberOnline", member);
}
}
else {
io.emit("updateMemberList");
io.emit("memberPresent", member);
}
response({ finishedOnboarding: true })
}
}
else {
socket.disconnect();
consolas("ID WAS WRONG ON USER JOIN ".red + member.id, "Debug");
}
});
socket.on('userLogin', function (member, response) {
member.id = xssFilters.inHTMLData(member.id)
member.password = xssFilters.inHTMLData(member.password)
member.name = xssFilters.inHTMLData(member.name)
member.duration = 0.1;
// Handling ip ban
var ip = socket.handshake.address;
if(serverconfig.ipblacklist.hasOwnProperty(ip)){
// if the ban has expired, unban them
if (Date.now() > serverconfig.ipblacklist[ip]) {
unbanIp(socket)
}
}
// initiate login counter
if(!loginAttempts.hasOwnProperty(ip)){
loginAttempts.push(ip);
loginAttempts[ip] = 0;
}
// increase login counter
loginAttempts[ip]++;
// if count exceeded, temporarily ban ip and clean up
if(loginAttempts[ip] > serverconfig.serverinfo.login.maxLoginAttempts){
banIp(socket, getNewDate(serverconfig.serverinfo.moderation.bans.ipBanDuration).getTime());
delete loginAttempts[ip];
response({ error: "You've been temporarily banned. Please try again later" })
socket.disconnect();
return;
}
console.log(loginAttempts[ip]);