-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
2542 lines (2203 loc) · 112 KB
/
server.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
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
else {
}
//In the production code, the secrets are fetched using an API and assigned to this const
const secrets = {JWT: '0', GPE: '0', SEND_GRID: '0', FIREBASE: '0', MONGO: '0'};
const express = require('express');
const app = express();
const server = require('http').Server(app);
const socketio = require('socket.io');
const io = socketio(server, { path: "/real-time/" });
const path = require('path');
const { env, disconnect, eventNames } = require('process');
const bcrypt = require('bcrypt');
const useragent = require('express-useragent');
const cmp = require('compression');
const flash = require('express-flash');
const session = require('cookie-session');
const mongoose = require('mongoose');
const uuid = require('uuid');
const UAC = require('./models/udata.js');
const UAC_v2 = require('./models/udata_v2.js');
const VULTURE_SCH = require('./models/vulture_model.js');
const DOCK_SCH = require('./models/dock_model.js');
const RELAY_STATION_SCH = require('./models/relay_station_model.js');
const fs = require('fs');
const crypto = require('crypto');
const forge = require('node-forge');
const { getMessaging } = require("firebase/messaging");
const limiter_src = require('limiter');
const str = require('@supercharge/strings');
const mfa_mgr = require('speakeasy');
const qrcode = require('qrcode');
const axios = require('axios');
const cookie_parser = require('cookie-parser');
const jwt = require('jsonwebtoken');
const jwt_scrt = secrets.JWT;
const { initializeApp } = require('firebase/app');
const frb_db = require("firebase/database");
const { getDatabase, get, once, increment, remove, query, limitToLast, update, push, set, ref, onValue } = require("firebase/database");
const { ToadScheduler, SimpleIntervalJob, AsyncTask, Task } = require('toad-scheduler')
const uap = require('useragent');
const user_profile_gen_functions = require('./user_profile_gen_functions.js');
const encryptor = require('simple-encryptor')(secrets.GPE);//process.env.WEB_RELAY_ENCRYPTION_KEY
const bodyParser = require('body-parser');
user_profile_gen_functions.gen_pilot_u_access_array()
const gen_admin_u_access_array = (acid, role) => user_profile_gen_functions.gen_admin_u_access_array(acid, role);
const gen_pilot_u_access_array = (acid, role) => user_profile_gen_functions.gen_pilot_u_access_array(acid, role);
const gen_data_analyst_u_access_array = (acid, role) => user_profile_gen_functions.gen_data_analyst_u_access_array(acid, role);
let json_parser = bodyParser.json();
let vulture_ping_unix = 0;
const sendgrid = require('@sendgrid/mail')
sendgrid.setApiKey(secrets.SEND_GRID);
const msg = {
to: 'x', // Change to your recipient
from: 'raven@vulture-uplink.com', // Change to your verified sender
subject: 'Your Ionic Vulture order is delayed',
text: "We're sorry to inform you that because of an issue regarding one of the micro nuclear reactors powering the starship Pheonix, the ship won't be able to depart to Luna with the supplies required for your delivery of the Ionic Vulture Xe¹³¹. We ensure you that our staff on the orbital shipyard is doing everything they can to solve this as soon as possible. You will receive as compensation a -1/12% (not to be confused with infinity) discount for any flight to and from Mars. Remember to report any unusual behaviour of anyone during flight to a Security Officer to prevent another Blue Flash™ incident. Fly safe and goodluck :)",
}
// sendgrid.send(msg)
// .then(() => {
// console.log('Email sent')
// })
// .catch((error) => {
// console.error(error)
// })
var admin = require("firebase-admin");
var serviceAccount = require("./vulture-uplinkv-SN.json");
app.use(cookie_parser());
///---MFA---///
// qrcode.toDataURL(secret.otpauth_url, (err, img_data) => {
// // console.log(img_data)
// });
// var verified = mfa_mgr.totp.verify({
// secret: secret.base32,
// encoding: 'base32',
// token: 920383
// });
// console.log(verified)
function getCryptoRandomInt(min, max) {
var maxBytes = 6;
var maxDec = 281474976710656;
var randbytes = parseInt(crypto.randomBytes(maxBytes).toString('hex'), 16);
var result = Math.floor(randbytes / maxDec * (max - min + 1) + min);
if (result > max) {
result = max;
}
return result;
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //max e | min i
}
const firebaseConfig = {
apiKey: secrets.FIREBASE,
authDomain: "rt-tlp.firebaseapp.com",
databaseURL: "https://vulture-uplink-82774-default-rtdb.europe-west1.firebasedatabase.app/",
projectId: "rt-tlp",
storageBucket: "rt-tlp.appspot.com",
messagingSenderId: "383716944699",
appId: "1:383716944699:web:6258045d7d25bcfcb8a51e",
databaseURL: "https://vulture-uplink-82774-default-rtdb.europe-west1.firebasedatabase.app/",
credential: admin.credential.cert(serviceAccount),
};
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://vulture-uplink-82774-default-rtdb.europe-west1.firebasedatabase.app/"
});
const db = admin.database();
var cmd_ping_trigger_unix = 0;
var data_transit_vulture_req_arr = [];
var data_transit_sid_arr = [];
var data_transit_un_arr = [];
var g_joystick_input_pkg;
var thrust_;
var pitch_;
var roll_;
var yaw_;
var ini_lping_time = 0;
var local_server_unix = 0;
var local_server_cs;
var adv_tele_uid_arr = [];
var adv_tele_sid_arr = [];
var command_sid_arr = [];
var last_cic_unix = 0;
var last_gnd_video_broadcaster_unix = 0;
var cic_active_status = false;
var gnd_video_broadcaster_cs = false;
var omega_board_last_unix = 0;
var last_fwd_video_broadcaster_unix = 0;
var fwd_video_broadcaster_cs = false;
var ini_ping_time = 0;
const deep_storage_link = secrets.MONGO;
mongoose.connect(deep_storage_link).then(() => console.log('Deep Storage Uplink Established')).catch(e => { console.log(`Deep Storage Link Failed | ${e}`) });
function add_vulture_to_vow(email, vn, vid) {
UAC_v2.find({ email: email }).exec().then(r => {
if (r.length > 0) {
var update_temp = r[0].vow;
r[0].vow.push({ vid: vid, vn: vn });
UAC_v2.findOneAndUpdate({ email: email }, { vow: update_temp }, { upsert: true }, (err, doc) => { console.log('New Vulture Added to vow') });
}
else {
console.log('Could not add vulture to vow [U404]');
}
});
}
function add_slgin_to_awol(email, obj) {
UAC_v2.find({ email: email }).exec().then(r => {
if (r.length > 0) {
var update_temp = r[0].activity_log_arr;
r[0].activity_log_arr.push(obj);
UAC_v2.findOneAndUpdate({ email: email }, { activity_log_arr: update_temp }, { upsert: true }, (err, doc) => { });
}
});
}
function remove_vulture_to_vow(email, vn) {//todo
// UAC_v2.find({ email: email }).exec().then(r => {
// if(r.length > 0){
// var update_temp = r[0].vow;
// r[0].vow.push({vid: uuid.v4(), vn: vn});
// UAC_v2.findOneAndUpdate({email: email}, {vow: update_temp}, {upsert: true}, (err, doc) => {console.log('New Vulture Added to vow')});
// }
// else{
// console.log('Could not add vulture to vow [U404]');
// }
// });
}
function rem_ebv(arr_0, arr, arr_1, arr_2, val) {
var ix = arr.indexOf(val);
if (ix != -1) {
arr_0.splice(ix, 1);
arr.splice(ix, 1);
arr_1.splice(ix, 1); function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //max e | min i
}
arr_2.splice(ix, 1);
}
}
//----Authentication [beta]----//
var acnt_id;;
// initialize_passport(passport, email => UAC_v2.find({ email: email }).exec())
var vulture_id_cnd_array = [];
const scheduler = new ToadScheduler();
const task = new Task('rm_expired_tokens_frltb', () => {//Remove auth tokens from the firebase realtime db
function rm_data_from_rtdb(path, expy) {
get(ref(db, `${path}/`)).then(snapshot => {
const data = snapshot.val();
for (tkn in data) {
if (Math.abs((Date.now()) - data[tkn].tx) > expy) {
remove(ref(db, `${path}/${tkn}`));
}
}
});
}
rm_data_from_rtdb('aprvd_tids', 7200000);//2h ttl
rm_data_from_rtdb('adv_tele_aprvd_tids', 7200000);//2h ttl
rm_data_from_rtdb('email_conf', 600000);//10min ttl
rm_data_from_rtdb('password_reset', 600000);//10min ttl
rm_data_from_rtdb('password_reset_tokens', 600000);//10min ttl
rm_data_from_rtdb('frstp_aprvd_tids', 180000);//3min ttl
});
const rm_expired_tokens_fdb = new SimpleIntervalJob({ seconds: 5 }, task);
scheduler.addIntervalJob(rm_expired_tokens_fdb);
function add_activity_log_tdb(req, ipx, service_id, email) {//- [X315] -//
//sf
let agl = uap.parse(req.headers["user-agent"]);
let os = agl.os.family;
let os_version = agl.os.major;
let browser = agl.toAgent().replace(agl.toVersion(), '');
let browser_version = agl.toVersion();
let ip = ipx.split(',')[0];
if (process.env.NODE_ENV === 'production') {
getipld(ip).then(ld => {
if (os_version != 0 && os_version != '') {
let log_obj_0 = { ip: ip, city: ld.city.name, state: ld.state.name, loc: ld.location, iso_code: ld.country.iso_code, tx: Date.now(), os: os, os_version: os_version, browser: browser, browser_version: browser_version, mobile: req.useragent.isMobile, service_id: service_id };
add_slgin_to_awol(email, log_obj_0);
}
else {
let log_obj_1 = { ip: ip, city: ld.city.name, state: ld.state.name, loc: ld.location, iso_code: ld.country.iso_code, tx: Date.now(), os: os, os_version: '', browser: browser, browser_version: browser_version, mobile: req.useragent.isMobile, service_id: service_id };
add_slgin_to_awol(email, log_obj_1);
}
});
}
}
let lastTelemetryUnix = 0;
let telemetry = [];
function sendTelemetry(){
const refx = ref(db, `telemetry/${Date.now()}`);
if(lastTelemetryUnix == 0){
set(refx, {telemetry: telemetry, tx: Date.now()});
}else{
if(Math.abs(Date.now() - lastTelemetryUnix) > 10){
set(refx, {telemetry: telemetry, tx: Date.now()});
}
}
lastTelemetryUnix = Date.now();
telemetry = [];
}
//----Global Relay ⇄ Vulture Comm----//
io.on('connection', function (socket_l) {
socket_l.on('fwd_cam_rtc_req', offer => {
io.emit('relayed_fwd_cam_rtc_req', offer);
});
socket_l.on('fwd_cam_rtc_res', answer => {
io.emit('relayed_fwd_cam_rtc_res', answer);
});
socket_l.on('vulture_handshake', payload => {
if (payload.handshake_vid != undefined) {
socket_l.join(payload.handshake_vid);
const add_active_vulture_to_rtdb = ref(db, `active_vultures/${payload.handshake_vid}`);
set(add_active_vulture_to_rtdb, {
tx: Date.now(),
sid: socket_l.id
});
io.emit('refresh_vulture_array_status_sig');
}
});
socket_l.on('disconnect', () => {
get(ref(db, `active_vultures/`)).then(snapshot => {
const data = snapshot.val();
if (data != null) {
for (elm in data) {
if (data[elm].sid == `${socket_l.id}`) {
remove(ref(db, `active_vultures/${elm}`));
io.emit('refresh_vulture_array_status_sig');
}
}
}
});
});
////--Advanced_Telemetry F/E, Command ⇄ this ⇄ Vulture | Command Line Interface parser and relayer--////
socket_l.on('cli_cmd_confirmation', cmd_verifiation_payload => {
var scmd_conf_payload = cmd_verifiation_payload.split(":");
io.emit('cmd_verification_payload', scmd_conf_payload);
});//Vulture ⇄ this ⇄ Advanced_Telemetry F/E | Command Execution Confirmation
socket_l.on('command_exe', cmd_payload => {
var scmd_payload = cmd_payload.cmd.trim().split(" ");
for (let x = 0; x <= scmd_payload.length; x++) {
if (scmd_payload[x] === "") {
scmd_payload.splice(x, 1);
x--;
}
}//CMD payload space separator
//Command Parser
if (scmd_payload[0].toUpperCase() == "RTH") {
if (scmd_payload[1] != null) {
if (scmd_payload[1].toUpperCase() == "-A") {
io.to(`${cmd_payload.vid}`).emit('parsed_cli_cmd', "RTH:1");
}
if (scmd_payload[1].toUpperCase() == "-D") {
io.to(`${cmd_payload.vid}`).emit('parsed_cli_cmd', "RTH:0");
}
if (scmd_payload[1].toUpperCase() != "-A" && scmd_payload[1].toUpperCase() != "-D") {
scmd_payload.push("2");
io.to(`${cmd_payload.vid}`).emit('unparsed_cli_cmd', scmd_payload);
}
}
else {
io.to(`${cmd_payload.vid}`).emit('parsed_cli_cmd', "RTH:-1");
//io.emit('unparsed_cli_cmd', `${scmd_payload[0]}:1`);
}
}
if (scmd_payload[0].toUpperCase() == "REBOOT") {
if (scmd_payload[1] == undefined) {
io.to(`${cmd_payload.vid}`).emit('unparsed_cli_cmd', `${scmd_payload[0]}:1`);
}
else {
if (scmd_payload[1].toUpperCase() == "-1310_DISCO") {
io.to(`${cmd_payload.vid}`).emit('parsed_cli_cmd', "REBOOT:1");
}
if (scmd_payload[1].toUpperCase() != "-1310_DISCO") {
scmd_payload.push("2");
io.to(`${cmd_payload.vid}`).emit('unparsed_cli_cmd', scmd_payload);
}
}
}
if (scmd_payload[0].toUpperCase() == "PING" || scmd_payload[0].toUpperCase() == "PINGU") {
if (scmd_payload[1] == undefined) {
io.to(`${cmd_payload.vid}`).emit('parsed_cli_cmd', "PING:0");
}
if (scmd_payload[1] != undefined) {
if (scmd_payload[1].toUpperCase() == "-L") {
io.to(`${cmd_payload.vid}`).emit('parsed_cli_cmd', "PING:1");
}
if (scmd_payload[1].toUpperCase() == "-N") {
io.to(`${cmd_payload.vid}`).emit('parsed_cli_cmd', "PING:2");
}
if (scmd_payload[1].toUpperCase() != "-L" && scmd_payload[1].toUpperCase() != "-N") {
scmd_payload.push("2");
io.to(`${cmd_payload.vid}`).emit('unparsed_cli_cmd', scmd_payload);
}
}
}
//Unidentifed Command Def Response
if (scmd_payload[0].toUpperCase() != "RTH" && scmd_payload[0].toUpperCase() != "REBOOT" && scmd_payload[0].toUpperCase() != "PING" && scmd_payload[0].toUpperCase() != "PINGU") {
if (local_server_cs == false) {
io.to(`${cmd_payload.vid}`).emit('unparsed_cli_cmd', `${scmd_payload[0]}:0`);
}
}
});
socket_l.on('vulture_online_signal', (payload) => {
console.log(payload);
io.emit('vulture_online_signal_server_relay', "Uplink Established");
});//Vulture ⇄ this uplink indicator
socket_l.on('omega_controller_cs', omega_controller_cs => {
io.emit('omega_controller_cs_rlyd', omega_controller_cs)
});
////--Data flow routing demo [In-progress]--////
socket_l.on('vulture_ownr_link', acnt_link => {
vulture_id_cnd_array.push(acnt_link);
acnt_id = acnt_link;
});
////--Vulture ⇄ this | Telemetry Relay to: Advanced_Telemetry F/E, Command--////
socket_l.on('sat_ops', payload => {
io.to(`${payload.vid}`).emit('sat_ops_rebound', payload.telemetry);
});//Origin HID [02F] | GPS Sat Ops
socket_l.on('gps_position_pkg', (payload) => {
io.to(`${payload.vid}`).emit('gps_position_pkg_rebound', payload.telemetry);
});//Origin HID [02F] | GPS [longitude, latitude, altitude]
socket_l.on('gps_nav_pkg', payload => {
io.to(`${payload.vid}`).emit('gps_nav_pkg_rebound', payload.telemetry);
});//Origin HID [02F] | GPS [heading, speed]
socket_l.on('sonar_telemetry_pkg', sonar_telemetry_payload => {
io.to(`${sonar_telemetry_payload.vid}`).emit('sonar_telemetry_pkg_rebound', sonar_telemetry_payload.telemetry);//to(`${payload.vid}`)
});
socket_l.on('sonar_1_rebound', function (payload) {
io.emit('sonar_1_dist', payload.telemetry);//to(`${payload.vid}`)
});//Origin HID [02D-0] | Front Sonar distance(cm)
socket_l.on('sonar_2_rebound', function (payload) {
io.to(`${payload.vid}`).emit('sonar_2_dist', payload.telemetry);
});//Origin HID [02D-1] | Leftside Sonar distance(cm)
socket_l.on('sonar_3_rebound', function (payload) {
io.to(`${payload.vid}`).emit('sonar_3_dist', payload.telemetry);
});//Origin HID [02D-2] | Rear Sonar distance(cm)
socket_l.on('sonar_4_rebound', function (payload) {
io.to(`${payload.vid}`).emit('sonar_4_dist', payload.telemetry);
}); //Origin HID [02D-3] | Rightside Sonar distance(cm)
socket_l.on('sonar_5_rebound', function (payload) {
io.to(`${payload.vid}`).emit('sonar_5_dist', payload.telemetry);
});//Origin HID [02D-4] | Ground Sonar distance(cm)
socket_l.on('gyro_data_pkg', function (payload) {
io.to(`${payload.vid}`).emit('acc_data_pkg_rebound', payload.telemetry)
});//Origin HID [02E] | Secondary Accelerometer [acceleration, inclination, orientation, pitch, roll, x, y, z]
socket_l.on('barometer_pkg', payload => {
io.to(`${payload.vid}`).emit('barometer_pkg_rebound', payload.telemetry);
});//Origin HID [02I] | Barometer [pressure(Pa), temperture(C), altitude(m)]
socket_l.on('imu_data_pkg_broadcast', payload => {
io.to(`${payload.vid}`).emit('imu_data_pkg_server_relay', payload.telemetry);
});//Origin HID [02C] | IMU [temperture(C)[0], x[1], y[2], z[3], pitch[4], roll[5], accel[6], inclination[7], orientation[8], Gyro x[9], Gyro y[10], Gyro z[11], Gyro pitch[12], Gyro roll[13], Gyro yaw[14], Gyro rate[15], Gyro isCalibrated[16]]
socket_l.on('imu_alpha_data_pkg_broadcast', payload => {
io.emit('imu_alpha_data_pkg_server_relay', payload.telemetry);
});//Origin HID [02C] | IMU [temperture(C)[0], x[1], y[2], z[3], pitch[4], roll[5], accel[6], inclination[7], orientation[8], Gyro x[9], Gyro y[10], Gyro z[11], Gyro pitch[12], Gyro roll[13], Gyro yaw[14], Gyro rate[15], Gyro isCalibrated[16]]
socket_l.on('sensor_array_es', payload => {
io.to(`${payload.vid}`).emit('sensor_array_es_rebound', payload.telemetry);
});//Origin Vulture | Dev purposes only | Relayed to: Advanced_Telemetry F/E
// socket_l.on('relayed_fwd_cam_rts_res', data => {
// console.log(data)
// })
////--Advanced_Telemetry F/E ⇄ this ⇄ Vulture | Special Controls--////
socket_l.on('vulture_heartbeat_emitter', (vulture_heartbeat_emitter_payload) => {
io.to(`${vulture_heartbeat_emitter_payload.vid}`).emit('vulture_heartbeat', vulture_heartbeat_emitter_payload);
});
socket_l.on('imu_restart_signal', () => {
io.emit('imu_restart_signal_sr');
});//Origin Advanced_Telemetry F/E | IMU Restart Signal [demo] | Relayed to: Vulture
socket_l.on('request_vulture_uplink', request_vulture_uplink_payload => {
io.to(`${request_vulture_uplink_payload.vid}`).emit('relayed_request_vulture_uplink');
});
socket_l.on('onEAX', EAX => {
io.to(`${EAX.vid}`).emit('onEAX', '0');
});
socket_l.on('onFCRestart', EAX => {
io.to(`${EAX.vid}`).emit('onFCRestart', '0');
});
socket_l.on('onTELCO', status => {
io.to(`${status.vid}`).emit('onTELCO', status.TELCO);
});
socket_l.on('onPowerOp', onPowerOpPayload => {
io.to(`${onPowerOpPayload.vid}`).emit('onPowerOp', {type: onPowerOpPayload.type});
})
socket_l.on('FlightInputOnChange', FlightInputOnChangePayload => {
io.to(`${FlightInputOnChangePayload.vid}`).emit('FlightInputOnChange', FlightInputOnChangePayload);
});
socket_l.on('baseThrustLvl', thrustLvl => {
telemetry.push({ throttle: { m1: thrustLvl.m1, m2: thrustLvl.m2, m3: thrustLvl.m3, m4: thrustLvl.m4 }, accel: { pitch: thrustLvl.pitch, roll: thrustLvl.roll }, timestamp: Date.now() });
if(thrustLvl.TELCO){
sendTelemetry();
}
io.emit('baseThrustLvl', thrustLvl);
})
socket_l.on('omega_reboot_signal', () => {
io.emit('omega_reboot_signal_relay');
});//Origin Advanced_Telemetry F/E | Omega Hardware Interface Board Restart Signal | Relayed to: Vulture
socket_l.on('vulture_server_reboot', () => {
io.emit('vulture_server_reboot_server_relay');
});//Origin Advanced_Telemetry F/E | Local server running on Vulture Restart Signal | Relayed to: Vulture
socket_l.on('m1_manual_thrust_lvl', (m1_thrust_lvl) => {
io.emit('m1_manual_thrust_lvl_rebound', m1_thrust_lvl);
});//Origin Advanced_Telemetry F/E | M1 Thrust value for manual testing | Relayed to: Vulture
socket_l.on('m2_manual_thrust_lvl', (m2_thrust_lvl) => {
io.emit('m2_manual_thrust_lvl_rebound', m2_thrust_lvl);
});//Origin Advanced_Telemetry F/E | M2 Thrust value for manual testing | Relayed to: Vulture
socket_l.on('m3_manual_thrust_lvl', (m3_thrust_lvl) => {
io.emit('m3_manual_thrust_lvl_rebound', m3_thrust_lvl);
});//Origin Advanced_Telemetry F/E | M3 Thrust value for manual testing | Relayed to: Vulture
socket_l.on('m4_manual_thrust_lvl', (m4_thrust_lvl) => {
io.emit('m4_manual_thrust_lvl_rebound', m4_thrust_lvl);
});//Origin Advanced_Telemetry F/E | M4 Thrust value for manual testing | Relayed to: Vulture
////--Advanced_Telemetry F/E ⇄ this ⇄ Vulture | Autonomy Pref Sync&Transmission--////
socket_l.on('rth_pref_arr_xw', (rth_pref_arr) => {
io.emit('rth_pref_arr_xq', rth_pref_arr);
});
socket_l.on('ca_pref_arr_xw', (ca_pref_arr) => {
io.emit('ca_pref_arr_xq', ca_pref_arr);
});
socket_l.on('wnav_pref_arr_xw', (wnav_pref_arr) => {
io.emit('wnav_pref_arr_xq', wnav_pref_arr);
});
socket_l.on('obj_recog_pref_arr_xw', (obj_recog_pref_arr) => {
io.emit('obj_recog_pref_arr_xq', obj_recog_pref_arr);
});
socket_l.on('rth_status_xw', (rth_status) => {
io.emit('rth_status_xq', rth_status);
});
socket_l.on('vulture_local_autonomy_pref_broadcast', vulture_autonomy_prefs => {
io.emit('vulture_autonomy_prefs_xf', vulture_autonomy_prefs);
});
socket_l.on('vulture_autonomy_prefs_req', () => {
io.emit('vulture_autonomy_prefs_req_xq');
});
socket_l.on('ca_status_xw', ca_status => {
io.emit('ca_status_xq', ca_status);
});
socket_l.on('vulture_local_autonomy_ca_status_broadcast', _ca_status => {
io.emit('vulture_local_autonomy_ca_status_broadcast_xf', _ca_status);
});
socket_l.on('vulture_local_autonomy_rth_status_broadcast', RTH => {
if (RTH == 0) {
io.emit('vulture_local_autonomy_rth_status_broadcast_xf', false);
}
else {
io.emit('vulture_local_autonomy_rth_status_broadcast_xf', true);
}
});
socket_l.on('wnav_status_xw', wnav_status => {
io.emit('wnav_status_xq', wnav_status);
});
socket_l.on('vulture_local_autonomy_wnav_status_broadcast', WNAV => {
if (WNAV == 0) {
io.emit('vulture_local_autonomy_wnav_status_broadcast_xf', false);
}
else {
io.emit('vulture_local_autonomy_wnav_status_broadcast_xf', true);
}
});
socket_l.on('obj_recog_status_xw', obj_recog_status => {
io.emit('obj_recog_status_xq', obj_recog_status);
});
socket_l.on('vulture_local_autonomy_obj_recog_status_broadcast', OBJ_RECOG => {
if (OBJ_RECOG == 0) {
io.emit('vulture_local_autonomy_obj_recog_status_broadcast_xf', false);
}
else {
io.emit('vulture_local_autonomy_obj_recog_status_broadcast_xf', true);
}
});
socket_l.on('vulture_local_autonomy_rth_status_broadcast_req', () => {
io.emit('vulture_local_autonomy_rth_status_broadcast_req_xq');
});
socket_l.on('vulture_local_autonomy_wnav_status_broadcast_req', () => {
io.emit('vulture_local_autonomy_wnav_status_broadcast_req_xq');
});
socket_l.on('vulture_local_autonomy_ca_status_broadcast_req', () => {
io.emit('vulture_local_autonomy_ca_status_broadcast_req_xq');
});
socket_l.on('vulture_local_autonomy_obj_recog_status_broadcast_req', () => {
io.emit('vulture_local_autonomy_obj_recog_status_broadcast_req_xq');
});
////--Hardware Status--////
socket_l.on('gamma_board_hs', () => {
omega_board_last_unix = Date.now();
});//sets last unix for the Omega Hardware Interface Board
socket_l.on('hardware_status', payload => {
io.to(`${payload.vid}`).emit('hardware_status', payload.telemetry);
});
socket_l.on('sensor_array_hardware_cs', payload => {//legacy
io.to(`${payload.vid}`).emit('sensor_array_hardware_cs_server_relay', payload.telemetry);
});//Origin Vulture | Hardware status for [IMU, axdl, sonar_1, sonar_2, sonar_3, sonar_4, sonar_5, GPS, Barometer] | Relayed to: Advanced_Telemetry F/E, Command
////--Ping Emitters--////
socket_l.on('vulture_ping_echo', payload => {
var latency = Math.round((((Date.now() - vulture_ping_unix)) * 100) / 100);
let vulture_connection_status;
if (Math.abs(Date.now() - vulture_ping_unix) > 3000) {
vulture_connection_status = false;
io.to(`${payload.vid}`).emit('vulture_connection_vitals', { latency: latency, status: vulture_connection_status });
}
else {
vulture_connection_status = true;
io.to(`${payload.vid}`).emit('vulture_connection_vitals', { latency: latency, status: vulture_connection_status });
}
});//Vulture ⇄ this ⇄ Advanced_Telemetry F/E, Command | Computed Latency Emitter
socket_l.on('vulture_connection_vitals_res', vulture_connection_vitals_res_payload => {
io.to(`${vulture_connection_vitals_res_payload.vid}`).emit('vulture_connection_vitals_res', vulture_connection_vitals_res_payload);
});
////--this ⇄ Vulture | User Input Relay to Vulture [demo]--////
socket_l.on('fe_rth_status_rqst', () => {
io.emit('be_rth_status_rqst');
});
});
//----Global Relay ⇄ Vulture Coms----//
// app.disable('x-powered-by');
app.use(useragent.express());
app.use(express.urlencoded({ extended: false }));
app.use(cmp());
app.set('views', path.join(__dirname, 'dist/views'));
//----CSP | Cache Control----//
app.use((req, res, next) => {
// res.setHeader('Content-Security-Policy', "default-src 'self'; font-src 'self' https://fonts.gstatic.com 'sha256-HKUd5PpYnXidtaGPY/HUnPf7XvJnSuJMqusXttreQC0=' 'sha256-z7zcnw/4WalZqx+PrNaRnoeLz/G9WXuFqV1WCJ129sg='; img-src 'self' data: https://cdn.maptiler.com; script-src 'self' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://cdn.maptiler.com; style-src 'self' 'unsafe-hashes' https://fonts.googleapis.com https://cdnjs.cloudflare.com https://cdn.maptiler.com 'sha256-HKUd5PpYnXidtaGPY/HUnPf7XvJnSuJMqusXttreQC0=' 'sha256-z7zcnw/4WalZqx+PrNaRnoeLz/G9WXuFqV1WCJ129sg='; frame-src 'self'; worker-src 'self' https://cdn.maptiler.com blob:; connect-src https://api.maptiler.com http://localhost:3300 ws://localhost:3300 https://vulture-uplink.com/ https://vulture-uplink.herokuapp.com/ wss://vulture-uplink.com/ wss://vulture-uplink.herokuapp.com/; object-src 'none';");
res.setHeader('X-Frame-Options', "SAMEORIGIN");
res.setHeader('X-Content-Type-Options', "nosniff");
res.setHeader('X-powered-by', 'antimatter');
// res.setHeader('Cache-Control', 'no-store');
res.setHeader('Permissions-Policy', "autoplay=(self), camera=(), geolocation=(self), microphone=(), usb=(self), interest-cohort=()");
next();
//
});
async function get_snapshot_from_path(path) {
return get(ref(db, path));
}
if (process.env.NODE_ENV === 'production') {
app.enable('trust proxy');
app.use((req, res, next) => {
req.secure ? next() : res.redirect('https://' + req.headers.host + req.url)
});//HTTPS Auto-redirect // handled by cloudflare
}
//----Authentication [beta]----//
app.post('/logout', (req, res) => {
if (req.cookies.at != undefined) {
get_snapshot_from_path(`adv_tele_aprvd_tids/${req.cookies.at.tid}`).then(snapshot => {
const data = snapshot.val();
if (data != null) {
remove(ref(db, `adv_tele_aprvd_tids/${req.cookies.at.tid}`));
}
});
}
res.clearCookie('acid');
res.clearCookie('at');
res.clearCookie('sat');
res.clearCookie('adv_tele_sio_ath');
res.clearCookie('sio_ath');
res.clearCookie('wid');
res.clearCookie('eor');
res.redirect('/login');
});
// UAC_v2.find({ username: 'raven' }).exec().then(r => {
// let acc_auth_methods_arr = { TOTP: false, security_key: false, app: false, first: null };
// let _acc_auth_methods_arr = { TOTP: false, security_key: false, app: true, first: 'app' };
// UAC_v2.findOneAndUpdate({ username: 'raven' }, { acc_auth_methods_arr: acc_auth_methods_arr }, { upsert: true }, (err, doc) => { });
// })
const MFA_mobile_poll_rate_limiter = new limiter_src.RateLimiter({ tokensPerInterval: 675, interval: 'hour' });
app.post('/MFA_mobile_poll', (req, res) => {
if (rate_limiter_checker(MFA_mobile_poll_rate_limiter, res)) {
if (req.cookies.frstp_aprvd_tid != undefined) {
get_snapshot_from_path(`frstp_aprvd_tids/${req.cookies.frstp_aprvd_tid.tid}`).then(snapshot => {
const data = snapshot.val();
if (data != null) {
try {
let agl = uap.parse(req.headers["user-agent"]);
let os = agl.os.family;
let os_version = agl.os.major;
var ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
let ipx = ip.split(',')[0];
if (!data.notification_sent) {
getipld(ipx).then(location => {
try {
set(ref(db, `frstp_aprvd_tids/${req.cookies.frstp_aprvd_tid.tid}`), { notification_sent: true, state: data.state, tx: data.tx, acid: data.acid });
} catch (e) { }
io.to(`${data.acid}`).emit('login_req', { iso_code: location.country.iso_code, state: location.state.name, city: location.city.name, os: os, os_version: os_version, tx: Date.now(), tid: req.cookies.frstp_aprvd_tid.tid });
console.log('nfw: 0')
}).catch(e => {
try {
set(ref(db, `frstp_aprvd_tids/${req.cookies.frstp_aprvd_tid.tid}`), { notification_sent: true, state: data.state, tx: data.tx, acid: data.acid });
} catch (e) { }
io.to(`${data.acid}`).emit('login_req', { iso_code: false, state: false, city: false, os: os, os_version: os_version, tx: Date.now(), tid: req.cookies.frstp_aprvd_tid.tid });
console.log('nfw: 1')
});
}
UAC_v2.find({ acid: req.cookies.frstp_aprvd_tid.acid }).then(r => {
if (r.length > 0) {
const user = r[0];
if (data.state == true) {
remove(ref(db, `frstp_aprvd_tids/${req.cookies.frstp_aprvd_tid.tid}`));
setTimeout(() => {
let user_acc_auth_methods_arr = user.acc_auth_methods_arr;
UAC_v2.findOneAndUpdate({ acid: req.cookies.frstp_aprvd_tid.acid }, { acc_auth_methods_arr: { TOTP: user_acc_auth_methods_arr.TOTP, security_key: user_acc_auth_methods_arr.security_key, app: true, email: user_acc_auth_methods_arr.email, first: user_acc_auth_methods_arr.first } }, { upsert: true }, (err, doc) => { });
successful_auth_post(req, res, user, false);
res.clearCookie('frstp_aprvd_tid');
res.json({ failure_id: 'none', res_tx: Date.now(), redirect_path: req.cookies.wid, result: true });
res.end();
}, 100);
}
if (data.state == false) {
remove(ref(db, `frstp_aprvd_tids/${req.cookies.frstp_aprvd_tid.tid}`));
res.clearCookie('frstp_aprvd_tid');
res.json({ failure_id: 'user_denied_req', res_tx: Date.now(), result: false });
res.end();
}
if (Math.abs(Date.now() - data.tx) > 180000) {
res.json({ failure_id: 'request_timeout', res_tx: Date.now(), result: false });
io.to(`${data.acid}`).emit('login_req_timeout_sig');
remove(ref(db, `frstp_aprvd_tids/${req.cookies.frstp_aprvd_tid.tid}`));
}
else {
if (data.state != true && data.state != false) {
res.end();
}
}
}
else {
res.json({ failure_id: 'failed_acid_fetch', res_tx: Date.now(), result: false });
}
});
} catch (e) { res.json({ failure_id: 'cookie TID not in RTDB', res_tx: Date.now(), result: false }); }
}
else {
res.json({ failure_id: 'cookie TID not in RTDB [RTDB returned null]', res_tx: Date.now(), result: false });
}
});
}
}
});
function successful_auth_post(req, res, user, redirect) {
const tid = `${uuid.v4()}${uuid.v4()}`;
const token = jwt.sign({ acid: user.acid, tid: tid }, jwt_scrt, {
algorithm: 'HS256',
expiresIn: 21600,//6h ttl
});
const add_tid_to_rtdb = ref(db, `adv_tele_aprvd_tids/${tid}`);
set(add_tid_to_rtdb, {
tx: Date.now(),
acid: user.acid,
mobile: req.useragent.isMobile
});
var ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
var at_expiry_date = new Date();
at_expiry_date.setHours(at_expiry_date.getHours() + 6);
if (process.env.NODE_ENV === 'production') {
add_activity_log_tdb(req, ip, 'Advanced Telemetry login', req.body.user_identifier);
// res.cookie('eor', req.body.user_identifier, { httpOnly: false, secure: true });
res.cookie('at', { tac: token, tid: tid, exp: at_expiry_date }, { httpOnly: true, secure: true, expires: at_expiry_date });
res.cookie('adv_tele_sio_ath', tid, { secure: true });
res.cookie('wid', 'advanced_telemetry', { httpOnly: true, secure: true });
res.cookie('acid', user.acid, { secure: true });
}
else {
// add_activity_log_tdb(req, ip, 'Advanced Telemetry login', req.body.user_identifier);
// res.cookie('eor', req.body.user_identifier, { httpOnly: false, secure: false });
res.cookie('at', { tac: token, tid: tid, exp: at_expiry_date }, { httpOnly: true, expires: at_expiry_date });
res.cookie('adv_tele_sio_ath', tid);
res.cookie('wid', 'advanced_telemetry', { httpOnly: true });
res.cookie('acid', user.acid, { secure: false });
}
if (req.cookies.frstp_aprvd_tid != undefined) {
remove(ref(db, `frstp_aprvd_tids/${req.cookies.frstp_aprvd_tid.tid}`));
}
setTimeout(() => {
if (redirect) {
res.redirect('advanced_telemetry');
}
}, 50);
}
app.post('/auth_post', json_parser, (req, res) => {
UAC_v2.find({ $or: [{ email: req.body.user_identifier }, { username: req.body.user_identifier }] }).exec().then(usr => {
if (usr.length > 0) {
const user = usr[0];
bcrypt.compare(req.body.password, user.password).then(rslt => {
if (rslt) {
let tid = `${uuid.v4()}${uuid.v4()}`;
if (user.acc_auth_methods_arr.TOTP || user.acc_auth_methods_arr.security_key || user.acc_auth_methods_arr.app) {
MFA_prep_and_redirect(req, res, user, 0, tid);
}
else {
successful_auth_post(req, res, user, false);
if (process.env.NODE_ENV === 'production') {
res.cookie('eor', req.body.user_identifier, { httpOnly: false, secure: true });
}
else {
res.cookie('eor', req.body.user_identifier, { httpOnly: false, secure: false });
}
if (req.cookies.wid != undefined) {
setTimeout(() => {
res.json({ result: true, redirect_path: req.cookies.wid });
}, 100);
} else {
setTimeout(() => {
res.json({ result: true, redirect_path: '/advanced_telemetry' });
}, 100);
}
}
}
else {
res.json({ result: false });
}
});
}
else {
res.json({ result: false });
}
});
});
function gen_rc() {
return `${uuid.v4().split('-')[0].toUpperCase()}-${uuid.v4().split('-')[3].toUpperCase()}`;
}
const doesUserExist_limiter = new limiter_src.RateLimiter({ tokensPerInterval: 4000, interval: 'hour' });
app.post('/doesUserExist', json_parser, (req, res) => {
if (rate_limiter_checker(doesUserExist_limiter, res)) {
UAC_v2.findOne({ username: req.body.username }).exec().then(query_res => {
if (query_res) {
res.json({ isUsernameTaken: true });
}
else {
res.json({ isUsernameTaken: false });
}
});
}
});
app.post('/opsec_to_adv_tele', (req, res) => {
res.clearCookie('sat');
res.clearCookie('sio_ath');
res.redirect('advanced_telemetry');
});
// const dock_model = new RELAY_STATION_SCH({
// relay_station_id: uuid.v4(),
// dock_array: [{dock_id: '21f9a158-5953-48fc-a4f1-a9af2bf4d27d'}],
// relay_station_name: 'RS-1',
// activity_logs: [],
// user_access_array: [{acid: '88d9e113-520b-45d0-9370-213dc2557a40'}]
// });
// dock_model.save();
// DOCK_SCH.findOneAndUpdate({dock_id: '536413de-9134-4c61-a859-1da3a12478f7'}, {payload_array: [{type: 'Thermal Camera', id: 'PY-2F'}, {type: 'Flood Lights', id: 'PY-1Z'}]}, {upsert: true}, (err, doc) => {});
// RELAY_STATION_SCH.findOneAndUpdate({relay_station_id: 'e2b67ec5-bea9-4251-a58d-cfefd75294fd'}, {dock_array: [{dock_id: '21f9a158-5953-48fc-a4f1-a9af2bf4d27d'}]}, {upsert: true}, (err, doc) => {});
app.post('/genesis_post', (req, res) => {
async function add_udb() {
try {
var es = await bcrypt.hash(req.body.password, 10);
var eq = encryptor.encrypt(req.body.email);
let nvid = uuid.v4();
let nacid = uuid.v4();
let nvn = `VULTURE-${str.random(3).toUpperCase()}${getRandomInt(100, 999)}`;
const uacq = new UAC_v2({
username: req.body.username,
email: req.body.email,
password: es,
vid: uuid.v4(),
acid: nacid,
did: [],
secca: es,
mfa_tkn: mfa_mgr.generateSecret({ length: 40 }),
sec_auth_methods_arr: [true, false, false],//pass | mfa | security key
sec_rcvry_methods_arr: [],
acc_auth_methods_arr: [true, false, false],
acc_rcvry_methods_arr: [],
rcvry_codes_arr: [gen_rc(), gen_rc(), gen_rc(), gen_rc(), gen_rc(), gen_rc(), gen_rc(), gen_rc()],
vow: [{ vid: nvid, vn: nvn }],
dock_array: [],
contact_emails_arr: [],
contact_phone_numbers_arr: [],
});
uacq.save().then((r) => console.log(`${r.vid} added to DeepStorage`))
console.log(`${uuid.v4()} saved to UAC`);
const vulture_sch = new VULTURE_SCH({
vid: nvid,
vn: nvn,
u_access_arr: gen_admin_u_access_array(nacid, 0),
local_prefs_arr: [],
security_rules_arr: [],
flt_logs: [],
});
vulture_sch.save().then(r => { });
} catch (e) {
res.redirect('genesis');
}
res.redirect('/login');
}
add_udb();
});
//----Cookies----//
// app.use(session({secret: 'wowi', cookie: {maxAge: 30000000}}));
//----Authentication [beta]----//
function auth_status(req, res, next) {