package api import ( "sync" "time" ) const ( agentWSRateLimitMax = 30 agentWSRateLimitWindow = time.Minute agentWSAuthTimeout = 45 * time.Second ) type agentWSRateLimiter struct { mu sync.Mutex attempts map[string][]time.Time } var agentWSRateLim = agentWSRateLimiter{attempts: make(map[string][]time.Time)} func allowAgentWSUpgrade(clientIP string) bool { if clientIP == "" { return true } now := time.Now() cutoff := now.Add(-agentWSRateLimitWindow) agentWSRateLim.mu.Lock() defer agentWSRateLim.mu.Unlock() filtered := agentWSRateLim.attempts[clientIP][:0] for _, t := range agentWSRateLim.attempts[clientIP] { if t.After(cutoff) { filtered = append(filtered, t) } } if len(filtered) == 0 { delete(agentWSRateLim.attempts, clientIP) } if len(filtered) >= agentWSRateLimitMax { agentWSRateLim.attempts[clientIP] = filtered return false } agentWSRateLim.attempts[clientIP] = append(filtered, now) return true }