validateBodyController.js 5.0 KB

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