validateBodyController.js 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. const axios = require('axios');
  2. const urlRegex = require('url-regex');
  3. const validator = require('express-validator/check');
  4. const { subHours } = require('date-fns/');
  5. const { validationResult } = require('express-validator/check');
  6. const { addCooldown, banUser, getCooldowns } = require('../db/user');
  7. const config = require('../config');
  8. exports.validationCriterias = [
  9. validator
  10. .body('email')
  11. .exists()
  12. .withMessage('Email must be provided.')
  13. .isEmail()
  14. .withMessage('Email is not valid.')
  15. .trim()
  16. .normalizeEmail(),
  17. validator
  18. .body('password', 'Password must be at least 8 chars long.')
  19. .exists()
  20. .withMessage('Password must be provided.')
  21. .isLength({ min: 8 }),
  22. ];
  23. exports.validateBody = (req, res, next) => {
  24. const errors = validationResult(req);
  25. if (!errors.isEmpty()) {
  26. const errorsObj = errors.mapped();
  27. const emailError = errorsObj.email && errorsObj.email.msg;
  28. const passwordError = errorsObj.password && errorsObj.password.msg;
  29. return res.status(400).json({ error: emailError || passwordError });
  30. }
  31. return next();
  32. };
  33. const preservedUrls = [
  34. 'login',
  35. 'logout',
  36. 'signup',
  37. 'reset-password',
  38. 'resetpassword',
  39. 'url-password',
  40. 'settings',
  41. 'stats',
  42. 'verify',
  43. 'api',
  44. '404',
  45. 'static',
  46. 'images',
  47. ];
  48. exports.preservedUrls = preservedUrls;
  49. exports.validateUrl = async ({ body, user }, res, next) => {
  50. // Validate URL existence
  51. if (!body.target) return res.status(400).json({ error: 'No target has been provided.' });
  52. // validate URL length
  53. if (body.target.length > 1024) {
  54. return res.status(400).json({ error: 'Maximum URL length is 1024.' });
  55. }
  56. // Validate URL
  57. const isValidUrl = urlRegex({ exact: true, strict: false }).test(body.target);
  58. if (!isValidUrl) return res.status(400).json({ error: 'URL is not valid.' });
  59. // Validate password length
  60. if (body.password && body.password.length > 64) {
  61. return res.status(400).json({ error: 'Maximum password length is 64.' });
  62. }
  63. // Custom URL validations
  64. if (user && body.customurl) {
  65. // Validate custom URL
  66. if (!/^[a-zA-Z0-9-_]+$/g.test(body.customurl.trim())) {
  67. return res.status(400).json({ error: 'Custom URL is not valid.' });
  68. }
  69. // Prevent from using preserved URLs
  70. if (preservedUrls.some(url => url === body.customurl)) {
  71. return res.status(400).json({ error: "You can't use this custom URL name." });
  72. }
  73. // Validate custom URL length
  74. if (body.customurl.length > 64) {
  75. return res.status(400).json({ error: 'Maximum custom URL length is 64.' });
  76. }
  77. }
  78. return next();
  79. };
  80. exports.cooldownCheck = async ({ user }, res, next) => {
  81. if (user) {
  82. const { cooldowns } = await getCooldowns(user);
  83. if (cooldowns.length > 4) {
  84. await banUser(user);
  85. return res.status(400).json({ error: 'Too much malware requests. You are now banned.' });
  86. }
  87. const hasCooldownNow = cooldowns.some(cooldown => cooldown > subHours(new Date(), 12).toJSON());
  88. if (hasCooldownNow) {
  89. return res.status(400).json({ error: 'Cooldown because of a malware URL. Wait 12h' });
  90. }
  91. }
  92. return next();
  93. };
  94. exports.malwareCheck = async ({ body, user }, res, next) => {
  95. const isMalware = await axios.post(
  96. `https://safebrowsing.googleapis.com/v4/threatMatches:find?key=${
  97. config.GOOGLE_SAFE_BROWSING_KEY
  98. }`,
  99. {
  100. client: {
  101. clientId: config.DEFAULT_DOMAIN.toLowerCase().replace('.', ''),
  102. clientVersion: '1.0.0',
  103. },
  104. threatInfo: {
  105. threatTypes: ['MALWARE', 'SOCIAL_ENGINEERING'],
  106. platformTypes: ['WINDOWS'],
  107. threatEntryTypes: ['URL'],
  108. threatEntries: [{ url: body.target }],
  109. },
  110. }
  111. );
  112. if (isMalware.data && isMalware.data.matches) {
  113. await addCooldown(user);
  114. return res.status(400).json({ error: 'Malware detected! Cooldown for 12h.' });
  115. }
  116. return next();
  117. };