validators.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. import { body, param } from "express-validator";
  2. import { isAfter, subDays, subHours, addMilliseconds } from "date-fns";
  3. import urlRegex from "url-regex-safe";
  4. import { promisify } from "util";
  5. import bcrypt from "bcryptjs";
  6. import axios from "axios";
  7. import dns from "dns";
  8. import URL from "url";
  9. import ms from "ms";
  10. import { CustomError, addProtocol, removeWww } from "../utils";
  11. import query from "../queries";
  12. import knex from "../knex";
  13. import env from "../env";
  14. const dnsLookup = promisify(dns.lookup);
  15. export const preservedUrls = [
  16. "login",
  17. "logout",
  18. "signup",
  19. "reset-password",
  20. "resetpassword",
  21. "url-password",
  22. "url-info",
  23. "settings",
  24. "stats",
  25. "verify",
  26. "api",
  27. "404",
  28. "static",
  29. "images",
  30. "banned",
  31. "terms",
  32. "privacy",
  33. "protected",
  34. "report",
  35. "pricing"
  36. ];
  37. export const checkUser = (value, { req }) => !!req.user;
  38. export const createLink = [
  39. body("target")
  40. .exists({ checkNull: true, checkFalsy: true })
  41. .withMessage("Target is missing.")
  42. .isString()
  43. .trim()
  44. .isLength({ min: 1, max: 2040 })
  45. .withMessage("Maximum URL length is 2040.")
  46. .customSanitizer(addProtocol)
  47. .custom(
  48. value =>
  49. urlRegex({ exact: true, strict: false }).test(value) ||
  50. /^(?!https?)(\w+):\/\//.test(value)
  51. )
  52. .withMessage("URL is not valid.")
  53. .custom(value => removeWww(URL.parse(value).host) !== env.DEFAULT_DOMAIN)
  54. .withMessage(`${env.DEFAULT_DOMAIN} URLs are not allowed.`),
  55. body("password")
  56. .optional({ nullable: true, checkFalsy: true })
  57. .custom(checkUser)
  58. .withMessage("Only users can use this field.")
  59. .isString()
  60. .isLength({ min: 3, max: 64 })
  61. .withMessage("Password length must be between 3 and 64."),
  62. body("customurl")
  63. .optional({ nullable: true, checkFalsy: true })
  64. .custom(checkUser)
  65. .withMessage("Only users can use this field.")
  66. .isString()
  67. .trim()
  68. .isLength({ min: 1, max: 64 })
  69. .withMessage("Custom URL length must be between 1 and 64.")
  70. .custom(value => /^[a-zA-Z0-9-_]+$/g.test(value))
  71. .withMessage("Custom URL is not valid")
  72. .custom(value => !preservedUrls.some(url => url.toLowerCase() === value))
  73. .withMessage("You can't use this custom URL."),
  74. body("reuse")
  75. .optional({ nullable: true })
  76. .custom(checkUser)
  77. .withMessage("Only users can use this field.")
  78. .isBoolean()
  79. .withMessage("Reuse must be boolean."),
  80. body("description")
  81. .optional({ nullable: true, checkFalsy: true })
  82. .isString()
  83. .trim()
  84. .isLength({ min: 0, max: 2040 })
  85. .withMessage("Description length must be between 0 and 2040."),
  86. body("expire_in")
  87. .optional({ nullable: true, checkFalsy: true })
  88. .isString()
  89. .trim()
  90. .custom(value => {
  91. try {
  92. return !!ms(value);
  93. } catch {
  94. return false;
  95. }
  96. })
  97. .withMessage("Expire format is invalid. Valid examples: 1m, 8h, 42 days.")
  98. .customSanitizer(ms)
  99. .custom(value => value >= ms("1m"))
  100. .withMessage("Minimum expire time should be '1 minute'.")
  101. .customSanitizer(value => addMilliseconds(new Date(), value).toISOString()),
  102. body("domain")
  103. .optional({ nullable: true, checkFalsy: true })
  104. .custom(checkUser)
  105. .withMessage("Only users can use this field.")
  106. .isString()
  107. .withMessage("Domain should be string.")
  108. .customSanitizer(value => value.toLowerCase())
  109. .customSanitizer(value => removeWww(URL.parse(value).hostname || value))
  110. .custom(async (address, { req }) => {
  111. if (address === env.DEFAULT_DOMAIN) {
  112. req.body.domain = null;
  113. return;
  114. }
  115. const domain = await query.domain.find({
  116. address,
  117. user_id: req.user.id
  118. });
  119. req.body.domain = domain || null;
  120. if (!domain) return Promise.reject();
  121. })
  122. .withMessage("You can't use this domain.")
  123. ];
  124. export const editLink = [
  125. body("target")
  126. .optional({ checkFalsy: true, nullable: true })
  127. .isString()
  128. .trim()
  129. .isLength({ min: 1, max: 2040 })
  130. .withMessage("Maximum URL length is 2040.")
  131. .customSanitizer(addProtocol)
  132. .custom(
  133. value =>
  134. urlRegex({ exact: true, strict: false }).test(value) ||
  135. /^(?!https?)(\w+):\/\//.test(value)
  136. )
  137. .withMessage("URL is not valid.")
  138. .custom(value => removeWww(URL.parse(value).host) !== env.DEFAULT_DOMAIN)
  139. .withMessage(`${env.DEFAULT_DOMAIN} URLs are not allowed.`),
  140. body("password")
  141. .optional({ nullable: true, checkFalsy: true })
  142. .isString()
  143. .isLength({ min: 3, max: 64 })
  144. .withMessage("Password length must be between 3 and 64."),
  145. body("address")
  146. .optional({ checkFalsy: true, nullable: true })
  147. .isString()
  148. .trim()
  149. .isLength({ min: 1, max: 64 })
  150. .withMessage("Custom URL length must be between 1 and 64.")
  151. .custom(value => /^[a-zA-Z0-9-_]+$/g.test(value))
  152. .withMessage("Custom URL is not valid")
  153. .custom(value => !preservedUrls.some(url => url.toLowerCase() === value))
  154. .withMessage("You can't use this custom URL."),
  155. body("expire_in")
  156. .optional({ nullable: true, checkFalsy: true })
  157. .isString()
  158. .trim()
  159. .custom(value => {
  160. try {
  161. return !!ms(value);
  162. } catch {
  163. return false;
  164. }
  165. })
  166. .withMessage("Expire format is invalid. Valid examples: 1m, 8h, 42 days.")
  167. .customSanitizer(ms)
  168. .custom(value => value >= ms("1m"))
  169. .withMessage("Minimum expire time should be '1 minute'.")
  170. .customSanitizer(value => addMilliseconds(new Date(), value).toISOString()),
  171. body("description")
  172. .optional({ nullable: true, checkFalsy: true })
  173. .isString()
  174. .trim()
  175. .isLength({ min: 0, max: 2040 })
  176. .withMessage("Description length must be between 0 and 2040."),
  177. param("id", "ID is invalid.")
  178. .exists({ checkFalsy: true, checkNull: true })
  179. .isLength({ min: 36, max: 36 })
  180. ];
  181. export const redirectProtected = [
  182. body("password", "Password is invalid.")
  183. .exists({ checkFalsy: true, checkNull: true })
  184. .isString()
  185. .isLength({ min: 3, max: 64 })
  186. .withMessage("Password length must be between 3 and 64."),
  187. param("id", "ID is invalid.")
  188. .exists({ checkFalsy: true, checkNull: true })
  189. .isLength({ min: 36, max: 36 })
  190. ];
  191. export const addDomain = [
  192. body("address", "Domain is not valid")
  193. .exists({ checkFalsy: true, checkNull: true })
  194. .isLength({ min: 3, max: 64 })
  195. .withMessage("Domain length must be between 3 and 64.")
  196. .trim()
  197. .customSanitizer(value => {
  198. const parsed = URL.parse(value);
  199. return removeWww(parsed.hostname || parsed.href);
  200. })
  201. .custom(value => urlRegex({ exact: true, strict: false }).test(value))
  202. .custom(value => value !== env.DEFAULT_DOMAIN)
  203. .withMessage("You can't use the default domain.")
  204. .custom(async value => {
  205. const domain = await query.domain.find({ address: value });
  206. if (domain?.user_id || domain?.banned) return Promise.reject();
  207. })
  208. .withMessage("You can't add this domain."),
  209. body("homepage")
  210. .optional({ checkFalsy: true, nullable: true })
  211. .customSanitizer(addProtocol)
  212. .custom(value => urlRegex({ exact: true, strict: false }).test(value))
  213. .withMessage("Homepage is not valid.")
  214. ];
  215. export const removeDomain = [
  216. param("id", "ID is invalid.")
  217. .exists({
  218. checkFalsy: true,
  219. checkNull: true
  220. })
  221. .isLength({ min: 36, max: 36 })
  222. ];
  223. export const deleteLink = [
  224. param("id", "ID is invalid.")
  225. .exists({
  226. checkFalsy: true,
  227. checkNull: true
  228. })
  229. .isLength({ min: 36, max: 36 })
  230. ];
  231. export const reportLink = [
  232. body("link", "No link has been provided.")
  233. .exists({
  234. checkFalsy: true,
  235. checkNull: true
  236. })
  237. .customSanitizer(addProtocol)
  238. .custom(
  239. value => removeWww(URL.parse(value).hostname) === env.DEFAULT_DOMAIN
  240. )
  241. .withMessage(`You can only report a ${env.DEFAULT_DOMAIN} link.`)
  242. ];
  243. export const banLink = [
  244. param("id", "ID is invalid.")
  245. .exists({
  246. checkFalsy: true,
  247. checkNull: true
  248. })
  249. .isLength({ min: 36, max: 36 }),
  250. body("host", '"host" should be a boolean.')
  251. .optional({
  252. nullable: true
  253. })
  254. .isBoolean(),
  255. body("user", '"user" should be a boolean.')
  256. .optional({
  257. nullable: true
  258. })
  259. .isBoolean(),
  260. body("userlinks", '"userlinks" should be a boolean.')
  261. .optional({
  262. nullable: true
  263. })
  264. .isBoolean(),
  265. body("domain", '"domain" should be a boolean.')
  266. .optional({
  267. nullable: true
  268. })
  269. .isBoolean()
  270. ];
  271. export const getStats = [
  272. param("id", "ID is invalid.")
  273. .exists({
  274. checkFalsy: true,
  275. checkNull: true
  276. })
  277. .isLength({ min: 36, max: 36 })
  278. ];
  279. export const signup = [
  280. body("password", "Password is not valid.")
  281. .exists({ checkFalsy: true, checkNull: true })
  282. .isLength({ min: 8, max: 64 })
  283. .withMessage("Password length must be between 8 and 64."),
  284. body("email", "Email is not valid.")
  285. .exists({ checkFalsy: true, checkNull: true })
  286. .trim()
  287. .isEmail()
  288. .isLength({ min: 0, max: 255 })
  289. .withMessage("Email length must be max 255.")
  290. .custom(async (value, { req }) => {
  291. const user = await query.user.find({ email: value });
  292. if (user) {
  293. req.user = user;
  294. }
  295. if (user?.verified) return Promise.reject();
  296. })
  297. .withMessage("You can't use this email address.")
  298. ];
  299. export const login = [
  300. body("password", "Password is not valid.")
  301. .exists({ checkFalsy: true, checkNull: true })
  302. .isLength({ min: 8, max: 64 })
  303. .withMessage("Password length must be between 8 and 64."),
  304. body("email", "Email is not valid.")
  305. .exists({ checkFalsy: true, checkNull: true })
  306. .trim()
  307. .isEmail()
  308. .isLength({ min: 0, max: 255 })
  309. .withMessage("Email length must be max 255.")
  310. ];
  311. export const changePassword = [
  312. body("password", "Password is not valid.")
  313. .exists({ checkFalsy: true, checkNull: true })
  314. .isLength({ min: 8, max: 64 })
  315. .withMessage("Password length must be between 8 and 64.")
  316. ];
  317. export const resetPasswordRequest = [
  318. body("email", "Email is not valid.")
  319. .exists({ checkFalsy: true, checkNull: true })
  320. .trim()
  321. .isEmail()
  322. .isLength({ min: 0, max: 255 })
  323. .withMessage("Email length must be max 255."),
  324. body("password", "Password is not valid.")
  325. .exists({ checkFalsy: true, checkNull: true })
  326. .isLength({ min: 8, max: 64 })
  327. .withMessage("Password length must be between 8 and 64.")
  328. ];
  329. export const resetEmailRequest = [
  330. body("email", "Email is not valid.")
  331. .exists({ checkFalsy: true, checkNull: true })
  332. .trim()
  333. .isEmail()
  334. .isLength({ min: 0, max: 255 })
  335. .withMessage("Email length must be max 255.")
  336. ];
  337. export const deleteUser = [
  338. body("password", "Password is not valid.")
  339. .exists({ checkFalsy: true, checkNull: true })
  340. .isLength({ min: 8, max: 64 })
  341. .custom(async (password, { req }) => {
  342. const isMatch = await bcrypt.compare(password, req.user.password);
  343. if (!isMatch) return Promise.reject();
  344. })
  345. ];
  346. export const cooldown = (user: User) => {
  347. if (!env.GOOGLE_SAFE_BROWSING_KEY || !user || !user.cooldowns) return;
  348. // If has active cooldown then throw error
  349. const hasCooldownNow = user.cooldowns.some(cooldown =>
  350. isAfter(subHours(new Date(), 12), new Date(cooldown))
  351. );
  352. if (hasCooldownNow) {
  353. throw new CustomError("Cooldown because of a malware URL. Wait 12h");
  354. }
  355. };
  356. export const malware = async (user: User, target: string) => {
  357. if (!env.GOOGLE_SAFE_BROWSING_KEY) return;
  358. const isMalware = await axios.post(
  359. `https://safebrowsing.googleapis.com/v4/threatMatches:find?key=${env.GOOGLE_SAFE_BROWSING_KEY}`,
  360. {
  361. client: {
  362. clientId: env.DEFAULT_DOMAIN.toLowerCase().replace(".", ""),
  363. clientVersion: "1.0.0"
  364. },
  365. threatInfo: {
  366. threatTypes: [
  367. "THREAT_TYPE_UNSPECIFIED",
  368. "MALWARE",
  369. "SOCIAL_ENGINEERING",
  370. "UNWANTED_SOFTWARE",
  371. "POTENTIALLY_HARMFUL_APPLICATION"
  372. ],
  373. platformTypes: ["ANY_PLATFORM", "PLATFORM_TYPE_UNSPECIFIED"],
  374. threatEntryTypes: [
  375. "EXECUTABLE",
  376. "URL",
  377. "THREAT_ENTRY_TYPE_UNSPECIFIED"
  378. ],
  379. threatEntries: [{ url: target }]
  380. }
  381. }
  382. );
  383. if (!isMalware.data || !isMalware.data.matches) return;
  384. if (user) {
  385. const [updatedUser] = await query.user.update(
  386. { id: user.id },
  387. {
  388. cooldowns: knex.raw("array_append(cooldowns, ?)", [
  389. new Date().toISOString()
  390. ]) as any
  391. }
  392. );
  393. // Ban if too many cooldowns
  394. if (updatedUser.cooldowns.length > 2) {
  395. await query.user.update({ id: user.id }, { banned: true });
  396. throw new CustomError("Too much malware requests. You are now banned.");
  397. }
  398. }
  399. throw new CustomError(
  400. user ? "Malware detected! Cooldown for 12h." : "Malware detected!"
  401. );
  402. };
  403. export const linksCount = async (user?: User) => {
  404. if (!user) return;
  405. const count = await query.link.total({
  406. user_id: user.id,
  407. created_at: [">", subDays(new Date(), 1).toISOString()]
  408. });
  409. if (count > env.USER_LIMIT_PER_DAY) {
  410. throw new CustomError(
  411. `You have reached your daily limit (${env.USER_LIMIT_PER_DAY}). Please wait 24h.`
  412. );
  413. }
  414. };
  415. export const bannedDomain = async (domain: string) => {
  416. const isBanned = await query.domain.find({
  417. address: domain,
  418. banned: true
  419. });
  420. if (isBanned) {
  421. throw new CustomError("URL is containing malware/scam.", 400);
  422. }
  423. };
  424. export const bannedHost = async (domain: string) => {
  425. let isBanned;
  426. try {
  427. const dnsRes = await dnsLookup(domain);
  428. if (!dnsRes || !dnsRes.address) return;
  429. isBanned = await query.host.find({
  430. address: dnsRes.address,
  431. banned: true
  432. });
  433. } catch (error) {
  434. isBanned = null;
  435. }
  436. if (isBanned) {
  437. throw new CustomError("URL is containing malware/scam.", 400);
  438. }
  439. };