Files
stpweb/backend/services/ratelimit.go
adamfandClaude Opus 5.5 18265871e1
Test and deploy / test (push) Successful in 16s
Test and deploy / deploy (push) Successful in 30s
Harden the chat hub, evict idle rate-limit keys, isolate Dozzle
- Chat: cap frame, message and file URL sizes, put a write deadline on
  every send so a stalled client can't hold the hub lock, and check the
  save, prune and history errors instead of broadcasting an unsaved
  message. ChatPanel's maxlength stays under the server cap.
- RateLimiter: sweep keys idle past the window, at most once a window.
- Dozzle: move to an internal dozzle-net shared only with Caddy, so the
  admin gate is the only way to reach the Docker socket.
- Drop the GraphQL WebSocket transport: the route is POST-only and the
  schema has no subscriptions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 15:15:31 +00:00

66 lines
1.5 KiB
Go

// Package services holds the backend's stateful collaborators, reached
// through handlers.Store.
package services
import (
"sync"
"time"
)
// RateLimiter is an in-memory sliding window per key, behind Caddy's limits.
type RateLimiter struct {
mu sync.Mutex
attempts map[string][]time.Time
max int
window time.Duration
lastSweep time.Time
}
func NewRateLimiter(max int, window time.Duration) *RateLimiter {
return &RateLimiter{
attempts: make(map[string][]time.Time),
max: max,
window: window,
}
}
// Allow doesn't record rejected attempts, so hammering doesn't extend a lockout.
func (rl *RateLimiter) Allow(key string) bool {
rl.mu.Lock()
defer rl.mu.Unlock()
now := time.Now()
cutoff := now.Add(-rl.window)
rl.sweep(now, cutoff)
// Filtered in place, reusing the backing array.
valid := rl.attempts[key][:0]
for _, t := range rl.attempts[key] {
if t.After(cutoff) {
valid = append(valid, t)
}
}
if len(valid) >= rl.max {
rl.attempts[key] = valid
return false
}
rl.attempts[key] = append(valid, now)
return true
}
// sweep drops keys with no attempt inside the window, at most once a window,
// so keys that are never seen again don't accumulate.
func (rl *RateLimiter) sweep(now, cutoff time.Time) {
if now.Sub(rl.lastSweep) < rl.window {
return
}
rl.lastSweep = now
for key, times := range rl.attempts {
if len(times) == 0 || !times[len(times)-1].After(cutoff) {
delete(rl.attempts, key)
}
}
}