2021-10-23 10:35:13 +02:00
|
|
|
const { RateLimiter } = require("limiter");
|
2022-04-13 17:33:37 +02:00
|
|
|
const { log } = require("../src/util");
|
2021-10-23 10:35:13 +02:00
|
|
|
|
|
|
|
class KumaRateLimiter {
|
2022-04-20 20:56:40 +02:00
|
|
|
/**
|
2023-08-11 09:46:41 +02:00
|
|
|
* @param {object} config Rate limiter configuration object
|
2022-04-20 20:56:40 +02:00
|
|
|
*/
|
2021-10-23 10:35:13 +02:00
|
|
|
constructor(config) {
|
|
|
|
this.errorMessage = config.errorMessage;
|
|
|
|
this.rateLimiter = new RateLimiter(config);
|
|
|
|
}
|
|
|
|
|
2022-04-20 20:56:40 +02:00
|
|
|
/**
|
|
|
|
* Callback for pass
|
|
|
|
* @callback passCB
|
2023-08-11 09:46:41 +02:00
|
|
|
* @param {object} err Too many requests
|
2022-04-20 20:56:40 +02:00
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Should the request be passed through
|
2023-08-11 09:46:41 +02:00
|
|
|
* @param {passCB} callback Callback function to call with decision
|
|
|
|
* @param {number} num Number of tokens to remove
|
|
|
|
* @returns {Promise<boolean>} Should the request be allowed?
|
2022-04-20 20:56:40 +02:00
|
|
|
*/
|
2021-10-23 10:35:13 +02:00
|
|
|
async pass(callback, num = 1) {
|
|
|
|
const remainingRequests = await this.removeTokens(num);
|
2022-04-13 17:33:37 +02:00
|
|
|
log.info("rate-limit", "remaining requests: " + remainingRequests);
|
2021-10-23 10:35:13 +02:00
|
|
|
if (remainingRequests < 0) {
|
|
|
|
if (callback) {
|
|
|
|
callback({
|
|
|
|
ok: false,
|
|
|
|
msg: this.errorMessage,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2022-04-20 20:56:40 +02:00
|
|
|
/**
|
|
|
|
* Remove a given number of tokens
|
2023-08-11 09:46:41 +02:00
|
|
|
* @param {number} num Number of tokens to remove
|
|
|
|
* @returns {Promise<number>} Number of remaining tokens
|
2022-04-20 20:56:40 +02:00
|
|
|
*/
|
2021-10-23 10:35:13 +02:00
|
|
|
async removeTokens(num = 1) {
|
|
|
|
return await this.rateLimiter.removeTokens(num);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const loginRateLimiter = new KumaRateLimiter({
|
|
|
|
tokensPerInterval: 20,
|
|
|
|
interval: "minute",
|
|
|
|
fireImmediately: true,
|
|
|
|
errorMessage: "Too frequently, try again later."
|
|
|
|
});
|
|
|
|
|
2023-02-15 22:53:49 +01:00
|
|
|
const apiRateLimiter = new KumaRateLimiter({
|
|
|
|
tokensPerInterval: 60,
|
|
|
|
interval: "minute",
|
|
|
|
fireImmediately: true,
|
|
|
|
errorMessage: "Too frequently, try again later."
|
|
|
|
});
|
|
|
|
|
2022-03-29 11:38:48 +02:00
|
|
|
const twoFaRateLimiter = new KumaRateLimiter({
|
|
|
|
tokensPerInterval: 30,
|
|
|
|
interval: "minute",
|
|
|
|
fireImmediately: true,
|
|
|
|
errorMessage: "Too frequently, try again later."
|
|
|
|
});
|
|
|
|
|
2021-10-23 10:35:13 +02:00
|
|
|
module.exports = {
|
2022-03-29 11:38:48 +02:00
|
|
|
loginRateLimiter,
|
2023-02-15 22:53:49 +01:00
|
|
|
apiRateLimiter,
|
2022-03-29 11:38:48 +02:00
|
|
|
twoFaRateLimiter,
|
2021-10-23 10:35:13 +02:00
|
|
|
};
|