2023-04-21 14:55:10 +02:00
|
|
|
import express from 'express'
|
|
|
|
import RateLimit, { Options as RateLimitHandlerOptions } from 'express-rate-limit'
|
2023-06-20 14:17:34 +02:00
|
|
|
import { CONFIG } from '@server/initializers/config'
|
2023-04-21 14:55:10 +02:00
|
|
|
import { RunnerModel } from '@server/models/runner/runner'
|
2022-05-30 11:33:38 +02:00
|
|
|
import { UserRole } from '@shared/models'
|
|
|
|
import { optionalAuthenticate } from './auth'
|
|
|
|
|
|
|
|
const whitelistRoles = new Set([ UserRole.ADMINISTRATOR, UserRole.MODERATOR ])
|
|
|
|
|
2023-04-21 14:55:10 +02:00
|
|
|
export function buildRateLimiter (options: {
|
2022-05-30 11:33:38 +02: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 14:55:10 +02:00
|
|
|
// Bypass rate limit for registered runners
|
|
|
|
if (req.body?.runnerToken) {
|
|
|
|
return RunnerModel.loadByToken(req.body.runnerToken)
|
|
|
|
.then(runner => {
|
|
|
|
if (runner) return next()
|
|
|
|
|
|
|
|
return sendRateLimited(res, options)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// Bypass rate limit for admins/moderators
|
2022-05-30 11:33:38 +02:00
|
|
|
return optionalAuthenticate(req, res, () => {
|
|
|
|
if (res.locals.authenticated === true && whitelistRoles.has(res.locals.oauth.token.User.role)) {
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
|
2023-04-21 14:55:10 +02:00
|
|
|
return sendRateLimited(res, options)
|
2022-05-30 11:33:38 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-06-20 14:17:34 +02:00
|
|
|
export const apiRateLimiter = buildRateLimiter({
|
|
|
|
windowMs: CONFIG.RATES_LIMIT.API.WINDOW_MS,
|
|
|
|
max: CONFIG.RATES_LIMIT.API.MAX
|
|
|
|
})
|
|
|
|
|
2023-04-21 14:55:10 +02:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// Private
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
function sendRateLimited (res: express.Response, options: RateLimitHandlerOptions) {
|
|
|
|
return res.status(options.statusCode).send(options.message)
|
2022-05-30 11:33:38 +02:00
|
|
|
}
|