The ecosystem · packages/auth
Sign-in you don't write yourself
People sign in by a mailed link or at Google, GitHub or any OpenID Connect provider, plus a code from an authenticator app once they turn that on. Sessions live in your app's database, and middleware hands the signed-in user to your routes.
The package is a plugin that does the parts easy to get wrong: tokens kept in plain text, links that work twice, redirects to another site, OAuth without its state or PKCE. It keeps your users too. Your app keeps three things: the pages, the email the link goes out in, and admit!, which says who gets in.
A first app#
Each file below is from packages/auth/example, a small app whose tests sign in every way, on SQLite and on Postgres, against a stand-in provider.
1. The plugin and its routes. The app's header names the package; its plugin lists the providers offered. The email plugin sends the links (under --dev with no SMTP server, they land in the dev mailbox).
## packages/auth's example: an app whose people sign in by a mailed link, or at a provider, and
## whose users the package keeps (D-134: `Accounts.admit!` asks `Auth.user_for!`, after turning
## away refused.example). The plugin brings its tables (D-072), the package its handlers, which the
## app's routes in routes/auth/ call (D-116: a link and a provider coming back, the code, signing
## out, the dev sign-in), and the middleware `Middlewares` names (each group's `+middleware.roc`
## puts one around its routes). Its pages are its own: a home page that says who is signed in, a
## sign-in page (an address, the providers set up, and the dev sign-in under `--dev`), and the page
## a mailed link opens, whose button signs in (so a mail scanner that opens the link can't use it).
## An admin (`ADMIN_EMAILS`) may act as anyone for half an hour (`/impersonate`), to see the app as
## they do. Anyone may turn on two-factor sign-in (`/two-factor`: a code from an authenticator app
## after the link or the provider, or a recovery code), which `/admin` asks its admins to have;
## its secrets are sealed under a key from `APP_SECRET`. A phone app (`dev.acme.example`) signs in
## through a browser tab and a ticket back (D-144: `/auth/app/*`, the root folder's middleware). Roles (`Roles`, D-127): an admin gives
## someone Pro as a gift, for good or for days (`/roles/grant`), and ends it (`/roles/revoke`);
## anyone may start a two-week trial once (`/trial`); `/roles` lists one's grants, past ones too,
## and `/pro` is for those who hold it. What each may do is `Policy`'s (D-132), from the roles the
## middleware read once a request.
app [program] { auth: "../main.roc", crypto: "../../crypto/main.roc", email: "../../email/main.roc", pf: platform "../../../server/platform/main.roc" }
import auth.Auth
import email.Email
import Generated/App
import Accounts
program = App.program({
init!: |_started| Ok({}),
plugins: [
Email.plugin({ from: "Example <example@example.com>" }),
Auth.plugin({ providers: Accounts.providers, link_page: "/sign-in/link", refusal: "Sign in first, at /sign-in.", two_factor: Bool.True, issuer: "Auth example", apps: ["dev.acme.example:/auth/app/back"] }),
],
database: Sqlite("data/auth.db"),
})Each step of signing in is your route under routes/auth/, calling one of the package's handlers. Its folder's middleware must let a signed-out request through. Add the steps you use, and pass admit! to the ones that let someone in:
# [provider]/+server.roc: GET /auth/<provider>?then=…, off to a provider
respond! = |{ request, params, .. }| Auth.provider_route!(request, Accounts.providers, params.provider)
# [provider]/callback/+server.roc: back from it (the redirect URI to register)
respond! = |{ request, params, .. }| Auth.callback_route!(request, Accounts.providers, params.provider, Accounts.admit!)
# link/+server.roc: a mailed link
respond! = |{ request, .. }| Auth.link_route!(request, Accounts.admit!)
# code/+server.roc: a sign-in's second factor
respond! = |{ request, .. }| Auth.code_route!(request)
# sign-out/+server.roc
respond! = |{ request, .. }| Auth.sign_out_route!(request)
# dev/+server.roc: any address, under --dev only
respond! = |{ request, .. }| Auth.dev_route!(request, Accounts.admit!)2. Who gets in (admit!). Here anyone gets in but addresses at refused.example, and Auth.user_for! finds their user, or makes one:
import pf.Db
import pf.Env
import pf.Log
import pf.Time
import auth.Auth
import auth.Roles
## Who gets in (`admit!`, which the auth routes ask at every sign-in), where else one may sign in,
## who is an admin, and the roles the app gives. The users themselves are packages/auth's (D-134).
Accounts := [].{
## Where else one may sign in: the plugin's list, and routes/auth/[provider]/'s.
providers : List(Auth.Provider)
providers = [Auth.google, Auth.github]
## Who gets in: anyone with a verified address, but nobody at refused.example (the example's
## stand-in for an address an app turns away), whose attempt is written down (`turned_away`, as
## a waiting list would keep its requests). Everyone else is one of the package's users
## (`Auth.user_for!`): an identity that signed in before is its user again, a new one the user
## with its address, or a new user. It runs inside the sign-in's transaction, which commits what
## it wrote whether it lets them in or not.
admit! : Auth.Identity => Try(Str, Str)
admit! = |identity|
if identity.email.ends_with("@refused.example") {
_ = Db.run!("insert into turned_away (email, at) values ($1, $2)", [Text(identity.email), Int(Time.now_millis!({}).to_i64_wrap())])
Err("This address isn't allowed in.")
} else {
match Auth.user_for!(identity) {
Ok(user) => Ok(user)
Err(NoAddress) => Err("${identity.provider} didn't give a verified address.")
Err(DbErr(why)) | Err(BadRow(why)) => {
# Why goes on the log: the sign-in page shows what this says.
Log.error!("accounts: a user couldn't be made", { error: why })
Err("Signing in failed just now. Try again in a minute.")
}
}
}
## Whether user `id` is an admin: their address is on `ADMIN_EMAILS` (`listed!`).
admin! : Str => Bool
admin! = |id|
match Auth.user!(id) {
Ok(user) => Accounts.listed!(user.email)
Err(_) => Bool.False
}
## Whether `email` is on `ADMIN_EMAILS` (commas between). Read each time, so taking someone off
## the list ends what only an admin may do at their next request.
listed! : Str => Bool
listed! = |email| (Env.var!("ADMIN_EMAILS") ?? "").split_on(",").map(|each| each.trim().with_ascii_lowercased()).contains(email)
## What a user may hold (packages/auth's `Roles`, D-127): Pro, which the `/pro` page asks for.
Role : [Pro]
## Why they hold it: an admin's gift (`/roles/grant`), or the trial anyone may start once
## (`/trial`).
Via : [Gift, Trial]
## How long a trial lasts: two weeks.
trial_ms : I64
trial_ms = 14 * 24 * 60 * 60 * 1000
## A grant as the routes answer it: its role and reason by name, who gave it and when, when it
## ends (0: never), its note, and where it stands (`current`, `ended`, or `revoked` and by whom).
Shown : { role : Str, via : Str, by : Str, since_ms : I64, ends_ms : I64, note : Str, state : Str, revoked_by : Str }
## Every grant user `id` has had, the latest given first, as the routes show them.
grants! : Str => Try(List(Accounts.Shown), [DbErr(Str), BadRow(Str)])
grants! = |id| {
held : List(Roles.Held(Accounts.Role, Accounts.Via))
held = Roles.of!(id)?
Ok(
held.map(
|grant| {
role: (
match grant.role {
Pro => "pro"
}
),
via: (
match grant.via {
Gift => "gift"
Trial => "trial"
}
),
by: grant.by,
since_ms: grant.since_ms,
ends_ms: Roles.ends_ms(grant.ends),
note: grant.note,
state: (
match grant.state {
Current => "current"
Ended => "ended"
Revoked(_) => "revoked"
}
),
revoked_by: (
match grant.state {
Revoked(revoked) => revoked.by
_ => ""
}
),
},
),
)
}
}3. The middleware. Auth.required guards routes for signed-in people, Auth.optional routes for anyone. Each takes a function that puts the session into the context your routes read. The example's Auth.required_with also reads the user (Auth.user!) and the roles they hold (Roles.current!), once a request:
import pf.Log
import pf.Middleware
import pf.Server
import auth.Auth
import auth.Roles
import Accounts
## What requests go through, named by directory (D-103): `anyone` around the `(anyone)` group (the
## home page), `signed_in` around the `(signed-in)` group; a group adds nothing to the path. A post
## from another site's page the platform refuses first.
Middlewares := [].{
## Who a signed-in request is: the user it acts as (their id and address), its session's id, and
## who really signed in (an admin impersonating someone: `Auth.impersonate!`); the roles the user
## holds now (`Roles.current!`), and whether who really signed in is an admin (`ADMIN_EMAILS`).
## What they may do is `Policy.can`'s to say, from these.
Me : { user : Str, email : Str, session : Str, real_user : Str, roles : List(Accounts.Role), admin : Bool }
## Whether a request is signed in, for a page anyone may see.
Visitor : { signed : Auth.Signed }
## Signed-in requests only, with their user's row and roles read (`Auth.required_with`): a
## page's GET goes to the sign-in page (and comes back after), anything else is a 401; a session
## whose user is gone is ended, and answered the same. Roles that can't be read just now are a
## 503, not none: a request is never let through as someone with less than they hold.
signed_in : Middleware({}, Middlewares.Me)
signed_in = Auth.required_with(
|{}, session|
match Auth.user!(session.user) {
Ok(user) => {
held : Try(List(Accounts.Role), [DbErr(Str), BadRow(Str)])
held = Roles.current!(user.id)
match held {
Ok(roles) => {
admin = if (session.real_user == user.id) Accounts.listed!(user.email) else Accounts.admin!(session.real_user)
Ok({ user: user.id, email: user.email, session: session.id, real_user: session.real_user, roles, admin })
}
Err(DbErr(why)) | Err(BadRow(why)) => {
Log.error!("accounts: roles couldn't be read", { error: why })
Err(Answer(Server.refused(503, "Your account couldn't be read just now. Try again in a minute.")))
}
}
}
_ => Err(SignedOut)
},
)
## Anyone, signed in or not.
anyone : Middleware({}, Middlewares.Visitor)
anyone = Auth.optional(|{}, signed| { signed: signed })
}A directory's +middleware.roc wraps the routes in it. The example's signed-in routes sit in a group, routes/(signed-in)/, which adds nothing to their paths; the sign-in pages sit outside it:
import ../../Middlewares
## Signed-in requests only: a page's GET goes to sign in, anything else is a 401. The sign-in pages
## and their endpoints sit outside the groups, for anyone.
middleware = Middlewares.signed_in4. The sign-in page's endpoint, under api/ at the page's path (/api/sign-in). Auth.link! keeps a link and gives you its URL to mail as you like. Its GET, which the page reads, lists the providers set up, for their buttons:
import pf.Server
import pf.Endpoint
import pf.Log
import auth.Auth
import email.Email
## GET /api/sign-in: what the page offers besides an address: the providers set up, and whether the dev
## sign-in is open (under `--dev`).
get! : { request : Server.Request, params : {}, context : {} } => Try({ providers : List({ name : Str, label : Str, path : Str }), dev : Bool }, Endpoint.Refusal)
get! = |_| Ok({ providers: Auth.providers!({}), dev: Auth.dev_sign_in!({}) })
## POST /api/sign-in, from its form: a sign-in link mailed to `email` (packages/email: the dev mailbox
## when the server has no SMTP server), going on to `then`.
post! : { request : Server.Request, params : {}, context : {}, body : { email : Str, then : Str } } => Try({ sent : Str }, Endpoint.Refusal)
post! = |{ body, .. }|
match Auth.link!(body.email, body.then) {
Ok(url) => {
to = body.email.trim()
sent = Email.send!({
to: to,
subject: "Your sign-in link",
text: "Open this link to sign in:\n\n${url}\n\nIt works once, for the next 15 minutes. If you didn't ask for it, ignore this email.\n",
html: "<p><a href=\"${url}\">Sign in</a></p><p>It works once, for the next 15 minutes. If you didn't ask for it, ignore this email.</p>",
})
match sent {
Ok({}) => Ok({ sent: to })
Err(EmailErr(why)) => {
Log.error!("example: a sign-in link couldn't be mailed", { error: why })
Err(Status(503, "The email couldn't be sent just now. Try again in a minute."))
}
}
}
Err(NotAnAddress) => Err(BadRequest("That isn't an email address."))
Err(DbErr(why)) => Err(Failed(why))
}5. The page a link opens. With link_page, a mailed link opens your page, which shows whom it signs in and posts the link to /auth/link from a button. Some mail services open every link to check it, so a link that signed in on opening would be used up before its person clicked it.
import pf.Server
import pf.Endpoint
import auth.Auth
import auth.SignInError
## GET /api/sign-in/link?token=…: whom a mailed link signs in, while it is good, without using it (the
## page's button does, posting the token to /auth/link). Used or expired: 410.
get! : { request : Server.Request, params : {}, context : {} } => Try({ email : Str }, Endpoint.Refusal)
get! = |{ request, .. }|
match Auth.link_for!(SignInError.field(request.query, "token")) {
Ok(link) => Ok({ email: link.email })
Err(Gone) => Err(Status(410, "This sign-in link has been used, or it has expired. Ask for another."))
}import pf.Html
import pf.Router
import pf.Server
import auth.SignInError
import ../../../Generated/Api
## Where a mailed link lands: whom it signs in, and a button that does. Opening the link signs
## nobody in by itself, so a mail scanner that opens links doesn't use yours up.
meta = { title: "Sign in" }
## Whom the link signs in, or why it doesn't (used, or expired: 410).
link! : Str => Try({ email : Str }, Server.Problem)
link! = |token| Api.get_api_sign_in_link({}).with_query("token=${Server.encode_segment(token)}").send!({})
view! = |_| {
token = SignInError.field(Router.location!({}).query, "token")
<main>
{match link!(token) {
Ok(found) =>
<form method="post" action="/auth/link">
<h1>Sign in as {found.email}?</h1>
<input type="hidden" name="token" value={token} />
<button type="submit">Sign in</button>
</form>
Err(_) =>
<div role="alert">
<h1>This link has expired</h1>
<p>A sign-in link works once, for 15 minutes. <a href="/sign-in">Get a new one</a>.</p>
</div>
}}
</main>
}How signing in goes#
By a mailed link. Auth.link!(email, then) stores the link (its token's hash, the address, where it goes after, its expiry) and gives you the URL. A link works once, for 15 minutes (link_ms). Your page posts its token to /auth/link; without a link_page, the URL is /auth/link itself.
At a provider. Your button links to /auth/<provider>?then=…. The plugin keeps a state, a PKCE verifier and a nonce in a cookie for ten minutes and sends the browser to the provider. Back at /auth/<provider>/callback, the state must match this browser's. The code is traded for who signed in: an ID token (OpenID Connect), or GitHub's API.
Under --dev. POST /auth/dev with any email signs it in at once, with no mail. Without --dev the route answers 404. It is for trying the app and for its tests: never start a server others can reach with --dev.
Your own way. Auth.sign_in!(answer, user) starts a session for a user you chose yourself (a password you checked, a person picked from a list) and sets its cookie. An app may sign people in this way alone, with no link or provider routes.
The other ways end alike: admit! is asked, a session starts, and the browser goes on, with the session cookie, to where it was going. That is always a path on your site: a link or a provider can't send anyone to another site.
Who gets in#
admit! is given who is signing in, an Auth.Identity:
| Field | Is |
|---|---|
provider : Str | "email" for a link or the dev sign-in, else the provider's name |
subject : Str | who they are there: the address, or the provider's own id for them |
email : Str | their address, lower-cased; "" when the provider has none it says is verified |
name : Str | their name, or "" |
user : [New, Known(Str)] | the user this identity signed in as before, even if its address has changed since |
then : Str | where the sign-in goes after: an invite's page, say, which admit! may act on |
It answers Ok(user), their user's id (Auth.user_for! gives it), or Err(why), which the sign-in page shows. It runs inside the transaction that starts the session, so its writes commit with the session (a new user's row, a welcome email queued as a job) or with its refusal (a request to join a waiting list). A database error rolls it all back. Keep slow work, such as a request to another server, out of it.
Users#
The package keeps your users: Auth.user_for!(identity), called from admit!, gives the id of the user an identity is, and makes one if it is no one yet. An identity that signed in before is its user, and when the provider gives another address, the user's changes with it (unless another user has that address). A new identity is the user with its address, so a mailed link and Google with the same verified address are one person, or else a new user, whose id is a version 7 UUID. A new identity with no verified address is NoAddress, for you to refuse. Each user is a row of auth_users: the id, the address as it is now, when they were made, when they last signed in, and when they were last seen. Someone you name before they sign in (an invitation to their address, an admin letting them in ahead) is Auth.user_with_address!(email), made if there is none; their first sign-in finds them. An app with ids of its own from before keeps them: a returning identity whose user has no row gets one, with that id.
Auth.user_for! : Auth.Identity => Try(Str, [NoAddress, DbErr(Str), BadRow(Str), ..])
Auth.user! : Str => Try(Auth.User, [NotFound, DbErr(Str), BadRow(Str), ..]) # by id
Auth.user_by_email! : Str => Try(Auth.User, [NotFound, DbErr(Str), BadRow(Str), ..]) # by address
Auth.user_with_address! : Str => Try(Str, [NotAnAddress, DbErr(Str), BadRow(Str), ..]) # made if none
Auth.forget! : Str => Try({}, [DbErr(Str), ..]) # the user is gone
Auth.User : { id : Str, email : Str, created_ms : I64, last_signed_in_ms : I64, last_seen_ms : I64 }Keep what else you know of a person in your own tables, by that id: a profile, their organizations, what they made. Your queries may join auth_users for an address; only the package writes it. Their address stays out of your rows, so it changes in one place, and deleting a person is Auth.forget!(id) and your own rows: it ends their sessions (an admin acting as them is themselves again) and deletes their identities, links on their way, authenticator, recovery codes, grants and row, all at once. Signing in again later makes a new user.
When someone last signed in and was last seen is the package's too, on their row (last_signed_in_at and last_seen_at), for an admin's list of users or a "seen 3 days ago". Every way in sets both, but the browser tab a phone app signs in for a flow. A signed-in request through the package's middleware marks whoever is using the session (an admin impersonating someone, not them) in the server's memory, at most once every 10 seconds (seen_ms); the plugin's interval writes those marked every 10 seconds in one statement, and once more as the server stops. So a request doesn't write, and the time is at most 10 seconds behind.
Sessions and middleware#
A session is a random token in a cookie, and a database row that keeps only its SHA-256. It lasts 30 days (session_ms). Used in its second half, it is extended by as long again, so requests don't write to the database each time.
Auth.requiredlets a signed-in request through. A signed-out page goes to your sign-in page and comes back after (?then=); anything else gets a 401 with the plugin'srefusal.Auth.required_withalso reads what your routes need first (the example: the user and their roles). A session whose user is gone ends and answers as signed out; an answer of its own (the example's 503 when roles can't be read) keeps the session.Auth.optionalhands onSignedIn(session)orSignedOut.Auth.sessions!lists a user's sessions,Auth.revoke!ends one, andAuth.sign_out_everywhere!ends them all.- A form that posts to
/auth/sign-outsigns out. - Your own way in:
Auth.sign_in!(above),Auth.switch!(request, answer, user)when someone picks another person, andAuth.path!(then)for where they may go after.
Impersonation#
An admin helping someone can see the app as they do. Auth.impersonate!(request, user, ms) makes the admin's session act as that user for a while: every route sees them.
- The session stays the admin's (
session.real_user). It goes back when its time runs out or onAuth.stop_impersonating!, and each start and stop is logged with both users. - You decide who may impersonate before calling it; the example's policy allows the addresses in
ADMIN_EMAILS. - Use
real_userto record who did what, and to guard what only a person may change themselves. - No two-factor code is asked of an admin acting as someone: nobody signs in.
Roles#
What a user holds, and why: Pro because they pay, because they are on a trial, or because an admin gave it. A role is one of your own tags, and so is the reason, so a misspelt one doesn't compile. Roles is a module of the package (import auth.Roles); its table comes with the plugin.
Role : [Pro, Admin] # your own tags
Via : [Paid, Trial, Gift] # why someone holds one
Roles.grant!({ user, role: Pro, via: Gift, by: admin }) # for good
Roles.grant!({ user, role: Pro, via: Paid, by: "stripe", ends: At(period_end) })
Roles.revoke!({ user, role: Pro, via: Gift, by: admin })
Roles.has!(user, Pro) # Bool
Roles.current!(user) # [Pro]: held now
Roles.of!(user) # every grant, past ones too
Roles.forget!(user) # the user is gone- Someone holds a role while any of their grants of it lasts, one grant for each reason: a subscription that ends never takes away a gift, and a gift isn't cut short by a payment.
- Granting again while a grant lasts moves its end, so a payment that grants until the next period's end each month stays one grant. Two grants at once give one.
- Nothing is deleted but by
forget!: grants that ran out or were revoked stay, soof!can show what ended when and who ended it, and you can tell someone had a trial already (the example's/trialdoes). - You decide who may grant before calling it, as with impersonation; each grant and revoke is logged.
has!says no when the database can't be read, so what it guards stays shut. - Paid roles come from your payments: with Stripe, a function that reads the user's subscription and grants Pro until its period's end, or revokes it once it ended, run for every event about them. It reads the state, not the event, so events that come twice or out of order change nothing.
What a user may do#
Roles are stored; what a user may do is not. It is a function of your own over what the request knows: the roles its middleware read once with Roles.current!, and anything else (a list of admins, the org they act in). A route asks for an action, not the roles behind it (Policy.need(context, UsePro)?), so a rule changes in one place, and expect tests it. The example's, beside its middleware's Me (above):
import pf.Endpoint
import Accounts
## What a signed-in user may do (D-132): worked out from what the request knows of them, never
## stored. Roles are stored (`Roles.grant!`), and the middleware reads the ones held now once
## (`Roles.current!`) into `Middlewares.Me`; whether someone is an admin comes from `ADMIN_EMAILS`.
## Each check is a rule here, so a route asks for an action (`need(context, UsePro)?`), not for the
## roles behind it, and a rule that changes changes here alone.
##
## `roles` are the user the routes see (behind impersonation, the user acted as); `admin` is who
## really signed in, so what only an admin may do stays theirs while they act as someone.
Policy := [].{
## What a route asks to do: open `/pro`, see `/admin`, act as someone, give or end a grant.
Action : [UsePro, Administer, Impersonate, Grant]
## Whether `me` may do `action`.
can : { roles : List(Accounts.Role), admin : Bool, .. }, Policy.Action -> Bool
can = |me, action|
match action {
UsePro => me.roles.contains(Pro)
Administer => me.admin
Impersonate => me.admin
Grant => me.admin
}
## `can`, as a route's answer: nothing to do when `me` may, else a 403.
need : { roles : List(Accounts.Role), admin : Bool, .. }, Policy.Action -> Try({}, Endpoint.Refusal)
need = |me, action| if (Policy.can(me, action)) Ok({}) else Err(Forbidden)
}
expect Policy.can({ roles: [Pro], admin: Bool.False }, UsePro)
expect !Policy.can({ roles: [], admin: Bool.True }, UsePro)
expect Policy.can({ roles: [], admin: Bool.True }, Grant)
expect !Policy.can({ roles: [Pro], admin: Bool.False }, Impersonate)
expect Policy.need({ roles: [Pro], admin: Bool.False }, Administer).is_err()- It takes an open record,
{ roles, admin, .. }: a request's context is one, and so is a record a job builds for someone (their roles fromcurrent!). - Each action can say its own refusal: a 402 that offers Pro for one, a 404 for an admin page.
- A check about a thing is an action that carries it,
Edit(post): the route reads the post, then asks. - A folder of routes asks once, in its
+middleware.roc. Behind impersonation, the roles are the user acted as, andadminis who really signed in.
Two-factor sign-in#
With two_factor: Bool.True in the plugin's options, users may turn on two-factor sign-in. Then, after their link or provider, they enter the six-digit code their authenticator app shows (1Password, Google Authenticator, a phone's passwords app), or a recovery code. The codes are TOTP (RFC 6238), which every authenticator app makes.
Turning it on. Auth.two_factor_start!(user, account) makes a secret and gives you its otpauth:// URI, to show as a QR code (packages/qr's QrCode), and the secret as text for an app that can't scan. The first code the app shows turns it on and gives ten recovery codes, each good once in place of a code. Show them once: only their hashes are kept. The example's endpoints:
import pf.Server
import pf.Endpoint
import auth.Auth
import ../../../Middlewares
## Signed-in requests only, and the person's own: while an admin impersonates someone, these
## refuse (403), as only the person may change how they sign in.
## GET /two-factor: whether the user's two-factor sign-in is on (`state`: off, pending or on), how
## many unused recovery codes they have, and while it waits for its first code, the secret again
## (`secret`, "" otherwise), for a page shown again.
get! : { request : Server.Request, params : {}, context : Middlewares.Me } => Try({ state : Str, recovery_codes : U64, secret : Str }, Endpoint.Refusal)
get! = |{ context, .. }|
match Auth.two_factor!(context.user) {
Ok(Off) => Ok({ state: "off", recovery_codes: 0, secret: "" })
Ok(Pending) =>
match Auth.two_factor_pending!(context.user, context.email) {
Ok(pending) => Ok({ state: "pending", recovery_codes: 0, secret: pending.secret })
Err(NotPending) => Ok({ state: "off", recovery_codes: 0, secret: "" })
Err(DbErr(why)) | Err(BadRow(why)) => Err(Failed(why))
}
Ok(On({ recovery_codes, .. })) => Ok({ state: "on", recovery_codes: recovery_codes, secret: "" })
Err(DbErr(why)) | Err(BadRow(why)) => Err(Failed(why))
}
## POST /two-factor: starts turning it on: a new secret, for the authenticator app (the
## `otpauth://` URI, as a QR code, or the secret typed in), which `/two-factor/confirm` turns on
## with its first code.
post! : { request : Server.Request, params : {}, context : Middlewares.Me, body : {} } => Try({ secret : Str, uri : Str }, Endpoint.Refusal)
post! = |{ context, .. }|
if context.user != context.real_user {
Err(Forbidden)
} else {
match Auth.two_factor_start!(context.user, context.email) {
Ok(started) => Ok(started)
Err(AlreadyOn) => Err(Conflict("Two-factor sign-in is on already."))
Err(NotOffered) => Err(NotFound)
Err(DbErr(why)) | Err(BadRow(why)) => Err(Failed(why))
}
}import pf.Server
import pf.Endpoint
import auth.Auth
import ../../../../Middlewares
## POST /two-factor/confirm: the first code the authenticator app shows turns two-factor sign-in
## on, and gives the user's ten recovery codes, once.
post! : { request : Server.Request, params : {}, context : Middlewares.Me, body : { code : Str } } => Try({ recovery_codes : List(Str) }, Endpoint.Refusal)
post! = |{ context, body, .. }|
if context.user != context.real_user {
Err(Forbidden)
} else {
match Auth.two_factor_confirm!(context.user, body.code) {
Ok(codes) => Ok({ recovery_codes: codes })
Err(WrongCode) => Err(BadRequest("That isn't the code your app shows now."))
Err(NotStarted) => Err(Conflict("Start turning two-factor sign-in on first."))
Err(AlreadyOn) => Err(Conflict("Two-factor sign-in is on already."))
Err(DbErr(why)) | Err(BadRow(why)) => Err(Failed(why))
}
}Auth.two_factor_disable! turns it off and Auth.two_factor_regenerate! makes new recovery codes, each given a code the app shows now, or a recovery code.
Signing in. For a user with it on, the link or provider doesn't sign in yet: the sign-in waits ten minutes for their code, and the browser goes to your code page (code_page, /sign-in/code). Meanwhile your middleware treats them as signed out, but sends a page to the code page, not the sign-in page. The code page posts the code to /auth/code:
import pf.Html
import pf.Router
import pf.Server
import auth.SignInError
import ../../../Generated/Api
## The second step of signing in, for someone with two-factor sign-in on (the plugin's
## `code_page`): the code their authenticator app shows, or a recovery code, posted to the plugin's
## /auth/code. Plain forms, so it works before the page's JavaScript has loaded.
meta = { title: "Enter your code" }
## Whom the waiting sign-in is for, or why there is none (410).
waiting! : {} => Try({ email : Str, tries_left : U64 }, Server.Problem)
waiting! = |{}| Api.get_api_sign_in_code({}).send!({})
view! = |_| {
query = Router.location!({}).query
problem = SignInError.message(query)
<main>
{match waiting!({}) {
Ok(found) =>
<form method="post" action="/auth/code">
<h1>Enter your code</h1>
<p>Signing in as <strong>{found.email}</strong>: the code your authenticator app shows, or one of your recovery codes.</p>
{if !problem.is_empty() {
<p role="alert">{problem}</p>
}}
<input type="hidden" name="then" value={SignInError.field(query, "then")} />
<label for="code">Code</label>
<input id="code" name="code" required autocomplete="one-time-code" autocapitalize="off" spellcheck="false" />
<button type="submit">Sign in</button>
</form>
Err(_) =>
<div role="alert">
<h1>Sign in again</h1>
<p>{if (problem.is_empty()) "No sign-in is waiting for a code here." else problem} <a href="/sign-in">Sign in</a></p>
</div>
}}
<form method="post" action="/auth/sign-out">
<button type="submit">Cancel</button>
</form>
</main>
}- A code is good now or for 30 seconds either side (a phone's clock may be a little out), and works once: a used code is refused, even in time.
- A recovery code works once, and its use is logged.
- A right code starts the session under a new token, so the token the browser waited with signs no one in. A wrong one comes back with
?error=code; the fifth ends the sign-in. - A user's wrong codes also count across sign-ins, turning it off and making new recovery codes: after ten in a row, their codes are refused for 15 minutes (
TooManyTries,?error=locked).
Who must have it is yours to decide: Auth.two_factor!(user) says whether it is on, and a route that requires it refuses those without. The example's admins must have it:
import pf.Server
import pf.Endpoint
import auth.Auth
import ../../../Middlewares
import ../../../Policy
## GET /admin: for admins (`Policy`'s `Administer`: on `ADMIN_EMAILS`, as who really signed in)
## with two-factor sign-in on; an admin without it is told to turn it on (403), anyone else
## refused. Who must have it is the app's to say: the package only answers whether it is on
## (`Auth.two_factor!`).
get! : { request : Server.Request, params : {}, context : Middlewares.Me } => Try({ admin : Str }, Endpoint.Refusal)
get! = |{ context, .. }| {
Policy.need(context, Administer)?
match Auth.two_factor!(context.real_user) {
Ok(On(_)) => Ok({ admin: context.real_user })
Ok(_) => Err(Status(403, "Turn on two-factor sign-in first, at /two-factor."))
Err(DbErr(why)) | Err(BadRow(why)) => Err(Failed(why))
}
}The secret at rest is sealed with the platform's AesGcm, under a key derived from APP_SECRET (32 characters or more: openssl rand -hex 32). With two-factor on, the server won't start without it, except under --dev, where a development secret stands in. Don't change it: every authenticator's codes would stop working, and only recovery codes would sign in.
The app rocx new makes has all of it: an account-page section that sets it up with a QR code and turns it on and off, and a code page.
Providers#
Register an app with the provider using the redirect URI below, after the server's public URL (PUBLIC_URL), and give the server its client id and secret. A provider without a client id isn't offered: Auth.providers! leaves its button out.
| Provider | Needs |
|---|---|
Auth.google | GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET; redirect URI /auth/google/callback; for a phone's account sheet, an Android client too (below) |
Auth.github | GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET; callback URL /auth/github/callback |
Auth.oidc({ name, label, issuer, authorize_url, token_url, client_id_env, client_secret_env }) | any OpenID Connect provider; redirect URI /auth/<name>/callback |
A record update changes any part of one: { ..Auth.google, client_id_env: "ACME_GOOGLE_ID" }.
Phone apps#
A phone app (the native host) can't sign in at Google inside its own views, and the phone's browser doesn't share its cookies. So it signs in through a browser tab that comes back to it with a ticket, as RFC 8252 has native apps do. The phone does its half by itself: a navigation whose redirects leave your site opens a tab. Your server needs one route file, one middleware, and the app's URI:
# routes/auth/app/[step]/+server.roc
respond! = |{ request, params, .. }| Auth.app_route!(request, Accounts.providers, params.step, Accounts.admit!)
# routes/+middleware.roc
middleware = Auth.back_to_app({})
# main.roc (or AUTH_APPS where the server runs)
Auth.plugin({ providers: Accounts.providers, apps: ["dev.acme.app:/auth/app/back"] })- The app keeps a PKCE verifier and, if it is signed in, asks
POST /auth/app/transferfor a ticket that signs the tab in as the same user (connecting an account needs them). - The tab opens at
/auth/app/startwith the verifier's challenge, the app's URI and where the app was going (/auth/google), and runs that flow as any browser does. - At the first of your pages it comes back to,
back_to_appsends the tab to the app's URI with a ticket for whoever it signed in as, and ends the tab's session. - The app trades the ticket and its verifier at
POST /auth/app/exchangefor a session of its own, and goes to that page.
A ticket works once, for a minute, only with its verifier, and goes only to a URI the server lists. A transfer ticket is taken only in a tab an app opened (Chrome's android-app:// referrer, which no web page can send). The browser's own session is never handed over. Your provider and connect routes don't change, and neither do the pages a browser gets.
Google's own account sheet. On Android 14 and later, an app built with it (google=/auth/google in its android/app.properties) signs in with Google with no tab: Google's account sheet over the app. The phone asks POST /auth/app/nonce for your client id and a nonce, the sheet gives it an ID token, and it posts the token to POST /auth/app/id-token. The server checks the token's RS256 signature by Google's keys (fetched once and kept), its issuer, audience, expiry and nonce (used once), then signs in through the same admit!. A phone with no Google account, or anything else that fails, goes through the tab instead; closing the sheet stays put. In Google Cloud, beside your web client, add an Android OAuth client with the app's package and signing key's SHA-1 (the build prints both).
When it fails#
A failed sign-in goes to your sign-in page with ?error= and where it was going (&then=):
error | Means |
|---|---|
link | the link has been used or has expired (an expired one still says where it was going) |
refused | admit! said no; &reason= is what it said, &email= the address it turned away |
provider | the provider refused, couldn't be reached, or isn't set up; &reason= says which |
state | back from a provider too late, or in another browser |
unavailable | the database couldn't take it just then |
attempts | the fifth wrong code ended a sign-in waiting for its code |
locked | the user had given ten wrong codes in a row: their codes are refused for a quarter of an hour after the last |
timeout | no sign-in was waiting for a code in this browser: ten minutes went by |
app | a phone app's ticket was used, expired, or came without its verifier |
A wrong code goes back to your code page with ?error=code.
auth.SignInError words them: SignInError.message(query) gives the sentence for a sign-in page's query, and SignInError.field(query, "then") reads a field. It names no platform, so it works in the browser too.
The tables#
The plugin's migrations make its tables, the same on SQLite and Postgres: auth_sessions, auth_links (links on their way), auth_identities (which of your users each identity signed in as), and for two-factor auth_two_factor (sealed secrets), auth_recovery_codes (their hashes) and auth_waiting (sign-ins waiting for a code), auth_roles (every grant, past ones too), auth_handoffs (phone apps' tickets, by their hashes), and auth_users (your users: an id, an address, when they were made). Everything else about a person is yours, in your tables, by their id.
Safety#
- Tokens are 32 random bytes, kept only as their SHA-256: a leaked table signs no one in.
- A link is used and deleted in one statement, so two clicks can't both sign in.
- Cookies are
HttpOnlyandSameSite=Lax, and on HTTPSSecureand__Host-, so no other site under your domain can set them. - OAuth's state is compared in constant time, PKCE binds the code to the browser that asked, and the nonce binds the ID token to it. The ID token's issuer, audience and expiry are checked, and an address counts only if the provider says it is verified.
- Links in mail use the server's public URL, never a request's
Host. - An authenticator's secret is sealed (AES-256-GCM) and never kept in clear; recovery codes are 80 random bits, kept as their SHA-256.
A form on another site can't post to yours: the platform refuses it (why). Put a rate limit on your sign-in endpoint, per address and per client (its directory's +middleware.roc), so nobody can mail an address a hundred links. The app rocx new makes has it.
Status#
Everything above is built and tested. Passwords come next: they need a slow hash (Argon2) that the server's host will compute. Passkeys come later: they need the host to verify a P-256 signature, which it can make but not yet check. Both are in the package's PROPOSALS.md.