Auth.constants.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Regex from: https://stackoverflow.com/a/68002755/4807782
  2. // modified to accept numbers in the body of domain though
  3. // examples of matches:
  4. // "vercel.com"
  5. // "www.vercel.com"
  6. // "uptime-monitor-fe.vercel.app"
  7. // "https://uptime-monitor-fe.vercel.app/"
  8. // Supports wildcards, port numbers at the end, paths at the end and query params
  9. const baseUrlRegex =
  10. /^((ftp|http|https):\/\/)?(www.)?(?!.*(ftp|http|https|www.))[a-zA-Z0-9_*-]+(\.[a-zA-Z0-9_*-]+)+((\/)[\w#]+)*(\/\w+\?[a-zA-Z0-9_]+=\w+(&[a-zA-Z0-9_]+=\w+)*)+(?:\.[a-z]+)*(?::\d+)?(?![^<]*(?:<\/\w+>|\/?>))(.*)?\/?(.)*?$/gm
  11. // iOS deep linking scheme https://benoitpasquier.com/deep-linking-url-scheme-ios/
  12. const appRegex =
  13. /^[a-z0-9-]+([.][a-z0-9]+)*:\/(\/[-a-z0-9._~!$&'()*+,;=:@%]+)+(?:\.[a-z]+)*(?::\d+)?(?![^<]*(?:<\/\w+>|\/?>))(.*)?\/?(.)*?$/i
  14. // Regex from https://stackoverflow.com/a/18696953/4807782
  15. const localhostRegex = /^(?:^|\s)((https?:\/\/)?(?:localhost|[\w-]+(?:\.[\w-]+)+)(:\d+)?(\/\S*)?)/i
  16. // "chrome-extension://<extension-id>"
  17. const chromeExtensionRegex = /chrome-extension:\/\/([a-zA-Z]*)/gm
  18. // New regex for custom scheme URLs
  19. const customSchemeRegex = /^([a-zA-Z][a-zA-Z0-9+.-]*):(?:\/{1,3})?([a-zA-Z0-9_.-]*)$/
  20. // Exclude simple domain names without protocol
  21. const excludeSimpleDomainRegex = /^[a-zA-Z0-9-]+\.[a-zA-Z]{2,}$/
  22. // combine the above regexes, with optional exclusion of options
  23. // usage: urlRegex() or urlRegex({ excludeSimpleDomains: false })
  24. export function urlRegex(
  25. options: { excludeSimpleDomains?: boolean } = { excludeSimpleDomains: true }
  26. ): RegExp {
  27. const { excludeSimpleDomains } = options
  28. const excludeSimpleDomainPart = excludeSimpleDomains
  29. ? `(?!${excludeSimpleDomainRegex.source})`
  30. : ''
  31. return new RegExp(
  32. `${excludeSimpleDomainPart}((${baseUrlRegex.source})|(${localhostRegex.source})|(${appRegex.source})|(${chromeExtensionRegex.source})|(${customSchemeRegex.source}))`,
  33. 'i'
  34. )
  35. }
  36. // Use a const string to represent no chars option. Represented as empty string on the backend side.
  37. export const NO_REQUIRED_CHARACTERS = 'NO_REQUIRED_CHARS'