Auth / foldkit-auth

How a request is verified

Every incoming request is evaluated in four steps:

  1. Missing cookie: If no session cookie is present, the request proceeds as an anonymous visitor (Option.none()).
  2. Origin and CSRF check: Because browsers attach cookies to cross-site requests automatically, a request with a cookie must prove it came from your application. Scripted requests require a trusted Origin (or Sec-Fetch-Site: same-origin) and x-effect-auth-csrf: 1; browser requests and page navigations use origin and Fetch Metadata checks suited to their transport. Failed checks return 401, never quietly dropping to visitor.
  3. Session lookup: verifySession checks the token against your session store; an ended or revoked session returns 401.
  4. Principal mapping: principal(session) returns Option.some(user) or refuses with 401.

Why the Origin check instead of SameSite or a token

Checking browser-enforced headers at the HTTP boundary avoids issuing, storing, or rotating a separate CSRF token:

  • Origin is compared strictly against http.origin and http.trustedOrigins. When a browser omits Origin (same-origin GET) or sends Origin: null, Sec-Fetch-Site must equal same-origin. Requests with neither header are refused.
  • The CSRF header (x-effect-auth-csrf: 1) is a static marker, not a secret: scripts on a trusted origin can send it, while injected HTML forms cannot. Setting requests: 'browser' skips this header where the browser itself initiates the request (like a WebSocket upgrade or form POST).
  • SameSite=Lax is too coarse alone because every subdomain shares a site; comparing exact origins ensures sibling subdomains like user-content.app.example are trusted only when listed in trustedOrigins.

Keep your own GET endpoints read-only whenever they rely on cookie auth, so cross-site links cannot trigger side effects.

The client's side

Remote's HTTP transport posts every call, so browsers include Origin automatically; add the CSRF header in httpWithLive:

ts
import { httpWithLive } from 'foldkit-remote/live'

const transport = httpWithLive('/remote', {
  headers: () => ({ 'x-effect-auth-csrf': '1' }),
})

A 401 refusal reaches your Model as a failure; RemoteData.denied(error) from foldkit-remote classifies it as Unauthenticated with the server's reason.