Fix formatting issues from merging (#5909)

* fix formatting issues in webserver.js * fix formatting issues is meshcentral.js

mstrhakr committed Mar 10, 2024 at 03:46 UTC 05fca6cb366664f0b1fe6c2ea26da2e741f967f9
2 files changed +72 -71
meshcentral.js
+24 -24
@@ -618,7 +618,7 @@ function CreateMeshCentralServer(config, args) {
618 obj.performServerUpdate = function (version) {
619 if (obj.serverSelfWriteAllowed != true) return false;
620 if ((version == null) || (version == '') || (typeof version != 'string')) { console.log('Starting self upgrade...'); } else { console.log('Starting self upgrade to: ' + version); }
621 - process.exit(200);
621 + process.exit(200);
622 return true;
623 };
624
@@ -648,7 +648,7 @@ function CreateMeshCentralServer(config, args) {
648 // Get new instance of the client
649 const vault = require("node-vault")({ endpoint: obj.args.vault.endpoint, token: obj.args.vault.token });
650 vault.unseal({ key: obj.args.vault.unsealkey })
651 - .then(function() {
651 + .then(function () {
652 if (obj.args.vaultdeleteconfigfiles) {
653 vault.delete('secret/data/' + obj.args.vault.name)
654 .then(function (r) { console.log('Done.'); process.exit(); })
@@ -764,7 +764,7 @@ function CreateMeshCentralServer(config, args) {
764 }
765
766 // Check top level configuration for any unrecognized values
767 - if (config) { for (var i in config) { if ((typeof i == 'string') && (i.length > 0) && (i[0] != '_') && (['settings', 'domaindefaults', 'domains', 'configfiles', 'smtp', 'letsencrypt', 'peers', 'sms', 'messaging', 'sendgrid', 'sendmail', 'firebase', 'firebaserelay', '$schema'].indexOf(i) == -1)) { addServerWarning('Unrecognized configuration option \"' + i + '\".', 3, [ i ]); } } }
767 + if (config) { for (var i in config) { if ((typeof i == 'string') && (i.length > 0) && (i[0] != '_') && (['settings', 'domaindefaults', 'domains', 'configfiles', 'smtp', 'letsencrypt', 'peers', 'sms', 'messaging', 'sendgrid', 'sendmail', 'firebase', 'firebaserelay', '$schema'].indexOf(i) == -1)) { addServerWarning('Unrecognized configuration option \"' + i + '\".', 3, [i]); } } }
768
769 // Read IP lists from files if applicable
770 config.settings.userallowedip = obj.args.userallowedip = readIpListFromFile(obj.args.userallowedip);
@@ -867,10 +867,10 @@ function CreateMeshCentralServer(config, args) {
867 delete user.phone; delete user.otpekey; delete user.otpsecret; delete user.otpkeys; delete user.otphkeys; delete user.otpdev; delete user.otpsms; delete user.otpmsg; // Disable 2FA
868 delete user.msghandle; // Disable users 2fa messaging too
869 var config = getConfig(false);
870 - if(config.domains[user.domain].auth || config.domains[user.domain].authstrategies){
870 + if (config.domains[user.domain].auth || config.domains[user.domain].authstrategies) {
871 console.log('This users domain has external authentication methods enabled so the password will not be changed if you set one')
872 obj.db.Set(user, function () { console.log("Done."); process.exit(); return; });
873 - }else{
873 + } else {
874 if (obj.args.hashpass && (typeof obj.args.hashpass == 'string')) {
875 // Reset an account using a pre-hashed password. Use --hashpassword to pre-hash a password.
876 var hashpasssplit = obj.args.hashpass.split(',');
@@ -878,14 +878,14 @@ function CreateMeshCentralServer(config, args) {
878 user.salt = hashpasssplit[0];
879 user.hash = hashpasssplit[1];
880 obj.db.Set(user, function () { console.log("Done. This command will only work if MeshCentral is stopped."); process.exit(); return; });
881 - } else if(obj.args.pass && (typeof obj.args.pass == 'string')) {
881 + } else if (obj.args.pass && (typeof obj.args.pass == 'string')) {
882 // Hash the password and reset the account.
883 require('./pass').hash(String(obj.args.pass), user.salt, function (err, hash, tag) {
884 if (err) { console.log("Unable to reset password: " + err); process.exit(); return; }
885 user.hash = hash;
886 obj.db.Set(user, function () { console.log("Done."); process.exit(); return; });
887 }, 0);
888 - }else{
888 + } else {
889 console.log('Not setting a users password');
890 obj.db.Set(user, function () { console.log("Done."); process.exit(); return; });
891 }
@@ -1107,7 +1107,7 @@ function CreateMeshCentralServer(config, args) {
1107 for (var j in doc) { if (j.indexOf('.') >= 0) { console.log("Invalid field name (" + j + ") in document: " + json[i]); return; } }
1108 //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]; } } }
1109 //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]; } } }
1110 - }
1110 + }
1111 //for (i in json) { if ((json[i].type == "node") && (json[i].host != null)) { json[i].rname = json[i].host; delete json[i].host; } } // DEBUG: Change host to rname
1112 setTimeout(function () { // If the Mongo database is being created for the first time, there is a race condition here. This will get around it.
1113 obj.db.RemoveAll(function () {
@@ -1386,7 +1386,7 @@ function CreateMeshCentralServer(config, args) {
1386 if (i == '') {
1387 addServerWarning("Unable to load Intel AMT TLS root certificate for default domain.", 5);
1388 } else {
1389 - addServerWarning("Unable to load Intel AMT TLS root certificate for domain " + i + ".", 6, [ i ]);
1389 + addServerWarning("Unable to load Intel AMT TLS root certificate for domain " + i + ".", 6, [i]);
1390 }
1391 }
1392 }
@@ -2156,7 +2156,7 @@ function CreateMeshCentralServer(config, args) {
2156 // Update the server state
2157 obj.updateServerState('state', "stopped");
2158 };
2159 -
2159 +
2160 // Event Dispatch
2161 obj.AddEventDispatch = function (ids, target) {
2162 obj.debug('dispatch', 'AddEventDispatch', ids);
@@ -2478,7 +2478,7 @@ function CreateMeshCentralServer(config, args) {
2478 if (connectType == 1) { state.agentPower = powerState; } else if (connectType == 2) { state.ciraPower = powerState; } else if (connectType == 4) { state.amtPower = powerState; }
2479 var powerState = 0, oldPowerState = state.powerState;
2480 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; }
2481 - if ((state.powerState == null)|| (state.powerState == undefined) || (state.powerState != powerState)) {
2481 + if ((state.powerState == null) || (state.powerState == undefined) || (state.powerState != powerState)) {
2482 state.powerState = powerState;
2483 eventConnectChange = 1;
2484
@@ -2522,7 +2522,7 @@ function CreateMeshCentralServer(config, args) {
2522 if (connectType == 1) { state.agentPower = powerState; } else if (connectType == 2) { state.ciraPower = powerState; } else if (connectType == 4) { state.amtPower = powerState; }
2523 var powerState = 0, oldPowerState = state.powerState;
2524 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; }
2525 - if ((state.powerState == null)|| (state.powerState == undefined) || (state.powerState != powerState)) {
2525 + if ((state.powerState == null) || (state.powerState == undefined) || (state.powerState != powerState)) {
2526 state.powerState = powerState;
2527 eventConnectChange = 1;
2528
@@ -2664,7 +2664,7 @@ function CreateMeshCentralServer(config, args) {
2664 if (obj.fs.existsSync(obj.path.join(meshcorePath, 'meshcore.js')) == false) {
2665 meshcorePath = obj.path.join(__dirname, 'agents');
2666 if (obj.fs.existsSync(obj.path.join(meshcorePath, 'meshcore.js')) == false) {
2667 - obj.defaultMeshCores = obj.defaultMeshCoresHash = { }; if (func != null) { func(false); } // meshcore.js not found
2667 + obj.defaultMeshCores = obj.defaultMeshCoresHash = {}; if (func != null) { func(false); } // meshcore.js not found
2668 }
2669 }
2670
@@ -2730,7 +2730,7 @@ function CreateMeshCentralServer(config, args) {
2730 // We are adding a JS file to the meshcores
2731 var moduleName = modulesDir[i].substring(0, modulesDir[i].length - 3);
2732 if (moduleName.endsWith('.min')) { moduleName = moduleName.substring(0, moduleName.length - 4); } // Remove the ".min" for ".min.js" files.
2733 - const moduleData = [ 'try { addModule("', moduleName, '", "', obj.escapeCodeString(obj.fs.readFileSync(obj.path.join(moduleDirPath, modulesDir[i])).toString('binary')), '"); addedModules.push("', moduleName, '"); } catch (ex) { }\r\n' ];
2733 + const moduleData = ['try { addModule("', moduleName, '", "', obj.escapeCodeString(obj.fs.readFileSync(obj.path.join(moduleDirPath, modulesDir[i])).toString('binary')), '"); addedModules.push("', moduleName, '"); } catch (ex) { }\r\n'];
2734
2735 // Merge this module
2736 // NOTE: "smbios" module makes some non-AI Linux segfault, only include for IA platforms.
@@ -2959,7 +2959,7 @@ function CreateMeshCentralServer(config, args) {
2959 } catch (ex) { }
2960 }
2961 };
2962 -
2962 +
2963 // List of possible mesh agents
2964 obj.meshAgentsArchitectureNumbers = {
2965 0: { id: 0, localname: 'Unknown', rname: 'meshconsole.exe', desc: 'Unknown agent', update: false, amt: true, platform: 'unknown', core: 'linux-noamt', rcore: 'linux-recovery', arcore: 'linux-agentrecovery', tcore: 'linux-tiny' },
@@ -3205,7 +3205,7 @@ function CreateMeshCentralServer(config, args) {
3205 console.log(obj.common.format('Code signed {0}.', agentSignedFunc.objx.meshAgentsArchitectureNumbers[agentSignedFunc.archid].localname));
3206 } else {
3207 // Failed to sign agent
3208 - addServerWarning('Failed to sign \"' + agentSignedFunc.objx.meshAgentsArchitectureNumbers[agentSignedFunc.archid].localname + '\": ' + err, 22, [ agentSignedFunc.objx.meshAgentsArchitectureNumbers[agentSignedFunc.archid].localname, err ]);
3208 + addServerWarning('Failed to sign \"' + agentSignedFunc.objx.meshAgentsArchitectureNumbers[agentSignedFunc.archid].localname + '\": ' + err, 22, [agentSignedFunc.objx.meshAgentsArchitectureNumbers[agentSignedFunc.archid].localname, err]);
3209 }
3210 if (--pendingOperations === 0) { agentSignedFunc.func(); }
3211 }
@@ -3759,7 +3759,7 @@ function CreateMeshCentralServer(config, args) {
3759 try {
3760 const d = new Date(), month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
3761 str = 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');
3762 - obj.fs.write(obj.authlogfile, str, function (err, written, string) { if (err) {console.error(err); } });
3762 + obj.fs.write(obj.authlogfile, str, function (err, written, string) { if (err) { console.error(err); } });
3763 } catch (ex) { console.error(ex); }
3764 }
3765 }
@@ -3858,7 +3858,7 @@ function InstallModules(modules, args, func) {
3858 missingModules.push(moduleNameAndVersion);
3859 }
3860 }
3861 -
3861 +
3862 if (missingModules.length > 0) { if (args.debug) { console.log('Missing Modules: ' + missingModules.join(', ')); } InstallModuleEx(missingModules, args, func); } else { func(); }
3863 }
3864 }
@@ -4007,11 +4007,11 @@ function mainStart() {
4007 if ((typeof config.domains[i].authstrategies.github == 'object') && (typeof config.domains[i].authstrategies.github.clientid == 'string') && (typeof config.domains[i].authstrategies.github.clientsecret == 'string') && (passport.indexOf('passport-github2') == -1)) { passport.push('passport-github2'); }
4008 if ((typeof config.domains[i].authstrategies.azure == 'object') && (typeof config.domains[i].authstrategies.azure.clientid == 'string') && (typeof config.domains[i].authstrategies.azure.clientsecret == 'string') && (typeof config.domains[i].authstrategies.azure.tenantid == 'string') && (passport.indexOf('passport-azure-oauth2') == -1)) { passport.push('passport-azure-oauth2'); passport.push('jwt-simple'); }
4009 if ((typeof config.domains[i].authstrategies.oidc == 'object') && (passport.indexOf('openid-client') == -1)) {
4010 - if ((nodeVersion >= 17)
4011 - || ((Math.floor(nodeVersion) == 16) && (nodeVersion >= 16.13))
4012 - || ((Math.floor(nodeVersion) == 14) && (nodeVersion >= 14.15))
4013 - || ((Math.floor(nodeVersion) == 12) && (nodeVersion >= 12.19))) {
4014 - passport.push('openid-client');
4010 + if ((nodeVersion >= 17)
4011 + || ((Math.floor(nodeVersion) == 16) && (nodeVersion >= 16.13))
4012 + || ((Math.floor(nodeVersion) == 14) && (nodeVersion >= 14.15))
4013 + || ((Math.floor(nodeVersion) == 12) && (nodeVersion >= 12.19))) {
4014 + passport.push('openid-client');
4015 } else {
4016 addServerWarning('This NodeJS version does not support OpenID Connect on MeshCentral.', 25);
4017 delete config.domains[i].authstrategies.oidc;
@@ -4026,7 +4026,7 @@ function mainStart() {
4026
4027 // Build the list of required modules
4028 // NOTE: ALL MODULES MUST HAVE A VERSION NUMBER AND THE VERSION MUST MATCH THAT USED IN Dockerfile
4029 - var modules = ['archiver@7.0.0','body-parser@1.20.2','cbor@5.2.0','compression@1.7.4','cookie-session@2.0.0','express@4.18.2','express-handlebars@5.3.5','express-ws@4.0.0','ipcheck@0.1.0','minimist@1.2.8','multiparty@4.2.3','@yetzt/nedb','node-forge@1.3.1','ua-parser-js@1.0.37','ws@8.14.2','yauzl@2.10.0'];
4029 + var modules = ['archiver@7.0.0', 'body-parser@1.20.2', 'cbor@5.2.0', 'compression@1.7.4', 'cookie-session@2.0.0', 'express@4.18.2', 'express-handlebars@5.3.5', 'express-ws@4.0.0', 'ipcheck@0.1.0', 'minimist@1.2.8', 'multiparty@4.2.3', '@yetzt/nedb', 'node-forge@1.3.1', 'ua-parser-js@1.0.37', 'ws@8.14.2', 'yauzl@2.10.0'];
4030 if (require('os').platform() == 'win32') { modules.push('node-windows@0.1.14'); modules.push('loadavg-windows@1.1.1'); if (sspi == true) { modules.push('node-sspi@0.2.10'); } } // Add Windows modules
4031 if (ldap == true) { modules.push('ldapauth-fork@5.0.5'); }
4032 if (ssh == true) { modules.push('ssh2@1.15.0'); }
webserver.js
+48 -47
@@ -2841,7 +2841,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
2841 // User credentials are being passed in the URL. WARNING: Putting credentials in a URL is bad security... but people are requesting this option.
2842 obj.authenticate(req.query.user, req.query.pass, domain, function (err, userid, passhint, loginOptions) {
2843 // 2FA is not supported in URL authentication method. If user has 2FA enabled, this login method fails.
2844 - var user = obj.users[userid];
2844 + var user = obj.users[userid];
2845 if ((err == null) && checkUserOneTimePasswordRequired(domain, user, req, loginOptions) == true) {
2846 handleRootRequestEx(req, res, domain, direct);
2847 } else if ((userid != null) && (err == null)) {
@@ -5899,11 +5899,11 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
5899 zipfile.readEntry();
5900 });
5901 });
5902 - } else if (entry.fileName == 'MeshAgent.mpkg/Contents/Packages/internal.pkg/Contents/meshagent_osx64_LaunchAgent.plist' ||
5902 + } else if (entry.fileName == 'MeshAgent.mpkg/Contents/Packages/internal.pkg/Contents/meshagent_osx64_LaunchAgent.plist' ||
5903 entry.fileName == 'MeshAgent.mpkg/Contents/Packages/internal.pkg/Contents/meshagent_osx64_LaunchDaemon.plist' ||
5904 entry.fileName == 'MeshAgent.mpkg/Contents/Packages/internal.pkg/Contents/Info.plist' ||
5905 entry.fileName == 'MeshAgent.mpkg/Contents/Packages/internal.pkg/Contents/Resources/postflight' ||
5906 - entry.fileName == 'MeshAgent.mpkg/Contents/Packages/internal.pkg/Contents/Resources/Postflight.sh' ||
5906 + entry.fileName == 'MeshAgent.mpkg/Contents/Packages/internal.pkg/Contents/Resources/Postflight.sh' ||
5907 entry.fileName == 'MeshAgent.mpkg/Uninstall.command') {
5908 // This is a special file entry, we need to fix it.
5909 zipfile.openReadStream(entry, function (err, readStream) {
@@ -5915,7 +5915,8 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
5915 zipfile.readEntry();
5916 });
5917 });
5918 -
5918 + });
5919 +
5920 } else {
5921 // Normal file entry
5922 zipfile.openReadStream(entry, function (err, readStream) {
@@ -6600,18 +6601,18 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6601 obj.app.post(url + 'pluginadmin.ashx', obj.bodyParser.urlencoded({ extended: false }), obj.handlePluginAdminPostReq);
6602 obj.app.get(url + 'pluginHandler.js', obj.handlePluginJS);
6603 }
6603 -
6604 +
6605 // New account CAPTCHA request
6606 if ((domain.newaccountscaptcha != null) && (domain.newaccountscaptcha !== false)) {
6607 obj.app.get(url + 'newAccountCaptcha.ashx', handleNewAccountCaptchaRequest);
6608 }
6608 -
6609 +
6610 // Check CrowdSec Bounser if configured
6611 if (parent.crowdSecBounser != null) {
6612 obj.app.get(url + 'captcha.ashx', handleCaptchaGetRequest);
6613 obj.app.post(url + 'captcha.ashx', obj.bodyParser.urlencoded({ extended: false }), handleCaptchaPostRequest);
6614 }
6614 -
6615 +
6616 // Setup IP-KVM relay if supported
6617 if (domain.ipkvm) {
6618 obj.app.ws(url + 'ipkvm.ashx/*', function (ws, req) {
@@ -6625,7 +6626,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6626 parent.ipKvmManager.handleIpKvmGet(domain, req, res, next);
6627 });
6628 }
6628 -
6629 +
6630 // Setup RDP unless indicated as disabled
6631 if (domain.mstsc !== false) {
6632 obj.app.get(url + 'mstsc.html', function (req, res) { handleMSTSCRequest(req, res, 'mstsc'); });
@@ -6637,7 +6638,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6638 try { require('./apprelays.js').CreateMstscRelay(obj, obj.db, ws, req, obj.args, domain); } catch (ex) { console.log(ex); }
6639 });
6640 }
6640 -
6641 +
6642 // Setup SSH if needed
6643 if (domain.ssh === true) {
6644 obj.app.get(url + 'ssh.html', function (req, res) { handleMSTSCRequest(req, res, 'ssh'); });
@@ -6659,7 +6660,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6660 });
6661 });
6662 }
6662 -
6663 +
6664 // Setup firebase push only server
6665 if ((obj.parent.firebase != null) && (obj.parent.config.firebase)) {
6666 if (obj.parent.config.firebase.pushrelayserver) { parent.debug('email', 'Firebase-pushrelay-handler'); obj.app.post(url + 'firebaserelay.aspx', obj.bodyParser.urlencoded({ extended: false }), handleFirebasePushOnlyRelayRequest); }
@@ -6812,10 +6813,10 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6813 }, handleStrategyLogin);
6814 }
6815 }
6815 -
6816 +
6817 // Server redirects
6818 if (parent.config.domains[i].redirects) { for (var j in parent.config.domains[i].redirects) { if (j[0] != '_') { obj.app.get(url + j, obj.handleDomainRedirect); } } }
6818 -
6819 +
6820 // Server picture
6821 obj.app.get(url + 'serverpic.ashx', function (req, res) {
6822 // Check if we have "server.jpg" in the data folder, if so, use that.
@@ -6843,7 +6844,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6844 }
6845 }
6846 });
6846 -
6847 +
6848 // Receive mesh agent connections
6849 obj.app.ws(url + 'agent.ashx', function (ws, req) {
6850 var domain = checkAgentIpAddress(ws, req);
@@ -6852,7 +6853,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6853 //console.log('Agent connect: ' + req.clientIp);
6854 try { obj.meshAgentHandler.CreateMeshAgent(obj, obj.db, ws, req, obj.args, domain); } catch (e) { console.log(e); }
6855 });
6855 -
6856 +
6857 // Setup MQTT broker over websocket
6858 if (obj.parent.mqttbroker != null) {
6859 obj.app.ws(url + 'mqtt.ashx', function (ws, req) {
@@ -6868,11 +6869,11 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6869 obj.parent.mqttbroker.handle(serialtunnel); // Pass socket wrapper to MQTT broker
6870 });
6871 }
6871 -
6872 +
6873 // Setup any .well-known folders
6874 var p = obj.parent.path.join(obj.parent.datapath, '.well-known' + ((parent.config.domains[i].id == '') ? '' : ('-' + parent.config.domains[i].id)));
6875 if (obj.parent.fs.existsSync(p)) { obj.app.use(url + '.well-known', obj.express.static(p)); }
6875 -
6876 +
6877 // Setup the alternative agent-only port
6878 if (obj.agentapp) {
6879 // Receive mesh agent connections on alternate port
@@ -6882,7 +6883,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6883 if (domain.agentkey && ((req.query.key == null) || (domain.agentkey.indexOf(req.query.key) == -1))) { return; } // If agent key is required and not provided or not valid, just hold the websocket and do nothing.
6884 try { obj.meshAgentHandler.CreateMeshAgent(obj, obj.db, ws, req, obj.args, domain); } catch (e) { console.log(e); }
6885 });
6885 -
6886 +
6887 // Setup mesh relay on alternative agent-only port
6888 obj.agentapp.ws(url + 'meshrelay.ashx', function (ws, req) {
6889 PerformWSSessionAuth(ws, req, true, function (ws1, req1, domain, user, cookie, authData) {
@@ -6893,41 +6894,41 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6894 }
6895 });
6896 });
6896 -
6897 +
6898 // Allows agents to transfer files
6899 obj.agentapp.ws(url + 'devicefile.ashx', function (ws, req) { obj.meshDeviceFileHandler.CreateMeshDeviceFile(obj, ws, null, req, domain); });
6899 -
6900 +
6901 // Setup agent to/from server file transfer handler
6902 obj.agentapp.ws(url + 'agenttransfer.ashx', handleAgentFileTransfer); // Setup agent to/from server file transfer handler
6902 -
6903 +
6904 // Setup agent downloads for meshcore updates
6905 obj.agentapp.get(url + 'meshagents', obj.handleMeshAgentRequest);
6906 }
6906 -
6907 +
6908 // Setup web relay on this web server if needed
6909 // We set this up when a DNS name is used as a web relay instead of a port
6910 if (obj.args.relaydns != null) {
6911 obj.webRelayRouter = require('express').Router();
6911 -
6912 +
6913 // This is the magic URL that will setup the relay session
6914 obj.webRelayRouter.get('/control-redirect.ashx', function (req, res, next) {
6915 if (obj.args.relaydns.indexOf(req.hostname) == -1) { res.sendStatus(404); return; }
6916 if ((req.session.userid == null) && obj.args.user && obj.users['user//' + obj.args.user.toLowerCase()]) { req.session.userid = 'user//' + obj.args.user.toLowerCase(); } // Use a default user if needed
6917 res.set({ 'Cache-Control': 'no-store' });
6918 parent.debug('web', 'webRelaySetup');
6918 -
6919 +
6920 // Decode the relay cookie
6921 if (req.query.c == null) { res.sendStatus(404); return; }
6921 -
6922 +
6923 // Decode and check if this relay cookie is valid
6924 var userid, domainid, domain, nodeid, addr, port, appid, webSessionId, expire, publicid;
6925 const urlCookie = obj.parent.decodeCookie(req.query.c, parent.loginCookieEncryptionKey, 32); // Allow cookies up to 32 minutes old. The web page will renew this cookie every 30 minutes.
6926 if (urlCookie == null) { res.sendStatus(404); return; }
6926 -
6927 +
6928 // Decode the incoming cookie
6929 if ((urlCookie.ruserid != null) && (urlCookie.x != null)) {
6930 if (parent.webserver.destroyedSessions[urlCookie.ruserid + '/' + urlCookie.x] != null) { res.sendStatus(404); return; }
6930 -
6931 +
6932 // This is a standard user, figure out what our web relay will be.
6933 if (req.session.x != urlCookie.x) { req.session.x = urlCookie.x; } // Set the sessionid if missing
6934 if (req.session.userid != urlCookie.ruserid) { req.session.userid = urlCookie.ruserid; } // Set the session userid if missing
@@ -6940,7 +6941,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6941 port = parseInt(req.query.p);
6942 appid = parseInt(req.query.appid);
6943 webSessionId = req.session.userid + '/' + req.session.x;
6943 -
6944 +
6945 // Check that all the required arguments are present
6946 if ((req.session.userid == null) || (req.session.x == null) || (req.query.n == null) || (req.query.p == null) || (parent.webserver.destroyedSessions[webSessionId] != null) || ((req.query.appid != 1) && (req.query.appid != 2))) { res.redirect('/'); return; }
6947 } else if (urlCookie.r == 8) {
@@ -6960,10 +6961,10 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6961 expire = urlCookie.expire;
6962 if ((expire != null) && (expire <= Date.now())) { parent.debug('webrelay', 'expired link'); res.sendStatus(404); return; }
6963 }
6963 -
6964 +
6965 // No session identifier was setup, exit now
6966 if (webSessionId == null) { res.sendStatus(404); return; }
6966 -
6967 +
6968 // Check that we have an exact session on any of the relay DNS names
6969 var xrelaySessionId, xrelaySession, freeRelayHost, oldestRelayTime, oldestRelayHost;
6970 for (var hostIndex in obj.args.relaydns) {
@@ -6987,7 +6988,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
6988 }
6989 return;
6990 }
6990 -
6991 +
6992 // Keep a record of the oldest web relay session, this could be useful.
6993 if (oldestRelayHost == null) {
6994 // Oldest host not set yet, set it
@@ -7002,12 +7003,12 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
7003 }
7004 }
7005 }
7005 -
7006 +
7007 // Check that the user has rights to access this device
7008 parent.webserver.GetNodeWithRights(domain, userid, nodeid, function (node, rights, visible) {
7009 // If there is no remote control or relay rights, reject this web relay
7010 if ((rights & 0x00200008) == 0) { res.sendStatus(404); return; } // MESHRIGHT_REMOTECONTROL or MESHRIGHT_RELAY
7010 -
7011 +
7012 // Check if there is a free relay DNS name we can use
7013 var selectedHost = null;
7014 if (freeRelayHost != null) {
@@ -7018,12 +7019,12 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
7019 selectedHost = oldestRelayHost;
7020 }
7021 xrelaySessionId = webSessionId + '/' + selectedHost;
7021 -
7022 +
7023 if (selectedHost == req.hostname) {
7024 // If this web relay session id is not free, close it now
7025 xrelaySession = webRelaySessions[xrelaySessionId];
7026 if (xrelaySession != null) { xrelaySession.close(); delete webRelaySessions[xrelaySessionId]; }
7026 -
7027 +
7028 // Create a web relay session
7029 const relaySession = require('./apprelays.js').CreateWebRelaySession(obj, db, req, args, domain, userid, nodeid, addr, port, appid, xrelaySessionId, expire, node.mtype);
7030 relaySession.xpublicid = publicid;
@@ -7033,13 +7034,13 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
7034 // If there are not more relay sessions, clear the cleanup timer
7035 if ((Object.keys(webRelaySessions).length == 0) && (obj.cleanupTimer != null)) { clearInterval(webRelayCleanupTimer); obj.cleanupTimer = null; }
7036 }
7036 -
7037 +
7038 // Set the multi-tunnel session
7039 webRelaySessions[xrelaySessionId] = relaySession;
7039 -
7040 +
7041 // Setup the cleanup timer if needed
7042 if (obj.cleanupTimer == null) { webRelayCleanupTimer = setInterval(checkWebRelaySessionsTimeout, 10000); }
7042 -
7043 +
7044 // Redirect to root.
7045 res.redirect('/');
7046 } else {
@@ -7054,26 +7055,26 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
7055 }
7056 });
7057 });
7057 -
7058 +
7059 // Handle all incoming requests as web relays
7060 obj.webRelayRouter.get('/*', function (req, res) { try { handleWebRelayRequest(req, res); } catch (ex) { console.log(ex); } })
7060 -
7061 +
7062 // Handle all incoming requests as web relays
7063 obj.webRelayRouter.post('/*', function (req, res) { try { handleWebRelayRequest(req, res); } catch (ex) { console.log(ex); } })
7063 -
7064 +
7065 // Handle all incoming requests as web relays
7066 obj.webRelayRouter.put('/*', function (req, res) { try { handleWebRelayRequest(req, res); } catch (ex) { console.log(ex); } })
7066 -
7067 +
7068 // Handle all incoming requests as web relays
7069 obj.webRelayRouter.delete('/*', function (req, res) { try { handleWebRelayRequest(req, res); } catch (ex) { console.log(ex); } })
7069 -
7070 +
7071 // Handle all incoming requests as web relays
7072 obj.webRelayRouter.options('/*', function (req, res) { try { handleWebRelayRequest(req, res); } catch (ex) { console.log(ex); } })
7072 -
7073 +
7074 // Handle all incoming requests as web relays
7075 obj.webRelayRouter.head('/*', function (req, res) { try { handleWebRelayRequest(req, res); } catch (ex) { console.log(ex); } })
7076 }
7076 -
7077 +
7078 // Indicates to ExpressJS that the override public folder should be used to serve static files.
7079 if (parent.config.domains[i].webpublicpath != null) {
7080 // Use domain public path
@@ -7082,10 +7083,10 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
7083 // Use override path
7084 obj.app.use(url, obj.express.static(obj.parent.webPublicOverridePath));
7085 }
7085 -
7086 +
7087 // Indicates to ExpressJS that the default public folder should be used to serve static files.
7088 obj.app.use(url, obj.express.static(obj.parent.webPublicPath));
7088 -
7089 +
7090 // Start regular disconnection list flush every 2 minutes.
7091 obj.wsagentsDisconnectionsTimer = setInterval(function () { obj.wsagentsDisconnections = {}; }, 120000);
7092 }
@@ -7329,7 +7330,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates, doneF
7330 if (typeof strategy.custom.tenant_id == 'string') { strategy.custom.preset = preset = 'azure' }
7331 if (strategy.custom.customer_id || strategy.custom.identitysource || strategy.client.client_id.split('.')[2] == 'googleusercontent') { strategy.custom.preset = preset = 'google' }
7332 }
7332 -
7333 +
7334 // Check issuer url
7335 let presetIssuer
7336 if (preset == 'azure') { presetIssuer = 'https://login.microsoftonline.com/' + strategy.custom.tenant_id + '/v2.0'; }