utils.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. "create-admin",
  120. "404",
  121. "settings",
  122. "admin",
  123. "stats",
  124. "signup",
  125. "banned",
  126. "report",
  127. "reset-password",
  128. "resetpassword",
  129. "verify-email",
  130. "verifyemail",
  131. "verify",
  132. "terms",
  133. "confirm-link-delete",
  134. "confirm-link-ban",
  135. "confirm-user-delete",
  136. "confirm-user-ban",
  137. "create-user",
  138. "confirm-domain-delete-admin",
  139. "confirm-domain-ban",
  140. "add-domain-form",
  141. "confirm-domain-delete",
  142. "get-report-email",
  143. "get-support-email",
  144. "link",
  145. "admin",
  146. "url-password",
  147. "url-info",
  148. "api",
  149. "static",
  150. "images",
  151. "privacy",
  152. "protected",
  153. "css",
  154. "fonts",
  155. "libs",
  156. "pricing"
  157. ];
  158. function parseBooleanQuery(query) {
  159. if (query === "true" || query === true) return true;
  160. if (query === "false" || query === false) return false;
  161. return undefined;
  162. }
  163. function getInitStats() {
  164. return Object.create({
  165. browser: {
  166. chrome: 0,
  167. edge: 0,
  168. firefox: 0,
  169. ie: 0,
  170. opera: 0,
  171. other: 0,
  172. safari: 0
  173. },
  174. os: {
  175. android: 0,
  176. ios: 0,
  177. linux: 0,
  178. macos: 0,
  179. other: 0,
  180. windows: 0
  181. },
  182. country: {},
  183. referrer: {}
  184. });
  185. }
  186. // format date to relative date
  187. const MINUTE = 60,
  188. HOUR = MINUTE * 60,
  189. DAY = HOUR * 24,
  190. WEEK = DAY * 7,
  191. MONTH = DAY * 30,
  192. YEAR = DAY * 365;
  193. function getTimeAgo(dateString) {
  194. const date = new Date(dateString);
  195. const secondsAgo = Math.round((Date.now() - Number(date)) / 1000);
  196. if (secondsAgo < MINUTE) {
  197. return `${secondsAgo} second${secondsAgo !== 1 ? "s" : ""} ago`;
  198. }
  199. let divisor;
  200. let unit = "";
  201. if (secondsAgo < HOUR) {
  202. [divisor, unit] = [MINUTE, "minute"];
  203. } else if (secondsAgo < DAY) {
  204. [divisor, unit] = [HOUR, "hour"];
  205. } else if (secondsAgo < WEEK) {
  206. [divisor, unit] = [DAY, "day"];
  207. } else if (secondsAgo < MONTH) {
  208. [divisor, unit] = [WEEK, "week"];
  209. } else if (secondsAgo < YEAR) {
  210. [divisor, unit] = [MONTH, "month"];
  211. } else {
  212. [divisor, unit] = [YEAR, "year"];
  213. }
  214. const count = Math.floor(secondsAgo / divisor);
  215. return `${count} ${unit}${count > 1 ? "s" : ""} ago`;
  216. }
  217. const sanitize = {
  218. domain: domain => ({
  219. ...domain,
  220. ...parseTimestamps(domain),
  221. id: domain.uuid,
  222. uuid: undefined,
  223. user_id: undefined,
  224. banned_by_id: undefined
  225. }),
  226. link: link => {
  227. const timestamps = parseTimestamps(link);
  228. return {
  229. ...link,
  230. ...timestamps,
  231. banned_by_id: undefined,
  232. domain_id: undefined,
  233. user_id: undefined,
  234. uuid: undefined,
  235. id: link.uuid,
  236. relative_created_at: getTimeAgo(timestamps.created_at),
  237. relative_expire_in: link.expire_in && ms(differenceInMilliseconds(parseDatetime(link.expire_in), new Date()), { long: true }),
  238. password: !!link.password,
  239. visit_count: link.visit_count.toLocaleString("en-US"),
  240. link: getShortURL(link.address, link.domain)
  241. }
  242. },
  243. link_admin: link => {
  244. const timestamps = parseTimestamps(link);
  245. return {
  246. ...link,
  247. ...timestamps,
  248. domain: link.domain || env.DEFAULT_DOMAIN,
  249. id: link.uuid,
  250. relative_created_at: getTimeAgo(timestamps.created_at),
  251. relative_expire_in: link.expire_in && ms(differenceInMilliseconds(parseDatetime(link.expire_in), new Date()), { long: true }),
  252. password: !!link.password,
  253. visit_count: link.visit_count.toLocaleString("en-US"),
  254. link: getShortURL(link.address, link.domain)
  255. }
  256. },
  257. user_admin: user => {
  258. const timestamps = parseTimestamps(user);
  259. return {
  260. ...user,
  261. ...timestamps,
  262. links_count: (user.links_count ?? 0).toLocaleString("en-US"),
  263. relative_created_at: getTimeAgo(timestamps.created_at),
  264. relative_updated_at: getTimeAgo(timestamps.updated_at),
  265. }
  266. },
  267. domain_admin: domain => {
  268. const timestamps = parseTimestamps(domain);
  269. return {
  270. ...domain,
  271. ...timestamps,
  272. links_count: (domain.links_count ?? 0).toLocaleString("en-US"),
  273. relative_created_at: getTimeAgo(timestamps.created_at),
  274. relative_updated_at: getTimeAgo(timestamps.updated_at),
  275. }
  276. }
  277. };
  278. function sleep(ms) {
  279. return new Promise(resolve => setTimeout(resolve, ms));
  280. }
  281. function removeWww(host) {
  282. return host.replace("www.", "");
  283. };
  284. function registerHandlebarsHelpers() {
  285. hbs.registerHelper("ifEquals", function(arg1, arg2, options) {
  286. return (arg1 === arg2) ? options.fn(this) : options.inverse(this);
  287. });
  288. hbs.registerHelper("json", function(context) {
  289. return JSON.stringify(context);
  290. });
  291. const blocks = {};
  292. hbs.registerHelper("extend", function(name, context) {
  293. let block = blocks[name];
  294. if (!block) {
  295. block = blocks[name] = [];
  296. }
  297. block.push(context.fn(this));
  298. });
  299. hbs.registerHelper("block", function(name) {
  300. const val = (blocks[name] || []).join('\n');
  301. blocks[name] = [];
  302. return val;
  303. });
  304. hbs.registerPartials(path.join(__dirname, "../views/partials"), function (err) {});
  305. }
  306. module.exports = {
  307. addProtocol,
  308. CustomError,
  309. dateToUTC,
  310. deleteCurrentToken,
  311. generateId,
  312. getDifferenceFunction,
  313. getInitStats,
  314. getShortURL,
  315. getStatsPeriods,
  316. isAdmin,
  317. parseBooleanQuery,
  318. parseDatetime,
  319. parseTimestamps,
  320. preservedURLs,
  321. registerHandlebarsHelpers,
  322. removeWww,
  323. sanitize,
  324. setToken,
  325. signToken,
  326. sleep,
  327. statsObjectToArray,
  328. urlRegex,
  329. ...knexUtils,
  330. }