@samitouri / QOSami-HFS / commits / 16df036f

fix: admin/logs: blocking a blocked ip caused duplication

Massimo Melina committed Feb 15, 2025 at 00:11 UTC 16df036fc67706f018210e47e31b4a6b43410326
1 file changed +10 -4
src/block.ts
+10 -4
@@ -2,8 +2,8 @@
2
3 import { defineConfig } from './config'
4 import { disconnect, getConnections, normalizeIp } from './connections'
5 -import { makeNetMatcher, MINUTE, onlyTruthy } from './misc'
6 -import { Socket } from 'net'
5 +import { makeNetMatcher, MINUTE, netMatches, onlyTruthy } from './misc'
6 +import { isIP, Socket } from 'net'
7 import _ from 'lodash'
8
9 export interface BlockingRule { ip: string, comment?: string, expire?: Date, disabled?: boolean }
@@ -22,10 +22,14 @@ export const block = defineConfig('block', [] as BlockingRule[], rules => {
22 })
23
24 export function applyBlock(socket: Socket, ip=normalizeIp(socket.remoteAddress||'')) {
25 - if (ip && block.compiled().find(rule => rule(ip)))
25 + if (ip && isBlocked(ip))
26 return disconnect(socket, 'block-ip')
27 }
28
29 +function isBlocked(ip: string) {
30 + return block.compiled().find(rule => rule(ip))
31 +}
32 +
33 setInterval(() => { // twice a minute, check if any block has expired
34 const now = new Date()
35 const next = block.get().filter(x => !x.expire || x.expire > now)
@@ -36,9 +40,11 @@ setInterval(() => { // twice a minute, check if any block has expired
40 }, MINUTE/2)
41
42 export function addBlock(rule: BlockingRule, merge?: Partial<BlockingRule>) {
43 + if (isIP(rule.ip) && isBlocked(rule.ip)) return // already
44 block.set(was => {
45 const foundIdx = merge ? _.findIndex(was, merge) : -1
46 return foundIdx < 0 ? [...was, { ...merge, ...rule }]
42 - : was.map((x, i) => i === foundIdx ? { ...x, ...rule, ip: `${x.ip}|${rule.ip}` } : x)
47 + : netMatches(rule.ip, was[foundIdx]!.ip) ? was // in case the rule is disabled, and isBlocked returned false
48 + : was.map((x, i) => i === foundIdx ? { ...x, ...rule, ip: `${x.ip}|${rule.ip}` } : x)
49 })
50 }
\ No newline at end of file