-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathrunserver.js
2518 lines (2286 loc) · 71.7 KB
/
runserver.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
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
/*
** Our World of Text
** Est. May 1, 2016 as Your World of Text Node, and November 19, 2016 as Node World of Text
** Reprogrammed September 17, 2017
** Released October 8, 2017 as Our World of Text
*/
console.log("Starting up...");
const crypto = require("crypto");
const fs = require("fs");
const http = require("http");
const https = require("https");
const nodemailer = require("nodemailer");
const path = require("path");
const pg = require("pg");
const querystring = require("querystring");
const sql = require("sqlite3");
const url = require("url");
const util = require("util");
const WebSocket = require("ws");
const worker = require("node:worker_threads");
const zip = require("adm-zip");
const bin_packet = require("./backend/utils/bin_packet.js");
const utils = require("./backend/utils/utils.js");
const rate_limiter = require("./backend/utils/rate_limiter.js");
const ipaddress = require("./backend/framework/ipaddress.js");
const prompt = require("./backend/utils/prompt.js");
const restrictions = require("./backend/utils/restrictions.js");
const frameUtils = require("./backend/framework/utils.js");
const serverUtil = require("./backend/framework/server.js");
const templates = require("./backend/framework/templates.js");
var trimHTML = utils.trimHTML;
var create_date = utils.create_date;
var san_nbr = utils.san_nbr;
var san_dp = utils.san_dp;
var checkURLParam = utils.checkURLParam;
var removeLastSlash = utils.removeLastSlash;
var ar_str_trim = utils.ar_str_trim;
var ar_str_decodeURI = utils.ar_str_decodeURI;
var http_time = utils.http_time;
var encode_base64 = utils.encode_base64;
var decode_base64 = utils.decode_base64;
var process_error_arg = utils.process_error_arg;
var tile_coord = utils.tile_coord;
var calculateTimeDiff = utils.calculateTimeDiff;
var compareNoCase = utils.compareNoCase;
var resembles_int_number = utils.resembles_int_number;
var TerminalMessage = utils.TerminalMessage;
var encodeCharProt = utils.encodeCharProt;
var decodeCharProt = utils.decodeCharProt;
var change_char_in_array = utils.change_char_in_array;
var html_tag_esc = utils.html_tag_esc;
var dump_dir = utils.dump_dir;
var arrayIsEntirely = utils.arrayIsEntirely;
var normalizeCacheTile = utils.normalizeCacheTile;
var checkDuplicateCookie = utils.checkDuplicateCookie;
var advancedSplit = utils.advancedSplit;
var filterEdit = utils.filterEdit;
var toHex64 = utils.toHex64;
var toInt64 = utils.toInt64;
var parseCookie = frameUtils.parseCookie;
var normalize_ipv6 = ipaddress.normalize_ipv6;
var ipv4_to_int = ipaddress.ipv4_to_int;
var ipv6_to_int = ipaddress.ipv6_to_int;
var ipv4_to_range = ipaddress.ipv4_to_range;
var ipv6_to_range = ipaddress.ipv6_to_range;
var is_cf_ipv4_int = ipaddress.is_cf_ipv4_int;
var is_cf_ipv6_int = ipaddress.is_cf_ipv6_int;
var DATA_PATH = "../nwotdata/";
var SETTINGS_PATH = DATA_PATH + "settings.json";
function initializeDirectoryStruct() {
// create the data folder that stores all of the server's data
if(!fs.existsSync(DATA_PATH)) {
fs.mkdirSync(DATA_PATH, 0o777);
}
// initialize server configuration
if(!fs.existsSync(SETTINGS_PATH)) {
fs.writeFileSync(SETTINGS_PATH, fs.readFileSync("./settings_example.json"));
console.log("Created the settings file at [" + SETTINGS_PATH + "]. You must configure the settings file and then start the server back up again.");
console.log("Full path of settings: " + path.resolve(SETTINGS_PATH));
sendProcMsg("EXIT");
process.exit();
}
}
initializeDirectoryStruct();
const settings = require(SETTINGS_PATH);
var serverPort = settings.port;
var serverDBPath = settings.paths.database;
var editsDBPath = settings.paths.edits;
var chatDBPath = settings.paths.chat_history;
var imageDBPath = settings.paths.images;
var miscDBPath = settings.paths.misc;
var staticNumsPath = settings.paths.static_shortcuts;
var restrPath = settings.paths.restr;
var restrCg1Path = settings.paths.restr_cg1;
var accountSystem = settings.account_system; // "uvias" or "local"
var loginPath = "/accounts/login/";
var logoutPath = "/accounts/logout/";
var registerPath = "/accounts/register/";
var profilePath = "/accounts/profile/";
var sql_table_init = "./backend/default.sql";
var sql_indexes_init = "./backend/indexes.sql";
var sql_edits_init = "./backend/edits.sql";
var serverSettings = {
announcement: "",
chatGlobalEnabled: "1"
};
var serverSettingsStatus = {};
if(accountSystem != "uvias" && accountSystem != "local") {
console.log("ERROR: Invalid account system: " + accountSystem);
sendProcMsg("EXIT");
process.exit();
}
var shellEnabled = true;
var isTestServer = false;
var debugLogging = false;
var testUviasIds = false;
var serverLoaded = false;
var isStopping = false;
var closed_client_limit = 1000 * 60 * 20; // 20 min
var ws_req_per_second = 1000;
var pw_encryption = "sha512WithRSAEncryption";
var connections_per_ip = 50;
var static_path = "./frontend/static/";
var static_path_web = "static/";
var templates_path = "./frontend/templates/";
var httpServer;
var wss; // websocket handler
var uvias;
var monitorWorker;
var pgConn; // postgreSQL connection for Uvias
var intv = {}; // intervals and timeouts
var pluginMgr = null;
var serverStartTime = Date.now();
var transporter;
var email_available = true;
var prompt_stopped = false;
var db,
db_edits,
db_chat,
db_img,
db_misc;
// Global
CONST = {};
CONST.tileCols = 16;
CONST.tileRows = 8;
CONST.tileArea = CONST.tileCols * CONST.tileRows;
// tile cache for fetching and updating
// 3 levels: world_id -> tile_y -> tile_x
var memTileCache = {};
var clientVersion = "";
var ranks_cache = { users: {} };
var restr_cache = "";
var restr_cg1_cache = "";
var restr_update = null;
var restr_cg1_update = null;
var worldData = {};
var client_cursor_pos = {};
var client_ips = {};
var ip_address_conn_limit = {}; // {ip: count}
var ip_address_req_limit = {}; // {ip: ws_limits} // TODO: Cleanup objects
var staticShortcuts = {};
var template_data = {}; // data used by the server
var static_data = {}; // return static server files
console.log("Loaded libs");
function loadPlugin(reload) {
if(!reload) {
return pluginMgr;
}
try {
var pluginPath = DATA_PATH + "plugin.js";
if(!fs.existsSync(pluginPath)) {
pluginMgr = {};
return pluginMgr;
}
var modPath = require.resolve(pluginPath);
delete require.cache[modPath];
pluginMgr = require(pluginPath);
} catch(e) {
console.log("Plugin load error:", e);
pluginMgr = {};
}
return pluginMgr;
}
function loadShellFile() {
var file = null;
try {
file = fs.readFileSync(DATA_PATH + "shell.js");
} catch(e) {
file = null;
}
if(file) {
file = file.toString("utf8");
}
return file;
}
function getServerUptime() {
return Date.now() - serverStartTime;
}
function getClientVersion() {
return clientVersion;
}
function setClientVersion(ver) {
if(clientVersion === ver) return false;
if(ver) {
clientVersion = ver;
} else {
clientVersion = "";
}
return true;
}
function deployNewClientVersion() {
var staticVersion = getClientVersion();
if(staticVersion) {
staticVersion = "?v=" + staticVersion;
}
httpServer.setDefaultTemplateData("staticVersion", staticVersion);
}
function handle_error(e, doLog) {
var str = JSON.stringify(process_error_arg(e));
log_error(str);
if(isTestServer || doLog) {
console.log("Error:", str);
}
}
process.argv.forEach(function(a) {
if(a == "--test-server") {
if(!isTestServer) console.log("\x1b[31;1mThis is a test server\x1b[0m");
isTestServer = true;
}
if(a == "--log") {
if(!debugLogging) console.log("\x1b[31;1mDebug logging enabled\x1b[0m");
debugLogging = true;
}
if(a == "--uvias-test-info") {
testUviasIds = true;
}
if(a == "--lt") {
if(!isTestServer) console.log("\x1b[31;1mThis is a test server\x1b[0m");
isTestServer = true;
if(!debugLogging) console.log("\x1b[31;1mDebug logging enabled\x1b[0m");
debugLogging = true;
testUviasIds = true;
}
});
// only accessible through modifying shell.js in the data directory - no web interface ever used to enter commands
async function runShellScript(includeColors) {
var shellFile = loadShellFile();
if(shellFile == null) {
return "ERR: File does not exist";
}
var getFunc = null;
var shellCont = {};
try {
getFunc = eval("(function(shell) {\n" + shellFile + "\n})(shellCont);");
} catch(e) {
return "ERR: Load: \n" + util.inspect(e, { colors: includeColors });
}
var mainFunc = shellCont.main;
if(!mainFunc) {
return "ERR: main function not found";
}
var resp = "<No response>";
try {
resp = await mainFunc();
} catch(e) {
return "ERR: Run: \n" + util.inspect(e, { colors: includeColors });
}
if(typeof resp != "string" && typeof resp != "number" && typeof resp != "bigint") {
resp = util.inspect(resp, { colors: includeColors });
} else {
resp += "";
}
return resp;
}
function makePgClient() {
pgConn = new pg.Client({
connectionString: "pg://"
});
console.log("Postgres client connected");
pgConn.on("end", function() {
console.log("WARNING: Postgres client is closed");
if(isStopping) return;
setTimeout(uvias_init, 1000 * 2);
});
pgConn.on("error", function(err) {
console.log("ERROR: Postgres client received an error:");
console.log(err);
});
}
if(accountSystem == "uvias") {
pg.defaults.user = settings.pg_db.user || "owot";
pg.defaults.host = settings.pg_db.host || "/var/run/postgresql";
pg.defaults.database = settings.pg_db.database || "uvias";
pg.defaults.password = settings.pg_db.password;
if(settings.pg_db.port) {
pg.defaults.port = settings.pg_db.port;
}
}
class UviasClient {
stats = {
runningAll: 0,
runningGet: 0,
runningRun: 0
}
ranksCache = {};
id = null;
name = null;
domain = null;
private = null;
only_verified = null;
custom_css_file_path = null;
pid_bypass = false;
paths = {
sso: null,
logout: null,
address: null,
loginPath: null,
logoutPath: null,
registerPath: null,
profilePath: null
};
async all(query, data) {
if(data != void 0 && !Array.isArray(data)) data = [data];
this.stats.runningAll++;
var result = await pgConn.query(query, data);
this.stats.runningAll--;
return result.rows;
}
async get(query, data) {
if(data != void 0 && !Array.isArray(data)) data = [data];
this.stats.runningGet++;
var result = await pgConn.query(query, data);
this.stats.runningGet--;
return result.rows[0];
}
async run(query, data) {
if(data != void 0 && !Array.isArray(data)) data = [data];
this.stats.runningRun++;
await pgConn.query(query, data);
this.stats.runningRun--;
}
async loadRanks() {
this.ranksCache = {};
var data = await this.all("SELECT * FROM accounts.ranks");
for(var i = 0; i < data.length; i++) {
var rank = data[i];
var id = rank.id;
var name = rank.name;
this.ranksCache[name] = id;
}
}
getRankIdByName(name) {
return this.ranksCache[name];
}
}
function setupUvias() {
uvias = new UviasClient();
if(testUviasIds) {
uvias.id = "owottest";
uvias.name = "Our World Of Text Test Server";
uvias.domain = "test.ourworldoftext.com";
uvias.private = true;
uvias.only_verified = false;
uvias.custom_css_file_path = settings.paths.uvias_css;
} else {
uvias.id = "owot";
uvias.name = "Our World Of Text";
uvias.domain = "ourworldoftext.com";
uvias.private = false;
uvias.only_verified = false;
uvias.custom_css_file_path = settings.paths.uvias_css;
}
if(uvias.custom_css_file_path) {
uvias.custom_css_file_path = path.resolve(uvias.custom_css_file_path);
}
if(settings.uvias?.pid_bypass) {
uvias.pid_bypass = true;
}
uvias.paths.sso = "/accounts/sso";
// redirect to /accounts/logout/ to clear token cookie
uvias.paths.logout = "/accounts/logout/?return=" + "/home/";
uvias.paths.address = "https://uvias.com";
uvias.paths.loginPath = uvias.paths.address + "/api/loginto/" + uvias.id;
uvias.paths.logoutPath = uvias.paths.address + "/logoff?service=" + uvias.id;
uvias.paths.registerPath = uvias.paths.address + "/api/loginto/" + uvias.id + "#create";
uvias.paths.profilePath = uvias.paths.address + "/profile/@me";
if(accountSystem == "uvias") {
loginPath = uvias.paths.loginPath;
logoutPath = uvias.paths.logoutPath;
registerPath = uvias.paths.registerPath;
profilePath = uvias.paths.profilePath;
}
}
if(isTestServer) {
serverPort = settings.test_port;
Error.stackTraceLimit = 128;
}
function log_error(err) {
if(settings.error_log) {
try {
err = JSON.stringify(err);
err = "TIME: " + Date.now() + "\r\n" + err + "\r\n" + "-".repeat(20) + "\r\n\r\n\r\n";
fs.appendFileSync(settings.paths.log, err);
} catch(e) {
console.log("Error logging error:", e);
}
}
}
function setupStaticShortcuts() {
if(!staticNumsPath) return;
var data;
try {
data = fs.readFileSync(staticNumsPath);
} catch(e) {
// static shortcuts don't exist
return;
}
for(var i in staticShortcuts) {
delete staticShortcuts[i];
}
data = data.toString("utf8").replace(/\r\n/g, "\n").split("\n");
for(var i = 0; i < data.length; i++) {
var row = data[i].split("\t");
var num = row[0];
var path = row[1];
if(!num || !path) continue;
num = num.trim();
path = path.trim();
staticShortcuts[num] = path;
}
}
templates.registerFilter("plural", function(count, string) {
if(!string) return "";
if(count != 1) {
if(string.endsWith("s")) {
return string + "es";
} else if(string.endsWith("y")) {
return string.slice(0, -1) + "ies";
} else {
return string + "s";
}
}
return string;
});
function loadStatic() {
for(var i in template_data) {
delete template_data[i];
}
for(var i in static_data) {
delete static_data[i];
}
console.log("Loading static files...");
dump_dir(static_data, static_path, static_path_web, false, true);
console.log("Loading HTML templates...");
dump_dir(template_data, templates_path, "", false, true);
console.log("Compiling HTML templates...");
for(var i in template_data) {
template_data[i] = templates.compile(template_data[i]);
templates.addFile(i, template_data[i]);
}
}
function setupZipLog() {
var zip_file;
if(!fs.existsSync(settings.paths.zip_log)) {
zip_file = new zip();
} else {
zip_file = new zip(settings.paths.zip_log);
}
console.log("Handling previous error logs (if any)");
if(fs.existsSync(settings.paths.log)) {
var file = fs.readFileSync(settings.paths.log);
if(file.length > 0) {
var log_data = fs.readFileSync(settings.paths.log);
zip_file.addFile("NWOT_LOG_" + Date.now() + ".txt", log_data, "", 0o644);
fs.truncateSync(settings.paths.log);
}
}
zip_file.writeZip(settings.paths.zip_log);
}
console.log("Loading page files");
var pages = {
accounts: {
configure: require("./backend/pages/accounts/configure.js"),
download: require("./backend/pages/accounts/download.js"),
login: require("./backend/pages/accounts/login.js"),
logout: require("./backend/pages/accounts/logout.js"),
member_autocomplete: require("./backend/pages/accounts/member_autocomplete.js"),
nsfw: require("./backend/pages/accounts/nsfw.js"),
password_change: require("./backend/pages/accounts/password_change.js"),
password_change_done: require("./backend/pages/accounts/password_change_done.js"),
private: require("./backend/pages/accounts/private.js"),
profile: require("./backend/pages/accounts/profile.js"),
register: require("./backend/pages/accounts/register.js"),
register_complete: require("./backend/pages/accounts/register_complete.js"),
sso: require("./backend/pages/accounts/sso.js"),
tabular: require("./backend/pages/accounts/tabular.js"),
verify: require("./backend/pages/accounts/verify.js"),
verify_email: require("./backend/pages/accounts/verify_email.js")
},
admin: {
administrator: require("./backend/pages/admin/administrator.js"),
backgrounds: require("./backend/pages/admin/backgrounds.js"),
manage_ranks: require("./backend/pages/admin/manage_ranks.js"),
set_custom_rank: require("./backend/pages/admin/set_custom_rank.js"),
user: require("./backend/pages/admin/user.js"),
user_list: require("./backend/pages/admin/user_list.js"),
users_by_id: require("./backend/pages/admin/users_by_id.js"),
users_by_username: require("./backend/pages/admin/users_by_username.js"),
restrictions: require("./backend/pages/admin/restrictions.js"),
shell: require("./backend/pages/admin/shell.js")
},
other: {
ipaddress: require("./backend/pages/other/ipaddress.js"),
load_backgrounds: require("./backend/pages/other/load_backgrounds.js"),
random_color: require("./backend/pages/other/random_color.js"),
test: require("./backend/pages/other/test.js")
},
"404": require("./backend/pages/404.js"),
activate_complete: require("./backend/pages/activate_complete.js"),
coordlink: require("./backend/pages/coordlink.js"),
home: require("./backend/pages/home.js"),
protect: require("./backend/pages/protect.js"),
protect_char: require("./backend/pages/protect_char.js"),
register_failed: require("./backend/pages/register_failed.js"),
script_edit: require("./backend/pages/script_edit.js"),
script_manager: require("./backend/pages/script_manager.js"),
script_view: require("./backend/pages/script_view.js"),
static: require("./backend/pages/static.js"),
unprotect: require("./backend/pages/unprotect.js"),
unprotect_char: require("./backend/pages/unprotect_char.js"),
urllink: require("./backend/pages/urllink.js"),
world_props: require("./backend/pages/world_props.js"),
world_style: require("./backend/pages/world_style.js"),
yourworld: require("./backend/pages/yourworld.js")
};
var websockets = {
chat: require("./backend/websockets/chat.js"),
chathistory: require("./backend/websockets/chathistory.js"),
clear_tile: require("./backend/websockets/clear_tile.js"),
cmd: require("./backend/websockets/cmd.js"),
cmd_opt: require("./backend/websockets/cmd_opt.js"),
cursor: require("./backend/websockets/cursor.js"),
fetch: require("./backend/websockets/fetch.js"),
link: require("./backend/websockets/link.js"),
protect: require("./backend/websockets/protect.js"),
write: require("./backend/websockets/write.js"),
config: require("./backend/websockets/config.js"),
boundary: require("./backend/websockets/boundary.js"),
stats: require("./backend/websockets/stats.js")
};
var modules = {
fetch_tiles: require("./backend/modules/fetch_tiles.js"),
protect_areas: require("./backend/modules/protect_areas.js"),
write_data: require("./backend/modules/write_data.js"),
write_links: require("./backend/modules/write_links.js"),
clear_areas: require("./backend/modules/clear_areas.js")
};
var subsystems = {
chat_mgr: require("./backend/subsystems/chat_mgr.js"),
tile_database: require("./backend/subsystems/tile_database.js"),
tile_fetcher: require("./backend/subsystems/tile_fetcher.js"),
world_mgr: require("./backend/subsystems/world_mgr.js")
};
var sanitizeWorldname = subsystems.world_mgr.sanitizeWorldname;
var modifyWorldProp = subsystems.world_mgr.modifyWorldProp;
var commitAllWorlds = subsystems.world_mgr.commitAllWorlds;
var releaseWorld = subsystems.world_mgr.releaseWorld;
var getOrCreateWorld = subsystems.world_mgr.getOrCreateWorld;
var fetchWorldMembershipsByUserId = subsystems.world_mgr.fetchWorldMembershipsByUserId;
var fetchOwnedWorldsByUserId = subsystems.world_mgr.fetchOwnedWorldsByUserId;
var revokeMembershipByWorldName = subsystems.world_mgr.revokeMembershipByWorldName;
var promoteMembershipByWorldName = subsystems.world_mgr.promoteMembershipByWorldName;
var claimWorldByName = subsystems.world_mgr.claimWorldByName;
var renameWorld = subsystems.world_mgr.renameWorld;
var canViewWorld = subsystems.world_mgr.canViewWorld;
var getWorldNameFromCacheById = subsystems.world_mgr.getWorldNameFromCacheById;
class AsyncDBManager {
database = null;
constructor(_db) {
this.database = _db;
}
// gets data from the database (only 1 row at a time)
async get(command, args) {
var self = this;
if(args == void 0 || args == null) args = [];
return new Promise(function(r, rej) {
self.database.get(command, args, function(err, res) {
if(err) {
return rej({
sqlite_error: process_error_arg(err),
input: { command, args }
});
}
r(res);
});
});
}
// runs a command (insert, update, etc...) and might return "lastID" if needed
async run(command, args) {
var self = this;
if(args == void 0 || args == null) args = [];
return new Promise(function(r, rej) {
self.database.run(command, args, function(err, res) {
if(err) {
return rej({
sqlite_error: process_error_arg(err),
input: { command, args }
});
}
var info = {
lastID: this.lastID,
changes: this.changes
}
r(info);
});
});
}
// gets multiple rows in one command
async all(command, args) {
var self = this;
if(args == void 0 || args == null) args = [];
return new Promise(function(r, rej) {
self.database.all(command, args, function(err, res) {
if(err) {
return rej({
sqlite_error: process_error_arg(err),
input: { command, args }
});
}
r(res);
});
});
}
// get multiple rows but execute a function for every row
async each(command, args, callbacks) {
var self = this;
if(typeof args == "function") {
callbacks = args;
args = [];
}
var def = callbacks;
var callback_error = false;
var cb_err_desc = "callback_error";
callbacks = function(e, data) {
try {
def(data);
} catch(e) {
callback_error = true;
cb_err_desc = e;
}
}
return new Promise(function(r, rej) {
self.database.each(command, args, callbacks, function(err, res) {
if(err) return rej({
sqlite_error: process_error_arg(err),
input: { command, args }
});
if(callback_error) return rej(cb_err_desc);
r(res);
});
});
}
// like run, but executes the command as a SQL file
// (no comments allowed, and must be semicolon separated)
async exec(command) {
var self = this;
return new Promise(function(r, rej) {
self.database.exec(command, function(err) {
if(err) {
return rej({
sqlite_error: process_error_arg(err),
input: { command }
});
}
r(true);
});
});
}
}
function loadDbSystems() {
var database = new sql.Database(serverDBPath);
var edits_db = new sql.Database(editsDBPath);
var chat_history = new sql.Database(chatDBPath);
var image_db = new sql.Database(imageDBPath);
var misc_db = new sql.Database(miscDBPath);
db = new AsyncDBManager(database);
db_edits = new AsyncDBManager(edits_db);
db_chat = new AsyncDBManager(chat_history);
db_img = new AsyncDBManager(image_db);
db_misc = new AsyncDBManager(misc_db);
}
async function loadEmail() {
if(!settings.email.enabled) return;
try {
if(isTestServer) throw "This is a test server";
transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: settings.email.username,
pass: settings.email.password
}
});
} catch(e) {
handle_error(e);
email_available = false;
console.log("\x1b[31;1mEmail disabled. Error message: " + JSON.stringify(process_error_arg(e)) + "\x1b[0m");
}
try {
if(email_available) {
await transporter.verify();
}
} catch(e) {
handle_error(e);
email_available = false;
console.log("\x1b[31;1mEmail is disabled because the verification failed (credentials possibly incorrect)" + JSON.stringify(process_error_arg(e)) + "\x1b[0m");
}
if(email_available) {
console.log("Logged into email");
}
}
async function send_email(destination, subject, text) {
var testEmailAddress = "test@localhost";
if(accountSystem != "local") return;
if(isTestServer || subject == testEmailAddress) {
console.log("To:", destination);
console.log("Subject:", subject);
console.log("Body:", text);
console.log("================");
return null;
}
if(!email_available) return false;
var options = {
from: settings.email.display_email,
to: destination,
subject: subject,
html: text
}
return new Promise(function(resolve) {
transporter.sendMail(options, function(error, info) {
if (error) {
resolve("error");
} else {
resolve(info);
}
});
});
}
async function fetchCloudflareIPs(ip_type) {
if(ip_type == 4) {
ip_type = "ips-v4";
} else if(ip_type == 6) {
ip_type = "ips-v6";
} else {
return null;
}
return new Promise(function(resolve) {
https.get("https://www.cloudflare.com/" + ip_type, function(response) {
var data = "";
response.on("data", function(part) {
data += part;
});
response.on("end", function() {
resolve(data);
});
}).on("error", function() {
resolve(null);
});
});
}
function setupHTTPServer() {
httpServer = new serverUtil.HTTPServer(settings.port, global_data);
httpServer.setPageTree(pages);
httpServer.setDefaultTemplateData("loginPath", loginPath);
httpServer.setDefaultTemplateData("logoutPath", logoutPath);
httpServer.setDefaultTemplateData("registerPath", registerPath);
httpServer.setDefaultTemplateData("profilePath", profilePath);
httpServer.setDefaultTemplateData("accountSystem", accountSystem);
}
async function initializeServer() {
console.log("Starting server...");
if(accountSystem == "uvias") {
setupUvias();
await uvias_init();
global_data.uvias = uvias;
}
loadDbSystems();
setupStaticShortcuts();
loadStatic();
setupZipLog();
setupHTTPServer();
await initialize_misc_db();
await initialize_ranks_db();
await initialize_edits_db();
await initialize_image_db();
global_data.db = db;
global_data.db_img = db_img;
global_data.db_misc = db_misc;
global_data.db_edits = db_edits;
global_data.db_chat = db_chat;
global_data.checkCSRF = httpServer.checkCSRF;
global_data.createCSRF = httpServer.createCSRF;
if(accountSystem == "local") {
await loadEmail();
}
if(!await db.get("SELECT name FROM sqlite_master WHERE type='table' AND name='server_info'")) {
// table to inform that the server is initialized
await db.run("CREATE TABLE 'server_info' (name TEXT, value TEXT)");
}
var init = false;
if(!await db.get("SELECT value FROM server_info WHERE name='initialized'")) {
// server is not initialized
console.log("Initializing server...");
await db.run("INSERT INTO server_info VALUES('initialized', 'true')");
var tables = fs.readFileSync(sql_table_init).toString();
var indexes = fs.readFileSync(sql_indexes_init).toString();
await db.exec(tables);
await db.exec(indexes);
init = true;
if(accountSystem == "local") {
account_prompt();
} else if(accountSystem == "uvias") {
account_prompt(true);
}
}
if(!init) {
start_server();
}
}
function sendProcMsg(msg) {
if(process.send) {
process.send(msg);
}
}
async function initialize_misc_db() {
if(!await db_misc.get("SELECT name FROM sqlite_master WHERE type='table' AND name='properties'")) {
await db_misc.run("CREATE TABLE 'properties' (key BLOB, value BLOB)");
}
}
async function initialize_edits_db() {
if(!await db_edits.get("SELECT name FROM sqlite_master WHERE type='table' AND name='edit'")) {
await db_edits.exec(fs.readFileSync(sql_edits_init).toString());
}
}
async function initialize_image_db() {
if(!await db_img.get("SELECT name FROM sqlite_master WHERE type='table' AND name='images'")) {
await db_img.run("CREATE TABLE 'images' (id INTEGER NOT NULL PRIMARY KEY, name TEXT, date_created INTEGER, mime TEXT, data BLOB)");
}
}
/*
TODO: scrap this & rename to 'chat tag'
proposed change:
- global tags; world tags
*/
async function initialize_ranks_db() {
if(!await db_misc.get("SELECT name FROM sqlite_master WHERE type='table' AND name='ranks'")) {
await db_misc.run("CREATE TABLE 'ranks' (id INTEGER, level INTEGER, name TEXT, props TEXT)");
await db_misc.run("CREATE TABLE 'user_ranks' (userid INTEGER, rank INTEGER)");
await db_misc.run("INSERT INTO properties VALUES(?, ?)", ["max_rank_id", 0]);
await db_misc.run("INSERT INTO properties VALUES(?, ?)", ["rank_next_level", 4]);
}
if(!await db_misc.get("SELECT name FROM sqlite_master WHERE type='table' AND name='admin_ranks'")) {
await db_misc.run("CREATE TABLE 'admin_ranks' (id INTEGER, level INTEGER)");
}
var ranks = await db_misc.all("SELECT * FROM ranks");
var user_ranks = await db_misc.all("SELECT * FROM user_ranks");
ranks_cache.ids = [];
for(var i = 0; i < ranks.length; i++) {
var rank = ranks[i];
var id = rank.id;
var level = rank.level;
var name = rank.name;
var props = JSON.parse(rank.props);
ranks_cache[id] = {
id,
level,
name,
chat_color: props.chat_color
};
ranks_cache.ids.push(id);
}
ranks_cache.count = ranks.length;
for(var i = 0; i < user_ranks.length; i++) {
var ur = user_ranks[i];
ranks_cache.users[ur.userid] = ur.rank;
}
}
function encryptHash(pass, salt) {
if(!salt) {
salt = crypto.randomBytes(10).toString("hex");
}
var hsh = crypto.createHmac(pw_encryption, salt).update(pass).digest("hex");
var hash = pw_encryption + "$" + salt + "$" + hsh;
return hash;
}
function checkHash(hash, pass) {
if(typeof pass !== "string") return false;
if(typeof hash !== "string") return false;
hash = hash.split("$");
if(hash.length !== 3) return false;
return encryptHash(pass, hash[1]) === hash.join("$");
}
async function account_prompt(isUvias) {
var question = "You've just installed the server,\nwhich means you don\'t have any superusers defined.\nWould you like to create one now? (yes/no): ";
var resp = await prompt.ask(question);