MeshMessenger customization improvements.

Ylian Saint-Hilaire committed Jan 26, 2021 at 11:46 UTC 2c632cfcf0b2034c6406551d49292beee6aff2e8
5 files changed +211 -146
agents/meshcore.js
+1 -1
@@ -2626,7 +2626,7 @@ function openUserDesktopUrl(url) {
2626 child = require('child_process').execFile(process.env['windir'] + '\\system32\\cmd.exe', ['cmd']);
2627 child.stderr.on('data', function () { });
2628 child.stdout.on('data', function () { });
2629 - child.stdin.write('SCHTASKS /CREATE /F /TN MeshChatTask /SC ONCE /ST 00:00 /RU ' + user + ' /TR "' + process.env['windir'] + '\\system32\\cmd.exe /C START ' + url + '"\r\n');
2629 + child.stdin.write('SCHTASKS /CREATE /F /TN MeshChatTask /SC ONCE /ST 00:00 /RU ' + user + ' /TR "' + process.env['windir'] + '\\system32\\cmd.exe /C START ' + url.split('&').join('^&') + '"\r\n');
2630 child.stdin.write('SCHTASKS /RUN /TN MeshChatTask\r\n');
2631 child.stdin.write('SCHTASKS /DELETE /F /TN MeshChatTask\r\n');
2632 child.stdin.write('exit\r\n');
meshagent.js
+1
@@ -1140,6 +1140,7 @@ module.exports.CreateMeshAgent = function (parent, db, ws, req, args, domain) {
1140
1141 // Process incoming agent JSON data
1142 function processAgentData(msg) {
1143 + if (obj.agentInfo == null) return;
1144 var i, str = msg.toString('utf8'), command = null;
1145 if (str[0] == '{') {
1146 try { command = JSON.parse(str); } catch (ex) {
meshuser.js
+2 -2
@@ -2727,9 +2727,9 @@ module.exports.CreateMeshUser = function (parent, db, ws, req, args, domain, use
2727 var httpsPort = ((args.aliasport == null) ? args.port : args.aliasport); // Use HTTPS alias port is specified
2728 var xdomain = (domain.dns == null) ? domain.id : '';
2729 if (xdomain != '') xdomain += "/";
2730 - var url = "https://" + parent.getWebServerName(domain) + ":" + httpsPort + "/" + xdomain + "messenger?id=meshmessenger/" + encodeURIComponent(command.nodeid) + "/" + encodeURIComponent(user._id) + "&title=" + encodeURIComponent(user.name);
2730 + var url = "https://" + parent.getWebServerName(domain) + ":" + httpsPort + "/" + xdomain + "messenger?id=meshmessenger/" + encodeURIComponent(command.nodeid) + "/" + encodeURIComponent(user._id);
2731
2732 - // Create the notification message
2732 + // Open a web page on the remote device
2733 routeCommandToNode({ 'action': 'openUrl', 'nodeid': command.nodeid, 'userid': user._id, 'username': user.name, 'url': url });
2734 });
2735 break;
views/messenger.handlebars
+7 -2
@@ -76,6 +76,8 @@
76 getUserMediaSupport(function (x) { userMediaSupport = x; })
77 var meshMessengerTitle = '{{{meshMessengerTitle}}}';
78 var meshMessengerImage = '{{{meshMessengerImage}}}';
79 + var remoteUserName = '{{{username}}}';
80 + var remoteUserId = '{{{userid}}}';
81 var webrtcconfiguration = '{{{webrtconfig}}}';
82 if (webrtcconfiguration == '') { webrtcconfiguration = null; } else { try { webrtcconfiguration = JSON.parse(decodeURIComponent(webrtcconfiguration)); } catch (ex) { console.log('Invalid WebRTC config: "' + webrtcconfiguration + '".'); webrtcconfiguration = null; } }
83 var windowFocus = true;
@@ -101,8 +103,11 @@
103 }
104
105 // Set the title
104 - if (args.title) { QH('xtitle', EscapeHtml(args.title).split(' ').join('&nbsp')); document.title = document.title + ' - ' + args.title; }
105 - else if (meshMessengerTitle == '!') { QH('xtitle', EscapeHtml("MeshMessenger")); } else { QH('xtitle', meshMessengerTitle); }
106 + var newTitle = '';
107 + if (args.title) { newTitle = decodeURIComponent(args.title); document.title = document.title + ' - ' + decodeURIComponent(args.title); }
108 + else if (meshMessengerTitle == '!') { newTitle = "MeshMessenger"; } else { newTitle = decodeURIComponent(meshMessengerTitle); }
109 + newTitle = newTitle.split('{0}').join(decodeURIComponent(remoteUserName)).split('{1}').join(decodeURIComponent(remoteUserId));
110 + QH('xtitle', EscapeHtml(newTitle).split(' ').join('&nbsp'));
111
112 // Setup web notifications
113 if (Notification) { QV('notifyButton', Notification.permission != 'granted'); }
webserver.js
+200 -141
@@ -2309,111 +2309,112 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
2309
2310 // If a user exists and is logged in, serve the default app, otherwise server the login app.
2311 if (req.session && req.session.userid && obj.users[req.session.userid]) {
2312 - var user = obj.users[req.session.userid];
2313 - if (req.session.domainid != domain.id) { // Check if the session is for the correct domain
2314 - parent.debug('web', 'handleRootRequestEx: incorrect domain.');
2315 - req.session = null;
2316 - res.redirect(domain.url + getQueryPortion(req)); // BAD***
2317 - return;
2318 - }
2312 + const user = obj.users[req.session.userid];
2313 + const xdbGetFunc = function dbGetFunc(err, states) {
2314 + if (dbGetFunc.req.session.domainid != domain.id) { // Check if the session is for the correct domain
2315 + parent.debug('web', 'handleRootRequestEx: incorrect domain.');
2316 + dbGetFunc.req.session = null;
2317 + dbGetFunc.res.redirect(domain.url + getQueryPortion(dbGetFunc.req)); // BAD***
2318 + return;
2319 + }
2320
2320 - // Check if this is a locked account
2321 - if ((user.siteadmin != null) && ((user.siteadmin & 32) != 0) && (user.siteadmin != 0xFFFFFFFF)) {
2322 - // Locked account
2323 - parent.debug('web', 'handleRootRequestEx: locked account.');
2324 - delete req.session.userid;
2325 - delete req.session.domainid;
2326 - delete req.session.currentNode;
2327 - delete req.session.passhint;
2328 - delete req.session.cuserid;
2329 - req.session.messageid = 110; // Account locked.
2330 - res.redirect(domain.url + getQueryPortion(req)); // BAD***
2331 - return;
2332 - }
2321 + // Check if this is a locked account
2322 + if ((dbGetFunc.user.siteadmin != null) && ((dbGetFunc.user.siteadmin & 32) != 0) && (dbGetFunc.user.siteadmin != 0xFFFFFFFF)) {
2323 + // Locked account
2324 + parent.debug('web', 'handleRootRequestEx: locked account.');
2325 + delete dbGetFunc.req.session.userid;
2326 + delete dbGetFunc.req.session.domainid;
2327 + delete dbGetFunc.req.session.currentNode;
2328 + delete dbGetFunc.req.session.passhint;
2329 + delete dbGetFunc.req.session.cuserid;
2330 + dbGetFunc.req.session.messageid = 110; // Account locked.
2331 + dbGetFunc.res.redirect(domain.url + getQueryPortion(dbGetFunc.req)); // BAD***
2332 + return;
2333 + }
2334
2334 - var viewmode = 1;
2335 - if (req.session.viewmode) {
2336 - viewmode = req.session.viewmode;
2337 - delete req.session.viewmode;
2338 - } else if (req.query.viewmode) {
2339 - viewmode = req.query.viewmode;
2340 - }
2341 - var currentNode = '';
2342 - if (req.session.currentNode) {
2343 - currentNode = req.session.currentNode;
2344 - delete req.session.currentNode;
2345 - } else if (req.query.node) {
2346 - currentNode = 'node/' + domain.id + '/' + req.query.node;
2347 - }
2348 - var logoutcontrols = {};
2349 - if (obj.args.nousers != true) { logoutcontrols.name = user.name; }
2350 -
2351 - // Give the web page a list of supported server features
2352 - features = 0;
2353 - features2 = 0;
2354 - if (obj.args.wanonly == true) { features += 0x00000001; } // WAN-only mode
2355 - if (obj.args.lanonly == true) { features += 0x00000002; } // LAN-only mode
2356 - if (obj.args.nousers == true) { features += 0x00000004; } // Single user mode
2357 - if (domain.userQuota == -1) { features += 0x00000008; } // No server files mode
2358 - if (obj.args.mpstlsoffload) { features += 0x00000010; } // No mutual-auth CIRA
2359 - if ((parent.config.settings.allowframing != null) || (domain.allowframing != null)) { features += 0x00000020; } // Allow site within iframe
2360 - if ((obj.parent.mailserver != null) && (obj.parent.certificates.CommonName != null) && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly != true)) { features += 0x00000040; } // Email invites
2361 - if (obj.args.webrtc == true) { features += 0x00000080; } // Enable WebRTC (Default false for now)
2362 - // 0x00000100 --> This feature flag is free for future use.
2363 - if (obj.args.allowhighqualitydesktop !== false) { features += 0x00000200; } // Enable AllowHighQualityDesktop (Default true)
2364 - if ((obj.args.lanonly == true) || (obj.args.mpsport == 0)) { features += 0x00000400; } // No CIRA
2365 - if ((obj.parent.serverSelfWriteAllowed == true) && (user != null) && (user.siteadmin == 0xFFFFFFFF)) { features += 0x00000800; } // Server can self-write (Allows self-update)
2366 - if ((parent.config.settings.no2factorauth !== true) && (domain.auth != 'sspi') && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.nousers !== true) && (user._id.split('/')[2][0] != '~')) { features += 0x00001000; } // 2FA login supported
2367 - if (domain.agentnoproxy === true) { features += 0x00002000; } // Indicates that agents should be installed without using a HTTP proxy
2368 - if ((parent.config.settings.no2factorauth !== true) && domain.yubikey && domain.yubikey.id && domain.yubikey.secret && (user._id.split('/')[2][0] != '~')) { features += 0x00004000; } // Indicates Yubikey support
2369 - if (domain.geolocation == true) { features += 0x00008000; } // Enable geo-location features
2370 - if ((domain.passwordrequirements != null) && (domain.passwordrequirements.hint === true)) { features += 0x00010000; } // Enable password hints
2371 - if (parent.config.settings.no2factorauth !== true) { features += 0x00020000; } // Enable WebAuthn/FIDO2 support
2372 - if ((obj.args.nousers != true) && (domain.passwordrequirements != null) && (domain.passwordrequirements.force2factor === true) && (user._id.split('/')[2][0] != '~')) {
2373 - // Check if we can skip 2nd factor auth because of the source IP address
2374 - var skip2factor = false;
2375 - if ((req != null) && (req.clientIp != null) && (domain.passwordrequirements != null) && (domain.passwordrequirements.skip2factor != null)) {
2376 - for (var i in domain.passwordrequirements.skip2factor) {
2377 - if (require('ipcheck').match(req.clientIp, domain.passwordrequirements.skip2factor[i]) === true) { skip2factor = true; }
2335 + var viewmode = 1;
2336 + if (dbGetFunc.req.session.viewmode) {
2337 + viewmode = dbGetFunc.req.session.viewmode;
2338 + delete dbGetFunc.req.session.viewmode;
2339 + } else if (dbGetFunc.req.query.viewmode) {
2340 + viewmode = dbGetFunc.req.query.viewmode;
2341 + }
2342 + var currentNode = '';
2343 + if (dbGetFunc.req.session.currentNode) {
2344 + currentNode = dbGetFunc.req.session.currentNode;
2345 + delete dbGetFunc.req.session.currentNode;
2346 + } else if (dbGetFunc.req.query.node) {
2347 + currentNode = 'node/' + domain.id + '/' + dbGetFunc.req.query.node;
2348 + }
2349 + var logoutcontrols = {};
2350 + if (obj.args.nousers != true) { logoutcontrols.name = user.name; }
2351 +
2352 + // Give the web page a list of supported server features
2353 + features = 0;
2354 + features2 = 0;
2355 + if (obj.args.wanonly == true) { features += 0x00000001; } // WAN-only mode
2356 + if (obj.args.lanonly == true) { features += 0x00000002; } // LAN-only mode
2357 + if (obj.args.nousers == true) { features += 0x00000004; } // Single user mode
2358 + if (domain.userQuota == -1) { features += 0x00000008; } // No server files mode
2359 + if (obj.args.mpstlsoffload) { features += 0x00000010; } // No mutual-auth CIRA
2360 + if ((parent.config.settings.allowframing != null) || (domain.allowframing != null)) { features += 0x00000020; } // Allow site within iframe
2361 + if ((obj.parent.mailserver != null) && (obj.parent.certificates.CommonName != null) && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly != true)) { features += 0x00000040; } // Email invites
2362 + if (obj.args.webrtc == true) { features += 0x00000080; } // Enable WebRTC (Default false for now)
2363 + // 0x00000100 --> This feature flag is free for future use.
2364 + if (obj.args.allowhighqualitydesktop !== false) { features += 0x00000200; } // Enable AllowHighQualityDesktop (Default true)
2365 + if ((obj.args.lanonly == true) || (obj.args.mpsport == 0)) { features += 0x00000400; } // No CIRA
2366 + if ((obj.parent.serverSelfWriteAllowed == true) && (dbGetFunc.user != null) && (dbGetFunc.user.siteadmin == 0xFFFFFFFF)) { features += 0x00000800; } // Server can self-write (Allows self-update)
2367 + if ((parent.config.settings.no2factorauth !== true) && (domain.auth != 'sspi') && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.nousers !== true) && (dbGetFunc.user._id.split('/')[2][0] != '~')) { features += 0x00001000; } // 2FA login supported
2368 + if (domain.agentnoproxy === true) { features += 0x00002000; } // Indicates that agents should be installed without using a HTTP proxy
2369 + if ((parent.config.settings.no2factorauth !== true) && domain.yubikey && domain.yubikey.id && domain.yubikey.secret && (dbGetFunc.user._id.split('/')[2][0] != '~')) { features += 0x00004000; } // Indicates Yubikey support
2370 + if (domain.geolocation == true) { features += 0x00008000; } // Enable geo-location features
2371 + if ((domain.passwordrequirements != null) && (domain.passwordrequirements.hint === true)) { features += 0x00010000; } // Enable password hints
2372 + if (parent.config.settings.no2factorauth !== true) { features += 0x00020000; } // Enable WebAuthn/FIDO2 support
2373 + if ((obj.args.nousers != true) && (domain.passwordrequirements != null) && (domain.passwordrequirements.force2factor === true) && (dbGetFunc.user._id.split('/')[2][0] != '~')) {
2374 + // Check if we can skip 2nd factor auth because of the source IP address
2375 + var skip2factor = false;
2376 + if ((dbGetFunc.req != null) && (dbGetFunc.req.clientIp != null) && (domain.passwordrequirements != null) && (domain.passwordrequirements.skip2factor != null)) {
2377 + for (var i in domain.passwordrequirements.skip2factor) {
2378 + if (require('ipcheck').match(dbGetFunc.req.clientIp, domain.passwordrequirements.skip2factor[i]) === true) { skip2factor = true; }
2379 + }
2380 }
2381 + if (skip2factor == false) { features += 0x00040000; } // Force 2-factor auth
2382 }
2380 - if (skip2factor == false) { features += 0x00040000; } // Force 2-factor auth
2381 - }
2382 - if ((domain.auth == 'sspi') || (domain.auth == 'ldap')) { features += 0x00080000; } // LDAP or SSPI in use, warn that users must login first before adding a user to a group.
2383 - if (domain.amtacmactivation) { features += 0x00100000; } // Intel AMT ACM activation/upgrade is possible
2384 - if (domain.usernameisemail) { features += 0x00200000; } // Username is email address
2385 - if (parent.mqttbroker != null) { features += 0x00400000; } // This server supports MQTT channels
2386 - if (((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.email2factor != false)) && (parent.mailserver != null)) { features += 0x00800000; } // using email for 2FA is allowed
2387 - if (domain.agentinvitecodes == true) { features += 0x01000000; } // Support for agent invite codes
2388 - if (parent.smsserver != null) { features += 0x02000000; } // SMS messaging is supported
2389 - if ((parent.smsserver != null) && ((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.sms2factor != false))) { features += 0x04000000; } // SMS 2FA is allowed
2390 - if (domain.sessionrecording != null) { features += 0x08000000; } // Server recordings enabled
2391 - if (domain.urlswitching === false) { features += 0x10000000; } // Disables the URL switching feature
2392 - if (domain.novnc === false) { features += 0x20000000; } // Disables noVNC
2393 - if (domain.mstsc !== true) { features += 0x40000000; } // Disables MSTSC.js
2394 - if (obj.isTrustedCert(domain) == false) { features += 0x80000000; } // Indicate we are not using a trusted certificate
2395 - if (obj.parent.amtManager != null) { features2 += 1; } // Indicates that the Intel AMT manager is active
2396 -
2397 - // Create a authentication cookie
2398 - const authCookie = obj.parent.encodeCookie({ userid: user._id, domainid: domain.id, ip: req.clientIp }, obj.parent.loginCookieEncryptionKey);
2399 - const authRelayCookie = obj.parent.encodeCookie({ ruserid: user._id, domainid: domain.id }, obj.parent.loginCookieEncryptionKey);
2400 -
2401 - // Send the main web application
2402 - var extras = (req.query.key != null) ? ('&key=' + req.query.key) : '';
2403 - if ((!obj.args.user) && (obj.args.nousers != true) && (nologout == false)) { logoutcontrols.logoutUrl = (domain.url + 'logout?' + Math.random() + extras); } // If a default user is in use or no user mode, don't display the logout button
2404 - var httpsPort = ((obj.args.aliasport == null) ? obj.args.port : obj.args.aliasport); // Use HTTPS alias port is specified
2383 + if ((domain.auth == 'sspi') || (domain.auth == 'ldap')) { features += 0x00080000; } // LDAP or SSPI in use, warn that users must login first before adding a user to a group.
2384 + if (domain.amtacmactivation) { features += 0x00100000; } // Intel AMT ACM activation/upgrade is possible
2385 + if (domain.usernameisemail) { features += 0x00200000; } // Username is email address
2386 + if (parent.mqttbroker != null) { features += 0x00400000; } // This server supports MQTT channels
2387 + if (((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.email2factor != false)) && (parent.mailserver != null)) { features += 0x00800000; } // using email for 2FA is allowed
2388 + if (domain.agentinvitecodes == true) { features += 0x01000000; } // Support for agent invite codes
2389 + if (parent.smsserver != null) { features += 0x02000000; } // SMS messaging is supported
2390 + if ((parent.smsserver != null) && ((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.sms2factor != false))) { features += 0x04000000; } // SMS 2FA is allowed
2391 + if (domain.sessionrecording != null) { features += 0x08000000; } // Server recordings enabled
2392 + if (domain.urlswitching === false) { features += 0x10000000; } // Disables the URL switching feature
2393 + if (domain.novnc === false) { features += 0x20000000; } // Disables noVNC
2394 + if (domain.mstsc !== true) { features += 0x40000000; } // Disables MSTSC.js
2395 + if (obj.isTrustedCert(domain) == false) { features += 0x80000000; } // Indicate we are not using a trusted certificate
2396 + if (obj.parent.amtManager != null) { features2 += 1; } // Indicates that the Intel AMT manager is active
2397 +
2398 + // Create a authentication cookie
2399 + const authCookie = obj.parent.encodeCookie({ userid: dbGetFunc.user._id, domainid: domain.id, ip: req.clientIp }, obj.parent.loginCookieEncryptionKey);
2400 + const authRelayCookie = obj.parent.encodeCookie({ ruserid: dbGetFunc.user._id, domainid: domain.id }, obj.parent.loginCookieEncryptionKey);
2401 +
2402 + // Send the main web application
2403 + var extras = (dbGetFunc.req.query.key != null) ? ('&key=' + dbGetFunc.req.query.key) : '';
2404 + if ((!obj.args.user) && (obj.args.nousers != true) && (nologout == false)) { logoutcontrols.logoutUrl = (domain.url + 'logout?' + Math.random() + extras); } // If a default user is in use or no user mode, don't display the logout button
2405 + var httpsPort = ((obj.args.aliasport == null) ? obj.args.port : obj.args.aliasport); // Use HTTPS alias port is specified
2406
2406 - // Clean up the U2F challenge if needed
2407 - if (req.session.u2fchallenge) { delete req.session.u2fchallenge; };
2407 + // Clean up the U2F challenge if needed
2408 + if (dbGetFunc.req.session.u2fchallenge) { delete dbGetFunc.req.session.u2fchallenge; };
2409
2409 - // Intel AMT Scanning options
2410 - var amtscanoptions = '';
2411 - if (typeof domain.amtscanoptions == 'string') { amtscanoptions = encodeURIComponent(domain.amtscanoptions); }
2412 - else if (obj.common.validateStrArray(domain.amtscanoptions)) { domain.amtscanoptions = domain.amtscanoptions.join(','); amtscanoptions = encodeURIComponent(domain.amtscanoptions); }
2410 + // Intel AMT Scanning options
2411 + var amtscanoptions = '';
2412 + if (typeof domain.amtscanoptions == 'string') { amtscanoptions = encodeURIComponent(domain.amtscanoptions); }
2413 + else if (obj.common.validateStrArray(domain.amtscanoptions)) { domain.amtscanoptions = domain.amtscanoptions.join(','); amtscanoptions = encodeURIComponent(domain.amtscanoptions); }
2414 +
2415 + // Fetch the web state
2416 + parent.debug('web', 'handleRootRequestEx: success.');
2417
2414 - // Fetch the web state
2415 - parent.debug('web', 'handleRootRequestEx: success.');
2416 - obj.db.Get('ws' + user._id, function (err, states) {
2418 var webstate = '';
2419 if ((err == null) && (states != null) && (Array.isArray(states)) && (states.length == 1) && (states[0].state != null)) { webstate = obj.filterUserWebState(states[0].state); }
2420 if ((webstate == '') && (typeof domain.defaultuserwebstate == 'object')) { webstate = JSON.stringify(domain.defaultuserwebstate); } // User has no web state, use defaults.
@@ -2445,7 +2446,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
2446 }
2447
2448 // Refresh the session
2448 - render(req, res, getRenderPage('default', req, domain), getRenderArgs({
2449 + render(dbGetFunc.req, dbGetFunc.res, getRenderPage('default', dbGetFunc.req, domain), getRenderArgs({
2450 authCookie: authCookie,
2451 authRelayCookie: authRelayCookie,
2452 viewmode: viewmode,
@@ -2468,8 +2469,12 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
2469 webstate: encodeURIComponent(webstate).replace(/'/g, '%27'),
2470 amtscanoptions: amtscanoptions,
2471 pluginHandler: (parent.pluginHandler == null) ? 'null' : parent.pluginHandler.prepExports()
2471 - }, req, domain));
2472 - });
2472 + }, dbGetFunc.req, domain));
2473 + }
2474 + xdbGetFunc.req = req;
2475 + xdbGetFunc.res = res;
2476 + xdbGetFunc.user = user;
2477 + obj.db.Get('ws' + user._id, xdbGetFunc);
2478 } else {
2479 // Send back the login application
2480 // If this is a 2 factor auth request, look for a hardware key challenge.
@@ -2748,6 +2753,18 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
2753 var options = { webrtconfig: webRtcConfig };
2754 if (typeof domain.meshmessengertitle == 'string') { options.meshMessengerTitle = domain.meshmessengertitle; } else { options.meshMessengerTitle = '!'; }
2755
2756 + // Get the userid and name
2757 + if ((domain.meshmessengertitle != null) && (req.query.id != null) && (req.query.id.startsWith('meshmessenger/node'))) {
2758 + var idSplit = decodeURIComponent(req.query.id).split('/');
2759 + if (idSplit.length == 7) {
2760 + const user = obj.users[idSplit[4] + '/' + idSplit[5] + '/' + idSplit[6]];
2761 + if (user != null) {
2762 + if (domain.meshmessengertitle.indexOf('{0}') >= 0) { options.username = encodeURIComponent(user.name ? user.name : user._id.split('/')[2]).replace(/'/g, '%27'); }
2763 + if (domain.meshmessengertitle.indexOf('{1}') >= 0) { options.userid = encodeURIComponent(user._id.split('/')[2]).replace(/'/g, '%27'); }
2764 + }
2765 + }
2766 + }
2767 +
2768 // Render the page
2769 res.set({ 'Cache-Control': 'no-store' });
2770 render(req, res, getRenderPage('messenger', req, domain), getRenderArgs(options, req, domain));
@@ -4134,18 +4151,18 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4151 if ((obj.parent.config.settings != null) && ((obj.parent.config.settings.lockagentdownload == true) || (domain.lockagentdownload == true)) && (req.session.userid == null)) { res.sendStatus(401); return; }
4152
4153 if ((req.query.meshinstall != null) && (req.query.id != null)) {
4137 - if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
4154 + if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { try { res.sendStatus(404); } catch (ex) { } return; } // Check 3FA URL key
4155
4156 // Send meshagent with included self installer for a specific platform back
4157 // Start by getting the .msh for this request
4158 var meshsettings = getMshFromRequest(req, res, domain);
4142 - if (meshsettings == null) { res.sendStatus(401); return; }
4159 + if (meshsettings == null) { try { res.sendStatus(401); } catch (ex) { } return; }
4160
4161 // Get the interactive install script, this only works for non-Windows agents
4162 var agentid = parseInt(req.query.meshinstall);
4163 var argentInfo = obj.parent.meshAgentBinaries[agentid];
4164 var scriptInfo = obj.parent.meshAgentInstallScripts[6];
4148 - if ((argentInfo == null) || (scriptInfo == null) || (argentInfo.platform == 'win32')) { res.sendStatus(404); return; }
4165 + if ((argentInfo == null) || (scriptInfo == null) || (argentInfo.platform == 'win32')) { try { res.sendStatus(404); } catch (ex) { } return; }
4166
4167 // Change the .msh file into JSON format and merge it into the install script
4168 var tokens, msh = {}, meshsettingslines = meshsettings.split('\r').join('').split('\n');
@@ -4162,18 +4179,27 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4179 } else if (req.query.id != null) {
4180 // Send a specific mesh agent back
4181 var argentInfo = obj.parent.meshAgentBinaries[req.query.id];
4165 - if (argentInfo == null) { res.sendStatus(404); return; }
4182 + if (argentInfo == null) { try { res.sendStatus(404); } catch (ex) { } return; }
4183
4184 // Download PDB debug files, only allowed for administrator or accounts with agent dump access
4185 if (req.query.pdb == 1) {
4169 - if ((req.session == null) || (req.session.userid == null)) { res.sendStatus(404); return; }
4186 + if ((req.session == null) || (req.session.userid == null)) { try { res.sendStatus(404); } catch (ex) { } return; }
4187 var user = obj.users[req.session.userid];
4171 - if (user == null) { res.sendStatus(404); return; }
4188 + if (user == null) { try { res.sendStatus(404); } catch (ex) { } return; }
4189 if ((user != null) && ((user.siteadmin == 0xFFFFFFFF) || ((Array.isArray(obj.parent.config.settings.agentcoredumpusers)) && (obj.parent.config.settings.agentcoredumpusers.indexOf(user._id) >= 0)))) {
4173 - if (argentInfo.id == 3) { setContentDispositionHeader(res, 'application/octet-stream', 'MeshService.pdb', null, 'MeshService.pdb'); res.sendFile(argentInfo.path.split('MeshService-signed.exe').join('MeshService.pdb')); return; }
4174 - if (argentInfo.id == 4) { setContentDispositionHeader(res, 'application/octet-stream', 'MeshService64.pdb', null, 'MeshService64.pdb'); res.sendFile(argentInfo.path.split('MeshService64-signed.exe').join('MeshService64.pdb')); return; }
4190 + if (argentInfo.id == 3) {
4191 + setContentDispositionHeader(res, 'application/octet-stream', 'MeshService.pdb', null, 'MeshService.pdb');
4192 + try { res.sendFile(argentInfo.path.split('MeshService-signed.exe').join('MeshService.pdb')); } catch (ex) { }
4193 + return;
4194 + }
4195 + if (argentInfo.id == 4) {
4196 + setContentDispositionHeader(res, 'application/octet-stream', 'MeshService64.pdb', null, 'MeshService64.pdb');
4197 + try { res.sendFile(argentInfo.path.split('MeshService64-signed.exe').join('MeshService64.pdb')); } catch (ex) { }
4198 + return;
4199 + }
4200 }
4176 - res.sendStatus(404); return;
4201 + try { res.sendStatus(404); } catch (ex) { }
4202 + return;
4203 }
4204
4205 if ((req.query.meshid == null) || (argentInfo.platform != 'win32')) {
@@ -4181,7 +4207,8 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4207 var meshagentFilename = argentInfo.rname;
4208 if ((domain.agentcustomization != null) && (typeof domain.agentcustomization.filename == 'string')) { meshagentFilename = domain.agentcustomization.filename; }
4209 setContentDispositionHeader(res, 'application/octet-stream', meshagentFilename, null, 'meshagent');
4184 - if (argentInfo.data == null) { res.sendFile(argentInfo.path); } else { res.end(argentInfo.data); }
4210 + if (argentInfo.data == null) { res.sendFile(argentInfo.path); } else { res.send(argentInfo.data); }
4211 + return;
4212 } else {
4213 // Check if the meshid is a time limited, encrypted cookie
4214 var meshcookie = obj.parent.decodeCookie(req.query.meshid, obj.parent.invitationLinkEncryptionKey);
@@ -4190,11 +4217,11 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4217 // We are going to embed the .msh file into the Windows executable (signed or not).
4218 // First, fetch the mesh object to build the .msh file
4219 var mesh = obj.meshes['mesh/' + domain.id + '/' + req.query.meshid];
4193 - if (mesh == null) { res.sendStatus(401); return; }
4220 + if (mesh == null) { try { res.sendStatus(401); } catch (ex) { } return; }
4221
4222 // If required, check if this user has rights to do this
4223 if ((obj.parent.config.settings != null) && ((obj.parent.config.settings.lockagentdownload == true) || (domain.lockagentdownload == true))) {
4197 - if ((domain.id != mesh.domain) || ((obj.GetMeshRights(req.session.userid, mesh) & 1) == 0)) { res.sendStatus(401); return; }
4224 + if ((domain.id != mesh.domain) || ((obj.GetMeshRights(req.session.userid, mesh) & 1) == 0)) { try { res.sendStatus(401); } catch (ex) { } return; }
4225 }
4226
4227 var meshidhex = Buffer.from(req.query.meshid.replace(/\@/g, '+').replace(/\$/g, '/'), 'base64').toString('hex').toUpperCase();
@@ -4241,13 +4268,14 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4268 if (parent.agentTranslations != null) { meshsettings += 'translation=' + parent.agentTranslations + '\r\n'; }
4269 setContentDispositionHeader(res, 'application/octet-stream', meshfilename, null, argentInfo.rname);
4270 obj.parent.exeHandler.streamExeWithMeshPolicy({ platform: 'win32', sourceFileName: obj.parent.meshAgentBinaries[req.query.id].path, destinationStream: res, msh: meshsettings, peinfo: obj.parent.meshAgentBinaries[req.query.id].pe });
4271 + return;
4272 }
4273 } else if (req.query.script != null) {
4246 - if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
4274 + if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { try { res.sendStatus(404); } catch (ex) { } return; } // Check 3FA URL key
4275
4276 // Send a specific mesh install script back
4277 var scriptInfo = obj.parent.meshAgentInstallScripts[req.query.script];
4250 - if (scriptInfo == null) { res.sendStatus(404); return; }
4278 + if (scriptInfo == null) { try { res.sendStatus(404); } catch (ex) { } return; }
4279 setContentDispositionHeader(res, 'application/octet-stream', scriptInfo.rname, null, 'script');
4280 var data = scriptInfo.data;
4281 var cmdoptions = { wgetoptionshttp: '', wgetoptionshttps: '', curloptionshttp: '-L ', curloptionshttps: '-L ' }
@@ -4263,8 +4291,9 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4291 }
4292 for (var i in cmdoptions) { data = data.split('{{{' + i + '}}}').join(cmdoptions[i]); }
4293 res.send(data);
4294 + return;
4295 } else if (req.query.meshcmd != null) {
4267 - if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
4296 + if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { try { res.sendStatus(404); } catch (ex) { } return; } // Check 3FA URL key
4297
4298 // Send meshcmd for a specific platform back
4299 var agentid = parseInt(req.query.meshcmd);
@@ -4287,7 +4316,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4316 // No signed agents, we are going to merge a new MeshCmd.
4317 if ((agentid < 10000) && (obj.parent.meshAgentBinaries[agentid + 10000] != null)) { agentid += 10000; } // Avoid merging javascript to a signed mesh agent.
4318 var argentInfo = obj.parent.meshAgentBinaries[agentid];
4290 - if ((argentInfo == null) || (obj.parent.defaultMeshCmd == null)) { res.sendStatus(404); return; }
4319 + if ((argentInfo == null) || (obj.parent.defaultMeshCmd == null)) { try { res.sendStatus(404); } catch (ex) { } return; }
4320 setContentDispositionHeader(res, 'application/octet-stream', 'meshcmd' + ((req.query.meshcmd <= 4) ? '.exe' : ''), null, 'meshcmd');
4321 res.statusCode = 200;
4322 if (argentInfo.signedMeshCmdPath != null) {
@@ -4298,12 +4327,12 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4327 obj.parent.exeHandler.streamExeWithJavaScript({ platform: argentInfo.platform, sourceFileName: argentInfo.path, destinationStream: res, js: Buffer.from(obj.parent.defaultMeshCmd, 'utf8'), peinfo: argentInfo.pe });
4328 }
4329 } else if (req.query.meshaction != null) {
4301 - if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
4330 + if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { try { res.sendStatus(404); } catch (ex) { } return; } // Check 3FA URL key
4331 var user = obj.users[req.session.userid];
4332 if (user == null) {
4333 // Check if we have an authentication cookie
4334 var c = obj.parent.decodeCookie(req.query.auth, obj.parent.loginCookieEncryptionKey);
4306 - if (c == null) { res.sendStatus(404); return; }
4335 + if (c == null) { try { res.sendStatus(404); } catch (ex) { } return; }
4336
4337 // Download tools using a cookie
4338 if (c.download == req.query.meshaction) {
@@ -4311,32 +4340,35 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4340 var p = obj.path.join(__dirname, 'agents', 'MeshCentralRouter.exe');
4341 if (obj.fs.existsSync(p)) {
4342 setContentDispositionHeader(res, 'application/octet-stream', 'MeshCentralRouter.exe', null, 'MeshCentralRouter.exe');
4314 - try { res.sendFile(p); } catch (e) { res.sendStatus(404); }
4315 - } else { res.sendStatus(404); }
4343 + try { res.sendFile(p); } catch (ex) { }
4344 + } else { try { res.sendStatus(404); } catch (ex) { } }
4345 + return;
4346 } else if (req.query.meshaction == 'winassistant') {
4347 var p = obj.path.join(__dirname, 'agents', 'MeshCentralAssistant.exe');
4348 if (obj.fs.existsSync(p)) {
4349 setContentDispositionHeader(res, 'application/octet-stream', 'MeshCentralAssistant.exe', null, 'MeshCentralAssistant.exe');
4320 - try { res.sendFile(p); } catch (e) { res.sendStatus(404); }
4321 - } else { res.sendStatus(404); }
4350 + try { res.sendFile(p); } catch (ex) { }
4351 + } else { try { res.sendStatus(404); } catch (ex) { } }
4352 + return;
4353 } else if (req.query.meshaction == 'macrouter') {
4354 var p = obj.path.join(__dirname, 'agents', 'MeshCentralRouter.dmg');
4355 if (obj.fs.existsSync(p)) {
4356 setContentDispositionHeader(res, 'application/octet-stream', 'MeshCentralRouter.dmg', null, 'MeshCentralRouter.dmg');
4326 - try { res.sendFile(p); } catch (e) { res.sendStatus(404); }
4327 - } else { res.sendStatus(404); }
4357 + try { res.sendFile(p); } catch (ex) { }
4358 + } else { try { res.sendStatus(404); } catch (ex) { } }
4359 + return;
4360 }
4361 return;
4362 }
4363
4364 // Check if the cookie authenticates a user
4333 - if (c.userid == null) { res.sendStatus(404); return; }
4365 + if (c.userid == null) { try { res.sendStatus(404); } catch (ex) { } return; }
4366 user = obj.users[c.userid];
4335 - if (user == null) { res.sendStatus(404); return; }
4367 + if (user == null) { try { res.sendStatus(404); } catch (ex) { } return; }
4368 }
4369 if ((req.query.meshaction == 'route') && (req.query.nodeid != null)) {
4370 obj.db.Get(req.query.nodeid, function (err, nodes) {
4339 - if (nodes.length != 1) { res.sendStatus(401); return; }
4371 + if (nodes.length != 1) { try { res.sendStatus(401); } catch (ex) { } return; }
4372 var node = nodes[0];
4373
4374 // Create the meshaction.txt file for meshcmd.exe
@@ -4360,6 +4392,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4392
4393 setContentDispositionHeader(res, 'application/octet-stream', 'meshaction.txt', null, 'meshaction.txt');
4394 res.send(JSON.stringify(meshaction, null, ' '));
4395 + return;
4396 });
4397 } else if (req.query.meshaction == 'generic') {
4398 var meshaction = {
@@ -4375,36 +4408,41 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4408 if (obj.args.lanonly != true) { meshaction.serverUrl = 'wss://' + obj.getWebServerName(domain) + ':' + httpsPort + '/' + ((domain.id == '') ? '' : ('/' + domain.id)) + 'meshrelay.ashx'; }
4409 setContentDispositionHeader(res, 'application/octet-stream', 'meshaction.txt', null, 'meshaction.txt');
4410 res.send(JSON.stringify(meshaction, null, ' '));
4411 + return;
4412 } else if (req.query.meshaction == 'winrouter') {
4413 console.log('t2');
4414 var p = obj.path.join(__dirname, 'agents', 'MeshCentralRouter.exe');
4415 if (obj.fs.existsSync(p)) {
4416 setContentDispositionHeader(res, 'application/octet-stream', 'MeshCentralRouter.exe', null, 'MeshCentralRouter.exe');
4383 - try { res.sendFile(p); } catch (e) { res.sendStatus(404); }
4384 - } else { res.sendStatus(404); }
4417 + try { res.sendFile(p); } catch (ex) { }
4418 + } else { try { res.sendStatus(404); } catch (ex) { } }
4419 + return;
4420 } else if (req.query.meshaction == 'winassistant') {
4421 var p = obj.path.join(__dirname, 'agents', 'MeshCentralAssistant.exe');
4422 if (obj.fs.existsSync(p)) {
4423 setContentDispositionHeader(res, 'application/octet-stream', 'MeshCentralAssistant.exe', null, 'MeshCentralAssistant.exe');
4389 - try { res.sendFile(p); } catch (e) { res.sendStatus(404); }
4390 - } else { res.sendStatus(404); }
4424 + try { res.sendFile(p); } catch (ex) { }
4425 + } else { try { res.sendStatus(404); } catch (ex) { } }
4426 + return;
4427 } else if (req.query.meshaction == 'macrouter') {
4428 var p = obj.path.join(__dirname, 'agents', 'MeshCentralRouter.dmg');
4429 if (obj.fs.existsSync(p)) {
4430 setContentDispositionHeader(res, 'application/octet-stream', 'MeshCentralRouter.dmg', null, 'MeshCentralRouter.dmg');
4395 - try { res.sendFile(p); } catch (e) { res.sendStatus(404); }
4396 - } else { res.sendStatus(404); }
4431 + try { res.sendFile(p); } catch (ex) { }
4432 + } else { try { res.sendStatus(404); } catch (ex) { } }
4433 + return;
4434 } else {
4398 - res.sendStatus(401);
4435 + try { res.sendStatus(401); } catch (ex) { }
4436 + return;
4437 }
4438 } else {
4439 domain = checkUserIpAddress(req, res); // Recheck the domain to apply user IP filtering.
4440 if (domain == null) return;
4403 - if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
4404 - if ((req.session == null) || (req.session.userid == null)) { res.sendStatus(404); return; }
4441 + if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { try { res.sendStatus(404); } catch (ex) { } return; } // Check 3FA URL key
4442 + if ((req.session == null) || (req.session.userid == null)) { try { res.sendStatus(404); } catch (ex) { } return; }
4443 var user = null, coreDumpsAllowed = false;
4444 if (typeof req.session.userid == 'string') { user = obj.users[req.session.userid]; }
4407 - if (user == null) { res.sendStatus(404); return; }
4445 + if (user == null) { try { res.sendStatus(404); } catch (ex) { } return; }
4446
4447 // Check if this user has access to agent core dumps
4448 if ((obj.parent.config.settings.agentcoredump === true) && ((user.siteadmin == 0xFFFFFFFF) || ((Array.isArray(obj.parent.config.settings.agentcoredumpusers)) && (obj.parent.config.settings.agentcoredumpusers.indexOf(user._id) >= 0)))) {
@@ -4417,7 +4455,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4455 setContentDispositionHeader(res, 'application/octet-stream', req.query.dldump, null, 'file.bin');
4456 res.sendFile(dumpFile); return;
4457 } else {
4420 - res.sendStatus(404); return;
4458 + try { res.sendStatus(404); } catch (ex) { } return;
4459 }
4460 }
4461
@@ -4488,7 +4526,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4526 if (req.query.dlcore != null) {
4527 // Download mesh core
4528 var bin = parent.defaultMeshCores[req.query.dlcore];
4491 - if (bin == null) { res.sendStatus(404); return; }
4529 + if (bin == null) { try { res.sendStatus(404); } catch (ex) { } return; }
4530 setContentDispositionHeader(res, 'application/octet-stream', req.query.dlcore + '.js', null, 'meshcore.js');
4531 res.send(bin);
4532 return;
@@ -4497,7 +4535,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4535 if (req.query.dlccore != null) {
4536 // Download compressed mesh core
4537 var bin = parent.defaultMeshCoresDeflate[req.query.dlccore];
4500 - if (bin == null) { res.sendStatus(404); return; }
4538 + if (bin == null) { try { res.sendStatus(404); } catch (ex) { } return; }
4539 setContentDispositionHeader(res, 'application/octet-stream', req.query.dlccore + '.js.deflate', null, 'meshcore.js.deflate');
4540 res.send(bin);
4541 return;
@@ -4524,6 +4562,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4562 if (coreDumpsAllowed) { response += '<a href="' + originalUrl + '?dumps=1' + (req.query.key ? ('&key=' + req.query.key) : '') + '">MeshAgent Crash Dumps</a>'; }
4563 response += '</body></html>';
4564 res.send(response);
4565 + return;
4566 }
4567 };
4568
@@ -4932,6 +4971,26 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
4971 // Extend the session time by forcing a change to the session every minute.
4972 if (req.session.userid != null) { req.session.nowInMinutes = Math.floor(Date.now() / 60e3); } else { delete req.session.nowInMinutes; }
4973
4974 + // Debugging code, this will stop the agent from crashing if two responses are made to the same request.
4975 + const render = res.render;
4976 + const send = res.send;
4977 + res.render = function renderWrapper(...args) {
4978 + Error.captureStackTrace(this);
4979 + return render.apply(this, args);
4980 + };
4981 + res.send = function sendWrapper(...args) {
4982 + try {
4983 + send.apply(this, args);
4984 + } catch (err) {
4985 + console.error(`Error in res.send | ${err.code} | ${err.message} | ${res.stack}`);
4986 + try {
4987 + var errlogpath = null;
4988 + if (typeof parent.args.mesherrorlogpath == 'string') { errlogpath = parent.path.join(parent.args.mesherrorlogpath, 'mesherrors.txt'); } else { errlogpath = parent.getConfigFilePath('mesherrors.txt'); }
4989 + parent.fs.appendFileSync(errlogpath, new Date().toLocaleString() + ': ' + `Error in res.send | ${err.code} | ${err.message} | ${res.stack}` + '\r\n');
4990 + } catch (ex) { console.log('ERROR: Unable to write to mesherrors.txt.'); }
4991 + }
4992 + };
4993 +
4994 // Continue processing the request
4995 return next();
4996 });