0
0
mirror of https://github.com/louislam/uptime-kuma.git synced 2024-11-21 10:48:58 +01:00
uptime-kuma/server/rate-limiter.js
Matthew Nickson 8a92054c2b
Added JSDoc to ESLint (#3529)
* Added JSDoc to eslint rules

Signed-off-by: Matthew Nickson <mnickson@sidingsmedia.com>

* Fixed JSDoc eslint errors

Signed-off-by: Matthew Nickson <mnickson@sidingsmedia.com>

* Update the check-linters workflow to Node.js 20

---------

Signed-off-by: Matthew Nickson <mnickson@sidingsmedia.com>
Co-authored-by: Louis Lam <louislam@users.noreply.github.com>
2023-08-11 15:46:41 +08:00

76 lines
2.0 KiB
JavaScript

const { RateLimiter } = require("limiter");
const { log } = require("../src/util");
class KumaRateLimiter {
/**
* @param {object} config Rate limiter configuration object
*/
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 Callback function to call with decision
* @param {number} num Number of tokens to remove
* @returns {Promise<boolean>} Should the request be allowed?
*/
async pass(callback, num = 1) {
const remainingRequests = await this.removeTokens(num);
log.info("rate-limit", "remaining requests: " + remainingRequests);
if (remainingRequests < 0) {
if (callback) {
callback({
ok: false,
msg: this.errorMessage,
});
}
return false;
}
return true;
}
/**
* Remove a given number of tokens
* @param {number} num Number of tokens to remove
* @returns {Promise<number>} Number of remaining tokens
*/
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."
});
const apiRateLimiter = new KumaRateLimiter({
tokensPerInterval: 60,
interval: "minute",
fireImmediately: true,
errorMessage: "Too frequently, try again later."
});
const twoFaRateLimiter = new KumaRateLimiter({
tokensPerInterval: 30,
interval: "minute",
fireImmediately: true,
errorMessage: "Too frequently, try again later."
});
module.exports = {
loginRateLimiter,
apiRateLimiter,
twoFaRateLimiter,
};