validators.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. import { body, param } from "express-validator";
  2. import { isAfter, subDays, subHours, addMilliseconds } from "date-fns";
  3. import urlRegex from "url-regex";
  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 } 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 => 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 => 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 => URL.parse(value).host !== env.DEFAULT_DOMAIN)
  139. .withMessage(`${env.DEFAULT_DOMAIN} URLs are not allowed.`),
  140. body("address")
  141. .optional({ checkFalsy: true, nullable: true })
  142. .isString()
  143. .trim()
  144. .isLength({ min: 1, max: 64 })
  145. .withMessage("Custom URL length must be between 1 and 64.")
  146. .custom(value => /^[a-zA-Z0-9-_]+$/g.test(value))
  147. .withMessage("Custom URL is not valid")
  148. .custom(value => !preservedUrls.some(url => url.toLowerCase() === value))
  149. .withMessage("You can't use this custom URL."),
  150. body("expire_in")
  151. .optional({ nullable: true, checkFalsy: true })
  152. .isString()
  153. .trim()
  154. .custom(value => {
  155. try {
  156. return !!ms(value);
  157. } catch {
  158. return false;
  159. }
  160. })
  161. .withMessage("Expire format is invalid. Valid examples: 1m, 8h, 42 days.")
  162. .customSanitizer(ms)
  163. .custom(value => value >= ms("1m"))
  164. .withMessage("Minimum expire time should be '1 minute'.")
  165. .customSanitizer(value => addMilliseconds(new Date(), value).toISOString()),
  166. body("description")
  167. .optional({ nullable: true, checkFalsy: true })
  168. .isString()
  169. .trim()
  170. .isLength({ min: 0, max: 2040 })
  171. .withMessage("Description length must be between 0 and 2040."),
  172. param("id", "ID is invalid.")
  173. .exists({ checkFalsy: true, checkNull: true })
  174. .isLength({ min: 36, max: 36 })
  175. ];
  176. export const redirectProtected = [
  177. body("password", "Password is invalid.")
  178. .exists({ checkFalsy: true, checkNull: true })
  179. .isString()
  180. .isLength({ min: 3, max: 64 })
  181. .withMessage("Password length must be between 3 and 64."),
  182. param("id", "ID is invalid.")
  183. .exists({ checkFalsy: true, checkNull: true })
  184. .isLength({ min: 36, max: 36 })
  185. ];
  186. export const addDomain = [
  187. body("address", "Domain is not valid")
  188. .exists({ checkFalsy: true, checkNull: true })
  189. .isLength({ min: 3, max: 64 })
  190. .withMessage("Domain length must be between 3 and 64.")
  191. .trim()
  192. .customSanitizer(value => {
  193. const parsed = URL.parse(value);
  194. return parsed.hostname || parsed.href;
  195. })
  196. .custom(value => urlRegex({ exact: true, strict: false }).test(value))
  197. .custom(value => value !== env.DEFAULT_DOMAIN)
  198. .withMessage("You can't use the default domain.")
  199. .custom(async value => {
  200. const domain = await query.domain.find({ address: value });
  201. if (domain?.user_id || domain?.banned) return Promise.reject();
  202. })
  203. .withMessage("You can't add this domain."),
  204. body("homepage")
  205. .optional({ checkFalsy: true, nullable: true })
  206. .customSanitizer(addProtocol)
  207. .custom(value => urlRegex({ exact: true, strict: false }).test(value))
  208. .withMessage("Homepage is not valid.")
  209. ];
  210. export const removeDomain = [
  211. param("id", "ID is invalid.")
  212. .exists({
  213. checkFalsy: true,
  214. checkNull: true
  215. })
  216. .isLength({ min: 36, max: 36 })
  217. ];
  218. export const deleteLink = [
  219. param("id", "ID is invalid.")
  220. .exists({
  221. checkFalsy: true,
  222. checkNull: true
  223. })
  224. .isLength({ min: 36, max: 36 })
  225. ];
  226. export const reportLink = [
  227. body("link", "No link has been provided.")
  228. .exists({
  229. checkFalsy: true,
  230. checkNull: true
  231. })
  232. .customSanitizer(addProtocol)
  233. .custom(value => URL.parse(value).hostname === env.DEFAULT_DOMAIN)
  234. .withMessage(`You can only report a ${env.DEFAULT_DOMAIN} link.`)
  235. ];
  236. export const banLink = [
  237. param("id", "ID is invalid.")
  238. .exists({
  239. checkFalsy: true,
  240. checkNull: true
  241. })
  242. .isLength({ min: 36, max: 36 }),
  243. body("host", '"host" should be a boolean.')
  244. .optional({
  245. nullable: true
  246. })
  247. .isBoolean(),
  248. body("user", '"user" should be a boolean.')
  249. .optional({
  250. nullable: true
  251. })
  252. .isBoolean(),
  253. body("userlinks", '"userlinks" should be a boolean.')
  254. .optional({
  255. nullable: true
  256. })
  257. .isBoolean(),
  258. body("domain", '"domain" should be a boolean.')
  259. .optional({
  260. nullable: true
  261. })
  262. .isBoolean()
  263. ];
  264. export const getStats = [
  265. param("id", "ID is invalid.")
  266. .exists({
  267. checkFalsy: true,
  268. checkNull: true
  269. })
  270. .isLength({ min: 36, max: 36 })
  271. ];
  272. export const signup = [
  273. body("password", "Password is not valid.")
  274. .exists({ checkFalsy: true, checkNull: true })
  275. .isLength({ min: 8, max: 64 })
  276. .withMessage("Password length must be between 8 and 64."),
  277. body("email", "Email is not valid.")
  278. .exists({ checkFalsy: true, checkNull: true })
  279. .trim()
  280. .isEmail()
  281. .isLength({ min: 0, max: 255 })
  282. .withMessage("Email length must be max 255.")
  283. .custom(async (value, { req }) => {
  284. const user = await query.user.find({ email: value });
  285. if (user) {
  286. req.user = user;
  287. }
  288. if (user?.verified) return Promise.reject();
  289. })
  290. .withMessage("You can't use this email address.")
  291. ];
  292. export const login = [
  293. body("password", "Password is not valid.")
  294. .exists({ checkFalsy: true, checkNull: true })
  295. .isLength({ min: 8, max: 64 })
  296. .withMessage("Password length must be between 8 and 64."),
  297. body("email", "Email is not valid.")
  298. .exists({ checkFalsy: true, checkNull: true })
  299. .trim()
  300. .isEmail()
  301. .isLength({ min: 0, max: 255 })
  302. .withMessage("Email length must be max 255.")
  303. ];
  304. export const changePassword = [
  305. body("password", "Password is not valid.")
  306. .exists({ checkFalsy: true, checkNull: true })
  307. .isLength({ min: 8, max: 64 })
  308. .withMessage("Password length must be between 8 and 64.")
  309. ];
  310. export const resetPasswordRequest = [
  311. body("email", "Email is not valid.")
  312. .exists({ checkFalsy: true, checkNull: true })
  313. .trim()
  314. .isEmail()
  315. .isLength({ min: 0, max: 255 })
  316. .withMessage("Email length must be max 255.")
  317. ];
  318. export const deleteUser = [
  319. body("password", "Password is not valid.")
  320. .exists({ checkFalsy: true, checkNull: true })
  321. .isLength({ min: 8, max: 64 })
  322. .custom(async (password, { req }) => {
  323. const isMatch = await bcrypt.compare(password, req.user.password);
  324. if (!isMatch) return Promise.reject();
  325. })
  326. ];
  327. export const cooldown = (user: User) => {
  328. if (!env.GOOGLE_SAFE_BROWSING_KEY || !user || !user.cooldowns) return;
  329. // If has active cooldown then throw error
  330. const hasCooldownNow = user.cooldowns.some(cooldown =>
  331. isAfter(subHours(new Date(), 12), new Date(cooldown))
  332. );
  333. if (hasCooldownNow) {
  334. throw new CustomError("Cooldown because of a malware URL. Wait 12h");
  335. }
  336. };
  337. export const malware = async (user: User, target: string) => {
  338. if (!env.GOOGLE_SAFE_BROWSING_KEY) return;
  339. const isMalware = await axios.post(
  340. `https://safebrowsing.googleapis.com/v4/threatMatches:find?key=${env.GOOGLE_SAFE_BROWSING_KEY}`,
  341. {
  342. client: {
  343. clientId: env.DEFAULT_DOMAIN.toLowerCase().replace(".", ""),
  344. clientVersion: "1.0.0"
  345. },
  346. threatInfo: {
  347. threatTypes: [
  348. "THREAT_TYPE_UNSPECIFIED",
  349. "MALWARE",
  350. "SOCIAL_ENGINEERING",
  351. "UNWANTED_SOFTWARE",
  352. "POTENTIALLY_HARMFUL_APPLICATION"
  353. ],
  354. platformTypes: ["ANY_PLATFORM", "PLATFORM_TYPE_UNSPECIFIED"],
  355. threatEntryTypes: [
  356. "EXECUTABLE",
  357. "URL",
  358. "THREAT_ENTRY_TYPE_UNSPECIFIED"
  359. ],
  360. threatEntries: [{ url: target }]
  361. }
  362. }
  363. );
  364. if (!isMalware.data || !isMalware.data.matches) return;
  365. if (user) {
  366. const [updatedUser] = await query.user.update(
  367. { id: user.id },
  368. {
  369. cooldowns: knex.raw("array_append(cooldowns, ?)", [
  370. new Date().toISOString()
  371. ]) as any
  372. }
  373. );
  374. // Ban if too many cooldowns
  375. if (updatedUser.cooldowns.length > 2) {
  376. await query.user.update({ id: user.id }, { banned: true });
  377. throw new CustomError("Too much malware requests. You are now banned.");
  378. }
  379. }
  380. throw new CustomError(
  381. user ? "Malware detected! Cooldown for 12h." : "Malware detected!"
  382. );
  383. };
  384. export const linksCount = async (user?: User) => {
  385. if (!user) return;
  386. const count = await query.link.total({
  387. user_id: user.id,
  388. created_at: [">", subDays(new Date(), 1).toISOString()]
  389. });
  390. if (count > env.USER_LIMIT_PER_DAY) {
  391. throw new CustomError(
  392. `You have reached your daily limit (${env.USER_LIMIT_PER_DAY}). Please wait 24h.`
  393. );
  394. }
  395. };
  396. export const bannedDomain = async (domain: string) => {
  397. const isBanned = await query.domain.find({
  398. address: domain,
  399. banned: true
  400. });
  401. if (isBanned) {
  402. throw new CustomError("URL is containing malware/scam.", 400);
  403. }
  404. };
  405. export const bannedHost = async (domain: string) => {
  406. let isBanned;
  407. try {
  408. const dnsRes = await dnsLookup(domain);
  409. if (!dnsRes || !dnsRes.address) return;
  410. isBanned = await query.host.find({
  411. address: dnsRes.address,
  412. banned: true
  413. });
  414. } catch (error) {
  415. isBanned = null;
  416. }
  417. if (isBanned) {
  418. throw new CustomError("URL is containing malware/scam.", 400);
  419. }
  420. };