-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
1514 lines (1159 loc) · 56 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
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
let
version = "1.4.1",
// Modules
uws = require('uWebSockets.js'),
fastJson = require("fast-json-stringify"),
fs = require("fs"),
app,
SSLApp,
bcrypt = require("bcrypt"), // Secure hashing
crypto = require('crypto'), // Cryptographic utils
uuid = (require("uuid")).v4, // UUID
jwt = require('jsonwebtoken'), // Web tokens
ipc,
{ exec, spawn } = require('child_process'),
// wscp = cookieParser(),
// multer = require('multer-md5'),
// formidable = require('formidable'),
lsdb = require("./addons/lsdb_mysql.js"), // SQL Wrapperr (temporary)
// Config parser
{ parse, stringify, merge, configTools } = require("./core/parser.js"),
{ proxyReq, proxyWebSocket, proxySFTP, remoteNodeShell } = require("./core/proxy.js"),
textEncoder = new TextEncoder,
textDecoder = new TextDecoder
;
try {
// Disable uWebSockets version header, remove to re-enable
uws._cfg('999999990007');
} catch (error) {}
let
// Globals
isDev = fs.existsSync("/www/__dev__"),
initialized = false,
db,
AddonCache = {},
Backend,
config,
configRaw,
API,
apiVersions,
doHost,
doBuild,
host,
port,
PATH = __dirname + "/",
total_hits,
// saved_hits,
since_startup = Date.now(),
devInspecting = isDev && !!process.execArgv.find(v => v.startsWith("--inspect"));
;
async function save_hits(){
const buffer = Buffer.alloc(4);
buffer.writeUInt32LE(total_hits, 0);
fs.writeFileSync(PATH + "./etc/hits", buffer);
// saved_hits = total_hits
}
// Initialize is the first thing that runs after the config is loaded and basics (like the backend object) initialized.
function initialize(){
// saved_hits = total_hits = fs.existsSync(PATH + "/etc/hits") ? fs.readFileSync(PATH + "./etc/hits").readUInt32LE(0) : 0;
// Hit counter
process.on('uncaughtException', (err) => {
// Why does this even happen in the first place
console.debug("[system] [ERROR] It's probably fine, most likely some poorly written module can't throw a proper error instead of crashing the whole thread.\nNot this might also be an actual fatal error and you shouldn't continue (reload might be required).\nThe error: ", err);
});
process.on('exit', () => {
save_hits()
console.log(`[system] API is stopping.`);
})
// Initialize the host communication module (optional)
if(doHost){
let
HostSocketID = 'eg_persistentHost',
HostSocket,
HostConnected = false,
HostQueue,
HostReplyListeners = [],
HostReplies = {}
;
host = {
dispatch(evt, data, force, prefix = 'app.'){
if(force || (HostConnected && HostSocket)){
return HostSocket.emit(prefix + evt, data)
}
if(HostQueue){
HostQueue.push(evt, ...data)
}
},
handleListener(evt){
if(HostReplyListeners.includes(evt))return;
HostReplyListeners.push(evt)
HostSocket.on("app." + evt + ".reply",
function(data){
HostReplies[data.id] = data.reply;
}
)
},
ask(evt, data){
host.handleListener(evt)
if(HostConnected && HostSocket){
let ID = uuid();
HostSocket.emit('app.' + evt, {id :ID, data: data})
return new Promise(resolve => {
let i, interval = setInterval(()=>{
if(HostReplies[ID]){
resolve(HostReplies[ID])
}
i++
if(i > 300){
clearInterval(interval)
resolve(null)
}
}, 10)
})
}
return null
}
}
ipc = require('@node-ipc/node-ipc').default;
ipc.config.id = 'eg_API';
ipc.config.retry = 1000;
ipc.config.logLevel = 'WARN';
let prefix = "[akeno] [persistentHost]";
console.log(prefix + ' CONNECTING TO HOST...');
ipc.connectTo(
HostSocketID,
function(){
HostSocket = ipc.of[HostSocketID];
HostSocket.handle = function(evt, fn){
HostSocket.on(evt, async(data, _socket) => {
if(!data.id){
return fn(data.data, _socket)
}
host.dispatch(evt + ".reply", {id: data.id, reply: await fn(data.data, _socket)}, false, "")
});
}
HostSocket.on(
'connect',
function(){
console.log(prefix + ' INFORMING HOST OF OUR EXISTENCE...');
host.dispatch("hi", "hello", true)
}
);
HostSocket.on(
'disconnect',
function(){
HostConnected = false
console.log(prefix + ' DISCONNECTED FROM HOST');
}
);
HostSocket.on(
'app.hi',
function(){
HostConnected = true
console.log(prefix + ' CONNECTED TO HOST');
if(doBuild) build()
}
);
}
);
} else if (doBuild) build();
}
//Add API handlers or addons here.
API = {
_default: 2,
//Add or remove API versions here.
1: require("./api/v1.js"),
2: require("./api/v2.js")
}
apiVersions = Object.keys(API).filter(version => !isNaN(+version));
API._latest = Math.max(...apiVersions.map(number => +number));
let noCorsHeaders = {
"access-control-allow-origin": "*",
"access-control-allow-methods": "GET,HEAD,POST,PUT,DELETE",
"access-control-allow-credentials": "true",
"access-control-allow-headers": "Authorization, *"
};
function shouldProxy(req, res, secured = false, ws = false, wsContext){
if(!req.domain) req.domain = req.getHeader("host").replace(/:([0-9]+)/, "");
if(req.domain == "upedie.online"){
// Redirect to a diferent server on a specific port
if(!ws) return proxyReq(req, res, {port: 42069}), true;
}
if(req.domain.startsWith("proxy.") || req.domain.startsWith("gateway_") || req.domain.startsWith("gateway.") || req.domain.startsWith("discord.")){
let url,
subdomain = req.domain.split(".")[0],
query = req.getQuery(),
reportedUrl = decodeURIComponent(req.getUrl()).substring(1) + (query? `?${query}`: "")
;
// Handle special cases
if(subdomain.startsWith("gateway_")){
reportedUrl = `http${secured? "s": ""}://${subdomain.replace("gateway_", "").replaceAll("_", ".")}/${reportedUrl}`
} else if(subdomain === "discord"){
reportedUrl = `https://discord.com/${reportedUrl}`
}
try {
url = new URL(decodeURIComponent(reportedUrl));
} catch {
return res.writeStatus("400 Bad Request").end("Proxy error: Invalid URL")
}
if(ws){
let headers = {};
req.forEach((key, value) => {
if(key.toLowerCase() === "host") return;
headers[key] = key.toLowerCase() === "origin"? "https://remote-auth-gateway.discord.gg" : value;
});
return proxyWebSocket(req, res, wsContext, {
url: decodeURIComponent(reportedUrl), parsedUrl: url, headers
}), true
}
return proxyReq(req, res, {
overwriteHeaders: noCorsHeaders,
hostname: url.hostname,
protocol: url.protocol,
path: url.pathname + url.search
}, {
mode: subdomain === "proxy"? "normal": "web",
subdomainMode: subdomain !== "proxy" && subdomain !== "gateway"
}), true
}
return false
}
// The init fucntion that initializes and starts the server.
function build(){
if(initialized) return;
initialized = true;
Backend.log("Initializing the API...")
// Initialize API
for(let version of apiVersions){
version = API[version]
if(version.Initialize) version.Initialize(Backend)
}
db = lsdb.Server(isDev? '109.71.252.170' : "localhost", 'api_full', Backend.config.block("database").properties.password[0])
// Set up multer for file uploads
// const storage = multer.diskStorage({
// destination: '/www/ram/',
// filename: (req, file, callback) => {
// callback(null, Backend.uuid());
// }
// });
// const upload = multer({ storage })
let wss = {
// idleTimeout: 32,
// maxBackpressure: 1024,
maxPayloadLength: 2**16,
compression: uws.DEDICATED_COMPRESSOR_32KB,
sendPingsAutomatically: true,
upgrade(res, req, context) {
// Upgrading a HTTP connection to a WebSocket
res.onAborted(() => {
continueUpgrade = false
})
let host = req.getHeader("host");
// Handle proxied websockets when needed
if(shouldProxy(req, res, true, true, context)) return;
if(req.domain.startsWith("ssh.")) {
return proxySFTP(req, res, context, "will-provide")
}
if(req.domain.startsWith("node.")) {
return remoteNodeShell(req, res, context)
}
if(req.domain.startsWith("ffmpeg-proxy.")){
// let ws;
res.upgrade({
handler: {
open(_ws){
// ws = _ws
},
message(ws, chunk, isBinary){
// For WebSocket receivers
// Backend.broadcast("akeno.ffmpeg.stream", chunk, isBinary, true)
// For HTTP receivers
for(let receiverID in ffmpegStreamReceivers) {if(typeof ffmpegStreamReceivers[receiverID] === "function") ffmpegStreamReceivers[receiverID](chunk)}
},
close(){
}
}
}, req.getHeader('sec-websocket-key'), req.getHeader('sec-websocket-protocol'), req.getHeader('sec-websocket-extensions'), context);
return
}
// if(req.domain.startsWith("ffmpeg-receiver.")){
// res.upgrade({
// handler: {
// open(ws){
// ws.subscribe("akeno.ffmpeg.stream")
// },
// }
// }, req.getHeader('sec-websocket-key'), req.getHeader('sec-websocket-protocol'), req.getHeader('sec-websocket-extensions'), context);
// return
// }
let segments = req.getUrl().split("/").filter(garbage => garbage), continueUpgrade = true;
if(segments[0].toLowerCase().startsWith("v") && !isNaN(+segments[0].replace("v", ""))) segments.shift();
let handler = API[API._latest].GetHandler(segments[0]);
if(!handler || !handler.HandleSocket) return res.end();
if(continueUpgrade) res.upgrade({
uuid: uuid(),
url: req.getUrl(),
query: req.getQuery(),
host,
ip: res.getRemoteAddress(),
ipAsText: res.getRemoteAddressAsText(),
handler: handler.HandleSocket,
segments
}, req.getHeader('sec-websocket-key'), req.getHeader('sec-websocket-protocol'), req.getHeader('sec-websocket-extensions'), context);
},
open(ws) {
if(ws.handler.open) ws.handler.open(ws);
},
message(ws, message, isBinary) {
if(ws.handler.message) ws.handler.message(ws, message, isBinary);
},
close(ws, code, message) {
if(ws.handler.close) ws.handler.close(ws, code, message);
}
};
let types = {
json: "application/json; charset=utf-8",
js: "text/javascript; charset=utf-8",
css: "text/css; charset=utf-8",
html: "text/html; charset=utf-8",
}
let version = Backend.config.valueOf("version") || "unknown";
let ffmpegStreamReceivers = [], ffmpegStreamReceiverID = 0;
function resolve(res, req, secured, virtual) {
total_hits++
// if((total_hits - saved_hits) > 500) save_hits();
// Helper variables
if(virtual){
if(virtual.method) req.getMethod = () => virtual.method
if(virtual.path) req.getUrl = () => virtual.path
if(virtual.domain) req.getHeader = header => header === "host"? virtual.domain: req.getHeader(header)
}
req.method = req.getMethod().toUpperCase(); // Lowercase would be pretty but harder to adapt
req.domain = req.getHeader("host").replace(/:([0-9]+)/, "");
// req.port = +req.getHeader("host").match(/:([0-9]+)/)[1];
req.path = req.getUrl();
req.secured = secured; // If the communication is done over HTTP or HTTPS
if(!req.wasResolved){
req.wasResolved = true; // To handle virtual redirecions
res.writeHeaders = (headers) => {
if(!headers) return res;
res.cork(() => {
for(let header in headers){
if(!headers[header]) return;
res.writeHeader(header, headers[header])
}
});
return res
}
res.onAborted(() => {
clearTimeout(res.timeout)
req.abort = true;
})
// Handle proxied requests
if(shouldProxy(req, res, secured)) return;
// if(req.domain.startsWith("ffmpeg-proxy.")){
// res.onData((chunk, isLast) => {
// console.log("Received chunk", chunk);
// for(let receiverID in ffmpegStreamReceivers) {if(typeof ffmpegStreamReceivers[receiverID] === "function") ffmpegStreamReceivers[receiverID](chunk, isLast)}
// });
// res.onAborted(() => {
// console.log('Stream aborted.');
// });
// return
// }
if(req.domain.startsWith("ffmpeg-receiver.")){
let id = ffmpegStreamReceiverID++;
res.writeHeaders({
// 'Content-Range': `bytes ${start}-${end}/${fileSize}`,
// 'Accept-Ranges': 'bytes',
// 'Content-Length': chunk.,
'Content-Type': 'audio/mpeg',
})
ffmpegStreamReceivers[id] = function(chunk, isLast){
res.cork(() => {
res.write(chunk)
})
}
res.onAborted(() => {
delete ffmpegStreamReceivers[id]
});
return
}
res.corsHeaders = () => {
res .writeHeader('X-Powered-By', 'Akeno Server/' + version)
.writeHeaders(noCorsHeaders)
.writeHeader("Origin", req.domain)
return res
}
// Handle preflights:
if(req.method == "OPTIONS"){
// Prevent preflights for 16 days... which chrome totally ignores anyway
res.corsHeaders().writeHeader("Cache-Control", "max-age=1382400").writeHeader("Access-Control-Max-Age", "1382400").writeHeader("CORS-is", "a piece of crap").end()
return
}
if(req.method === "POST" || (req.transferProtocol === "qblaze" && req.hasBody)){
req.fullBody = Buffer.from('');
// In my opinion; Body on GET requests SHOULD be allowed. There are many legitimate uses for it (eg. when I need to provide extra data, like a query, for the information i want to fetch).
// But since current browser implementations usually block the body for GET requests, I am also skipping their body proccessing.
// Weirdly enough, the spec itself does not prohibit body on GET requests, and yet it is still not widely available.
req.hasFullBody = false
req.contentType = req.getHeader('content-type');
res.onData((chunk, isLast) => {
req.fullBody = Buffer.concat([req.fullBody, Buffer.from(chunk)]);
if (isLast) {
req.hasFullBody = true;
if(req.onFullData) req.onFullData();
}
})
// Helper function
req.parseBody = function bodyParser(callback){
return {
get type(){
return req.getHeader("content-type")
},
get length(){
return req.getHeader("content-length")
},
upload(key = "file", hash){
function done(){
let parts = uws.getParts(req.fullBody, req.contentType);
for(let part of parts){
part.data = Buffer.from(part.data)
if(hash) part.md5 = crypto.createHash('md5').update(part.data).digest('hex')
}
callback(parts)
}
if(req.hasFullBody) done(); else req.onFullData = done;
},
data(){
function done(){
req.body = {
get data(){
return req.fullBody
},
get string(){
return req.fullBody.toString('utf8');
},
get json(){
let data;
try{
data = JSON.parse(req.fullBody.toString('utf8'));
} catch {
return null
}
return data
}
}
callback(req.body)
}
if(req.hasFullBody) done(); else req.onFullData = done;
}
}
}
}
// Default 15s timeout when the request doesnt get answered
res.timeout = setTimeout(() => {
try {
if(req.abort) return;
if(res && !res.sent && !res.wait) res.writeStatus("408 Request Timeout").tryEnd();
} catch {}
}, res.timeout || 15000)
res.send = (message, headers = {}, status) => {
if(req.abort) return;
// OUTDATED!
// Should be avoided for performance reasons
if(Array.isArray(message) || (typeof message !== "string" && !(message instanceof ArrayBuffer) && !(message instanceof Uint8Array) && !(message instanceof DataView) && !(message instanceof Buffer))) {
headers["content-type"] = types["json"];
message = JSON.stringify(message);
Backend.log.warn("[performance] Warning: You are not properly encoding your data before sending. The data were automatically stringified using JSON.stringify, but this has a bad impact on performance. If possible, either send a string, binary data or stringify using fast-json-stringify.")
}
if(res.setType){
headers["content-type"] = res.setType;
}
if(res.setCache){
headers["Cache-Control"] = "public, max-age=" + res.setCache;
}
if(req.begin && headers) {
let hrTime = process.hrtime()
headers["server-timing"] = `generation;dur=${hrTime[0] * 1000 + hrTime[1] / 1000000 - req.begin}`
};
res.cork(() => {
res.writeStatus(status? status + "": "200 OK").corsHeaders().writeHeaders(headers).end(message)
});
}
res.stream = (stream, totalSize) => {
stream.on('data', (chunk) => {
let buffer = chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength), lastOffset = res.getWriteOffset();
res.cork(() => {
// Try writing the chunk
const [ok, done] = res.tryEnd(buffer, totalSize);
if (!done && !ok) {
// Backpressure handling
stream.pause();
// Resume once the client is ready
res.onWritable((offset) => {
const [ok, done] = res.tryEnd(buffer.slice(offset - lastOffset), totalSize);
if (done) {
stream.close();
} else if (ok) {
stream.resume();
}
return ok;
});
} else if (done) stream.close();
})
});
stream.on('error', (err) => {
res.writeStatus('500 Internal Server Error').end();
});
stream.on('end', () => {
res.end();
});
res.onAborted(() => {
stream.destroy();
});
}
res.type = (type) => {
res.setType = types[type] || type
return res
}
res.cache = (duration) => {
res.setCache = duration
return res
}
}
// And when we finally finish with all the utility and other things, let's route the request.
router: {
let index = -1, segments = req.path.split("/").filter(trash => trash).map(segment => decodeURIComponent(segment));
let hrTime = process.hrtime()
req.begin = hrTime[0] * 1000 + hrTime[1] / 1000000;
function error(error, code){
if(req.abort) return;
if(typeof error == "number" && Backend.Errors[error]){
let _code = code;
code = error;
error = (_code? code : "") + Backend.Errors[code]
}
res.cork(() => {
res.writeStatus('400').corsHeaders().writeHeader("content-type", "application/json").end(`{"success":false,"code":${code || -1},"error":"${(JSON.stringify(error) || "Unknown error").replaceAll('"', '\\"')}"}`);
})
}
function shift(){
index++
return segments[index] || "";
}
if(segments[0] === "___internal"){
// console.log(res.getRemoteAddressAsText()); // this does not get the text for some reason
Backend.addon("core/web").HandleInternal({segments, req, res})
}
// Handle the builtin CDN
else if(req.domain.startsWith("cdn.") || req.domain.startsWith("cdn-origin.")){
Backend.addon("cdn").HandleRequest({segments, shift, error, req, res})
}
// Handle the builtin API
else if(req.domain.startsWith("api.extragon")){
let ver = segments[0] ? +(segments[0].slice(1)) : 0;
if(ver && segments[0].toLowerCase().startsWith("v")){
segments.shift()
}
ver = (ver? ver : API._default);
if(API[ver]){
API[ver].HandleRequest({segments, shift, error, req, res})
} else {
return error(0)
}
}
else {
// In this case, the request didnt match any special scenarios, thus should be passed to the webserver:
Backend.addon("core/web").HandleRequest({segments, req, res})
}
}
}
Backend.exposeToDebugger("router", resolve)
Backend.exposeToDebugger("proxyRouter", proxyReq)
// Create server instances
app = uws.App()
Backend.exposeToDebugger("uws", app)
// Initialize WebSockets
app.ws('/*', wss)
// Initialize WebServer
app.any('/*', (res, req) => resolve(res, req, Backend.isDev))
app.listen(port, (listenSocket) => {
if (listenSocket) {
console.log(`[system] [ time:${Date.now()} ] > The Akeno server has started and is listening on port ${port}! Total hits so far: ${typeof total_hits === "number"? total_hits: "(not counting)"}, startup took ${Date.now() - since_startup}ms`)
// Configure SSL
if(Backend.config.block("server").properties.enableSSL) {
SSLApp = uws.SSLApp();
Backend.exposeToDebugger("uws_ssl", SSLApp)
let SSLPort = (+ Backend.config.block("server").properties.sslPort) || 443;
SSLApp.ws('/*', wss)
SSLApp.any('/*', (res, req) => resolve(res, req, true))
// If sslRouter is defined
if(Backend.config.block("sslRouter")){
let SNIDomains = Backend.config.block("sslRouter").properties.domains;
if(SNIDomains){
// This entire proccess is a bit annoying and messy due to the weird API for SNI domains in uWebSockets.
// If it will be necessary, a fork of uWS could be made to make the API cleaner, faster and more fitting to our use-case.
if(!Backend.config.block("sslRouter").properties.certBase){
return Backend.log.error("Could not start SSL server - you are missing certBase in your sslRouter block.")
}
if(!Backend.config.block("sslRouter").properties.certBase){
return Backend.log.error("Could not start SSL server - you are missing keyBase in your sslRouter block.")
}
function addSNIRoute(domain) {
SSLApp.addServerName(domain, {
key_file_name: Backend.config.block("sslRouter").properties.keyBase[0].replace("{domain}", domain.replace("*.", "")),
cert_file_name: Backend.config.block("sslRouter").properties.certBase[0].replace("{domain}", domain.replace("*.", ""))
})
// For some reason we still have to include a separate router like so:
SSLApp.domain(domain).any("/*", (res, req) => resolve(res, req, true)).ws("/*", wss)
// If we do not do this, the domain will respond with ERR_CONNECTION_CLOSED.
// A bit wasteful right? For every domain..
}
for(let domain of SNIDomains) {
addSNIRoute(domain)
if(Backend.config.block("sslRouter").properties.subdomainWildcard){
addSNIRoute("*." + domain)
}
}
// if(Backend.config.block("sslRouter").properties.autoAddDomains){
// SSLApp.missingServerName((hostname) => {
// Backend.log.warn("You are missing a SSL server name <" + hostname + ">! Trying to use a certificate on the fly.");
// addSNIRoute(hostname)
// })
// }
}
}
SSLApp.listen(SSLPort, (listenSocket) => {
if (listenSocket) {
console.log(`[system] Listening with SSL on ${SSLPort}!`)
} else Backend.log.error("[error] Could not start the SSL server! If you do not need SSL, you can ignore this, but it is recommended to remove it from the config. If you do need SSL, make sure nothing is taking the port you configured (" +SSLPort+ ")")
});
}
} else Backend.log.error("[error] Could not start the server!")
});
Backend.resolve = resolve;
if(Backend.config.block("server").properties.preloadWeb) Backend.addon("core/web");
}
// First initialization, ints the backend object.
(private => {
let testKey = process.env.AKENO_KEY;
Backend = {
isDev,
logLevel: isDev? 5 : 3,
config,
configRaw,
get path(){
return PATH
},
get PATH(){
return PATH
},
// configTools,
refreshConfig(){
Backend.log("Refreshing configuration")
if(!fs.existsSync(PATH + "/config")){
Backend.log("No main config file found in /config, creating a default config file.")
fs.writeFileSync(PATH + "/config", fs.readFileSync(PATH + "/etc/default-config", "utf8"))
}
let alreadyResolved = {}; // Prevent infinite loops
function resolveImports(parsed, stack, referer){
let imports = [];
configTools(parsed).forEach("import", (block, remove) => {
remove() // remove the block from the config
if(block.values[0][0]){
let path = block.values[0].join("").replace("./", PATH + "/");
if(path === stack) return Backend.log.warn("Warning: You have a self-import of \"" + path + "\", stopped import to prevent an infinite loop.");
if(!fs.existsSync(path)){
Backend.log.warn("Failed import of \"" + path + "\", file not found")
return;
}
imports.push(path)
}
})
alreadyResolved[stack] = imports;
for(let path of imports){
if(stack === referer || (alreadyResolved[path] && alreadyResolved[path].includes(stack))){
Backend.log.warn("Warning: You have a recursive import of \"" + path + "\" in \"" + stack + "\", stopped import to prevent an infinite loop.");
continue
}
parsed = merge(parsed, resolveImports(parse(fs.readFileSync(path, "utf8"), true), path, stack))
}
return parsed
}
let path = PATH + "/config";
configRaw = Backend.configRaw = resolveImports(parse(fs.readFileSync(path, "utf8"), true), path, null);
config = Backend.config = configTools(configRaw);
},
jwt: {
verify(something, options){
return jwt.verify(something, testKey, options)
},
sign(something, options){
return jwt.sign(something, testKey, options)
}
},
get db(){
return db
},
uuid,
bcrypt,
fastJson,
fs,
exec,
spawn,
host,
app,
SSLApp,
API,
CreationCache: {},
broadcast(topic, data, isBinary, compress){
if(Backend.config.block("server").properties.enableSSL) return SSLApp.publish(topic, data, isBinary, compress); else return app.publish(topic, data, isBinary, compress);
},
user: {
get(idList, callback, items = ["username", "displayname", "pfp", "email", "verified_email", "status", "id"]){
if(!Array.isArray(idList)) idList = [idList];
for(let i = 0; i < idList.length; i++){
if(typeof idList[i] === "object") idList[i] = idList[i].id;
if(typeof idList[i] === "string") idList[i] = +idList[i];
}
idList = idList.filter(id => typeof id === "number")
if(idList.length < 1) return callback(2);
items = items.map(item => item.replace(/[^a-zA-Z0-9_.\-]/g, '')).filter(nothing => nothing).join();
if(items.length < 1) return callback(2);
db.database("extragon").query(`SELECT ${items} FROM users WHERE id IN (${idList.join()}) LIMIT 300`,
function(err, results){
if(err){
return callback(err)
}
if(results.length < 1){
return callback(6)
}
for(let result of results){
if(result.verified_email) result.verified_email = !!result.verified_email.data
}
callback(null, results)
}
)
},
login(username, password, callback, expiresIn = 5184000000, createToken = true){
db.database("extragon").query(
'SELECT hash, id, username FROM `users` WHERE `username` = ? OR `email` = ?',
[username, username],
async function(err, results) {
if(err){
return callback(err)
}
if(results.length < 1){
return callback(6)
}
let user = results[0];
bcrypt.compare(password, user.hash.replace("$2y$", "$2b$"), function(err, result){
if(!err && result){