package bot import ( "crypto/sha256" "encoding/hex" "strings" "sync" "time" ) // rateLimiter is a sliding window counter per key. It lives in memory: a // restart forgets it, which is fine for a limit measured in a minute. type rateLimiter struct { mu sync.Mutex hits map[string][]time.Time now func() time.Time } func newRateLimiter() *rateLimiter { return &rateLimiter{hits: map[string][]time.Time{}, now: time.Now} } // allow records a hit for key and reports whether it stays within limit // hits per window. A limit of 0 or less allows everything. func (r *rateLimiter) allow(key string, limit int, window time.Duration) bool { if limit <= 0 { return true } now := r.now() cut := now.Add(-window) r.mu.Lock() defer r.mu.Unlock() kept := r.hits[key][:0] for _, t := range r.hits[key] { if t.After(cut) { kept = append(kept, t) } } if len(kept) >= limit { r.hits[key] = kept return false } r.hits[key] = append(kept, now) // Keep the map from growing without bound. if len(r.hits) > 50_000 { for k, v := range r.hits { if len(v) == 0 || !v[len(v)-1].After(cut) { delete(r.hits, k) } } } return true } // tokenDigest returns a stable fingerprint of a bearer token, so the token // itself is never stored or logged. func tokenDigest(token string) string { sum := sha256.Sum256([]byte(strings.TrimSpace(token))) return hex.EncodeToString(sum[:16]) }