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

+37 -58
View File
@@ -22,98 +22,76 @@ func NewUserRepository(pool *pgxpool.Pool) *UserRepository {
return &UserRepository{pool: pool}
}
// Create inserts a new user into the database.
// Create inserts a new user into the database. The very first account becomes
// admin; the decision is made atomically under an advisory lock so two
// concurrent first registrations can't both be promoted.
func (r *UserRepository) Create(user *domain.User) error {
ctx := context.Background()
// Check if this is the first user
var count int
err := r.pool.QueryRow(ctx, "SELECT COUNT(*) FROM users").Scan(&count)
tx, err := r.pool.Begin(ctx)
if err != nil {
return fmt.Errorf("counting users: %w", err)
return fmt.Errorf("starting transaction: %w", err)
}
defer tx.Rollback(ctx)
// Arbitrary constant key serialising user creation.
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(7314001)`); err != nil {
return fmt.Errorf("locking user creation: %w", err)
}
if count == 0 {
user.Role = domain.RoleAdmin
} else if user.Role == "" {
user.Role = domain.RoleUser
role := user.Role
if role == "" {
role = domain.RoleUser
}
query := `
const query = `
INSERT INTO users (id, email, password_hash, created_at, role)
VALUES ($1, $2, $3, $4, $5)
`
VALUES ($1, $2, $3, $4,
CASE WHEN NOT EXISTS (SELECT 1 FROM users) THEN 'admin' ELSE $5 END)
RETURNING role`
_, err = r.pool.Exec(ctx, query,
user.ID,
user.Email,
user.PasswordHash,
user.CreatedAt,
user.Role,
)
if err != nil {
if err := tx.QueryRow(ctx, query,
user.ID, user.Email, user.PasswordHash, user.CreatedAt, role,
).Scan(&user.Role); err != nil {
return fmt.Errorf("creating user: %w", err)
}
user.IsAdmin = user.Role == domain.RoleAdmin
return nil
return tx.Commit(ctx)
}
// GetByEmail retrieves a user by their email address.
// GetByEmail retrieves a user by their email address (case-insensitive).
func (r *UserRepository) GetByEmail(email string) (*domain.User, error) {
ctx := context.Background()
query := `
return r.getOne(`
SELECT id, email, password_hash, created_at, role
FROM users
WHERE email = $1
`
var user domain.User
err := r.pool.QueryRow(ctx, query, email).Scan(
&user.ID,
&user.Email,
&user.PasswordHash,
&user.CreatedAt,
&user.Role,
)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil // User not found
}
return nil, fmt.Errorf("getting user by email: %w", err)
}
return &user, nil
WHERE lower(email) = lower($1)`, email)
}
// GetByID retrieves a user by their ID.
func (r *UserRepository) GetByID(id uuid.UUID) (*domain.User, error) {
ctx := context.Background()
query := `
return r.getOne(`
SELECT id, email, password_hash, created_at, role
FROM users
WHERE id = $1
`
WHERE id = $1`, id)
}
func (r *UserRepository) getOne(query string, arg any) (*domain.User, error) {
var user domain.User
err := r.pool.QueryRow(ctx, query, id).Scan(
err := r.pool.QueryRow(context.Background(), query, arg).Scan(
&user.ID,
&user.Email,
&user.PasswordHash,
&user.CreatedAt,
&user.Role,
)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil // User not found
}
return nil, fmt.Errorf("getting user by ID: %w", err)
return nil, fmt.Errorf("getting user: %w", err)
}
user.IsAdmin = user.Role == domain.RoleAdmin
return &user, nil
}
@@ -134,10 +112,11 @@ func (r *UserRepository) List() ([]*domain.User, error) {
if err := rows.Scan(&u.ID, &u.Email, &u.CreatedAt, &u.Role); err != nil {
return nil, fmt.Errorf("scanning user: %w", err)
}
u.IsAdmin = u.Role == domain.RoleAdmin
users = append(users, &u)
}
return users, nil
return users, rows.Err()
}
// Delete removes a user and their data (cascaded by DB).
@@ -150,11 +129,11 @@ func (r *UserRepository) Delete(id uuid.UUID) error {
return nil
}
// Exists checks if an email already exists.
// Exists checks if an email already exists (case-insensitive).
func (r *UserRepository) Exists(email string) (bool, error) {
ctx := context.Background()
query := `SELECT EXISTS(SELECT 1 FROM users WHERE email = $1)`
query := `SELECT EXISTS(SELECT 1 FROM users WHERE lower(email) = lower($1))`
var exists bool
err := r.pool.QueryRow(ctx, query, email).Scan(&exists)