You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
33 lines
576 B
JavaScript
33 lines
576 B
JavaScript
"use strict";
|
|
|
|
const net = require("net");
|
|
|
|
function normalizeAddress(address) {
|
|
let family = address.includes(":")
|
|
? "ipv6"
|
|
: "ipv4";
|
|
|
|
return (new net.SocketAddress({ address: address, family: family })).address;
|
|
}
|
|
|
|
module.exports = function createRateLimiter(cap) {
|
|
let ips = new Map();
|
|
|
|
return {
|
|
tryMark: function (ip) {
|
|
let normalized = normalizeAddress(ip);
|
|
|
|
let current = ips.has(normalized)
|
|
? ips.get(normalized)
|
|
: 0;
|
|
|
|
if (current >= cap) {
|
|
return false;
|
|
} else {
|
|
ips.set(normalized, current + 1);
|
|
return true;
|
|
}
|
|
}
|
|
};
|
|
};
|