validateBodyController.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. const { promisify } = require('util');
  2. const dns = require('dns');
  3. const axios = require('axios');
  4. const URL = require('url');
  5. const urlRegex = require('url-regex');
  6. const validator = require('express-validator/check');
  7. const { differenceInMinutes, subHours } = require('date-fns/');
  8. const { validationResult } = require('express-validator/check');
  9. const { addCooldown, banUser, getIPCooldown: getIPCooldownCount } = require('../db/user');
  10. const { getBannedDomain, getBannedHost, urlCountFromDate } = require('../db/url');
  11. const subDay = require('date-fns/sub_days');
  12. const { addProtocol } = require('../utils');
  13. const dnsLookup = promisify(dns.lookup);
  14. exports.validationCriterias = [
  15. validator
  16. .body('email')
  17. .exists()
  18. .withMessage('Email must be provided.')
  19. .isEmail()
  20. .withMessage('Email is not valid.')
  21. .trim()
  22. .normalizeEmail(),
  23. validator
  24. .body('password', 'Password must be at least 8 chars long.')
  25. .exists()
  26. .withMessage('Password must be provided.')
  27. .isLength({ min: 8 }),
  28. ];
  29. exports.validateBody = (req, res, next) => {
  30. const errors = validationResult(req);
  31. if (!errors.isEmpty()) {
  32. const errorsObj = errors.mapped();
  33. const emailError = errorsObj.email && errorsObj.email.msg;
  34. const passwordError = errorsObj.password && errorsObj.password.msg;
  35. return res.status(400).json({ error: emailError || passwordError });
  36. }
  37. return next();
  38. };
  39. const preservedUrls = [
  40. 'login',
  41. 'logout',
  42. 'signup',
  43. 'reset-password',
  44. 'resetpassword',
  45. 'url-password',
  46. 'url-info',
  47. 'settings',
  48. 'stats',
  49. 'verify',
  50. 'api',
  51. '404',
  52. 'static',
  53. 'images',
  54. 'banned',
  55. 'terms',
  56. 'privacy',
  57. 'report',
  58. ];
  59. exports.preservedUrls = preservedUrls;
  60. exports.validateUrl = async ({ body, user }, res, next) => {
  61. // Validate URL existence
  62. if (!body.target) return res.status(400).json({ error: 'No target has been provided.' });
  63. // validate URL length
  64. if (body.target.length > 3000) {
  65. return res.status(400).json({ error: 'Maximum URL length is 3000.' });
  66. }
  67. // Validate URL
  68. const isValidUrl = urlRegex({ exact: true, strict: false }).test(body.target);
  69. if (!isValidUrl) return res.status(400).json({ error: 'URL is not valid.' });
  70. // If target is the URL shortener itself
  71. const { host } = URL.parse(addProtocol(body.target));
  72. if (host === process.env.DEFAULT_DOMAIN) {
  73. return res.status(400).json({ error: `${process.env.DEFAULT_DOMAIN} URLs are not allowed.` });
  74. }
  75. // Validate password length
  76. if (body.password && body.password.length > 64) {
  77. return res.status(400).json({ error: 'Maximum password length is 64.' });
  78. }
  79. // Custom URL validations
  80. if (user && body.customurl) {
  81. // Validate custom URL
  82. if (!/^[a-zA-Z0-9-_]+$/g.test(body.customurl.trim())) {
  83. return res.status(400).json({ error: 'Custom URL is not valid.' });
  84. }
  85. // Prevent from using preserved URLs
  86. if (preservedUrls.some(url => url === body.customurl)) {
  87. return res.status(400).json({ error: "You can't use this custom URL name." });
  88. }
  89. // Validate custom URL length
  90. if (body.customurl.length > 64) {
  91. return res.status(400).json({ error: 'Maximum custom URL length is 64.' });
  92. }
  93. }
  94. return next();
  95. };
  96. exports.cooldownCheck = async user => {
  97. if (user && user.cooldowns) {
  98. if (user.cooldowns.length > 4) {
  99. await banUser(user);
  100. throw new Error('Too much malware requests. You are now banned.');
  101. }
  102. const hasCooldownNow = user.cooldowns.some(
  103. cooldown => cooldown > subHours(new Date(), 12).toJSON()
  104. );
  105. if (hasCooldownNow) {
  106. throw new Error('Cooldown because of a malware URL. Wait 12h');
  107. }
  108. }
  109. };
  110. exports.ipCooldownCheck = async (req, res, next) => {
  111. const cooldonwConfig = Number(process.env.NON_USER_COOLDOWN);
  112. if (req.user || !cooldonwConfig) return next();
  113. const cooldownDate = await getIPCooldownCount(req.realIp);
  114. if (cooldownDate) {
  115. const timeToWait = cooldonwConfig - differenceInMinutes(new Date(), cooldownDate);
  116. return res
  117. .status(400)
  118. .json({ error: `Non-users are limited. Wait ${timeToWait} minutes or log in.` });
  119. }
  120. next();
  121. };
  122. exports.malwareCheck = async (user, target) => {
  123. const isMalware = await axios.post(
  124. `https://safebrowsing.googleapis.com/v4/threatMatches:find?key=${
  125. process.env.GOOGLE_SAFE_BROWSING_KEY
  126. }`,
  127. {
  128. client: {
  129. clientId: process.env.DEFAULT_DOMAIN.toLowerCase().replace('.', ''),
  130. clientVersion: '1.0.0',
  131. },
  132. threatInfo: {
  133. threatTypes: [
  134. 'THREAT_TYPE_UNSPECIFIED',
  135. 'MALWARE',
  136. 'SOCIAL_ENGINEERING',
  137. 'UNWANTED_SOFTWARE',
  138. 'POTENTIALLY_HARMFUL_APPLICATION',
  139. ],
  140. platformTypes: ['ANY_PLATFORM', 'PLATFORM_TYPE_UNSPECIFIED'],
  141. threatEntryTypes: ['EXECUTABLE', 'URL', 'THREAT_ENTRY_TYPE_UNSPECIFIED'],
  142. threatEntries: [{ url: target }],
  143. },
  144. }
  145. );
  146. if (isMalware.data && isMalware.data.matches) {
  147. if (user) {
  148. await addCooldown(user);
  149. }
  150. throw new Error(user ? 'Malware detected! Cooldown for 12h.' : 'Malware detected!');
  151. }
  152. };
  153. exports.urlCountsCheck = async email => {
  154. const { count } = await urlCountFromDate({
  155. email,
  156. date: subDay(new Date(), 1).toJSON(),
  157. });
  158. if (count > Number(process.env.USER_LIMIT_PER_DAY)) {
  159. throw new Error(
  160. `You have reached your daily limit (${process.env.USER_LIMIT_PER_DAY}). Please wait 24h.`
  161. );
  162. }
  163. };
  164. exports.checkBannedDomain = async domain => {
  165. const isDomainBanned = await getBannedDomain(domain);
  166. if (isDomainBanned) {
  167. throw new Error('URL is containing malware/scam.');
  168. }
  169. };
  170. exports.checkBannedHost = async domain => {
  171. let isHostBanned;
  172. try {
  173. const dnsRes = await dnsLookup(domain);
  174. isHostBanned = await getBannedHost(dnsRes && dnsRes.address);
  175. } catch (error) {
  176. isHostBanned = null;
  177. }
  178. if (isHostBanned) {
  179. throw new Error('URL is containing malware/scam.');
  180. }
  181. };