summaryrefslogtreecommitdiff
path: root/packages/backend/src/server/api/limiter.ts
blob: e74db8466e6239696a84ba3f2b26691d7b9d0be9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import Limiter from 'ratelimiter';
import { redisClient } from '../../db/redis.js';
import { IEndpoint } from './endpoints.js';
import * as Acct from '@/misc/acct.js';
import { CacheableLocalUser, User } from '@/models/entities/user.js';
import Logger from '@/services/logger.js';

const logger = new Logger('limiter');

export const limiter = (endpoint: IEndpoint & { meta: { limit: NonNullable<IEndpoint['meta']['limit']> } }, user: CacheableLocalUser) => new Promise<void>((ok, reject) => {
	const limitation = endpoint.meta.limit;

	const key = Object.prototype.hasOwnProperty.call(limitation, 'key')
		? limitation.key
		: endpoint.name;

	const hasShortTermLimit =
		Object.prototype.hasOwnProperty.call(limitation, 'minInterval');

	const hasLongTermLimit =
		Object.prototype.hasOwnProperty.call(limitation, 'duration') &&
		Object.prototype.hasOwnProperty.call(limitation, 'max');

	if (hasShortTermLimit) {
		min();
	} else if (hasLongTermLimit) {
		max();
	} else {
		ok();
	}

	// Short-term limit
	function min(): void {
		const minIntervalLimiter = new Limiter({
			id: `${user.id}:${key}:min`,
			duration: limitation.minInterval,
			max: 1,
			db: redisClient,
		});

		minIntervalLimiter.get((err, info) => {
			if (err) {
				return reject('ERR');
			}

			logger.debug(`@${Acct.toString(user)} ${endpoint.name} min remaining: ${info.remaining}`);

			if (info.remaining === 0) {
				reject('BRIEF_REQUEST_INTERVAL');
			} else {
				if (hasLongTermLimit) {
					max();
				} else {
					ok();
				}
			}
		});
	}

	// Long term limit
	function max(): void {
		const limiter = new Limiter({
			id: `${user.id}:${key}`,
			duration: limitation.duration,
			max: limitation.max,
			db: redisClient,
		});

		limiter.get((err, info) => {
			if (err) {
				return reject('ERR');
			}

			logger.debug(`@${Acct.toString(user)} ${endpoint.name} max remaining: ${info.remaining}`);

			if (info.remaining === 0) {
				reject('RATE_LIMIT_EXCEEDED');
			} else {
				ok();
			}
		});
	}
});