]>
Commit | Line | Data |
---|---|---|
1 | import express from 'express' | |
2 | import RateLimit, { Options as RateLimitHandlerOptions } from 'express-rate-limit' | |
3 | import { RunnerModel } from '@server/models/runner/runner' | |
4 | import { UserRole } from '@shared/models' | |
5 | import { optionalAuthenticate } from './auth' | |
6 | ||
7 | const whitelistRoles = new Set([ UserRole.ADMINISTRATOR, UserRole.MODERATOR ]) | |
8 | ||
9 | export function buildRateLimiter (options: { | |
10 | windowMs: number | |
11 | max: number | |
12 | skipFailedRequests?: boolean | |
13 | }) { | |
14 | return RateLimit({ | |
15 | windowMs: options.windowMs, | |
16 | max: options.max, | |
17 | skipFailedRequests: options.skipFailedRequests, | |
18 | ||
19 | handler: (req, res, next, options) => { | |
20 | // Bypass rate limit for registered runners | |
21 | if (req.body?.runnerToken) { | |
22 | return RunnerModel.loadByToken(req.body.runnerToken) | |
23 | .then(runner => { | |
24 | if (runner) return next() | |
25 | ||
26 | return sendRateLimited(res, options) | |
27 | }) | |
28 | } | |
29 | ||
30 | // Bypass rate limit for admins/moderators | |
31 | return optionalAuthenticate(req, res, () => { | |
32 | if (res.locals.authenticated === true && whitelistRoles.has(res.locals.oauth.token.User.role)) { | |
33 | return next() | |
34 | } | |
35 | ||
36 | return sendRateLimited(res, options) | |
37 | }) | |
38 | } | |
39 | }) | |
40 | } | |
41 | ||
42 | // --------------------------------------------------------------------------- | |
43 | // Private | |
44 | // --------------------------------------------------------------------------- | |
45 | ||
46 | function sendRateLimited (res: express.Response, options: RateLimitHandlerOptions) { | |
47 | return res.status(options.statusCode).send(options.message) | |
48 | ||
49 | } |