ExpressLocals.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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 = brandVariation =>
  170. brandVariation?.brand_id === IEEE_BRAND_ID
  171. res.locals.getCssThemeModifier = function (
  172. userSettings,
  173. brandVariation,
  174. ieeeStylesheetEnabled
  175. ) {
  176. // Themes only exist in OL v2
  177. if (Settings.overleaf != null) {
  178. // The IEEE theme takes precedence over the user personal setting, i.e. a user with
  179. // a theme setting of "light" will still get the IEE theme in IEEE branded projects.
  180. if (ieeeStylesheetEnabled && res.locals.isIEEE(brandVariation)) {
  181. return 'ieee-'
  182. } else if (userSettings && userSettings.overallTheme != null) {
  183. return userSettings.overallTheme
  184. }
  185. }
  186. return ''
  187. }
  188. res.locals.buildStylesheetPath = function (cssFileName) {
  189. return staticFilesBase + webpackManifest[cssFileName]
  190. }
  191. res.locals.buildCssPath = function (
  192. themeModifier = '',
  193. bootstrapVersion = 3
  194. ) {
  195. // Pick which main stylesheet to use based on Bootstrap version
  196. const bootstrap5Modifier = bootstrapVersion === 5 ? '-bootstrap-5' : ''
  197. const computedThemeModifier = bootstrapVersion === 5 ? '' : themeModifier
  198. return res.locals.buildStylesheetPath(
  199. `main-${computedThemeModifier}style${bootstrap5Modifier}.css`
  200. )
  201. }
  202. res.locals.buildImgPath = function (imgFile) {
  203. const path = Path.join('/img/', imgFile)
  204. return staticFilesBase + path
  205. }
  206. next()
  207. })
  208. webRouter.use(function (req, res, next) {
  209. res.locals.translate = req.i18n.translate
  210. const addTranslatedTextDeep = obj => {
  211. if (_.isObject(obj)) {
  212. if (_.has(obj, 'text')) {
  213. obj.translatedText = req.i18n.translate(obj.text)
  214. }
  215. _.forOwn(obj, value => {
  216. addTranslatedTextDeep(value)
  217. })
  218. }
  219. }
  220. // This function is used to add translations from the server for main
  221. // navigation items because it's tricky to get them in the front end
  222. // otherwise.
  223. res.locals.cloneAndTranslateText = obj => {
  224. const clone = _.cloneDeep(obj)
  225. addTranslatedTextDeep(clone)
  226. return clone
  227. }
  228. // Don't include the query string parameters, otherwise Google
  229. // treats ?nocdn=true as the canonical version
  230. try {
  231. const parsedOriginalUrl = new URL(req.originalUrl, Settings.siteUrl)
  232. res.locals.currentUrl = parsedOriginalUrl.pathname
  233. res.locals.currentUrlWithQueryParams =
  234. parsedOriginalUrl.pathname + parsedOriginalUrl.search
  235. } catch (err) {
  236. return next(new Errors.InvalidError())
  237. }
  238. res.locals.capitalize = function (string) {
  239. if (string.length === 0) {
  240. return ''
  241. }
  242. return string.charAt(0).toUpperCase() + string.slice(1)
  243. }
  244. next()
  245. })
  246. webRouter.use(function (req, res, next) {
  247. res.locals.getUserEmail = function () {
  248. const user = SessionManager.getSessionUser(req.session)
  249. const email = (user != null ? user.email : undefined) || ''
  250. return email
  251. }
  252. next()
  253. })
  254. webRouter.use(function (req, res, next) {
  255. res.locals.StringHelper = require('../Features/Helpers/StringHelper')
  256. next()
  257. })
  258. webRouter.use(function (req, res, next) {
  259. res.locals.csrfToken = req != null ? req.csrfToken() : undefined
  260. next()
  261. })
  262. webRouter.use(function (req, res, next) {
  263. res.locals.getReqQueryParam = field =>
  264. req.query != null ? req.query[field] : undefined
  265. next()
  266. })
  267. webRouter.use(function (req, res, next) {
  268. const currentUser = SessionManager.getSessionUser(req.session)
  269. if (currentUser != null) {
  270. res.locals.user = {
  271. email: currentUser.email,
  272. first_name: currentUser.first_name,
  273. last_name: currentUser.last_name,
  274. }
  275. }
  276. next()
  277. })
  278. webRouter.use(function (req, res, next) {
  279. res.locals.getLoggedInUserId = () =>
  280. SessionManager.getLoggedInUserId(req.session)
  281. res.locals.getSessionUser = () => SessionManager.getSessionUser(req.session)
  282. res.locals.canRedirectToAdminDomain = () =>
  283. canRedirectToAdminDomain(SessionManager.getSessionUser(req.session))
  284. res.locals.hasAdminAccess = () =>
  285. hasAdminAccess(SessionManager.getSessionUser(req.session))
  286. next()
  287. })
  288. webRouter.use(function (req, res, next) {
  289. // Clone the nav settings so they can be modified for each request
  290. res.locals.nav = {}
  291. for (const key in Settings.nav) {
  292. res.locals.nav[key] = _.clone(Settings.nav[key])
  293. }
  294. res.locals.templates = Settings.templateLinks
  295. next()
  296. })
  297. webRouter.use(function (req, res, next) {
  298. if (Settings.reloadModuleViewsOnEachRequest) {
  299. Modules.loadViewIncludes(req.app)
  300. }
  301. res.locals.moduleIncludes = Modules.moduleIncludes
  302. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  303. next()
  304. })
  305. webRouter.use(function (req, res, next) {
  306. // TODO
  307. if (Settings.overleaf != null) {
  308. res.locals.overallThemes = [
  309. {
  310. name: 'Default',
  311. val: '',
  312. path: res.locals.buildCssPath(),
  313. },
  314. {
  315. name: 'Light',
  316. val: 'light-',
  317. path: res.locals.buildCssPath('light-'),
  318. },
  319. ]
  320. }
  321. next()
  322. })
  323. webRouter.use(function (req, res, next) {
  324. res.locals.settings = Settings
  325. next()
  326. })
  327. webRouter.use(function (req, res, next) {
  328. res.locals.showThinFooter = !Features.hasFeature('saas')
  329. next()
  330. })
  331. webRouter.use(function (req, res, next) {
  332. res.locals.bootstrap5Override =
  333. req.query['bootstrap-5-override'] === 'enabled'
  334. next()
  335. })
  336. webRouter.use(function (req, res, next) {
  337. res.locals.ExposedSettings = {
  338. isOverleaf: Settings.overleaf != null,
  339. appName: Settings.appName,
  340. adminEmail: Settings.adminEmail,
  341. dropboxAppName:
  342. Settings.apis.thirdPartyDataStore?.dropboxAppName || 'Overleaf',
  343. ieeeBrandId: IEEE_BRAND_ID,
  344. hasSamlBeta: req.session.samlBeta,
  345. hasAffiliationsFeature: Features.hasFeature('affiliations'),
  346. hasSamlFeature: Features.hasFeature('saml'),
  347. samlInitPath: _.get(Settings, ['saml', 'ukamf', 'initPath']),
  348. hasLinkUrlFeature: Features.hasFeature('link-url'),
  349. hasLinkedProjectFileFeature: Features.hasFeature('linked-project-file'),
  350. hasLinkedProjectOutputFileFeature: Features.hasFeature(
  351. 'linked-project-output-file'
  352. ),
  353. siteUrl: Settings.siteUrl,
  354. emailConfirmationDisabled: Settings.emailConfirmationDisabled,
  355. maxEntitiesPerProject: Settings.maxEntitiesPerProject,
  356. maxUploadSize: Settings.maxUploadSize,
  357. projectUploadTimeout: Settings.projectUploadTimeout,
  358. recaptchaSiteKey: Settings.recaptcha?.siteKey,
  359. recaptchaSiteKeyV3: Settings.recaptcha?.siteKeyV3,
  360. recaptchaDisabled: Settings.recaptcha?.disabled,
  361. textExtensions: Settings.textExtensions,
  362. editableFilenames: Settings.editableFilenames,
  363. validRootDocExtensions: Settings.validRootDocExtensions,
  364. fileIgnorePattern: Settings.fileIgnorePattern,
  365. sentryAllowedOriginRegex: Settings.sentry.allowedOriginRegex,
  366. sentryDsn: Settings.sentry.publicDSN,
  367. sentryEnvironment: Settings.sentry.environment,
  368. sentryRelease: Settings.sentry.release,
  369. enableSubscriptions: Settings.enableSubscriptions,
  370. gaToken:
  371. Settings.analytics &&
  372. Settings.analytics.ga &&
  373. Settings.analytics.ga.token,
  374. gaTokenV4:
  375. Settings.analytics &&
  376. Settings.analytics.ga &&
  377. Settings.analytics.ga.tokenV4,
  378. cookieDomain: Settings.cookieDomain,
  379. templateLinks: Settings.templateLinks,
  380. labsEnabled: Settings.labs && Settings.labs.enable,
  381. groupSSOEnabled: Settings.groupSSO?.enabled,
  382. wikiEnabled: Settings.overleaf != null || Settings.proxyLearn,
  383. templatesEnabled:
  384. Settings.overleaf != null || Settings.templates?.user_id != null,
  385. }
  386. next()
  387. })
  388. }