-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
1126 lines (823 loc) · 36.9 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.5.5",
since_startup = performance.now(),
// Modules
uws = require('uWebSockets.js'),
fastJson = require("fast-json-stringify"),
fs = require("fs"),
{ ipc_server } = require("./core/ipc"),
ipc,
app,
SSLApp,
H3App,
lmdb = require('node-lmdb'),
lsdb,
bcrypt = require("bcrypt"), // Secure hashing
crypto = require('crypto'), // Cryptographic utils
uuid = (require("uuid")).v4, // UUID
jwt = require('jsonwebtoken'), // Web tokens
// Config parser
{ parse, stringify, merge, configTools } = require("./core/parser"),
// { proxyReq, proxyWebSocket, proxySFTP, remoteNodeShell } = require("./core/proxy"),
{ xxh32 } = require("@node-rs/xxhash"),
// For code compression
CleanCSS = new (require('clean-css')),
UglifyJS = require("uglify-js")
;
try {
// Disable uWebSockets version header, remove to re-enable
uws._cfg('999999990007');
} catch (error) {}
let
// Globals
AddonCache = {},
config,
configRaw,
API = { handlers: new Map },
PATH = __dirname + "/",
total_hits,
domainRouter = new Map,
// TODO: you know what to do :sob:
trustedOrigins = new Set(["https://lstv.space", "https://lstv.test", "https://dev.lstv.test", "https://dev.lstv.space"])
;
const cache_db = {
env: new lmdb.Env(),
memory_compression_cache: new Map,
memory_general_cache: new Map,
commit(){
try {
cache_db.txn.commit();
} catch (error) {
console.error(error);
cache_db.txn.abort();
}
cache_db.txn = cache_db.env.beginTxn();
}
}
cache_db.env.open({
path: PATH + "db/cache",
maxDbs: 3
});
cache_db.compression = cache_db.env.openDbi({
name: "compression_cache",
create: true,
// 32-bit xxhash
keyIsUint32: true
})
cache_db.general = cache_db.env.openDbi({
name: "general_cache",
create: true,
})
cache_db.txn = cache_db.env.beginTxn();
function initialize(){
const socketPath = (backend.config.block("ipc").get("socket_path", String)) || '/tmp/akeno.backend.sock';
// Internal ipc server
ipc = new ipc_server({
onRequest(socket, request, respond){
const command = typeof request === "string"? (request = [request] && request[0]): request[0];
switch(command){
case "ping":
respond(null, {
backend_path: PATH,
version,
isDev,
server_enabled
})
break
case "usage":
const res = {
mem: process.memoryUsage(),
cpu: process.cpuUsage(),
uptime: process.uptime(),
backend_path: PATH,
version,
isDev,
server_enabled,
};
// Calculate CPU usage in percentages
if(request[1] === "cpu") {
setTimeout(() => {
const endUsage = process.cpuUsage(res.cpu);
const userTime = endUsage.user / 1000;
const systemTime = endUsage.system / 1000;
res.cpu.usage = ((userTime + systemTime) / 200) * 100
respond(null, res)
}, 200);
} else respond(null, res);
break
case "web.list":
respond(null, backend.addon("core/web").util.list())
break
case "web.list.domains":
respond(null, backend.addon("core/web").util.listDomains(request[1]))
break
case "web.list.getDomain":
respond(null, backend.addon("core/web").util.getDomain(request[1]))
break
case "web.enable":
respond(null, backend.addon("core/web").util.enable(request[1]))
break
case "web.disable":
respond(null, backend.addon("core/web").util.disable(request[1]))
break
case "web.reload":
respond(null, backend.addon("core/web").util.reload(request[1]))
break
case "web.tempDomain":
respond(null, backend.addon("core/web").util.tempDomain(request[1]))
break
default:
respond("Invalid command")
}
}
})
ipc.listen(socketPath, () => {
console.log(`[system] IPC socket is listening on ${socketPath}`)
})
if (!server_enabled) return;
backend.log("Initializing the server...")
for(let version of API.handlers.values()){
if(version.Initialize) version.Initialize(backend)
}
// Websocket handler
const 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;
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.handlers.get(API.default).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);
}
};
const web_handler = backend.addon("core/web").HandleRequest;
function resolve(res, req, flags, virtual = null) {
if(!virtual) {
req.begin = performance.now()
// Lowercase is pretty but most code already uses uppercase
req.method = req.getMethod && req.getMethod().toUpperCase();
const _host = req.getHeader("host"), _colon_index = _host.lastIndexOf(":");
req.domain = _colon_index === -1? _host: _host.slice(0, _host.lastIndexOf(":"));
req.path = req.getUrl();
req.origin = req.getHeader('origin');
req.secure = flags && !!flags.secure; // If the request is done over a secured connection
// req.secured = req.secure; // I messed up the name at first...
} else {
// Virtual requests for whatever reason...
// Should this be kept or removed?
// It has a real use-case: selectively handling some requests by different handlers or "emulating" requests.
req.getMethod = () => virtual.method;
req.getUrl = () => virtual.path;
Object.assign(req, virtual)
req.virtual = true
}
// Handle preflight requests
// TODO: make this more flexible
if(req.method == "OPTIONS"){
backend.helper.corsHeaders(req, res)
res.writeHeader("Cache-Control", "max-age=1382400").writeHeader("Access-Control-Max-Age", "1382400").end()
return
}
// Yeah, if the request is virtual, resolve may be called multiple times on the same request.
// However it is not valid if the request has already been sent.
if(!req.wasResolved){
req.wasResolved = true;
res.onAborted(() => {
clearTimeout(res.timeout)
req.abort = true;
})
// Handle proxied requests
// if(shouldProxy(req, res, flags)) return;
// Receive POST body
if(req.method === "POST" || (req.transferProtocol === "qblaze" && req.hasBody)){
req.fullBody = Buffer.from('');
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();
}
})
}
// 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)
}
// Finally, lets route the request to find a handler.
let index = -1, segments = decodeURIComponent(req.path).split("/").filter(Boolean)
function shift(){
index++
return segments[index] || "";
}
// Default handler is the web handler
let handler = domainRouter.get(req.domain) || web_handler;
// Handle the built-in API
if(handler === 2){
const versionCode = segments.shift();
const firstChar = versionCode && versionCode.charCodeAt(0);
if(!firstChar || (firstChar !== 118 && firstChar !== 86)) return backend.helper.error(req, res, 0);
const api = API.handlers.get(parseInt(versionCode.slice(1), 10));
handler = api && api.HandleRequest;
if(!handler) return backend.helper.error(req, res, 0);
} else if(typeof handler !== "function"){
return req.writeStatus("400 Bad Request").end("400 Bad Request")
}
handler({segments, shift, error: (error, code) => backend.helper.error(req, res, error, code), req, res})
}
backend.exposeToDebugger("router", resolve)
// 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(HTTPort, (listenSocket) => {
if (listenSocket) {
console.log(`[system] Akeno server v${version} has started and is listening on port ${HTTPort}! Total hits: ${typeof total_hits === "number"? total_hits: "(not counting)"}, startup took ${(performance.now() - since_startup).toFixed(2)}ms`)
// Configure SSL
if(ssl_enabled) {
SSLApp = uws.SSLApp();
backend.exposeToDebugger("uws_ssl", SSLApp)
if(h3_enabled){
H3App = uws.H3App({
key_file_name: '/etc/letsencrypt/live/lstv.space/privkey.pem',
cert_file_name: '/etc/letsencrypt/live/lstv.space/fullchain.pem',
passphrase: '1234'
});
// HTTP3 doesn't have WebSockets, do not setup ws listeners.
H3App.any('/*', (res, req) => resolve(res, req, {secure: true, h3: true}))
backend.exposeToDebugger("uws_h3", H3App)
}
SSLApp.ws('/*', wss)
SSLApp.any('/*', (res, req) => resolve(res, req, {secure: true}))
// If sslRouter is defined
if(backend.config.block("sslRouter")){
let SNIDomains = backend.config.block("sslRouter").properties.domains;
if(SNIDomains){
if(!backend.config.block("sslRouter").properties.certBase || !backend.config.block("sslRouter").properties.keyBase){
return backend.log.error("Could not start server with SSL - you are missing your certificate files (either base or key)!")
}
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, {secure: 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(domain.startsWith("*.")){
addSNIRoute(domain.replace("*.", ""))
}
}
// 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+ ")")
});
if(h3_enabled){
H3App.listen(H3Port, (listenSocket) => {
if (listenSocket) {
console.log(`[system] HTTP3 Listening with SSL on ${H3Port}!`)
} else backend.log.error("[error] Could not start the HTTP3 server! If you do not need HTTP3, you can ignore this, but it is recommended to remove it from the config. Make sure nothing is taking the port you configured for H3 (" +H3Port+ ")")
});
}
}
} else backend.log.error("[fatal error] Could not start the server on port " + HTTPort + "!")
});
backend.resolve = resolve;
if(backend.config.block("server").get("preloadWeb", Boolean)) backend.addon("core/web");
}
const jwt_key = process.env.AKENO_KEY;
const devInspecting = !!process.execArgv.find(v => v.startsWith("--inspect"));
const backend = {
version,
config,
configRaw,
get path(){
return PATH
},
get PATH(){
return PATH
},
helper: {
writeHeaders(req, res, headers){
if(headers) {
res.cork(() => {
for(let header in headers){
if(!headers[header]) return;
res.writeHeader(header, headers[header])
}
});
}
return backend.helper
},
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",
},
corsHeaders(req, res, credentials = false) {
if(trustedOrigins.has(req.origin)){
credentials = true
}
res.cork(() => {
res.writeHeader('X-Powered-By', 'Akeno Server/' + version);
if(credentials){
res.writeHeader("Access-Control-Allow-Credentials", "true");
res.writeHeader("Access-Control-Allow-Origin", req.origin);
res.writeHeader("Access-Control-Allow-Headers", "Content-Type,Authorization,Credentials,Data-Auth-Identifier");
} else {
res.writeHeader('Access-Control-Allow-Origin', '*');
res.writeHeader("Access-Control-Allow-Headers", "Authorization,*");
}
res.writeHeader("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,DELETE,OPTIONS");
if(h3_enabled){
// EXPERIMENTAL: add alt-svc header for HTTP3
res.writeHeader("alt-svc", `h3=":${H3Port}"`)
}
})
return backend.helper
},
// This helper should be avoided.
// Only use this if: 1) You are lazy; ...
send(req, res, data, headers = {}, status){
if(req.abort) return;
if(data !== undefined && (typeof data !== "string" && !(data instanceof ArrayBuffer) && !(data instanceof Uint8Array) && !(data instanceof Buffer)) || Array.isArray(data)) {
headers["content-type"] = backend.helper.types["json"];
data = JSON.stringify(data);
}
res.cork(() => {
res.writeStatus(status || "200 OK")
if(req.begin) {
res.writeHeader("server-timing", `generation;dur=${performance.now() - req.begin}`)
}
backend.helper.corsHeaders(req, res).writeHeaders(req, res, headers)
if(data !== undefined) res.end(data)
});
},
// This helper should likely be avoided.
error(req, res, 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')
backend.helper.corsHeaders(req, res)
res.writeHeader("content-type", "application/json").end(`{"success":false,"code":${code || -1},"error":"${(JSON.stringify(error) || "Unknown error").replaceAll('"', '\\"')}"}`);
})
},
stream(req, res, 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();
});
},
parseBody(req, res, 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;
},
parts(){
function done(){
let parts = uws.getParts(req.fullBody, req.contentType);
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;
}
}
}
},
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
// TODO: Merge function must be updated
function resolveImports(parsed, stack, referer){
let imports = [];
configTools(parsed).forEach("import", (block, remove) => {
remove() // remove the block from the config
if(block.attributes.length !== 0){
let path = block.attributes[0].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"), {
strict: true,
asLookupTable: true
}), path, stack))
}
return parsed
}
let path = PATH + "/config";
configRaw = backend.configRaw = resolveImports(parse(fs.readFileSync(path, "utf8"), {
strict: true,
asLookupTable: true
}), path, null);
// configRaw = backend.configRaw = parse(fs.readFileSync(path, "utf8"), {
// strict: true,
// asLookupTable: true
// });
config = backend.config = configTools(configRaw);
},
compression: {
// Code compression with both disk and memory cache.
code(code, isCSS){
const hash = xxh32(code);
let compressed;
if(compressed = cache_db.memory_general_cache.get(hash)) return compressed;
let hasDiskCache = false // lmdb_exists(cache_db.txn, cache_db.compression, hash)
if(!hasDiskCache){
compressed = Buffer.from(isCSS? CleanCSS.minify(code).styles: UglifyJS.minify(code).code)
// cache_db.txn.putBinary(cache_db.compression, hash, compressed);
// cache_db.commit();
}
// else {
// compressed = cache_db.txn.getBinary(cache_db.compression, hash)
// }
cache_db.memory_compression_cache.set(hash, compressed)
return compressed || code;
}
},
cache: {
set(key, value){
switch (true) {
case value instanceof Buffer:
cache_db.txn.putBinary(cache_db.general, key, value);
break;
case typeof value === "boolean":
cache_db.txn.putBoolean(cache_db.general, key, value);
break;
case typeof value === "string":
cache_db.txn.putString(cache_db.general, key, value);
break;
case typeof value === "number":
cache_db.txn.putNumber(cache_db.general, key, value);
break;
default:
throw new Error("Unsupported value type");
}
cache_db.memory_general_cache.set(key, value)
},
get(key, type){
type = {Buffer: "getBinary", Boolean: "getBoolean", Number: "getNumber", String: "getString"}[type] || "getBinary";
return cache_db.memory_general_cache.get(key) || cache_db.txn[type](cache_db.general, key)
},
delete(key){
cache_db.memory_general_cache.delete(key)
cache_db.txn.del(cache_db.general, key);
},
commit(){
cache_db.commit();
}
},
jwt: {
verify(something, options){
return jwt.verify(something, jwt_key, options)
},
sign(something, options){
return jwt.sign(something, jwt_key, options)
}
},
uuid,
bcrypt,
fastJson,
app,
SSLApp,
API,
apiExtensions: {},
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);
},
writeLog(data, severity = 2, source = "api"){
// 0 = Debug (Verbose), 1 = Info (Verbose), 2 = Info, 3 = Warning, 4 = Error, 5 = Important
if(severity < (5 - backend.logLevel)) return;
if(!Array.isArray(data)) data = [data];
if(devInspecting) data.unshift("color: aquamarine");
console[severity == 4? "error": severity == 3? "warn": severity < 2? "debug": "log"](`${devInspecting? "%c": ""}[${source}]`, ...data)
},
createLoggerContext(target){
let logger = function (...data){
backend.writeLog(data, 2, target)
}
logger.debug = function (...data){
backend.writeLog(data, 0, target)
}
logger.verbose = function (...data){
backend.writeLog(data, 1, target)
}
logger.info = function (...data){
backend.writeLog(data, 2, target)
}
logger.warn = function (...data){
backend.writeLog(data, 3, target)
}
logger.error = function (...data){
backend.writeLog(data, 4, target)
}
logger.impotant = function (...data){
backend.writeLog(data, 5, target)
}
return logger
},
addon(name, path){
if(!AddonCache[name]){
path = path || `./${name.startsWith("core/") ? "" : "addons/"}${name}`;
backend.log("Loading addon;", name);
AddonCache[name] = require(path);
AddonCache[name].log = backend.createLoggerContext(name)
if(AddonCache[name].Initialize) AddonCache[name].Initialize(backend);
}
return AddonCache[name]
},
mime: {
// My own mimetype checker since the current mimetype library for Node is meh.
types: null,
extensions: null,
load(){
backend.mime.types = JSON.parse(fs.readFileSync(PATH + "/etc/mimetypes.json", "utf8"))
backend.mime.extensions = {}
for(let extension in backend.mime.types){
backend.mime.extensions[backend.mime.types[extension]] = extension
}
},
getType(extension){
if(!backend.mime.types) backend.mime.load();
return backend.mime.types[extension] || null
},
getExtension(mimetype){
if(!backend.mime.extensions) backend.mime.load();
return backend.mime.extensions[mimetype] || null
}
},
Errors: {
0: "Unknown API version",
1: "Invalid API endpoint",
2: "Missing parameters in request body/query string.",
3: "Internal Server Error.",
4: "Access denied.",
5: "You do not have access to this endpoint.",
6: "User not found.",
7: "Username already taken.",
8: "Email address is already registered.",
9: "Your login session has expired. Please log-in again.",
10: "Incorrect verification code.", // FIXME: What does this even mean
11: "Invalid password.",
12: "Authentication failed.",
13: "Session/API token missing or expired.", // FIXME: Identical to 9
14: "This account is suspended.",
15: "Forbidden action.", // FIXME: Unclear
16: "Entity not found.",
17: "Request timed out.",
18: "Too many requests. Try again in a few seconds.", // FIXME: Identical to 34/36/429
19: "Service temporarily unavailable.",
20: "Service/Feature not enabled. It might first require setup from your panel, is not available (or is paid and you don't have access).",
21: "Unsupported media type.",
22: "Deprecated endpoint. Consult documentation for a replacement.",
23: "Not implemented.",
24: "Conflict.",
25: "Data already exist.",
26: "Deprecated endpoint. Consult documentation for a replacement.",
27: "This endpoint has been removed from this version of the API. Please migrate your code to the latest API version to keep using it.",
28: "Access blocked for the suspicion of fraudulent/illegal activity. Contact our support team to get this resolved.",
29: "This endpoint requires an additional parametter (cannot be called directly)",
30: "Invalid method.", // FIXME: Identical to 39
31: "Underlying host could not be resolved.",
32: "Underlying host could not resolve this request due to a server error.",
33: "Temporarily down due to high demand. Please try again in a few moments.",
34: "Global rate-limit has been reached. Please try again in a few moments.",
35: "This endpoint may handle sensitive data, so you must use HTTPS. Do not use unsecured connections to avoid your information being vulnerable to attacks.",
36: "Rate-Limited. Please try again in a few minutes.",
37: "Rate-Limited. You have used all of your requests for a given time period.",
38: "Rate-Limited. Please contact support for more information.",
39: "Invalid method for this endpoint.",
40: "This is a WebSocket-only endpoint. Use the ws:// or wss:// protocol instead of http.",
41: "Wrong protocol.",
42: "Internal error: Configured backend type doesn't have a driver for it. Please contact support.",
43: "File not found.",
44: "The request contains wrong data",
45: "Wrong data type",
46: "Invalid email address.",
47: "Username must be within 2 to 200 characters in range and only contain bare letters, numbers, and _, -, .",
48: "Weak password.",
49: "Sent data exceed maximum allowed size.",