2023-04-21 07:55:10 -05:00
|
|
|
import express from 'express'
|
|
|
|
import RateLimit, { Options as RateLimitHandlerOptions } from 'express-rate-limit'
|
2023-07-31 07:34:36 -05:00
|
|
|
import { UserRole, UserRoleType } from '@peertube/peertube-models'
|
|
|
|
import { CONFIG } from '@server/initializers/config.js'
|
|
|
|
import { RunnerModel } from '@server/models/runner/runner.js'
|
|
|
|
import { optionalAuthenticate } from './auth.js'
|
2024-03-09 14:43:17 -06:00
|
|
|
import { logger } from '@server/helpers/logger.js'
|
2022-05-30 04:33:38 -05:00
|
|
|
|
2023-07-31 07:34:36 -05:00
|
|
|
const whitelistRoles = new Set<UserRoleType>([ UserRole.ADMINISTRATOR, UserRole.MODERATOR ])
|
2022-05-30 04:33:38 -05:00
|
|
|
|
2023-04-21 07:55:10 -05:00
|
|
|
export function buildRateLimiter (options: {
|
2022-05-30 04:33:38 -05:00
|
|
|
windowMs: number
|
|
|
|
max: number
|
|
|
|
skipFailedRequests?: boolean
|
|
|
|
}) {
|
|
|
|
return RateLimit({
|
|
|
|
windowMs: options.windowMs,
|
|
|
|
max: options.max,
|
|
|
|
skipFailedRequests: options.skipFailedRequests,
|
|
|
|
|
|
|
|
handler: (req, res, next, options) => {
|
2023-04-21 07:55:10 -05:00
|
|
|
// Bypass rate limit for registered runners
|
|
|
|
if (req.body?.runnerToken) {
|
|
|
|
return RunnerModel.loadByToken(req.body.runnerToken)
|
|
|
|
.then(runner => {
|
|
|
|
if (runner) return next()
|
|
|
|
|
2024-03-09 14:43:17 -06:00
|
|
|
return sendRateLimited(req, res, options)
|
2023-04-21 07:55:10 -05:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// Bypass rate limit for admins/moderators
|
2022-05-30 04:33:38 -05:00
|
|
|
return optionalAuthenticate(req, res, () => {
|
|
|
|
if (res.locals.authenticated === true && whitelistRoles.has(res.locals.oauth.token.User.role)) {
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
|
2024-03-09 14:43:17 -06:00
|
|
|
return sendRateLimited(req, res, options)
|
2022-05-30 04:33:38 -05:00
|
|
|
})
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-06-20 07:17:34 -05:00
|
|
|
export const apiRateLimiter = buildRateLimiter({
|
|
|
|
windowMs: CONFIG.RATES_LIMIT.API.WINDOW_MS,
|
|
|
|
max: CONFIG.RATES_LIMIT.API.MAX
|
|
|
|
})
|
|
|
|
|
2023-07-25 08:18:10 -05:00
|
|
|
export const activityPubRateLimiter = buildRateLimiter({
|
|
|
|
windowMs: CONFIG.RATES_LIMIT.ACTIVITY_PUB.WINDOW_MS,
|
|
|
|
max: CONFIG.RATES_LIMIT.ACTIVITY_PUB.MAX
|
|
|
|
})
|
|
|
|
|
2023-04-21 07:55:10 -05:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// Private
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
2024-03-09 14:43:17 -06:00
|
|
|
function sendRateLimited (req: express.Request, res: express.Response, options: RateLimitHandlerOptions) {
|
|
|
|
logger.debug('Rate limit exceeded for route ' + req.originalUrl)
|
|
|
|
|
2023-04-21 07:55:10 -05:00
|
|
|
return res.status(options.statusCode).send(options.message)
|
2022-05-30 04:33:38 -05:00
|
|
|
}
|