utils.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. import { ExecutionContext, HttpException } from '@nestjs/common';
  2. import { Reflector } from '@nestjs/core';
  3. import { GqlExecutionContext } from '@nestjs/graphql';
  4. import { Prisma } from '@prisma/client';
  5. import * as A from 'fp-ts/Array';
  6. import * as E from 'fp-ts/Either';
  7. import { pipe } from 'fp-ts/lib/function';
  8. import * as O from 'fp-ts/Option';
  9. import * as T from 'fp-ts/Task';
  10. import * as TE from 'fp-ts/TaskEither';
  11. import { AuthProvider } from './auth/helper';
  12. import {
  13. ENV_EMPTY_AUTH_PROVIDERS,
  14. ENV_NOT_FOUND_KEY_AUTH_PROVIDERS,
  15. ENV_NOT_FOUND_KEY_DATA_ENCRYPTION_KEY,
  16. ENV_NOT_SUPPORT_AUTH_PROVIDERS,
  17. JSON_INVALID,
  18. } from './errors';
  19. import { TeamMemberRole } from './team/team.model';
  20. import { RESTError } from './types/RESTError';
  21. import * as crypto from 'crypto';
  22. /**
  23. * A workaround to throw an exception in an expression.
  24. * JS throw keyword creates a statement not an expression.
  25. * This function allows throw to be used as an expression
  26. * @param errMessage Message present in the error message
  27. */
  28. export function throwErr(errMessage: string): never {
  29. throw new Error(errMessage);
  30. }
  31. /**
  32. * This function allows throw to be used as an expression
  33. * @param errMessage Message present in the error message
  34. */
  35. export function throwHTTPErr(errorData: RESTError): never {
  36. const { message, statusCode } = errorData;
  37. throw new HttpException(message, statusCode);
  38. }
  39. /**
  40. * Prints the given value to log and returns the same value.
  41. * Used for debugging functional pipelines.
  42. * @param val The value to print
  43. * @returns `val` itself
  44. */
  45. export const trace = <T>(val: T) => {
  46. console.log(val);
  47. return val;
  48. };
  49. /**
  50. * Similar to `trace` but allows for labels and also an
  51. * optional transform function.
  52. * @param name The label to given to the trace log (log outputs like this "<name>: <value>")
  53. * @param transform An optional function to transform the log output value (useful for checking specific aspects or transforms (duh))
  54. * @returns A function which takes a value, and is traced.
  55. */
  56. export const namedTrace =
  57. <T>(name: string, transform?: (val: T) => unknown) =>
  58. (val: T) => {
  59. console.log(`${name}:`, transform ? transform(val) : val);
  60. return val;
  61. };
  62. /**
  63. * Returns the list of required roles annotated on a GQL Operation
  64. * @param reflector NestJS Reflector instance
  65. * @param context NestJS Execution Context
  66. * @returns An Option which contains the defined roles
  67. */
  68. export const getAnnotatedRequiredRoles = (
  69. reflector: Reflector,
  70. context: ExecutionContext,
  71. ) =>
  72. pipe(
  73. reflector.get<TeamMemberRole[]>('requiresTeamRole', context.getHandler()),
  74. O.fromNullable,
  75. );
  76. /**
  77. * Gets the user from the NestJS GQL Execution Context.
  78. * Usually used within guards.
  79. * @param ctx The Execution Context to use to get it
  80. * @returns An Option of the user
  81. */
  82. export const getUserFromGQLContext = (ctx: ExecutionContext) =>
  83. pipe(
  84. ctx,
  85. GqlExecutionContext.create,
  86. (ctx) => ctx.getContext().req,
  87. ({ user }) => user,
  88. O.fromNullable,
  89. );
  90. /**
  91. * Gets a GQL Argument in the defined operation.
  92. * Usually used in guards.
  93. * @param argName The name of the argument to get
  94. * @param ctx The NestJS Execution Context to use to get it.
  95. * @returns The argument value typed as `unknown`
  96. */
  97. export const getGqlArg = <ArgName extends string>(
  98. argName: ArgName,
  99. ctx: ExecutionContext,
  100. ) =>
  101. pipe(
  102. ctx,
  103. GqlExecutionContext.create,
  104. (ctx) => ctx.getArgs<object>(),
  105. // We are not sure if this thing will even exist
  106. // We pass that worry to the caller
  107. (args) => args[argName as any] as unknown,
  108. );
  109. /**
  110. * To the daring adventurer who has stumbled upon this relic of code... welcome.
  111. * Many have gazed upon its depths, yet few have returned with answers.
  112. * I could have deleted it, but that felt... too easy, too final.
  113. *
  114. * If you're still reading, perhaps you're the one destined to unravel its secrets.
  115. * Or, maybe you're like me—content to let it linger, a puzzle for the ages.
  116. * The choice is yours, but beware... once you start, there is no turning back.
  117. *
  118. * PLEASE, NO ONE KNOWS HOW THIS WORKS...
  119. * -- Balu, whispering from the great beyond... probably still trying to understand this damn thing.
  120. *
  121. * Sequences an array of TaskEither values while maintaining an array of all the error values
  122. * @param arr Array of TaskEithers
  123. * @returns A TaskEither saying all the errors possible on the left or all the success values on the right
  124. */
  125. export const taskEitherValidateArraySeq = <A, B>(
  126. arr: TE.TaskEither<A, B>[],
  127. ): TE.TaskEither<A[], B[]> =>
  128. pipe(
  129. arr,
  130. A.map(TE.mapLeft(A.of)),
  131. A.sequence(
  132. TE.getApplicativeTaskValidation(T.ApplicativeSeq, A.getMonoid<A>()),
  133. ),
  134. );
  135. /**
  136. * Checks to see if the email is valid or not
  137. * @param email The email
  138. * @see https://emailregex.com/ for information on email regex
  139. * @returns A Boolean depending on the format of the email
  140. */
  141. export const validateEmail = (email: string) => {
  142. return new RegExp(
  143. /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
  144. ).test(email);
  145. };
  146. // Regular expressions for supported address object formats by nodemailer
  147. // check out for more info https://nodemailer.com/message/addresses
  148. const emailRegex1 = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  149. const emailRegex2 =
  150. /^[\w\s]* <([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})>$/;
  151. const emailRegex3 =
  152. /^"[\w\s]+" <([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})>$/;
  153. /**
  154. * Checks to see if the SMTP email is valid or not
  155. * @param email
  156. * @returns A Boolean depending on the format of the email
  157. */
  158. export const validateSMTPEmail = (email: string) => {
  159. // Check if the input matches any of the formats
  160. return (
  161. emailRegex1.test(email) ||
  162. emailRegex2.test(email) ||
  163. emailRegex3.test(email)
  164. );
  165. };
  166. /**
  167. * Checks to see if the URL is valid or not
  168. * @param url The URL to validate
  169. * @returns boolean
  170. */
  171. export const validateSMTPUrl = (url: string) => {
  172. // Possible valid formats
  173. // smtp(s)://mail.example.com
  174. // smtp(s)://user:pass@mail.example.com
  175. // smtp(s)://mail.example.com:587
  176. // smtp(s)://user:pass@mail.example.com:587
  177. if (!url || url.length === 0) return false;
  178. const regex =
  179. /^(smtp|smtps):\/\/(?:([^:]+):([^@]+)@)?((?!\.)[^:]+)(?::(\d+))?$/;
  180. if (regex.test(url)) return true;
  181. return false;
  182. };
  183. /**
  184. * Checks to see if the URL is valid or not
  185. * @param url The URL to validate
  186. * @returns boolean
  187. */
  188. export const validateUrl = (url: string) => {
  189. const urlRegex = /^(http|https):\/\/[^ "]+$/;
  190. return urlRegex.test(url);
  191. };
  192. /**
  193. * String to JSON parser
  194. * @param {str} str The string to parse
  195. * @returns {E.Right<T> | E.Left<"json_invalid">} An Either of the parsed JSON
  196. */
  197. export function stringToJson<T>(
  198. str: string,
  199. ): E.Right<T | any> | E.Left<string> {
  200. try {
  201. return E.right(JSON.parse(str));
  202. } catch (err) {
  203. return E.left(JSON_INVALID);
  204. }
  205. }
  206. /**
  207. *
  208. * @param title string whose length we need to check
  209. * @param length minimum length the title needs to be
  210. * @returns boolean if title is of valid length or not
  211. */
  212. export function isValidLength(title: string, length: number) {
  213. if (title.length < length) {
  214. return false;
  215. }
  216. return true;
  217. }
  218. /**
  219. * This function is called by bootstrap() in main.ts
  220. * It checks if the "VITE_ALLOWED_AUTH_PROVIDERS" environment variable is properly set or not.
  221. * If not, it throws an error.
  222. */
  223. export function checkEnvironmentAuthProvider(
  224. VITE_ALLOWED_AUTH_PROVIDERS: string,
  225. ) {
  226. if (!VITE_ALLOWED_AUTH_PROVIDERS) {
  227. throw new Error(ENV_NOT_FOUND_KEY_AUTH_PROVIDERS);
  228. }
  229. if (VITE_ALLOWED_AUTH_PROVIDERS === '') {
  230. throw new Error(ENV_EMPTY_AUTH_PROVIDERS);
  231. }
  232. const givenAuthProviders = VITE_ALLOWED_AUTH_PROVIDERS.split(',').map(
  233. (provider) => provider.toLocaleUpperCase(),
  234. );
  235. const supportedAuthProviders = Object.values(AuthProvider).map(
  236. (provider: string) => provider.toLocaleUpperCase(),
  237. );
  238. for (const givenAuthProvider of givenAuthProviders) {
  239. if (!supportedAuthProviders.includes(givenAuthProvider)) {
  240. throw new Error(ENV_NOT_SUPPORT_AUTH_PROVIDERS);
  241. }
  242. }
  243. }
  244. /**
  245. * Adds escape backslashes to the input so that it can be used inside
  246. * SQL LIKE/ILIKE queries. Inspired by PHP's `mysql_real_escape_string`
  247. * function.
  248. *
  249. * Eg. "100%" -> "100\\%"
  250. *
  251. * Source: https://stackoverflow.com/a/32648526
  252. */
  253. export function escapeSqlLikeString(str: string) {
  254. if (typeof str != 'string') return str;
  255. return str.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, function (char) {
  256. switch (char) {
  257. case '\0':
  258. return '\\0';
  259. case '\x08':
  260. return '\\b';
  261. case '\x09':
  262. return '\\t';
  263. case '\x1a':
  264. return '\\z';
  265. case '\n':
  266. return '\\n';
  267. case '\r':
  268. return '\\r';
  269. case '"':
  270. case "'":
  271. case '\\':
  272. case '%':
  273. return '\\' + char; // prepends a backslash to backslash, percent,
  274. // and double/single quotes
  275. }
  276. });
  277. }
  278. /**
  279. * Calculate the expiration date of the token
  280. *
  281. * @param expiresOn Number of days the token is valid for
  282. * @returns Date object of the expiration date
  283. */
  284. export function calculateExpirationDate(expiresOn: null | number) {
  285. if (expiresOn === null) return null;
  286. return new Date(Date.now() + expiresOn * 24 * 60 * 60 * 1000);
  287. }
  288. /*
  289. * Transforms the collection level properties (authorization & headers) under the `data` field.
  290. * Preserves `null` values and prevents duplicate stringification.
  291. *
  292. * @param {Prisma.JsonValue} collectionData - The team collection data to transform.
  293. * @returns {string | null} The transformed team collection data as a string.
  294. */
  295. export function transformCollectionData(
  296. collectionData: Prisma.JsonValue,
  297. ): string | null {
  298. if (!collectionData) {
  299. return null;
  300. }
  301. return typeof collectionData === 'string'
  302. ? collectionData
  303. : JSON.stringify(collectionData);
  304. }
  305. // Encrypt and Decrypt functions. InfraConfig and Account table uses these functions to encrypt and decrypt the data.
  306. const ENCRYPTION_ALGORITHM = 'aes-256-cbc';
  307. /**
  308. * Encrypts a text using a key
  309. * @param text The text to encrypt
  310. * @param key The key to use for encryption
  311. * @returns The encrypted text
  312. */
  313. export function encrypt(text: string, key = process.env.DATA_ENCRYPTION_KEY) {
  314. if (!key) throw new Error(ENV_NOT_FOUND_KEY_DATA_ENCRYPTION_KEY);
  315. if (text === null || text === undefined) return text;
  316. const iv = crypto.randomBytes(16);
  317. const cipher = crypto.createCipheriv(
  318. ENCRYPTION_ALGORITHM,
  319. Buffer.from(key),
  320. iv,
  321. );
  322. let encrypted = cipher.update(text);
  323. encrypted = Buffer.concat([encrypted, cipher.final()]);
  324. return iv.toString('hex') + ':' + encrypted.toString('hex');
  325. }
  326. /**
  327. * Decrypts a text using a key
  328. * @param text The text to decrypt
  329. * @param key The key to use for decryption
  330. * @returns The decrypted text
  331. */
  332. export function decrypt(
  333. encryptedData: string,
  334. key = process.env.DATA_ENCRYPTION_KEY,
  335. ) {
  336. if (!key) throw new Error(ENV_NOT_FOUND_KEY_DATA_ENCRYPTION_KEY);
  337. if (encryptedData === null || encryptedData === undefined) {
  338. return encryptedData;
  339. }
  340. const textParts = encryptedData.split(':');
  341. const iv = Buffer.from(textParts.shift(), 'hex');
  342. const encryptedText = Buffer.from(textParts.join(':'), 'hex');
  343. const decipher = crypto.createDecipheriv(
  344. ENCRYPTION_ALGORITHM,
  345. Buffer.from(key),
  346. iv,
  347. );
  348. let decrypted = decipher.update(encryptedText);
  349. decrypted = Buffer.concat([decrypted, decipher.final()]);
  350. return decrypted.toString();
  351. }