ExpressLocals.js 14 KB

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