HavenDOCS
Back to Home

Security & Auth Proxy

Haven implements a specialized Auth Proxy through Next.js Middleware to ensure high-performance, secure requests while minimizing database load.

The Middleware Gateway

The file middleware.ts acts as the platform's security gateway. It is responsible for:

  1. Authentication (Proxy Layer):

    • Uses Supabase Auth to verify JWTs stored in sb-access-token.
    • Injects x-user-id and x-middleware-verified headers.
    • External APIs (e.g., /api/livekit/token) trust these headers for identity, avoiding redundant database lookups.
  2. Upstash Redis Rate Limiting:

    • Every IP is tracked in Upstash Redis.
    • Global Limit: 60 requests per minute.
    • IP Hashing: Uses crypto.subtle.digest to anonymize IPs before storing them in Redis, ensuring GDPR compliance.
  3. Verification Guards:

    • v_cache: Caches the user's age and email verification status in a 1-minute v_cache cookie.
    • Prevents database over-fetching for every protected route visit.

Request Flow with Authentication

sequenceDiagram
    participant User
    participant Middleware
    participant Redis
    participant API
    participant DB

    User->>Middleware: GET /sangha
    Middleware->>Redis: Check Rate Limit (IP)
    Redis-->>Middleware: OK (Reset in Xs)
    Middleware->>Middleware: Fetch Verification Status
    Middleware->>Middleware: Verify Supabase JWT
    Middleware->>API: Next (x-user-id: UUID)
    API->>DB: Query User Data
    DB-->>API: Results
    API-->>User: Rendered Component

RLS (Row Level Security)

All database tables follow strict Row Level Security policies:

  • Profiles: Publicly readable, but only the owner can update.
  • Study Connections: Only the requester or receiver can see the relationship.
  • Sangha Roles: Managed by creators; checked via check_room_permission_internal.

Security Recommendations

  • Never Hardcode Secrets:

    • All critical keys (SUPABASE_SERVICE_ROLE_KEY, LIVEKIT_API_SECRET, UPSTASH_REDIS_REST_URL) must be in .env.
    • Middleware uses MIDDLEWARE_SECRET to sign headers and prevent spoofing.
  • Parameterized Queries:

    • All database interactions use the Supabase PostgREST client, ensuring protection against SQL injection.
    • Manual SQL functions (see scripts/) follow best practices for naming and RLS-bypass (using SECURITY DEFINER only when necessary).

Maintained by the Antigravity Security Team.