egirlskey/packages/backend/src/server/api/RateLimiterService.ts

101 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-09-17 18:27:08 +00:00
import { Inject, Injectable } from '@nestjs/common';
import Limiter from 'ratelimiter';
2023-04-14 04:50:05 +00:00
import * as Redis from 'ioredis';
2022-09-17 18:27:08 +00:00
import { DI } from '@/di-symbols.js';
2022-09-18 14:07:41 +00:00
import type Logger from '@/logger.js';
import { LoggerService } from '@/core/LoggerService.js';
import { bindThis } from '@/decorators.js';
import type { IEndpointMeta } from './endpoints.js';
2022-09-17 18:27:08 +00:00
@Injectable()
export class RateLimiterService {
2022-09-18 18:11:50 +00:00
private logger: Logger;
private disabled = false;
2022-09-18 14:07:41 +00:00
2022-09-17 18:27:08 +00:00
constructor(
@Inject(DI.redis)
private redisClient: Redis.Redis,
2022-09-18 14:07:41 +00:00
private loggerService: LoggerService,
2022-09-17 18:27:08 +00:00
) {
2022-09-18 18:11:50 +00:00
this.logger = this.loggerService.getLogger('limiter');
if (process.env.NODE_ENV !== 'production') {
this.disabled = true;
}
2022-09-17 18:27:08 +00:00
}
@bindThis
public limit(limitation: IEndpointMeta['limit'] & { key: NonNullable<string> }, actor: string, factor = 1) {
2022-09-17 18:27:08 +00:00
return new Promise<void>((ok, reject) => {
if (this.disabled) ok();
2022-09-17 18:27:08 +00:00
// Short-term limit
const min = (): void => {
const minIntervalLimiter = new Limiter({
id: `${actor}:${limitation.key}:min`,
2023-02-09 01:55:15 +00:00
duration: limitation.minInterval! * factor,
2022-09-17 18:27:08 +00:00
max: 1,
db: this.redisClient,
});
2022-09-17 18:27:08 +00:00
minIntervalLimiter.get((err, info) => {
if (err) {
return reject('ERR');
}
2022-09-18 18:11:50 +00:00
this.logger.debug(`${actor} ${limitation.key} min remaining: ${info.remaining}`);
2022-09-17 18:27:08 +00:00
if (info.remaining === 0) {
reject('BRIEF_REQUEST_INTERVAL');
} else {
if (hasLongTermLimit) {
max();
} else {
ok();
}
}
});
};
2022-09-17 18:27:08 +00:00
// Long term limit
const max = (): void => {
const limiter = new Limiter({
id: `${actor}:${limitation.key}`,
2023-02-09 01:55:15 +00:00
duration: limitation.duration! * factor,
max: limitation.max! / factor,
2022-09-17 18:27:08 +00:00
db: this.redisClient,
});
2022-09-17 18:27:08 +00:00
limiter.get((err, info) => {
if (err) {
return reject('ERR');
}
2022-09-18 18:11:50 +00:00
this.logger.debug(`${actor} ${limitation.key} max remaining: ${info.remaining}`);
2022-09-17 18:27:08 +00:00
if (info.remaining === 0) {
reject('RATE_LIMIT_EXCEEDED');
} else {
ok();
}
});
};
2022-09-17 18:27:08 +00:00
const hasShortTermLimit = typeof limitation.minInterval === 'number';
2022-09-17 18:27:08 +00:00
const hasLongTermLimit =
typeof limitation.duration === 'number' &&
typeof limitation.max === 'number';
2022-09-17 18:27:08 +00:00
if (hasShortTermLimit) {
min();
} else if (hasLongTermLimit) {
max();
} else {
ok();
}
});
}
}