ExpressLocals.js 13 KB

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