Add rate limits

Co-authored-by: mrjvs <mistrjvs@gmail.com>
This commit is contained in:
William Oldham
2023-11-04 14:52:11 +00:00
parent 616778ab6d
commit 78b4dbd705
12 changed files with 216 additions and 11 deletions

View File

@@ -0,0 +1,24 @@
import { conf } from '@/config';
import { Limiter } from '@/modules/ratelimits/limiter';
import { connectRedis } from '@/modules/ratelimits/redis';
import { scopedLogger } from '@/services/logger';
const log = scopedLogger('ratelimits');
let limiter: null | Limiter = null;
export function getLimiter() {
return limiter;
}
export async function setupRatelimits() {
if (!conf.ratelimits.enabled) {
log.warn('Ratelimits disabled!');
return;
}
const redis = await connectRedis();
limiter = new Limiter({
redis,
});
log.info('Ratelimits have been setup!');
}

View File

@@ -0,0 +1,63 @@
import Redis from 'ioredis';
import RateLimiter from 'async-ratelimiter';
import ms from 'ms';
import { StatusError } from '@/services/error';
export interface LimiterOptions {
redis: Redis;
}
interface LimitBucket {
limiter: RateLimiter;
}
interface BucketOptions {
id: string;
window: string;
max: number;
inc?: number;
}
export class Limiter {
private redis: Redis;
private buckets: Record<string, LimitBucket> = {};
constructor(ops: LimiterOptions) {
this.redis = ops.redis;
}
async bump(req: { ip: string }, ops: BucketOptions) {
const ip = req.ip;
if (!this.buckets[ops.id]) {
this.buckets[ops.id] = {
limiter: new RateLimiter({
db: this.redis,
namespace: `RATELIMIT_${ops.id}`,
duration: ms(ops.window),
max: ops.max,
}),
};
}
for (let i = 1; i < (ops.inc ?? 0); i++) {
await this.buckets[ops.id].limiter.get({
id: ip,
});
}
const currentLimit = await this.buckets[ops.id].limiter.get({
id: ip,
});
return {
hasBeenLimited: currentLimit.remaining <= 0,
limit: currentLimit,
};
}
async assertAndBump(req: { ip: string }, ops: BucketOptions) {
const { hasBeenLimited } = await this.bump(req, ops);
if (hasBeenLimited) {
throw new StatusError('Ratelimited', 429);
}
}
}

View File

@@ -0,0 +1,7 @@
import { conf } from '@/config';
import Redis from 'ioredis';
export function connectRedis() {
if (!conf.ratelimits.redisUrl) throw new Error('missing redis URL');
return new Redis(conf.ratelimits.redisUrl);
}