links.ts 10.0 KB

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