ExpressLocals.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. const logger = require('@overleaf/logger')
  2. const Settings = require('@overleaf/settings')
  3. const querystring = require('querystring')
  4. const _ = require('lodash')
  5. const { URL } = require('url')
  6. const Path = require('path')
  7. const moment = require('moment')
  8. const pug = require('pug-runtime')
  9. const request = require('request')
  10. const Features = require('./Features')
  11. const SessionManager = require('../Features/Authentication/SessionManager')
  12. const PackageVersions = require('./PackageVersions')
  13. const Modules = require('./Modules')
  14. const SafeHTMLSubstitute = require('../Features/Helpers/SafeHTMLSubstitution')
  15. const {
  16. canRedirectToAdminDomain,
  17. hasAdminAccess,
  18. } = require('../Features/Helpers/AdminAuthorizationHelper')
  19. let webpackManifest
  20. switch (process.env.NODE_ENV) {
  21. case 'production':
  22. // Only load webpack manifest file in production.
  23. webpackManifest = require(`../../../public/manifest.json`)
  24. break
  25. case 'development':
  26. // In dev, fetch the manifest from the webpack container.
  27. loadManifestFromWebpackDevServer()
  28. setInterval(loadManifestFromWebpackDevServer, 10 * 1000)
  29. break
  30. default:
  31. // In ci, all entries are undefined.
  32. webpackManifest = {}
  33. }
  34. function loadManifestFromWebpackDevServer(done = function () {}) {
  35. request(
  36. {
  37. uri: `${Settings.apis.webpack.url}/manifest.json`,
  38. headers: { Host: 'localhost' },
  39. json: true,
  40. },
  41. (err, res, body) => {
  42. if (!err && res.statusCode !== 200) {
  43. err = new Error(`webpack responded with statusCode: ${res.statusCode}`)
  44. }
  45. if (err) {
  46. logger.err({ err }, 'cannot fetch webpack manifest')
  47. return done(err)
  48. }
  49. webpackManifest = body
  50. done()
  51. }
  52. )
  53. }
  54. const IN_CI = process.env.NODE_ENV === 'test'
  55. function getWebpackAssets(entrypoint, section) {
  56. if (IN_CI) {
  57. // Emit an empty list of entries in CI.
  58. return []
  59. }
  60. return webpackManifest.entrypoints[entrypoint].assets[section] || []
  61. }
  62. const I18N_HTML_INJECTIONS = new Set()
  63. module.exports = function (webRouter, privateApiRouter, publicApiRouter) {
  64. if (process.env.NODE_ENV === 'development') {
  65. // In the dev-env, delay requests until we fetched the manifest once.
  66. webRouter.use(function (req, res, next) {
  67. if (!webpackManifest) {
  68. loadManifestFromWebpackDevServer(next)
  69. } else {
  70. next()
  71. }
  72. })
  73. }
  74. webRouter.use(function (req, res, next) {
  75. res.locals.session = req.session
  76. next()
  77. })
  78. function addSetContentDisposition(req, res, next) {
  79. res.setContentDisposition = function (type, opts) {
  80. const directives = _.map(
  81. opts,
  82. (v, k) => `${k}="${encodeURIComponent(v)}"`
  83. )
  84. const contentDispositionValue = `${type}; ${directives.join('; ')}`
  85. res.setHeader('Content-Disposition', contentDispositionValue)
  86. }
  87. next()
  88. }
  89. webRouter.use(addSetContentDisposition)
  90. privateApiRouter.use(addSetContentDisposition)
  91. publicApiRouter.use(addSetContentDisposition)
  92. webRouter.use(function (req, res, next) {
  93. req.externalAuthenticationSystemUsed =
  94. Features.externalAuthenticationSystemUsed
  95. res.locals.externalAuthenticationSystemUsed =
  96. Features.externalAuthenticationSystemUsed
  97. req.hasFeature = res.locals.hasFeature = Features.hasFeature
  98. next()
  99. })
  100. webRouter.use(function (req, res, next) {
  101. let staticFilesBase
  102. const cdnAvailable =
  103. Settings.cdn && Settings.cdn.web && !!Settings.cdn.web.host
  104. const cdnBlocked = req.query.nocdn === 'true' || req.session.cdnBlocked
  105. const userId = SessionManager.getLoggedInUserId(req.session)
  106. if (cdnBlocked && req.session.cdnBlocked == null) {
  107. logger.log(
  108. { user_id: userId, ip: req != null ? req.ip : undefined },
  109. 'cdnBlocked for user, not using it and turning it off for future requets'
  110. )
  111. req.session.cdnBlocked = true
  112. }
  113. const host = req.headers && req.headers.host
  114. const isSmoke = host.slice(0, 5).toLowerCase() === 'smoke'
  115. if (cdnAvailable && !isSmoke && !cdnBlocked) {
  116. staticFilesBase = Settings.cdn.web.host
  117. } else {
  118. staticFilesBase = ''
  119. }
  120. res.locals.buildBaseAssetPath = function () {
  121. // Return the base asset path (including the CDN url) so that webpack can
  122. // use this to dynamically fetch scripts (e.g. PDFjs worker)
  123. return staticFilesBase + '/'
  124. }
  125. res.locals.buildJsPath = function (jsFile) {
  126. return staticFilesBase + webpackManifest[jsFile]
  127. }
  128. res.locals.buildCopiedJsAssetPath = function (jsFile) {
  129. return staticFilesBase + (webpackManifest[jsFile] || '/' + jsFile)
  130. }
  131. res.locals.entrypointScripts = function (entrypoint) {
  132. const chunks = getWebpackAssets(entrypoint, 'js')
  133. return chunks.map(chunk => staticFilesBase + chunk)
  134. }
  135. res.locals.entrypointStyles = function (entrypoint) {
  136. const chunks = getWebpackAssets(entrypoint, 'css')
  137. return chunks.map(chunk => staticFilesBase + chunk)
  138. }
  139. res.locals.mathJaxPath = `/js/libs/mathjax/MathJax.js?${querystring.stringify(
  140. {
  141. config: 'TeX-AMS_HTML,Safe',
  142. v: require('mathjax/package.json').version,
  143. }
  144. )}`
  145. res.locals.lib = PackageVersions.lib
  146. res.locals.moment = moment
  147. const IEEE_BRAND_ID = 15
  148. res.locals.isIEEE = brandVariation =>
  149. (brandVariation != null ? brandVariation.brand_id : undefined) ===
  150. IEEE_BRAND_ID
  151. res.locals.getCssThemeModifier = function (userSettings, brandVariation) {
  152. // Themes only exist in OL v2
  153. if (Settings.overleaf != null) {
  154. // The IEEE theme takes precedence over the user personal setting, i.e. a user with
  155. // a theme setting of "light" will still get the IEE theme in IEEE branded projects.
  156. if (res.locals.isIEEE(brandVariation)) {
  157. return 'ieee-'
  158. } else if (userSettings && userSettings.overallTheme != null) {
  159. return userSettings.overallTheme
  160. }
  161. }
  162. }
  163. res.locals.buildStylesheetPath = function (cssFileName) {
  164. return staticFilesBase + webpackManifest[cssFileName]
  165. }
  166. res.locals.buildCssPath = function (themeModifier = '') {
  167. return res.locals.buildStylesheetPath(`${themeModifier}style.css`)
  168. }
  169. res.locals.buildImgPath = function (imgFile) {
  170. const path = Path.join('/img/', imgFile)
  171. return staticFilesBase + path
  172. }
  173. next()
  174. })
  175. webRouter.use(function (req, res, next) {
  176. res.locals.translate = function (key, vars, components) {
  177. vars = vars || {}
  178. if (Settings.i18n.checkForHTMLInVars) {
  179. Object.entries(vars).forEach(([field, value]) => {
  180. if (pug.escape(value) !== value) {
  181. const violationsKey = key + field
  182. // do not flood the logs, log one sample per pod + key + field
  183. if (!I18N_HTML_INJECTIONS.has(violationsKey)) {
  184. logger.warn(
  185. { key, field, value },
  186. 'html content in translations context vars'
  187. )
  188. I18N_HTML_INJECTIONS.add(violationsKey)
  189. }
  190. }
  191. })
  192. }
  193. vars.appName = Settings.appName
  194. const locale = req.i18n.translate(key, vars)
  195. if (components) {
  196. return SafeHTMLSubstitute.render(locale, components)
  197. } else {
  198. return locale
  199. }
  200. }
  201. // Don't include the query string parameters, otherwise Google
  202. // treats ?nocdn=true as the canonical version
  203. const parsedOriginalUrl = new URL(req.originalUrl, Settings.siteUrl)
  204. res.locals.currentUrl = parsedOriginalUrl.pathname
  205. res.locals.currentUrlWithQueryParams =
  206. parsedOriginalUrl.pathname + parsedOriginalUrl.search
  207. res.locals.capitalize = function (string) {
  208. if (string.length === 0) {
  209. return ''
  210. }
  211. return string.charAt(0).toUpperCase() + string.slice(1)
  212. }
  213. next()
  214. })
  215. webRouter.use(function (req, res, next) {
  216. res.locals.getUserEmail = function () {
  217. const user = SessionManager.getSessionUser(req.session)
  218. const email = (user != null ? user.email : undefined) || ''
  219. return email
  220. }
  221. next()
  222. })
  223. webRouter.use(function (req, res, next) {
  224. res.locals.StringHelper = require('../Features/Helpers/StringHelper')
  225. next()
  226. })
  227. webRouter.use(function (req, res, next) {
  228. res.locals.buildReferalUrl = function (referalMedium) {
  229. let url = Settings.siteUrl
  230. const currentUser = SessionManager.getSessionUser(req.session)
  231. if (
  232. currentUser != null &&
  233. (currentUser != null ? currentUser.referal_id : undefined) != null
  234. ) {
  235. url += `?r=${currentUser.referal_id}&rm=${referalMedium}&rs=b` // Referal source = bonus
  236. }
  237. return url
  238. }
  239. res.locals.getReferalId = function () {
  240. const currentUser = SessionManager.getSessionUser(req.session)
  241. if (
  242. currentUser != null &&
  243. (currentUser != null ? currentUser.referal_id : undefined) != null
  244. ) {
  245. return currentUser.referal_id
  246. }
  247. }
  248. next()
  249. })
  250. webRouter.use(function (req, res, next) {
  251. res.locals.csrfToken = req != null ? req.csrfToken() : undefined
  252. next()
  253. })
  254. webRouter.use(function (req, res, next) {
  255. res.locals.getReqQueryParam = field =>
  256. req.query != null ? req.query[field] : undefined
  257. next()
  258. })
  259. webRouter.use(function (req, res, next) {
  260. const currentUser = SessionManager.getSessionUser(req.session)
  261. if (currentUser != null) {
  262. res.locals.user = {
  263. email: currentUser.email,
  264. first_name: currentUser.first_name,
  265. last_name: currentUser.last_name,
  266. }
  267. }
  268. next()
  269. })
  270. webRouter.use(function (req, res, next) {
  271. res.locals.getLoggedInUserId = () =>
  272. SessionManager.getLoggedInUserId(req.session)
  273. res.locals.getSessionUser = () => SessionManager.getSessionUser(req.session)
  274. res.locals.canRedirectToAdminDomain = () =>
  275. canRedirectToAdminDomain(SessionManager.getSessionUser(req.session))
  276. res.locals.hasAdminAccess = () =>
  277. hasAdminAccess(SessionManager.getSessionUser(req.session))
  278. next()
  279. })
  280. webRouter.use(function (req, res, next) {
  281. // Clone the nav settings so they can be modified for each request
  282. res.locals.nav = {}
  283. for (const key in Settings.nav) {
  284. res.locals.nav[key] = _.clone(Settings.nav[key])
  285. }
  286. res.locals.templates = Settings.templateLinks
  287. next()
  288. })
  289. webRouter.use(function (req, res, next) {
  290. if (Settings.reloadModuleViewsOnEachRequest) {
  291. Modules.loadViewIncludes()
  292. }
  293. res.locals.moduleIncludes = Modules.moduleIncludes
  294. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  295. next()
  296. })
  297. webRouter.use(function (req, res, next) {
  298. // TODO
  299. if (Settings.overleaf != null) {
  300. res.locals.overallThemes = [
  301. {
  302. name: 'Default',
  303. val: '',
  304. path: res.locals.buildCssPath(),
  305. },
  306. {
  307. name: 'Light',
  308. val: 'light-',
  309. path: res.locals.buildCssPath('light-'),
  310. },
  311. ]
  312. }
  313. next()
  314. })
  315. webRouter.use(function (req, res, next) {
  316. res.locals.settings = Settings
  317. next()
  318. })
  319. webRouter.use(function (req, res, next) {
  320. res.locals.showThinFooter = !Features.hasFeature('saas')
  321. next()
  322. })
  323. webRouter.use(function (req, res, next) {
  324. res.locals.ExposedSettings = {
  325. isOverleaf: Settings.overleaf != null,
  326. appName: Settings.appName,
  327. dropboxAppName:
  328. Settings.apis.thirdPartyDataStore?.dropboxAppName || 'Overleaf',
  329. hasSamlBeta: req.session.samlBeta,
  330. hasAffiliationsFeature: Features.hasFeature('affiliations'),
  331. hasSamlFeature: Features.hasFeature('saml'),
  332. samlInitPath: _.get(Settings, ['saml', 'ukamf', 'initPath']),
  333. hasLinkUrlFeature: Features.hasFeature('link-url'),
  334. hasLinkedProjectFileFeature: Features.hasFeature('linked-project-file'),
  335. hasLinkedProjectOutputFileFeature: Features.hasFeature(
  336. 'linked-project-output-file'
  337. ),
  338. siteUrl: Settings.siteUrl,
  339. emailConfirmationDisabled: Settings.emailConfirmationDisabled,
  340. maxEntitiesPerProject: Settings.maxEntitiesPerProject,
  341. maxUploadSize: Settings.maxUploadSize,
  342. recaptchaSiteKeyV3:
  343. Settings.recaptcha != null ? Settings.recaptcha.siteKeyV3 : undefined,
  344. recaptchaDisabled:
  345. Settings.recaptcha != null ? Settings.recaptcha.disabled : undefined,
  346. textExtensions: Settings.textExtensions,
  347. validRootDocExtensions: Settings.validRootDocExtensions,
  348. sentryAllowedOriginRegex: Settings.sentry.allowedOriginRegex,
  349. sentryDsn: Settings.sentry.publicDSN,
  350. sentryEnvironment: Settings.sentry.environment,
  351. sentryRelease: Settings.sentry.release,
  352. enableSubscriptions: Settings.enableSubscriptions,
  353. gaToken:
  354. Settings.analytics &&
  355. Settings.analytics.ga &&
  356. Settings.analytics.ga.token,
  357. gaTokenV4:
  358. Settings.analytics &&
  359. Settings.analytics.ga &&
  360. Settings.analytics.ga.tokenV4,
  361. cookieDomain: Settings.cookieDomain,
  362. }
  363. next()
  364. })
  365. }