Changed var to const at many places.
Ylian Saint-Hilaire committed
Apr 14, 2022 at 13:07 UTC
a4a5aea4d477900d8250b45258356fc6e38681c8
1 file changed
+119
-116
meshcentral.js
+119
-116
@@ -20,7 +20,7 @@ const common = require('./common.js');
20
if (process.argv[2] == '--launch') { try { require('appmetrics-dash').monitor({ url: '/', title: 'MeshCentral', port: 88, host: '127.0.0.1' }); } catch (ex) { } }
21
22
function CreateMeshCentralServer(config, args) {
23
- var obj = {};
23
+ const obj = {};
24
obj.db = null;
25
obj.webserver = null;
26
obj.redirserver = null;
@@ -107,8 +107,8 @@ function CreateMeshCentralServer(config, args) {
107
}
108
109
// Clean up any temporary files
110
- var removeTime = new Date(Date.now()).getTime() - (30 * 60 * 1000); // 30 minutes
111
- var dir = obj.fs.readdir(obj.path.join(obj.filespath, 'tmp'), function (err, files) {
110
+ const removeTime = new Date(Date.now()).getTime() - (30 * 60 * 1000); // 30 minutes
111
+ const dir = obj.fs.readdir(obj.path.join(obj.filespath, 'tmp'), function (err, files) {
112
if (err != null) return;
113
for (var i in files) { try { const filepath = obj.path.join(obj.filespath, 'tmp', files[i]); if (obj.fs.statSync(filepath).mtime.getTime() < removeTime) { obj.fs.unlink(filepath, function () { }); } } catch (ex) { } }
114
});
@@ -125,9 +125,9 @@ function CreateMeshCentralServer(config, args) {
125
obj.service = null;
126
obj.servicelog = null;
127
if (obj.platform == 'win32') {
128
- var nodewindows = require('node-windows');
128
+ const nodewindows = require('node-windows');
129
obj.service = nodewindows.Service;
130
- var eventlogger = nodewindows.EventLogger;
130
+ const eventlogger = nodewindows.EventLogger;
131
obj.servicelog = new eventlogger('MeshCentral');
132
}
133
@@ -137,7 +137,7 @@ function CreateMeshCentralServer(config, args) {
137
try { require('./pass').hash('test', function () { }, 0); } catch (ex) { console.log('Old version of node, must upgrade.'); return; } // TODO: Not sure if this test works or not.
138
139
// Check for invalid arguments
140
- var validArguments = ['_', 'user', 'port', 'aliasport', 'mpsport', 'mpsaliasport', 'redirport', 'rediraliasport', 'cert', 'mpscert', 'deletedomain', 'deletedefaultdomain', 'showall', 'showusers', 'showitem', 'listuserids', 'showusergroups', 'shownodes', 'showallmeshes', 'showmeshes', 'showevents', 'showsmbios', 'showpower', 'clearpower', 'showiplocations', 'help', 'exactports', 'xinstall', 'xuninstall', 'install', 'uninstall', 'start', 'stop', 'restart', 'debug', 'filespath', 'datapath', 'noagentupdate', 'launch', 'noserverbackup', 'mongodb', 'mongodbcol', 'wanonly', 'lanonly', 'nousers', 'mpspass', 'ciralocalfqdn', 'dbexport', 'dbexportmin', 'dbimport', 'dbmerge', 'dbfix', 'dbencryptkey', 'selfupdate', 'tlsoffload', 'userallowedip', 'userblockedip', 'swarmallowedip', 'agentallowedip', 'agentblockedip', 'fastcert', 'swarmport', 'logintoken', 'logintokenkey', 'logintokengen', 'mailtokengen', 'admin', 'unadmin', 'sessionkey', 'sessiontime', 'minify', 'minifycore', 'dblistconfigfiles', 'dbshowconfigfile', 'dbpushconfigfiles', 'dbpullconfigfiles', 'dbdeleteconfigfiles', 'vaultpushconfigfiles', 'vaultpullconfigfiles', 'vaultdeleteconfigfiles', 'configkey', 'loadconfigfromdb', 'npmpath', 'serverid', 'recordencryptionrecode', 'vault', 'token', 'unsealkey', 'name', 'log', 'dbstats', 'translate', 'createaccount', 'resetaccount', 'pass', 'removesubdomain', 'adminaccount', 'domain', 'email', 'configfile', 'maintenancemode', 'nedbtodb', 'removetestagents', 'agentupdatetest', 'hashpassword', 'hashpass', 'indexmcrec', 'mpsdebug', 'dumpcores'];
140
+ const validArguments = ['_', 'user', 'port', 'aliasport', 'mpsport', 'mpsaliasport', 'redirport', 'rediraliasport', 'cert', 'mpscert', 'deletedomain', 'deletedefaultdomain', 'showall', 'showusers', 'showitem', 'listuserids', 'showusergroups', 'shownodes', 'showallmeshes', 'showmeshes', 'showevents', 'showsmbios', 'showpower', 'clearpower', 'showiplocations', 'help', 'exactports', 'xinstall', 'xuninstall', 'install', 'uninstall', 'start', 'stop', 'restart', 'debug', 'filespath', 'datapath', 'noagentupdate', 'launch', 'noserverbackup', 'mongodb', 'mongodbcol', 'wanonly', 'lanonly', 'nousers', 'mpspass', 'ciralocalfqdn', 'dbexport', 'dbexportmin', 'dbimport', 'dbmerge', 'dbfix', 'dbencryptkey', 'selfupdate', 'tlsoffload', 'userallowedip', 'userblockedip', 'swarmallowedip', 'agentallowedip', 'agentblockedip', 'fastcert', 'swarmport', 'logintoken', 'logintokenkey', 'logintokengen', 'mailtokengen', 'admin', 'unadmin', 'sessionkey', 'sessiontime', 'minify', 'minifycore', 'dblistconfigfiles', 'dbshowconfigfile', 'dbpushconfigfiles', 'dbpullconfigfiles', 'dbdeleteconfigfiles', 'vaultpushconfigfiles', 'vaultpullconfigfiles', 'vaultdeleteconfigfiles', 'configkey', 'loadconfigfromdb', 'npmpath', 'serverid', 'recordencryptionrecode', 'vault', 'token', 'unsealkey', 'name', 'log', 'dbstats', 'translate', 'createaccount', 'resetaccount', 'pass', 'removesubdomain', 'adminaccount', 'domain', 'email', 'configfile', 'maintenancemode', 'nedbtodb', 'removetestagents', 'agentupdatetest', 'hashpassword', 'hashpass', 'indexmcrec', 'mpsdebug', 'dumpcores'];
141
for (var arg in obj.args) { obj.args[arg.toLocaleLowerCase()] = obj.args[arg]; if (validArguments.indexOf(arg.toLocaleLowerCase()) == -1) { console.log('Invalid argument "' + arg + '", use --help.'); return; } }
142
if (obj.args.mongodb == true) { console.log('Must specify: --mongodb [connectionstring] \r\nSee https://docs.mongodb.com/manual/reference/connection-string/ for MongoDB connection string.'); return; }
143
for (i in obj.config.settings) { obj.args[i] = obj.config.settings[i]; } // Place all settings into arguments, arguments have already been placed into settings so arguments take precedence.
@@ -208,7 +208,7 @@ function CreateMeshCentralServer(config, args) {
208
// Perform translation operations
209
var didSomething = false;
210
process.chdir(obj.path.join(__dirname, 'translate'));
211
- var translateEngine = require('./translate/translate.js')
211
+ const translateEngine = require('./translate/translate.js')
212
if (customTranslation == true) {
213
// Translate all of the default files using custom translation file
214
translateEngine.startEx(['', '', 'minifyall']);
@@ -271,7 +271,8 @@ function CreateMeshCentralServer(config, args) {
271
if (obj.args.install == true) {
272
// Install MeshCentral in Systemd
273
console.log('Installing MeshCentral as background Service...');
274
- var userinfo = require('os').userInfo(), systemdConf = null;
274
+ var systemdConf = null;
275
+ const userinfo = require('os').userInfo();
276
if (require('fs').existsSync('/etc/systemd/system')) { systemdConf = '/etc/systemd/system/meshcentral.service'; }
277
else if (require('fs').existsSync('/lib/systemd/system')) { systemdConf = '/lib/systemd/system/meshcentral.service'; }
278
else if (require('fs').existsSync('/usr/lib/systemd/system')) { systemdConf = '/usr/lib/systemd/system/meshcentral.service'; }
@@ -279,8 +280,8 @@ function CreateMeshCentralServer(config, args) {
280
console.log('Writing config file...');
281
require('child_process').exec('which node', {}, function (error, stdout, stderr) {
282
if ((error != null) || (stdout.indexOf('\n') == -1)) { console.log('ERROR: Unable to get node location: ' + error); process.exit(); return; }
282
- var nodePath = stdout.substring(0, stdout.indexOf('\n'));
283
- var config = '[Unit]\nDescription=MeshCentral Server\n\n[Service]\nType=simple\nLimitNOFILE=1000000\nExecStart=' + nodePath + ' ' + __dirname + '/meshcentral\nWorkingDirectory=' + userinfo.homedir + '\nEnvironment=NODE_ENV=production\nUser=' + userinfo.username + '\nGroup=' + userinfo.username + '\nRestart=always\n# Restart service after 10 seconds if node service crashes\nRestartSec=10\n# Set port permissions capability\nAmbientCapabilities=cap_net_bind_service\n\n[Install]\nWantedBy=multi-user.target\n';
283
+ const nodePath = stdout.substring(0, stdout.indexOf('\n'));
284
+ const config = '[Unit]\nDescription=MeshCentral Server\n\n[Service]\nType=simple\nLimitNOFILE=1000000\nExecStart=' + nodePath + ' ' + __dirname + '/meshcentral\nWorkingDirectory=' + userinfo.homedir + '\nEnvironment=NODE_ENV=production\nUser=' + userinfo.username + '\nGroup=' + userinfo.username + '\nRestart=always\n# Restart service after 10 seconds if node service crashes\nRestartSec=10\n# Set port permissions capability\nAmbientCapabilities=cap_net_bind_service\n\n[Install]\nWantedBy=multi-user.target\n';
285
require('child_process').exec('echo \"' + config + '\" | sudo tee ' + systemdConf, {}, function (error, stdout, stderr) {
286
if ((error != null) && (error != '')) { console.log('ERROR: Unable to write config file: ' + error); process.exit(); return; }
287
console.log('Enabling service...');
@@ -363,7 +364,7 @@ function CreateMeshCentralServer(config, args) {
364
// Build MeshCentral parent path and Windows Service path
365
var mcpath = __dirname;
366
if (mcpath.endsWith('\\node_modules\\meshcentral') || mcpath.endsWith('/node_modules/meshcentral')) { mcpath = require('path').join(mcpath, '..', '..'); }
366
- var servicepath = obj.path.join(mcpath, 'WinService');
367
+ const servicepath = obj.path.join(mcpath, 'WinService');
368
369
// Check if we need to install, start, stop, remove ourself as a background service
370
if (((obj.args.xinstall == true) || (obj.args.xuninstall == true) || (obj.args.start == true) || (obj.args.stop == true) || (obj.args.restart == true))) {
@@ -376,7 +377,7 @@ function CreateMeshCentralServer(config, args) {
377
else if (obj.fs.existsSync(obj.path.join(__dirname, 'winservice.js'))) { serviceFilePath = obj.path.join(__dirname, 'winservice.js'); }
378
if (serviceFilePath == null) { console.log('Unable to find winservice.js'); return; }
379
379
- var svc = new obj.service({ name: 'MeshCentral', description: 'MeshCentral Remote Management Server', script: servicepath, env: env, wait: 2, grow: 0.5 });
380
+ const svc = new obj.service({ name: 'MeshCentral', description: 'MeshCentral Remote Management Server', script: servicepath, env: env, wait: 2, grow: 0.5 });
381
svc.on('install', function () { console.log('MeshCentral service installed.'); svc.start(); });
382
svc.on('uninstall', function () { console.log('MeshCentral service uninstalled.'); process.exit(); });
383
svc.on('start', function () { console.log('MeshCentral service started.'); process.exit(); });
@@ -432,10 +433,10 @@ function CreateMeshCentralServer(config, args) {
433
if (obj.args.vault) { obj.StartVault(); } else { obj.StartEx(); }
434
} else {
435
// if "--launch" is not specified, launch the server as a child process.
435
- var startArgs = [];
436
+ const startArgs = [];
437
for (i in process.argv) {
438
if (i > 0) {
438
- var arg = process.argv[i];
439
+ const arg = process.argv[i];
440
if ((arg.length > 0) && ((arg.indexOf(' ') >= 0) || (arg.indexOf('&') >= 0))) { startArgs.push(arg); } else { startArgs.push(arg); }
441
}
442
}
@@ -446,7 +447,7 @@ function CreateMeshCentralServer(config, args) {
447
448
// Launch MeshCentral as a child server and monitor it.
449
obj.launchChildServer = function (startArgs) {
449
- var child_process = require('child_process');
450
+ const child_process = require('child_process');
451
try { if (process.traceDeprecation === true) { startArgs.unshift('--trace-deprecation'); } } catch (ex) { }
452
childProcess = child_process.execFile(process.argv[0], startArgs, { maxBuffer: Infinity, cwd: obj.parentpath }, function (error, stdout, stderr) {
453
if (childProcess.xrestart == 1) {
@@ -459,12 +460,12 @@ function CreateMeshCentralServer(config, args) {
460
var version = '';
461
if (typeof obj.args.selfupdate == 'string') { version = '@' + obj.args.selfupdate; }
462
else if (typeof obj.args.specificupdate == 'string') { version = '@' + obj.args.specificupdate; delete obj.args.specificupdate; }
462
- var child_process = require('child_process');
463
- var npmpath = ((typeof obj.args.npmpath == 'string') ? obj.args.npmpath : 'npm');
464
- var npmproxy = ((typeof obj.args.npmproxy == 'string') ? (' --proxy ' + obj.args.npmproxy) : '');
465
- var env = Object.assign({}, process.env); // Shallow clone
463
+ const child_process = require('child_process');
464
+ const npmpath = ((typeof obj.args.npmpath == 'string') ? obj.args.npmpath : 'npm');
465
+ const npmproxy = ((typeof obj.args.npmproxy == 'string') ? (' --proxy ' + obj.args.npmproxy) : '');
466
+ const env = Object.assign({}, process.env); // Shallow clone
467
if (typeof obj.args.npmproxy == 'string') { env['HTTP_PROXY'] = env['HTTPS_PROXY'] = env['http_proxy'] = env['https_proxy'] = obj.args.npmproxy; }
467
- var xxprocess = child_process.exec(npmpath + ' install meshcentral' + version + npmproxy, { maxBuffer: Infinity, cwd: obj.parentpath, env: env }, function (error, stdout, stderr) {
468
+ const xxprocess = child_process.exec(npmpath + ' install meshcentral' + version + npmproxy, { maxBuffer: Infinity, cwd: obj.parentpath, env: env }, function (error, stdout, stderr) {
469
if ((error != null) && (error != '')) { console.log('Update failed: ' + error); }
470
});
471
xxprocess.data = '';
@@ -484,7 +485,7 @@ function CreateMeshCentralServer(config, args) {
485
if (obj.args.cleannpmcacheonupdate === true) {
486
// Perform NPM cache clean
487
console.log('Cleaning NPM cache...');
487
- var xxxprocess = child_process.exec(npmpath + ' cache clean --force', { maxBuffer: Infinity, cwd: obj.parentpath, env: env }, function (error, stdout, stderr) { });
488
+ const xxxprocess = child_process.exec(npmpath + ' cache clean --force', { maxBuffer: Infinity, cwd: obj.parentpath, env: env }, function (error, stdout, stderr) { });
489
xxxprocess.on('close', function (code) { setTimeout(function () { obj.launchChildServer(startArgs); }, 1000); });
490
} else {
491
// Run the updated server
@@ -544,12 +545,12 @@ function CreateMeshCentralServer(config, args) {
545
if (callback == null) return;
546
try {
547
if (typeof obj.args.selfupdate == 'string') { callback(getCurrentVersion(), obj.args.selfupdate); return; } // If we are targetting a specific version, return that one as current.
547
- var child_process = require('child_process');
548
- var npmpath = ((typeof obj.args.npmpath == 'string') ? obj.args.npmpath : 'npm');
549
- var npmproxy = ((typeof obj.args.npmproxy == 'string') ? (' --proxy ' + obj.args.npmproxy) : '');
550
- var env = Object.assign({}, process.env); // Shallow clone
548
+ const child_process = require('child_process');
549
+ const npmpath = ((typeof obj.args.npmpath == 'string') ? obj.args.npmpath : 'npm');
550
+ const npmproxy = ((typeof obj.args.npmproxy == 'string') ? (' --proxy ' + obj.args.npmproxy) : '');
551
+ const env = Object.assign({}, process.env); // Shallow clone
552
if (typeof obj.args.npmproxy == 'string') { env['HTTP_PROXY'] = env['HTTPS_PROXY'] = env['http_proxy'] = env['https_proxy'] = obj.args.npmproxy; }
552
- var xxprocess = child_process.exec(npmpath + npmproxy + ' view meshcentral dist-tags.latest', { maxBuffer: 512000, cwd: obj.parentpath, env: env }, function (error, stdout, stderr) { });
553
+ const xxprocess = child_process.exec(npmpath + npmproxy + ' view meshcentral dist-tags.latest', { maxBuffer: 512000, cwd: obj.parentpath, env: env }, function (error, stdout, stderr) { });
554
xxprocess.data = '';
555
xxprocess.stdout.on('data', function (data) { xxprocess.data += data; });
556
xxprocess.stderr.on('data', function (data) { });
@@ -566,12 +567,12 @@ function CreateMeshCentralServer(config, args) {
567
if (callback == null) return;
568
try {
569
if (typeof obj.args.selfupdate == 'string') { callback({ current: getCurrentVersion(), latest: obj.args.selfupdate }); return; } // If we are targetting a specific version, return that one as current.
569
- var child_process = require('child_process');
570
- var npmpath = ((typeof obj.args.npmpath == 'string') ? obj.args.npmpath : 'npm');
571
- var npmproxy = ((typeof obj.args.npmproxy == 'string') ? (' --proxy ' + obj.args.npmproxy) : '');
572
- var env = Object.assign({}, process.env); // Shallow clone
570
+ const child_process = require('child_process');
571
+ const npmpath = ((typeof obj.args.npmpath == 'string') ? obj.args.npmpath : 'npm');
572
+ const npmproxy = ((typeof obj.args.npmproxy == 'string') ? (' --proxy ' + obj.args.npmproxy) : '');
573
+ const env = Object.assign({}, process.env); // Shallow clone
574
if (typeof obj.args.npmproxy == 'string') { env['HTTP_PROXY'] = env['HTTPS_PROXY'] = env['http_proxy'] = env['https_proxy'] = obj.args.npmproxy; }
574
- var xxprocess = child_process.exec(npmpath + npmproxy + ' dist-tag ls meshcentral', { maxBuffer: 512000, cwd: obj.parentpath, env: env }, function (error, stdout, stderr) { });
575
+ const xxprocess = child_process.exec(npmpath + npmproxy + ' dist-tag ls meshcentral', { maxBuffer: 512000, cwd: obj.parentpath, env: env }, function (error, stdout, stderr) { });
576
xxprocess.data = '';
577
xxprocess.stdout.on('data', function (data) { xxprocess.data += data; });
578
xxprocess.stderr.on('data', function (data) { });
@@ -591,12 +592,12 @@ function CreateMeshCentralServer(config, args) {
592
// Use NPM to get list of versions
593
obj.getServerVersions = function (callback) {
594
try {
594
- var child_process = require('child_process');
595
- var npmpath = ((typeof obj.args.npmpath == 'string') ? obj.args.npmpath : 'npm');
596
- var npmproxy = ((typeof obj.args.npmproxy == 'string') ? (' --proxy ' + obj.args.npmproxy) : '');
597
- var env = Object.assign({}, process.env); // Shallow clone
595
+ const child_process = require('child_process');
596
+ const npmpath = ((typeof obj.args.npmpath == 'string') ? obj.args.npmpath : 'npm');
597
+ const npmproxy = ((typeof obj.args.npmproxy == 'string') ? (' --proxy ' + obj.args.npmproxy) : '');
598
+ const env = Object.assign({}, process.env); // Shallow clone
599
if (typeof obj.args.npmproxy == 'string') { env['HTTP_PROXY'] = env['HTTPS_PROXY'] = env['http_proxy'] = env['https_proxy'] = obj.args.npmproxy; }
599
- var xxprocess = child_process.exec(npmpath + npmproxy + ' view meshcentral versions --json', { maxBuffer: 512000, cwd: obj.parentpath, env: env }, function (error, stdout, stderr) { });
600
+ const xxprocess = child_process.exec(npmpath + npmproxy + ' view meshcentral versions --json', { maxBuffer: 512000, cwd: obj.parentpath, env: env }, function (error, stdout, stderr) { });
601
xxprocess.data = '';
602
xxprocess.stdout.on('data', function (data) { xxprocess.data += data; });
603
xxprocess.stderr.on('data', function (data) { });
@@ -638,9 +639,9 @@ function CreateMeshCentralServer(config, args) {
639
if (obj.args.vault.name == null) { obj.args.vault.name = 'meshcentral'; }
640
641
// Get new instance of the client
641
- var vault = require("node-vault")({ endpoint: obj.args.vault.endpoint, token: obj.args.vault.token });
642
+ const vault = require("node-vault")({ endpoint: obj.args.vault.endpoint, token: obj.args.vault.token });
643
vault.unseal({ key: obj.args.vault.unsealkey })
643
- .then(() => {
644
+ .then(function() {
645
if (obj.args.vaultdeleteconfigfiles) {
646
vault.delete('secret/data/' + obj.args.vault.name)
647
.then(function (r) { console.log('Done.'); process.exit(); })
@@ -787,7 +788,7 @@ function CreateMeshCentralServer(config, args) {
788
789
// Check if WebSocket compression is supported. It's known to be broken in NodeJS v11.11 to v12.15, and v13.2
790
const verSplit = process.version.substring(1).split('.');
790
- var ver = parseInt(verSplit[0]) + (parseInt(verSplit[1]) / 100);
791
+ const ver = parseInt(verSplit[0]) + (parseInt(verSplit[1]) / 100);
792
if (((ver >= 11.11) && (ver <= 12.15)) || (ver == 13.2)) {
793
if ((obj.args.wscompression === true) || (obj.args.agentwscompression === true)) { addServerWarning('WebSocket compression is disabled, this feature is broken in NodeJS v11.11 to v12.15 and v13.2', 4); }
794
obj.args.wscompression = obj.args.agentwscompression = false;
@@ -832,7 +833,7 @@ function CreateMeshCentralServer(config, args) {
833
if (err != null) { console.log("Database error: " + err); process.exit(); return; }
834
if ((docs != null) && (docs.length != 0)) { console.log('User already exists.'); process.exit(); return; }
835
if ((domainid != '') && ((config.domains == null) || (config.domains[domainid] == null))) { console.log("Invalid domain."); process.exit(); return; }
835
- var user = { _id: userid, type: 'user', name: (typeof obj.args.name == 'string') ? obj.args.name : (userid.split('/')[2]), domain: domainid, creation: Math.floor(Date.now() / 1000), links: {} };
836
+ const user = { _id: userid, type: 'user', name: (typeof obj.args.name == 'string') ? obj.args.name : (userid.split('/')[2]), domain: domainid, creation: Math.floor(Date.now() / 1000), links: {} };
837
if (typeof obj.args.email == 'string') { user.email = obj.args.email; user.emailVerified = true; }
838
if (obj.args.hashpass) {
839
// Create an account using a pre-hashed password. Use --hashpassword to pre-hash a password.
@@ -856,7 +857,7 @@ function CreateMeshCentralServer(config, args) {
857
obj.db.Get(userid, function (err, docs) {
858
if (err != null) { console.log("Database error: " + err); process.exit(); return; }
859
if ((docs == null) || (docs.length == 0)) { console.log("Unknown userid, usage: --resetaccount [userid] --domain (domain) --pass [password]."); process.exit(); return; }
859
- var user = docs[0]; if ((user.siteadmin) && (user.siteadmin != 0xFFFFFFFF) && (user.siteadmin & 32) != 0) { user.siteadmin -= 32; } // Unlock the account.
860
+ const user = docs[0]; if ((user.siteadmin) && (user.siteadmin != 0xFFFFFFFF) && (user.siteadmin & 32) != 0) { user.siteadmin -= 32; } // Unlock the account.
861
delete user.phone; delete user.otpekey; delete user.otpsecret; delete user.otpkeys; delete user.otphkeys; delete user.otpdev; delete user.otpsms; // Disable 2FA
862
if (obj.args.hashpass) {
863
// Reset an account using a pre-hashed password. Use --hashpassword to pre-hash a password.
@@ -897,7 +898,7 @@ function CreateMeshCentralServer(config, args) {
898
process.exit(0);
899
} else {
900
// Load all users
900
- var allusers = {}, removeCount = 0;
901
+ const allusers = {}, removeCount = 0;
902
obj.db.GetAllType('user', function (err, docs) {
903
obj.common.unEscapeAllLinksFieldName(docs);
904
for (i in docs) { allusers[docs[i]._id] = docs[i]; }
@@ -907,7 +908,7 @@ function CreateMeshCentralServer(config, args) {
908
for (var i in docs) {
909
if ((docs[i] != null) && (docs[i].agent != null) && (docs[i].agent.id == 23)) {
910
// Remove this test node
910
- var node = docs[i];
911
+ const node = docs[i];
912
913
// Delete this node including network interface information, events and timeline
914
removeCount++;
@@ -973,7 +974,7 @@ function CreateMeshCentralServer(config, args) {
974
obj.db.getConfigFile(obj.args.dbshowconfigfile, function (err, docs) {
975
if (err == null) {
976
if (docs.length == 0) { console.log("File not found."); } else {
976
- var data = obj.db.decryptData(obj.args.configkey, docs[0].data);
977
+ const data = obj.db.decryptData(obj.args.configkey, docs[0].data);
978
if (data == null) { console.log("Invalid config key."); } else { console.log(data); }
979
}
980
} else { console.log("Unable to read from database."); }
@@ -1037,7 +1038,7 @@ function CreateMeshCentralServer(config, args) {
1038
if (binary == null) {
1039
console.log("Invalid config key.");
1040
} else {
1040
- var fullFileName = obj.path.join(obj.args.dbpullconfigfiles, file);
1041
+ const fullFileName = obj.path.join(obj.args.dbpullconfigfiles, file);
1042
try { obj.fs.writeFileSync(fullFileName, binary); } catch (ex) { console.log('Unable to write to ' + fullFileName); process.exit(); return; }
1043
console.log('Pulling ' + file + ', ' + binary.length + ' bytes.');
1044
}
@@ -1082,7 +1083,7 @@ function CreateMeshCentralServer(config, args) {
1083
if ((json == null) || (typeof json.length != 'number') || (json.length < 1)) { console.log('Invalid JSON format: ' + obj.args.dbimport + '.'); }
1084
// Escape MongoDB invalid field chars
1085
for (i in json) {
1085
- var doc = json[i];
1086
+ const doc = json[i];
1087
for (var j in doc) { if (j.indexOf('.') >= 0) { console.log("Invalid field name (" + j + ") in document: " + json[i]); return; } }
1088
//if ((json[i].type == 'ifinfo') && (json[i].netif2 != null)) { for (var j in json[i].netif2) { var esc = obj.common.escapeFieldName(j); if (esc !== j) { json[i].netif2[esc] = json[i].netif2[j]; delete json[i].netif2[j]; } } }
1089
//if ((json[i].type == 'mesh') && (json[i].links != null)) { for (var j in json[i].links) { var esc = obj.common.escapeFieldName(j); if (esc !== j) { json[i].links[esc] = json[i].links[j]; delete json[i].links[j]; } } }
@@ -1124,19 +1125,19 @@ function CreateMeshCentralServer(config, args) {
1125
1126
// Get all users from current database
1127
obj.db.GetAllType('user', function (err, docs) {
1127
- var users = {}, usersCount = 0;
1128
+ const users = {}, usersCount = 0;
1129
for (var i in docs) { users[docs[i]._id] = docs[i]; usersCount++; }
1130
1131
// Fetch all meshes from the database
1132
obj.db.GetAllType('mesh', function (err, docs) {
1133
obj.common.unEscapeAllLinksFieldName(docs);
1133
- var meshes = {}, meshesCount = 0;
1134
+ const meshes = {}, meshesCount = 0;
1135
for (var i in docs) { meshes[docs[i]._id] = docs[i]; meshesCount++; }
1136
console.log('Loaded ' + usersCount + ' users and ' + meshesCount + ' meshes.');
1137
// Look at each object in the import file
1137
- var objectToAdd = [];
1138
+ const objectToAdd = [];
1139
for (var i in json) {
1139
- var newobj = json[i];
1140
+ const newobj = json[i];
1141
if (newobj.type == 'user') {
1142
// Check if the user already exists
1143
var existingUser = users[newobj._id];
@@ -1246,7 +1247,7 @@ function CreateMeshCentralServer(config, args) {
1247
if (process.ppid) { obj.updateServerState('server-parent-pid', process.ppid); }
1248
1249
// Read environment variables. For a subset of arguments, we allow them to be read from environment variables.
1249
- var xenv = ['user', 'port', 'mpsport', 'mpsaliasport', 'redirport', 'rediraliasport', 'exactport', 'debug'];
1250
+ const xenv = ['user', 'port', 'mpsport', 'mpsaliasport', 'redirport', 'rediraliasport', 'exactport', 'debug'];
1251
for (i in xenv) { if ((obj.args[xenv[i]] == null) && (process.env['mesh' + xenv[i]])) { obj.args[xenv[i]] = obj.common.toNumber(process.env['mesh' + xenv[i]]); } }
1252
1253
// Validate the domains, this is used for multi-hosting
@@ -1435,9 +1436,9 @@ function CreateMeshCentralServer(config, args) {
1436
if (obj.args.getwspass.length == 64) {
1437
obj.crypto.randomBytes(6, function (err, buf) {
1438
while (obj.dbconfig.amtWsEventSecret == null) { process.nextTick(); }
1438
- var username = buf.toString('hex');
1439
- var nodeid = obj.args.getwspass;
1440
- var pass = obj.crypto.createHash('sha384').update(username.toLowerCase() + ':' + nodeid + ':' + obj.dbconfig.amtWsEventSecret).digest('base64').substring(0, 12).split('/').join('x').split('\\').join('x');
1439
+ const username = buf.toString('hex');
1440
+ const nodeid = obj.args.getwspass;
1441
+ const pass = obj.crypto.createHash('sha384').update(username.toLowerCase() + ':' + nodeid + ':' + obj.dbconfig.amtWsEventSecret).digest('base64').substring(0, 12).split('/').join('x').split('\\').join('x');
1442
console.log("--- Intel(r) AMT WSMAN eventing credentials ---");
1443
console.log("Username: " + username);
1444
console.log("Password: " + pass);
@@ -1490,7 +1491,7 @@ function CreateMeshCentralServer(config, args) {
1491
else if (obj.config.letsencrypt.email.split('@').length != 2) { leok = false; addServerWarning("Invalid Let's Encrypt email address.", 10); }
1492
else if (obj.config.letsencrypt.email.trim() !== obj.config.letsencrypt.email) { leok = false; addServerWarning("Invalid Let's Encrypt email address.", 10); }
1493
else {
1493
- var le = require('./letsencrypt.js');
1494
+ const le = require('./letsencrypt.js');
1495
try { obj.letsencrypt = le.CreateLetsEncrypt(obj); } catch (ex) { console.log(ex); }
1496
if (obj.letsencrypt == null) { addServerWarning("Unable to setup Let's Encrypt module.", 13); leok = false; }
1497
}
@@ -1545,7 +1546,7 @@ function CreateMeshCentralServer(config, args) {
1546
obj.certificateOperations.loadTextFile('https://www.cloudflare.com/ips-v4', null, function (url, data, tag) {
1547
if (data != null) {
1548
if (Array.isArray(obj.args.trustedproxy) == false) { obj.args.trustedproxy = []; }
1548
- var ipranges = data.split('\n');
1549
+ const ipranges = data.split('\n');
1550
for (var i in ipranges) { if (ipranges[i] != '') { obj.args.trustedproxy.push(ipranges[i]); } }
1551
obj.certificateOperations.loadTextFile('https://www.cloudflare.com/ips-v6', null, function (url, data, tag) {
1552
if (data != null) {
@@ -1575,8 +1576,8 @@ function CreateMeshCentralServer(config, args) {
1576
if (obj.certificates.CommonName.indexOf('.') == -1) { /*console.log('Server name not configured, running in LAN-only mode.');*/ obj.args.lanonly = true; }
1577
1578
// Write server version and run mode
1578
- var productionMode = (process.env.NODE_ENV && (process.env.NODE_ENV == 'production'));
1579
- var runmode = (obj.args.lanonly ? 2 : (obj.args.wanonly ? 1 : 0));
1579
+ const productionMode = (process.env.NODE_ENV && (process.env.NODE_ENV == 'production'));
1580
+ const runmode = (obj.args.lanonly ? 2 : (obj.args.wanonly ? 1 : 0));
1581
console.log("MeshCentral v" + getCurrentVersion() + ', ' + (["Hybrid (LAN + WAN) mode", "WAN mode", "LAN mode"][runmode]) + (productionMode ? ", Production mode." : '.'));
1582
1583
// Check that no sub-domains have the same DNS as the parent
@@ -1592,7 +1593,7 @@ function CreateMeshCentralServer(config, args) {
1593
// Load MeshAgent translation strings
1594
try {
1595
var translationpath = obj.path.join(__dirname, 'agents', 'agent-translations.json');
1595
- var translationpath2 = obj.path.join(obj.datapath, 'agents', 'agent-translations.json');
1596
+ const translationpath2 = obj.path.join(obj.datapath, 'agents', 'agent-translations.json');
1597
if (obj.fs.existsSync(translationpath2)) { translationpath = translationpath2; } // If the agent is present in "meshcentral-data/agents", use that one instead.
1598
var translations = JSON.parse(obj.fs.readFileSync(translationpath).toString());
1599
if (translations['zh-chs']) { translations['zh-hans'] = translations['zh-chs']; delete translations['zh-chs']; }
@@ -1792,7 +1793,7 @@ function CreateMeshCentralServer(config, args) {
1793
else if ((Math.floor(obj.serverStatsCounter / 4) % 2) == 1) { hours = 24; } // Another half of the event get removed after 24 hours.
1794
else if ((Math.floor(obj.serverStatsCounter / 8) % 2) == 1) { hours = 48; } // Another half of the event get removed after 48 hours.
1795
else if ((Math.floor(obj.serverStatsCounter / 16) % 2) == 1) { hours = 72; } // Another half of the event get removed after 72 hours.
1795
- var expire = new Date();
1796
+ const expire = new Date();
1797
expire.setTime(expire.getTime() + (60 * 60 * 1000 * hours));
1798
1799
// Get traffic data
@@ -1866,7 +1867,7 @@ function CreateMeshCentralServer(config, args) {
1867
obj.watchdogmaxtime = null;
1868
obj.watchdogtable = [];
1869
obj.watchdog = setInterval(function () {
1869
- var now = Date.now(), delta = now - obj.watchdogtime - config.settings.watchdog.interval;
1870
+ const now = Date.now(), delta = now - obj.watchdogtime - config.settings.watchdog.interval;
1871
if (delta > obj.watchdogmax) { obj.watchdogmax = delta; obj.watchdogmaxtime = new Date().toLocaleString(); }
1872
if (delta > config.settings.watchdog.timeout) {
1873
const msg = obj.common.format("Watchdog timer timeout, {0}ms.", delta);
@@ -1926,14 +1927,14 @@ function CreateMeshCentralServer(config, args) {
1927
obj.pendingProxyCertificatesRequests--;
1928
if (cert != null) {
1929
// Hash the entire cert
1929
- var hash = obj.crypto.createHash('sha384').update(Buffer.from(cert, 'binary')).digest('hex');
1930
+ const hash = obj.crypto.createHash('sha384').update(Buffer.from(cert, 'binary')).digest('hex');
1931
if (xdomain.certhash != hash) { // The certificate has changed.
1932
xdomain.certkeyhash = hash;
1933
xdomain.certhash = hash;
1934
1935
try {
1936
// Decode a RSA certificate and hash the public key, if this is not RSA, skip this.
1936
- var forgeCert = obj.certificateOperations.forge.pki.certificateFromAsn1(obj.certificateOperations.forge.asn1.fromDer(cert));
1937
+ const forgeCert = obj.certificateOperations.forge.pki.certificateFromAsn1(obj.certificateOperations.forge.asn1.fromDer(cert));
1938
xdomain.certkeyhash = obj.certificateOperations.forge.pki.getPublicKeyFingerprint(forgeCert.publicKey, { md: obj.certificateOperations.forge.md.sha384.create(), encoding: 'hex' });
1939
obj.webserver.webCertificateExpire[xdomain.id] = Date.parse(forgeCert.validity.notAfter); // Update certificate expire time
1940
//console.log('V1: ' + xdomain.certkeyhash);
@@ -1968,8 +1969,8 @@ function CreateMeshCentralServer(config, args) {
1969
obj.db.maintenance();
1970
1971
// Clean up any temporary files
1971
- var removeTime = new Date(Date.now()).getTime() - (30 * 60 * 1000); // 30 minutes
1972
- var dir = obj.fs.readdir(obj.path.join(obj.filespath, 'tmp'), function (err, files) {
1972
+ const removeTime = new Date(Date.now()).getTime() - (30 * 60 * 1000); // 30 minutes
1973
+ const dir = obj.fs.readdir(obj.path.join(obj.filespath, 'tmp'), function (err, files) {
1974
if (err != null) return;
1975
for (var i in files) { try { const filepath = obj.path.join(obj.filespath, 'tmp', files[i]); if (obj.fs.statSync(filepath).mtime.getTime() < removeTime) { obj.fs.unlink(filepath, function () { }); } } catch (ex) { } }
1976
});
@@ -1998,9 +1999,10 @@ function CreateMeshCentralServer(config, args) {
1999
if (obj.config.settings.autobackup && (typeof obj.config.settings.autobackup.backupintervalhours == 'number')) {
2000
obj.db.Get('LastAutoBackupTime', function (err, docs) {
2001
if (err != null) return;
2001
- var lastBackup = 0, now = new Date().getTime();
2002
+ var lastBackup = 0;
2003
+ const now = new Date().getTime();
2004
if (docs.length == 1) { lastBackup = docs[0].value; }
2003
- var delta = now - lastBackup;
2005
+ const delta = now - lastBackup;
2006
if (delta > (obj.config.settings.autobackup.backupintervalhours * 60 * 60 * 1000)) {
2007
// A new auto-backup is required.
2008
obj.db.Set({ _id: 'LastAutoBackupTime', value: now }); // Save the current time in the database
@@ -2024,7 +2026,7 @@ function CreateMeshCentralServer(config, args) {
2026
obj.debug('main', obj.common.format("Server stopped, updating settings: {0}", restoreFile));
2027
console.log("Updating settings folder...");
2028
2027
- var yauzl = require('yauzl');
2029
+ const yauzl = require('yauzl');
2030
yauzl.open(restoreFile, { lazyEntries: true }, function (err, zipfile) {
2031
if (err) throw err;
2032
zipfile.readEntry();
@@ -2039,7 +2041,7 @@ function CreateMeshCentralServer(config, args) {
2041
zipfile.openReadStream(entry, function (err, readStream) {
2042
if (err) throw err;
2043
readStream.on('end', function () { zipfile.readEntry(); });
2042
- var directory = obj.path.dirname(entry.fileName);
2044
+ const directory = obj.path.dirname(entry.fileName);
2045
if (directory != '.') {
2046
directory = obj.getConfigFilePath(directory)
2047
if (obj.fs.existsSync(directory) == false) { obj.fs.mkdirSync(directory); }
@@ -2234,7 +2236,7 @@ function CreateMeshCentralServer(config, args) {
2236
2237
// Get the list of users that have visibility to this device
2238
// This includes users that are part of user groups
2237
- var users = [];
2239
+ const users = [];
2240
for (var i in mesh.links) {
2241
if (i.startsWith('user/') && (users.indexOf(i) < 0)) { users.push(i); }
2242
if (i.startsWith('ugrp/')) {
@@ -2316,7 +2318,7 @@ function CreateMeshCentralServer(config, args) {
2318
eventConnectChange = 1;
2319
2320
// Set new power state in database
2319
- var record = { time: new Date(connectTime), nodeid: nodeid, power: powerState };
2321
+ const record = { time: new Date(connectTime), nodeid: nodeid, power: powerState };
2322
if (oldPowerState != null) { record.oldPower = oldPowerState; }
2323
obj.db.storePowerEvent(record, obj.multiServer);
2324
}
@@ -2340,7 +2342,7 @@ function CreateMeshCentralServer(config, args) {
2342
if (serverid == null) { serverid = obj.serverId; }
2343
if (obj.peerConnectivityByNode[serverid] == null) return; // Guard against unknown serverid's
2344
var eventConnectChange = 0;
2343
- var state = obj.peerConnectivityByNode[serverid][nodeid];
2345
+ const state = obj.peerConnectivityByNode[serverid][nodeid];
2346
if (state) {
2347
// Change the connection in the node and mesh state lists
2348
if ((state.connectivity & connectType) == 0) { state.connectivity |= connectType; eventConnectChange = 1; }
@@ -2396,7 +2398,7 @@ function CreateMeshCentralServer(config, args) {
2398
var eventConnectChange = 0;
2399
2400
// Remove the agent connection from the nodes connection list
2399
- var state = obj.connectivityByNode[nodeid];
2401
+ const state = obj.connectivityByNode[nodeid];
2402
if (state == null) return;
2403
2404
if ((state.connectivity & connectType) != 0) {
@@ -2413,7 +2415,8 @@ function CreateMeshCentralServer(config, args) {
2415
}
2416
2417
// Clear node power state
2416
- var oldPowerState = state.powerState, powerState = 0;
2418
+ var powerState = 0;
2419
+ const oldPowerState = state.powerState;
2420
if (connectType == 1) { state.agentPower = 0; } else if (connectType == 2) { state.ciraPower = 0; } else if (connectType == 4) { state.amtPower = 0; }
2421
if ((state.connectivity & 1) != 0) { powerState = state.agentPower; } else if ((state.connectivity & 2) != 0) { powerState = state.ciraPower; } else if ((state.connectivity & 4) != 0) { powerState = state.amtPower; }
2422
if ((state.powerState == null) || (state.powerState != powerState)) {
@@ -2437,7 +2440,7 @@ function CreateMeshCentralServer(config, args) {
2440
// Remove the agent connection from the nodes connection list
2441
if (serverid == null) { serverid = obj.serverId; }
2442
if (obj.peerConnectivityByNode[serverid] == null) return; // Guard against unknown serverid's
2440
- var state = obj.peerConnectivityByNode[serverid][nodeid];
2443
+ const state = obj.peerConnectivityByNode[serverid][nodeid];
2444
if (state == null) return;
2445
2446
// If existing state exist, remove this connection
@@ -2687,7 +2690,7 @@ function CreateMeshCentralServer(config, args) {
2690
};
2691
2692
// List of possible mesh agent install scripts
2690
- var meshToolsList = {
2693
+ const meshToolsList = {
2694
'MeshCentralRouter': { localname: 'MeshCentralRouter.exe', dlname: 'winrouter' },
2695
'MeshCentralAssistant': { localname: 'MeshCentralAssistant.exe', dlname: 'winassistant', winhash: true }
2696
//'MeshCentralRouterMacOS': { localname: 'MeshCentralRouter.dmg', dlname: 'MeshCentralRouter.dmg' }
@@ -2698,7 +2701,7 @@ function CreateMeshCentralServer(config, args) {
2701
for (var toolname in meshToolsList) {
2702
if (meshToolsList[toolname].winhash === true) {
2703
var toolpath = obj.path.join(__dirname, 'agents', meshToolsList[toolname].localname);
2701
- var toolpath2 = obj.path.join(obj.datapath, 'agents', meshToolsList[toolname].localname);
2704
+ const toolpath2 = obj.path.join(obj.datapath, 'agents', meshToolsList[toolname].localname);
2705
if (obj.fs.existsSync(toolpath2)) { toolpath = toolpath2; } // If the tool is present in "meshcentral-data/agents", use that one instead.
2706
2707
var hashStream = obj.crypto.createHash('sha384');
@@ -2713,11 +2716,11 @@ function CreateMeshCentralServer(config, args) {
2716
try { stats = obj.fs.statSync(this.toolpath); } catch (ex) { }
2717
if (stats != null) { obj.meshToolsBinaries[this.toolname].size = stats.size; }
2718
});
2716
- var options = { sourcePath: toolpath, targetStream: hashStream };
2719
+ const options = { sourcePath: toolpath, targetStream: hashStream };
2720
obj.exeHandler.hashExecutableFile(options);
2721
} else {
2722
var toolpath = obj.path.join(__dirname, 'agents', meshToolsList[toolname].localname);
2720
- var toolpath2 = obj.path.join(obj.datapath, 'agents', meshToolsList[toolname].localname);
2723
+ const toolpath2 = obj.path.join(obj.datapath, 'agents', meshToolsList[toolname].localname);
2724
if (obj.fs.existsSync(toolpath2)) { toolpath = toolpath2; } // If the tool is present in "meshcentral-data/agents", use that one instead.
2725
2726
var stream = null;
@@ -2751,7 +2754,7 @@ function CreateMeshCentralServer(config, args) {
2754
};
2755
2756
// List of possible mesh agent install scripts
2754
- var meshAgentsInstallScriptList = {
2757
+ const meshAgentsInstallScriptList = {
2758
1: { id: 1, localname: 'meshinstall-linux.sh', rname: 'meshinstall.sh', linux: true },
2759
2: { id: 2, localname: 'meshinstall-initd.sh', rname: 'meshagent', linux: true },
2760
5: { id: 5, localname: 'meshinstall-bsd-rcd.sh', rname: 'meshagent', linux: true },
@@ -2846,7 +2849,7 @@ function CreateMeshCentralServer(config, args) {
2849
if (objx == null) { objx = obj; } else { suffix = '-' + domain.id; objx.meshAgentBinaries = {}; }
2850
2851
// Load agent information file. This includes the data & time of the agent.
2849
- var agentInfo = [];
2852
+ const agentInfo = [];
2853
try { agentInfo = JSON.parse(obj.fs.readFileSync(obj.path.join(__dirname, 'agents', 'hashagents.json'), 'utf8')); } catch (ex) { }
2854
2855
var archcount = 0;
@@ -2882,7 +2885,7 @@ function CreateMeshCentralServer(config, args) {
2885
if ((obj.args.agentsinram === true) || (((archid == 3) || (archid == 4)) && (obj.args.agentsinram !== false))) {
2886
if ((archid == 3) || (archid == 4)) {
2887
// Load the agent with a random msh added to it.
2885
- var outStream = new require('stream').Duplex();
2888
+ const outStream = new require('stream').Duplex();
2889
outStream.meshAgentBinary = objx.meshAgentBinaries[archid];
2890
outStream.meshAgentBinary.randomMsh = Buffer.from(obj.crypto.randomBytes(64), 'binary').toString('base64');
2891
outStream.bufferList = [];
@@ -2895,20 +2898,20 @@ function CreateMeshCentralServer(config, args) {
2898
delete this.bufferList;
2899
2900
// Hash the uncompressed binary
2898
- var hash = obj.crypto.createHash('sha384').update(this.meshAgentBinary.data);
2901
+ const hash = obj.crypto.createHash('sha384').update(this.meshAgentBinary.data);
2902
this.meshAgentBinary.fileHash = hash.digest('binary');
2903
this.meshAgentBinary.fileHashHex = Buffer.from(this.meshAgentBinary.fileHash, 'binary').toString('hex');
2904
2905
// Compress the agent using ZIP
2903
- var archive = require('archiver')('zip', { level: 9 }); // Sets the compression method.
2906
+ const archive = require('archiver')('zip', { level: 9 }); // Sets the compression method.
2907
const onZipData = function onZipData(buffer) { onZipData.x.zacc.push(buffer); }
2908
const onZipEnd = function onZipEnd() {
2909
// Concat all the buffer for create compressed zip agent
2907
- var concatData = Buffer.concat(onZipData.x.zacc);
2910
+ const concatData = Buffer.concat(onZipData.x.zacc);
2911
delete onZipData.x.zacc;
2912
2913
// Hash the compressed binary
2911
- var hash = obj.crypto.createHash('sha384').update(concatData);
2914
+ const hash = obj.crypto.createHash('sha384').update(concatData);
2915
onZipData.x.zhash = hash.digest('binary');
2916
onZipData.x.zhashhex = Buffer.from(onZipData.x.zhash, 'binary').toString('hex');
2917
@@ -2949,16 +2952,16 @@ function CreateMeshCentralServer(config, args) {
2952
objx.meshAgentBinaries[archid].data = obj.fs.readFileSync(agentpath);
2953
2954
// Compress the agent using ZIP
2952
- var archive = require('archiver')('zip', { level: 9 }); // Sets the compression method.
2955
+ const archive = require('archiver')('zip', { level: 9 }); // Sets the compression method.
2956
2957
const onZipData = function onZipData(buffer) { onZipData.x.zacc.push(buffer); }
2958
const onZipEnd = function onZipEnd() {
2959
// Concat all the buffer for create compressed zip agent
2957
- var concatData = Buffer.concat(onZipData.x.zacc);
2960
+ const concatData = Buffer.concat(onZipData.x.zacc);
2961
delete onZipData.x.zacc;
2962
2963
// Hash the compressed binary
2961
- var hash = obj.crypto.createHash('sha384').update(concatData);
2964
+ const hash = obj.crypto.createHash('sha384').update(concatData);
2965
onZipData.x.zhash = hash.digest('binary');
2966
onZipData.x.zhashhex = Buffer.from(onZipData.x.zhash, 'binary').toString('hex');
2967
@@ -2982,20 +2985,20 @@ function CreateMeshCentralServer(config, args) {
2985
}
2986
2987
// Hash the binary
2985
- var hashStream = obj.crypto.createHash('sha384');
2988
+ const hashStream = obj.crypto.createHash('sha384');
2989
hashStream.archid = archid;
2990
hashStream.on('data', function (data) {
2991
objx.meshAgentBinaries[this.archid].hash = data.toString('binary');
2992
objx.meshAgentBinaries[this.archid].hashhex = data.toString('hex');
2993
if ((--archcount == 0) && (func != null)) { func(); }
2994
});
2992
- var options = { sourcePath: agentpath, targetStream: hashStream, platform: obj.meshAgentsArchitectureNumbers[archid].platform };
2995
+ const options = { sourcePath: agentpath, targetStream: hashStream, platform: obj.meshAgentsArchitectureNumbers[archid].platform };
2996
if (objx.meshAgentBinaries[archid].pe != null) { options.peinfo = objx.meshAgentBinaries[archid].pe; }
2997
obj.exeHandler.hashExecutableFile(options);
2998
2999
// If we are not loading Windows binaries to RAM, compute the RAW file hash of the signed binaries here.
3000
if ((obj.args.agentsinram === false) && ((archid == 3) || (archid == 4))) {
2998
- var hash = obj.crypto.createHash('sha384').update(obj.fs.readFileSync(agentpath));
3001
+ const hash = obj.crypto.createHash('sha384').update(obj.fs.readFileSync(agentpath));
3002
objx.meshAgentBinaries[archid].fileHash = hash.digest('binary');
3003
objx.meshAgentBinaries[archid].fileHashHex = Buffer.from(objx.meshAgentBinaries[archid].fileHash, 'binary').toString('hex');
3004
}
@@ -3008,7 +3011,7 @@ function CreateMeshCentralServer(config, args) {
3011
// Generate a time limited user login token
3012
obj.getLoginToken = function (userid, func) {
3013
if ((userid == null) || (typeof userid != 'string')) { func('Invalid userid.'); return; }
3011
- var x = userid.split('/');
3014
+ const x = userid.split('/');
3015
if (x == null || x.length != 3 || x[0] != 'user') { func('Invalid userid.'); return; }
3016
obj.db.Get(userid, function (err, docs) {
3017
if (err != null || docs == null || docs.length == 0) {
@@ -3047,13 +3050,13 @@ function CreateMeshCentralServer(config, args) {
3050
3051
// Load the list of Intel AMT UUID and passwords from "amtactivation.log"
3052
obj.loadAmtActivationLogPasswords = function (func) {
3050
- var amtlogfilename = obj.path.join(obj.datapath, 'amtactivation.log');
3053
+ const amtlogfilename = obj.path.join(obj.datapath, 'amtactivation.log');
3054
obj.fs.readFile(amtlogfilename, 'utf8', function (err, data) {
3052
- var amtPasswords = {}; // UUID --> [Passwords]
3055
+ const amtPasswords = {}; // UUID --> [Passwords]
3056
if ((err == null) && (data != null)) {
3057
const lines = data.split('\n');
3058
for (var i in lines) {
3056
- var line = lines[i];
3059
+ const line = lines[i];
3060
if (line.startsWith('{')) {
3061
var j = null;
3062
try { j = JSON.parse(line); } catch (ex) { }
@@ -3091,7 +3094,7 @@ function CreateMeshCentralServer(config, args) {
3094
o.time = Math.floor(Date.now() / 1000); // Add the cookie creation time
3095
const iv = Buffer.from(obj.crypto.randomBytes(12), 'binary'), cipher = obj.crypto.createCipheriv('aes-256-gcm', key.slice(0, 32), iv);
3096
const crypted = Buffer.concat([cipher.update(JSON.stringify(o), 'utf8'), cipher.final()]);
3094
- var r = Buffer.concat([iv, cipher.getAuthTag(), crypted]).toString(obj.args.cookieencoding ? obj.args.cookieencoding : 'base64').replace(/\+/g, '@').replace(/\//g, '$');
3097
+ const r = Buffer.concat([iv, cipher.getAuthTag(), crypted]).toString(obj.args.cookieencoding ? obj.args.cookieencoding : 'base64').replace(/\+/g, '@').replace(/\//g, '$');
3098
obj.debug('cookie', 'Encoded AESGCM cookie: ' + JSON.stringify(o));
3099
return r;
3100
} catch (ex) { obj.debug('cookie', 'ERR: Failed to encode AESGCM cookie due to exception: ' + ex); return null; }
@@ -3100,7 +3103,7 @@ function CreateMeshCentralServer(config, args) {
3103
// Decode a cookie back into an object using a key using AES256-GCM or AES128-CBC/HMAC-SHA384. Return null if it's not a valid cookie. (key must be 32 bytes or more)
3104
obj.decodeCookie = function (cookie, key, timeout) {
3105
if (cookie == null) return null;
3103
- var r = obj.decodeCookieAESGCM(cookie, key, timeout);
3106
+ const r = obj.decodeCookieAESGCM(cookie, key, timeout);
3107
if (r == null) { r = obj.decodeCookieAESSHA(cookie, key, timeout); }
3108
if ((r == null) && (obj.args.cookieencoding == null) && (cookie.length != 64) && ((cookie == cookie.toLowerCase()) || (cookie == cookie.toUpperCase()))) {
3109
obj.debug('cookie', 'Upper/Lowercase cookie, try "CookieEncoding":"hex" in settings section of config.json.');
@@ -3215,9 +3218,9 @@ function CreateMeshCentralServer(config, args) {
3218
if ((obj.debugRemoteSources != null) && ((obj.debugRemoteSources == '*') || (obj.debugRemoteSources.indexOf(source) >= 0))) {
3219
var sendcount = 0;
3220
for (var sessionid in obj.webserver.wssessions2) {
3218
- var ws = obj.webserver.wssessions2[sessionid];
3221
+ const ws = obj.webserver.wssessions2[sessionid];
3222
if ((ws != null) && (ws.userid != null)) {
3220
- var user = obj.webserver.users[ws.userid];
3223
+ const user = obj.webserver.users[ws.userid];
3224
if ((user != null) && (user.siteadmin == 4294967295)) {
3225
try { ws.send(JSON.stringify({ action: 'trace', source: source, args: args, time: Date.now() })); sendcount++; } catch (ex) { }
3226
}
@@ -3228,7 +3231,7 @@ function CreateMeshCentralServer(config, args) {
3231
};
3232
3233
// Update server state. Writes a server state file.
3231
- var meshServerState = {};
3234
+ const meshServerState = {};
3235
obj.updateServerState = function (name, val) {
3236
//console.log('updateServerState', name, val);
3237
try {
@@ -3251,7 +3254,7 @@ function CreateMeshCentralServer(config, args) {
3254
var lines = null;
3255
try { lines = obj.fs.readFileSync(obj.path.join(obj.datapath, arg.substring(5))).toString().split('\r\n').join('\r').split('\r'); } catch (ex) { }
3256
if (lines == null) return null;
3254
- var validLines = [];
3257
+ const validLines = [];
3258
for (var i in lines) { if ((lines[i].length > 0) && (((lines[i].charAt(0) > '0') && (lines[i].charAt(0) < '9')) || (lines[i].charAt(0) == ':'))) validLines.push(lines[i]); }
3259
return validLines;
3260
}
@@ -3270,8 +3273,8 @@ function CreateMeshCentralServer(config, args) {
3273
if (obj.syslogauth != null) { try { obj.syslogauth.log(obj.syslogauth.LOG_INFO, msg); } catch (ex) { } }
3274
if (obj.authlogfile != null) { // Write authlog to file
3275
try {
3273
- var d = new Date(), month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
3274
- var msg = month + ' ' + d.getDate() + ' ' + obj.common.zeroPad(d.getHours(), 2) + ':' + obj.common.zeroPad(d.getMinutes(), 2) + ':' + d.getSeconds() + ' meshcentral ' + server + '[' + process.pid + ']: ' + msg + ((obj.platform == 'win32') ? '\r\n' : '\n');
3276
+ const d = new Date(), month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
3277
+ const msg = month + ' ' + d.getDate() + ' ' + obj.common.zeroPad(d.getHours(), 2) + ':' + obj.common.zeroPad(d.getMinutes(), 2) + ':' + d.getSeconds() + ' meshcentral ' + server + '[' + process.pid + ']: ' + msg + ((obj.platform == 'win32') ? '\r\n' : '\n');
3278
obj.fs.write(obj.authlogfile, msg, function (err, written, string) { });
3279
} catch (ex) { }
3280
}
@@ -3292,7 +3295,7 @@ function CreateMeshCentralServer(config, args) {
3295
3296
// Resolve a list of names, call back with list of failed resolves.
3297
function checkResolveAll(names, func) {
3295
- var dns = require('dns'), state = { func: func, count: names.length, err: null };
3298
+ const dns = require('dns'), state = { func: func, count: names.length, err: null };
3299
for (var i in names) {
3300
dns.resolve(names[i], function (err, records) {
3301
if (err != null) { if (this.state.err == null) { this.state.err = [this.name]; } else { this.state.err.push(this.name); } }
@@ -3304,8 +3307,8 @@ function checkResolveAll(names, func) {
3307
// Return the server configuration
3308
function getConfig(createSampleConfig) {
3309
// Figure out the datapath location
3307
- var i, fs = require('fs'), path = require('path'), datapath = null;
3308
- var args = require('minimist')(process.argv.slice(2));
3310
+ var i, datapath = null;
3311
+ const fs = require('fs'), path = require('path'), args = require('minimist')(process.argv.slice(2));
3312
if ((__dirname.endsWith('/node_modules/meshcentral')) || (__dirname.endsWith('\\node_modules\\meshcentral')) || (__dirname.endsWith('/node_modules/meshcentral/')) || (__dirname.endsWith('\\node_modules\\meshcentral\\'))) {
3313
datapath = path.join(__dirname, '../../meshcentral-data');
3314
} else {
@@ -3327,7 +3330,7 @@ function getConfig(createSampleConfig) {
3330
} else {
3331
if (createSampleConfig === true) {
3332
// Copy the "sample-config.json" to give users a starting point
3330
- var sampleConfigPath = path.join(__dirname, 'sample-config.json');
3333
+ const sampleConfigPath = path.join(__dirname, 'sample-config.json');
3334
if (fs.existsSync(sampleConfigPath)) { fs.createReadStream(sampleConfigPath).pipe(fs.createWriteStream(configFilePath)); }
3335
}
3336
}
@@ -3349,16 +3352,16 @@ function getConfig(createSampleConfig) {
3352
3353
// Check if a list of modules are present and install any missing ones
3354
function InstallModules(modules, func) {
3352
- var missingModules = [];
3355
+ const missingModules = [];
3356
if (modules.length > 0) {
3354
- var dependencies = require('./package.json').dependencies;
3357
+ const dependencies = require('./package.json').dependencies;
3358
for (var i in modules) {
3359
// Modules may contain a version tag (foobar@1.0.0), remove it so the module can be found using require
3357
- var moduleNameAndVersion = modules[i];
3358
- var moduleInfo = moduleNameAndVersion.split('@', 2);
3360
+ const moduleNameAndVersion = modules[i];
3361
+ const moduleInfo = moduleNameAndVersion.split('@', 2);
3362
var moduleName = moduleInfo[0];
3363
var moduleVersion = moduleInfo[1];
3361
- if (moduleName == '') { moduleName = moduleNameAndVersion; moduleVersion = undefined; } // If the module name starts with @, don't use @ as a version seperator.
3364
+ if (moduleName == '') { moduleName = moduleNameAndVersion; moduleVersion = null; } // If the module name starts with @, don't use @ as a version seperator.
3365
try {
3366
// Does the module need a specific version?
3367
if (moduleVersion) {
@@ -3366,7 +3369,7 @@ function InstallModules(modules, func) {
3369
} else {
3370
// For all other modules, do the check here.
3371
// Is the module in package.json? Install exact version.
3369
- if (typeof dependencies[moduleName] != undefined) { moduleVersion = dependencies[moduleName]; }
3372
+ if (typeof dependencies[moduleName] != null) { moduleVersion = dependencies[moduleName]; }
3373
require(moduleName);
3374
}
3375
} catch (ex) {
@@ -3404,7 +3407,7 @@ function InstallModule(modulename, func, tag1, tag2) {
3407
process.on('SIGINT', function () { if (meshserver != null) { meshserver.Stop(); meshserver = null; } console.log('Server Ctrl-C exit...'); process.exit(); });
3408
3409
// Add a server warning, warnings will be shown to the administrator on the web application
3407
-var serverWarnings = [];
3410
+const serverWarnings = [];
3411
function addServerWarning(msg, id, args, print) { serverWarnings.push({ msg: msg, id: id, args: args }); if (print !== false) { console.log("WARNING: " + msg); } }
3412
3413
/*
@@ -3447,7 +3450,7 @@ function mainStart() {
3450
// Check for any missing modules.
3451
InstallModules(['minimist'], function () {
3452
// Parse inbound arguments
3450
- var args = require('minimist')(process.argv.slice(2));
3453
+ const args = require('minimist')(process.argv.slice(2));
3454
3455
// Setup the NPM path
3456
if (args.npmpath == null) {