add diaposine
This commit is contained in:
@@ -12,6 +12,32 @@ function normalizeIp(ip) {
|
||||
return ip
|
||||
}
|
||||
|
||||
function ipToInt(ip) {
|
||||
const parts = ip.split('.')
|
||||
if (parts.length !== 4) return null
|
||||
return parts.reduce((acc, octet) => {
|
||||
const num = parseInt(octet, 10)
|
||||
if (isNaN(num) || num < 0 || num > 255) return null
|
||||
return acc !== null ? (acc << 8) + num : null
|
||||
}, 0)
|
||||
}
|
||||
|
||||
function cidrMatch(ip, cidr) {
|
||||
const slashIdx = cidr.indexOf('/')
|
||||
if (slashIdx === -1) return false
|
||||
|
||||
const baseIp = cidr.slice(0, slashIdx)
|
||||
const prefix = parseInt(cidr.slice(slashIdx + 1), 10)
|
||||
if (isNaN(prefix) || prefix < 0 || prefix > 32) return false
|
||||
|
||||
const ipInt = ipToInt(normalizeIp(ip))
|
||||
const baseInt = ipToInt(normalizeIp(baseIp))
|
||||
if (ipInt === null || baseInt === null) return false
|
||||
|
||||
const mask = prefix === 0 ? 0 : ~(2 ** (32 - prefix) - 1) >>> 0
|
||||
return (ipInt & mask) === (baseInt & mask)
|
||||
}
|
||||
|
||||
export function build403Html(ip) {
|
||||
const safeIp = ip || 'не определён'
|
||||
return `<!DOCTYPE html>
|
||||
@@ -95,7 +121,11 @@ export async function registerIpGate(fastify) {
|
||||
|
||||
if (EXCLUDED_PATHS.includes(urlPath)) return
|
||||
|
||||
if (allowedIps.includes(normalizeIp(request.ip))) return
|
||||
const normalizedIp = normalizeIp(request.ip)
|
||||
if (allowedIps.includes(normalizedIp)) return
|
||||
|
||||
const isInCidr = allowedIps.some((entry) => cidrMatch(normalizedIp, entry))
|
||||
if (isInCidr) return
|
||||
|
||||
return reply.code(403).type('text/html').send(build403Html(request.ip))
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user