59 lines
2.2 KiB
Python
59 lines
2.2 KiB
Python
"""Клиентские ошибки: чистка PII, лимит, хранение 30 дней."""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import time
|
|
|
|
_EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
|
|
_PHONE = re.compile(r"\+?\d[\d\s().-]{8,}\d")
|
|
_TOKEN = re.compile(r"(?i)(token|password|secret|authorization)[=:]\s*\S+")
|
|
_RATE: dict[str, list[float]] = {}
|
|
MAX_PER_MIN = 10
|
|
KEEP_DAYS = 30
|
|
|
|
|
|
def scrub(text: str, limit: int = 4000) -> str:
|
|
s = str(text or "")[:limit]
|
|
s = _EMAIL.sub("[email]", s)
|
|
s = _PHONE.sub("[phone]", s)
|
|
s = _TOKEN.sub(r"\1=[скрыто]", s)
|
|
return s
|
|
|
|
|
|
def record(username: str, message: str, stack: str = "", path: str = "",
|
|
ua: str = "", ip: str = "") -> bool:
|
|
key = f"{username or 'anon'}:{ip}"
|
|
now = time.time()
|
|
arr = [t for t in _RATE.get(key, []) if now - t < 60]
|
|
if len(arr) >= MAX_PER_MIN:
|
|
_RATE[key] = arr
|
|
return False
|
|
arr.append(now); _RATE[key] = arr
|
|
import db
|
|
with db._conn() as conn:
|
|
conn.execute(
|
|
"INSERT INTO client_errors (ts, username, message, stack, path, ua, ip) "
|
|
"VALUES (?,?,?,?,?,?,?)",
|
|
(now, username or "anon", scrub(message), scrub(stack), scrub(path, 500),
|
|
scrub(ua, 500), scrub(ip, 100)))
|
|
conn.execute("DELETE FROM client_errors WHERE ts < ?",
|
|
(now - KEEP_DAYS * 86400,))
|
|
return True
|
|
|
|
|
|
def summary(days: int = 7) -> dict:
|
|
import db
|
|
days = max(1, min(int(days), 90))
|
|
cutoff = time.time() - days * 86400
|
|
with db._conn() as conn:
|
|
rows = conn.execute(
|
|
"SELECT id, ts, username, message, stack, path FROM client_errors "
|
|
"WHERE ts >= ? ORDER BY id DESC LIMIT 200", (cutoff,)).fetchall()
|
|
total = conn.execute("SELECT COUNT(*) AS n FROM client_errors WHERE ts >= ?",
|
|
(cutoff,)).fetchone()["n"]
|
|
by_day = conn.execute(
|
|
"SELECT date(ts, 'unixepoch') AS day, COUNT(*) AS n FROM client_errors "
|
|
"WHERE ts >= ? GROUP BY day ORDER BY day", (cutoff,)).fetchall()
|
|
return {"items": [dict(r) for r in rows], "total": total,
|
|
"by_day": [dict(r) for r in by_day], "days": days}
|