Skip to content

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 holding user (the old one, if any, is deleted: a session id is never carried across a sign-in) whose cookie goes on whatever answers req: a handler's Response, 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 on res.
  • signOut(req): the session deleted, its cookie cleared. signOutEverywhere(req): every session of the signed-in user deleted (the store's deleteUser; a store without one panics), this one's cookie cleared. Both Task<void ! StoreError>.
  • principal(req: Request?): Task<Principal? ! StoreError>: the session's user; null when signed out, when the session expired or was revoked, or for null (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 maxAge after sign-in (30 days) or idle after its last use (7 days): sessions({ maxAge, idle }) in std/http. Its last use is written back at most once a minute. A session holds the Principal as 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 to signIn.
  • requireUser(req: Request?): Task<Principal ! AuthError | StoreError>: the signed-in user, or it fails with Unauthorized. requireRole(req: Request?, role): the same, and Forbidden when the user lacks role. In a server function, pass request(). hasRole(user: Principal?, role): boolean.
  • Errors answer with their status: an Unauthorized that a handler, a middleware, a server function or a typed endpoint fails with is a 401, Forbidden a 403, RateLimited a 429 (with retry-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 a guard answers first.
  • guard(options?: { role?: string, signIn?: Route }): Middleware: a router's routes behind sign-in (and the role): a 401 (or a redirect to signIn, with ?next= the path asked for) or a 403; otherwise the request goes on with its principal in currentUser (currentUser.get(req), a local<Principal>).
  • The bridge to std/db (db.md): policies are evaluated for the principal a scoped handle is made for. With Principal as the schema's principal type (table<Todo, Principal>(…)), db.as(try await principal(req)) (in a server function, principal(request())) is the scoped handle: null is no one signed in, owned("owner") reads its id and role("admin") its roles. sessionStore(db) keeps sessions in the database, sign-out everywhere included (its deleteUser, by an indexed user_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 with InvalidPassword).
  • verifyPassword(req, { account, hash: string?, password }): Task<boolean ! AuthError>: whether password matches hash. With hash null (no such account) it checks against a fixed hash, so the answer takes as long and says only false. 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 with RateLimited { 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? }): trustProxy reads the client's address from the last x-forwarded-for entry (the one the proxy in front added) instead of the connection's; origins are other sites allowed to call (CSRF, below); limits: { account?, address?, window? } (window in 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 through webauthn-rs; allowAnyPort for localhost in development).
  • registerOptions(req, user, existing: Passkey[]): Task<json ! StoreError>: the options for a new discoverable passkey of user (user verification required; existing excluded), to pass to createPasskey in the browser. The ceremony's state stays on the server, in req'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 }: id the credential id (base64url), user the principal's id, data the public key and counter (opaque json). The app keeps it with the user and must refuse an id it already has.
  • signInOptions(req): Task<json ! StoreError> and signIn(req, answer, find: (id: string) => Task<Passkey?>): Task<Passkey ! AuthError | StoreError>: a discoverable sign-in. find gives the stored passkey of the credential the browser answered with (it can't fail: a lookup that fails gives null); 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 calls signIn for passkey.user. A failed check (here or in register) fails with PasskeyFailed.
  • The browser side, std/auth/client: createPasskey(options): Task<json ! PasskeyError> and getPasskey(options): Task<json ! PasskeyError> run navigator.credentials.create/get with the server's options (base64url fields decoded) and give the answer as JSON for the server; passkeysAvailable(): boolean. A refusal or a cancel fails with PasskeyError = PasskeyError { message: string } (the module's). On the server they panic.
  • email({ sender, baseUrl, path, subject?, ttl? }): EmailSignIn. sender is 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 }. baseUrl is the site's address (links are never built from the request's Host); ttl in seconds (15 minutes).
  • send(req, address): Task<void ! AuthError | StoreError | MailError>: sends address a 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's MailError passes 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 }) is oidc with Google's issuer. github({ clientId, clientSecret, redirectUri, scopes?, authorizeUrl?, tokenUrl?, apiUrl? }): GitHub's OAuth apps (not OIDC): the profile from GET /user and the primary verified address from GET /user/emails.
  • provider.start(req, redirect: string?): Task<Response ! AuthError | StoreError>: a redirect to the provider with a random state, an OIDC nonce and a PKCE (S256) challenge, kept with req's session for 10 minutes, as is redirect (where to go after); an OIDC provider whose discovery fails fails with OAuthFailed.
  • provider.finish(req): Task<OAuthProfile ! AuthError | StoreError> on the redirectUri route: state must 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 }; redirect is the start's, made safe (safeRedirect). A refusal, a failed check or a provider that can't be reached (discovery, the token exchange) fails with OAuthFailed.
  • The app finds or makes the user for provider + subject (trusting email only when emailVerified) and calls signIn.

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 send

CSRF and redirects ​

  • Cookies are HttpOnly, SameSite=Lax, and Secure when the request came over HTTPS (x-forwarded-proto or the origin), unless sessions({ 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: a sec-fetch-site other than same-origin or none, or an origin whose host isn't the request's host, is a 403 unless the origin is listed in configure({ origins }). That also holds when a cors() lets another origin read answers.
  • Typed endpoints' writes (post, put, patch, delete, with an argument or without) take only content-type: application/json (a 415 otherwise: a form can't send it) and the same origin check.
  • csrf(): Middleware gives a router's raw handlers the origin check for POST, PUT, PATCH and DELETE; clients that send neither header (not browsers) pass. A server.weft's raw handler checks with crossSite(req): boolean (if crossSite(req) { return status(403) }).
  • safeRedirect(target: string?, fallback = "/"): string: target when it is a path of this site (/…, not //…, no \, no control characters), else fallback.

Decided here ​

  1. One module, plain functions and records of functions; the browser's half is std/auth/client. Flows hand the app data (Passkey, an address, an OAuthProfile) and the app owns its users and calls signIn: std/auth keeps no user table.
  2. 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).
  3. Cookies set while serving a request go on its answer (signIn from a server function), so sign-in needs no raw endpoint.
  4. The x-weft-call header 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.
  5. SessionStore grows an optional deleteUser(userId) (needed for sign-out everywhere) and keeps std/auth's link tokens too: a std/db store gives sessions and tokens one table.
  6. Rate limits are per process and in memory: a cluster behind a balancer multiplies them.
  7. One AuthError for the module's own failures; the session store's StoreError and the sender's MailError pass on as they are. find can't fail (a failed lookup is no passkey).

Weft is in development. The reference is the spec as it stands today.