ExpressLocals.js 13 KB

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