links.ts 9.8 KB

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