Files
url-shortener-public/functions/utilities/ratelimit.js
T
2023-11-03 21:12:55 +01:00

48 lines
2.0 KiB
JavaScript

const crypto = require('crypto');
module.exports = {
name:"ratelimit",
async function(req){
return new Promise(async (resolve,reject) => {
// If developer key has been sent, skip ratelimiter
if(req.headers.devkey){if(req.headers.devkey == config.ratelimit.devKey){resolve();return}}
// If user is banned already, reject with code 3 (ignore)
let bh = false
await commands.get("banHandler").check(req).catch(err => {reject(3);bh=true})
if(bh){return}
if(!config.ratelimit.enabled){
resolve()
return
}
let hash = req.headers["cf-connecting-ip"] == undefined ? crypto.createHash('md5').update("localhost").digest('hex') : crypto.createHash('md5').update(req.headers["cf-connecting-ip"]).digest('hex')
if(ratelimit[hash] == undefined){
// Everything is fine
ratelimit[hash] = [new Date().getTime()+1000,0]
resolve()
return
}
else{
if(ratelimit[hash][0] > new Date().getTime()){
ratelimit[hash][1] = ratelimit[hash][1] + 1
if(ratelimit[hash][1] >= config.ratelimit.hitsUntilBan){
// User gets banned now, reject with code 2 (tell user about the ban)
commands.get("banHandler").ban(req)
reject(2)
console.log(`${new Date()}: Banning ${hash}`);
return
}
// User hits ratelimit, reject with code 1 (tell user about the hit)
reject(1)
// console.log(`Rate Limiting ${hash}`);
return
}else{
// Everything is fine
ratelimit[hash][0] = new Date().getTime()+1000
resolve()
return
}
}
})
}
}