diff options
Diffstat (limited to 'server/middlewares/rate-limiter.ts')
-rw-r--r-- | server/middlewares/rate-limiter.ts | 59 |
1 files changed, 0 insertions, 59 deletions
diff --git a/server/middlewares/rate-limiter.ts b/server/middlewares/rate-limiter.ts deleted file mode 100644 index 143d43632..000000000 --- a/server/middlewares/rate-limiter.ts +++ /dev/null | |||
@@ -1,59 +0,0 @@ | |||
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' | ||
7 | |||
8 | const whitelistRoles = new Set([ UserRole.ADMINISTRATOR, UserRole.MODERATOR ]) | ||
9 | |||
10 | export function buildRateLimiter (options: { | ||
11 | windowMs: number | ||
12 | max: number | ||
13 | skipFailedRequests?: boolean | ||
14 | }) { | ||
15 | return RateLimit({ | ||
16 | windowMs: options.windowMs, | ||
17 | max: options.max, | ||
18 | skipFailedRequests: options.skipFailedRequests, | ||
19 | |||
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) | ||
24 | .then(runner => { | ||
25 | if (runner) return next() | ||
26 | |||
27 | return sendRateLimited(res, options) | ||
28 | }) | ||
29 | } | ||
30 | |||
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)) { | ||
34 | return next() | ||
35 | } | ||
36 | |||
37 | return sendRateLimited(res, options) | ||
38 | }) | ||
39 | } | ||
40 | }) | ||
41 | } | ||
42 | |||
43 | export const apiRateLimiter = buildRateLimiter({ | ||
44 | windowMs: CONFIG.RATES_LIMIT.API.WINDOW_MS, | ||
45 | max: CONFIG.RATES_LIMIT.API.MAX | ||
46 | }) | ||
47 | |||
48 | export const activityPubRateLimiter = buildRateLimiter({ | ||
49 | windowMs: CONFIG.RATES_LIMIT.ACTIVITY_PUB.WINDOW_MS, | ||
50 | max: CONFIG.RATES_LIMIT.ACTIVITY_PUB.MAX | ||
51 | }) | ||
52 | |||
53 | // --------------------------------------------------------------------------- | ||
54 | // Private | ||
55 | // --------------------------------------------------------------------------- | ||
56 | |||
57 | function sendRateLimited (res: express.Response, options: RateLimitHandlerOptions) { | ||
58 | return res.status(options.statusCode).send(options.message) | ||
59 | } | ||