links.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. import ua from "universal-analytics";
  2. import { Handler } from "express";
  3. import { promisify } from "util";
  4. import bcrypt from "bcryptjs";
  5. import isbot from "isbot";
  6. import next from "next";
  7. import URL from "url";
  8. import dns from "dns";
  9. import * as validators from "./validators";
  10. import { CreateLinkReq } from "./types";
  11. import { CustomError } from "../utils";
  12. import transporter from "../mail/mail";
  13. import * as utils from "../utils";
  14. import query from "../queries";
  15. import queue from "../queues";
  16. import env from "../env";
  17. const dnsLookup = promisify(dns.lookup);
  18. export const get: Handler = async (req, res) => {
  19. const { limit, skip, search, all } = req.query;
  20. const userId = req.user.id;
  21. const match = {
  22. ...(!all && { user_id: userId })
  23. };
  24. const [links, total] = await Promise.all([
  25. query.link.get(match, { limit, search, skip }),
  26. query.link.total(match, { search })
  27. ]);
  28. const data = links.map(utils.sanitize.link);
  29. return res.send({
  30. total,
  31. limit,
  32. skip,
  33. data
  34. });
  35. };
  36. export const create: Handler = async (req: CreateLinkReq, res) => {
  37. const { reuse, password, customurl, target, domain } = req.body;
  38. const domain_id = domain ? domain.id : null;
  39. const targetDomain = URL.parse(target).hostname;
  40. const queries = await Promise.all([
  41. validators.cooldown(req.user),
  42. validators.malware(req.user, target),
  43. validators.linksCount(req.user),
  44. reuse &&
  45. query.link.find({
  46. target,
  47. user_id: req.user.id,
  48. domain_id
  49. }),
  50. customurl &&
  51. query.link.find({
  52. address: customurl,
  53. user_id: req.user.id,
  54. domain_id
  55. }),
  56. !customurl && utils.generateId(domain_id),
  57. validators.bannedDomain(targetDomain),
  58. validators.bannedHost(targetDomain)
  59. ]);
  60. // if "reuse" is true, try to return
  61. // the existent URL without creating one
  62. if (queries[3]) {
  63. return res.json(utils.sanitize.link(queries[3]));
  64. }
  65. // Check if custom link already exists
  66. if (queries[4]) {
  67. throw new CustomError("Custom URL is already in use.");
  68. }
  69. // Create new link
  70. const address = customurl || queries[5];
  71. const link = await query.link.create({
  72. password,
  73. address,
  74. domain_id,
  75. target,
  76. user_id: req.user && req.user.id
  77. });
  78. if (!req.user && env.NON_USER_COOLDOWN) {
  79. query.ip.add(req.realIP);
  80. }
  81. return res
  82. .status(201)
  83. .send(utils.sanitize.link({ ...link, domain: domain?.address }));
  84. };
  85. export const edit: Handler = async (req, res) => {
  86. const { address, target } = req.body;
  87. if (!address && !target) {
  88. throw new CustomError("Should at least update one field.");
  89. }
  90. const link = await query.link.find({
  91. uuid: req.params.id,
  92. ...(!req.user.admin && { user_id: req.user.id })
  93. });
  94. if (!link) {
  95. throw new CustomError("Link was not found.");
  96. }
  97. const targetDomain = URL.parse(target).hostname;
  98. const domain_id = link.domain_id || null;
  99. const queries = await Promise.all([
  100. validators.cooldown(req.user),
  101. validators.malware(req.user, target),
  102. address !== link.address &&
  103. query.link.find({
  104. address,
  105. user_id: req.user.id,
  106. domain_id
  107. }),
  108. validators.bannedDomain(targetDomain),
  109. validators.bannedHost(targetDomain)
  110. ]);
  111. // Check if custom link already exists
  112. if (queries[2]) {
  113. throw new CustomError("Custom URL is already in use.");
  114. }
  115. // Update link
  116. const [updatedLink] = await query.link.update(
  117. {
  118. id: link.id
  119. },
  120. {
  121. ...(address && { address }),
  122. ...(target && { target })
  123. }
  124. );
  125. return res.status(200).send(utils.sanitize.link({ ...link, ...updatedLink }));
  126. };
  127. export const remove: Handler = async (req, res) => {
  128. const link = await query.link.remove({
  129. uuid: req.params.id,
  130. ...(!req.user.admin && { user_id: req.user.id })
  131. });
  132. if (!link) {
  133. throw new CustomError("Could not delete the link");
  134. }
  135. return res
  136. .status(200)
  137. .send({ message: "Link has been deleted successfully." });
  138. };
  139. export const report: Handler = async (req, res) => {
  140. const { link } = req.body;
  141. const mail = await transporter.sendMail({
  142. from: env.MAIL_FROM || env.MAIL_USER,
  143. to: env.REPORT_EMAIL,
  144. subject: "[REPORT]",
  145. text: link,
  146. html: link
  147. });
  148. if (!mail.accepted.length) {
  149. throw new CustomError("Couldn't submit the report. Try again later.");
  150. }
  151. return res
  152. .status(200)
  153. .send({ message: "Thanks for the report, we'll take actions shortly." });
  154. };
  155. export const ban: Handler = async (req, res) => {
  156. const { id } = req.params;
  157. const update = {
  158. banned_by_id: req.user.id,
  159. banned: true
  160. };
  161. // 1. Check if link exists
  162. const link = await query.link.find({ uuid: id });
  163. if (!link) {
  164. throw new CustomError("No link has been found.", 400);
  165. }
  166. if (link.banned) {
  167. return res.status(200).send({ message: "Link has been banned already." });
  168. }
  169. const tasks = [];
  170. // 2. Ban link
  171. tasks.push(query.link.update({ uuid: id }, update));
  172. const domain = URL.parse(link.target).hostname;
  173. // 3. Ban target's domain
  174. if (req.body.domain) {
  175. tasks.push(query.domain.add({ ...update, address: domain }));
  176. }
  177. // 4. Ban target's host
  178. if (req.body.host) {
  179. const dnsRes = await dnsLookup(domain).catch(() => {
  180. throw new CustomError("Couldn't fetch DNS info.");
  181. });
  182. const host = dnsRes?.address;
  183. tasks.push(query.host.add({ ...update, address: host }));
  184. }
  185. // 5. Ban link owner
  186. if (req.body.user && link.user_id) {
  187. tasks.push(query.user.update({ id: link.user_id }, update));
  188. }
  189. // 6. Ban all of owner's links
  190. if (req.body.userLinks && link.user_id) {
  191. tasks.push(query.link.update({ user_id: link.user_id }, update));
  192. }
  193. // 7. Wait for all tasks to finish
  194. await Promise.all(tasks).catch(() => {
  195. throw new CustomError("Couldn't ban entries.");
  196. });
  197. // 8. Send response
  198. return res.status(200).send({ message: "Banned link successfully." });
  199. };
  200. export const redirect = (app: ReturnType<typeof next>): Handler => async (
  201. req,
  202. res,
  203. next
  204. ) => {
  205. const isBot = isbot(req.headers["user-agent"]);
  206. const isPreservedUrl = validators.preservedUrls.some(
  207. item => item === req.path.replace("/", "")
  208. );
  209. if (isPreservedUrl) return next();
  210. // 1. If custom domain, get domain info
  211. const { host } = req.headers;
  212. const domain =
  213. host !== env.DEFAULT_DOMAIN
  214. ? await query.domain.find({ address: host })
  215. : null;
  216. // 2. Get link
  217. const address = req.params.id.replace("+", "");
  218. const link = await query.link.find({
  219. address,
  220. domain_id: domain ? domain.id : null
  221. });
  222. // 3. When no link, if has domain redirect to domain's homepage
  223. // otherwise rediredt to 404
  224. if (!link) {
  225. return res.redirect(301, domain ? domain.homepage : "/404");
  226. }
  227. // 4. If link is banned, redirect to banned page.
  228. if (link.banned) {
  229. return res.redirect("/banned");
  230. }
  231. // 5. If wants to see link info, then redirect
  232. const doesRequestInfo = /.*\+$/gi.test(req.params.id);
  233. if (doesRequestInfo && !link.password) {
  234. return app.render(req, res, "/url-info", { target: link.target });
  235. }
  236. // 6. If link is protected, redirect to password page
  237. if (link.password) {
  238. return res.redirect(`/protected/${link.uuid}`);
  239. }
  240. // 7. Create link visit
  241. if (link.user_id && !isBot) {
  242. queue.visit.add({
  243. headers: req.headers,
  244. realIP: req.realIP,
  245. referrer: req.get("Referrer"),
  246. link
  247. });
  248. }
  249. // 8. Create Google Analytics visit
  250. if (env.GOOGLE_ANALYTICS_UNIVERSAL && !isBot) {
  251. ua(env.GOOGLE_ANALYTICS_UNIVERSAL)
  252. .pageview({
  253. dp: `/${address}`,
  254. ua: req.headers["user-agent"],
  255. uip: req.realIP,
  256. aip: 1
  257. })
  258. .send();
  259. }
  260. // 10. Redirect to target
  261. return res.redirect(link.target);
  262. };
  263. export const redirectProtected: Handler = async (req, res) => {
  264. // 1. Get link
  265. const uuid = req.params.id;
  266. const link = await query.link.find({ uuid });
  267. // 2. Throw error if no link
  268. if (!link || !link.password) {
  269. throw new CustomError("Couldn't find the link.", 400);
  270. }
  271. // 3. Check if password matches
  272. const matches = await bcrypt.compare(req.body.password, link.password);
  273. if (!matches) {
  274. throw new CustomError("Password is not correct.", 401);
  275. }
  276. // 4. Create visit
  277. if (link.user_id) {
  278. queue.visit.add({
  279. headers: req.headers,
  280. realIP: req.realIP,
  281. referrer: req.get("Referrer"),
  282. link
  283. });
  284. }
  285. // 5. Create Google Analytics visit
  286. if (env.GOOGLE_ANALYTICS_UNIVERSAL) {
  287. ua(env.GOOGLE_ANALYTICS_UNIVERSAL)
  288. .pageview({
  289. dp: `/${link.address}`,
  290. ua: req.headers["user-agent"],
  291. uip: req.realIP,
  292. aip: 1
  293. })
  294. .send();
  295. }
  296. // 6. Send target
  297. return res.status(200).send({ target: link.target });
  298. };
  299. export const redirectCustomDomain: Handler = async (req, res, next) => {
  300. const {
  301. headers: { host },
  302. path
  303. } = req;
  304. if (host === env.DEFAULT_DOMAIN) {
  305. return next();
  306. }
  307. if (
  308. path === "/" ||
  309. validators.preservedUrls
  310. .filter(l => l !== "url-password")
  311. .some(item => item === path.replace("/", ""))
  312. ) {
  313. const domain = await query.domain.find({ address: host });
  314. const redirectURL = domain
  315. ? domain.homepage
  316. : `https://${env.DEFAULT_DOMAIN + path}`;
  317. return res.redirect(301, redirectURL);
  318. }
  319. return next();
  320. };
  321. export const stats: Handler = async (req, res) => {
  322. const { user } = req;
  323. const uuid = req.params.id;
  324. const link = await query.link.find({
  325. ...(!user.admin && { user_id: user.id }),
  326. uuid
  327. });
  328. if (!link) {
  329. throw new CustomError("Link could not be found.");
  330. }
  331. const stats = await query.visit.find({ link_id: link.id }, link.visit_count);
  332. if (!stats) {
  333. throw new CustomError("Could not get the short link stats.");
  334. }
  335. return res.status(200).send({
  336. ...stats,
  337. ...utils.sanitize.link(link)
  338. });
  339. };