fix(backend): harden security and speed up feeds and article API

Security:
- WebSocket events are routed to their owner only (no cross-user leak);
  hub close is idempotent (fixes double-close panic), adds ping/pong and
  write deadlines.
- Session tokens stored as SHA-256 (migration 008 keeps sessions valid);
  single-query auth middleware puts the user in the request context.
- Client IP only trusts X-Forwarded-For from TRUSTED_PROXIES; rate limiter
  map is bounded; per-user limit on AI summaries.
- Argon2id at OWASP minimum with a concurrency cap; constant-time login
  for unknown emails; atomic first-admin bootstrap; REGISTRATION_ENABLED.
- CSP/HSTS/COOP headers, same-origin guard on mutations, body size limits,
  wider SSRF denylist, bounded feed/page/AI response reads, generic errors.
- Upgrade chi, pgx, x/net, x/text, x/crypto (known CVEs); commit go.sum.

Performance:
- List endpoints return a plain-text excerpt and reading time instead of
  full HTML; content is sanitized once at ingest (legacy rows backfilled).
- Keyset pagination on (sort_at, id) with matching partial indexes;
  redundant indexes dropped (migration 007).
- Fetcher: bounded worker pool, conditional GET (ETag/Last-Modified),
  exponential backoff, dedupe before insert, column-safe truncation,
  retention-aware ingest, per-user refresh coalescing.
- Read/favorite/read-all are single ownership-scoped statements.
- gzip compression, immutable caching for hashed assets, path-safe SPA
  handler, server timeouts; expired sessions purged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Antigravity AgentandClaude Opus 5.5 committed 2026-10-09 07:34:08 +02:00
1 parent d037e2be34
commit 03e57e4308
40 files changed
+2231 -1898

No files matched your search

+33 -7
View File
@@ -16,6 +16,9 @@ type rateLimiter struct {
capacity float64 // max tokens (burst)
}
// maxBuckets caps the number of tracked keys per limiter.
const maxBuckets = 50_000
type bucket struct {
tokens float64
last time.Time
@@ -40,6 +43,11 @@ func (rl *rateLimiter) allow(key string) bool {
now := time.Now()
b, ok := rl.buckets[key]
if !ok {
// Bound memory: under a flood of distinct keys, fail closed rather
// than growing the map without limit.
if len(rl.buckets) >= maxBuckets {
return false
}
rl.buckets[key] = &bucket{tokens: rl.capacity - 1, last: now}
return true
}
@@ -75,14 +83,21 @@ func (rl *rateLimiter) cleanupLoop() {
// Middleware returns a chi-compatible middleware enforcing the limit per IP.
func (rl *rateLimiter) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !rl.allow(getClientIP(r)) {
return rl.middlewareBy(getClientIP)(next)
}
// middlewareBy enforces the limit per key computed from the request.
func (rl *rateLimiter) middlewareBy(key func(*http.Request) string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !rl.allow(key(r)) {
w.Header().Set("Retry-After", "60")
respondError(w, http.StatusTooManyRequests, "Too many requests. Please slow down.")
return
}
next.ServeHTTP(w, r)
})
respondError(w, http.StatusTooManyRequests, "Too many requests. Please slow down.")
return
}
next.ServeHTTP(w, r)
})
}
}
// NewAuthRateLimiter builds the limiter used for authentication routes:
@@ -90,3 +105,14 @@ func (rl *rateLimiter) Middleware(next http.Handler) http.Handler {
func NewAuthRateLimiter() func(http.Handler) http.Handler {
return newRateLimiter(10, 5).Middleware
}
// NewUserRateLimiter limits an authenticated user's calls to an expensive
// endpoint (e.g. AI summaries). Must run after RequireAuth.
func NewUserRateLimiter(perMinute, burst int) func(http.Handler) http.Handler {
return newRateLimiter(perMinute, burst).middlewareBy(func(r *http.Request) string {
if u := currentUser(r); u != nil {
return u.ID.String()
}
return getClientIP(r)
})
}