Auth / foldkit-auth

Who the client believes it is

Because cookies are shared across browser tabs, signing in or out in one tab changes who another tab's next request answers as. Without coordination, an in-flight read in tab two could merge the new account's rows into the old account's cached Model.

Pair AuthServer.answered on the server with believing() on the client so every request echoes who the tab expects to be:

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

const resolving = { auth: AppAuth, http, principal, key: Policy.key }
serveFetch({
  server,
  resolvePrincipal: AuthServer.resolver(resolving),
  headers: AuthServer.answered(resolving), // sends `x-foldkit-subject` on each response
  layer: () => AppAuthLive,
})

// Browser: wrap fetch so Remote sends and updates the believed subject.
export const belief = believing()
httpWithLive('/remote', {
  headers: () => ({ 'x-effect-auth-csrf': '1' }),
  fetch: belief.fetch,
})
  • AuthServer.answered takes the same config plus key, writing subjectSaid(Option.some(key(user))) or 'visitor' into x-foldkit-subject (URI-encoded for Latin-1 headers).
  • believing() tracks the last confirmed subject alongside the cookie. Once the cookie resolves to someone else, the server rejects the request with SUBJECT_CHANGED (401).
  • Handling 401: Any 401 resets believing() to anonymous so subsequent reads learn the new identity. When update sees SUBJECT_CHANGED, call Remote.forget to re-fetch as the new user; for any other 401 reason (Your session ended.), prompt the user to sign in.
  • Same-tab sign-in or sign-out: Call belief.forget() in the sign-in or sign-out Command before clearing Remote state so subsequent reads succeed immediately instead of hitting one SUBJECT_CHANGED round trip.

examples/auth wires this end to end.