-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.js
More file actions
1630 lines (1361 loc) · 54.4 KB
/
Copy pathServer.js
File metadata and controls
1630 lines (1361 loc) · 54.4 KB
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
var express = require("express");
var WebSocket = require('ws');
var fs = require('fs');
var bodyParser = require("body-parser");
var cors = require('cors');
// var http = require('http');
const https = require('https');
const Client = require('ssh2').Client
var app = express();
(function () {
var old = console.log;
console.log("> Log Date Format DD/MM/YY HH:MM:SS - UTCString");
console.log = function () {
var n = new Date();
var d = ("0" + (n.getDate().toString())).slice(-2),
m = ("0" + ((n.getMonth() + 1).toString())).slice(-2),
y = ("0" + (n.getFullYear().toString())).slice(-2),
t = n.toUTCString().slice(-13, -4);
Array.prototype.unshift.call(arguments, "[" + d + "/" + m + "/" + y + t + "]");
old.apply(this, arguments);
}
})();
// const corsOptions = {
// // origin: process.env.CORS_ALLOW_ORIGIN || '*',
// origin: 'https://consol.cybera.ca/',
// methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'],
// allowedHeaders: ['Content-Type', 'Authorization']
// };
// app.use(cors(corsOptions));
function customHeaders(req, res, next) {
res.setHeader('X-Powered-By', 'dsStack');
res.setHeader('x-content-type-options', 'nosniff');
next()
}
app.use(customHeaders);
var router = express.Router();
// all templates are located in `/views` directory
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
const viewPath = __dirname + '/views/';
const stylesPath = __dirname + '/static/theme/';
app.use(express.static('static'));
global.compDataObj = {}
global.compDataObj = { "0": JSON.parse(fs.readFileSync(__dirname + '/compData.json')) }
// compDataObj["93dee0ac-da81-4f07-a503-ef7b0b02aa43"] = compDataObj[0]
// const config = { "username": "admin" }
function generateUUID() {
var d = new Date().getTime();
if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
d += performance.now(); //use high-precision timer if available
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}
router.use(function (req, res, next) {
var log = {
date: new Date().toISOString().replace(/T/, '_').replace(/:/g, '-'),
md: req.method,
protocol: req.protocol,
host: req.get('host'),
pathname: req.originalUrl,
rad: req.connection.remoteAddress,
referrer: req.headers.referrer || req.headers.referer
};
fs.appendFile('dsStack_access.log', JSON.stringify(log) + "\n", function (err) {
if (err) throw err;
});
next();
});
//redirect from consol
router.use(function (req, res, next) {
if (req.get('host') === "consol.cybera.ca:8443") {
res.redirect(301, 'https://dsstack.cybera.ca:8443');
} else {
next();
}
});
//redirect from dsman
router.use(function (req, res, next) {
if (req.get('host') === "dsman.cybera.ca:8443") {
res.redirect(301, 'https://dsstack.cybera.ca:8443/dsman');
} else {
next();
}
});
router.get("/", function (req, res) {
res.render("index", { manager: false });
});
router.get("/dsman", function (req, res) {
res.render("dsman", { manager: true })
});
router.get("/getTree", function (req, res) {
var id = req.query.id;
var userID = req.query.userID;
var compData = {}
//if compDataObj does not contain user's component data, attenpt to load user's component file if it exists
if (!compDataObj[userID]) {
// log("! compDataObj[userID]")
fs.readFile(__dirname + '/compData/compData.' + userID + '.json', (err, data) => {
if (!err && data) {
// log("!err && data")
log("Loaded /compData/compData." + userID + ".json")
compDataObj[userID] = JSON.parse(data)
compData = compDataObj[userID]
buildTree(id, compData)
} else {
log("Did not load /compData/compData." + userID + ".json")
compData = compDataObj["0"]
buildTree(id, compData)
}
})
} else if (Object.keys(compDataObj[userID]).length === 0) {
// log("compDataObj[userID]).length === 0")
compData = compDataObj["0"]
buildTree(id, compData)
} else {
// log("else", userID)
compData = compDataObj[userID]
buildTree(id, compData)
}
//builds the return json for node(s) and responds to req
function buildTree(id, compData) {
var searchSt = ""
if (req.query.hasOwnProperty("searchSt")) {
if (req.query.searchSt.trim() !== "") {
searchSt = req.query.searchSt.toLowerCase()
}
}
res.writeHead(200, { "Content-Type": "application/json" });
var resJSON = [];
if (id !== '#') {
// if (compData.hasOwnProperty(key)) {
let rowdata = compData[id];
// rowdata.id = id;
resJSON.push(rowdata);
} else {
var found = false
var foundIds = [];
for (var key in compData) {
if (compData.hasOwnProperty(key)) {
let rowdata = compData[key];
found = false
// if (searchSt === "" || !rowdata.hasOwnProperty("text") || !rowdata.hasOwnProperty("description") || !rowdata.hasOwnProperty("script")) {
if (searchSt === "") {
found = true
} else if (rowdata.hasOwnProperty("text") && rowdata.text.toLowerCase().includes(searchSt)) {
found = true
rowdata.found = true
} else if (rowdata.hasOwnProperty("description") && compData[key].description.hasOwnProperty("ops")) {
compData[key].description.ops.forEach(function (row) {
if (row.hasOwnProperty("insert")) {
var rTxt = row.insert;
if (rTxt.hasOwnProperty("includes")) { //could be image
if (rTxt.includes(searchSt)) {
found = true
}
}
}
})
} else if (rowdata.hasOwnProperty("script") && rowdata.script.toLowerCase().includes(searchSt)) {
found = true
rowdata.found = true
}
if (found === true) {
var a = compData[key].parent
var x = 0
while (a && a !== '#') {
if (!foundIds.includes(compData[a].id)) {
resJSON.unshift(compData[a])
foundIds.push(a)
}
a = compData[a].parent
x++
if (x > 100) {
log("Error: too many grand parents found during search [" + key + "]")
res.end("500")
return ("Error: too many grand parents found during search [" + key + "]")
}
}
rowdata.id = key
if (!rowdata.hasOwnProperty("enabled") || rowdata.enabled !== "true") {
rowdata.type = "disabled"
} else {
rowdata.type = "code"
}
resJSON.push(rowdata)
foundIds.push(key)
} else {
}
}
}
}
res.end(JSON.stringify(resJSON));
}
});
// Save existing component or create new.
router.post("/saveComp", function (req, res) {
var reqJSON = req.body;
let userID = reqJSON.userID
let userName = reqJSON.userName
var retId = ""
let newFlag = true
var compData
if (!reqJSON.hasOwnProperty("userID")) {
log("saveComp error: reqJSON does not have property userID")
res.end("saveComp error: reqJSON does not have property userID");
} else if (!reqJSON.hasOwnProperty("id")) {
log("saveComp error: reqJSON does not have property id")
res.end("saveComp error: reqJSON does not have property id")
} else if (userID == "0") {
log("saveComp error: Cannot save to default ID 0")
res.end("saveComp error: Cannot save to default ID 0")
} else if (!compDataObj[userID]) {
log("saveComp error: compDataObj does not have property userID")
res.end("saveComp error: compDataObj does not have property userID")
} else {
if (Object.keys(compDataObj[userID]).length === 0) {
compDataObj[userID] = compDataObj["0"]
}
compData = compDataObj[userID]
newFlag = reqJSON.id.trim() !== "" ? false : true
let id
if (!newFlag) {
id = reqJSON.id;
retId = id
compData[id].text = reqJSON.text
compData[id].script = reqJSON.script
compData[id].description = reqJSON.description
compData[id].variables = reqJSON.compVariables
var ds = new Date().toISOString();
if (compData[id].hist) {
compData[id].hist.push({ ds: ds, event: "save", userName: userName })
} else {
let hist = [{ ds: ds, event: "save", userName: userName }]
compData[id].hist = hist
}
} else {
id = generateUUID();
retId = id
compData[id] = {}
compData[id].text = reqJSON.text
compData[id].parent = reqJSON.parent
compData[id].script = reqJSON.script
compData[id].description = reqJSON.description
compData[id].sort = 9000
var ds = new Date().toISOString();
let hist = [{ ds: ds, event: "new", userName: userName }]
compData[id].hist = hist
}
saveAllJSON(true, userID, [id])
log("Saved " + userID + " for " + userName)
res.end(retId);
}
});
// Delete components from the users compdata. Req should include ids array attrib and userID attrib.
// Include all children IDs
router.post("/remove", function (req, res) {
var reqJSON = req.body;
log("Remove comp(s) " + reqJSON.ids + " for " + reqJSON.userName)
if (reqJSON.ids && reqJSON.userID) {
var userID = reqJSON.userID
if (userID === "0" || !compDataObj[userID]) {
log("remove error: compDataObj does not have property userID")
res.end("remove error: compDataObj does not have property userID")
} else {
var compData = compDataObj[userID]
var ids = reqJSON.ids.split(';');
// let index = 0
ids.forEach(function (id) { //Loop throu all ids
if (compData.hasOwnProperty(id)) {
delete compData[id];
// compData.splice(index, 1)
// index++
}
});
saveAllJSON(true, userID, []);
}
}
res.end('');
});
router.post("/copy", function (req, res) {
var reqJSON = req.body;
var userID = reqJSON.userID
var userName = reqJSON.userName
var errorMsg = ""
if (userID === "0" || !compDataObj[userID]) {
log("copy error: compDataObj does not have property userID")
errorMsg = "copy error: compDataObj does not have property userID"
} else {
var compData = compDataObj[userID]
var fromIds = reqJSON.ids.split(';');
var targetId = reqJSON.parent;
var position = reqJSON.pos;
// var lib = reqJSON.lib;
var error = false;
var errorID = '';
//Set error flag if target not exist
if ((!compData.hasOwnProperty(targetId)) && (targetId !== '#')) {
error = true;
errorID = targetId;
errorMsg = "target not exist"
}
//set error flag if from ID(s) not exist
fromIds.forEach(function (id) {
if (!compData.hasOwnProperty(id) && error === false) {
error = true;
errorID = id;
}
errorMsg = "from ID(s) not exist"
});
//Ensure move flag is present
if (!reqJSON.move) {
log("copy error: move flag is absent in request")
res.end("copy error: move flag is absent in request")
error = true;
errorID = targetId;
errorMsg = "move flag is absent in request"
}
//If no error
if (error === false) {
if (reqJSON.move === "true") {
compData[fromIds[0]].parent = targetId
fixChildsSort(targetId, userID);
//Save compData and backup
saveAllJSON(true, userID, []);
//Return OK status
res.sendStatus(200);
res.end('');
} else {
//build id map of old parents and new parents
var idMap = {};
//add from parent and new parent to id map
idMap[compData[fromIds[0]].parent] = targetId;
//loop through all fromIds and copy
fromIds.forEach(function (fromId) {
var fromNode = compData[fromId];
var id = generateUUID();
//update parent id map
idMap[fromId] = id;
var newParentId = idMap[compData[fromId].parent];
//log('move to:'+compData[newParentId].name);
//initial history json
var ds = new Date().toISOString();
// var hist = [{ username: config.username, ds: ds, fromId: fromId }];
var hist = [{ ds: ds, fromId: fromId, userName: userName }];
//Build new component obj. Version 1
var NewRow = {
parent: newParentId,
text: fromNode.text,
description: fromNode.description,
// ver: 1,
// comType: fromNode.comType,
// sort: fromNode.sort,
// text: fromNode.name,
hist: hist
};
//if 1st component append "new" to name
if (fromIds[0] === fromNode.id) {
NewRow.text = "new " + NewRow.text
}
//Add new family tree
// if (newParentId === "#") {
// NewRow.ft = "#"
// } else {
// NewRow.ft = compData[newParentId].ft + '/' + newParentId;
// }
//Add more properties to the new component obj if type = 'job' (ie component)
// if (fromNode.comType === 'job') {
// NewRow.enabled = fromNode.enabled;
// NewRow.promoted = fromNode.promoted;
NewRow.variables = {};
//copy vars that are not private
for (var ind in compData[fromId].variables) {
if (compData[fromId].variables.hasOwnProperty(ind)) {
if (!fromNode.variables[ind].private) {
NewRow.variables[ind] = fromNode.variables[ind]
} else {
NewRow.variables[ind] = JSON.parse(JSON.stringify(fromNode.variables[ind]));
NewRow.variables[ind].value = "";
}
}
}
// NewRow.icon = fromNode.icon;
NewRow.script = fromNode.script;
// if (fromNode.hasOwnProperty('thumbnail')) {
// NewRow.thumbnail = fromNode.thumbnail;
// }
// }
compData[id] = NewRow;
//Copy file resources
// if (fs.existsSync(filesPath + fromId)) { //copy file resources if they exist
// fs.mkdirSync(filesPath + id);
// const files = fs.readdirSync(filesPath + fromId);
// files.forEach(function (file) {
// if (!fs.lstatSync(filesPath + fromId + '/' + file).isDirectory()) {
// const targetFile = filesPath + id + '/' + file;
// const source = filesPath + fromId + '/' + file;
// fs.writeFileSync(targetFile, fs.readFileSync(source))
// }
// })
// }
});
//add new sort order value to the 1st id
var posInt = parseInt(position, 10);
for (var key in compData) {
if (compData[key].parent === targetId) {
if (compData[key].sort >= posInt) {
compData[key].sort = compData[key].sort + 1;
}
}
}
compData[idMap[fromIds[0]]].sort = posInt;
fixChildsSort(targetId, userID);
//Save compData and backup
saveAllJSON(true, userID, []);
//Return OK status
res.sendStatus(200);
res.end('');
//log("saving script"+ JSON.stringify(foundRow));
}
} else {
//error detected. Return error message
res.sendStatus(500);
res.end(errorMsg + " - " + errorID)
}
}
});
router.get("/move", function (req, res) {
//log("move...");
var userID = req.query.userID
if (!compDataObj[userID]) {
log("move error: compDataObj does not have property userID")
res.end("move error: compDataObj does not have property userID")
} else {
var compData = compDataObj[userID]
var id = req.query.id
var direction = req.query.direction[0]; //either u or d
var oldPos = compData[id].sort;
var otherId = "";
if (!id || !direction) {
res.end('');
}
var parent = compData[id].parent;
fixChildsSort(parent, userID);
var beforeId = '';
var afterId = '';
//get all siblings
var siblings = [];
for (var key in compData) {
if (compData.hasOwnProperty(key)) {
if (parent === compData[key].parent) {
//log("found: " , compData[key].name, compData[key].sort, parent , compData[key].parent);
siblings.push(key);
}
}
}
//sort
siblings.sort((a, b) => (compData[a].sort > compData[b].sort) ? 1 : -1);
//re-apply sort # because there could be dups or gaps
var x = 0;
for (var key in siblings) {
compData[siblings[key]].sort = x;
x++
}
//find the before and after ids
for (var key in siblings) {
if (compData[id].sort + 1 === compData[siblings[key]].sort) {
afterId = siblings[key]
}
if (compData[id].sort - 1 === compData[siblings[key]].sort) {
beforeId = siblings[key]
}
}
if (direction === 'u' && beforeId !== '') {
var tmp = compData[beforeId].sort;
compData[beforeId].sort = compData[id].sort;
compData[id].sort = tmp;
otherId = beforeId;
}
//set new sort para for current and after if down
if (direction === 'd' && afterId !== '') {
var tmp = compData[afterId].sort;
compData[afterId].sort = compData[id].sort;
compData[id].sort = tmp;
otherId = afterId;
}
//Save the resorted SystemJSON
saveAllJSON(true, userID, []);
var newPos = compData[id].sort;
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ "newPos": newPos, "oldPos": oldPos, "otherId": otherId }));
}
});
router.get("/getBackup", function (req, res) {
res.writeHead(200, { "Content-Type": "application/json" });
var userID = req.query.userID
var id = req.query.id
var idx = req.query.idx
let backup = {}
if (!compDataObj[userID]) {
log("getBackup error: compDataObj does not have property userID")
res.end("getBackup error: compDataObj does not have property userID")
} else {
backup = compDataObj[userID][id].backups[idx]
res.end(JSON.stringify(backup))
}
})
router.get("/getPromoted", function (req, res) {
res.writeHead(200, { "Content-Type": "application/json" });
var userID = req.query.userID
function findProm(compData, retArr) {
for (var key in compData) {
if (compData[key].hasOwnProperty("variables")) {
if (compData[key].variables["promoted"]) {
if (compData[key].variables["promoted"].value.trim() === "true") {
let icon = compData[key].variables["icon"] ? compData[key].variables["icon"].value.trim() : ""
let onclickJob = compData[key].variables["onclickJob"] ? compData[key].variables["onclickJob"].value.trim() : ""
let text = compData[key].text ? compData[key].text : ""
retArr.push({ "id": compData[key].id, "icon": icon, "text": text, "onclickJob": onclickJob })
}
}
}
}
}
var retArr = []
if (!compDataObj[userID]) {
fs.readFile(__dirname + '/compData/compData.' + userID + '.json', (err, data) => {
if (!err && data) {
compDataObj[userID] = JSON.parse(data)
let compData = compDataObj[userID]
findProm(compData, retArr)
res.end(JSON.stringify(retArr));
} else {
log("loadSavedComps error: compDataObj does not have property userID")
}
})
} else {
let compData = compDataObj[userID]
findProm(compData, retArr)
res.end(JSON.stringify(retArr));
}
})
router.get("/SetAttrib", function (req, res) {
var userID = req.query.userID ? req.query.userID : ""
var id = req.query.id ? req.query.id : ""
var attrib = req.query.attrib ? req.query.attrib : ""
var value = req.query.value ? req.query.value : ""
if (!compDataObj[userID] || userID == 0) {
log("SetAttrib error: compDataObj does not have property userID")
res.end("SetAttrib error: compDataObj does not have property userID")
} else {
if (attrib == "enabled") {
compDataObj[userID][id].enabled = value
}
saveAllJSON(false, userID, []);
res.end("");
}
});
function fixChildsSort(parentId, userID) {
if (!compDataObj[userID]) {
log("fixChildsSort error: compDataObj does not have property userID")
res.end("fixChildsSort error: compDataObj does not have property userID")
} else {
var compData = compDataObj[userID]
//get all siblings
var siblings = [];
for (var key in compData) {
if (compData.hasOwnProperty(key)) {
if (parentId === compData[key].parent) {
siblings.push(key);
}
}
}
//sort
siblings.sort((a, b) => (compData[a].sort > compData[b].sort) ? 1 : -1);
//re-apply sort # because there could be dups or gaps
var x = 0;
for (var key in siblings) {
compData[siblings[key]].sort = x;
x++
}
}
}
var connections = []
//Create and register connection or lookup connection
function getConn(conOptions, callback) {
let token = conOptions.token
let userID = conOptions.userID
let name = conOptions.name
let ids = conOptions.ids
let ws = conOptions.ws
let key = conOptions.key
let props = conOptions.props
let conn = false
connections.forEach(function (value, index, array) {
if (value.token === token) {
conn = connections[index]
log("Found connection for " + name)
}
});
//clear results from all components to be run
if (compDataObj[userID]) {
for (idx in ids) {
compDataObj[userID][ids[idx]].results = []
}
}
if (conn) {
conn.key = key
if (ids) {
const req = { "id": ids[0], "varName": "", "varVal": "", "props": props }
conn.reqs.push(req)
ids.shift()
for (idx in ids) {
conn.reqs.push({ "id": ids[idx], "varName": "", "varVal": "", "props": "" })
}
}
callback(conn)
} else {
log("Add connection to " + connections.length + " for " + name)
let c = new Client();
if (!conOptions.username || !conOptions.privateKey || !conOptions.host) {
let mess = JSON.stringify({
"message": "\r\n# Not Connected to SSH host\r\n",
"status": "down"
})
ws.send(mess)
} else {
try {
c.connect(conOptions);
c.on('error', function (err) {
log('SSH - Connection Error for ' + name + ': ' + err);
let mess = JSON.stringify({
"message": "\r\n# Error: Connection error\r\n" + err + "\r\n",
"status": "down"
})
ws.send(mess)
connections.every((element, index, array) => {
if (element.token === token) {
log("connection error - delete connections[" + index + "] for " + element.name)
// delete connections[index]
connections.splice(index, 1)
return false;
}
return true;
});
});
//connection end event.
c.on('end', function () {
log('SSH - Connection ended');
let mess = JSON.stringify({
"message": "\r\n# SSH connection ended\r\n",
"status": "down"
})
ws.send(mess)
connections.every((element, index, array) => {
if (element.token === token) {
log("connection end - delete connections[" + index + "] for " + element.name)
// delete connections[index]
connections.splice(index, 1)
return false;
}
return true;
});
});
//connection ready event.
c.on('ready', function () {
c.shell(function (err, stream) {
let token = generateUUID()
let conObj = { "err": err, "conn": c, "stream": stream, "token": token, "userID": userID, "key": key, "ws": ws, "name": name, "reqs": [{ "id": ids[0], "varName": "", "varVal": "", "props": props }], "jConn": [], "jStream": [] }
ids.shift()
for (idx in ids) {
conObj.reqs.push({ "id": ids[idx], "varName": "", "varVal": "", "props": "" })
}
connections.push(conObj)
stream.token = token
streamEvents(conObj)
let mess = JSON.stringify({
"status": "up"
})
ws.send(mess)
stream.write(' stty cols 200' + '\n' + ' PS1="[ceStack]$PS1"' + '\n'); //insert [ceStack] into the current prompt
if (!compDataObj[userID]) {
fs.readFile(__dirname + '/compData/compData.' + userID + '.json', (err, data) => {
if (!err && data) {
compDataObj[userID] = JSON.parse(data)
callback(conObj)
} else {
callback(conObj)
}
})
} else {
callback(conObj)
}
})
});
} catch (error) {
log('SSH - Connection Error for ' + name + ': ' + error);
let mess = JSON.stringify({
"message": "# Error: Connection error\r\n" + error + "\r\n",
"status": "down"
})
ws.send(mess)
}
}
}
}
function jump(newHost, conn) {
var currentUser = conn.conn._chanMgr._client.config.username
if (newHost.includes("@")) {
currentUser = newHost.split("@")[0]
newHost = newHost.split("@")[1]
}
log('Jump to: ' + currentUser + "@" + newHost + " for " + conn.name);
conn.jConn.push(true)
conn.jStream.push(true)
const jumpConn = new Client()
let privKey = conn.conn._chanMgr._client.config.privateKey
const destinationSSH = {
host: newHost,
port: 22,
username: currentUser,
privateKey: privKey
}
srcHost = 'localhost'
forwardConfig = {
srcHost: srcHost, // source host
// srcPort: 8000 + randomIntFromInterval(700, 999), // source port
srcPort: 22, // source port
dstHost: destinationSSH.host, // destination host
dstPort: destinationSSH.port // destination port
};
var fConn
if (conn.jConn.length < 2) {
fConn = conn.conn
} else {
fConn = conn.jConn[conn.jConn.length - 2]
}
fConn.forwardOut(forwardConfig.srcHost, forwardConfig.srcPort, forwardConfig.dstHost, forwardConfig.dstPort, (err, fwdStream) => {
if (err) {
log('forwardOut error: for ' + conn.name + ": " + err.message);
let mess = JSON.stringify({
"message": "\r\n# Jump error: " + err.message
})
conn.ws.send(mess)
conn.jStream.pop()
if (conn.jConn.length < 1) {
conn.stream.write('\n')
} else {
conn.jStream[conn.jConn.length - 1].write('\n')
}
} else {
jumpConn.connect({
sock: fwdStream,
username: destinationSSH.username,
privateKey: destinationSSH.privateKey,
readyTimeout: 5000
});
}
jumpConn.on('ready', function () {
jumpConn.shell(function (err, stream) {
let ws = conn.ws
conn.jConn.pop()
conn.jStream.pop()
conn.jConn.push(jumpConn)
conn.jStream.push(stream)
jumpEvents(conn, stream)
conn.jStream[conn.jStream.length - 1].write(' stty cols 200' + '\n' + ' PS1="[ceStack]$PS1"' + '\n'); //insert [ceStack] into the current prompt
})
});
jumpConn.on('error', function (err) {
log("Error connecting to jump server: " + forwardConfig.dstHost);
log(err.message);
let mess = JSON.stringify({
"message": "\r\nError connecting to jump server: " + forwardConfig.dstHost + "\r\n" + err.message + "\r\n"
})
conn.ws.send(mess)
conn.jConn.pop()
conn.jStream.pop()
if (conn.jConn.length < 1) {
conn.stream.write('\n')
} else {
conn.jStream[conn.jConn.length - 1].write('\n')
}
});
jumpConn.on('end', function () {
log('SSH - Jump connection ended');
let mess = JSON.stringify({
"message": "\r\n# SSH jump connection closed\r\n"
})
conn.ws.send(mess)
conn.jConn.pop()
conn.jStream.pop()
if (conn.jConn.length < 1) {
conn.stream.write('\n')
} else {
if (conn.jStream[conn.jConn.length - 1]) { conn.jStream[conn.jConn.length - 1].write('\n') }
}
});
});
}
function jumpEvents(conn, stream) {
// let stream = conn.jStream[conn.jStream.length - 1]
stream.on('data', function (data) {
processStreamData(conn, data, stream)
});
stream.on('close', function (code, signal) {
var dsString = new Date().toISOString(); //date stamp
log('Jump stream close: ' + dsString);
let mess = JSON.stringify({
"message": "\r\n# SSH Jump stream closed\r\n"
})
conn.ws.send(mess)
// conn.jStream.shift()
if (conn.jConn[conn.jConn.length - 1]) { conn.jConn[conn.jConn.length - 1].end() }
});
stream.stderr.on('data', function (data) {
var dsString = new Date().toISOString(); //date stamp
log('Jump stream stderr: ' + dsString + " for " + conn.name);
log(data.toString())
let mess = JSON.stringify({
"message": "\r\n# SSH Jump stream stderr\r\n"
})
conn.ws.send(mess)
// conn.jStream.pop()
conn.jConn[conn.jConn.length - 1].end()