utils.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. const { differenceInDays, differenceInHours, differenceInMonths, differenceInMilliseconds, addDays, subHours, subDays, subMonths, subYears, format } = require("date-fns");
  2. const nanoid = require("nanoid/generate");
  3. const JWT = require("jsonwebtoken");
  4. const path = require("path");
  5. const hbs = require("hbs");
  6. const ms = require("ms");
  7. const { ROLES } = require("../consts");
  8. const knexUtils = require("./knex");
  9. const knex = require("../knex");
  10. const env = require("../env");
  11. class CustomError extends Error {
  12. constructor(message, statusCode, data) {
  13. super(message);
  14. this.name = this.constructor.name;
  15. this.statusCode = statusCode ?? 500;
  16. this.data = data;
  17. }
  18. }
  19. const urlRegex = /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i;
  20. function isAdmin(user) {
  21. return user.role === ROLES.ADMIN;
  22. }
  23. function signToken(user) {
  24. return JWT.sign(
  25. {
  26. iss: "ApiAuth",
  27. sub: user.email,
  28. domain: user.domain || "",
  29. iat: parseInt((new Date().getTime() / 1000).toFixed(0)),
  30. exp: parseInt((addDays(new Date(), 7).getTime() / 1000).toFixed(0))
  31. },
  32. env.JWT_SECRET
  33. )
  34. }
  35. function setToken(res, token) {
  36. res.cookie("token", token, {
  37. maxAge: 1000 * 60 * 60 * 24 * 7, // expire after seven days
  38. httpOnly: true,
  39. secure: env.isProd
  40. });
  41. }
  42. function deleteCurrentToken(res) {
  43. res.clearCookie("token", { httpOnly: true, secure: env.isProd });
  44. }
  45. async function generateId(query, domain_id) {
  46. const address = nanoid(
  47. "abcdefghkmnpqrstuvwxyzABCDEFGHKLMNPQRSTUVWXYZ23456789",
  48. env.LINK_LENGTH
  49. );
  50. const link = await query.link.find({ address, domain_id });
  51. if (!link) return address;
  52. return generateId(domain_id);
  53. }
  54. function addProtocol(url) {
  55. const hasProtocol = /^(\w+:|\/\/)/.test(url);
  56. return hasProtocol ? url : "http://" + url;
  57. }
  58. function getShortURL(address, domain) {
  59. const protocol = (env.CUSTOM_DOMAIN_USE_HTTPS || !domain) && !env.isDev ? "https://" : "http://";
  60. const link = `${domain || env.DEFAULT_DOMAIN}/${address}`;
  61. const url = `${protocol}${link}`;
  62. return { address, link, url };
  63. }
  64. function statsObjectToArray(obj) {
  65. const objToArr = (key) =>
  66. Array.from(Object.keys(obj[key]))
  67. .map((name) => ({
  68. name,
  69. value: obj[key][name]
  70. }))
  71. .sort((a, b) => b.value - a.value);
  72. return {
  73. browser: objToArr("browser"),
  74. os: objToArr("os"),
  75. country: objToArr("country"),
  76. referrer: objToArr("referrer")
  77. };
  78. }
  79. function getDifferenceFunction(type) {
  80. if (type === "lastDay") return differenceInHours;
  81. if (type === "lastWeek") return differenceInDays;
  82. if (type === "lastMonth") return differenceInDays;
  83. if (type === "lastYear") return differenceInMonths;
  84. throw new Error("Unknown type.");
  85. }
  86. function parseDatetime(date) {
  87. // because postgres and mysql return date, sqlite returns formatted iso 8601 string in utc
  88. return date instanceof Date ? date : new Date(date + "Z");
  89. }
  90. function parseTimestamps(item) {
  91. return {
  92. created_at: parseDatetime(item.created_at),
  93. updated_at: parseDatetime(item.updated_at),
  94. }
  95. }
  96. function dateToUTC(date) {
  97. const dateUTC = date instanceof Date ? date.toISOString() : new Date(date).toISOString();
  98. // format the utc date in 'YYYY-MM-DD hh:mm:ss' for SQLite
  99. if (knex.isSQLite) {
  100. return dateUTC.substring(0, 10) + " " + dateUTC.substring(11, 19);
  101. }
  102. // mysql doesn't save time in utc, so format the date in local timezone instead
  103. if (knex.isMySQL) {
  104. return format(new Date(date), "yyyy-MM-dd HH:mm:ss");
  105. }
  106. // return unformatted utc string for postgres
  107. return dateUTC;
  108. }
  109. function getStatsPeriods(now) {
  110. return [
  111. ["lastDay", subHours(now, 24)],
  112. ["lastWeek", subDays(now, 7)],
  113. ["lastMonth", subDays(now, 30)],
  114. ["lastYear", subMonths(now, 12)],
  115. ]
  116. }
  117. const preservedURLs = [
  118. "login",
  119. "logout",
  120. "404",
  121. "settings",
  122. "stats",
  123. "signup",
  124. "banned",
  125. "report",
  126. "reset-password",
  127. "resetpassword",
  128. "verify-email",
  129. "verifyemail",
  130. "verify",
  131. "terms",
  132. "confirm-link-delete",
  133. "confirm-link-ban",
  134. "add-domain-form",
  135. "confirm-domain-delete",
  136. "get-report-email",
  137. "link",
  138. "url-password",
  139. "url-info",
  140. "api",
  141. "static",
  142. "images",
  143. "privacy",
  144. "protected",
  145. "css",
  146. "fonts",
  147. "libs",
  148. "pricing"
  149. ];
  150. function parseBooleanQuery(query) {
  151. if (query === "true" || query === true) return true;
  152. if (query === "false" || query === false) return false;
  153. return undefined;
  154. }
  155. function getInitStats() {
  156. return Object.create({
  157. browser: {
  158. chrome: 0,
  159. edge: 0,
  160. firefox: 0,
  161. ie: 0,
  162. opera: 0,
  163. other: 0,
  164. safari: 0
  165. },
  166. os: {
  167. android: 0,
  168. ios: 0,
  169. linux: 0,
  170. macos: 0,
  171. other: 0,
  172. windows: 0
  173. },
  174. country: {},
  175. referrer: {}
  176. });
  177. }
  178. // format date to relative date
  179. const MINUTE = 60,
  180. HOUR = MINUTE * 60,
  181. DAY = HOUR * 24,
  182. WEEK = DAY * 7,
  183. MONTH = DAY * 30,
  184. YEAR = DAY * 365;
  185. function getTimeAgo(dateString) {
  186. const date = new Date(dateString);
  187. const secondsAgo = Math.round((Date.now() - Number(date)) / 1000);
  188. if (secondsAgo < MINUTE) {
  189. return `${secondsAgo} second${secondsAgo !== 1 ? "s" : ""} ago`;
  190. }
  191. let divisor;
  192. let unit = "";
  193. if (secondsAgo < HOUR) {
  194. [divisor, unit] = [MINUTE, "minute"];
  195. } else if (secondsAgo < DAY) {
  196. [divisor, unit] = [HOUR, "hour"];
  197. } else if (secondsAgo < WEEK) {
  198. [divisor, unit] = [DAY, "day"];
  199. } else if (secondsAgo < MONTH) {
  200. [divisor, unit] = [WEEK, "week"];
  201. } else if (secondsAgo < YEAR) {
  202. [divisor, unit] = [MONTH, "month"];
  203. } else {
  204. [divisor, unit] = [YEAR, "year"];
  205. }
  206. const count = Math.floor(secondsAgo / divisor);
  207. return `${count} ${unit}${count > 1 ? "s" : ""} ago`;
  208. }
  209. const sanitize = {
  210. domain: domain => ({
  211. ...domain,
  212. ...parseTimestamps(domain),
  213. id: domain.uuid,
  214. uuid: undefined,
  215. user_id: undefined,
  216. banned_by_id: undefined
  217. }),
  218. link: link => {
  219. const timestamps = parseTimestamps(link);
  220. return {
  221. ...link,
  222. ...timestamps,
  223. banned_by_id: undefined,
  224. domain_id: undefined,
  225. user_id: undefined,
  226. uuid: undefined,
  227. id: link.uuid,
  228. relative_created_at: getTimeAgo(timestamps.created_at),
  229. relative_expire_in: link.expire_in && ms(differenceInMilliseconds(parseDatetime(link.expire_in), new Date()), { long: true }),
  230. password: !!link.password,
  231. visit_count: link.visit_count.toLocaleString("en-US"),
  232. link: getShortURL(link.address, link.domain)
  233. }
  234. },
  235. link_admin: link => {
  236. const timestamps = parseTimestamps(link);
  237. return {
  238. ...link,
  239. ...timestamps,
  240. domain: link.domain || env.DEFAULT_DOMAIN,
  241. id: link.uuid,
  242. relative_created_at: getTimeAgo(timestamps.created_at),
  243. relative_expire_in: link.expire_in && ms(differenceInMilliseconds(parseDatetime(link.expire_in), new Date()), { long: true }),
  244. password: !!link.password,
  245. visit_count: link.visit_count.toLocaleString("en-US"),
  246. link: getShortURL(link.address, link.domain)
  247. }
  248. },
  249. user_admin: user => {
  250. const timestamps = parseTimestamps(user);
  251. return {
  252. ...user,
  253. ...timestamps,
  254. links_count: (user.links_count ?? 0).toLocaleString("en-US"),
  255. relative_created_at: getTimeAgo(timestamps.created_at),
  256. relative_updated_at: getTimeAgo(timestamps.updated_at),
  257. }
  258. },
  259. domain_admin: domain => {
  260. const timestamps = parseTimestamps(domain);
  261. return {
  262. ...domain,
  263. ...timestamps,
  264. links_count: (domain.links_count ?? 0).toLocaleString("en-US"),
  265. relative_created_at: getTimeAgo(timestamps.created_at),
  266. relative_updated_at: getTimeAgo(timestamps.updated_at),
  267. }
  268. }
  269. };
  270. function sleep(ms) {
  271. return new Promise(resolve => setTimeout(resolve, ms));
  272. }
  273. function removeWww(host) {
  274. return host.replace("www.", "");
  275. };
  276. function registerHandlebarsHelpers() {
  277. hbs.registerHelper("ifEquals", function(arg1, arg2, options) {
  278. return (arg1 === arg2) ? options.fn(this) : options.inverse(this);
  279. });
  280. hbs.registerHelper("json", function(context) {
  281. return JSON.stringify(context);
  282. });
  283. const blocks = {};
  284. hbs.registerHelper("extend", function(name, context) {
  285. let block = blocks[name];
  286. if (!block) {
  287. block = blocks[name] = [];
  288. }
  289. block.push(context.fn(this));
  290. });
  291. hbs.registerHelper("block", function(name) {
  292. const val = (blocks[name] || []).join('\n');
  293. blocks[name] = [];
  294. return val;
  295. });
  296. hbs.registerPartials(path.join(__dirname, "../views/partials"), function (err) {});
  297. }
  298. module.exports = {
  299. addProtocol,
  300. CustomError,
  301. dateToUTC,
  302. deleteCurrentToken,
  303. generateId,
  304. getDifferenceFunction,
  305. getInitStats,
  306. getShortURL,
  307. getStatsPeriods,
  308. isAdmin,
  309. parseBooleanQuery,
  310. parseDatetime,
  311. parseTimestamps,
  312. preservedURLs,
  313. registerHandlebarsHelpers,
  314. removeWww,
  315. sanitize,
  316. setToken,
  317. signToken,
  318. sleep,
  319. statsObjectToArray,
  320. urlRegex,
  321. ...knexUtils,
  322. }