0
0
mirror of https://github.com/louislam/uptime-kuma.git synced 2024-11-28 21:32:46 +01:00
uptime-kuma/server/rate-limiter.js

68 lines
1.7 KiB
JavaScript
Raw Normal View History

2021-10-23 10:35:13 +02:00
const { RateLimiter } = require("limiter");
const { log } = require("../src/util");
2021-10-23 10:35:13 +02:00
class KumaRateLimiter {
/**
* @param {Object} config Rate limiter configuration object
*/
2021-10-23 10:35:13 +02:00
constructor(config) {
this.errorMessage = config.errorMessage;
this.rateLimiter = new RateLimiter(config);
}
/**
* Callback for pass
* @callback passCB
* @param {Object} err Too many requests
*/
/**
* Should the request be passed through
* @param {passCB} callback
* @param {number} [num=1] Number of tokens to remove
* @returns {Promise<boolean>}
*/
2021-10-23 10:35:13 +02:00
async pass(callback, num = 1) {
const remainingRequests = await this.removeTokens(num);
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;
}
/**
* Remove a given number of tokens
* @param {number} [num=1] Number of tokens to remove
* @returns {Promise<number>}
*/
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."
});
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,
twoFaRateLimiter,
2021-10-23 10:35:13 +02:00
};