ExpressLocals.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. getAdminCapabilities,
  18. hasAdminAccess,
  19. } = require('../Features/Helpers/AdminAuthorizationHelper')
  20. const {
  21. addOptionalCleanupHandlerAfterDrainingConnections,
  22. } = require('./GracefulShutdown')
  23. const { sanitizeSessionUserForFrontEnd } = require('./FrontEndUser')
  24. const { expressify } = require('@overleaf/promise-utils')
  25. const IEEE_BRAND_ID = Settings.ieeeBrandId
  26. let webpackManifest
  27. function loadManifest() {
  28. switch (process.env.NODE_ENV) {
  29. case 'production':
  30. // Only load webpack manifest file in production.
  31. webpackManifest = require('../../../public/manifest.json')
  32. break
  33. case 'development': {
  34. // In dev, fetch the manifest from the webpack container.
  35. loadManifestFromWebpackDevServer()
  36. const intervalHandle = setInterval(
  37. loadManifestFromWebpackDevServer,
  38. 10 * 1000
  39. )
  40. addOptionalCleanupHandlerAfterDrainingConnections(
  41. 'refresh webpack manifest',
  42. () => {
  43. clearInterval(intervalHandle)
  44. }
  45. )
  46. break
  47. }
  48. default:
  49. // In ci, all entries are undefined.
  50. webpackManifest = {}
  51. }
  52. }
  53. function loadManifestFromWebpackDevServer(done = function () {}) {
  54. fetchJson(new URL(`/manifest.json`, Settings.apis.webpack.url), {
  55. headers: {
  56. Host: 'localhost',
  57. },
  58. })
  59. .then(json => {
  60. webpackManifest = json
  61. done()
  62. })
  63. .catch(error => {
  64. logger.err({ error }, 'cannot fetch webpack manifest')
  65. done(error)
  66. })
  67. }
  68. const IN_CI = process.env.NODE_ENV === 'test'
  69. function getWebpackAssets(entrypoint, section) {
  70. if (IN_CI) {
  71. // Emit an empty list of entries in CI.
  72. return []
  73. }
  74. return webpackManifest.entrypoints[entrypoint].assets[section] || []
  75. }
  76. module.exports = function (webRouter, privateApiRouter, publicApiRouter) {
  77. loadManifest()
  78. if (process.env.NODE_ENV === 'development') {
  79. // In the dev-env, delay requests until we fetched the manifest once.
  80. webRouter.use(function (req, res, next) {
  81. if (!webpackManifest) {
  82. loadManifestFromWebpackDevServer(next)
  83. } else {
  84. next()
  85. }
  86. })
  87. }
  88. webRouter.use(function (req, res, next) {
  89. res.locals.session = req.session
  90. next()
  91. })
  92. function addSetContentDisposition(req, res, next) {
  93. res.setContentDisposition = function (type, { filename }) {
  94. res.setHeader(
  95. 'Content-Disposition',
  96. contentDisposition(filename, { type })
  97. )
  98. }
  99. next()
  100. }
  101. webRouter.use(addSetContentDisposition)
  102. privateApiRouter.use(addSetContentDisposition)
  103. publicApiRouter.use(addSetContentDisposition)
  104. webRouter.use(function (req, res, next) {
  105. req.externalAuthenticationSystemUsed =
  106. Features.externalAuthenticationSystemUsed
  107. res.locals.externalAuthenticationSystemUsed =
  108. Features.externalAuthenticationSystemUsed
  109. req.hasFeature = res.locals.hasFeature = Features.hasFeature
  110. next()
  111. })
  112. webRouter.use(function (req, res, next) {
  113. let staticFilesBase
  114. const cdnAvailable =
  115. Settings.cdn && Settings.cdn.web && !!Settings.cdn.web.host
  116. const cdnBlocked =
  117. req.query.nocdn === 'true' || req.session.cdnBlocked || false
  118. const userId = SessionManager.getLoggedInUserId(req.session)
  119. if (cdnBlocked && req.session.cdnBlocked == null) {
  120. logger.debug(
  121. { userId, ip: req != null ? req.ip : undefined },
  122. 'cdnBlocked for user, not using it and turning it off for future requets'
  123. )
  124. Metrics.inc('no_cdn', 1, {
  125. path: userId ? 'logged-in' : 'pre-login',
  126. method: 'true',
  127. })
  128. req.session.cdnBlocked = true
  129. }
  130. Metrics.inc('cdn_blocked', 1, {
  131. path: userId ? 'logged-in' : 'pre-login',
  132. method: String(cdnBlocked),
  133. })
  134. const host = req.headers && req.headers.host
  135. const isSmoke = host.slice(0, 5).toLowerCase() === 'smoke'
  136. if (cdnAvailable && !isSmoke && !cdnBlocked) {
  137. staticFilesBase = Settings.cdn.web.host
  138. } else {
  139. staticFilesBase = ''
  140. }
  141. res.locals.buildBaseAssetPath = function () {
  142. // Return the base asset path (including the CDN url) so that webpack can
  143. // use this to dynamically fetch scripts (e.g. PDFjs worker)
  144. return staticFilesBase + '/'
  145. }
  146. res.locals.buildJsPath = function (jsFile) {
  147. return staticFilesBase + webpackManifest[jsFile]
  148. }
  149. res.locals.buildCopiedJsAssetPath = function (jsFile) {
  150. return staticFilesBase + (webpackManifest[jsFile] || '/' + jsFile)
  151. }
  152. let runtimeEmitted = false
  153. const runtimeChunk = webpackManifest['runtime.js']
  154. res.locals.entrypointScripts = function (entrypoint) {
  155. // Each "entrypoint" contains the runtime chunk as imports.
  156. // Loading the entrypoint twice results in broken execution.
  157. let chunks = getWebpackAssets(entrypoint, 'js')
  158. if (runtimeEmitted) {
  159. chunks = chunks.filter(chunk => chunk !== runtimeChunk)
  160. }
  161. runtimeEmitted = true
  162. return chunks.map(chunk => staticFilesBase + chunk)
  163. }
  164. res.locals.entrypointStyles = function (entrypoint) {
  165. const chunks = getWebpackAssets(entrypoint, 'css')
  166. return chunks.map(chunk => staticFilesBase + chunk)
  167. }
  168. res.locals.mathJaxPath = `/js/libs/mathjax-${PackageVersions.version.mathjax}/es5/tex-svg-full.js`
  169. res.locals.dictionariesRoot = `/js/dictionaries/${PackageVersions.version.dictionaries}/`
  170. res.locals.lib = PackageVersions.lib
  171. res.locals.moment = moment
  172. res.locals.isIEEE = brandId => brandId === IEEE_BRAND_ID
  173. res.locals.getCssThemeModifier = function (
  174. userSettings,
  175. brandVariation,
  176. enableIeeeBranding
  177. ) {
  178. // Themes only exist in OL v2
  179. if (Settings.overleaf != null) {
  180. // The IEEE theme is no longer applied in the editor, which sets
  181. // enableIeeeBranding to false, but is used in the IEEE portal. If
  182. // this is an IEEE-branded page and IEEE branding is disabled in this
  183. // page, always use the default theme (i.e. no light theme in the
  184. // IEEE-branded editor)
  185. if (res.locals.isIEEE(brandVariation?.brand_id)) {
  186. return enableIeeeBranding ? 'ieee-' : ''
  187. } else if (userSettings && userSettings.overallTheme != null) {
  188. if (!['', 'light-'].includes(userSettings.overallTheme)) {
  189. return ''
  190. }
  191. return userSettings.overallTheme
  192. }
  193. }
  194. return ''
  195. }
  196. res.locals.buildStylesheetPath = function (cssFileName) {
  197. return staticFilesBase + webpackManifest[cssFileName]
  198. }
  199. res.locals.buildCssPath = function () {
  200. return res.locals.buildStylesheetPath('main-style.css')
  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 and footer items because it's tricky to get them in the front
  222. // end 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 = sanitizeSessionUserForFrontEnd(currentUser)
  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(
  285. expressify(async function (req, res, next) {
  286. const user = SessionManager.getSessionUser(req.session)
  287. try {
  288. const { adminCapabilities, adminCapabilitiesAvailable } =
  289. await getAdminCapabilities(user)
  290. res.locals.hasAdminCapability = capability => {
  291. if (!hasAdminAccess(user)) {
  292. return false
  293. }
  294. if (!adminCapabilitiesAvailable) {
  295. // If admin capabilities are not available, then all admins have all capabilities
  296. return true
  297. }
  298. return adminCapabilities.includes(capability)
  299. }
  300. } catch (error) {
  301. if (user) {
  302. // This is unexpected, it probably means that the session user does not exist.
  303. logger.warn({ error, req, user }, 'Failed to get admin capabilities')
  304. }
  305. // adminCapabilitiesAvailable should be true if we are here so deny to be safe
  306. res.locals.hasAdminCapability = () => false
  307. }
  308. next()
  309. })
  310. )
  311. webRouter.use(function (req, res, next) {
  312. // Clone the nav settings so they can be modified for each request
  313. res.locals.nav = {}
  314. for (const key in Settings.nav) {
  315. res.locals.nav[key] = _.clone(Settings.nav[key])
  316. }
  317. res.locals.templates = Settings.templateLinks
  318. next()
  319. })
  320. webRouter.use(function (req, res, next) {
  321. if (Settings.reloadModuleViewsOnEachRequest) {
  322. Modules.loadViewIncludes(req.app)
  323. }
  324. res.locals.moduleIncludes = Modules.moduleIncludes
  325. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  326. next()
  327. })
  328. webRouter.use(function (req, res, next) {
  329. // TODO
  330. if (Settings.overleaf != null) {
  331. res.locals.overallThemes = [
  332. {
  333. name: 'Dark',
  334. val: '',
  335. },
  336. {
  337. name: 'Light',
  338. val: 'light-',
  339. },
  340. {
  341. name: 'System',
  342. val: 'system',
  343. },
  344. ]
  345. }
  346. next()
  347. })
  348. webRouter.use(function (req, res, next) {
  349. res.locals.settings = Settings
  350. next()
  351. })
  352. webRouter.use(function (req, res, next) {
  353. res.locals.showThinFooter = !Features.hasFeature('saas')
  354. next()
  355. })
  356. webRouter.use(function (req, res, next) {
  357. res.locals.websiteRedesignOverride = req.query.redesign === 'enabled'
  358. next()
  359. })
  360. webRouter.use(function (req, res, next) {
  361. res.locals.ExposedSettings = {
  362. isOverleaf: Settings.overleaf != null,
  363. appName: Settings.appName,
  364. adminEmail: Settings.adminEmail,
  365. dropboxAppName:
  366. Settings.apis.thirdPartyDataStore?.dropboxAppName || 'Overleaf',
  367. ieeeBrandId: IEEE_BRAND_ID,
  368. hasSamlBeta: req.session.samlBeta,
  369. hasAffiliationsFeature: Features.hasFeature('affiliations'),
  370. hasSamlFeature: Features.hasFeature('saml'),
  371. samlInitPath: _.get(Settings, ['saml', 'ukamf', 'initPath']),
  372. hasLinkUrlFeature: Features.hasFeature('link-url'),
  373. hasLinkedProjectFileFeature: Features.hasFeature('linked-project-file'),
  374. hasLinkedProjectOutputFileFeature: Features.hasFeature(
  375. 'linked-project-output-file'
  376. ),
  377. siteUrl: Settings.siteUrl,
  378. emailConfirmationDisabled: Settings.emailConfirmationDisabled,
  379. maxEntitiesPerProject: Settings.maxEntitiesPerProject,
  380. maxUploadSize: Settings.maxUploadSize,
  381. projectUploadTimeout: Settings.projectUploadTimeout,
  382. recaptchaSiteKey: Settings.recaptcha?.siteKey,
  383. recaptchaSiteKeyV3: Settings.recaptcha?.siteKeyV3,
  384. recaptchaDisabled: Settings.recaptcha?.disabled,
  385. textExtensions: Settings.textExtensions,
  386. editableFilenames: Settings.editableFilenames,
  387. validRootDocExtensions: Settings.validRootDocExtensions,
  388. fileIgnorePattern: Settings.fileIgnorePattern,
  389. sentryAllowedOriginRegex: Settings.sentry.allowedOriginRegex,
  390. sentryDsn: Settings.sentry.publicDSN,
  391. sentryEnvironment: Settings.sentry.environment,
  392. sentryRelease: Settings.sentry.release,
  393. hotjarId: Settings.hotjar?.id,
  394. hotjarVersion: Settings.hotjar?.version,
  395. enableSubscriptions: Settings.enableSubscriptions,
  396. gaToken:
  397. Settings.analytics &&
  398. Settings.analytics.ga &&
  399. Settings.analytics.ga.token,
  400. gaTokenV4:
  401. Settings.analytics &&
  402. Settings.analytics.ga &&
  403. Settings.analytics.ga.tokenV4,
  404. propensityId: Settings?.analytics?.propensity?.id,
  405. cookieDomain: Settings.cookieDomain,
  406. templateLinks: Settings.templateLinks,
  407. labsEnabled: Settings.labs && Settings.labs.enable,
  408. wikiEnabled: Settings.overleaf != null || Settings.proxyLearn,
  409. templatesEnabled:
  410. Settings.overleaf != null || Settings.templates?.user_id != null,
  411. cioWriteKey: Settings.analytics?.cio?.writeKey,
  412. cioSiteId: Settings.analytics?.cio?.siteId,
  413. }
  414. next()
  415. })
  416. }