Upload files to "core"

This commit is contained in:
2026-07-24 15:38:44 +00:00
parent bfc8075396
commit 9d94ae38b9
5 changed files with 4263 additions and 0 deletions

111
core/burst_detector.py Normal file
View File

@@ -0,0 +1,111 @@
import threading
import time
from collections import defaultdict, deque
_lock = threading.Lock()
_ip_hits: dict[str, deque] = defaultdict(deque)
_global_hits: deque = deque()
_IP_WINDOW = 60
_IP_THRESHOLD = 80
_GLOBAL_WINDOW = 60
_GLOBAL_THRESHOLD = 400
_alerted_ips: dict[str, float] = {}
_ALERT_COOLDOWN = 300
_global_alerted_at: float = 0
_SKIP_PREFIXES = (
"/assets/",
"/static/",
"/alt/",
"/public/",
"/music/",
)
_SKIP_IPS = {"127.0.0.1", "::1"}
def record(ip: str, path: str) -> None:
if ip in _SKIP_IPS:
return
for prefix in _SKIP_PREFIXES:
if path.startswith(prefix):
return
now = time.monotonic()
global _global_alerted_at
with _lock:
dq = _ip_hits[ip]
dq.append(now)
while dq and now - dq[0] > _IP_WINDOW:
dq.popleft()
ip_count = len(dq)
_global_hits.append(now)
while _global_hits and now - _global_hits[0] > _GLOBAL_WINDOW:
_global_hits.popleft()
global_count = len(_global_hits)
fire_ip = (
ip_count >= _IP_THRESHOLD
and now - _alerted_ips.get(ip, 0) > _ALERT_COOLDOWN
)
if fire_ip:
_alerted_ips[ip] = now
fire_global = (
global_count >= _GLOBAL_THRESHOLD
and now - _global_alerted_at > _ALERT_COOLDOWN
)
if fire_global:
_global_alerted_at = now
if fire_ip:
_alert_ip(ip, ip_count, path)
if fire_global:
_alert_global(global_count, ip, path)
def _alert_ip(ip: str, count: int, path: str) -> None:
try:
from core.discord import send_security
send_security(
title="Request Burst — Single IP",
color=0xE74C3C,
fields=[
{"name": "IP", "value": ip, "inline": True},
{"name": "Requests / 60s", "value": str(count), "inline": True},
{"name": "Last Path", "value": path[:100], "inline": False},
],
description=f"IP `{ip}` sent **{count} requests** in the last 60 seconds.",
throttle_key=f"burst_ip_{ip}",
throttle_secs=_ALERT_COOLDOWN,
)
print(f"[BurstDetector] Alert: IP {ip} sent {count} reqs/60s on {path}")
except Exception as e:
print(f"[BurstDetector] Alert error: {e}")
def _alert_global(count: int, last_ip: str, path: str) -> None:
try:
from core.discord import send_security
send_security(
title="Request Burst — Server Wide",
color=0xC0392B,
fields=[
{"name": "Requests / 60s", "value": str(count), "inline": True},
{"name": "Last IP", "value": last_ip, "inline": True},
{"name": "Last Path", "value": path[:100], "inline": False},
],
description=f"Server received **{count} requests** in the last 60 seconds.",
throttle_key="burst_global",
throttle_secs=_ALERT_COOLDOWN,
)
print(f"[BurstDetector] Alert: global {count} reqs/60s")
except Exception as e:
print(f"[BurstDetector] Alert error: {e}")