45 lines
1.0 KiB
JavaScript
45 lines
1.0 KiB
JavaScript
'use strict';
|
|
|
|
const audit = require('./auditLog');
|
|
|
|
const MAX_FAILURES = 60;
|
|
const BLOCK_MS = 60 * 60 * 1000;
|
|
|
|
const failCounts = new Map();
|
|
|
|
function getClientIp(req) {
|
|
const xff = req.headers['x-forwarded-for'];
|
|
if (xff) {
|
|
const first = String(xff).split(',')[0].trim();
|
|
if (first) return first;
|
|
}
|
|
return (req.socket && req.socket.remoteAddress) || '';
|
|
}
|
|
|
|
function isBlocked(ip) {
|
|
if (!ip || audit.isWhitelisted(ip)) return false;
|
|
const block = audit.getActiveBlock(ip);
|
|
if (!block) return false;
|
|
if (Date.now() > block.blockedUntil) {
|
|
audit.removeActiveBlock(ip);
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function recordFailure(ip) {
|
|
if (!ip || audit.isWhitelisted(ip)) return;
|
|
const count = (failCounts.get(ip) || 0) + 1;
|
|
if (count >= MAX_FAILURES) {
|
|
failCounts.delete(ip);
|
|
audit.blockIp(ip, BLOCK_MS, count);
|
|
} else {
|
|
failCounts.set(ip, count);
|
|
}
|
|
}
|
|
|
|
function reset(ip) {
|
|
if (ip) failCounts.delete(ip);
|
|
}
|
|
|
|
module.exports = { getClientIp, isBlocked, recordFailure, reset, MAX_FAILURES, BLOCK_MS }; |