Add centralized constants module and .env configuration support

This commit is contained in:
zwitschi committed 2026-08-05 19:33:12 +02:00
1 parent 94be1da199
commit eea5ef6885
14 files changed
+334 -126

No files matched your search

+15 -17
View File
@@ -9,22 +9,23 @@ import os
import re
from typing import Iterable
from .ip_utils import ip_version, parse_ip
# WHOIS Cache file path
_WHOIS_CACHE_PATH = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))
), "data", "whois_cache.json"
from .constants import (
SUBNET_THRESHOLD,
WHOIS_CACHE_PATH,
WHOIS_PORT,
WHOIS_SERVER,
WHOIS_TIMEOUT,
)
from .ip_utils import ip_version, parse_ip
_whois_cache: dict[str, str] = {}
def load_whois_cache() -> None:
global _whois_cache
if not _whois_cache and os.path.exists(_WHOIS_CACHE_PATH):
if not _whois_cache and os.path.exists(WHOIS_CACHE_PATH):
try:
with open(_WHOIS_CACHE_PATH, "r", encoding="utf-8") as f:
with open(WHOIS_CACHE_PATH, "r", encoding="utf-8") as f:
_whois_cache = json.load(f)
except Exception:
_whois_cache = {}
@@ -32,9 +33,9 @@ def load_whois_cache() -> None:
def save_whois_cache() -> None:
if _whois_cache:
os.makedirs(os.path.dirname(_WHOIS_CACHE_PATH), exist_ok=True)
os.makedirs(os.path.dirname(WHOIS_CACHE_PATH), exist_ok=True)
try:
with open(_WHOIS_CACHE_PATH, "w", encoding="utf-8") as f:
with open(WHOIS_CACHE_PATH, "w", encoding="utf-8") as f:
json.dump(_whois_cache, f, indent=2)
except Exception:
pass
@@ -53,8 +54,8 @@ def query_whois_subnet(ip: str) -> str | None:
import socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3.0)
s.connect(("whois.radb.net", 43))
s.settimeout(WHOIS_TIMEOUT)
s.connect((WHOIS_SERVER, WHOIS_PORT))
s.sendall(f"{ip}\r\n".encode())
res = ""
while True:
@@ -89,7 +90,8 @@ def query_whois_subnet(ip: str) -> str | None:
return subnet_str
def consolidate_by_subnet(ips: Iterable[str], threshold: int = 3) -> set[str]:
def consolidate_by_subnet(ips: Iterable[str],
threshold: int = SUBNET_THRESHOLD) -> set[str]:
"""Group IPs by WHOIS subnet; if >= threshold IPs in a subnet, block the subnet.
Otherwise, block individual IPs.
@@ -124,7 +126,3 @@ def consolidate_by_subnet(ips: Iterable[str], threshold: int = 3) -> set[str]:
f"{ip}/32" if ip_version(ip) == 4 else f"{ip}/128")
return blocked_targets
# Re-export path for backward compat
WHOIS_CACHE_PATH = _WHOIS_CACHE_PATH