links.ts 9.9 KB

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