Add files via upload

This commit is contained in:
David Rotermund 2024-10-02 18:15:15 +02:00 committed by GitHub
parent 729ba76524
commit 6264c82052
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
26 changed files with 9888 additions and 0 deletions

View file

@ -0,0 +1,204 @@
const Path = require('path')
const { promisify } = require('util')
const Settings = require('@overleaf/settings')
const logger = require('@overleaf/logger')
const CommandRunner = require('./CommandRunner')
const fs = require('fs')
const ProcessTable = {} // table of currently running jobs (pids or docker container names)
const TIME_V_METRICS = Object.entries({
'cpu-percent': /Percent of CPU this job got: (\d+)/m,
'cpu-time': /User time.*: (\d+.\d+)/m,
'sys-time': /System time.*: (\d+.\d+)/m,
})
const COMPILER_FLAGS = {
latex: '-pdfdvi',
lualatex: '-lualatex',
pdflatex: '-pdf',
xelatex: '-xelatex',
}
function runLatex(projectId, options, callback) {
const {
directory,
mainFile,
image,
environment,
flags,
compileGroup,
stopOnFirstError,
stats,
timings,
} = options
const compiler = options.compiler || 'pdflatex'
const timeout = options.timeout || 60000 // milliseconds
logger.debug(
{
directory,
compiler,
timeout,
mainFile,
environment,
flags,
compileGroup,
stopOnFirstError,
},
'starting compile'
)
let command
try {
command = _buildLatexCommand(mainFile, {
compiler,
stopOnFirstError,
flags,
})
} catch (err) {
return callback(err)
}
const id = `${projectId}` // record running project under this id
ProcessTable[id] = CommandRunner.run(
projectId,
command,
directory,
image,
timeout,
environment,
compileGroup,
function (error, output) {
delete ProcessTable[id]
if (error) {
return callback(error)
}
const runs =
output?.stderr?.match(/^Run number \d+ of .*latex/gm)?.length || 0
const failed = output?.stdout?.match(/^Latexmk: Errors/m) != null ? 1 : 0
// counters from latexmk output
stats['latexmk-errors'] = failed
stats['latex-runs'] = runs
stats['latex-runs-with-errors'] = failed ? runs : 0
stats[`latex-runs-${runs}`] = 1
stats[`latex-runs-with-errors-${runs}`] = failed ? 1 : 0
// timing information from /usr/bin/time
const stderr = (output && output.stderr) || ''
if (stderr.includes('Command being timed:')) {
// Add metrics for runs with `$ time -v ...`
for (const [timing, matcher] of TIME_V_METRICS) {
const match = stderr.match(matcher)
if (match) {
timings[timing] = parseFloat(match[1])
}
}
}
// record output files
_writeLogOutput(projectId, directory, output, () => {
callback(error, output)
})
}
)
}
function _writeLogOutput(projectId, directory, output, callback) {
if (!output) {
return callback()
}
// internal method for writing non-empty log files
function _writeFile(file, content, cb) {
if (content && content.length > 0) {
fs.unlink(file, () => {
fs.writeFile(file, content, { flag: 'wx' }, err => {
if (err) {
// don't fail on error
logger.error({ err, projectId, file }, 'error writing log file')
}
cb()
})
})
} else {
cb()
}
}
// write stdout and stderr, ignoring errors
_writeFile(Path.join(directory, 'output.stdout'), output.stdout, () => {
_writeFile(Path.join(directory, 'output.stderr'), output.stderr, () => {
callback()
})
})
}
function killLatex(projectId, callback) {
const id = `${projectId}`
logger.debug({ id }, 'killing running compile')
if (ProcessTable[id] == null) {
logger.warn({ id }, 'no such project to kill')
callback(null)
} else {
CommandRunner.kill(ProcessTable[id], callback)
}
}
function _buildLatexCommand(mainFile, opts = {}) {
const command = []
if (Settings.clsi?.strace) {
command.push('strace', '-o', 'strace', '-ff')
}
if (Settings.clsi?.latexmkCommandPrefix) {
command.push(...Settings.clsi.latexmkCommandPrefix)
}
// Basic command and flags
command.push(
'latexmk',
'-cd',
'-jobname=output',
'-auxdir=$COMPILE_DIR',
'-outdir=$COMPILE_DIR',
'-synctex=1',
'-shell-escape',
'-interaction=batchmode'
)
// Stop on first error option
if (opts.stopOnFirstError) {
command.push('-halt-on-error')
} else {
// Run all passes despite errors
command.push('-f')
}
// Extra flags
if (opts.flags) {
command.push(...opts.flags)
}
// TeX Engine selection
const compilerFlag = COMPILER_FLAGS[opts.compiler]
if (compilerFlag) {
command.push(compilerFlag)
} else {
throw new Error(`unknown compiler: ${opts.compiler}`)
}
// We want to run latexmk on the tex file which we will automatically
// generate from the Rtex/Rmd/md file.
mainFile = mainFile.replace(/\.(Rtex|md|Rmd|Rnw)$/, '.tex')
command.push(Path.join('$COMPILE_DIR', mainFile))
return command
}
module.exports = {
runLatex,
killLatex,
promises: {
runLatex: promisify(runLatex),
killLatex: promisify(killLatex),
},
}

View file

@ -0,0 +1,63 @@
const AuthenticationManagerLdap = require('./AuthenticationManagerLdap')
const AuthenticationController = require('../../../../app/src/Features/Authentication/AuthenticationController')
const LoginRateLimiter = require('../../../../app/src/Features/Security/LoginRateLimiter')
const logger = require('@overleaf/logger')
const { handleAuthenticateErrors } = require('../../../../app/src/Features/Authentication/AuthenticationErrors')
const Modules = require('../../../../app/src/infrastructure/Modules')
const AuthenticationControllerLdap = {
async doPassportLdapLogin(req, ldapUser, done) {
let user, info
try {
;({ user, info } = await AuthenticationControllerLdap._doPassportLdapLogin(
req,
ldapUser
))
} catch (error) {
return done(error)
}
return done(undefined, user, info)
},
async _doPassportLdapLogin(req, ldapUser) {
const { fromKnownDevice } = AuthenticationController.getAuditInfo(req)
const auditLog = {
ipAddress: req.ip,
info: { method: 'LDAP password login', fromKnownDevice },
}
let user, isPasswordReused
try {
user = await AuthenticationManagerLdap.promises.findOrCreateLdapUser(ldapUser, auditLog)
} catch (error) {
return {
user: false,
info: handleAuthenticateErrors(error, req),
}
}
if (user && AuthenticationController.captchaRequiredForLogin(req, user)) {
return {
user: false,
info: {
text: req.i18n.translate('cannot_verify_user_not_robot'),
type: 'error',
errorReason: 'cannot_verify_user_not_robot',
status: 400,
},
}
} else if (user) {
// async actions
return { user, info: undefined }
} else { //something wrong
logger.debug({ email : ldapUser.mail }, 'failed LDAP log in')
return {
user: false,
info: {
type: 'error',
status: 500,
},
}
}
},
}
module.exports = AuthenticationControllerLdap

View file

@ -0,0 +1,73 @@
const Settings = require('@overleaf/settings')
const UserCreator = require('../../../../app/src/Features/User/UserCreator')
const { User } = require('../../../../app/src/models/User')
const {
callbackify,
promisify,
} = require('@overleaf/promise-utils')
const AuthenticationManagerLdap = {
splitFullName(fullName) {
fullName = fullName.trim();
let lastSpaceIndex = fullName.lastIndexOf(' ');
let firstNames = fullName.substring(0, lastSpaceIndex).trim();
let lastName = fullName.substring(lastSpaceIndex + 1).trim();
return [firstNames, lastName];
},
async findOrCreateLdapUser(ldapUser, auditLog) {
//user is already authenticated in Ldap
const attEmail = Settings.ldap.attEmail
const attFirstName = Settings.ldap?.attFirstName || ""
const attLastName = Settings.ldap?.attLastName || ""
const attName = Settings.ldap?.attName || ""
let nameParts = ["",""]
if ((!attFirstName || !attLastName) && attName) {
nameParts = this.splitFullName(ldapUser[attName] || "")
}
const firstName = attFirstName ? (ldapUser[attFirstName] || "") : nameParts[0]
const lastName = attLastName ? (ldapUser[attLastName] || "") : nameParts[1]
const email = Array.isArray(ldapUser[attEmail])
? ldapUser[attEmail][0].toLowerCase()
: ldapUser[attEmail].toLowerCase()
const isAdmin = ldapUser._groups?.length > 0
var user = await User.findOne({ 'email': email }).exec()
if( !user ) {
user = await UserCreator.promises.createNewUser(
{
email: email,
first_name: firstName,
last_name: lastName,
isAdmin: isAdmin,
holdingAccount: false,
}
)
await User.updateOne(
{ _id: user._id },
{ $set : { 'emails.0.confirmedAt' : Date.now() } }
).exec() //email of ldap user is confirmed
}
var userDetails = Settings.ldap.updateUserDetailsOnLogin ? { first_name : firstName, last_name: lastName } : {}
if( Settings.ldap.updateAdminOnLogin ) {
user.isAdmin = isAdmin
userDetails.isAdmin = isAdmin
}
const result = await User.updateOne(
{ _id: user._id, loginEpoch: user.loginEpoch }, { $inc: { loginEpoch: 1 }, $set: userDetails },
{}
).exec()
if (result.modifiedCount !== 1) {
throw new ParallelLoginError()
}
return user
},
}
module.exports = {
findOrCreateLdapUser: callbackify(AuthenticationManagerLdap.findOrCreateLdapUser),
splitFullName: AuthenticationManagerLdap.splitFullName,
promises: AuthenticationManagerLdap,
}

View file

@ -0,0 +1,666 @@
const AuthenticationManager = require('./AuthenticationManager')
const SessionManager = require('./SessionManager')
const OError = require('@overleaf/o-error')
const LoginRateLimiter = require('../Security/LoginRateLimiter')
const UserUpdater = require('../User/UserUpdater')
const Metrics = require('@overleaf/metrics')
const logger = require('@overleaf/logger')
const querystring = require('querystring')
const Settings = require('@overleaf/settings')
const basicAuth = require('basic-auth')
const tsscmp = require('tsscmp')
const UserHandler = require('../User/UserHandler')
const UserSessionsManager = require('../User/UserSessionsManager')
const Analytics = require('../Analytics/AnalyticsManager')
const passport = require('passport')
const NotificationsBuilder = require('../Notifications/NotificationsBuilder')
const UrlHelper = require('../Helpers/UrlHelper')
const AsyncFormHelper = require('../Helpers/AsyncFormHelper')
const _ = require('lodash')
const UserAuditLogHandler = require('../User/UserAuditLogHandler')
const AnalyticsRegistrationSourceHelper = require('../Analytics/AnalyticsRegistrationSourceHelper')
const {
acceptsJson,
} = require('../../infrastructure/RequestContentTypeDetection')
const {
ParallelLoginError,
PasswordReusedError,
} = require('./AuthenticationErrors')
const { hasAdminAccess } = require('../Helpers/AdminAuthorizationHelper')
const Modules = require('../../infrastructure/Modules')
const { expressify, promisify } = require('@overleaf/promise-utils')
function send401WithChallenge(res) {
res.setHeader('WWW-Authenticate', 'OverleafLogin')
res.sendStatus(401)
}
function checkCredentials(userDetailsMap, user, password) {
const expectedPassword = userDetailsMap.get(user)
const userExists = userDetailsMap.has(user) && expectedPassword // user exists with a non-null password
const isValid = userExists && tsscmp(expectedPassword, password)
if (!isValid) {
logger.err({ user }, 'invalid login details')
}
Metrics.inc('security.http-auth.check-credentials', 1, {
path: userExists ? 'known-user' : 'unknown-user',
status: isValid ? 'pass' : 'fail',
})
return isValid
}
function reduceStaffAccess(staffAccess) {
const reducedStaffAccess = {}
for (const field in staffAccess) {
if (staffAccess[field]) {
reducedStaffAccess[field] = true
}
}
return reducedStaffAccess
}
function userHasStaffAccess(user) {
return user.staffAccess && Object.values(user.staffAccess).includes(true)
}
// TODO: Finish making these methods async
const AuthenticationController = {
serializeUser(user, callback) {
if (!user._id || !user.email) {
const err = new Error('serializeUser called with non-user object')
logger.warn({ user }, err.message)
return callback(err)
}
const lightUser = {
_id: user._id,
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
referal_id: user.referal_id,
session_created: new Date().toISOString(),
ip_address: user._login_req_ip,
must_reconfirm: user.must_reconfirm,
v1_id: user.overleaf != null ? user.overleaf.id : undefined,
analyticsId: user.analyticsId || user._id,
alphaProgram: user.alphaProgram || undefined, // only store if set
betaProgram: user.betaProgram || undefined, // only store if set
}
if (user.isAdmin) {
lightUser.isAdmin = true
}
if (userHasStaffAccess(user)) {
lightUser.staffAccess = reduceStaffAccess(user.staffAccess)
}
callback(null, lightUser)
},
deserializeUser(user, cb) {
cb(null, user)
},
passportLogin(req, res, next) {
// This function is middleware which wraps the passport.authenticate middleware,
// so we can send back our custom `{message: {text: "", type: ""}}` responses on failure,
// and send a `{redir: ""}` response on success
passport.authenticate(
Settings.ldap?.enable ? ['custom-fail-ldapauth','local'] : ['local'],
{ keepSessionInfo: true },
function (err, user, infoArray) {
if (err) {
return next(err)
}
if (user) {
// `user` is either a user object or false
AuthenticationController.setAuditInfo(req, {
method: 'Password login',
})
return AuthenticationController.finishLogin(user, req, res, next)
} else {
let info = infoArray[0]
if (info.redir != null) {
return res.json({ redir: info.redir })
} else {
res.status(info.status || 200)
delete info.status
const body = { message: info }
const { errorReason } = info
if (errorReason) {
body.errorReason = errorReason
delete info.errorReason
}
return res.json(body)
}
}
}
)(req, res, next)
},
async _finishLoginAsync(user, req, res) {
if (user === false) {
return AsyncFormHelper.redirect(req, res, '/login')
} // OAuth2 'state' mismatch
if (user.suspended) {
return AsyncFormHelper.redirect(req, res, '/account-suspended')
}
if (Settings.adminOnlyLogin && !hasAdminAccess(user)) {
return res.status(403).json({
message: { type: 'error', text: 'Admin only panel' },
})
}
const auditInfo = AuthenticationController.getAuditInfo(req)
const anonymousAnalyticsId = req.session.analyticsId
const isNewUser = req.session.justRegistered || false
const results = await Modules.promises.hooks.fire(
'preFinishLogin',
req,
res,
user
)
if (results.some(result => result && result.doNotFinish)) {
return
}
if (user.must_reconfirm) {
return AuthenticationController._redirectToReconfirmPage(req, res, user)
}
const redir =
AuthenticationController.getRedirectFromSession(req) || '/project'
_loginAsyncHandlers(req, user, anonymousAnalyticsId, isNewUser)
const userId = user._id
await UserAuditLogHandler.promises.addEntry(
userId,
'login',
userId,
req.ip,
auditInfo
)
await _afterLoginSessionSetupAsync(req, user)
AuthenticationController._clearRedirectFromSession(req)
AnalyticsRegistrationSourceHelper.clearSource(req.session)
AnalyticsRegistrationSourceHelper.clearInbound(req.session)
AsyncFormHelper.redirect(req, res, redir)
},
finishLogin(user, req, res, next) {
AuthenticationController._finishLoginAsync(user, req, res).catch(err =>
next(err)
)
},
doPassportLogin(req, username, password, done) {
const email = username.toLowerCase()
Modules.hooks.fire(
'preDoPassportLogin',
req,
email,
function (err, infoList) {
if (err) {
return done(err)
}
const info = infoList.find(i => i != null)
if (info != null) {
return done(null, false, info)
}
LoginRateLimiter.processLoginRequest(email, function (err, isAllowed) {
if (err) {
return done(err)
}
if (!isAllowed) {
logger.debug({ email }, 'too many login requests')
return done(null, null, {
text: req.i18n.translate('to_many_login_requests_2_mins'),
type: 'error',
key: 'to-many-login-requests-2-mins',
status: 429,
})
}
const { fromKnownDevice } = AuthenticationController.getAuditInfo(req)
const auditLog = {
ipAddress: req.ip,
info: { method: 'Password login', fromKnownDevice },
}
AuthenticationManager.authenticate(
{ email },
password,
auditLog,
{
enforceHIBPCheck: !fromKnownDevice,
},
function (error, user, isPasswordReused) {
if (error != null) {
if (error instanceof ParallelLoginError) {
return done(null, false, { status: 429 })
} else if (error instanceof PasswordReusedError) {
const text = `${req.i18n
.translate(
'password_compromised_try_again_or_use_known_device_or_reset'
)
.replace('<0>', '')
.replace('</0>', ' (https://haveibeenpwned.com/passwords)')
.replace('<1>', '')
.replace(
'</1>',
` (${Settings.siteUrl}/user/password/reset)`
)}.`
return done(null, false, {
status: 400,
type: 'error',
key: 'password-compromised',
text,
})
}
return done(error)
}
if (
user &&
AuthenticationController.captchaRequiredForLogin(req, user)
) {
done(null, false, {
text: req.i18n.translate('cannot_verify_user_not_robot'),
type: 'error',
errorReason: 'cannot_verify_user_not_robot',
status: 400,
})
} else if (user) {
if (
isPasswordReused &&
AuthenticationController.getRedirectFromSession(req) == null
) {
AuthenticationController.setRedirectInSession(
req,
'/compromised-password'
)
}
// async actions
done(null, user)
} else {
AuthenticationController._recordFailedLogin()
logger.debug({ email }, 'failed log in')
done(null, false, {
type: 'error',
key: 'invalid-password-retry-or-reset',
status: 401,
})
}
}
)
})
}
)
},
captchaRequiredForLogin(req, user) {
switch (AuthenticationController.getAuditInfo(req).captcha) {
case 'trusted':
case 'disabled':
return false
case 'solved':
return false
case 'skipped': {
let required = false
if (user.lastFailedLogin) {
const requireCaptchaUntil =
user.lastFailedLogin.getTime() +
Settings.elevateAccountSecurityAfterFailedLogin
required = requireCaptchaUntil >= Date.now()
}
Metrics.inc('force_captcha_on_login', 1, {
status: required ? 'yes' : 'no',
})
return required
}
default:
throw new Error('captcha middleware missing in handler chain')
}
},
ipMatchCheck(req, user) {
if (req.ip !== user.lastLoginIp) {
NotificationsBuilder.ipMatcherAffiliation(user._id).create(
req.ip,
() => {}
)
}
return UserUpdater.updateUser(
user._id.toString(),
{
$set: { lastLoginIp: req.ip },
},
() => {}
)
},
requireLogin() {
const doRequest = function (req, res, next) {
if (next == null) {
next = function () {}
}
if (!SessionManager.isUserLoggedIn(req.session)) {
if (acceptsJson(req)) return send401WithChallenge(res)
return AuthenticationController._redirectToLoginOrRegisterPage(req, res)
} else {
req.user = SessionManager.getSessionUser(req.session)
return next()
}
}
return doRequest
},
/**
* @param {string} scope
* @return {import('express').Handler}
*/
requireOauth(scope) {
if (typeof scope !== 'string' || !scope) {
throw new Error(
"requireOauth() expects a non-empty string as 'scope' parameter"
)
}
// require this here because module may not be included in some versions
const Oauth2Server = require('../../../../modules/oauth2-server/app/src/Oauth2Server')
const middleware = async (req, res, next) => {
const request = new Oauth2Server.Request(req)
const response = new Oauth2Server.Response(res)
try {
const token = await Oauth2Server.server.authenticate(
request,
response,
{ scope }
)
req.oauth = { access_token: token.accessToken }
req.oauth_token = token
req.oauth_user = token.user
next()
} catch (err) {
if (
err.code === 400 &&
err.message === 'Invalid request: malformed authorization header'
) {
err.code = 401
}
// send all other errors
res
.status(err.code)
.json({ error: err.name, error_description: err.message })
}
}
return expressify(middleware)
},
_globalLoginWhitelist: [],
addEndpointToLoginWhitelist(endpoint) {
return AuthenticationController._globalLoginWhitelist.push(endpoint)
},
requireGlobalLogin(req, res, next) {
if (
AuthenticationController._globalLoginWhitelist.includes(
req._parsedUrl.pathname
)
) {
return next()
}
if (req.headers.authorization != null) {
AuthenticationController.requirePrivateApiAuth()(req, res, next)
} else if (SessionManager.isUserLoggedIn(req.session)) {
next()
} else {
logger.debug(
{ url: req.url },
'user trying to access endpoint not in global whitelist'
)
if (acceptsJson(req)) return send401WithChallenge(res)
AuthenticationController.setRedirectInSession(req)
res.redirect('/login')
}
},
validateAdmin(req, res, next) {
const adminDomains = Settings.adminDomains
if (
!adminDomains ||
!(Array.isArray(adminDomains) && adminDomains.length)
) {
return next()
}
const user = SessionManager.getSessionUser(req.session)
if (!hasAdminAccess(user)) {
return next()
}
const email = user.email
if (email == null) {
return next(
new OError('[ValidateAdmin] Admin user without email address', {
userId: user._id,
})
)
}
if (!adminDomains.find(domain => email.endsWith(`@${domain}`))) {
return next(
new OError('[ValidateAdmin] Admin user with invalid email domain', {
email,
userId: user._id,
})
)
}
return next()
},
checkCredentials,
requireBasicAuth: function (userDetails) {
const userDetailsMap = new Map(Object.entries(userDetails))
return function (req, res, next) {
const credentials = basicAuth(req)
if (
!credentials ||
!checkCredentials(userDetailsMap, credentials.name, credentials.pass)
) {
send401WithChallenge(res)
Metrics.inc('security.http-auth', 1, { status: 'reject' })
} else {
Metrics.inc('security.http-auth', 1, { status: 'accept' })
next()
}
}
},
requirePrivateApiAuth() {
return AuthenticationController.requireBasicAuth(Settings.httpAuthUsers)
},
setAuditInfo(req, info) {
if (!req.__authAuditInfo) {
req.__authAuditInfo = {}
}
Object.assign(req.__authAuditInfo, info)
},
getAuditInfo(req) {
return req.__authAuditInfo || {}
},
setRedirectInSession(req, value) {
if (value == null) {
value =
Object.keys(req.query).length > 0
? `${req.path}?${querystring.stringify(req.query)}`
: `${req.path}`
}
if (
req.session != null &&
!/^\/(socket.io|js|stylesheets|img)\/.*$/.test(value) &&
!/^.*\.(png|jpeg|svg)$/.test(value)
) {
const safePath = UrlHelper.getSafeRedirectPath(value)
return (req.session.postLoginRedirect = safePath)
}
},
_redirectToLoginOrRegisterPage(req, res) {
if (
req.query.zipUrl != null ||
req.session.sharedProjectData ||
req.path === '/user/subscription/new'
) {
AuthenticationController._redirectToRegisterPage(req, res)
} else {
AuthenticationController._redirectToLoginPage(req, res)
}
},
_redirectToLoginPage(req, res) {
logger.debug(
{ url: req.url },
'user not logged in so redirecting to login page'
)
AuthenticationController.setRedirectInSession(req)
const url = `/login?${querystring.stringify(req.query)}`
res.redirect(url)
Metrics.inc('security.login-redirect')
},
_redirectToReconfirmPage(req, res, user) {
logger.debug(
{ url: req.url },
'user needs to reconfirm so redirecting to reconfirm page'
)
req.session.reconfirm_email = user != null ? user.email : undefined
const redir = '/user/reconfirm'
AsyncFormHelper.redirect(req, res, redir)
},
_redirectToRegisterPage(req, res) {
logger.debug(
{ url: req.url },
'user not logged in so redirecting to register page'
)
AuthenticationController.setRedirectInSession(req)
const url = `/register?${querystring.stringify(req.query)}`
res.redirect(url)
Metrics.inc('security.login-redirect')
},
_recordSuccessfulLogin(userId, callback) {
if (callback == null) {
callback = function () {}
}
UserUpdater.updateUser(
userId.toString(),
{
$set: { lastLoggedIn: new Date() },
$inc: { loginCount: 1 },
},
function (error) {
if (error != null) {
callback(error)
}
Metrics.inc('user.login.success')
callback()
}
)
},
_recordFailedLogin(callback) {
Metrics.inc('user.login.failed')
if (callback) callback()
},
getRedirectFromSession(req) {
let safePath
const value = _.get(req, ['session', 'postLoginRedirect'])
if (value) {
safePath = UrlHelper.getSafeRedirectPath(value)
}
return safePath || null
},
_clearRedirectFromSession(req) {
if (req.session != null) {
delete req.session.postLoginRedirect
}
},
}
function _afterLoginSessionSetup(req, user, callback) {
req.login(user, { keepSessionInfo: true }, function (err) {
if (err) {
OError.tag(err, 'error from req.login', {
user_id: user._id,
})
return callback(err)
}
delete req.session.__tmp
delete req.session.csrfSecret
req.session.save(function (err) {
if (err) {
OError.tag(err, 'error saving regenerated session after login', {
user_id: user._id,
})
return callback(err)
}
UserSessionsManager.trackSession(user, req.sessionID, function () {})
if (!req.deviceHistory) {
// Captcha disabled or SSO-based login.
return callback()
}
req.deviceHistory.add(user.email)
req.deviceHistory
.serialize(req.res)
.catch(err => {
logger.err({ err }, 'cannot serialize deviceHistory')
})
.finally(() => callback())
})
})
}
const _afterLoginSessionSetupAsync = promisify(_afterLoginSessionSetup)
function _loginAsyncHandlers(req, user, anonymousAnalyticsId, isNewUser) {
UserHandler.setupLoginData(user, err => {
if (err != null) {
logger.warn({ err }, 'error setting up login data')
}
})
LoginRateLimiter.recordSuccessfulLogin(user.email, () => {})
AuthenticationController._recordSuccessfulLogin(user._id, () => {})
AuthenticationController.ipMatchCheck(req, user)
Analytics.recordEventForUserInBackground(user._id, 'user-logged-in', {
source: req.session.saml
? 'saml'
: req.user_info?.auth_provider || 'email-password',
})
Analytics.identifyUser(user._id, anonymousAnalyticsId, isNewUser)
logger.debug(
{ email: user.email, userId: user._id.toString() },
'successful log in'
)
req.session.justLoggedIn = true
// capture the request ip for use when creating the session
return (user._login_req_ip = req.ip)
}
AuthenticationController.promises = {
finishLogin: AuthenticationController._finishLoginAsync,
}
module.exports = AuthenticationController

View file

@ -0,0 +1,212 @@
const PasswordResetHandler = require('./PasswordResetHandler')
const AuthenticationController = require('../Authentication/AuthenticationController')
const AuthenticationManager = require('../Authentication/AuthenticationManager')
const SessionManager = require('../Authentication/SessionManager')
const UserGetter = require('../User/UserGetter')
const UserUpdater = require('../User/UserUpdater')
const UserSessionsManager = require('../User/UserSessionsManager')
const OError = require('@overleaf/o-error')
const EmailsHelper = require('../Helpers/EmailHelper')
const { expressify } = require('@overleaf/promise-utils')
async function setNewUserPassword(req, res, next) {
let user
let { passwordResetToken, password, email } = req.body
if (!passwordResetToken || !password) {
return res.status(400).json({
message: {
key: 'invalid-password',
},
})
}
const err = AuthenticationManager.validatePassword(password, email)
if (err) {
const message = AuthenticationManager.getMessageForInvalidPasswordError(
err,
req
)
return res.status(400).json({ message })
}
passwordResetToken = passwordResetToken.trim()
const initiatorId = SessionManager.getLoggedInUserId(req.session)
// password reset via tokens can be done while logged in, or not
const auditLog = {
initiatorId,
ip: req.ip,
}
try {
const result = await PasswordResetHandler.promises.setNewUserPassword(
passwordResetToken,
password,
auditLog
)
const { found, reset, userId } = result
if (!found) {
return res.status(404).json({
message: {
key: 'token-expired',
},
})
}
if (!reset) {
return res.status(500).json({
message: req.i18n.translate('error_performing_request'),
})
}
await UserSessionsManager.promises.removeSessionsFromRedis({ _id: userId })
await UserUpdater.promises.removeReconfirmFlag(userId)
if (!req.session.doLoginAfterPasswordReset) {
return res.sendStatus(200)
}
user = await UserGetter.promises.getUser(userId)
} catch (error) {
if (error.name === 'NotFoundError') {
return res.status(404).json({
message: {
key: 'token-expired',
},
})
} else if (error.name === 'InvalidPasswordError') {
return res.status(400).json({
message: {
key: 'invalid-password',
},
})
} else if (error.name === 'PasswordMustBeDifferentError') {
return res.status(400).json({
message: {
key: 'password-must-be-different',
},
})
} else if (error.name === 'PasswordReusedError') {
return res.status(400).json({
message: {
key: 'password-must-be-strong',
},
})
} else {
return res.status(500).json({
message: req.i18n.translate('error_performing_request'),
})
}
}
AuthenticationController.setAuditInfo(req, {
method: 'Password reset, set new password',
})
AuthenticationController.finishLogin(user, req, res, next)
}
async function requestReset(req, res, next) {
const email = EmailsHelper.parseEmail(req.body.email)
if (!email) {
return res.status(400).json({
message: req.i18n.translate('must_be_email_address'),
})
}
let status
try {
status =
await PasswordResetHandler.promises.generateAndEmailResetToken(email)
} catch (err) {
OError.tag(err, 'failed to generate and email password reset token', {
email,
})
if (err.message === 'user does not have permission for change-password') {
return res.status(403).json({
message: {
key: 'no-password-allowed-due-to-sso',
},
})
}
throw err
}
if (status === 'primary') {
return res.status(200).json({
message: req.i18n.translate('password_reset_email_sent'),
})
} else if (status === 'secondary') {
return res.status(404).json({
message: req.i18n.translate('secondary_email_password_reset'),
})
} else if (status === 'external') {
return res.status(403).json({
message: req.i18n.translate('password_managed_externally'),
})
} else {
return res.status(404).json({
message: req.i18n.translate('cant_find_email'),
})
}
}
async function renderSetPasswordForm(req, res, next) {
if (req.query.passwordResetToken != null) {
try {
const result =
await PasswordResetHandler.promises.getUserForPasswordResetToken(
req.query.passwordResetToken
)
const { user, remainingPeeks } = result || {}
if (!user || remainingPeeks <= 0) {
return res.redirect('/user/password/reset?error=token_expired')
}
req.session.resetToken = req.query.passwordResetToken
let emailQuery = ''
if (typeof req.query.email === 'string') {
const email = EmailsHelper.parseEmail(req.query.email)
if (email) {
emailQuery = `?email=${encodeURIComponent(email)}`
}
}
return res.redirect('/user/password/set' + emailQuery)
} catch (err) {
if (err.name === 'ForbiddenError') {
return next(err)
}
return res.redirect('/user/password/reset?error=token_expired')
}
}
if (req.session.resetToken == null) {
return res.redirect('/user/password/reset')
}
const email = EmailsHelper.parseEmail(req.query.email)
// clean up to avoid leaking the token in the session object
const passwordResetToken = req.session.resetToken
delete req.session.resetToken
res.render('user/setPassword', {
title: 'set_password',
email,
passwordResetToken,
})
}
module.exports = {
renderRequestResetForm(req, res) {
const errorQuery = req.query.error
let error = null
if (errorQuery === 'token_expired') {
error = 'password_reset_token_expired'
}
res.render('user/passwordReset', {
title: 'reset_password',
error,
})
},
requestReset: expressify(requestReset),
renderSetPasswordForm: expressify(renderSetPasswordForm),
setNewUserPassword: expressify(setNewUserPassword),
}

View file

@ -0,0 +1,145 @@
const settings = require('@overleaf/settings')
const UserAuditLogHandler = require('../User/UserAuditLogHandler')
const UserGetter = require('../User/UserGetter')
const OneTimeTokenHandler = require('../Security/OneTimeTokenHandler')
const EmailHandler = require('../Email/EmailHandler')
const AuthenticationManager = require('../Authentication/AuthenticationManager')
const { callbackify, promisify } = require('util')
const { assertUserPermissions } =
require('../Authorization/PermissionsManager').promises
const AUDIT_LOG_TOKEN_PREFIX_LENGTH = 10
async function generateAndEmailResetToken(email) {
const user = await UserGetter.promises.getUserByAnyEmail(email)
if (!user) {
return null
}
if (!user.hashedPassword) {
return 'external'
}
if (user.email !== email) {
return 'secondary'
}
await assertUserPermissions(user, ['change-password'])
const data = { user_id: user._id.toString(), email }
const token = await OneTimeTokenHandler.promises.getNewToken('password', data)
const emailOptions = {
to: email,
setNewPasswordUrl: `${
settings.siteUrl
}/user/password/set?passwordResetToken=${token}&email=${encodeURIComponent(
email
)}`,
}
await EmailHandler.promises.sendEmail('passwordResetRequested', emailOptions)
return 'primary'
}
function expirePasswordResetToken(token, callback) {
OneTimeTokenHandler.expireToken('password', token, err => {
return callback(err)
})
}
async function getUserForPasswordResetToken(token) {
let result
try {
result = await OneTimeTokenHandler.promises.peekValueFromToken(
'password',
token
)
} catch (err) {
if (err.name === 'NotFoundError') {
return
} else {
throw err
}
}
const { data, remainingPeeks } = result || {}
if (data == null || data.email == null) {
return { user: null, remainingPeeks }
}
const user = await UserGetter.promises.getUserByMainEmail(data.email, {
_id: 1,
'overleaf.id': 1,
email: 1,
})
await assertUserPermissions(user, ['change-password'])
if (user == null) {
return { user: null, remainingPeeks: 0 }
} else if (data.user_id != null && data.user_id === user._id.toString()) {
return { user, remainingPeeks }
} else if (
data.v1_user_id != null &&
user.overleaf != null &&
data.v1_user_id === user.overleaf.id
) {
return { user, remainingPeeks }
} else {
return { user: null, remainingPeeks: 0 }
}
}
async function setNewUserPassword(token, password, auditLog) {
const result =
await PasswordResetHandler.promises.getUserForPasswordResetToken(token)
const { user } = result || {}
if (!user) {
return {
found: false,
reset: false,
userId: null,
}
}
await UserAuditLogHandler.promises.addEntry(
user._id,
'reset-password',
auditLog.initiatorId,
auditLog.ip,
{ token: token.substring(0, AUDIT_LOG_TOKEN_PREFIX_LENGTH) }
)
const reset = await AuthenticationManager.promises.setUserPassword(
user,
password
)
await PasswordResetHandler.promises.expirePasswordResetToken(token)
return { found: true, reset, userId: user._id }
}
const PasswordResetHandler = {
generateAndEmailResetToken: callbackify(generateAndEmailResetToken),
setNewUserPassword: callbackify(setNewUserPassword),
getUserForPasswordResetToken: callbackify(getUserForPasswordResetToken),
expirePasswordResetToken,
}
PasswordResetHandler.promises = {
generateAndEmailResetToken,
getUserForPasswordResetToken,
expirePasswordResetToken: promisify(
PasswordResetHandler.expirePasswordResetToken
),
setNewUserPassword,
}
module.exports = PasswordResetHandler

View file

@ -0,0 +1,517 @@
const UserHandler = require('./UserHandler')
const UserDeleter = require('./UserDeleter')
const UserGetter = require('./UserGetter')
const { User } = require('../../models/User')
const NewsletterManager = require('../Newsletter/NewsletterManager')
const logger = require('@overleaf/logger')
const metrics = require('@overleaf/metrics')
const AuthenticationManager = require('../Authentication/AuthenticationManager')
const SessionManager = require('../Authentication/SessionManager')
const Features = require('../../infrastructure/Features')
const UserAuditLogHandler = require('./UserAuditLogHandler')
const UserSessionsManager = require('./UserSessionsManager')
const UserUpdater = require('./UserUpdater')
const Errors = require('../Errors/Errors')
const HttpErrorHandler = require('../Errors/HttpErrorHandler')
const OError = require('@overleaf/o-error')
const EmailHandler = require('../Email/EmailHandler')
const UrlHelper = require('../Helpers/UrlHelper')
const { promisify, callbackify } = require('util')
const { expressify } = require('@overleaf/promise-utils')
const {
acceptsJson,
} = require('../../infrastructure/RequestContentTypeDetection')
const Modules = require('../../infrastructure/Modules')
const OneTimeTokenHandler = require('../Security/OneTimeTokenHandler')
async function _sendSecurityAlertClearedSessions(user) {
const emailOptions = {
to: user.email,
actionDescribed: `active sessions were cleared on your account ${user.email}`,
action: 'active sessions cleared',
}
try {
await EmailHandler.promises.sendEmail('securityAlert', emailOptions)
} catch (error) {
// log error when sending security alert email but do not pass back
logger.error(
{ error, userId: user._id },
'could not send security alert email when sessions cleared'
)
}
}
function _sendSecurityAlertPasswordChanged(user) {
const emailOptions = {
to: user.email,
actionDescribed: `your password has been changed on your account ${user.email}`,
action: 'password changed',
}
EmailHandler.promises
.sendEmail('securityAlert', emailOptions)
.catch(error => {
// log error when sending security alert email but do not pass back
logger.error(
{ error, userId: user._id },
'could not send security alert email when password changed'
)
})
}
async function _ensureAffiliation(userId, emailData) {
if (emailData.samlProviderId) {
await UserUpdater.promises.confirmEmail(userId, emailData.email)
} else {
await UserUpdater.promises.addAffiliationForNewUser(userId, emailData.email)
}
}
async function changePassword(req, res, next) {
metrics.inc('user.password-change')
const userId = SessionManager.getLoggedInUserId(req.session)
const { user } = await AuthenticationManager.promises.authenticate(
{ _id: userId },
req.body.currentPassword,
null,
{ enforceHIBPCheck: false }
)
if (!user) {
return HttpErrorHandler.badRequest(
req,
res,
req.i18n.translate('password_change_old_password_wrong')
)
}
if (req.body.newPassword1 !== req.body.newPassword2) {
return HttpErrorHandler.badRequest(
req,
res,
req.i18n.translate('password_change_passwords_do_not_match')
)
}
try {
await AuthenticationManager.promises.setUserPassword(
user,
req.body.newPassword1
)
} catch (error) {
if (error.name === 'InvalidPasswordError') {
const message = AuthenticationManager.getMessageForInvalidPasswordError(
error,
req
)
return res.status(400).json({ message })
} else if (error.name === 'PasswordMustBeDifferentError') {
return HttpErrorHandler.badRequest(
req,
res,
req.i18n.translate('password_change_password_must_be_different')
)
} else if (error.name === 'PasswordReusedError') {
return res.status(400).json({
message: {
key: 'password-must-be-strong',
},
})
} else {
throw error
}
}
await UserAuditLogHandler.promises.addEntry(
user._id,
'update-password',
user._id,
req.ip
)
// no need to wait, errors are logged and not passed back
_sendSecurityAlertPasswordChanged(user)
await UserSessionsManager.promises.removeSessionsFromRedis(
user,
req.sessionID // remove all sessions except the current session
)
await OneTimeTokenHandler.promises.expireAllTokensForUser(
userId.toString(),
'password'
)
return res.json({
message: {
type: 'success',
email: user.email,
text: req.i18n.translate('password_change_successful'),
},
})
}
async function clearSessions(req, res, next) {
metrics.inc('user.clear-sessions')
const userId = SessionManager.getLoggedInUserId(req.session)
const user = await UserGetter.promises.getUser(userId, { email: 1 })
const sessions = await UserSessionsManager.promises.getAllUserSessions(user, [
req.sessionID,
])
await UserAuditLogHandler.promises.addEntry(
user._id,
'clear-sessions',
user._id,
req.ip,
{ sessions }
)
await UserSessionsManager.promises.removeSessionsFromRedis(
user,
req.sessionID // remove all sessions except the current session
)
await _sendSecurityAlertClearedSessions(user)
res.sendStatus(201)
}
async function ensureAffiliation(user) {
if (!Features.hasFeature('affiliations')) {
return
}
const flaggedEmails = user.emails.filter(email => email.affiliationUnchecked)
if (flaggedEmails.length === 0) {
return
}
if (flaggedEmails.length > 1) {
logger.error(
{ userId: user._id },
`Unexpected number of flagged emails: ${flaggedEmails.length}`
)
}
await _ensureAffiliation(user._id, flaggedEmails[0])
}
async function ensureAffiliationMiddleware(req, res, next) {
let user
if (!Features.hasFeature('affiliations') || !req.query.ensureAffiliation) {
return next()
}
const userId = SessionManager.getLoggedInUserId(req.session)
try {
user = await UserGetter.promises.getUser(userId)
} catch (error) {
return new Errors.UserNotFoundError({ info: { userId } })
}
// if the user does not have permission to add an affiliation, we skip this middleware
try {
req.assertPermission('add-affiliation')
} catch (error) {
if (error instanceof Errors.ForbiddenError) {
return next()
}
}
try {
await ensureAffiliation(user)
} catch (error) {
return next(error)
}
return next()
}
async function tryDeleteUser(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
const { password } = req.body
req.logger.addFields({ userId })
logger.debug({ userId }, 'trying to delete user account')
if (password == null || password === '') {
logger.err({ userId }, 'no password supplied for attempt to delete account')
return res.sendStatus(403)
}
let user
try {
user = (
await AuthenticationManager.promises.authenticate(
{ _id: userId },
password,
null,
{ enforceHIBPCheck: false }
)
).user
} catch (err) {
throw OError.tag(
err,
'error authenticating during attempt to delete account',
{ userId }
)
}
if (!user) {
logger.err({ userId }, 'auth failed during attempt to delete account')
return res.sendStatus(403)
}
try {
await UserDeleter.promises.deleteUser(userId, {
deleterUser: user,
ipAddress: req.ip,
})
} catch (err) {
const errorData = {
message: 'error while deleting user account',
info: { userId },
}
if (err instanceof Errors.SubscriptionAdminDeletionError) {
// set info.public.error for JSON response so frontend can display
// a specific message
errorData.info.public = {
error: 'SubscriptionAdminDeletionError',
}
logger.warn(OError.tag(err, errorData.message, errorData.info))
return HttpErrorHandler.unprocessableEntity(
req,
res,
errorData.message,
errorData.info.public
)
} else {
throw OError.tag(err, errorData.message, errorData.info)
}
}
await Modules.promises.hooks.fire('tryDeleteV1Account', user)
const sessionId = req.sessionID
if (typeof req.logout === 'function') {
const logout = promisify(req.logout)
await logout()
}
const destroySession = promisify(req.session.destroy.bind(req.session))
await destroySession()
UserSessionsManager.promises.untrackSession(user, sessionId).catch(err => {
logger.warn({ err, userId: user._id }, 'failed to untrack session')
})
res.sendStatus(200)
}
async function subscribe(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
req.logger.addFields({ userId })
const user = await UserGetter.promises.getUser(userId, {
_id: 1,
email: 1,
first_name: 1,
last_name: 1,
})
await NewsletterManager.promises.subscribe(user)
res.json({
message: req.i18n.translate('thanks_settings_updated'),
})
}
async function unsubscribe(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
req.logger.addFields({ userId })
const user = await UserGetter.promises.getUser(userId, {
_id: 1,
email: 1,
first_name: 1,
last_name: 1,
})
await NewsletterManager.promises.unsubscribe(user)
await Modules.promises.hooks.fire('newsletterUnsubscribed', user)
res.json({
message: req.i18n.translate('thanks_settings_updated'),
})
}
async function updateUserSettings(req, res, next) {
const userId = SessionManager.getLoggedInUserId(req.session)
req.logger.addFields({ userId })
const user = await User.findById(userId).exec()
if (user == null) {
throw new OError('problem updating user settings', { userId })
}
if (req.body.first_name != null) {
user.first_name = req.body.first_name.trim()
}
if (req.body.last_name != null) {
user.last_name = req.body.last_name.trim()
}
if (req.body.role != null) {
user.role = req.body.role.trim()
}
if (req.body.institution != null) {
user.institution = req.body.institution.trim()
}
if (req.body.mode != null) {
user.ace.mode = req.body.mode
}
if (req.body.editorTheme != null) {
user.ace.theme = req.body.editorTheme
}
if (req.body.overallTheme != null) {
user.ace.overallTheme = req.body.overallTheme
}
if (req.body.fontSize != null) {
user.ace.fontSize = req.body.fontSize
}
if (req.body.autoComplete != null) {
user.ace.autoComplete = req.body.autoComplete
}
if (req.body.autoPairDelimiters != null) {
user.ace.autoPairDelimiters = req.body.autoPairDelimiters
}
if (req.body.spellCheckLanguage != null) {
user.ace.spellCheckLanguage = req.body.spellCheckLanguage
}
if (req.body.pdfViewer != null) {
user.ace.pdfViewer = req.body.pdfViewer
}
if (req.body.syntaxValidation != null) {
user.ace.syntaxValidation = req.body.syntaxValidation
}
if (req.body.fontFamily != null) {
user.ace.fontFamily = req.body.fontFamily
}
if (req.body.lineHeight != null) {
user.ace.lineHeight = req.body.lineHeight
}
if (req.body.mathPreview != null) {
user.ace.mathPreview = req.body.mathPreview
}
await user.save()
const newEmail = req.body.email?.trim().toLowerCase()
if (
newEmail == null ||
newEmail === user.email ||
(req.externalAuthenticationSystemUsed() && !user.hashedPassword)
) {
// end here, don't update email
SessionManager.setInSessionUser(req.session, {
first_name: user.first_name,
last_name: user.last_name,
})
res.sendStatus(200)
} else if (newEmail.indexOf('@') === -1) {
// email invalid
res.sendStatus(400)
} else {
// update the user email
const auditLog = {
initiatorId: userId,
ipAddress: req.ip,
}
try {
await UserUpdater.promises.changeEmailAddress(userId, newEmail, auditLog)
} catch (err) {
if (err instanceof Errors.EmailExistsError) {
const translation = req.i18n.translate('email_already_registered')
return HttpErrorHandler.conflict(req, res, translation)
} else {
return HttpErrorHandler.legacyInternal(
req,
res,
req.i18n.translate('problem_changing_email_address'),
OError.tag(err, 'problem_changing_email_address', {
userId,
newEmail,
})
)
}
}
const user = await User.findById(userId).exec()
SessionManager.setInSessionUser(req.session, {
email: user.email,
first_name: user.first_name,
last_name: user.last_name,
})
try {
await UserHandler.promises.populateTeamInvites(user)
} catch (err) {
logger.error({ err }, 'error populateTeamInvites')
}
res.sendStatus(200)
}
}
async function doLogout(req) {
metrics.inc('user.logout')
const user = SessionManager.getSessionUser(req.session)
logger.debug({ user }, 'logging out')
const sessionId = req.sessionID
if (typeof req.logout === 'function') {
// passport logout
const logout = promisify(req.logout.bind(req))
await logout()
}
const destroySession = promisify(req.session.destroy.bind(req.session))
await destroySession()
if (user != null) {
UserSessionsManager.promises.untrackSession(user, sessionId).catch(err => {
logger.warn({ err, userId: user._id }, 'failed to untrack session')
})
}
}
async function logout(req, res, next) {
const requestedRedirect = req.body.redirect
? UrlHelper.getSafeRedirectPath(req.body.redirect)
: undefined
const redirectUrl = requestedRedirect || '/login'
await doLogout(req)
if (acceptsJson(req)) {
res.status(200).json({ redir: redirectUrl })
} else {
res.redirect(redirectUrl)
}
}
async function expireDeletedUser(req, res, next) {
const userId = req.params.userId
await UserDeleter.promises.expireDeletedUser(userId)
res.sendStatus(204)
}
async function expireDeletedUsersAfterDuration(req, res, next) {
await UserDeleter.promises.expireDeletedUsersAfterDuration()
res.sendStatus(204)
}
module.exports = {
clearSessions: expressify(clearSessions),
changePassword: expressify(changePassword),
tryDeleteUser: expressify(tryDeleteUser),
subscribe: expressify(subscribe),
unsubscribe: expressify(unsubscribe),
updateUserSettings: expressify(updateUserSettings),
doLogout: callbackify(doLogout),
logout: expressify(logout),
expireDeletedUser: expressify(expireDeletedUser),
expireDeletedUsersAfterDuration: expressify(expireDeletedUsersAfterDuration),
promises: {
doLogout,
ensureAffiliation,
ensureAffiliationMiddleware,
},
}

View file

@ -0,0 +1,54 @@
const Settings = require('@overleaf/settings')
const fs = require('fs')
function _getFilesContents(paths) {
return paths.map(path => {
try {
const content = fs.readFileSync(path)
return content
} catch (error) {
console.error(`Error reading file at ${path}:`, error)
return null
}
})
}
function initLdapAuthentication() {
Settings.ldap = {
enable: process.env.EXTERNAL_AUTH === 'ldap',
updateUserDetailsOnLogin: process.env.OVERLEAF_LDAP_UPDATE_USER_DETAILS_ON_LOGIN === 'true',
placeholder: process.env.OVERLEAF_LDAP_PLACEHOLDER || 'Username or email address',
attEmail: process.env.OVERLEAF_LDAP_EMAIL_ATT || 'mail',
attFirstName: process.env.OVERLEAF_LDAP_FIRST_NAME_ATT,
attLastName: process.env.OVERLEAF_LDAP_LAST_NAME_ATT,
attName: process.env.OVERLEAF_LDAP_NAME_ATT,
updateAdminOnLogin: process.env.OVERLEAF_LDAP_UPDATE_ADMIN_ON_LOGIN === 'true',
server: {
url: process.env.OVERLEAF_LDAP_URL,
bindDN: process.env.OVERLEAF_LDAP_BIND_DN || "",
bindCredentials: process.env.OVERLEAF_LDAP_BIND_CREDENTIALS || "",
bindProperty: process.env.OVERLEAF_LDAP_BIND_PROPERTY,
searchBase: process.env.OVERLEAF_LDAP_SEARCH_BASE,
searchFilter: process.env.OVERLEAF_LDAP_SEARCH_FILTER,
searchScope: process.env.OVERLEAF_LDAP_SEARCH_SCOPE || 'sub',
searchAttributes: JSON.parse(process.env.OVERLEAF_LDAP_SEARCH_ATTRIBUTES || '[]'),
groupSearchBase: process.env.OVERLEAF_LDAP_ADMIN_SEARCH_BASE,
groupSearchFilter: process.env.OVERLEAF_LDAP_ADMIN_SEARCH_FILTER,
groupSearchScope: process.env.OVERLEAF_LDAP_ADMIN_SEARCH_SCOPE || 'sub',
groupSearchAttributes: ["dn"],
groupDnProperty: process.env.OVERLEAF_LDAP_ADMIN_DN_PROPERTY,
cache: process.env.OVERLEAF_LDAP_CACHE === 'true',
timeout: process.env.OVERLEAF_LDAP_TIMEOUT,
connectTimeout: process.env.OVERLEAF_LDAP_CONNECT_TIMEOUT,
starttls: process.env.OVERLEAF_LDAP_STARTTLS === 'true',
tlsOptions: {
ca: _getFilesContents(
JSON.parse(process.env.OVERLEAF_LDAP_TLS_OPTS_CA_PATH || '[]')
),
rejectUnauthorized: process.env.OVERLEAF_LDAP_TLS_OPTS_REJECT_UNAUTH === 'true',
}
}
}
}
module.exports = { initLdapAuthentication }

View file

@ -0,0 +1,133 @@
const Settings = require('@overleaf/settings')
const ldapjs = require('ldapauth-fork/node_modules/ldapjs')
const { splitFullName } = require('./AuthenticationManagerLdap')
const UserGetter = require('../../../../app/src/Features/User/UserGetter')
async function fetchLdapContacts(userId, contacts) {
if (!Settings.ldap?.enable || !process.env.OVERLEAF_LDAP_CONTACTS_FILTER) {
return []
}
const { attEmail, attFirstName = "", attLastName = "", attName = "" } = Settings.ldap
const {
url,
timeout,
connectTimeout,
tlsOptions,
starttls,
bindDN,
bindCredentials,
} = Settings.ldap.server
const searchBase = process.env.OVERLEAF_LDAP_CONTACTS_SEARCH_BASE || Settings.ldap.server.searchBase
const searchScope = process.env.OVERLEAF_LDAP_CONTACTS_SEARCH_SCOPE || 'sub'
const ldapConfig = { url, timeout, connectTimeout, tlsOptions }
let ldapUsers
const client = ldapjs.createClient(ldapConfig)
try {
if (starttls) {
await _upgradeToTLS(client, tlsOptions)
}
await _bindLdap(client, bindDN, bindCredentials)
const filter = await _formContactsSearchFilter(client, userId, process.env.OVERLEAF_LDAP_CONTACTS_FILTER)
const searchOptions = { scope: searchScope, attributes: [attEmail, attFirstName, attLastName, attName], filter }
ldapUsers = await _searchLdap(client, searchBase, searchOptions)
} catch (error) {
console.error('Error in fetchLdapContacts: ', error)
return []
} finally {
client.unbind()
}
const newLdapContacts = ldapUsers.reduce((acc, ldapUser) => {
const email = Array.isArray(ldapUser[attEmail])
? ldapUser[attEmail][0]?.toLowerCase()
: ldapUser[attEmail]?.toLowerCase()
if (!email) return acc
if (!contacts.some(contact => contact.email === email)) {
let nameParts = ["",""]
if ((!attFirstName || !attLastName) && attName) {
nameParts = splitFullName(ldapUser[attName] || "")
}
const firstName = attFirstName ? (ldapUser[attFirstName] || "") : nameParts[0]
const lastName = attLastName ? (ldapUser[attLastName] || "") : nameParts[1]
acc.push({
first_name: firstName,
last_name: lastName,
email: email,
type: 'user',
})
}
return acc
}, [])
return newLdapContacts.sort((a, b) =>
a.last_name.localeCompare(b.last_name) ||
a.first_name.localeCompare(a.first_name) ||
a.email.localeCompare(b.email)
)
}
function _upgradeToTLS(client, tlsOptions) {
return new Promise((resolve, reject) => {
client.on('error', error => reject(new Error(`LDAP client error: ${error}`)))
client.on('connect', () => {
client.starttls(tlsOptions, null, error => {
if (error) {
reject(new Error(`StartTLS error: ${error}`))
} else {
resolve()
}
})
})
})
}
function _bindLdap(client, bindDN, bindCredentials) {
return new Promise((resolve, reject) => {
client.bind(bindDN, bindCredentials, error => {
if (error) {
reject(error)
} else {
resolve()
}
})
})
}
function _searchLdap(client, baseDN, options) {
return new Promise((resolve, reject) => {
const searchEntries = []
client.search(baseDN, options, (error, res) => {
if (error) {
reject(error)
} else {
res.on('searchEntry', entry => searchEntries.push(entry.object))
res.on('error', reject)
res.on('end', () => resolve(searchEntries))
}
})
})
}
async function _formContactsSearchFilter(client, userId, contactsFilter) {
const searchProperty = process.env.OVERLEAF_LDAP_CONTACTS_PROPERTY
if (!searchProperty) {
return contactsFilter
}
const email = await UserGetter.promises.getUserEmail(userId)
const searchOptions = {
scope: Settings.ldap.server.searchScope,
attributes: [searchProperty],
filter: `(${Settings.ldap.attEmail}=${email})`,
}
const searchBase = Settings.ldap.server.searchBase
const ldapUser = (await _searchLdap(client, searchBase, searchOptions))[0]
const searchPropertyValue = ldapUser ? ldapUser[searchProperty]
: process.env.OVERLEAF_LDAP_CONTACTS_NON_LDAP_VALUE || 'IMATCHNOTHING'
return contactsFilter.replace(/{{userProperty}}/g, searchPropertyValue)
}
module.exports = { fetchLdapContacts }

View file

@ -0,0 +1,38 @@
const Settings = require('@overleaf/settings')
const AuthenticationControllerLdap = require('./AuthenticationControllerLdap')
const passport = require('passport')
const LdapStrategy = require('passport-ldapauth').Strategy
// custom responses on authentication failure
class CustomFailLdapStrategy extends LdapStrategy {
constructor(options, validate) {
super(options, validate);
this.name = 'custom-fail-ldapauth'
}
authenticate(req, options) {
const defaultFail = this.fail.bind(this)
this.fail = function(info, status) {
info.type = 'error'
info.key = 'invalid-password-retry-or-reset'
info.status = 401
return defaultFail(info, status)
}.bind(this)
super.authenticate(req, options)
}
}
function addLdapStrategy(passport) {
passport.use(
new CustomFailLdapStrategy(
{
server: Settings.ldap.server,
passReqToCallback: true,
usernameField: 'email',
passwordField: 'password',
},
AuthenticationControllerLdap.doPassportLdapLogin
)
)
}
module.exports = { addLdapStrategy }

View file

@ -0,0 +1,101 @@
const _ = require('lodash')
const Settings = require('@overleaf/settings')
const supportModuleAvailable = Settings.moduleImportSequence.includes('support')
const symbolPaletteModuleAvailable =
Settings.moduleImportSequence.includes('symbol-palette')
const trackChangesModuleAvailable =
Settings.moduleImportSequence.includes('track-changes')
/**
* @typedef {Object} Settings
* @property {Object | undefined} apis
* @property {Object | undefined} apis.linkedUrlProxy
* @property {string | undefined} apis.linkedUrlProxy.url
* @property {Object | undefined} apis.references
* @property {string | undefined} apis.references.url
* @property {boolean | undefined} enableGithubSync
* @property {boolean | undefined} enableGitBridge
* @property {boolean | undefined} enableHomepage
* @property {boolean | undefined} enableSaml
* @property {boolean | undefined} ldap
* @property {boolean | undefined} oauth
* @property {Object | undefined} overleaf
* @property {Object | undefined} overleaf.oauth
* @property {boolean | undefined} saml
*/
const Features = {
/**
* @returns {boolean}
*/
externalAuthenticationSystemUsed() {
return (
(Boolean(Settings.ldap) && Boolean(Settings.ldap.enable)) ||
(Boolean(Settings.saml) && Boolean(Settings.saml.enable)) ||
Boolean(Settings.overleaf)
)
},
/**
* Whether a feature is enabled in the appliation's configuration
*
* @param {string} feature
* @returns {boolean}
*/
hasFeature(feature) {
switch (feature) {
case 'saas':
return Boolean(Settings.overleaf)
case 'homepage':
return Boolean(Settings.enableHomepage)
case 'registration-page':
return (
!Features.externalAuthenticationSystemUsed() ||
Boolean(Settings.overleaf)
)
case 'registration':
return Boolean(Settings.overleaf)
case 'github-sync':
return Boolean(Settings.enableGithubSync)
case 'git-bridge':
return Boolean(Settings.enableGitBridge)
case 'oauth':
return Boolean(Settings.oauth)
case 'templates-server-pro':
return Boolean(Settings.templates?.user_id)
case 'affiliations':
case 'analytics':
return Boolean(_.get(Settings, ['apis', 'v1', 'url']))
case 'overleaf-integration':
return Boolean(Settings.overleaf) || Boolean(Settings.enableRegistrationPage)
case 'references':
return Boolean(_.get(Settings, ['apis', 'references', 'url']))
case 'saml':
return Boolean(Settings.enableSaml)
case 'linked-project-file':
return Boolean(Settings.enabledLinkedFileTypes.includes('project_file'))
case 'linked-project-output-file':
return Boolean(
Settings.enabledLinkedFileTypes.includes('project_output_file')
)
case 'link-url':
return Boolean(
_.get(Settings, ['apis', 'linkedUrlProxy', 'url']) &&
Settings.enabledLinkedFileTypes.includes('url')
)
case 'support':
return supportModuleAvailable
case 'symbol-palette':
return symbolPaletteModuleAvailable
case 'track-changes':
return trackChangesModuleAvailable
default:
throw new Error(`unknown feature: ${feature}`)
}
},
}
module.exports = Features

View file

@ -0,0 +1,42 @@
extends ../layout-marketing
block content
main.content.content-alt#main-content
.container
.row
.col-md-6.col-md-offset-3.col-lg-4.col-lg-offset-4
.card
.page-header
h1 #{translate("log_in")}
form(data-ol-async-form, name="loginForm", action='/login', method="POST")
input(name='_csrf', type='hidden', value=csrfToken)
+formMessages()
+customFormMessage('invalid-password-retry-or-reset', 'danger')
| !{translate('email_or_password_wrong_try_again_or_reset', {}, [{ name: 'a', attrs: { href: '/user/password/reset', 'aria-describedby': 'resetPasswordDescription' } }])}
span.sr-only(id='resetPasswordDescription')
| #{translate('reset_password_link')}
+customValidationMessage('password-compromised')
| !{translate('password_compromised_try_again_or_use_known_device_or_reset', {}, [{name: 'a', attrs: {href: 'https://haveibeenpwned.com/passwords', rel: 'noopener noreferrer', target: '_blank'}}, {name: 'a', attrs: {href: '/user/password/reset', target: '_blank'}}])}.
.form-group
input.form-control(
type=(settings.ldap && settings.ldap.enable) ? 'text' : 'email',
name='email',
required,
placeholder=(settings.ldap && settings.ldap.enable) ? settings.ldap.placeholder : 'email@example.com',
autofocus="true"
)
.form-group
input.form-control(
type='password',
name='password',
required,
placeholder='********',
)
.actions
button.btn-primary.btn(
type='submit',
data-ol-disabled-inflight
)
span(data-ol-inflight="idle") #{translate("login")}
span(hidden data-ol-inflight="pending") #{translate("logging_in")}…
a.pull-right(href='/user/password/reset') #{translate("forgot_your_password")}?

View file

@ -0,0 +1,40 @@
extends ../layout-marketing
block entrypointVar
- entrypoint = 'pages/user/settings'
block vars
- bootstrap5PageStatus = 'enabled' // One of 'disabled', 'enabled', and 'queryStringOnly'
- bootstrap5PageSplitTest = 'bootstrap-5'
block append meta
meta(name="ol-hasPassword" data-type="boolean" content=hasPassword)
meta(name="ol-shouldAllowEditingDetails" data-type="boolean" content=shouldAllowEditingDetails || hasPassword)
meta(name="ol-oauthProviders", data-type="json", content=oauthProviders)
meta(name="ol-institutionLinked", data-type="json", content=institutionLinked)
meta(name="ol-samlError", data-type="json", content=samlError)
meta(name="ol-institutionEmailNonCanonical", content=institutionEmailNonCanonical)
meta(name="ol-reconfirmedViaSAML", content=reconfirmedViaSAML)
meta(name="ol-reconfirmationRemoveEmail", content=reconfirmationRemoveEmail)
meta(name="ol-samlBeta", content=samlBeta)
meta(name="ol-ssoErrorMessage", content=ssoErrorMessage)
meta(name="ol-thirdPartyIds", data-type="json", content=thirdPartyIds || {})
meta(name="ol-passwordStrengthOptions", data-type="json", content=settings.passwordStrengthOptions || {})
meta(name="ol-isExternalAuthenticationSystemUsed" data-type="boolean" content=externalAuthenticationSystemUsed() && !hasPassword)
meta(name="ol-user" data-type="json" content=user)
meta(name="ol-dropbox" data-type="json" content=dropbox)
meta(name="ol-github" data-type="json" content=github)
meta(name="ol-projectSyncSuccessMessage", content=projectSyncSuccessMessage)
meta(name="ol-showPersonalAccessToken", data-type="boolean" content=showPersonalAccessToken)
meta(name="ol-optionalPersonalAccessToken", data-type="boolean" content=optionalPersonalAccessToken)
meta(name="ol-personalAccessTokens", data-type="json" content=personalAccessTokens)
meta(name="ol-emailAddressLimit", data-type="json", content=emailAddressLimit)
meta(name="ol-currentManagedUserAdminEmail" data-type="string" content=currentManagedUserAdminEmail)
meta(name="ol-gitBridgeEnabled" data-type="boolean" content=gitBridgeEnabled)
meta(name="ol-isSaas" data-type="boolean" content=isSaas)
meta(name="ol-memberOfSSOEnabledGroups" data-type="json" content=memberOfSSOEnabledGroups)
block content
main.content.content-alt#main-content
#settings-page-root

View file

@ -0,0 +1,533 @@
import { useCallback, useEffect, useRef } from 'react'
import { EditorState } from '@codemirror/state'
import useScopeValue from '../../../shared/hooks/use-scope-value'
import useScopeEventEmitter from '../../../shared/hooks/use-scope-event-emitter'
import useEventListener from '../../../shared/hooks/use-event-listener'
import useScopeEventListener from '../../../shared/hooks/use-scope-event-listener'
import { createExtensions } from '../extensions'
import {
lineHeights,
setEditorTheme,
setOptionsTheme,
} from '../extensions/theme'
import {
restoreCursorPosition,
setCursorLineAndScroll,
setCursorPositionAndScroll,
} from '../extensions/cursor-position'
import {
setAnnotations,
showCompileLogDiagnostics,
} from '../extensions/annotations'
import { useDetachCompileContext as useCompileContext } from '../../../shared/context/detach-compile-context'
import { setCursorHighlights } from '../extensions/cursor-highlights'
import {
setLanguage,
setMetadata,
setSyntaxValidation,
} from '../extensions/language'
import { restoreScrollPosition } from '../extensions/scroll-position'
import { setEditable } from '../extensions/editable'
import { useFileTreeData } from '../../../shared/context/file-tree-data-context'
import { setAutoPair } from '../extensions/auto-pair'
import { setAutoComplete } from '../extensions/auto-complete'
import { usePhrases } from './use-phrases'
import { setPhrases } from '../extensions/phrases'
import {
addLearnedWord,
removeLearnedWord,
resetLearnedWords,
setSpelling,
} from '../extensions/spelling'
import {
createChangeManager,
dispatchEditorEvent,
reviewPanelToggled,
} from '../extensions/changes/change-manager'
import { setKeybindings } from '../extensions/keybindings'
import { Highlight } from '../../../../../types/highlight'
import { EditorView } from '@codemirror/view'
import { useErrorHandler } from 'react-error-boundary'
import { setVisual } from '../extensions/visual/visual'
import { useFileTreePathContext } from '@/features/file-tree/contexts/file-tree-path'
import { useUserSettingsContext } from '@/shared/context/user-settings-context'
import { setDocName } from '@/features/source-editor/extensions/doc-name'
import isValidTexFile from '@/main/is-valid-tex-file'
import { captureException } from '@/infrastructure/error-reporter'
import grammarlyExtensionPresent from '@/shared/utils/grammarly'
import { DocumentContainer } from '@/features/ide-react/editor/document-container'
import { useLayoutContext } from '@/shared/context/layout-context'
import { debugConsole } from '@/utils/debugging'
import { useMetadataContext } from '@/features/ide-react/context/metadata-context'
import { useUserContext } from '@/shared/context/user-context'
function useCodeMirrorScope(view: EditorView) {
const { fileTreeData } = useFileTreeData()
const [permissions] = useScopeValue<{ write: boolean }>('permissions')
// set up scope listeners
const { logEntryAnnotations, editedSinceCompileStarted, compiling } =
useCompileContext()
const { reviewPanelOpen, miniReviewPanelVisible } = useLayoutContext()
const metadata = useMetadataContext()
const [loadingThreads] = useScopeValue<boolean>('loadingThreads')
const [currentDoc] = useScopeValue<DocumentContainer | null>(
'editor.sharejs_doc'
)
const [docName] = useScopeValue<string>('editor.open_doc_name')
const [trackChanges] = useScopeValue<boolean>('editor.trackChanges')
const { id: userId } = useUserContext()
const { userSettings } = useUserSettingsContext()
const {
fontFamily,
fontSize,
lineHeight,
overallTheme,
autoComplete,
editorTheme,
autoPairDelimiters,
mode,
syntaxValidation,
} = userSettings
const [cursorHighlights] = useScopeValue<Record<string, Highlight[]>>(
'onlineUserCursorHighlights'
)
const [spellCheckLanguage] = useScopeValue<string>(
'project.spellCheckLanguage'
)
const [visual] = useScopeValue<boolean>('editor.showVisual')
const [references] = useScopeValue<{ keys: string[] }>('$root._references')
// build the translation phrases
const phrases = usePhrases()
const phrasesRef = useRef(phrases)
// initialise the local state
const themeRef = useRef({
fontFamily,
fontSize,
lineHeight,
overallTheme,
editorTheme,
})
useEffect(() => {
themeRef.current = {
fontFamily,
fontSize,
lineHeight,
overallTheme,
editorTheme,
}
view.dispatch(
setOptionsTheme({
fontFamily,
fontSize,
lineHeight,
overallTheme,
})
)
setEditorTheme(editorTheme).then(spec => {
view.dispatch(spec)
})
}, [view, fontFamily, fontSize, lineHeight, overallTheme, editorTheme])
const settingsRef = useRef({
autoComplete,
autoPairDelimiters,
mode,
syntaxValidation,
})
const currentDocRef = useRef({
currentDoc,
trackChanges,
loadingThreads,
})
useEffect(() => {
if (currentDoc) {
currentDocRef.current.currentDoc = currentDoc
}
}, [view, currentDoc])
const docNameRef = useRef(docName)
useEffect(() => {
currentDocRef.current.loadingThreads = loadingThreads
}, [view, loadingThreads])
useEffect(() => {
currentDocRef.current.trackChanges = trackChanges
if (currentDoc) {
if (trackChanges) {
currentDoc.track_changes_as = userId || 'anonymous-user'
} else {
currentDoc.track_changes_as = null
}
}
}, [userId, currentDoc, trackChanges])
useEffect(() => {
if (lineHeight && fontSize) {
dispatchEditorEvent('line-height', lineHeights[lineHeight] * fontSize)
}
}, [lineHeight, fontSize])
const spellingRef = useRef({
spellCheckLanguage,
})
useEffect(() => {
spellingRef.current = {
spellCheckLanguage,
}
view.dispatch(setSpelling(spellingRef.current))
}, [view, spellCheckLanguage])
// listen to doc:after-opened, and focus the editor
useEffect(() => {
const listener = () => {
scheduleFocus(view)
}
window.addEventListener('doc:after-opened', listener)
return () => window.removeEventListener('doc:after-opened', listener)
}, [view])
// set the project metadata, mostly for use in autocomplete
// TODO: read this data from the scope?
const metadataRef = useRef({
...metadata,
references: references.keys,
fileTreeData,
})
// listen to project metadata (commands, labels and package names) updates
useEffect(() => {
metadataRef.current = { ...metadataRef.current, ...metadata }
view.dispatch(setMetadata(metadataRef.current))
}, [view, metadata])
// listen to project reference keys updates
useEffect(() => {
const listener = (event: Event) => {
metadataRef.current.references = (event as CustomEvent<string[]>).detail
view.dispatch(setMetadata(metadataRef.current))
}
window.addEventListener('project:references', listener)
return () => window.removeEventListener('project:references', listener)
}, [view])
// listen to project root folder updates
useEffect(() => {
if (fileTreeData) {
metadataRef.current.fileTreeData = fileTreeData
view.dispatch(setMetadata(metadataRef.current))
}
}, [view, fileTreeData])
const editableRef = useRef(permissions.write)
const { previewByPath } = useFileTreePathContext()
const showVisual = visual && isValidTexFile(docName)
const visualRef = useRef({
previewByPath,
visual: showVisual,
})
const handleError = useErrorHandler()
const handleException = useCallback((exception: any) => {
captureException(exception, {
tags: {
handler: 'cm6-exception',
// which editor mode is active ('visual' | 'code')
ol_editor_mode: visualRef.current.visual ? 'visual' : 'code',
// which editor keybindings are active ('default' | 'vim' | 'emacs')
ol_editor_keybindings: settingsRef.current.mode,
// whether Writefull is present ('extension' | 'integration' | 'none')
ol_extensions_writefull: window.writefull?.type ?? 'none',
// whether Grammarly is present
ol_extensions_grammarly: grammarlyExtensionPresent(),
},
})
}, [])
// create a new state when currentDoc changes
useEffect(() => {
if (currentDoc) {
debugConsole.log('creating new editor state')
const state = EditorState.create({
doc: currentDoc.getSnapshot(),
extensions: createExtensions({
currentDoc: {
...currentDocRef.current,
currentDoc,
},
docName: docNameRef.current,
theme: themeRef.current,
metadata: metadataRef.current,
settings: settingsRef.current,
phrases: phrasesRef.current,
spelling: spellingRef.current,
visual: visualRef.current,
changeManager: createChangeManager(view, currentDoc),
handleError,
handleException,
}),
})
view.setState(state)
// synchronous config
view.dispatch(
restoreCursorPosition(state.doc, currentDoc.doc_id),
setEditable(editableRef.current),
setOptionsTheme(themeRef.current)
)
// asynchronous config
setEditorTheme(themeRef.current.editorTheme).then(spec => {
view.dispatch(spec)
})
setKeybindings(settingsRef.current.mode).then(spec => {
view.dispatch(spec)
})
if (!visualRef.current.visual) {
window.setTimeout(() => {
view.dispatch(restoreScrollPosition())
view.focus()
})
}
}
// IMPORTANT: This effect must not depend on anything variable apart from currentDoc,
// as the editor state is recreated when the effect runs.
}, [view, currentDoc, handleError, handleException])
useEffect(() => {
if (docName) {
docNameRef.current = docName
view.dispatch(
setDocName(docNameRef.current),
setLanguage(
docNameRef.current,
metadataRef.current,
settingsRef.current.syntaxValidation
)
)
}
}, [view, docName])
useEffect(() => {
visualRef.current.visual = showVisual
view.dispatch(setVisual(visualRef.current))
view.dispatch({
effects: EditorView.scrollIntoView(view.state.selection.main.head),
})
// clear performance measures and marks when switching between Source and Rich Text
window.dispatchEvent(new Event('editor:visual-switch'))
}, [view, showVisual])
useEffect(() => {
visualRef.current.previewByPath = previewByPath
view.dispatch(setVisual(visualRef.current))
}, [view, previewByPath])
useEffect(() => {
editableRef.current = permissions.write
view.dispatch(setEditable(editableRef.current)) // the editor needs to be locked when there's a problem saving data
}, [view, permissions.write])
useEffect(() => {
phrasesRef.current = phrases
view.dispatch(setPhrases(phrases))
}, [view, phrases])
// listen to editor settings updates
useEffect(() => {
settingsRef.current.autoPairDelimiters = autoPairDelimiters
view.dispatch(setAutoPair(autoPairDelimiters))
}, [view, autoPairDelimiters])
useEffect(() => {
settingsRef.current.autoComplete = autoComplete
view.dispatch(setAutoComplete(autoComplete))
}, [view, autoComplete])
useEffect(() => {
settingsRef.current.mode = mode
setKeybindings(mode).then(spec => {
view.dispatch(spec)
})
}, [view, mode])
useEffect(() => {
settingsRef.current.syntaxValidation = syntaxValidation
view.dispatch(setSyntaxValidation(syntaxValidation))
}, [view, syntaxValidation])
const emitSyncToPdf = useScopeEventEmitter('cursor:editor:syncToPdf')
const handleGoToLine = useCallback(
(event, lineNumber, columnNumber, syncToPdf) => {
setCursorLineAndScroll(view, lineNumber, columnNumber)
if (syncToPdf) {
emitSyncToPdf()
}
},
[emitSyncToPdf, view]
)
// select and scroll to position on editor:gotoLine event (from synctex)
useScopeEventListener('editor:gotoLine', handleGoToLine)
const handleGoToOffset = useCallback(
(event, offset) => {
setCursorPositionAndScroll(view, offset)
},
[view]
)
// select and scroll to position on editor:gotoOffset event (from review panel)
useScopeEventListener('editor:gotoOffset', handleGoToOffset)
// dispatch 'cursor:editor:update' to Angular scope (for synctex and realtime)
const dispatchCursorUpdate = useScopeEventEmitter('cursor:editor:update')
const handleCursorUpdate = useCallback(
(event: CustomEvent) => {
dispatchCursorUpdate(event.detail)
},
[dispatchCursorUpdate]
)
// listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
useEventListener('cursor:editor:update', handleCursorUpdate)
// dispatch 'cursor:editor:update' to Angular scope (for outline)
const dispatchScrollUpdate = useScopeEventEmitter('scroll:editor:update')
const handleScrollUpdate = useCallback(
(event: CustomEvent) => {
dispatchScrollUpdate(event.detail)
},
[dispatchScrollUpdate]
)
// listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
useEventListener('scroll:editor:update', handleScrollUpdate)
// enable the compile log linter a) when "Code Check" is off, b) when the project hasn't changed and isn't compiling.
// the project "changed at" date is reset at the start of the compile, i.e. "the project hasn't changed",
// but we don't want to display the compile log diagnostics from the previous compile.
const enableCompileLogLinter =
!syntaxValidation || (!editedSinceCompileStarted && !compiling)
// store enableCompileLogLinter in a ref for use in useEffect
const enableCompileLogLinterRef = useRef(enableCompileLogLinter)
useEffect(() => {
enableCompileLogLinterRef.current = enableCompileLogLinter
}, [enableCompileLogLinter])
// enable/disable the compile log linter as appropriate
useEffect(() => {
// dispatch in a timeout, so the dispatch isn't in the same cycle as the edit which caused it
window.setTimeout(() => {
view.dispatch(showCompileLogDiagnostics(enableCompileLogLinter))
}, 0)
}, [view, enableCompileLogLinter])
// set the compile log annotations when they change
useEffect(() => {
if (currentDoc && logEntryAnnotations) {
const annotations = logEntryAnnotations[currentDoc.doc_id]
// dispatch in a timeout, so the dispatch isn't in the same cycle as the edit which caused it
window.setTimeout(() => {
view.dispatch(
setAnnotations(view.state.doc, annotations || []),
// reconfigure the compile log lint source, so it runs once with the new data
showCompileLogDiagnostics(enableCompileLogLinterRef.current)
)
})
}
}, [view, currentDoc, logEntryAnnotations])
const highlightsRef = useRef<{ cursorHighlights: Highlight[] }>({
cursorHighlights: [],
})
useEffect(() => {
if (cursorHighlights && currentDoc) {
const items = cursorHighlights[currentDoc.doc_id]
highlightsRef.current.cursorHighlights = items
window.setTimeout(() => {
view.dispatch(setCursorHighlights(items))
})
}
}, [view, cursorHighlights, currentDoc])
const handleAddLearnedWords = useCallback(
(event: CustomEvent<string>) => {
// If the word addition is from adding the word to the dictionary via the
// editor, there will be a transaction running now so wait for that to
// finish before starting a new one
window.setTimeout(() => {
view.dispatch(addLearnedWord(spellCheckLanguage, event.detail))
}, 0)
},
[spellCheckLanguage, view]
)
useEventListener('learnedWords:add', handleAddLearnedWords)
const handleRemoveLearnedWords = useCallback(
(event: CustomEvent<string>) => {
view.dispatch(removeLearnedWord(spellCheckLanguage, event.detail))
},
[spellCheckLanguage, view]
)
useEventListener('learnedWords:remove', handleRemoveLearnedWords)
const handleResetLearnedWords = useCallback(() => {
view.dispatch(resetLearnedWords())
}, [view])
useEventListener('learnedWords:reset', handleResetLearnedWords)
useEffect(() => {
view.dispatch(reviewPanelToggled())
}, [reviewPanelOpen, miniReviewPanelVisible, view])
}
export default useCodeMirrorScope
const scheduleFocus = (view: EditorView) => {
window.setTimeout(() => {
view.focus()
}, 0)
}

View file

@ -0,0 +1,27 @@
const { initLdapAuthentication } = require('./app/src/InitLdapAuthentication')
const { fetchLdapContacts } = require('./app/src/LdapContacts')
const { addLdapStrategy } = require('./app/src/LdapStrategy')
initLdapAuthentication()
module.exports = {
name: 'ldap-authentication',
hooks: {
passportSetup: function (passport, callback) {
try {
addLdapStrategy(passport)
callback(null)
} catch (error) {
callback(error)
}
},
getContacts: async function (userId, contacts, callback) {
try {
const newLdapContacts = await fetchLdapContacts(userId, contacts)
callback(null, newLdapContacts)
} catch (error) {
callback(error)
}
},
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,240 @@
const OError = require('@overleaf/o-error')
const { expressify } = require('@overleaf/promise-utils')
const Settings = require('@overleaf/settings')
const Path = require('path')
const logger = require('@overleaf/logger')
const UserRegistrationHandler = require('../../../../app/src/Features/User/UserRegistrationHandler')
const EmailHandler = require('../../../../app/src/Features/Email/EmailHandler')
const UserGetter = require('../../../../app/src/Features/User/UserGetter')
const { User } = require('../../../../app/src/models/User')
const AuthenticationManager = require('../../../../app/src/Features/Authentication/AuthenticationManager')
const AuthenticationController = require('../../../../app/src/Features/Authentication/AuthenticationController')
const SessionManager = require('../../../../app/src/Features/Authentication/SessionManager')
const {
hasAdminAccess,
} = require('../../../../app/src/Features/Helpers/AdminAuthorizationHelper')
const _LaunchpadController = {
_getAuthMethod() {
if (Settings.ldap?.enable) {
return 'ldap'
} else if (Settings.saml) {
return 'saml'
} else {
return 'local'
}
},
async launchpadPage(req, res) {
// TODO: check if we're using external auth?
// * how does all this work with ldap and saml?
const sessionUser = SessionManager.getSessionUser(req.session)
const authMethod = LaunchpadController._getAuthMethod()
const adminUserExists = await LaunchpadController._atLeastOneAdminExists()
if (!sessionUser) {
if (!adminUserExists) {
res.render(Path.resolve(__dirname, '../views/launchpad'), {
adminUserExists,
authMethod,
})
} else {
AuthenticationController.setRedirectInSession(req)
res.redirect('/login')
}
} else {
const user = await UserGetter.promises.getUser(sessionUser._id, {
isAdmin: 1,
})
if (hasAdminAccess(user)) {
res.render(Path.resolve(__dirname, '../views/launchpad'), {
wsUrl: Settings.wsUrl,
adminUserExists,
authMethod,
})
} else {
res.redirect('/restricted')
}
}
},
async _atLeastOneAdminExists() {
const user = await UserGetter.promises.getUser(
{ isAdmin: true },
{ _id: 1, isAdmin: 1 }
)
return Boolean(user)
},
async sendTestEmail(req, res) {
const { email } = req.body
if (!email) {
logger.debug({}, 'no email address supplied')
return res.status(400).json({
message: 'no email address supplied',
})
}
logger.debug({ email }, 'sending test email')
const emailOptions = { to: email }
try {
await EmailHandler.promises.sendEmail('testEmail', emailOptions)
logger.debug({ email }, 'sent test email')
res.json({ message: res.locals.translate('email_sent') })
} catch (err) {
OError.tag(err, 'error sending test email', {
email,
})
throw err
}
},
registerExternalAuthAdmin(authMethod) {
return expressify(async function (req, res) {
if (LaunchpadController._getAuthMethod() !== authMethod) {
logger.debug(
{ authMethod },
'trying to register external admin, but that auth service is not enabled, disallow'
)
return res.sendStatus(403)
}
const email = req.body.email.toLowerCase()
if (!email) {
logger.debug({ authMethod }, 'no email supplied, disallow')
return res.sendStatus(400)
}
logger.debug({ email }, 'attempted register first admin user')
const exists = await LaunchpadController._atLeastOneAdminExists()
if (exists) {
logger.debug(
{ email },
'already have at least one admin user, disallow'
)
return res.sendStatus(403)
}
const body = {
email,
password: 'password_here',
first_name: email,
last_name: '',
}
logger.debug(
{ body, authMethod },
'creating admin account for specified external-auth user'
)
let user
try {
user = await UserRegistrationHandler.promises.registerNewUser(body)
} catch (err) {
OError.tag(err, 'error with registerNewUser', {
email,
authMethod,
})
throw err
}
try {
await User.updateOne(
{ _id: user._id },
{
$set: { isAdmin: true, emails: [{ email, reversedHostname, 'confirmedAt' : Date.now() }] }, // no email confirmation is required
$unset: { 'hashedPassword': "" }, // external-auth user must not have a hashedPassword
emails: [{ email }],
}
).exec()
} catch (err) {
OError.tag(err, 'error setting user to admin', {
user_id: user._id,
})
throw err
}
AuthenticationController.setRedirectInSession(req, '/launchpad')
logger.debug(
{ email, userId: user._id, authMethod },
'created first admin account'
)
res.json({ redir: '/launchpad', email })
})
},
async registerAdmin(req, res) {
const { email } = req.body
const { password } = req.body
if (!email || !password) {
logger.debug({}, 'must supply both email and password, disallow')
return res.sendStatus(400)
}
logger.debug({ email }, 'attempted register first admin user')
const exists = await LaunchpadController._atLeastOneAdminExists()
if (exists) {
logger.debug(
{ email: req.body.email },
'already have at least one admin user, disallow'
)
return res.status(403).json({
message: { type: 'error', text: 'admin user already exists' },
})
}
const invalidEmail = AuthenticationManager.validateEmail(email)
if (invalidEmail) {
return res
.status(400)
.json({ message: { type: 'error', text: invalidEmail.message } })
}
const invalidPassword = AuthenticationManager.validatePassword(
password,
email
)
if (invalidPassword) {
return res
.status(400)
.json({ message: { type: 'error', text: invalidPassword.message } })
}
const body = { email, password }
const user = await UserRegistrationHandler.promises.registerNewUser(body)
logger.debug({ userId: user._id }, 'making user an admin')
try {
await User.updateOne(
{ _id: user._id },
{
$set: {
isAdmin: true,
emails: [{ email }],
},
}
).exec()
} catch (err) {
OError.tag(err, 'error setting user to admin', {
user_id: user._id,
})
throw err
}
logger.debug({ email, userId: user._id }, 'created first admin account')
res.json({ redir: '/launchpad' })
},
}
const LaunchpadController = {
launchpadPage: expressify(_LaunchpadController.launchpadPage),
registerAdmin: expressify(_LaunchpadController.registerAdmin),
registerExternalAuthAdmin: _LaunchpadController.registerExternalAuthAdmin,
sendTestEmail: expressify(_LaunchpadController.sendTestEmail),
_atLeastOneAdminExists: _LaunchpadController._atLeastOneAdminExists,
_getAuthMethod: _LaunchpadController._getAuthMethod,
}
module.exports = LaunchpadController

View file

@ -0,0 +1,264 @@
extends ../../../../app/views/layout-marketing
mixin launchpad-check(section)
div(data-ol-launchpad-check=section)
span(data-ol-inflight="pending")
i.fa.fa-fw.fa-spinner.fa-spin
span &nbsp;#{translate('checking')}
span(hidden data-ol-inflight="idle")
div(data-ol-result="success")
i.fa.fa-check
span &nbsp;#{translate('ok')}
button.btn.btn-inline-link
span.text-danger &nbsp;#{translate('retry')}
div(hidden data-ol-result="error")
i.fa.fa-exclamation
span &nbsp;#{translate('error')}
button.btn.btn-inline-link
span.text-danger &nbsp;#{translate('retry')}
div.alert.alert-danger
span(data-ol-error)
block entrypointVar
- entrypoint = 'modules/launchpad/pages/launchpad'
block vars
- metadata = metadata || {}
block append meta
meta(name="ol-adminUserExists" data-type="boolean" content=adminUserExists)
meta(name="ol-ideJsPath" content=buildJsPath('ide-detached.js'))
block content
script(type="text/javascript", nonce=scriptNonce, src=(wsUrl || '/socket.io') + '/socket.io.js')
.content.content-alt#main-content
.container
.row
.col-md-8.col-md-offset-2
.card.launchpad-body
.row
.col-md-12
.text-center
h1 #{translate('welcome_to_sl')}
p
img(src=buildImgPath('/ol-brand/overleaf-o.svg'))
<!-- wrapper -->
.row
.col-md-8.col-md-offset-2
<!-- create first admin form -->
if !adminUserExists
.row(data-ol-not-sent)
.col-md-12
h2 #{translate('create_first_admin_account')}
// Local Auth Form
if authMethod === 'local'
form(
data-ol-async-form
data-ol-register-admin
action="/launchpad/register_admin"
method="POST"
)
input(name='_csrf', type='hidden', value=csrfToken)
+formMessages()
.form-group
label(for='email') #{translate("email")}
input.form-control(
type='email',
name='email',
placeholder="email@example.com"
autocomplete="username"
required,
autofocus="true"
)
.form-group
label(for='password') #{translate("password")}
input.form-control#passwordField(
type='password',
name='password',
placeholder="********",
autocomplete="new-password"
required,
)
.actions
button.btn-primary.btn(
type='submit'
data-ol-disabled-inflight
)
span(data-ol-inflight="idle") #{translate("register")}
span(hidden data-ol-inflight="pending") #{translate("registering")}…
// Ldap Form
if authMethod === 'ldap'
h3 #{translate('ldap')}
p
| #{translate('ldap_create_admin_instructions')}
form(
data-ol-async-form
data-ol-register-admin
action="/launchpad/register_ldap_admin"
method="POST"
)
input(name='_csrf', type='hidden', value=csrfToken)
+formMessages()
.form-group
label(for='email') #{translate("email")}
input.form-control(
type='email',
name='email',
placeholder="email@example.com"
autocomplete="username"
required,
autofocus="true"
)
.actions
button.btn-primary.btn(
type='submit'
data-ol-disabled-inflight
)
span(data-ol-inflight="idle") #{translate("register")}
span(hidden data-ol-inflight="pending") #{translate("registering")}…
h3 #{translate('local_account')}
p
| #{translate('alternatively_create_local_admin_account')}
form(
data-ol-async-form
data-ol-register-admin
action="/launchpad/register_admin"
method="POST"
)
input(name='_csrf', type='hidden', value=csrfToken)
+formMessages()
.form-group
label(for='email') #{translate("email")}
input.form-control(
type='email',
name='email',
placeholder="email@example.com"
autocomplete="username"
required,
autofocus="true"
)
.form-group
label(for='password') #{translate("password")}
input.form-control#passwordField(
type='password',
name='password',
placeholder="********",
autocomplete="new-password"
required,
)
.actions
button.btn-primary.btn(
type='submit'
data-ol-disabled-inflight
)
span(data-ol-inflight="idle") #{translate("register")}
span(hidden data-ol-inflight="pending") #{translate("registering")}…
// Saml Form
if authMethod === 'saml'
h3 #{translate('saml')}
p
| #{translate('saml_create_admin_instructions')}
form(
data-ol-async-form
data-ol-register-admin
action="/launchpad/register_saml_admin"
method="POST"
)
input(name='_csrf', type='hidden', value=csrfToken)
+formMessages()
.form-group
label(for='email') #{translate("email")}
input.form-control(
type='email',
name='email',
placeholder="email@example.com"
autocomplete="username"
required,
autofocus="true"
)
.actions
button.btn-primary.btn(
type='submit'
data-ol-disabled-inflight
)
span(data-ol-inflight="idle") #{translate("register")}
span(hidden data-ol-inflight="pending") #{translate("registering")}…
br
<!-- status indicators -->
if adminUserExists
.row
.col-md-12.status-indicators
h2 #{translate('status_checks')}
<!-- websocket -->
.row.row-spaced-small
.col-sm-5
| #{translate('websockets')}
.col-sm-7
+launchpad-check('websocket')
<!-- break -->
hr.thin
<!-- other actions -->
.row
.col-md-12
h2 #{translate('other_actions')}
h3 #{translate('send_test_email')}
form.form(
data-ol-async-form
action="/launchpad/send_test_email"
method="POST"
)
.form-group
label(for="email") Email
input.form-control(
type="text"
id="email"
name="email"
required
)
button.btn-primary.btn(
type='submit'
data-ol-disabled-inflight
)
span(data-ol-inflight="idle") #{translate("send")}
span(hidden data-ol-inflight="pending") #{translate("sending")}…
p
+formMessages()
<!-- break -->
hr.thin
<!-- Go to app -->
.row
.col-md-12
.text-center
br
p
a(href="/admin").btn.btn-info
| Go To Admin Panel
p
a(href="/project").btn.btn-primary
| Start Using #{settings.appName}
br

View file

@ -0,0 +1,64 @@
diff --git a/node_modules/ldapauth-fork/lib/ldapauth.js b/node_modules/ldapauth-fork/lib/ldapauth.js
index 85ecf36a8b..a7d07e0f78 100644
--- a/node_modules/ldapauth-fork/lib/ldapauth.js
+++ b/node_modules/ldapauth-fork/lib/ldapauth.js
@@ -69,6 +69,7 @@ function LdapAuth(opts) {
this.opts.bindProperty || (this.opts.bindProperty = 'dn');
this.opts.groupSearchScope || (this.opts.groupSearchScope = 'sub');
this.opts.groupDnProperty || (this.opts.groupDnProperty = 'dn');
+ this.opts.tlsStarted = false;
EventEmitter.call(this);
@@ -108,21 +109,7 @@ function LdapAuth(opts) {
this._userClient.on('error', this._handleError.bind(this));
var self = this;
- if (this.opts.starttls) {
- // When starttls is enabled, this callback supplants the 'connect' callback
- this._adminClient.starttls(this.opts.tlsOptions, this._adminClient.controls, function(err) {
- if (err) {
- self._handleError(err);
- } else {
- self._onConnectAdmin();
- }
- });
- this._userClient.starttls(this.opts.tlsOptions, this._userClient.controls, function(err) {
- if (err) {
- self._handleError(err);
- }
- });
- } else if (opts.reconnect) {
+ if (opts.reconnect && !this.opts.starttls) {
this.once('_installReconnectListener', function() {
self.log && self.log.trace('install reconnect listener');
self._adminClient.on('connect', function() {
@@ -384,6 +371,28 @@ LdapAuth.prototype._findGroups = function(user, callback) {
*/
LdapAuth.prototype.authenticate = function(username, password, callback) {
var self = this;
+ if (this.opts.starttls && !this.opts.tlsStarted) {
+ // When starttls is enabled, this callback supplants the 'connect' callback
+ this._adminClient.starttls(this.opts.tlsOptions, this._adminClient.controls, function (err) {
+ if (err) {
+ self._handleError(err);
+ } else {
+ self._onConnectAdmin(function(){self._handleAuthenticate(username, password, callback);});
+ }
+ });
+ this._userClient.starttls(this.opts.tlsOptions, this._userClient.controls, function (err) {
+ if (err) {
+ self._handleError(err);
+ }
+ });
+ } else {
+ self._handleAuthenticate(username, password, callback);
+ }
+};
+
+LdapAuth.prototype._handleAuthenticate = function (username, password, callback) {
+ this.opts.tlsStarted = true;
+ var self = this;
if (typeof password === 'undefined' || password === null || password === '') {
return callback(new Error('no password given'));

View file

@ -0,0 +1,938 @@
const Path = require('path')
const { merge } = require('@overleaf/settings/merge')
let defaultFeatures, siteUrl
// Make time interval config easier.
const seconds = 1000
const minutes = 60 * seconds
// These credentials are used for authenticating api requests
// between services that may need to go over public channels
const httpAuthUser = process.env.WEB_API_USER
const httpAuthPass = process.env.WEB_API_PASSWORD
const httpAuthUsers = {}
if (httpAuthUser && httpAuthPass) {
httpAuthUsers[httpAuthUser] = httpAuthPass
}
const intFromEnv = function (name, defaultValue) {
if (
[null, undefined].includes(defaultValue) ||
typeof defaultValue !== 'number'
) {
throw new Error(
`Bad default integer value for setting: ${name}, ${defaultValue}`
)
}
return parseInt(process.env[name], 10) || defaultValue
}
const defaultTextExtensions = [
'tex',
'latex',
'sty',
'cls',
'bst',
'bib',
'bibtex',
'txt',
'tikz',
'mtx',
'rtex',
'md',
'asy',
'lbx',
'bbx',
'cbx',
'm',
'lco',
'dtx',
'ins',
'ist',
'def',
'clo',
'ldf',
'rmd',
'lua',
'gv',
'mf',
'yml',
'yaml',
'lhs',
'mk',
'xmpdata',
'cfg',
'rnw',
'ltx',
'inc',
]
const parseTextExtensions = function (extensions) {
if (extensions) {
return extensions.split(',').map(ext => ext.trim())
} else {
return []
}
}
const httpPermissionsPolicy = {
blocked: [
'accelerometer',
'attribution-reporting',
'browsing-topics',
'camera',
'display-capture',
'encrypted-media',
'gamepad',
'geolocation',
'gyroscope',
'hid',
'identity-credentials-get',
'idle-detection',
'local-fonts',
'magnetometer',
'microphone',
'midi',
'otp-credentials',
'payment',
'picture-in-picture',
'screen-wake-lock',
'serial',
'storage-access',
'usb',
'window-management',
'xr-spatial-tracking',
],
allowed: {
autoplay: 'self "https://videos.ctfassets.net"',
fullscreen: 'self',
},
}
module.exports = {
env: 'server-ce',
limits: {
httpGlobalAgentMaxSockets: 300,
httpsGlobalAgentMaxSockets: 300,
},
allowAnonymousReadAndWriteSharing:
process.env.OVERLEAF_ALLOW_ANONYMOUS_READ_AND_WRITE_SHARING === 'true',
// Databases
// ---------
mongo: {
options: {
appname: 'web',
maxPoolSize: parseInt(process.env.MONGO_POOL_SIZE, 10) || 100,
serverSelectionTimeoutMS:
parseInt(process.env.MONGO_SERVER_SELECTION_TIMEOUT, 10) || 60000,
// Setting socketTimeoutMS to 0 means no timeout
socketTimeoutMS: parseInt(
process.env.MONGO_SOCKET_TIMEOUT ?? '60000',
10
),
monitorCommands: true,
},
url:
process.env.MONGO_CONNECTION_STRING ||
process.env.MONGO_URL ||
`mongodb://${process.env.MONGO_HOST || '127.0.0.1'}/sharelatex`,
hasSecondaries: process.env.MONGO_HAS_SECONDARIES === 'true',
},
redis: {
web: {
host: process.env.REDIS_HOST || '127.0.0.1',
port: process.env.REDIS_PORT || '6379',
password: process.env.REDIS_PASSWORD || '',
db: process.env.REDIS_DB,
maxRetriesPerRequest: parseInt(
process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20'
),
},
// websessions:
// cluster: [
// {host: '127.0.0.1', port: 7000}
// {host: '127.0.0.1', port: 7001}
// {host: '127.0.0.1', port: 7002}
// {host: '127.0.0.1', port: 7003}
// {host: '127.0.0.1', port: 7004}
// {host: '127.0.0.1', port: 7005}
// ]
// ratelimiter:
// cluster: [
// {host: '127.0.0.1', port: 7000}
// {host: '127.0.0.1', port: 7001}
// {host: '127.0.0.1', port: 7002}
// {host: '127.0.0.1', port: 7003}
// {host: '127.0.0.1', port: 7004}
// {host: '127.0.0.1', port: 7005}
// ]
// cooldown:
// cluster: [
// {host: '127.0.0.1', port: 7000}
// {host: '127.0.0.1', port: 7001}
// {host: '127.0.0.1', port: 7002}
// {host: '127.0.0.1', port: 7003}
// {host: '127.0.0.1', port: 7004}
// {host: '127.0.0.1', port: 7005}
// ]
api: {
host: process.env.REDIS_HOST || '127.0.0.1',
port: process.env.REDIS_PORT || '6379',
password: process.env.REDIS_PASSWORD || '',
maxRetriesPerRequest: parseInt(
process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20'
),
},
},
// Service locations
// -----------------
// Configure which ports to run each service on. Generally you
// can leave these as they are unless you have some other services
// running which conflict, or want to run the web process on port 80.
internal: {
web: {
port: process.env.WEB_PORT || 3000,
host: process.env.LISTEN_ADDRESS || '127.0.0.1',
},
},
// Tell each service where to find the other services. If everything
// is running locally then this is easy, but they exist as separate config
// options incase you want to run some services on remote hosts.
apis: {
web: {
url: `http://${
process.env.WEB_API_HOST || process.env.WEB_HOST || '127.0.0.1'
}:${process.env.WEB_API_PORT || process.env.WEB_PORT || 3000}`,
user: httpAuthUser,
pass: httpAuthPass,
},
documentupdater: {
url: `http://${
process.env.DOCUPDATER_HOST ||
process.env.DOCUMENT_UPDATER_HOST ||
'127.0.0.1'
}:3003`,
},
spelling: {
url: `http://${process.env.SPELLING_HOST || '127.0.0.1'}:3005`,
host: process.env.SPELLING_HOST,
},
docstore: {
url: `http://${process.env.DOCSTORE_HOST || '127.0.0.1'}:3016`,
pubUrl: `http://${process.env.DOCSTORE_HOST || '127.0.0.1'}:3016`,
},
chat: {
internal_url: `http://${process.env.CHAT_HOST || '127.0.0.1'}:3010`,
},
filestore: {
url: `http://${process.env.FILESTORE_HOST || '127.0.0.1'}:3009`,
},
clsi: {
url: `http://${process.env.CLSI_HOST || '127.0.0.1'}:3013`,
// url: "http://#{process.env['CLSI_LB_HOST']}:3014"
backendGroupName: undefined,
submissionBackendClass:
process.env.CLSI_SUBMISSION_BACKEND_CLASS || 'n2d',
},
project_history: {
sendProjectStructureOps: true,
url: `http://${process.env.PROJECT_HISTORY_HOST || '127.0.0.1'}:3054`,
},
realTime: {
url: `http://${process.env.REALTIME_HOST || '127.0.0.1'}:3026`,
},
contacts: {
url: `http://${process.env.CONTACTS_HOST || '127.0.0.1'}:3036`,
},
notifications: {
url: `http://${process.env.NOTIFICATIONS_HOST || '127.0.0.1'}:3042`,
},
webpack: {
url: `http://${process.env.WEBPACK_HOST || '127.0.0.1'}:3808`,
},
wiki: {
url: process.env.WIKI_URL || 'https://learn.sharelatex.com',
maxCacheAge: parseInt(process.env.WIKI_MAX_CACHE_AGE || 5 * minutes, 10),
},
haveIBeenPwned: {
enabled: process.env.HAVE_I_BEEN_PWNED_ENABLED === 'true',
url:
process.env.HAVE_I_BEEN_PWNED_URL || 'https://api.pwnedpasswords.com',
timeout: parseInt(process.env.HAVE_I_BEEN_PWNED_TIMEOUT, 10) || 5 * 1000,
},
// For legacy reasons, we need to populate the below objects.
v1: {},
recurly: {},
},
// Defines which features are allowed in the
// Permissions-Policy HTTP header
httpPermissions: httpPermissionsPolicy,
useHttpPermissionsPolicy: true,
jwt: {
key: process.env.OT_JWT_AUTH_KEY,
algorithm: process.env.OT_JWT_AUTH_ALG || 'HS256',
},
devToolbar: {
enabled: false,
},
splitTests: [],
// Where your instance of Overleaf Community Edition/Server Pro can be found publicly. Used in emails
// that are sent out, generated links, etc.
siteUrl: (siteUrl = process.env.PUBLIC_URL || 'http://127.0.0.1:3000'),
lockManager: {
lockTestInterval: intFromEnv('LOCK_MANAGER_LOCK_TEST_INTERVAL', 50),
maxTestInterval: intFromEnv('LOCK_MANAGER_MAX_TEST_INTERVAL', 1000),
maxLockWaitTime: intFromEnv('LOCK_MANAGER_MAX_LOCK_WAIT_TIME', 10000),
redisLockExpiry: intFromEnv('LOCK_MANAGER_REDIS_LOCK_EXPIRY', 30),
slowExecutionThreshold: intFromEnv(
'LOCK_MANAGER_SLOW_EXECUTION_THRESHOLD',
5000
),
},
// Optional separate location for websocket connections, if unset defaults to siteUrl.
wsUrl: process.env.WEBSOCKET_URL,
wsUrlV2: process.env.WEBSOCKET_URL_V2,
wsUrlBeta: process.env.WEBSOCKET_URL_BETA,
wsUrlV2Percentage: parseInt(
process.env.WEBSOCKET_URL_V2_PERCENTAGE || '0',
10
),
wsRetryHandshake: parseInt(process.env.WEBSOCKET_RETRY_HANDSHAKE || '5', 10),
// cookie domain
// use full domain for cookies to only be accessible from that domain,
// replace subdomain with dot to have them accessible on all subdomains
cookieDomain: process.env.COOKIE_DOMAIN,
cookieName: process.env.COOKIE_NAME || 'overleaf.sid',
cookieRollingSession: true,
// this is only used if cookies are used for clsi backend
// clsiCookieKey: "clsiserver"
robotsNoindex: process.env.ROBOTS_NOINDEX === 'true' || false,
maxEntitiesPerProject: parseInt(
process.env.MAX_ENTITIES_PER_PROJECT || '2000',
10
),
projectUploadTimeout: parseInt(
process.env.PROJECT_UPLOAD_TIMEOUT || '120000',
10
),
maxUploadSize: 50 * 1024 * 1024, // 50 MB
multerOptions: {
preservePath: process.env.MULTER_PRESERVE_PATH,
},
// start failing the health check if active handles exceeds this limit
maxActiveHandles: process.env.MAX_ACTIVE_HANDLES
? parseInt(process.env.MAX_ACTIVE_HANDLES, 10)
: undefined,
// Security
// --------
security: {
sessionSecret: process.env.SESSION_SECRET,
sessionSecretUpcoming: process.env.SESSION_SECRET_UPCOMING,
sessionSecretFallback: process.env.SESSION_SECRET_FALLBACK,
bcryptRounds: parseInt(process.env.BCRYPT_ROUNDS, 10) || 12,
}, // number of rounds used to hash user passwords (raised to power 2)
adminUrl: process.env.ADMIN_URL,
adminOnlyLogin: process.env.ADMIN_ONLY_LOGIN === 'true',
adminPrivilegeAvailable: process.env.ADMIN_PRIVILEGE_AVAILABLE === 'true',
blockCrossOriginRequests: process.env.BLOCK_CROSS_ORIGIN_REQUESTS === 'true',
allowedOrigins: (process.env.ALLOWED_ORIGINS || siteUrl).split(','),
httpAuthUsers,
// Default features
// ----------------
//
// You can select the features that are enabled by default for new
// new users.
defaultFeatures: (defaultFeatures = {
collaborators: -1,
dropbox: true,
github: true,
gitBridge: true,
versioning: true,
compileTimeout: 180,
compileGroup: 'standard',
references: true,
trackChanges: true,
}),
// featuresEpoch: 'YYYY-MM-DD',
features: {
personal: defaultFeatures,
},
groupPlanModalOptions: {
plan_codes: [],
currencies: [],
sizes: [],
usages: [],
},
plans: [
{
planCode: 'personal',
name: 'Personal',
price_in_cents: 0,
features: defaultFeatures,
},
],
enableSubscriptions: false,
restrictedCountries: [],
enableOnboardingEmails: process.env.ENABLE_ONBOARDING_EMAILS === 'true',
enabledLinkedFileTypes: (process.env.ENABLED_LINKED_FILE_TYPES || '').split(
','
),
// i18n
// ------
//
i18n: {
checkForHTMLInVars: process.env.I18N_CHECK_FOR_HTML_IN_VARS === 'true',
escapeHTMLInVars: process.env.I18N_ESCAPE_HTML_IN_VARS === 'true',
subdomainLang: {
www: { lngCode: 'en', url: siteUrl },
},
defaultLng: 'en',
},
// Spelling languages
// ------------------
//
// You must have the corresponding aspell package installed to
// be able to use a language.
languages: [
{ code: 'en', name: 'English' },
{ code: 'en_US', name: 'English (American)' },
{ code: 'en_GB', name: 'English (British)' },
{ code: 'en_CA', name: 'English (Canadian)' },
{ code: 'af', name: 'Afrikaans' },
{ code: 'ar', name: 'Arabic' },
{ code: 'gl', name: 'Galician' },
{ code: 'eu', name: 'Basque' },
{ code: 'br', name: 'Breton' },
{ code: 'bg', name: 'Bulgarian' },
{ code: 'ca', name: 'Catalan' },
{ code: 'hr', name: 'Croatian' },
{ code: 'cs', name: 'Czech' },
{ code: 'da', name: 'Danish' },
{ code: 'nl', name: 'Dutch' },
{ code: 'eo', name: 'Esperanto' },
{ code: 'et', name: 'Estonian' },
{ code: 'fo', name: 'Faroese' },
{ code: 'fr', name: 'French' },
{ code: 'de', name: 'German' },
{ code: 'el', name: 'Greek' },
{ code: 'id', name: 'Indonesian' },
{ code: 'ga', name: 'Irish' },
{ code: 'it', name: 'Italian' },
{ code: 'kk', name: 'Kazakh' },
{ code: 'ku', name: 'Kurdish' },
{ code: 'lv', name: 'Latvian' },
{ code: 'lt', name: 'Lithuanian' },
{ code: 'nr', name: 'Ndebele' },
{ code: 'ns', name: 'Northern Sotho' },
{ code: 'no', name: 'Norwegian' },
{ code: 'fa', name: 'Persian' },
{ code: 'pl', name: 'Polish' },
{ code: 'pt_BR', name: 'Portuguese (Brazilian)' },
{ code: 'pt_PT', name: 'Portuguese (European)' },
{ code: 'pa', name: 'Punjabi' },
{ code: 'ro', name: 'Romanian' },
{ code: 'ru', name: 'Russian' },
{ code: 'sk', name: 'Slovak' },
{ code: 'sl', name: 'Slovenian' },
{ code: 'st', name: 'Southern Sotho' },
{ code: 'es', name: 'Spanish' },
{ code: 'sv', name: 'Swedish' },
{ code: 'tl', name: 'Tagalog' },
{ code: 'ts', name: 'Tsonga' },
{ code: 'tn', name: 'Tswana' },
{ code: 'hsb', name: 'Upper Sorbian' },
{ code: 'cy', name: 'Welsh' },
{ code: 'xh', name: 'Xhosa' },
],
translatedLanguages: {
cn: '简体中文',
cs: 'Čeština',
da: 'Dansk',
de: 'Deutsch',
en: 'English',
es: 'Español',
fi: 'Suomi',
fr: 'Français',
it: 'Italiano',
ja: '日本語',
ko: '한국어',
nl: 'Nederlands',
no: 'Norsk',
pl: 'Polski',
pt: 'Português',
ro: 'Română',
ru: 'Русский',
sv: 'Svenska',
tr: 'Türkçe',
uk: 'Українська',
'zh-CN': '简体中文',
},
maxDictionarySize: 1024 * 1024, // 1 MB
// Password Settings
// -----------
// These restrict the passwords users can use when registering
// opts are from http://antelle.github.io/passfield
passwordStrengthOptions: {
length: {
min: 8,
// Bcrypt does not support longer passwords than that.
max: 72,
},
},
elevateAccountSecurityAfterFailedLogin:
parseInt(process.env.ELEVATED_ACCOUNT_SECURITY_AFTER_FAILED_LOGIN_MS, 10) ||
24 * 60 * 60 * 1000,
deviceHistory: {
cookieName: process.env.DEVICE_HISTORY_COOKIE_NAME || 'deviceHistory',
entryExpiry:
parseInt(process.env.DEVICE_HISTORY_ENTRY_EXPIRY_MS, 10) ||
90 * 24 * 60 * 60 * 1000,
maxEntries: parseInt(process.env.DEVICE_HISTORY_MAX_ENTRIES, 10) || 10,
secret: process.env.DEVICE_HISTORY_SECRET,
},
// Email support
// -------------
//
// Overleaf uses nodemailer (http://www.nodemailer.com/) to send transactional emails.
// To see the range of transport and options they support, see http://www.nodemailer.com/docs/transports
// email:
// fromAddress: ""
// replyTo: ""
// lifecycle: false
// # Example transport and parameter settings for Amazon SES
// transport: "SES"
// parameters:
// AWSAccessKeyID: ""
// AWSSecretKey: ""
// For legacy reasons, we need to populate this object.
sentry: {},
// Production Settings
// -------------------
debugPugTemplates: process.env.DEBUG_PUG_TEMPLATES === 'true',
precompilePugTemplatesAtBootTime: process.env
.PRECOMPILE_PUG_TEMPLATES_AT_BOOT_TIME
? process.env.PRECOMPILE_PUG_TEMPLATES_AT_BOOT_TIME === 'true'
: process.env.NODE_ENV === 'production',
// Should javascript assets be served minified or not.
useMinifiedJs: process.env.MINIFIED_JS === 'true' || false,
// Should static assets be sent with a header to tell the browser to cache
// them.
cacheStaticAssets: false,
// If you are running Overleaf over https, set this to true to send the
// cookie with a secure flag (recommended).
secureCookie: false,
// 'SameSite' cookie setting. Can be set to 'lax', 'none' or 'strict'
// 'lax' is recommended, as 'strict' will prevent people linking to projects
// https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7
sameSiteCookie: 'lax',
// If you are running Overleaf behind a proxy (like Apache, Nginx, etc)
// then set this to true to allow it to correctly detect the forwarded IP
// address and http/https protocol information.
behindProxy: false,
// Delay before closing the http server upon receiving a SIGTERM process signal.
gracefulShutdownDelayInMs:
parseInt(process.env.GRACEFUL_SHUTDOWN_DELAY_SECONDS ?? '5', 10) * seconds,
// Expose the hostname in the `X-Served-By` response header
exposeHostname: process.env.EXPOSE_HOSTNAME === 'true',
// Cookie max age (in milliseconds). Set to false for a browser session.
cookieSessionLength: 5 * 24 * 60 * 60 * 1000, // 5 days
// When true, only allow invites to be sent to email addresses that
// already have user accounts
restrictInvitesToExistingAccounts: false,
// Should we allow access to any page without logging in? This includes
// public projects, /learn, /templates, about pages, etc.
allowPublicAccess: process.env.OVERLEAF_ALLOW_PUBLIC_ACCESS === 'true',
// editor should be open by default
editorIsOpen: process.env.EDITOR_OPEN !== 'false',
// site should be open by default
siteIsOpen: process.env.SITE_OPEN !== 'false',
// status file for closing/opening the site at run-time, polled every 5s
siteMaintenanceFile: process.env.SITE_MAINTENANCE_FILE,
// Use a single compile directory for all users in a project
// (otherwise each user has their own directory)
// disablePerUserCompiles: true
// Domain the client (pdfjs) should download the compiled pdf from
pdfDownloadDomain: process.env.COMPILES_USER_CONTENT_DOMAIN, // "http://clsi-lb:3014"
// By default turn on feature flag, can be overridden per request.
enablePdfCaching: process.env.ENABLE_PDF_CACHING === 'true',
// Maximum size of text documents in the real-time editing system.
max_doc_length: 2 * 1024 * 1024, // 2mb
primary_email_check_expiration: 1000 * 60 * 60 * 24 * 90, // 90 days
// Maximum JSON size in HTTP requests
// We should be able to process twice the max doc length, to allow for
// - the doc content
// - text ranges spanning the whole doc
//
// There's also overhead required for the JSON encoding and the UTF-8 encoding,
// theoretically up to 3 times the max doc length. On the other hand, we don't
// want to block the event loop with JSON parsing, so we try to find a
// practical compromise.
max_json_request_size:
parseInt(process.env.MAX_JSON_REQUEST_SIZE) || 6 * 1024 * 1024, // 6 MB
// Internal configs
// ----------------
path: {
// If we ever need to write something to disk (e.g. incoming requests
// that need processing but may be too big for memory, then write
// them to disk here).
dumpFolder: Path.resolve(__dirname, '../data/dumpFolder'),
uploadFolder: Path.resolve(__dirname, '../data/uploads'),
},
// Automatic Snapshots
// -------------------
automaticSnapshots: {
// How long should we wait after the user last edited to
// take a snapshot?
waitTimeAfterLastEdit: 5 * minutes,
// Even if edits are still taking place, this is maximum
// time to wait before taking another snapshot.
maxTimeBetweenSnapshots: 30 * minutes,
},
// Smoke test
// ----------
// Provide log in credentials and a project to be able to run
// some basic smoke tests to check the core functionality.
//
smokeTest: {
user: process.env.SMOKE_TEST_USER,
userId: process.env.SMOKE_TEST_USER_ID,
password: process.env.SMOKE_TEST_PASSWORD,
projectId: process.env.SMOKE_TEST_PROJECT_ID,
rateLimitSubject: process.env.SMOKE_TEST_RATE_LIMIT_SUBJECT || '127.0.0.1',
stepTimeout: parseInt(process.env.SMOKE_TEST_STEP_TIMEOUT || '10000', 10),
},
appName: process.env.APP_NAME || 'Overleaf (Community Edition)',
adminEmail: process.env.ADMIN_EMAIL || 'placeholder@example.com',
adminDomains: process.env.ADMIN_DOMAINS
? JSON.parse(process.env.ADMIN_DOMAINS)
: undefined,
nav: {
title: process.env.APP_NAME || 'Overleaf Community Edition',
hide_powered_by: process.env.NAV_HIDE_POWERED_BY === 'true',
left_footer: [],
right_footer: [
{
text: "<i class='fa fa-github-square'></i> Fork on GitHub!",
url: 'https://github.com/overleaf/overleaf',
},
],
showSubscriptionLink: false,
header_extras: [],
},
// Example:
// header_extras: [{text: "Some Page", url: "http://example.com/some/page", class: "subdued"}]
recaptcha: {
endpoint:
process.env.RECAPTCHA_ENDPOINT ||
'https://www.google.com/recaptcha/api/siteverify',
trustedUsers: (process.env.CAPTCHA_TRUSTED_USERS || '')
.split(',')
.map(x => x.trim())
.filter(x => x !== ''),
disabled: {
invite: true,
login: true,
passwordReset: true,
register: true,
addEmail: true,
},
},
customisation: {},
redirects: {
'/templates/index': '/templates/',
},
reloadModuleViewsOnEachRequest: process.env.NODE_ENV === 'development',
rateLimit: {
autoCompile: {
everyone: process.env.RATE_LIMIT_AUTO_COMPILE_EVERYONE || 100,
standard: process.env.RATE_LIMIT_AUTO_COMPILE_STANDARD || 25,
},
},
analytics: {
enabled: false,
},
compileBodySizeLimitMb: process.env.COMPILE_BODY_SIZE_LIMIT_MB || 7,
textExtensions: defaultTextExtensions.concat(
parseTextExtensions(process.env.ADDITIONAL_TEXT_EXTENSIONS)
),
// case-insensitive file names that is editable (doc) in the editor
editableFilenames: ['latexmkrc', '.latexmkrc', 'makefile', 'gnumakefile'],
fileIgnorePattern:
process.env.FILE_IGNORE_PATTERN ||
'**/{{__MACOSX,.git,.texpadtmp,.R}{,/**},.!(latexmkrc),*.{dvi,aux,log,toc,out,pdfsync,synctex,synctex(busy),fdb_latexmk,fls,nlo,ind,glo,gls,glg,bbl,blg,doc,docx,gz,swp}}',
validRootDocExtensions: ['tex', 'Rtex', 'ltx', 'Rnw'],
emailConfirmationDisabled:
process.env.EMAIL_CONFIRMATION_DISABLED === 'true' || false,
emailAddressLimit: intFromEnv('EMAIL_ADDRESS_LIMIT', 10),
enabledServices: (process.env.ENABLED_SERVICES || 'web,api')
.split(',')
.map(s => s.trim()),
// module options
// ----------
modules: {
sanitize: {
options: {
allowedTags: [
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'blockquote',
'p',
'a',
'ul',
'ol',
'nl',
'li',
'b',
'i',
'strong',
'em',
'strike',
'code',
'hr',
'br',
'div',
'table',
'thead',
'col',
'caption',
'tbody',
'tr',
'th',
'td',
'tfoot',
'pre',
'iframe',
'img',
'figure',
'figcaption',
'span',
'source',
'video',
'del',
],
allowedAttributes: {
a: [
'href',
'name',
'target',
'class',
'event-tracking',
'event-tracking-ga',
'event-tracking-label',
'event-tracking-trigger',
],
div: ['class', 'id', 'style'],
h1: ['class', 'id'],
h2: ['class', 'id'],
h3: ['class', 'id'],
h4: ['class', 'id'],
h5: ['class', 'id'],
h6: ['class', 'id'],
p: ['class'],
col: ['width'],
figure: ['class', 'id', 'style'],
figcaption: ['class', 'id', 'style'],
i: ['aria-hidden', 'aria-label', 'class', 'id'],
iframe: [
'allowfullscreen',
'frameborder',
'height',
'src',
'style',
'width',
],
img: ['alt', 'class', 'src', 'style'],
source: ['src', 'type'],
span: ['class', 'id', 'style'],
strong: ['style'],
table: ['border', 'class', 'id', 'style'],
td: ['colspan', 'rowspan', 'headers', 'style'],
th: [
'abbr',
'headers',
'colspan',
'rowspan',
'scope',
'sorted',
'style',
],
tr: ['class'],
video: ['alt', 'class', 'controls', 'height', 'width'],
},
},
},
},
overleafModuleImports: {
// modules to import (an empty array for each set of modules)
//
// Restart webpack after making changes.
//
createFileModes: [],
devToolbar: [],
gitBridge: [],
publishModal: [],
tprFileViewInfo: [],
tprFileViewRefreshError: [],
tprFileViewRefreshButton: [],
tprFileViewNotOriginalImporter: [],
newFilePromotions: [],
contactUsModal: [],
editorToolbarButtons: [],
sourceEditorExtensions: [],
sourceEditorComponents: [],
pdfLogEntryComponents: [],
pdfLogEntriesComponents: [],
diagnosticActions: [],
sourceEditorCompletionSources: [],
sourceEditorSymbolPalette: [],
sourceEditorToolbarComponents: [],
editorPromotions: [],
langFeedbackLinkingWidgets: [],
labsExperiments: [],
integrationLinkingWidgets: [],
referenceLinkingWidgets: [],
importProjectFromGithubModalWrapper: [],
importProjectFromGithubMenu: [],
editorLeftMenuSync: [],
editorLeftMenuManageTemplate: [],
oauth2Server: [],
managedGroupSubscriptionEnrollmentNotification: [],
userNotifications: [],
managedGroupEnrollmentInvite: [],
ssoCertificateInfo: [],
},
moduleImportSequence: [
'history-v1',
'launchpad',
'server-ce-scripts',
'user-activate',
'track-changes',
'ldap-authentication',
],
viewIncludes: {},
csp: {
enabled: process.env.CSP_ENABLED === 'true',
reportOnly: process.env.CSP_REPORT_ONLY === 'true',
reportPercentage: parseFloat(process.env.CSP_REPORT_PERCENTAGE) || 0,
reportUri: process.env.CSP_REPORT_URI,
exclude: [],
viewDirectives: {
'app/views/project/ide-react': [`img-src 'self' data: blob:`],
},
},
unsupportedBrowsers: {
ie: '<=11',
safari: '<=13',
},
// ID of the IEEE brand in the rails app
ieeeBrandId: intFromEnv('IEEE_BRAND_ID', 15),
managedUsers: {
enabled: false,
},
enableRegistrationPage: false,
}
module.exports.mergeWith = function (overrides) {
return merge(overrides, module.exports)
}

View file

@ -0,0 +1,156 @@
let ProjectEditorHandler
const _ = require('lodash')
const Path = require('path')
function mergeDeletedDocs(a, b) {
const docIdsInA = new Set(a.map(doc => doc._id.toString()))
return a.concat(b.filter(doc => !docIdsInA.has(doc._id.toString())))
}
module.exports = ProjectEditorHandler = {
trackChangesAvailable: true,
buildProjectModelView(project, members, invites, deletedDocsFromDocstore) {
let owner, ownerFeatures
if (!Array.isArray(project.deletedDocs)) {
project.deletedDocs = []
}
project.deletedDocs.forEach(doc => {
// The frontend does not use this field.
delete doc.deletedAt
})
const result = {
_id: project._id,
name: project.name,
rootDoc_id: project.rootDoc_id,
rootFolder: [this.buildFolderModelView(project.rootFolder[0])],
publicAccesLevel: project.publicAccesLevel,
dropboxEnabled: !!project.existsInDropbox,
compiler: project.compiler,
description: project.description,
spellCheckLanguage: project.spellCheckLanguage,
deletedByExternalDataSource: project.deletedByExternalDataSource || false,
deletedDocs: mergeDeletedDocs(
project.deletedDocs,
deletedDocsFromDocstore
),
members: [],
invites: this.buildInvitesView(invites),
imageName:
project.imageName != null
? Path.basename(project.imageName)
: undefined,
}
;({ owner, ownerFeatures, members } =
this.buildOwnerAndMembersViews(members))
result.owner = owner
result.members = members
result.features = _.defaults(ownerFeatures || {}, {
collaborators: -1, // Infinite
versioning: false,
dropbox: false,
compileTimeout: 60,
compileGroup: 'standard',
templates: false,
references: false,
referencesSearch: false,
mendeley: false,
trackChanges: true,
trackChangesVisible: ProjectEditorHandler.trackChangesAvailable,
symbolPalette: false,
})
if (result.features.trackChanges) {
result.trackChangesState = project.track_changes || false
}
// Originally these two feature flags were both signalled by the now-deprecated `references` flag.
// For older users, the presence of the `references` feature flag should still turn on these features.
result.features.referencesSearch =
result.features.referencesSearch || result.features.references
result.features.mendeley =
result.features.mendeley || result.features.references
return result
},
buildOwnerAndMembersViews(members) {
let owner = null
let ownerFeatures = null
const filteredMembers = []
for (const member of members || []) {
if (member.privilegeLevel === 'owner') {
ownerFeatures = member.user.features
owner = this.buildUserModelView(member.user, 'owner')
} else {
filteredMembers.push(
this.buildUserModelView(member.user, member.privilegeLevel)
)
}
}
return {
owner,
ownerFeatures,
members: filteredMembers,
}
},
buildUserModelView(user, privileges) {
return {
_id: user._id,
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
privileges,
signUpDate: user.signUpDate,
}
},
buildFolderModelView(folder) {
const fileRefs = _.filter(folder.fileRefs || [], file => file != null)
return {
_id: folder._id,
name: folder.name,
folders: (folder.folders || []).map(childFolder =>
this.buildFolderModelView(childFolder)
),
fileRefs: fileRefs.map(file => this.buildFileModelView(file)),
docs: (folder.docs || []).map(doc => this.buildDocModelView(doc)),
}
},
buildFileModelView(file) {
return {
_id: file._id,
name: file.name,
linkedFileData: file.linkedFileData,
created: file.created,
}
},
buildDocModelView(doc) {
return {
_id: doc._id,
name: doc.name,
}
},
buildInvitesView(invites) {
if (invites == null) {
return []
}
return invites.map(invite =>
_.pick(invite, [
'_id',
'createdAt',
'email',
'expires',
'privileges',
'projectId',
'sendingUserId',
])
)
},
}

View file

@ -0,0 +1,935 @@
const Path = require('path')
const { merge } = require('@overleaf/settings/merge')
let defaultFeatures, siteUrl
// Make time interval config easier.
const seconds = 1000
const minutes = 60 * seconds
// These credentials are used for authenticating api requests
// between services that may need to go over public channels
const httpAuthUser = process.env.WEB_API_USER
const httpAuthPass = process.env.WEB_API_PASSWORD
const httpAuthUsers = {}
if (httpAuthUser && httpAuthPass) {
httpAuthUsers[httpAuthUser] = httpAuthPass
}
const intFromEnv = function (name, defaultValue) {
if (
[null, undefined].includes(defaultValue) ||
typeof defaultValue !== 'number'
) {
throw new Error(
`Bad default integer value for setting: ${name}, ${defaultValue}`
)
}
return parseInt(process.env[name], 10) || defaultValue
}
const defaultTextExtensions = [
'tex',
'latex',
'sty',
'cls',
'bst',
'bib',
'bibtex',
'txt',
'tikz',
'mtx',
'rtex',
'md',
'asy',
'lbx',
'bbx',
'cbx',
'm',
'lco',
'dtx',
'ins',
'ist',
'def',
'clo',
'ldf',
'rmd',
'lua',
'gv',
'mf',
'yml',
'yaml',
'lhs',
'mk',
'xmpdata',
'cfg',
'rnw',
'ltx',
'inc',
]
const parseTextExtensions = function (extensions) {
if (extensions) {
return extensions.split(',').map(ext => ext.trim())
} else {
return []
}
}
const httpPermissionsPolicy = {
blocked: [
'accelerometer',
'attribution-reporting',
'browsing-topics',
'camera',
'display-capture',
'encrypted-media',
'gamepad',
'geolocation',
'gyroscope',
'hid',
'identity-credentials-get',
'idle-detection',
'local-fonts',
'magnetometer',
'microphone',
'midi',
'otp-credentials',
'payment',
'picture-in-picture',
'screen-wake-lock',
'serial',
'storage-access',
'usb',
'window-management',
'xr-spatial-tracking',
],
allowed: {
autoplay: 'self "https://videos.ctfassets.net"',
fullscreen: 'self',
},
}
module.exports = {
env: 'server-ce',
limits: {
httpGlobalAgentMaxSockets: 300,
httpsGlobalAgentMaxSockets: 300,
},
allowAnonymousReadAndWriteSharing:
process.env.OVERLEAF_ALLOW_ANONYMOUS_READ_AND_WRITE_SHARING === 'true',
// Databases
// ---------
mongo: {
options: {
appname: 'web',
maxPoolSize: parseInt(process.env.MONGO_POOL_SIZE, 10) || 100,
serverSelectionTimeoutMS:
parseInt(process.env.MONGO_SERVER_SELECTION_TIMEOUT, 10) || 60000,
// Setting socketTimeoutMS to 0 means no timeout
socketTimeoutMS: parseInt(
process.env.MONGO_SOCKET_TIMEOUT ?? '60000',
10
),
monitorCommands: true,
},
url:
process.env.MONGO_CONNECTION_STRING ||
process.env.MONGO_URL ||
`mongodb://${process.env.MONGO_HOST || '127.0.0.1'}/sharelatex`,
hasSecondaries: process.env.MONGO_HAS_SECONDARIES === 'true',
},
redis: {
web: {
host: process.env.REDIS_HOST || '127.0.0.1',
port: process.env.REDIS_PORT || '6379',
password: process.env.REDIS_PASSWORD || '',
db: process.env.REDIS_DB,
maxRetriesPerRequest: parseInt(
process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20'
),
},
// websessions:
// cluster: [
// {host: '127.0.0.1', port: 7000}
// {host: '127.0.0.1', port: 7001}
// {host: '127.0.0.1', port: 7002}
// {host: '127.0.0.1', port: 7003}
// {host: '127.0.0.1', port: 7004}
// {host: '127.0.0.1', port: 7005}
// ]
// ratelimiter:
// cluster: [
// {host: '127.0.0.1', port: 7000}
// {host: '127.0.0.1', port: 7001}
// {host: '127.0.0.1', port: 7002}
// {host: '127.0.0.1', port: 7003}
// {host: '127.0.0.1', port: 7004}
// {host: '127.0.0.1', port: 7005}
// ]
// cooldown:
// cluster: [
// {host: '127.0.0.1', port: 7000}
// {host: '127.0.0.1', port: 7001}
// {host: '127.0.0.1', port: 7002}
// {host: '127.0.0.1', port: 7003}
// {host: '127.0.0.1', port: 7004}
// {host: '127.0.0.1', port: 7005}
// ]
api: {
host: process.env.REDIS_HOST || '127.0.0.1',
port: process.env.REDIS_PORT || '6379',
password: process.env.REDIS_PASSWORD || '',
maxRetriesPerRequest: parseInt(
process.env.REDIS_MAX_RETRIES_PER_REQUEST || '20'
),
},
},
// Service locations
// -----------------
// Configure which ports to run each service on. Generally you
// can leave these as they are unless you have some other services
// running which conflict, or want to run the web process on port 80.
internal: {
web: {
port: process.env.WEB_PORT || 3000,
host: process.env.LISTEN_ADDRESS || '127.0.0.1',
},
},
// Tell each service where to find the other services. If everything
// is running locally then this is easy, but they exist as separate config
// options incase you want to run some services on remote hosts.
apis: {
web: {
url: `http://${
process.env.WEB_API_HOST || process.env.WEB_HOST || '127.0.0.1'
}:${process.env.WEB_API_PORT || process.env.WEB_PORT || 3000}`,
user: httpAuthUser,
pass: httpAuthPass,
},
documentupdater: {
url: `http://${
process.env.DOCUPDATER_HOST ||
process.env.DOCUMENT_UPDATER_HOST ||
'127.0.0.1'
}:3003`,
},
spelling: {
url: `http://${process.env.SPELLING_HOST || '127.0.0.1'}:3005`,
host: process.env.SPELLING_HOST,
},
docstore: {
url: `http://${process.env.DOCSTORE_HOST || '127.0.0.1'}:3016`,
pubUrl: `http://${process.env.DOCSTORE_HOST || '127.0.0.1'}:3016`,
},
chat: {
internal_url: `http://${process.env.CHAT_HOST || '127.0.0.1'}:3010`,
},
filestore: {
url: `http://${process.env.FILESTORE_HOST || '127.0.0.1'}:3009`,
},
clsi: {
url: `http://${process.env.CLSI_HOST || '127.0.0.1'}:3013`,
// url: "http://#{process.env['CLSI_LB_HOST']}:3014"
backendGroupName: undefined,
submissionBackendClass:
process.env.CLSI_SUBMISSION_BACKEND_CLASS || 'n2d',
},
project_history: {
sendProjectStructureOps: true,
url: `http://${process.env.PROJECT_HISTORY_HOST || '127.0.0.1'}:3054`,
},
realTime: {
url: `http://${process.env.REALTIME_HOST || '127.0.0.1'}:3026`,
},
contacts: {
url: `http://${process.env.CONTACTS_HOST || '127.0.0.1'}:3036`,
},
notifications: {
url: `http://${process.env.NOTIFICATIONS_HOST || '127.0.0.1'}:3042`,
},
webpack: {
url: `http://${process.env.WEBPACK_HOST || '127.0.0.1'}:3808`,
},
wiki: {
url: process.env.WIKI_URL || 'https://learn.sharelatex.com',
maxCacheAge: parseInt(process.env.WIKI_MAX_CACHE_AGE || 5 * minutes, 10),
},
haveIBeenPwned: {
enabled: process.env.HAVE_I_BEEN_PWNED_ENABLED === 'true',
url:
process.env.HAVE_I_BEEN_PWNED_URL || 'https://api.pwnedpasswords.com',
timeout: parseInt(process.env.HAVE_I_BEEN_PWNED_TIMEOUT, 10) || 5 * 1000,
},
// For legacy reasons, we need to populate the below objects.
v1: {},
recurly: {},
},
// Defines which features are allowed in the
// Permissions-Policy HTTP header
httpPermissions: httpPermissionsPolicy,
useHttpPermissionsPolicy: true,
jwt: {
key: process.env.OT_JWT_AUTH_KEY,
algorithm: process.env.OT_JWT_AUTH_ALG || 'HS256',
},
devToolbar: {
enabled: false,
},
splitTests: [],
// Where your instance of Overleaf Community Edition/Server Pro can be found publicly. Used in emails
// that are sent out, generated links, etc.
siteUrl: (siteUrl = process.env.PUBLIC_URL || 'http://127.0.0.1:3000'),
lockManager: {
lockTestInterval: intFromEnv('LOCK_MANAGER_LOCK_TEST_INTERVAL', 50),
maxTestInterval: intFromEnv('LOCK_MANAGER_MAX_TEST_INTERVAL', 1000),
maxLockWaitTime: intFromEnv('LOCK_MANAGER_MAX_LOCK_WAIT_TIME', 10000),
redisLockExpiry: intFromEnv('LOCK_MANAGER_REDIS_LOCK_EXPIRY', 30),
slowExecutionThreshold: intFromEnv(
'LOCK_MANAGER_SLOW_EXECUTION_THRESHOLD',
5000
),
},
// Optional separate location for websocket connections, if unset defaults to siteUrl.
wsUrl: process.env.WEBSOCKET_URL,
wsUrlV2: process.env.WEBSOCKET_URL_V2,
wsUrlBeta: process.env.WEBSOCKET_URL_BETA,
wsUrlV2Percentage: parseInt(
process.env.WEBSOCKET_URL_V2_PERCENTAGE || '0',
10
),
wsRetryHandshake: parseInt(process.env.WEBSOCKET_RETRY_HANDSHAKE || '5', 10),
// cookie domain
// use full domain for cookies to only be accessible from that domain,
// replace subdomain with dot to have them accessible on all subdomains
cookieDomain: process.env.COOKIE_DOMAIN,
cookieName: process.env.COOKIE_NAME || 'overleaf.sid',
cookieRollingSession: true,
// this is only used if cookies are used for clsi backend
// clsiCookieKey: "clsiserver"
robotsNoindex: process.env.ROBOTS_NOINDEX === 'true' || false,
maxEntitiesPerProject: parseInt(
process.env.MAX_ENTITIES_PER_PROJECT || '2000',
10
),
projectUploadTimeout: parseInt(
process.env.PROJECT_UPLOAD_TIMEOUT || '120000',
10
),
maxUploadSize: 50 * 1024 * 1024, // 50 MB
multerOptions: {
preservePath: process.env.MULTER_PRESERVE_PATH,
},
// start failing the health check if active handles exceeds this limit
maxActiveHandles: process.env.MAX_ACTIVE_HANDLES
? parseInt(process.env.MAX_ACTIVE_HANDLES, 10)
: undefined,
// Security
// --------
security: {
sessionSecret: process.env.SESSION_SECRET,
sessionSecretUpcoming: process.env.SESSION_SECRET_UPCOMING,
sessionSecretFallback: process.env.SESSION_SECRET_FALLBACK,
bcryptRounds: parseInt(process.env.BCRYPT_ROUNDS, 10) || 12,
}, // number of rounds used to hash user passwords (raised to power 2)
adminUrl: process.env.ADMIN_URL,
adminOnlyLogin: process.env.ADMIN_ONLY_LOGIN === 'true',
adminPrivilegeAvailable: process.env.ADMIN_PRIVILEGE_AVAILABLE === 'true',
blockCrossOriginRequests: process.env.BLOCK_CROSS_ORIGIN_REQUESTS === 'true',
allowedOrigins: (process.env.ALLOWED_ORIGINS || siteUrl).split(','),
httpAuthUsers,
// Default features
// ----------------
//
// You can select the features that are enabled by default for new
// new users.
defaultFeatures: (defaultFeatures = {
collaborators: -1,
dropbox: true,
github: true,
gitBridge: true,
versioning: true,
compileTimeout: 180,
compileGroup: 'standard',
references: true,
trackChanges: true,
}),
// featuresEpoch: 'YYYY-MM-DD',
features: {
personal: defaultFeatures,
},
groupPlanModalOptions: {
plan_codes: [],
currencies: [],
sizes: [],
usages: [],
},
plans: [
{
planCode: 'personal',
name: 'Personal',
price_in_cents: 0,
features: defaultFeatures,
},
],
enableSubscriptions: false,
restrictedCountries: [],
enableOnboardingEmails: process.env.ENABLE_ONBOARDING_EMAILS === 'true',
enabledLinkedFileTypes: (process.env.ENABLED_LINKED_FILE_TYPES || '').split(
','
),
// i18n
// ------
//
i18n: {
checkForHTMLInVars: process.env.I18N_CHECK_FOR_HTML_IN_VARS === 'true',
escapeHTMLInVars: process.env.I18N_ESCAPE_HTML_IN_VARS === 'true',
subdomainLang: {
www: { lngCode: 'en', url: siteUrl },
},
defaultLng: 'en',
},
// Spelling languages
// ------------------
//
// You must have the corresponding aspell package installed to
// be able to use a language.
languages: [
{ code: 'en', name: 'English' },
{ code: 'en_US', name: 'English (American)' },
{ code: 'en_GB', name: 'English (British)' },
{ code: 'en_CA', name: 'English (Canadian)' },
{ code: 'af', name: 'Afrikaans' },
{ code: 'ar', name: 'Arabic' },
{ code: 'gl', name: 'Galician' },
{ code: 'eu', name: 'Basque' },
{ code: 'br', name: 'Breton' },
{ code: 'bg', name: 'Bulgarian' },
{ code: 'ca', name: 'Catalan' },
{ code: 'hr', name: 'Croatian' },
{ code: 'cs', name: 'Czech' },
{ code: 'da', name: 'Danish' },
{ code: 'nl', name: 'Dutch' },
{ code: 'eo', name: 'Esperanto' },
{ code: 'et', name: 'Estonian' },
{ code: 'fo', name: 'Faroese' },
{ code: 'fr', name: 'French' },
{ code: 'de', name: 'German' },
{ code: 'el', name: 'Greek' },
{ code: 'id', name: 'Indonesian' },
{ code: 'ga', name: 'Irish' },
{ code: 'it', name: 'Italian' },
{ code: 'kk', name: 'Kazakh' },
{ code: 'ku', name: 'Kurdish' },
{ code: 'lv', name: 'Latvian' },
{ code: 'lt', name: 'Lithuanian' },
{ code: 'nr', name: 'Ndebele' },
{ code: 'ns', name: 'Northern Sotho' },
{ code: 'no', name: 'Norwegian' },
{ code: 'fa', name: 'Persian' },
{ code: 'pl', name: 'Polish' },
{ code: 'pt_BR', name: 'Portuguese (Brazilian)' },
{ code: 'pt_PT', name: 'Portuguese (European)' },
{ code: 'pa', name: 'Punjabi' },
{ code: 'ro', name: 'Romanian' },
{ code: 'ru', name: 'Russian' },
{ code: 'sk', name: 'Slovak' },
{ code: 'sl', name: 'Slovenian' },
{ code: 'st', name: 'Southern Sotho' },
{ code: 'es', name: 'Spanish' },
{ code: 'sv', name: 'Swedish' },
{ code: 'tl', name: 'Tagalog' },
{ code: 'ts', name: 'Tsonga' },
{ code: 'tn', name: 'Tswana' },
{ code: 'hsb', name: 'Upper Sorbian' },
{ code: 'cy', name: 'Welsh' },
{ code: 'xh', name: 'Xhosa' },
],
translatedLanguages: {
cn: '简体中文',
cs: 'Čeština',
da: 'Dansk',
de: 'Deutsch',
en: 'English',
es: 'Español',
fi: 'Suomi',
fr: 'Français',
it: 'Italiano',
ja: '日本語',
ko: '한국어',
nl: 'Nederlands',
no: 'Norsk',
pl: 'Polski',
pt: 'Português',
ro: 'Română',
ru: 'Русский',
sv: 'Svenska',
tr: 'Türkçe',
uk: 'Українська',
'zh-CN': '简体中文',
},
maxDictionarySize: 1024 * 1024, // 1 MB
// Password Settings
// -----------
// These restrict the passwords users can use when registering
// opts are from http://antelle.github.io/passfield
passwordStrengthOptions: {
length: {
min: 8,
// Bcrypt does not support longer passwords than that.
max: 72,
},
},
elevateAccountSecurityAfterFailedLogin:
parseInt(process.env.ELEVATED_ACCOUNT_SECURITY_AFTER_FAILED_LOGIN_MS, 10) ||
24 * 60 * 60 * 1000,
deviceHistory: {
cookieName: process.env.DEVICE_HISTORY_COOKIE_NAME || 'deviceHistory',
entryExpiry:
parseInt(process.env.DEVICE_HISTORY_ENTRY_EXPIRY_MS, 10) ||
90 * 24 * 60 * 60 * 1000,
maxEntries: parseInt(process.env.DEVICE_HISTORY_MAX_ENTRIES, 10) || 10,
secret: process.env.DEVICE_HISTORY_SECRET,
},
// Email support
// -------------
//
// Overleaf uses nodemailer (http://www.nodemailer.com/) to send transactional emails.
// To see the range of transport and options they support, see http://www.nodemailer.com/docs/transports
// email:
// fromAddress: ""
// replyTo: ""
// lifecycle: false
// # Example transport and parameter settings for Amazon SES
// transport: "SES"
// parameters:
// AWSAccessKeyID: ""
// AWSSecretKey: ""
// For legacy reasons, we need to populate this object.
sentry: {},
// Production Settings
// -------------------
debugPugTemplates: process.env.DEBUG_PUG_TEMPLATES === 'true',
precompilePugTemplatesAtBootTime: process.env
.PRECOMPILE_PUG_TEMPLATES_AT_BOOT_TIME
? process.env.PRECOMPILE_PUG_TEMPLATES_AT_BOOT_TIME === 'true'
: process.env.NODE_ENV === 'production',
// Should javascript assets be served minified or not.
useMinifiedJs: process.env.MINIFIED_JS === 'true' || false,
// Should static assets be sent with a header to tell the browser to cache
// them.
cacheStaticAssets: false,
// If you are running Overleaf over https, set this to true to send the
// cookie with a secure flag (recommended).
secureCookie: false,
// 'SameSite' cookie setting. Can be set to 'lax', 'none' or 'strict'
// 'lax' is recommended, as 'strict' will prevent people linking to projects
// https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7
sameSiteCookie: 'lax',
// If you are running Overleaf behind a proxy (like Apache, Nginx, etc)
// then set this to true to allow it to correctly detect the forwarded IP
// address and http/https protocol information.
behindProxy: false,
// Delay before closing the http server upon receiving a SIGTERM process signal.
gracefulShutdownDelayInMs:
parseInt(process.env.GRACEFUL_SHUTDOWN_DELAY_SECONDS ?? '5', 10) * seconds,
// Expose the hostname in the `X-Served-By` response header
exposeHostname: process.env.EXPOSE_HOSTNAME === 'true',
// Cookie max age (in milliseconds). Set to false for a browser session.
cookieSessionLength: 5 * 24 * 60 * 60 * 1000, // 5 days
// When true, only allow invites to be sent to email addresses that
// already have user accounts
restrictInvitesToExistingAccounts: false,
// Should we allow access to any page without logging in? This includes
// public projects, /learn, /templates, about pages, etc.
allowPublicAccess: process.env.OVERLEAF_ALLOW_PUBLIC_ACCESS === 'true',
// editor should be open by default
editorIsOpen: process.env.EDITOR_OPEN !== 'false',
// site should be open by default
siteIsOpen: process.env.SITE_OPEN !== 'false',
// status file for closing/opening the site at run-time, polled every 5s
siteMaintenanceFile: process.env.SITE_MAINTENANCE_FILE,
// Use a single compile directory for all users in a project
// (otherwise each user has their own directory)
// disablePerUserCompiles: true
// Domain the client (pdfjs) should download the compiled pdf from
pdfDownloadDomain: process.env.COMPILES_USER_CONTENT_DOMAIN, // "http://clsi-lb:3014"
// By default turn on feature flag, can be overridden per request.
enablePdfCaching: process.env.ENABLE_PDF_CACHING === 'true',
// Maximum size of text documents in the real-time editing system.
max_doc_length: 2 * 1024 * 1024, // 2mb
primary_email_check_expiration: 1000 * 60 * 60 * 24 * 90, // 90 days
// Maximum JSON size in HTTP requests
// We should be able to process twice the max doc length, to allow for
// - the doc content
// - text ranges spanning the whole doc
//
// There's also overhead required for the JSON encoding and the UTF-8 encoding,
// theoretically up to 3 times the max doc length. On the other hand, we don't
// want to block the event loop with JSON parsing, so we try to find a
// practical compromise.
max_json_request_size:
parseInt(process.env.MAX_JSON_REQUEST_SIZE) || 6 * 1024 * 1024, // 6 MB
// Internal configs
// ----------------
path: {
// If we ever need to write something to disk (e.g. incoming requests
// that need processing but may be too big for memory, then write
// them to disk here).
dumpFolder: Path.resolve(__dirname, '../data/dumpFolder'),
uploadFolder: Path.resolve(__dirname, '../data/uploads'),
},
// Automatic Snapshots
// -------------------
automaticSnapshots: {
// How long should we wait after the user last edited to
// take a snapshot?
waitTimeAfterLastEdit: 5 * minutes,
// Even if edits are still taking place, this is maximum
// time to wait before taking another snapshot.
maxTimeBetweenSnapshots: 30 * minutes,
},
// Smoke test
// ----------
// Provide log in credentials and a project to be able to run
// some basic smoke tests to check the core functionality.
//
smokeTest: {
user: process.env.SMOKE_TEST_USER,
userId: process.env.SMOKE_TEST_USER_ID,
password: process.env.SMOKE_TEST_PASSWORD,
projectId: process.env.SMOKE_TEST_PROJECT_ID,
rateLimitSubject: process.env.SMOKE_TEST_RATE_LIMIT_SUBJECT || '127.0.0.1',
stepTimeout: parseInt(process.env.SMOKE_TEST_STEP_TIMEOUT || '10000', 10),
},
appName: process.env.APP_NAME || 'Overleaf (Community Edition)',
adminEmail: process.env.ADMIN_EMAIL || 'placeholder@example.com',
adminDomains: process.env.ADMIN_DOMAINS
? JSON.parse(process.env.ADMIN_DOMAINS)
: undefined,
nav: {
title: process.env.APP_NAME || 'Overleaf Community Edition',
hide_powered_by: process.env.NAV_HIDE_POWERED_BY === 'true',
left_footer: [],
right_footer: [
{
text: "<i class='fa fa-github-square'></i> Fork on GitHub!",
url: 'https://github.com/overleaf/overleaf',
},
],
showSubscriptionLink: false,
header_extras: [],
},
// Example:
// header_extras: [{text: "Some Page", url: "http://example.com/some/page", class: "subdued"}]
recaptcha: {
endpoint:
process.env.RECAPTCHA_ENDPOINT ||
'https://www.google.com/recaptcha/api/siteverify',
trustedUsers: (process.env.CAPTCHA_TRUSTED_USERS || '')
.split(',')
.map(x => x.trim())
.filter(x => x !== ''),
disabled: {
invite: true,
login: true,
passwordReset: true,
register: true,
addEmail: true,
},
},
customisation: {},
redirects: {
'/templates/index': '/templates/',
},
reloadModuleViewsOnEachRequest: process.env.NODE_ENV === 'development',
rateLimit: {
autoCompile: {
everyone: process.env.RATE_LIMIT_AUTO_COMPILE_EVERYONE || 100,
standard: process.env.RATE_LIMIT_AUTO_COMPILE_STANDARD || 25,
},
},
analytics: {
enabled: false,
},
compileBodySizeLimitMb: process.env.COMPILE_BODY_SIZE_LIMIT_MB || 7,
textExtensions: defaultTextExtensions.concat(
parseTextExtensions(process.env.ADDITIONAL_TEXT_EXTENSIONS)
),
// case-insensitive file names that is editable (doc) in the editor
editableFilenames: ['latexmkrc', '.latexmkrc', 'makefile', 'gnumakefile'],
fileIgnorePattern:
process.env.FILE_IGNORE_PATTERN ||
'**/{{__MACOSX,.git,.texpadtmp,.R}{,/**},.!(latexmkrc),*.{dvi,aux,log,toc,out,pdfsync,synctex,synctex(busy),fdb_latexmk,fls,nlo,ind,glo,gls,glg,bbl,blg,doc,docx,gz,swp}}',
validRootDocExtensions: ['tex', 'Rtex', 'ltx', 'Rnw'],
emailConfirmationDisabled:
process.env.EMAIL_CONFIRMATION_DISABLED === 'true' || false,
emailAddressLimit: intFromEnv('EMAIL_ADDRESS_LIMIT', 10),
enabledServices: (process.env.ENABLED_SERVICES || 'web,api')
.split(',')
.map(s => s.trim()),
// module options
// ----------
modules: {
sanitize: {
options: {
allowedTags: [
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'blockquote',
'p',
'a',
'ul',
'ol',
'nl',
'li',
'b',
'i',
'strong',
'em',
'strike',
'code',
'hr',
'br',
'div',
'table',
'thead',
'col',
'caption',
'tbody',
'tr',
'th',
'td',
'tfoot',
'pre',
'iframe',
'img',
'figure',
'figcaption',
'span',
'source',
'video',
'del',
],
allowedAttributes: {
a: [
'href',
'name',
'target',
'class',
'event-tracking',
'event-tracking-ga',
'event-tracking-label',
'event-tracking-trigger',
],
div: ['class', 'id', 'style'],
h1: ['class', 'id'],
h2: ['class', 'id'],
h3: ['class', 'id'],
h4: ['class', 'id'],
h5: ['class', 'id'],
h6: ['class', 'id'],
p: ['class'],
col: ['width'],
figure: ['class', 'id', 'style'],
figcaption: ['class', 'id', 'style'],
i: ['aria-hidden', 'aria-label', 'class', 'id'],
iframe: [
'allowfullscreen',
'frameborder',
'height',
'src',
'style',
'width',
],
img: ['alt', 'class', 'src', 'style'],
source: ['src', 'type'],
span: ['class', 'id', 'style'],
strong: ['style'],
table: ['border', 'class', 'id', 'style'],
td: ['colspan', 'rowspan', 'headers', 'style'],
th: [
'abbr',
'headers',
'colspan',
'rowspan',
'scope',
'sorted',
'style',
],
tr: ['class'],
video: ['alt', 'class', 'controls', 'height', 'width'],
},
},
},
},
overleafModuleImports: {
// modules to import (an empty array for each set of modules)
//
// Restart webpack after making changes.
//
createFileModes: [],
devToolbar: [],
gitBridge: [],
publishModal: [],
tprFileViewInfo: [],
tprFileViewRefreshError: [],
tprFileViewRefreshButton: [],
tprFileViewNotOriginalImporter: [],
newFilePromotions: [],
contactUsModal: [],
editorToolbarButtons: [],
sourceEditorExtensions: [],
sourceEditorComponents: [],
pdfLogEntryComponents: [],
pdfLogEntriesComponents: [],
diagnosticActions: [],
sourceEditorCompletionSources: [],
sourceEditorSymbolPalette: [],
sourceEditorToolbarComponents: [],
editorPromotions: [],
langFeedbackLinkingWidgets: [],
labsExperiments: [],
integrationLinkingWidgets: [],
referenceLinkingWidgets: [],
importProjectFromGithubModalWrapper: [],
importProjectFromGithubMenu: [],
editorLeftMenuSync: [],
editorLeftMenuManageTemplate: [],
oauth2Server: [],
managedGroupSubscriptionEnrollmentNotification: [],
userNotifications: [],
managedGroupEnrollmentInvite: [],
ssoCertificateInfo: [],
},
moduleImportSequence: [
'history-v1',
'launchpad',
'server-ce-scripts',
'user-activate',
'track-changes',
],
viewIncludes: {},
csp: {
enabled: process.env.CSP_ENABLED === 'true',
reportOnly: process.env.CSP_REPORT_ONLY === 'true',
reportPercentage: parseFloat(process.env.CSP_REPORT_PERCENTAGE) || 0,
reportUri: process.env.CSP_REPORT_URI,
exclude: [],
viewDirectives: {
'app/views/project/ide-react': [`img-src 'self' data: blob:`],
},
},
unsupportedBrowsers: {
ie: '<=11',
safari: '<=13',
},
// ID of the IEEE brand in the rails app
ieeeBrandId: intFromEnv('IEEE_BRAND_ID', 15),
managedUsers: {
enabled: false,
},
}
module.exports.mergeWith = function (overrides) {
return merge(overrides, module.exports)
}

View file

@ -0,0 +1,308 @@
const ChatApiHandler = require('../../../../app/src/Features/Chat/ChatApiHandler')
const ChatManager = require('../../../../app/src/Features/Chat/ChatManager')
const EditorRealTimeController = require('../../../../app/src/Features/Editor/EditorRealTimeController')
const SessionManager = require('../../../../app/src/Features/Authentication/SessionManager')
const UserInfoManager = require('../../../../app/src/Features/User/UserInfoManager')
const DocstoreManager = require('../../../../app/src/Features/Docstore/DocstoreManager')
const DocumentUpdaterHandler = require('../../../../app/src/Features/DocumentUpdater/DocumentUpdaterHandler')
const CollaboratorsGetter = require('../../../../app/src/Features/Collaborators/CollaboratorsGetter')
const { Project } = require('../../../../app/src/models/Project')
const pLimit = require('p-limit')
async function _updateTCState (projectId, state, callback) {
await Project.updateOne({_id: projectId}, {track_changes: state}).exec()
callback()
}
function _transformId(doc) {
if (doc._id) {
doc.id = doc._id;
delete doc._id;
}
return doc;
}
const TrackChangesController = {
trackChanges(req, res, next) {
const { project_id } = req.params
let state = req.body.on || req.body.on_for
if ( req.body.on_for_guests && !req.body.on ) state.__guests__ = true
return _updateTCState(project_id, state,
function (err, message) {
if (err != null) {
return next(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'toggle-track-changes',
state
)
return res.sendStatus(204)
}
)
},
acceptChanges(req, res, next) {
const { project_id, doc_id } = req.params
const change_ids = req.body.change_ids
return DocumentUpdaterHandler.acceptChanges(
project_id,
doc_id,
change_ids,
function (err, message) {
if (err != null) {
return next(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'accept-changes',
doc_id,
change_ids,
)
return res.sendStatus(204)
}
)
},
async getAllRanges(req, res, next) {
const { project_id } = req.params
// FIXME: ranges are from mongodb, probably already outdated
const ranges = await DocstoreManager.promises.getAllRanges(project_id)
// frontend expects 'id', not '_id'
return res.json(ranges.map(_transformId))
},
async getChangesUsers(req, res, next) {
const { project_id } = req.params
const memberIds = await CollaboratorsGetter.promises.getMemberIds(project_id)
// FIXME: Does not work properly if the user is no longer a member of the project
// memberIds from DocstoreManager.getAllRanges(project_id) is not a remedy
// because ranges are not updated in real-time
const limit = pLimit(3)
const users = await Promise.all(
memberIds.map(memberId =>
limit(async () => {
const user = await UserInfoManager.promises.getPersonalInfo(memberId)
return user
})
)
)
users.push({_id: null}) // An anonymous user won't cause any harm
// frontend expects 'id', not '_id'
return res.json(users.map(_transformId))
},
getThreads(req, res, next) {
const { project_id } = req.params
return ChatApiHandler.getThreads(
project_id,
function (err, messages) {
if (err != null) {
return next(err)
}
return ChatManager.injectUserInfoIntoThreads(
messages,
function (err) {
if (err != null) {
return next(err)
}
return res.json(messages)
}
)
}
)
},
sendComment(req, res, next) {
const { project_id, thread_id } = req.params
const { content } = req.body
const user_id = SessionManager.getLoggedInUserId(req.session)
if (user_id == null) {
const err = new Error('no logged-in user')
return next(err)
}
return ChatApiHandler.sendComment(
project_id,
thread_id,
user_id,
content,
function (err, message) {
if (err != null) {
return next(err)
}
return UserInfoManager.getPersonalInfo(
user_id,
function (err, user) {
if (err != null) {
return next(err)
}
message.user = user
EditorRealTimeController.emitToRoom(
project_id,
'new-comment',
thread_id, message
)
return res.sendStatus(204)
}
)
}
)
},
editMessage(req, res, next) {
const { project_id, thread_id, message_id } = req.params
const { content } = req.body
const user_id = SessionManager.getLoggedInUserId(req.session)
if (user_id == null) {
const err = new Error('no logged-in user')
return next(err)
}
return ChatApiHandler.editMessage(
project_id,
thread_id,
message_id,
user_id,
content,
function (err, message) {
if (err != null) {
return next(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'edit-message',
thread_id,
message_id,
content
)
return res.sendStatus(204)
}
)
},
deleteMessage(req, res, next) {
const { project_id, thread_id, message_id } = req.params
return ChatApiHandler.deleteMessage(
project_id,
thread_id,
message_id,
function (err, message) {
if (err != null) {
return next(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'delete-message',
thread_id,
message_id
)
return res.sendStatus(204)
}
)
},
resolveThread(req, res, next) {
const { project_id, doc_id, thread_id } = req.params
const user_id = SessionManager.getLoggedInUserId(req.session)
if (user_id == null) {
const err = new Error('no logged-in user')
return next(err)
}
DocumentUpdaterHandler.resolveThread(
project_id,
doc_id,
thread_id,
user_id,
function (err, message) {
if (err != null) {
return next(err)
}
}
)
return ChatApiHandler.resolveThread(
project_id,
thread_id,
user_id,
function (err, message) {
if (err != null) {
return next(err)
}
return UserInfoManager.getPersonalInfo(
user_id,
function (err, user) {
if (err != null) {
return next(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'resolve-thread',
thread_id,
user
)
return res.sendStatus(204)
}
)
}
)
},
reopenThread(req, res, next) {
const { project_id, doc_id, thread_id } = req.params
const user_id = SessionManager.getLoggedInUserId(req.session)
if (user_id == null) {
const err = new Error('no logged-in user')
return next(err)
}
DocumentUpdaterHandler.reopenThread(
project_id,
doc_id,
thread_id,
user_id,
function (err, message) {
if (err != null) {
return next(err)
}
}
)
return ChatApiHandler.reopenThread(
project_id,
thread_id,
function (err, message) {
if (err != null) {
return next(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'reopen-thread',
thread_id
)
return res.sendStatus(204)
}
)
},
deleteThread(req, res, next) {
const { project_id, doc_id, thread_id } = req.params
const user_id = SessionManager.getLoggedInUserId(req.session)
if (user_id == null) {
const err = new Error('no logged-in user')
return next(err)
}
return DocumentUpdaterHandler.deleteThread(
project_id,
doc_id,
thread_id,
user_id,
function (err, message) {
if (err != null) {
return next(err)
}
ChatApiHandler.deleteThread(
project_id,
thread_id,
function (err, message) {
if (err != null) {
return next(err)
}
EditorRealTimeController.emitToRoom(
project_id,
'delete-thread',
thread_id
)
return res.sendStatus(204)
}
)
}
)
},
}
module.exports = TrackChangesController

View file

@ -0,0 +1,72 @@
const logger = require('@overleaf/logger')
const AuthorizationMiddleware = require('../../../../app/src/Features/Authorization/AuthorizationMiddleware')
const TrackChangesController = require('./TrackChangesController')
module.exports = {
apply(webRouter) {
logger.debug({}, 'Init track-changes router')
webRouter.post('/project/:project_id/track_changes',
AuthorizationMiddleware.blockRestrictedUserFromProject,
AuthorizationMiddleware.ensureUserCanReadProject,
TrackChangesController.trackChanges
)
webRouter.post('/project/:project_id/doc/:doc_id/changes/accept',
AuthorizationMiddleware.blockRestrictedUserFromProject,
AuthorizationMiddleware.ensureUserCanReadProject,
TrackChangesController.acceptChanges
)
webRouter.get('/project/:project_id/ranges',
AuthorizationMiddleware.blockRestrictedUserFromProject,
AuthorizationMiddleware.ensureUserCanReadProject,
TrackChangesController.getAllRanges
)
webRouter.get('/project/:project_id/changes/users',
AuthorizationMiddleware.blockRestrictedUserFromProject,
AuthorizationMiddleware.ensureUserCanReadProject,
TrackChangesController.getChangesUsers
)
webRouter.get(
'/project/:project_id/threads',
AuthorizationMiddleware.blockRestrictedUserFromProject,
AuthorizationMiddleware.ensureUserCanReadProject,
TrackChangesController.getThreads
)
webRouter.post(
'/project/:project_id/thread/:thread_id/messages',
AuthorizationMiddleware.blockRestrictedUserFromProject,
AuthorizationMiddleware.ensureUserCanReadProject,
TrackChangesController.sendComment
)
webRouter.post(
'/project/:project_id/thread/:thread_id/messages/:message_id/edit',
AuthorizationMiddleware.blockRestrictedUserFromProject,
AuthorizationMiddleware.ensureUserCanReadProject,
TrackChangesController.editMessage
)
webRouter.delete(
'/project/:project_id/thread/:thread_id/messages/:message_id',
AuthorizationMiddleware.blockRestrictedUserFromProject,
AuthorizationMiddleware.ensureUserCanReadProject,
TrackChangesController.deleteMessage
)
webRouter.post(
'/project/:project_id/doc/:doc_id/thread/:thread_id/resolve',
AuthorizationMiddleware.blockRestrictedUserFromProject,
AuthorizationMiddleware.ensureUserCanReadProject,
TrackChangesController.resolveThread
)
webRouter.post(
'/project/:project_id/doc/:doc_id/thread/:thread_id/reopen',
AuthorizationMiddleware.blockRestrictedUserFromProject,
AuthorizationMiddleware.ensureUserCanReadProject,
TrackChangesController.reopenThread
)
webRouter.delete(
'/project/:project_id/doc/:doc_id/thread/:thread_id',
AuthorizationMiddleware.blockRestrictedUserFromProject,
AuthorizationMiddleware.ensureUserCanReadProject,
TrackChangesController.deleteThread
)
},
}

View file

@ -0,0 +1,2 @@
const TrackChangesRouter = require('./app/src/TrackChangesRouter')
module.exports = { router : TrackChangesRouter }