File size: 2,335 Bytes
5f20dc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""Registration helpers — rate limiting, honeypot, pending cap (Phase 11)."""
import time
from threading import Lock

# ---------- In-memory rate limiter ----------
_RATE_LOCK = Lock()
_register_attempts = {}   # ip -> [timestamps]
_RATE_WINDOW = 3600       # 1 hour
_RATE_MAX = 3             # max 3 registrations per IP per hour

_PENDING_CAP = 50         # refuse new signups if this many pending

# Form must be submitted at least this many seconds after page load
MIN_FORM_AGE = 2


def check_rate_limit(ip):
    """Returns (ok, seconds_until_retry)."""
    now = time.time()
    ip = ip or "unknown"
    with _RATE_LOCK:
        bucket = _register_attempts.get(ip, [])
        bucket = [t for t in bucket if now - t < _RATE_WINDOW]
        if len(bucket) >= _RATE_MAX:
            oldest = min(bucket)
            wait = int(_RATE_WINDOW - (now - oldest)) + 1
            _register_attempts[ip] = bucket
            return False, wait
        bucket.append(now)
        _register_attempts[ip] = bucket
    return True, 0


def check_pending_cap(pending_count):
    """Returns True if new registrations are still allowed."""
    return pending_count < _PENDING_CAP


def check_honeypot(form_data):
    """Return True if honeypot field is empty (real user)."""
    val = (form_data.get("website") or "").strip()
    return val == ""


def check_timing(form_data):
    """Return True if form was submitted ≥ MIN_FORM_AGE seconds after load."""
    try:
        loaded_at = float(form_data.get("loaded_at") or 0)
    except (TypeError, ValueError):
        return False
    if loaded_at <= 0:
        return False
    return (time.time() - loaded_at) >= MIN_FORM_AGE


def password_error(pw):
    """Return error message string if password invalid, else None."""
    pw = pw or ""
    if len(pw) < 10:
        return "Password must be at least 10 characters"
    if not any(c.isdigit() for c in pw) and not any(not c.isalnum() for c in pw):
        return "Password must include a number or symbol"
    return None


def client_ip(request):
    """Best-effort client IP (behind Cloudflare / Cloud Run)."""
    h = request.headers
    for header in ("CF-Connecting-IP", "X-Forwarded-For", "X-Real-IP"):
        v = h.get(header)
        if v:
            return v.split(",")[0].strip()
    return request.remote_addr or "unknown"