3 var Promise = require('bluebird');
4 var env = require('gitter-web-env');
5 var nconf = env.config;
6 var logger = env.logger;
7 var errorReporter = env.errorReporter;
8 var StatusError = require('statuserror');
9 var checkAlreadyOnUnauthorizedUrl = require('../utils/check-already-on-unauthorized-url');
11 const revokedUserAgents = [].concat(nconf.get('revokedUserAgents'));
13 function validateUserAgentFromReq(req) {
14 let isUserAgentValid = true;
16 // We would be safe without this check but this is just a pre-optimization to avoid going through the logic below
17 if (!revokedUserAgents || revokedUserAgents.length === 0) return true;
19 // If they are missing a user-agent then let them pass because we have nothing to filter on
20 if (!req || !req.headers) return true;
21 var useragentHeader = req.headers['user-agent'];
22 if (!useragentHeader) return true;
24 // We already redirected them to the only page they can visit
25 var alreadyOnUnauthorizedUrl = checkAlreadyOnUnauthorizedUrl(req.url);
26 if (alreadyOnUnauthorizedUrl) return true;
28 isUserAgentValid = !revokedUserAgents.some(needle => {
29 return useragentHeader.includes(needle);
32 errorReporter(err, {}, { module: 'validate-user-agent-from-req' });
34 // Just let them through if it's our fault
38 if (!isUserAgentValid) {
39 logger.warn('user-agent can not be accepted (matches revoked user-agent): ', {
40 userAgent: useragentHeader
43 var err = new StatusError(401, 'user-agent is not allowed');
44 err.revokedUserAgent = true;
49 module.exports = Promise.method(validateUserAgentFromReq);