UrlHelper.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const Settings = require('@overleaf/settings')
  2. const { URL } = require('url')
  3. const PROTO = new URL(Settings.siteUrl).protocol
  4. function getCanonicalURL(req, url) {
  5. const origin = `${PROTO}//${req.headers.host}`
  6. url = new URL(url || req.originalUrl, origin)
  7. if (url.pathname.endsWith('/')) {
  8. url.pathname = url.pathname.replace(/\/+$/, '')
  9. }
  10. url.search = ''
  11. url.hash = ''
  12. return url.href
  13. }
  14. function getSafeRedirectPath(value) {
  15. const baseURL = Settings.siteUrl // base URL is required to construct URL from path
  16. const url = new URL(value, baseURL)
  17. let safePath = `${url.pathname}${url.search}${url.hash}`.replace(/^\/+/, '/')
  18. if (safePath === '/') {
  19. safePath = undefined
  20. }
  21. return safePath
  22. }
  23. function getSafeAdminDomainRedirect(path) {
  24. return Settings.adminUrl + (getSafeRedirectPath(path) || '/')
  25. }
  26. module.exports = {
  27. getCanonicalURL,
  28. getSafeRedirectPath,
  29. getSafeAdminDomainRedirect,
  30. wrapUrlWithProxy(url) {
  31. // TODO: Consider what to do for Community and Enterprise edition?
  32. if (!Settings.apis.linkedUrlProxy.url) {
  33. throw new Error('no linked url proxy configured')
  34. }
  35. return `${Settings.apis.linkedUrlProxy.url}?url=${encodeURIComponent(url)}`
  36. },
  37. prependHttpIfNeeded(url) {
  38. if (!url.match('://')) {
  39. url = `http://${url}`
  40. }
  41. return url
  42. },
  43. }