Appearance
std/auth
From the spec
This page is spec/std/auth.md, the specification the compiler and the backends are written from. It is rebuilt from the spec with every deploy (how).
Sign-in on top of std/http's sessions (http.md, Sessions): passwords, passkeys, email links and codes, OAuth 2.0 and OpenID Connect, the signed-in Principal with its roles, and the guards that check them. core/crates/weft-check/src/std/auth.weft declares it; the server runtime implements it (core/crates/weft-runtime/src/server/auth/). Every piece of crypto is a reviewed crate's: argon2 (passwords), webauthn-rs (passkeys), openidconnect and oauth2 (OAuth and OIDC), subtle (comparisons).
weft
import { signIn, signOut, hashPassword, verifyPassword, requireUser, requireRole } from "std/auth"
import { request } from "std/http"
export action fn logIn(name: string, password: string): boolean {
let req = request()!
let user = users.get(name)
// Unknown accounts take as long as known ones; failures are counted per account and address.
// Past the limit it fails with RateLimited, which answers the call with a 429.
if !(try await verifyPassword(req, { account: name, hash: user?.hash, password })) { return false }
try await signIn(req, { id: user!.id, name, roles: user!.roles }) // a new session, its cookie on this call's answer
return true
}
export action fn adminStats(): Stats {
try await requireRole(request(), "admin") // fails: 401 signed out, 403 without the role
return stats()
}Signing in and out
signIn(req, user: Principal): Task<void ! StoreError>: a new session holdinguser(the old one, if any, is deleted: a session id is never carried across a sign-in) whose cookie goes on whatever answersreq: a handler'sResponse, a server function's or typed endpoint's answer, a page. Every function below that starts a session (to keep a ceremony's state) sets its cookie the same way.session(req).login(user, res)is the same with the cookie onres.signOut(req): the session deleted, its cookie cleared.signOutEverywhere(req): every session of the signed-in user deleted (the store'sdeleteUser; a store without one panics), this one's cookie cleared. BothTask<void ! StoreError>.principal(req: Request?): Task<Principal? ! StoreError>: the session's user;nullwhen signed out, when the session expired or was revoked, or fornull(no request).- Every function here that reads or writes the session fails with the store's
StoreError(std/http's; the default store can't fail). - A session ends
maxAgeafter sign-in (30 days) oridleafter its last use (7 days):sessions({ maxAge, idle })instd/http. Its last use is written back at most once a minute. A session holds thePrincipalas it was at sign-in: to change a user's roles at once, sign them out everywhere.
Principal and roles
Principal = { id, name?, roles?, data? }(std/http): what the app passes tosignIn.requireUser(req: Request?): Task<Principal ! AuthError | StoreError>: the signed-in user, or it fails withUnauthorized.requireRole(req: Request?, role): the same, andForbiddenwhen the user lacksrole. In a server function, passrequest().hasRole(user: Principal?, role): boolean.- Errors answer with their status: an
Unauthorizedthat a handler, a middleware, a server function or a typed endpoint fails with is a 401,Forbiddena 403,RateLimiteda 429 (withretry-after), with the error as its body (a server function's as{ "error": … }, which its client gets as the error). A page can't fail (spec/app.md): it handles them (@await … @catch), or aguardanswers first. guard(options?: { role?: string, signIn?: Route }): Middleware: a router's routes behind sign-in (and the role): a 401 (or a redirect tosignIn, with?next=the path asked for) or a 403; otherwise the request goes on with its principal incurrentUser(currentUser.get(req), alocal<Principal>).- The bridge to
std/db(db.md): policies are evaluated for the principal a scoped handle is made for. WithPrincipalas the schema's principal type (table<Todo, Principal>(…)),db.as(try await principal(req))(in a server function,principal(request())) is the scoped handle:nullis no one signed in,owned("owner")reads itsidandrole("admin")itsroles.sessionStore(db)keeps sessions in the database, sign-out everywhere included (itsdeleteUser, by an indexeduser_id).
Passwords
hashPassword(password): Task<string ! AuthError>: an argon2id hash in the PHC format (19 MiB, 2 passes, 1 lane: OWASP's minimum), computed on an I/O thread. A password is 8 to 1,024 characters (else it fails withInvalidPassword).verifyPassword(req, { account, hash: string?, password }): Task<boolean ! AuthError>: whetherpasswordmatcheshash. Withhashnull(no such account) it checks against a fixed hash, so the answer takes as long and says onlyfalse. Failures are counted per account and per client address (clientAddress(req)) over a sliding 15 minutes: past 5 for an account or 20 for an address, attempts fail withRateLimited { retryAfter }(seconds) without checking, until the oldest failure leaves the window. A success forgets the account's failures. The counts are the process's (in memory).configure({ trustProxy?, origins?, limits? }):trustProxyreads the client's address from the lastx-forwarded-forentry (the one the proxy in front added) instead of the connection's;originsare other sites allowed to call (CSRF, below);limits: { account?, address?, window? }(windowin seconds) change the counts.
Passkeys
weft
let keys = passkeys({ rpId: "todos.example", rpName: "Todos", origin: "https://todos.example" })
export action fn addPasskeyOptions(): json { return try await keys.registerOptions(request()!, try await requireUser(request()), mine()) }
export action fn addPasskey(answer: json): void { save(try await keys.register(request()!, answer)) }passkeys({ rpId, origin, rpName?, origins?, allowAnyPort? }): Passkeys(WebAuthn level 3 throughwebauthn-rs;allowAnyPortforlocalhostin development).registerOptions(req, user, existing: Passkey[]): Task<json ! StoreError>: the options for a new discoverable passkey ofuser(user verification required;existingexcluded), to pass tocreatePasskeyin the browser. The ceremony's state stays on the server, inreq's session (started if there is none), for 5 minutes.register(req, answer: json): Task<Passkey ! AuthError | StoreError>: the browser's answer checked against that state (challenge, origin, RP id, user verification, attestation format); the state is used up either way.Passkey = { id, user, created, data }:idthe credential id (base64url),userthe principal's id,datathe public key and counter (opaquejson). The app keeps it with the user and must refuse anidit already has.signInOptions(req): Task<json ! StoreError>andsignIn(req, answer, find: (id: string) => Task<Passkey?>): Task<Passkey ! AuthError | StoreError>: a discoverable sign-in.findgives the stored passkey of the credential the browser answered with (it can't fail: a lookup that fails givesnull); the answer must be signed by it, for the challenge this session was given, by the user it was registered to. The passkey comes back with its counter updated (store it), and the app callssignInforpasskey.user. A failed check (here or inregister) fails withPasskeyFailed.- The browser side,
std/auth/client:createPasskey(options): Task<json ! PasskeyError>andgetPasskey(options): Task<json ! PasskeyError>runnavigator.credentials.create/getwith the server's options (base64url fields decoded) and give the answer as JSON for the server;passkeysAvailable(): boolean. A refusal or a cancel fails withPasskeyError = PasskeyError { message: string }(the module's). On the server they panic.
Email links and codes
email({ sender, baseUrl, path, subject?, ttl? }): EmailSignIn.senderis any{ send(message: MailMessage): Task<void ! MailError> }(MailError = MailError { message: string }, std/auth's); no provider is built in.MailMessage = { to, subject, text, link, code }.baseUrlis the site's address (links are never built from the request'sHost);ttlin seconds (15 minutes).send(req, address): Task<void ! AuthError | StoreError | MailError>: sendsaddressa link (<baseUrl><path>?token=…, 32 random bytes) and a 6-digit code. The link's token is kept hashed in the session store (auth:link:<sha-256>); the code with this session. At most 5 sends per address and 20 per client address per 15 minutes (RateLimited); the sender'sMailErrorpasses on.verifyLink(req, token): Task<string? ! StoreError>gives the address once (the token is used up), within its lifetime; any browser can open it.verifyCode(req, code): Task<string? ! StoreError>works only in the session that asked, compares in constant time, and allows 5 wrong codes before the code is gone. Using either uses up both.- The app then finds or makes the user for the address and calls
signIn.
OAuth 2.0 and OpenID Connect
oidc({ issuer, clientId, clientSecret?, redirectUri, scopes? }): any OpenID provider, found by discovery (<issuer>/.well-known/openid-configuration, kept for an hour).google({ clientId, clientSecret, redirectUri })isoidcwith Google's issuer.github({ clientId, clientSecret, redirectUri, scopes?, authorizeUrl?, tokenUrl?, apiUrl? }): GitHub's OAuth apps (not OIDC): the profile fromGET /userand the primary verified address fromGET /user/emails.provider.start(req, redirect: string?): Task<Response ! AuthError | StoreError>: a redirect to the provider with a randomstate, an OIDCnonceand a PKCE (S256) challenge, kept withreq's session for 10 minutes, as isredirect(where to go after); an OIDC provider whose discovery fails fails withOAuthFailed.provider.finish(req): Task<OAuthProfile ! AuthError | StoreError>on theredirectUriroute:statemust be the session's (once); the code is exchanged with the PKCE verifier; an ID token must verify (signature from the provider's keys, issuer, audience, expiry, nonce).OAuthProfile = { provider, subject, email?, emailVerified, name?, picture?, redirect, claims };redirectis the start's, made safe (safeRedirect). A refusal, a failed check or a provider that can't be reached (discovery, the token exchange) fails withOAuthFailed.- The app finds or makes the user for
provider+subject(trustingemailonly whenemailVerified) and callssignIn.
Errors
weft
export type AuthError =
| Unauthorized { message: string } // signed out: a 401
| Forbidden { message: string } // without the role: a 403
| RateLimited { message: string, retryAfter: number } // too many attempts (seconds to wait): a 429 with `retry-after`
| InvalidPassword { message: string } // hashPassword: not 8 to 1,024 characters
| PasskeyFailed { message: string } // a passkey's answer that doesn't check
| OAuthFailed { message: string } // a refusal, a failed check, a provider that can't be reached
export type MailError = MailError { message: string } // a `MailSender` that couldn't sendCSRF and redirects
- Cookies are
HttpOnly,SameSite=Lax, andSecurewhen the request came over HTTPS (x-forwarded-protoor theorigin), unlesssessions({ secure })says otherwise. - Server function calls need
x-weft-call: 1(a form can't send it; a script on another site can only with a CORS preflight the server accepts) and, when the browser says where the call comes from, the same origin: asec-fetch-siteother thansame-originornone, or anoriginwhose host isn't the request'shost, is a 403 unless the origin is listed inconfigure({ origins }). That also holds when acors()lets another origin read answers. - Typed endpoints' writes (
post,put,patch,delete, with an argument or without) take onlycontent-type: application/json(a 415 otherwise: a form can't send it) and the same origin check. csrf(): Middlewaregives a router's raw handlers the origin check forPOST,PUT,PATCHandDELETE; clients that send neither header (not browsers) pass. Aserver.weft's raw handler checks withcrossSite(req): boolean(if crossSite(req) { return status(403) }).safeRedirect(target: string?, fallback = "/"): string:targetwhen it is a path of this site (/…, not//…, no\, no control characters), elsefallback.
Decided here
- One module, plain functions and records of functions; the browser's half is
std/auth/client. Flows hand the app data (Passkey, an address, anOAuthProfile) and the app owns its users and callssignIn:std/authkeeps no user table. - A ceremony's state (passkey challenges, OAuth state, the email code) lives in the session, started anonymously when needed and replaced at sign-in; a state is used once (and the process refuses a second use while a store's write is in flight).
- Cookies set while serving a request go on its answer (
signInfrom a server function), so sign-in needs no raw endpoint. - The
x-weft-callheader holds against forms, but not against a sibling site with a lax CORS policy or a page on the same site; the origin check is added for both. SessionStoregrows an optionaldeleteUser(userId)(needed for sign-out everywhere) and keeps std/auth's link tokens too: astd/dbstore gives sessions and tokens one table.- Rate limits are per process and in memory: a cluster behind a balancer multiplies them.
- One
AuthErrorfor the module's own failures; the session store'sStoreErrorand the sender'sMailErrorpass on as they are.findcan't fail (a failed lookup is no passkey).