1 import express from 'express'
2 import RateLimit, { Options as RateLimitHandlerOptions } from 'express-rate-limit'
3 import { CONFIG } from '@server/initializers/config'
4 import { RunnerModel } from '@server/models/runner/runner'
5 import { UserRole } from '@shared/models'
6 import { optionalAuthenticate } from './auth'
8 const whitelistRoles = new Set([ UserRole.ADMINISTRATOR, UserRole.MODERATOR ])
10 export function buildRateLimiter (options: {
13 skipFailedRequests?: boolean
16 windowMs: options.windowMs,
18 skipFailedRequests: options.skipFailedRequests,
20 handler: (req, res, next, options) => {
21 // Bypass rate limit for registered runners
22 if (req.body?.runnerToken) {
23 return RunnerModel.loadByToken(req.body.runnerToken)
25 if (runner) return next()
27 return sendRateLimited(res, options)
31 // Bypass rate limit for admins/moderators
32 return optionalAuthenticate(req, res, () => {
33 if (res.locals.authenticated === true && whitelistRoles.has(res.locals.oauth.token.User.role)) {
37 return sendRateLimited(res, options)
43 export const apiRateLimiter = buildRateLimiter({
44 windowMs: CONFIG.RATES_LIMIT.API.WINDOW_MS,
45 max: CONFIG.RATES_LIMIT.API.MAX
48 // ---------------------------------------------------------------------------
50 // ---------------------------------------------------------------------------
52 function sendRateLimited (res: express.Response, options: RateLimitHandlerOptions) {
53 return res.status(options.statusCode).send(options.message)