utils.js 9.1 KB

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