utils.js 9.3 KB

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