ExpressLocals.mjs 13 KB

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