Server.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. import express from 'express'
  2. import Settings from '@overleaf/settings'
  3. import logger from '@overleaf/logger'
  4. import metrics from '@overleaf/metrics'
  5. import Validation from './Validation.js'
  6. import csp from './CSP.js'
  7. import Router from '../router.mjs'
  8. import helmet from 'helmet'
  9. import UserSessionsRedis from '../Features/User/UserSessionsRedis.js'
  10. import Csrf from './Csrf.js'
  11. import HttpPermissionsPolicyMiddleware from './HttpPermissionsPolicy.js'
  12. import SessionAutostartMiddleware from './SessionAutostartMiddleware.js'
  13. import AnalyticsManager from '../Features/Analytics/AnalyticsManager.js'
  14. import session from 'express-session'
  15. import CookieMetrics from './CookieMetrics.js'
  16. import CustomSessionStore from './CustomSessionStore.js'
  17. import bodyParser from './BodyParserWrapper.js'
  18. import methodOverride from 'method-override'
  19. import cookieParser from 'cookie-parser'
  20. import bearerTokenMiddleware from 'express-bearer-token'
  21. import passport from 'passport'
  22. import { Strategy as LocalStrategy } from 'passport-local'
  23. import ReferalConnect from '../Features/Referal/ReferalConnect.mjs'
  24. import RedirectManager from './RedirectManager.js'
  25. import translations from './Translations.js'
  26. import Views from './Views.js'
  27. import Features from './Features.js'
  28. import ErrorController from '../Features/Errors/ErrorController.js'
  29. import HttpErrorHandler from '../Features/Errors/HttpErrorHandler.js'
  30. import UserSessionsManager from '../Features/User/UserSessionsManager.js'
  31. import AuthenticationController from '../Features/Authentication/AuthenticationController.js'
  32. import SessionManager from '../Features/Authentication/SessionManager.js'
  33. import { hasAdminAccess } from '../Features/Helpers/AdminAuthorizationHelper.js'
  34. import Modules from './Modules.js'
  35. import expressLocals from './ExpressLocals.js'
  36. import noCache from 'nocache'
  37. import os from 'node:os'
  38. import http from 'node:http'
  39. import { fileURLToPath } from 'node:url'
  40. import serveStaticWrapper from './ServeStaticWrapper.mjs'
  41. const sessionsRedisClient = UserSessionsRedis.client()
  42. const oneDayInMilliseconds = 86400000
  43. const STATIC_CACHE_AGE = Settings.cacheStaticAssets
  44. ? oneDayInMilliseconds * 365
  45. : 0
  46. // Init the session store
  47. const sessionStore = new CustomSessionStore({ client: sessionsRedisClient })
  48. const app = express()
  49. const webRouter = express.Router()
  50. const privateApiRouter = express.Router()
  51. const publicApiRouter = express.Router()
  52. if (Settings.behindProxy) {
  53. app.set('trust proxy', Settings.trustedProxyIps || true)
  54. /**
  55. * Handle the X-Original-Forwarded-For header.
  56. *
  57. * The nginx ingress sends us the contents of X-Forwarded-For it received in
  58. * X-Original-Forwarded-For. Express expects all proxy IPs to be in a comma
  59. * separated list in X-Forwarded-For.
  60. */
  61. app.use((req, res, next) => {
  62. if (
  63. req.headers['x-original-forwarded-for'] &&
  64. req.headers['x-forwarded-for']
  65. ) {
  66. req.headers['x-forwarded-for'] =
  67. req.headers['x-original-forwarded-for'] +
  68. ', ' +
  69. req.headers['x-forwarded-for']
  70. }
  71. next()
  72. })
  73. }
  74. // `req.ip` is a getter on the underlying socket.
  75. // The socket details are freed as the connection is dropped -- aka aborted.
  76. // Hence `req.ip` may read `undefined` upon connection drop.
  77. // A couple of places require a valid IP at all times. Cache it!
  78. const ORIGINAL_REQ_IP = Object.getOwnPropertyDescriptor(
  79. Object.getPrototypeOf(app.request),
  80. 'ip'
  81. ).get
  82. Object.defineProperty(app.request, 'ip', {
  83. configurable: true,
  84. enumerable: true,
  85. get() {
  86. const ip = ORIGINAL_REQ_IP.call(this)
  87. // Shadow the prototype level getter with a property on the instance.
  88. // Any future access on `req.ip` will get served by the instance property.
  89. Object.defineProperty(this, 'ip', { value: ip })
  90. return ip
  91. },
  92. })
  93. app.use((req, res, next) => {
  94. if (req.destroyed) {
  95. // Request has been aborted already.
  96. return
  97. }
  98. // Implicitly cache the ip, see above.
  99. if (!req.ip) {
  100. // Critical connection details are missing.
  101. return
  102. }
  103. next()
  104. })
  105. if (Settings.exposeHostname) {
  106. const HOSTNAME = os.hostname()
  107. app.use((req, res, next) => {
  108. res.setHeader('X-Served-By', HOSTNAME)
  109. next()
  110. })
  111. }
  112. webRouter.use(
  113. serveStaticWrapper(
  114. fileURLToPath(new URL('../../../public', import.meta.url)),
  115. {
  116. maxAge: STATIC_CACHE_AGE,
  117. setHeaders: csp.removeCSPHeaders,
  118. }
  119. )
  120. )
  121. app.set('views', fileURLToPath(new URL('../../views', import.meta.url)))
  122. app.set('view engine', 'pug')
  123. if (Settings.enabledServices.includes('web')) {
  124. if (app.get('env') !== 'development') {
  125. logger.debug('enabling view cache for production or acceptance tests')
  126. app.enable('view cache')
  127. }
  128. if (Settings.precompilePugTemplatesAtBootTime) {
  129. logger.debug('precompiling views for web in production environment')
  130. Views.precompileViews(app)
  131. }
  132. Modules.loadViewIncludes(app)
  133. }
  134. app.use(metrics.http.monitor(logger))
  135. await Modules.applyMiddleware(app, 'appMiddleware')
  136. app.use(bodyParser.urlencoded({ extended: true, limit: '2mb' }))
  137. app.use(bodyParser.json({ limit: Settings.max_json_request_size }))
  138. app.use(methodOverride())
  139. // add explicit name for telemetry
  140. app.use(bearerTokenMiddleware())
  141. if (Settings.blockCrossOriginRequests) {
  142. app.use(Csrf.blockCrossOriginRequests())
  143. }
  144. if (Settings.useHttpPermissionsPolicy) {
  145. const httpPermissionsPolicy = new HttpPermissionsPolicyMiddleware(
  146. Settings.httpPermissions
  147. )
  148. logger.debug('adding permissions policy config', Settings.httpPermissions)
  149. webRouter.use(httpPermissionsPolicy.middleware)
  150. }
  151. RedirectManager.apply(webRouter)
  152. if (!Settings.security.sessionSecret) {
  153. throw new Error('No SESSION_SECRET provided.')
  154. }
  155. const sessionSecrets = [
  156. Settings.security.sessionSecret,
  157. Settings.security.sessionSecretUpcoming,
  158. Settings.security.sessionSecretFallback,
  159. ].filter(Boolean)
  160. webRouter.use(cookieParser(sessionSecrets))
  161. webRouter.use(CookieMetrics.middleware)
  162. SessionAutostartMiddleware.applyInitialMiddleware(webRouter)
  163. await Modules.applyMiddleware(webRouter, 'sessionMiddleware', {
  164. store: sessionStore,
  165. })
  166. webRouter.use(
  167. session({
  168. resave: false,
  169. saveUninitialized: false,
  170. secret: sessionSecrets,
  171. proxy: Settings.behindProxy,
  172. cookie: {
  173. domain: Settings.cookieDomain,
  174. maxAge: Settings.cookieSessionLength, // in milliseconds, see https://github.com/expressjs/session#cookiemaxage
  175. secure: Settings.secureCookie,
  176. sameSite: Settings.sameSiteCookie,
  177. },
  178. store: sessionStore,
  179. key: Settings.cookieName,
  180. rolling: Settings.cookieRollingSession === true,
  181. })
  182. )
  183. if (Features.hasFeature('saas')) {
  184. webRouter.use(AnalyticsManager.analyticsIdMiddleware)
  185. }
  186. // passport
  187. webRouter.use(passport.initialize())
  188. webRouter.use(passport.session())
  189. passport.use(
  190. new LocalStrategy(
  191. {
  192. passReqToCallback: true,
  193. usernameField: 'email',
  194. passwordField: 'password',
  195. },
  196. AuthenticationController.doPassportLogin
  197. )
  198. )
  199. passport.serializeUser(AuthenticationController.serializeUser)
  200. passport.deserializeUser(AuthenticationController.deserializeUser)
  201. Modules.hooks.fire('passportSetup', passport, err => {
  202. if (err != null) {
  203. logger.err({ err }, 'error setting up passport in modules')
  204. }
  205. })
  206. await Modules.applyNonCsrfRouter(webRouter, privateApiRouter, publicApiRouter)
  207. webRouter.csrf = new Csrf()
  208. webRouter.use(webRouter.csrf.middleware)
  209. webRouter.use(translations.i18nMiddleware)
  210. webRouter.use(translations.setLangBasedOnDomainMiddleware)
  211. if (Settings.cookieRollingSession) {
  212. // Measure expiry from last request, not last login
  213. webRouter.use((req, res, next) => {
  214. if (!req.session.noSessionCallback) {
  215. req.session.touch()
  216. if (SessionManager.isUserLoggedIn(req.session)) {
  217. UserSessionsManager.touch(
  218. SessionManager.getSessionUser(req.session),
  219. err => {
  220. if (err) {
  221. logger.err({ err }, 'error extending user session')
  222. }
  223. }
  224. )
  225. }
  226. }
  227. next()
  228. })
  229. }
  230. webRouter.use(ReferalConnect.use)
  231. expressLocals(webRouter, privateApiRouter, publicApiRouter)
  232. webRouter.use(SessionAutostartMiddleware.invokeCallbackMiddleware)
  233. webRouter.use(function checkIfSiteClosed(req, res, next) {
  234. if (Settings.siteIsOpen) {
  235. next()
  236. } else if (hasAdminAccess(SessionManager.getSessionUser(req.session))) {
  237. next()
  238. } else {
  239. HttpErrorHandler.maintenance(req, res)
  240. }
  241. })
  242. webRouter.use(function checkIfEditorClosed(req, res, next) {
  243. if (Settings.editorIsOpen) {
  244. next()
  245. } else if (req.url.indexOf('/admin') === 0) {
  246. next()
  247. } else {
  248. HttpErrorHandler.maintenance(req, res)
  249. }
  250. })
  251. webRouter.use(AuthenticationController.validateAdmin)
  252. // add security headers using Helmet
  253. const noCacheMiddleware = noCache()
  254. webRouter.use((req, res, next) => {
  255. const isProjectPage = /^\/project\/[a-f0-9]{24}$/.test(req.path)
  256. if (isProjectPage) {
  257. // always set no-cache headers on a project page, as it could be an anonymous token viewer
  258. return noCacheMiddleware(req, res, next)
  259. }
  260. const isProjectFile = /^\/project\/[a-f0-9]{24}\/file\/[a-f0-9]{24}$/.test(
  261. req.path
  262. )
  263. if (isProjectFile) {
  264. // don't set no-cache headers on a project file, as it's immutable and can be cached (privately)
  265. return next()
  266. }
  267. const isProjectBlob = /^\/project\/[a-f0-9]{24}\/blob\/[a-f0-9]{40}$/.test(
  268. req.path
  269. )
  270. if (isProjectBlob) {
  271. // don't set no-cache headers on a project blobs, as they are immutable and can be cached (privately)
  272. return next()
  273. }
  274. const isWikiContent = /^\/learn(-scripts)?(\/|$)/i.test(req.path)
  275. if (isWikiContent) {
  276. // don't set no-cache headers on wiki content, as it's immutable and can be cached (publicly)
  277. return next()
  278. }
  279. const isLoggedIn = SessionManager.isUserLoggedIn(req.session)
  280. if (isLoggedIn) {
  281. // always set no-cache headers for authenticated users (apart from project files, above)
  282. return noCacheMiddleware(req, res, next)
  283. }
  284. // allow other responses (anonymous users, except for project pages) to be cached
  285. return next()
  286. })
  287. webRouter.use(
  288. helmet({
  289. // note that more headers are added by default
  290. dnsPrefetchControl: false,
  291. referrerPolicy: { policy: 'origin-when-cross-origin' },
  292. hsts: false,
  293. // Disabled because it's impractical to include every resource via CORS or
  294. // with the magic CORP header
  295. crossOriginEmbedderPolicy: false,
  296. // We need to be able to share the context of some popups. For example,
  297. // when Recurly opens Paypal in a popup.
  298. crossOriginOpenerPolicy: { policy: 'same-origin-allow-popups' },
  299. // Disabled because it's not a security header and has possibly-unwanted
  300. // effects
  301. originAgentCluster: false,
  302. // We have custom handling for CSP below, so Helmet's default is disabled
  303. contentSecurityPolicy: false,
  304. })
  305. )
  306. // add CSP header to HTML-rendering routes, if enabled
  307. if (Settings.csp && Settings.csp.enabled) {
  308. logger.debug('adding CSP header to rendered routes', Settings.csp)
  309. app.use(csp(Settings.csp))
  310. }
  311. logger.debug('creating HTTP server'.yellow)
  312. const server = http.createServer(app)
  313. // provide settings for separate web and api processes
  314. if (Settings.enabledServices.includes('api')) {
  315. logger.debug({}, 'providing api router')
  316. app.use(privateApiRouter)
  317. app.use(Validation.errorMiddleware)
  318. app.use(ErrorController.handleApiError)
  319. }
  320. if (Settings.enabledServices.includes('web')) {
  321. logger.debug({}, 'providing web router')
  322. app.use(publicApiRouter) // public API goes with web router for public access
  323. app.use(Validation.errorMiddleware)
  324. app.use(ErrorController.handleApiError)
  325. app.use(webRouter)
  326. app.use(Validation.errorMiddleware)
  327. app.use(ErrorController.handleError)
  328. }
  329. metrics.injectMetricsRoute(webRouter)
  330. metrics.injectMetricsRoute(privateApiRouter)
  331. await Router.initialize(webRouter, privateApiRouter, publicApiRouter)
  332. export default { app, server }