ExpressLocals.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import logger from '@overleaf/logger'
  2. import Settings from '@overleaf/settings'
  3. import _ from 'lodash'
  4. import { URL } from 'node:url'
  5. import Path from 'node:path'
  6. import moment from 'moment'
  7. import { fetchJson } from '@overleaf/fetch-utils'
  8. import contentDisposition from 'content-disposition'
  9. import Features from './Features.mjs'
  10. import SessionManager from '../Features/Authentication/SessionManager.mjs'
  11. import PackageVersions from './PackageVersions.js'
  12. import Modules from './Modules.mjs'
  13. import Errors from '../Features/Errors/Errors.js'
  14. import AdminAuthorizationHelper from '../Features/Helpers/AdminAuthorizationHelper.mjs'
  15. import { addOptionalCleanupHandlerAfterDrainingConnections } from './GracefulShutdown.mjs'
  16. import { sanitizeSessionUserForFrontEnd } from './FrontEndUser.mjs'
  17. import { expressify } from '@overleaf/promise-utils'
  18. const {
  19. canRedirectToAdminDomain,
  20. hasAdminAccess,
  21. useAdminCapabilities,
  22. useHasAdminCapability,
  23. useNonAdminDomainCapabilities,
  24. useHasNonAdminDomainCapability,
  25. } = AdminAuthorizationHelper
  26. const IEEE_BRAND_ID = Settings.ieeeBrandId
  27. let webpackManifest
  28. async function loadManifest() {
  29. switch (process.env.NODE_ENV) {
  30. case 'production':
  31. /* eslint-disable import/no-unresolved */
  32. // Only load webpack manifest file in production.
  33. webpackManifest = (
  34. await import('../../../public/manifest.json', {
  35. with: { type: 'json' },
  36. })
  37. ).default
  38. /* eslint-enable import/no-unresolved */
  39. break
  40. case 'development': {
  41. // In dev, fetch the manifest from the webpack container.
  42. loadManifestFromWebpackDevServer()
  43. const intervalHandle = setInterval(
  44. loadManifestFromWebpackDevServer,
  45. 10 * 1000
  46. )
  47. addOptionalCleanupHandlerAfterDrainingConnections(
  48. 'refresh webpack manifest',
  49. () => {
  50. clearInterval(intervalHandle)
  51. }
  52. )
  53. break
  54. }
  55. default:
  56. // In ci, all entries are undefined.
  57. webpackManifest = {}
  58. }
  59. }
  60. function loadManifestFromWebpackDevServer(done = function () {}) {
  61. fetchJson(new URL(`/manifest.json`, Settings.apis.webpack.url), {
  62. headers: {
  63. Host: 'localhost',
  64. },
  65. })
  66. .then(json => {
  67. webpackManifest = json
  68. done()
  69. })
  70. .catch(error => {
  71. logger.err({ error }, 'cannot fetch webpack manifest')
  72. done(error)
  73. })
  74. }
  75. const IN_CI = process.env.NODE_ENV === 'test'
  76. function getWebpackAssets(entrypoint, section) {
  77. if (IN_CI) {
  78. // Emit an empty list of entries in CI.
  79. return []
  80. }
  81. return webpackManifest.entrypoints[entrypoint].assets[section] || []
  82. }
  83. export default async function (webRouter, privateApiRouter, publicApiRouter) {
  84. await loadManifest()
  85. if (process.env.NODE_ENV === 'development') {
  86. // In the dev-env, delay requests until we fetched the manifest once.
  87. webRouter.use(function (req, res, next) {
  88. if (!webpackManifest) {
  89. loadManifestFromWebpackDevServer(next)
  90. } else {
  91. next()
  92. }
  93. })
  94. }
  95. webRouter.use(function (req, res, next) {
  96. res.locals.session = req.session
  97. next()
  98. })
  99. function addSetContentDisposition(req, res, next) {
  100. res.setContentDisposition = function (type, { filename }) {
  101. res.setHeader(
  102. 'Content-Disposition',
  103. contentDisposition(filename, { type })
  104. )
  105. }
  106. next()
  107. }
  108. webRouter.use(addSetContentDisposition)
  109. privateApiRouter.use(addSetContentDisposition)
  110. publicApiRouter.use(addSetContentDisposition)
  111. webRouter.use(function (req, res, next) {
  112. req.externalAuthenticationSystemUsed =
  113. Features.externalAuthenticationSystemUsed
  114. res.locals.externalAuthenticationSystemUsed =
  115. Features.externalAuthenticationSystemUsed
  116. req.hasFeature = res.locals.hasFeature = Features.hasFeature
  117. next()
  118. })
  119. webRouter.use(function (req, res, next) {
  120. let staticFilesBase
  121. const cdnAvailable =
  122. Settings.cdn && Settings.cdn.web && !!Settings.cdn.web.host
  123. const host = req.headers && req.headers.host
  124. const isSmoke = host.slice(0, 5).toLowerCase() === 'smoke'
  125. if (cdnAvailable && !isSmoke) {
  126. staticFilesBase = Settings.cdn.web.host
  127. } else {
  128. staticFilesBase = ''
  129. }
  130. res.locals.buildBaseAssetPath = function () {
  131. // Return the base asset path (including the CDN url) so that webpack can
  132. // use this to dynamically fetch scripts (e.g. PDFjs worker)
  133. return staticFilesBase + '/'
  134. }
  135. res.locals.buildJsPath = function (jsFile) {
  136. return staticFilesBase + webpackManifest[jsFile]
  137. }
  138. res.locals.buildCopiedJsAssetPath = function (jsFile) {
  139. return staticFilesBase + (webpackManifest[jsFile] || '/' + jsFile)
  140. }
  141. let runtimeEmitted = false
  142. const runtimeChunk = webpackManifest['runtime.js']
  143. res.locals.entrypointScripts = function (entrypoint) {
  144. // Each "entrypoint" contains the runtime chunk as imports.
  145. // Loading the entrypoint twice results in broken execution.
  146. let chunks = getWebpackAssets(entrypoint, 'js')
  147. if (runtimeEmitted) {
  148. chunks = chunks.filter(chunk => chunk !== runtimeChunk)
  149. }
  150. runtimeEmitted = true
  151. return chunks.map(chunk => staticFilesBase + chunk)
  152. }
  153. res.locals.entrypointStyles = function (entrypoint) {
  154. const chunks = getWebpackAssets(entrypoint, 'css')
  155. return chunks.map(chunk => staticFilesBase + chunk)
  156. }
  157. res.locals.mathJaxPath = `/js/libs/mathjax-${PackageVersions.version.mathjax}/es5/tex-svg-full.js`
  158. res.locals.dictionariesRoot = `/js/dictionaries/${PackageVersions.version.dictionaries}/`
  159. res.locals.lib = PackageVersions.lib
  160. res.locals.moment = moment
  161. res.locals.buildStylesheetPath = function (cssFileName) {
  162. return staticFilesBase + webpackManifest[cssFileName]
  163. }
  164. res.locals.buildCssPath = function () {
  165. return res.locals.buildStylesheetPath('main-style.css')
  166. }
  167. res.locals.buildImgPath = function (imgFile) {
  168. const path = Path.join('/img/', imgFile)
  169. return staticFilesBase + path
  170. }
  171. next()
  172. })
  173. webRouter.use(function (req, res, next) {
  174. res.locals.translate = req.i18n.translate
  175. const addTranslatedTextDeep = obj => {
  176. if (_.isObject(obj)) {
  177. if (_.has(obj, 'text')) {
  178. obj.translatedText = req.i18n.translate(obj.text)
  179. }
  180. _.forOwn(obj, value => {
  181. addTranslatedTextDeep(value)
  182. })
  183. }
  184. }
  185. // This function is used to add translations from the server for main
  186. // navigation and footer items because it's tricky to get them in the front
  187. // end otherwise.
  188. res.locals.cloneAndTranslateText = obj => {
  189. const clone = _.cloneDeep(obj)
  190. addTranslatedTextDeep(clone)
  191. return clone
  192. }
  193. // Don't include the query string parameters, otherwise Google
  194. try {
  195. const parsedOriginalUrl = new URL(req.originalUrl, Settings.siteUrl)
  196. res.locals.currentUrl = parsedOriginalUrl.pathname
  197. res.locals.currentUrlWithQueryParams =
  198. parsedOriginalUrl.pathname + parsedOriginalUrl.search
  199. } catch (err) {
  200. return next(new Errors.InvalidError())
  201. }
  202. res.locals.capitalize = function (string) {
  203. if (string.length === 0) {
  204. return ''
  205. }
  206. return string.charAt(0).toUpperCase() + string.slice(1)
  207. }
  208. next()
  209. })
  210. webRouter.use(function (req, res, next) {
  211. res.locals.getUserEmail = function () {
  212. const user = SessionManager.getSessionUser(req.session)
  213. const email = (user != null ? user.email : undefined) || ''
  214. return email
  215. }
  216. next()
  217. })
  218. webRouter.use(
  219. expressify(async function (req, res, next) {
  220. res.locals.StringHelper = (
  221. await import('../Features/Helpers/StringHelper.mjs')
  222. ).default
  223. next()
  224. })
  225. )
  226. webRouter.use(function (req, res, next) {
  227. res.locals.csrfToken = req != null ? req.csrfToken() : undefined
  228. next()
  229. })
  230. webRouter.use(function (req, res, next) {
  231. res.locals.getReqQueryParam = field =>
  232. req.query != null ? req.query[field] : undefined
  233. next()
  234. })
  235. webRouter.use(function (req, res, next) {
  236. const currentUser = SessionManager.getSessionUser(req.session)
  237. if (currentUser != null) {
  238. res.locals.user = sanitizeSessionUserForFrontEnd(currentUser)
  239. }
  240. next()
  241. })
  242. webRouter.use(function (req, res, next) {
  243. res.locals.getLoggedInUserId = () =>
  244. SessionManager.getLoggedInUserId(req.session)
  245. res.locals.getSessionUser = () => SessionManager.getSessionUser(req.session)
  246. res.locals.canRedirectToAdminDomain = () =>
  247. canRedirectToAdminDomain(SessionManager.getSessionUser(req.session))
  248. res.locals.hasAdminAccess = () =>
  249. hasAdminAccess(SessionManager.getSessionUser(req.session))
  250. next()
  251. })
  252. webRouter.use(useAdminCapabilities)
  253. webRouter.use(useHasAdminCapability)
  254. webRouter.use(useNonAdminDomainCapabilities)
  255. webRouter.use(useHasNonAdminDomainCapability)
  256. webRouter.use(function (req, res, next) {
  257. // Clone the nav settings so they can be modified for each request
  258. res.locals.nav = {}
  259. for (const key in Settings.nav) {
  260. res.locals.nav[key] = _.clone(Settings.nav[key])
  261. }
  262. res.locals.templates = Settings.templateLinks
  263. next()
  264. })
  265. webRouter.use(function (req, res, next) {
  266. if (Settings.reloadModuleViewsOnEachRequest) {
  267. Modules.loadViewIncludes(req.app)
  268. }
  269. res.locals.moduleIncludes = Modules.moduleIncludes
  270. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  271. next()
  272. })
  273. webRouter.use(function (req, res, next) {
  274. res.locals.overallThemes = [
  275. {
  276. name: 'Dark',
  277. val: '',
  278. },
  279. {
  280. name: 'Light',
  281. val: 'light-',
  282. },
  283. {
  284. name: 'System',
  285. val: 'system',
  286. },
  287. ]
  288. next()
  289. })
  290. webRouter.use(function (req, res, next) {
  291. res.locals.settings = Settings
  292. next()
  293. })
  294. webRouter.use(function (req, res, next) {
  295. res.locals.showThinFooter = !Features.hasFeature('saas')
  296. next()
  297. })
  298. webRouter.use(function (req, res, next) {
  299. res.locals.websiteRedesignOverride = req.query.redesign === 'enabled'
  300. next()
  301. })
  302. webRouter.use(function (req, res, next) {
  303. // Notifications that are no longer used for which we want to remove the dismiss cookies.
  304. // This can be removed after some time
  305. const LEGACY_NOTIFICATIONS = [{ id: 'ciaminfo', paths: ['/login'] }]
  306. const KEY_PREFIX = 'readnotif-'
  307. const dismissedNotifications = []
  308. for (const cookieName in req.cookies) {
  309. if (cookieName.startsWith(KEY_PREFIX)) {
  310. const legacyNotification = LEGACY_NOTIFICATIONS.find(
  311. ({ id }) => cookieName === `${KEY_PREFIX}${id}`
  312. )
  313. if (legacyNotification) {
  314. // Remove the cookie for legacy notifications that we no longer use.
  315. for (const path of legacyNotification.paths) {
  316. res.clearCookie(cookieName, { path, domain: Settings.cookieDomain })
  317. }
  318. } else {
  319. dismissedNotifications.push(cookieName.slice(KEY_PREFIX.length))
  320. }
  321. }
  322. }
  323. res.locals.dismissedNotifications = dismissedNotifications
  324. next()
  325. })
  326. webRouter.use(function (req, res, next) {
  327. res.locals.ExposedSettings = {
  328. isOverleaf: Settings.overleaf != null,
  329. appName: Settings.appName,
  330. adminEmail: Settings.adminEmail,
  331. dropboxAppName:
  332. Settings.apis.thirdPartyDataStore?.dropboxAppName || 'Overleaf',
  333. ieeeBrandId: IEEE_BRAND_ID,
  334. hasSamlBeta: req.session.samlBeta,
  335. hasAffiliationsFeature: Features.hasFeature('affiliations'),
  336. hasSamlFeature: Features.hasFeature('saml'),
  337. samlInitPath: _.get(Settings, ['saml', 'ukamf', 'initPath']),
  338. hasLinkUrlFeature: Features.hasFeature('link-url'),
  339. hasLinkedProjectFileFeature: Features.hasFeature('linked-project-file'),
  340. hasLinkedProjectOutputFileFeature: Features.hasFeature(
  341. 'linked-project-output-file'
  342. ),
  343. siteUrl: Settings.siteUrl,
  344. emailConfirmationDisabled: Settings.emailConfirmationDisabled,
  345. maxEntitiesPerProject: Settings.maxEntitiesPerProject,
  346. maxUploadSize: Settings.maxUploadSize,
  347. projectUploadTimeout: Settings.projectUploadTimeout,
  348. recaptchaSiteKey: Settings.recaptcha?.siteKey,
  349. recaptchaSiteKeyV3: Settings.recaptcha?.siteKeyV3,
  350. recaptchaDisabled: Settings.recaptcha?.disabled,
  351. textExtensions: Settings.textExtensions,
  352. editableFilenames: Settings.editableFilenames,
  353. validRootDocExtensions: Settings.validRootDocExtensions,
  354. fileIgnorePattern: Settings.fileIgnorePattern,
  355. sentryAllowedOriginRegex: Settings.sentry.allowedOriginRegex,
  356. sentryDsn: Settings.sentry.publicDSN,
  357. sentryEnvironment: Settings.sentry.environment,
  358. sentryRelease: Settings.sentry.release,
  359. hotjarId: Settings.hotjar?.id,
  360. hotjarVersion: Settings.hotjar?.version,
  361. enableSubscriptions: Settings.enableSubscriptions,
  362. gaToken:
  363. Settings.analytics &&
  364. Settings.analytics.ga &&
  365. Settings.analytics.ga.token,
  366. gaTokenV4:
  367. Settings.analytics &&
  368. Settings.analytics.ga &&
  369. Settings.analytics.ga.tokenV4,
  370. propensityId: Settings?.analytics?.propensity?.id,
  371. cookieDomain: Settings.cookieDomain,
  372. templateLinks: Settings.templateLinks,
  373. labsEnabled: Settings.labs && Settings.labs.enable,
  374. wikiEnabled: Settings.overleaf != null || Settings.proxyLearn,
  375. templatesEnabled:
  376. Settings.overleaf != null || Settings.templates?.user_id != null,
  377. cioWriteKey: Settings.analytics?.cio?.writeKey,
  378. cioSiteId: Settings.analytics?.cio?.siteId,
  379. linkedInInsightsPartnerId: Settings.analytics?.linkedIn?.partnerId,
  380. enablePandocConversions: Settings.enablePandocConversions,
  381. }
  382. next()
  383. })
  384. }