forked from ioBroker/ioBroker.web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
1852 lines (1678 loc) · 80.9 KB
/
main.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
/* jshint -W097 */
/* jshint strict: false */
/* jslint node: true */
'use strict';
const express = require('express');
const fs = require('fs');
const path = require('path');
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const LE = utils.commonTools.letsEncrypt;
const mime = require('mime-types');
const adapterName = require('./package.json').name.split('.').pop();
const compression = require('compression');
const ONE_MONTH_SEC = 30 * 24 * 3600;
let session;// = require('express-session');
let cookieParser;// = require('cookie-parser');
let bodyParser;// = require('body-parser');
let AdapterStore;// = require(__dirname + '/../../lib/session.js')(session);
let passport;// = require('passport');
let LocalStrategy;// = require('passport-local').Strategy;
let flash;// = require('connect-flash'); // TODO report error to user
let webServer = null;
let store = null;
let secret = 'Zgfr56gFe87jJOM'; // Will be generated by first start
let socketUrl = '';
const cache = {}; // cached web files
let ownSocket = false;
let lang = 'en';
const extensions = {};
const bruteForce = {};
let socketIoFile = null;
const webPreSettings = {};
const webByVersion = {};
let loginPage = null;
const FORBIDDEN_CHARS = /[\][*,;'"`<>\\\s?]/g; // with space
const LOGIN_PAGE = '/login/index.html';
const wwwDir = 'www';
function getAppName() {
const parts = __dirname.replace(/\\/g, '/').split('/');
return parts[parts.length - 1].split('.')[0].toLowerCase();
}
utils.appName = getAppName();
// copied from here: https://github.com/component/escape-html/blob/master/index.js
const matchHtmlRegExp = /["'&<>]/;
function escapeHtml (string) {
const str = '' + string;
const match = matchHtmlRegExp.exec(str);
if (!match) {
return str;
}
let escape;
let html = '';
let index;
let lastIndex = 0;
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34: // "
escape = '"';
break;
case 38: // &
escape = '&';
break;
case 39: // '
escape = ''';
break;
case 60: // <
escape = '<';
break;
case 62: // >
escape = '>';
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
}
lastIndex = index + 1;
html += escape;
}
return lastIndex !== index
? html + str.substring(lastIndex, index)
: html;
}
async function getSocketUrl(obj) {
if (adapter.config.socketio && adapter.config.socketio.match(/^system\.adapter\./)) {
obj = obj || (await adapter.getForeignObjectAsync(adapter.config.socketio));
if (obj && obj.common && !obj.common.enabled) {
const state = await adapter.getForeignStateAsync(`${adapter.config.socketio}.alive`);
if (state && state.val) {
return `:${obj.native.port}`;
}
} else if (obj && obj.common && obj.common.enabled && obj.native) {
return `:${obj.native.port}`;
}
}
return '';
}
let adapter;
function startAdapter(options) {
options = options || {};
Object.assign(options, {
name: adapterName,
objectChange: (id, obj) => {
if (id.startsWith('system.adapter')) {
if (obj && obj.common && obj.common.webExtension && obj.native &&
(extensions[id.substring('system.adapter.'.length)] ||
obj.native.webInstance === '*' ||
obj.native.webInstance === adapter.namespace
)
) {
return adapter.setForeignState(`system.adapter.${adapter.namespace}.alive`, false, true, () =>
adapter.terminate ? adapter.terminate(-100) : process.exit(-100));
}
// 'system.adapter.'.length = 15
const _id = id.substring(15).replace(/\.\d+$/, '');
if (obj && obj.common && obj.common.webByVersion) {
webByVersion[_id] = obj.common.version;
} else if (webByVersion[_id]) {
delete webByVersion[_id];
}
}
if (obj && obj.common && obj.common.webPreSettings) {
updatePreSettings(obj);
}
if (!ownSocket && id === adapter.config.socketio) {
getSocketUrl(obj)
.then(_socketUrl => {
socketUrl = _socketUrl;
adapter.log.info(`SocketURL now "${socketUrl}"`);
});
}
if (id === 'system.config' && !adapter.config.language) {
lang = obj && obj.common && obj.common.language ? obj.common.language : 'en';
}
if (webServer && webServer.io) {
try {
webServer.io.publishAll('objectChange', id, obj);
} catch (e) {
adapter.log.error(`Cannot objectChange to io: ${e}`);
}
}
if (webServer && webServer.api) {
try {
webServer.api.objectChange && webServer.api.objectChange(id, obj);
} catch (e) {
adapter.log.error(`Cannot call objectChange for simple api: ${e.message}`);
}
}
// inform extensions
Object.keys(extensions).forEach(instance => {
try {
if (extensions[instance].obj && typeof extensions[instance].obj.objectChange === 'function') {
extensions[instance].obj.objectChange(id, obj);
}
} catch (err) {
adapter.log.error(`Cannot call objectChange for "${instance}": ${err.message}`);
}
});
},
stateChange: (id, state) => {
if (webServer && webServer.io) {
webServer.io.publishAll('stateChange', id, state);
}
if (webServer && webServer.api) {
try {
webServer.api.stateChange && webServer.api.stateChange(id, state);
} catch (e) {
adapter.log.error(`Cannot call stateChange for simple api: ${e.message}`);
}
}
// inform extensions
Object.keys(extensions).forEach(instance => {
try {
if (extensions[instance].obj && typeof extensions[instance].obj.stateChange === 'function') {
extensions[instance].obj.stateChange(id, state);
}
} catch (err) {
adapter.log.error(`Cannot call stateChange for "${instance}": ${err.message}`);
}
});
},
fileChange: (id, fileName, size) => {
if (webServer && webServer.io) {
webServer.io.publishFileAll(id, fileName, size);
}
if (webServer && webServer.api) {
try {
webServer.api.fileChange && webServer.api.fileChange(id, fileName, size);
} catch (e) {
adapter.log.error(`Cannot call fileChange for simple api: ${e.message}`);
}
}
// inform extensions
Object.keys(extensions).forEach(instance => {
try {
if (extensions[instance].obj && typeof extensions[instance].obj.fileChange === 'function') {
extensions[instance].obj.fileChange(id, fileName, size);
}
} catch (err) {
adapter.log.error(`Cannot call fileChange for "${instance}": ${err.message}`);
}
});
},
unload: callback => {
try {
const promises = [];
if (adapter.setStateAsync) {
promises.push(adapter.setStateAsync('info.connected', '', true));
promises.push(adapter.setStateAsync('info.connection', false, true));
}
Object.keys(extensions).forEach(instance => {
try {
if (extensions[instance] && extensions[instance].obj && extensions[instance].obj.unload) {
const promise = extensions[instance].obj.unload();
if (promise && typeof promise === 'object' && typeof promise.then === 'function') {
promises.push(promise
.catch(e =>
adapter && adapter.log && adapter.log.error(`Cannot unload web extension "${instance}": ${e}`)));
}
}
} catch (e) {
adapter && adapter.log && adapter.log.error(`Cannot unload web extension "${instance}": ${e}`);
}
});
let timeout;
if (promises.length) {
timeout = setTimeout(() => {
timeout = null;
adapter && adapter.log && adapter.log.warn(`Timeout by termination of web-extensions!`);
webServer && webServer.settings && adapter && adapter.log && adapter.log.debug(`terminating http${webServer.settings.secure ? 's' : ''} server on port ${webServer.settings.port}`);
webServer && webServer.io && webServer.io.close();
webServer && webServer.server && webServer.server.close();
webServer && webServer.settings && adapter && adapter.log && adapter.log.info(`terminated http${webServer.settings.secure ? 's' : ''} server on port ${webServer.settings.port}`);
callback && callback();
}, 500);
}
Promise.all(promises)
.catch(e => adapter && adapter.log && adapter.log.error(`Cannot unload web extensions: ${e}`))
.then(() => {
if (!promises.length || timeout) {
clearTimeout(timeout);
timeout = null;
webServer && webServer.settings && adapter && adapter.log && adapter.log.debug(`terminating http${webServer.settings.secure ? 's' : ''} server on port ${webServer.settings.port}`);
webServer && webServer.io && webServer.io.close();
webServer && webServer.server && webServer.server.close();
webServer && webServer.settings && adapter && adapter.log && adapter.log.info(`terminated http${webServer.settings.secure ? 's' : ''} server on port ${webServer.settings.port}`);
callback && callback();
}
});
} catch (e) {
callback();
}
},
ready: async () => {
// Generate secret for session manager
const systemConfig = await adapter.getForeignObjectAsync('system.config');
if (systemConfig) {
if (!systemConfig.native || !systemConfig.native.secret) {
systemConfig.native = systemConfig.native || {};
const buf = await new Promise(resolve => require('crypto').randomBytes(24, (ex, buf) => resolve(buf)));
secret = buf.toString('hex');
await adapter.extendForeignObjectAsync('system.config', {native: {secret}});
} else {
secret = systemConfig.native.secret;
}
} else {
adapter.log.error('Cannot find object system.config');
}
// information about connected socket.io adapter
if (adapter.config.socketio && adapter.config.socketio.match(/^system\.adapter\./)) {
socketUrl = await getSocketUrl();
// Listen for changes
await adapter.subscribeForeignObjectsAsync(adapter.config.socketio);
} else {
socketUrl = adapter.config.socketio;
ownSocket = socketUrl !== 'none';
}
// Read language
if (adapter.config.language) {
lang = adapter.config.language;
} else
if (systemConfig && systemConfig.common) {
lang = systemConfig.common.language || 'en';
}
main();
}
});
adapter = new utils.Adapter(options);
return adapter;
}
function extractPreSetting(obj, attr) {
const parts = attr.split('.');
if (parts.length === 1) {
if ((obj && typeof obj === 'object') || (obj !== null && obj !== undefined)) {
return obj[attr];
} else {
return null;
}
} else {
attr = parts.shift();
if (obj[attr] && typeof obj[attr] === 'object') {
return extractPreSetting(obj[attr], parts.join('.'));
} else {
return null;
}
}
}
function updatePreSettings(obj) {
if (!obj || !obj.common) {
return;
}
if (obj.common.webPreSettings) {
for (const attr of Object.keys(obj.common.webPreSettings)) {
webPreSettings[obj._id] = webPreSettings[obj._id] || {};
const _attr = attr.replace(/[^\w0-9]/g, '_');
webPreSettings[obj._id][_attr] = extractPreSetting(obj, obj.common.webPreSettings[attr]);
if (typeof webPreSettings[obj._id][_attr] === 'object') {
webPreSettings[obj._id][_attr] = JSON.stringify(webPreSettings[obj._id][_attr]);
} else {
webPreSettings[obj._id][_attr] = webPreSettings[obj._id][_attr].replace(/"/g, '\\"');
}
}
} else if (webPreSettings[obj._id]) {
delete webPreSettings[obj._id];
}
}
function getExtensionsAndSettings(callback) {
adapter.getObjectView('system', 'instance', null, (err, doc) => {
if (err) {
callback && callback(err, []);
} else {
if (doc.rows.length === 0) {
callback && callback(null, []);
} else {
const res = [];
for (let i = 0; i < doc.rows.length; i++) {
const instance = doc.rows[i].value;
if (instance && instance.common) {
if (instance.common.enabled &&
instance.common.webExtension &&
(instance.native.webInstance === adapter.namespace || instance.native.webInstance === '*')) {
// decrypt all native attributes listed in instance.encryptedNative
if (Array.isArray(instance.encryptedNative) && instance.native) {
instance.encryptedNative.forEach(key => {
if (instance.native[key]) {
instance.native[key] = adapter.decrypt(secret, instance.native[key]);
}
});
}
res.push(instance);
}
if (instance.common.webPreSettings) {
updatePreSettings(instance);
}
if (instance.common.webByVersion) {
// 'system.adapter.'.length = 15
const _id = doc.rows[i].value._id.substring(15).replace(/\.\d+$/, '');
webByVersion[_id] = instance.common.version;
}
}
}
callback && callback(null, res);
}
}
});
}
function main() {
getExtensionsAndSettings((err, ext) => {
err && adapter.log.error(`Cannot read extensions: ${err}`);
if (ext) {
for (let e = 0; e < ext.length; e++) {
if (ext[e] && ext[e].common) {
const instance = ext[e]._id.substring('system.adapter.'.length);
const name = instance.split('.')[0];
extensions[instance] = {
path: name + '/' + ext[e].common.webExtension,
config: ext[e]
};
}
}
}
// TODO: This whole setting of webServer global is pretty nasty, needs cleaning up.
initWebServer(adapter.config)
.then(returnedServer => webServer = returnedServer)
.catch(err => {
adapter.log.error(`Failed to initWebServer: ${err}`);
adapter.terminate ? adapter.terminate(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION) : process.exit(utils.EXIT_CODES.ADAPTER_REQUESTED_TERMINATION);
});
// monitor extensions and pro keys
adapter.subscribeForeignObjects('system.adapter.*');
});
}
/* function readDirs(dirs, cb, result) {
result = result || [];
if (!dirs || !dirs.length) {
return cb && cb(result);
}
const dir = dirs.shift();
adapter.readDir(dir, '', (err, files) => {
if (!err && files && files.length) {
for (let f = 0; f < files.length; f++) {
if (files[f].file.match(/\.html$/)) {
result.push(dir + '/' + files[f].file);
}
}
}
setImmediate(readDirs, dirs, cb, result);
});
}
*/
let indexHtml;
function getLinkVar(_var, obj, attr, link) {
if (attr === 'protocol') {
attr = 'secure';
}
if (_var === 'ip') {
link = link.replace(`%${_var}%`, '$host$');
} else
if (_var === 'instance') {
const instance = obj._id.split('.').pop();
link = link.replace(`%${_var}%`, instance);
} else {
if (obj) {
if (attr.startsWith('native_')) {
attr = attr.substring(7);
}
let val = obj.native[attr];
if (_var === 'bind' && (!val || val === '0.0.0.0')) {
val = '$host$';
}
if (attr === 'secure') {
link = link.replace(`%${_var}%`, val ? 'https' : 'http');
} else {
if (!link.includes(`%${_var}%`)) {
link = link.replace(`%native_${_var}%`, val);
} else {
link = link.replace(`%${_var}%`, val);
}
}
} else {
if (attr === 'secure') {
link = link.replace(`%${_var}%`, 'http');
} else {
if (!link.includes(`%${_var}%`)) {
link = link.replace(`%native_${_var}%`, '');
} else {
link = link.replace(`%${_var}%`, '');
}
}
}
}
return link;
}
function resolveLink(link, instanceObj, instancesMap) {
const vars = link.match(/%(\w+)%/g);
let _var;
let v;
let parts;
let result;
if (vars) {
// first replace simple patterns
for (v = vars.length - 1; v >= 0; v--) {
_var = vars[v];
_var = _var.replace(/%/g, '');
parts = _var.split('_');
// like "port"
if (_var.startsWith('native_')) {
link = getLinkVar(_var, instanceObj, _var, link);
vars.splice(v, 1);
} else
if (parts.length === 1) {
link = getLinkVar(_var, instanceObj, parts[0], link);
vars.splice(v, 1);
} else
// like "web.0_port"
if (parts[0].match(/\.\d+$/)) {
link = getLinkVar(_var, instancesMap[`system.adapter.${parts[0]}`], parts[1], link);
vars.splice(v, 1);
}
}
const links = {};
let instances;
const adptr = parts[0];
// process web_port
for (v = 0; v < vars.length; v++) {
_var = vars[v];
_var = _var.replace(/%/g, '');
if (_var.startsWith('native_')) {
_var = _var.substring(7);
}
parts = _var.split('_');
if (!instances) {
instances = [];
// TODO !
/*for (let inst = 0; inst < 10; inst++) {
if (that.main.objects[`system.adapter.${adptr}.${inst}`]) {
instances.push(inst);
}
}*/
}
for (let i = 0; i < instances.length; i++) {
links[adptr + '.' + i] = {
instance: `${adptr}.${i}`,
link: getLinkVar(_var, instancesMap[`system.adapter.${adptr}.${i}`], parts[1], links[`${adptr}.${i}`] ? links[adptr + '.' + i].link : link)
};
}
}
if (instances) {
result = [];
let count = 0;
let firstLink = '';
for (const d of Object.keys(links)) {
result[links[d].instance] = links[d].link;
firstLink = firstLink || links[d].link;
count++;
}
if (count < 2) {
link = firstLink;
result = null;
}
}
}
return result || link;
}
/*function replaceInLink(link, instanceObj, instances) {
if (typeof link === 'object') {
const links = JSON.parse(JSON.stringify(link));
let first = '';
for (const v of Object.keys(links)) {
links[v] = resolveLink(links[v], instanceObj, instances);
first = first || links[v];
}
links.__first = first;
return links;
} else {
return resolveLink(link, instanceObj, instances);
}
}*/
function processWelcome(welcomeScreen, isPro, adapterObj, foundInstanceIDs, list) {
if (welcomeScreen) {
welcomeScreen = JSON.parse(JSON.stringify(welcomeScreen));
if (Array.isArray(welcomeScreen)) {
for (let w = 0; w < welcomeScreen.length; w++) {
// temporary disabled for non-pro
if (!isPro && welcomeScreen[w].name === 'vis editor') {
continue;
}
if (welcomeScreen[w].localLinks && typeof welcomeScreen[w].localLinks === 'string') {
welcomeScreen[w].localLink = adapterObj.common.localLinks[welcomeScreen[w].localLinks];
if (typeof welcomeScreen[w].localLink === 'object') {
welcomeScreen[w].localLink = welcomeScreen[w].localLink.link;
}
} else
if (welcomeScreen[w].localLink && typeof welcomeScreen[w].localLink === 'boolean') {
welcomeScreen[w].localLink = adapterObj.common.localLink;
}
welcomeScreen[w].pro = isPro;
if (welcomeScreen[w].localLink) {
if (foundInstanceIDs.length > 1) {
foundInstanceIDs.forEach(id => {
const _welcomeScreen = JSON.parse(JSON.stringify(welcomeScreen));
_welcomeScreen.id = id;
_welcomeScreen.instance = parseInt(id.split('.').pop(), 10);
list.push(_welcomeScreen);
});
} else {
welcomeScreen[w].id = foundInstanceIDs[0];
list.push(welcomeScreen[w]);
}
} else {
list.push(welcomeScreen[w]);
}
}
} else {
if (welcomeScreen.localLinks && typeof welcomeScreen.localLinks === 'string') {
welcomeScreen.localLink = adapterObj.common.localLinks[welcomeScreen.localLinks];
if (typeof welcomeScreen.localLink === 'object') {
welcomeScreen.localLink = welcomeScreen.localLink.link;
}
} else
if (welcomeScreen.localLink && typeof welcomeScreen.localLink === 'boolean') {
welcomeScreen.localLink = adapterObj.common.localLink;
}
welcomeScreen.pro = isPro;
if (welcomeScreen.localLink) {
if (foundInstanceIDs.length > 1) {
foundInstanceIDs.forEach(id => {
const _welcomeScreen = JSON.parse(JSON.stringify(welcomeScreen));
_welcomeScreen.id = id;
_welcomeScreen.instance = parseInt(id.split('.').pop(), 10);
list.push(_welcomeScreen);
});
} else {
welcomeScreen.id = foundInstanceIDs[0];
list.push(welcomeScreen);
}
} else {
list.push(welcomeScreen);
}
}
}
}
function getListOfAllAdapters(settings, server, req, callback) {
// read all instances
adapter.getObjectView('system', 'instance', {}, (err, instances) => {
adapter.getObjectView('system', 'adapter', {}, (err, adapters) => {
try {
const list = [];
const mapInstance = {};
for (let r = 0; r < instances.rows.length; r++) {
mapInstance[instances.rows[r].id] = instances.rows[r].value;
}
for (let a = 0; a < adapters.rows.length; a++) {
const obj = adapters.rows[a].value;
let found;
if (instances && instances.rows) {
found = [];
// find if any instance of this adapter is exists and started
for (let i = 0; i < instances.rows.length; i++) {
let id = instances.rows[i].id;
const ids = id.split('.');
ids.pop();
id = ids.join('.');
if (id === obj._id && instances.rows[i].value.common && (true || instances.rows[i].value.common.enabled || instances.rows[i].value.common.onlyWWW)) {
found.push(instances.rows[i].id);
}
}
}
if (found && found.length) {
processWelcome(obj.common.welcomeScreen, false, obj, found, list);
processWelcome(obj.common.welcomeScreenPro, true, obj, found, list);
/*if (obj.common.welcomeScreen || obj.common.welcomeScreenPro) {
if (obj.common.welcomeScreen) {
if (obj.common.welcomeScreen instanceof Array) {
for (let w = 0; w < obj.common.welcomeScreen.length; w++) {
// temporary disabled
if (obj.common.welcomeScreen[w].name === 'vis editor') {
continue;
}
if (obj.common.welcomeScreen[w].localLinks && typeof obj.common.welcomeScreen[w].localLinks === 'string') {
obj.common.welcomeScreen[w].localLink = obj.common.localLinks[obj.common.welcomeScreen[w].localLinks];
if (typeof obj.common.welcomeScreen[w].localLink === 'object') {
obj.common.welcomeScreen[w].localLink = obj.common.welcomeScreen[w].localLink.link;
}
} else
if (obj.common.welcomeScreen[w].localLink && typeof obj.common.welcomeScreen[w].localLink === 'boolean') {
obj.common.welcomeScreen[w].localLink = obj.common.localLink;
}
if (obj.common.welcomeScreen[w].localLink) {
if (found.length > 1) {
found.forEach(id => {
const welcomeScreen = JSON.stringify(JSON.parse(obj.common.welcomeScreen[w]));
welcomeScreen.id = id;
list.push(welcomeScreen);
});
} else {
obj.common.welcomeScreen[w].id = found[0];
list.push(obj.common.welcomeScreen[w]);
}
} else {
list.push(obj.common.welcomeScreen[w]);
}
}
} else {
if (obj.common.welcomeScreen.localLinks && typeof obj.common.welcomeScreen.localLinks === 'string') {
obj.common.welcomeScreen.localLink = obj.common.localLinks[obj.common.welcomeScreen.localLinks];
if (typeof obj.common.welcomeScreen.localLink === 'object') {
obj.common.welcomeScreen.localLink = obj.common.welcomeScreen.localLink.link;
}
} else
if (obj.common.welcomeScreen.localLink && typeof obj.common.welcomeScreen.localLink === 'boolean') {
obj.common.welcomeScreen.localLink = obj.common.localLink;
}
if (obj.common.welcomeScreen.localLink) {
if (found.length > 1) {
found.forEach(id => {
const welcomeScreen = JSON.stringify(JSON.parse(obj.common.welcomeScreen));
welcomeScreen.id = id;
list.push(welcomeScreen);
});
} else {
obj.common.welcomeScreen.id = found[0];
list.push(obj.common.welcomeScreen);
}
} else {
list.push(obj.common.welcomeScreen);
}
}
}
if (obj.common.welcomeScreenPro) {
if (obj.common.welcomeScreenPro instanceof Array) {
for (let ww = 0; ww < obj.common.welcomeScreenPro.length; ww++) {
const tile = Object.assign({}, obj.common.welcomeScreenPro[ww]);
tile.pro = true;
if (tile.localLinks && typeof tile.localLinks === 'string') {
tile.localLink = obj.common.localLinks[tile.localLinks];
if (typeof tile.localLink === 'object') {
tile.localLink = tile.localLink.link;
}
} else
if (tile.localLink && typeof tile.localLink === 'boolean') {
tile.localLink = obj.common.localLink;
}
if (tile.localLink) {
tile.id = found;
}
list.push(tile);
}
} else {
const tile_ = Object.assign({}, obj.common.welcomeScreenPro);
tile_.pro = true;
if (tile_.localLinks && typeof tile_.localLinks === 'string') {
tile_.localLink = obj.common.localLinks[tile_.localLinks];
if (typeof tile_.localLink === 'object') {
tile_.localLink = tile_.localLink.link;
}
} else
if (tile_.localLink && typeof tile_.localLink === 'boolean') {
tile_.localLink = obj.common.localLink;
}
if (tile_.localLink) {
if (found.length > 1) {
found.forEach(id => {
const welcomeScreen = JSON.stringify(JSON.parse(obj.common.tile_));
welcomeScreen.id = id;
list.push(welcomeScreen);
});
} else {
tile_.id = found[0];
list.push(obj.common.welcomeScreen);
}
} else {
list.push(tile_);
}
}
}
}*/
}
}
if (!indexHtml && !fs.existsSync(`${__dirname}/${wwwDir}/index.html`)) {
return callback(null, `${__dirname}/${wwwDir}/index.html was not found or no access! Check the file or access rights or start the fixer: "curl -sL https://iobroker.net/fix.sh | bash -"`);
}
indexHtml = indexHtml || fs.readFileSync(`${__dirname}/${wwwDir}/index.html`).toString();
// calculate localLinks
for (let t = 0; t < list.length; t++) {
if (list[t].localLink) {
list[t].localLink = resolveLink(list[t].localLink, mapInstance[list[t].id], mapInstance);
}
}
// try to find swagger web-extension
// inform extensions
Object.keys(extensions).forEach(instance => {
try {
if (extensions[instance].obj && typeof extensions[instance].obj.welcomePage === 'function') {
list.push(extensions[instance].obj.welcomePage());
}
} catch (err) {
adapter.log.error(`Cannot call welcomePage for "${instance}": ${err.message}`);
}
});
list.sort((a, b) => {
const aName = (typeof a.name === 'object' ? a.name[lang] || a.name.en : a.name).toLowerCase();
const bName = (typeof b.name === 'object' ? b.name[lang] || b.name.en : b.name).toLowerCase();
if (a.order === undefined && b.order === undefined) {
if (aName > bName) {
return 1;
}
if (aName < bName) {
return -1;
}
return 0;
} else if (a.order === undefined) {
return -1;
} else if (b.order === undefined) {
return 1;
} else {
if (a.order > b.order) {
return 1;
}
if (a.order < b.order) {
return -1;
}
if (aName > bName) {
return 1;
}
if (aName < bName) {
return -1;
}
if (a.instance !== undefined && b.instance !== undefined) {
if (a.instance > b.instance) {
return 1;
}
if (a.instance < b.instance) {
return -1;
}
}
return 0;
}
});
let text = `systemLang = "${lang}";\n`;
text += `list = ${JSON.stringify(list, null, 2)};\n`;
const whiteListIp = isInWhiteList(settings, server, req);
// if login
text += `let authEnabled = ${adapter.config.auth && !adapter.config.basicAuth && !whiteListIp};\n`;
callback(null, indexHtml.replace('// -- PLACE THE LIST HERE --', text));
} catch (e) {
callback(e);
}
});
});
}
function getInfoJs(settings) {
const result = [
`var socketUrl = "${socketUrl}";`,
`var socketSession = "";`,
`window._authIoBroker = ${settings.auth};`,
`window.sysLang = "${lang}";`,
`window.socketForceWebSockets = ${settings.forceWebSockets ? 'true' : 'false'};`
];
for (const id of Object.keys(webPreSettings)) {
if (webPreSettings[id]) {
for (const attr of Object.keys(webPreSettings[id])) {
result.push(`window.${attr} = "${webPreSettings[id][attr]}";`);
}
}
}
return result.join(' ');
}
function prepareLoginTemplate() {
let def =
' font: 13px/20px \'Lucida Grande\', Tahoma, Verdana, sans-serif;\n' +
' color: #404040;\n' +
' background-color: #0ae;\n' +
' background-image: -webkit-gradient(linear, 0 0, 0 100%, color-stop(.5, rgba(255, 255, 255, .2)), color-stop(.5, transparent), to(transparent));\n' +
' background-image: -webkit-linear-gradient(rgba(255, 255, 255, .2) 50%, transparent 50%, transparent);\n' +
' background-image: -moz-linear-gradient(rgba(255, 255, 255, .2) 50%, transparent 50%, transparent);\n' +
' background-image: -ms-linear-gradient(rgba(255, 255, 255, .2) 50%, transparent 50%, transparent);\n' +
' background-image: -o-linear-gradient(rgba(255, 255, 255, .2) 50%, transparent 50%, transparent);\n' +
' background-image: linear-gradient(rgba(255, 255, 255, .2) 50%, transparent 50%, transparent);\n' +
' background-size: 50px 50px;\n'
;
const template = fs.readFileSync(`${__dirname}/${wwwDir}${LOGIN_PAGE}`).toString('utf8');
if (adapter.config.loginBackgroundColor) {
def = `background-color: ${adapter.config.loginBackgroundColor};\n`;
}
if (adapter.config.loginBackgroundImage) {
def += ` background-image: url(../${adapter.namespace}/login-bg.png);\n`;
}
return template.replace('background: black;', def);
}
function checkUser(username, password, cb) {
username = (username || '').toString().replace(FORBIDDEN_CHARS, '_').replace(/\s/g, '_').replace(/\./g, '_').toLowerCase();
if (bruteForce[username] && bruteForce[username].errors > 4) {
let minutes = Date.now() - bruteForce[username].time;
if (bruteForce[username].errors < 7) {
if (Date.now() - bruteForce[username].time < 60000) {
minutes = 1;
} else {
minutes = 0;
}
} else
if (bruteForce[username].errors < 10) {
if (Date.now() - bruteForce[username].time < 180000) {
minutes = Math.ceil((180000 - minutes) / 60000);
} else {
minutes = 0;
}
} else
if (bruteForce[username].errors < 15) {
if (Date.now() - bruteForce[username].time < 600000) {
minutes = Math.ceil((600000 - minutes) / 60000);
} else {
minutes = 0;
}
} else
if (Date.now() - bruteForce[username].time < 3600000) {
minutes = Math.ceil((3600000 - minutes) / 60000);
} else {
minutes = 0;
}
if (minutes) {
return cb(`Too many errors. Try again in ${minutes} ${minutes === 1 ? 'minute' : 'minutes'}.`, false);
}
}
adapter.checkPassword(username, password, res => {
if (!res) {
bruteForce[username] = bruteForce[username] || {errors: 0};
bruteForce[username].time = Date.now();
bruteForce[username].errors++;
} else if (bruteForce[username]) {
delete bruteForce[username];
}
if (res) {
return cb(null, username);
} else {
return cb(null, false);
}
});
}
function initAuth(server, settings) {
session = require('express-session');
cookieParser = require('cookie-parser');
bodyParser = require('body-parser');
AdapterStore = utils.commonTools.session(session, settings.ttl);
passport = require('passport');
LocalStrategy = require('passport-local').Strategy;
flash = require('connect-flash'); // TODO report error to user
store = new AdapterStore({adapter});
passport.use(new LocalStrategy(checkUser));
passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((user, done) => done(null, user));