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.answeredtakes the same config pluskey, writingsubjectSaid(Option.some(key(user)))or'visitor'intox-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 withSUBJECT_CHANGED(401).- Handling
401: Any401resetsbelieving()to anonymous so subsequent reads learn the new identity. WhenupdateseesSUBJECT_CHANGED, callRemote.forgetto re-fetch as the new user; for any other401reason (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 clearingRemotestate so subsequent reads succeed immediately instead of hitting oneSUBJECT_CHANGEDround trip.
examples/auth wires this end to end.