Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

auth-chad

Summary: what auth-chad is, what it is for, what it is not for, and where to start.
Key terms: passkey, device key, first-party, connected app, authentication, authorization.
Related: Concepts · Map · Recipes

auth-chad is a Rust authentication library that runs inside your application and stores its data in your database. People sign in with passkeys, which are bound to the site and resist phishing. Programs such as CLIs, servers and build jobs sign in with device keys that a person approves once. Other companies’ apps get short, scoped tokens through OAuth after the user consents.

auth-chad establishes who made a request and how recently they proved it. Your application decides what that person may do.

The picture as text
flowchart LR
    P[Person with a passkey] --> A
    M[Program with a device key] --> A
    O[Another company's app, with consent] --> A
    A[Your application<br/>with auth-chad inside] --> D[(Your database:<br/>users and your data)]

What it is for

You wantauth-chad gives
Accounts with passkeysSignup, login, more passkeys, logout, and a fresh passkey check before a risky action
Only invited peopleInvite-only signup, with your own data on the invite
A CLI or a server that acts for a person, or as itselfDevice login (approved in the browser) and machine keys
Other apps (for example an AI assistant) that read data for a userOAuth with consent, short tokens, limited scopes
A way back after a lost phoneA recovery key, recovery by tenant owners, or email (unavailable with end-to-end encryption)
Organizations with membersTenants and memberships, with your own columns such as a role
Data that the server must not readEnd-to-end encryption keys that only a passkey or the recovery key can open
Growth from one machine to manyThe same program on one process or many; see Scaling

What it is not for

Not forReason and alternative
Password logins, SMS codes, authenticator-app codesThey can be phished or copied. A password can be checked once, to move an old account to a passkey
Login links sent by emailWhoever controls the mailbox controls the account
“Log in with another company” as the only proofThat company would control the account. auth-chad accepts it as extra proof of identity only
Roles, permissions, sharing rulesThese are authorization. Your application decides them with its own data
A hosted login serviceauth-chad runs inside your program, on your database
SAML, old OAuth grants, a choice of algorithmsEach adds attack surface or allows downgrade attacks. There is one strict profile
Servers in many regions that cannot reach the users’ databaseUnsupported; see Scaling

Where to start

You areRead
New to the projectConcepts: the model and the vocabulary
Adding auth-chad to an applicationRecipes, starting with start
Changing auth-chadMap, Data, Flows, Interfaces, then the spec
A coding agentINDEX.md, then one recipe or page
Reviewing the securityThreats and the spec
Planning hostingScaling

Getting started

cd rust && cargo run -p example-minimal   # a whole application with passkeys, on http://localhost:3000
[dependencies]
auth-chad = { git = "https://github.com/audiochad/auth-chad", rev = "<commit>", features = ["axum", "sqlite"] }
  • Status: before a first release. The Rust crates work and are tested. No external security review has happened yet; values marked † in the spec need that review.
  • The core rule: login is proof of a key. Anything that can be copied must be short-lived, single-use or limited.
  • Exact rules: the spec is the contract. Where this wiki and the spec differ, the spec is correct.
  • Decisions and their reasons: decisions.
  • MIT license.

Concepts

Summary: the model behind auth-chad in seven ideas, and the vocabulary that the code and the spec use.
Key terms: flow, decision, write, commit, Authenticated, tenant, realm, policy, DPoP, ceremony, envelope.
Related: Data · Flows · Interfaces · spec 01

Every account change in auth-chad follows the same pattern. A pure function, called a flow, reads the database and returns a decision: the result plus the list of rows to write. The application commits those rows in one transaction, and only then is the result real. Every request carries a key proof, and the library alone turns a valid proof into an Authenticated value that handlers can use. Configuration can make the rules stricter and has no setting that weakens them.

The seven ideas

1. Login is proof of a key

A person proves a passkey. A program proves a device key. A browser session or an app signs every request with its session key (DPoP). A copied database row, log line or token cannot log anyone in.

2. A flow decides, the application commits

Each step (signup, login, device approval) is a flow: a function that reads, applies the rules and returns a decision. A decision has an output and a list of writes. The writes are committed together in one transaction, and the output is valid only after that commit succeeds. The application can add its own writes to the same transaction.

use auth_chad::{Decision, Store};

async fn finish<S: Store, T>(store: &S, decision: Decision<T>) -> Result<T, auth_chad::Error> {
    store.commit(decision.writes).await?; // all or nothing
    Ok(decision.out)                      // valid only after the commit
}

3. Every write has a condition

Another request can change a row between the read and the commit. Each write therefore states what it expects: “no row with this key exists”, or “the row is still at version 7”. If any condition fails, the commit stores nothing and the request fails with conflict. When two requests use the same single-use token, exactly one succeeds.

4. Only the library makes a proof

When a request passes the checks, the library creates an Authenticated value. It records who the caller is, the tenant, the client level (first-party, connected app or API key), the key, and the last passkey use. Application code cannot construct one. A handler declares in its signature what it needs, and requests that lack it are rejected before the handler runs.

use auth_chad::axum::{FirstParty, FreshLogin, Refused};

async fn notes(who: FirstParty) -> Result<String, Refused> {
    Ok(format!("notes of {}", who.user()?))
}

async fn delete_account(_fresh: FreshLogin<300>) -> &'static str {
    "the passkey was used in the last 5 minutes"
}

5. Two levels of client

First-partyConnected app
WhoYour own web app, apps, CLIs and machinesOther companies’ apps, with the user’s consent
TokenBound to a key, or a secure cookie for page loadsShort-lived, one audience, limited scopes
May change passkeys, sessions or recoveryYes, after a fresh loginNo

6. Rules only get stricter

One profile fixes the algorithms, checks and upper limits. An instance, a tenant and a route can each add a policy. Policies combine, and the strictest value wins. No setting turns a check off.

7. All effects come from outside

Time, random bytes, storage, network and mail reach the library through traits. The library writes no logs. It returns audit events as writes in the same commit, so a change cannot be stored without its event. Every flow can be tested with a fake clock and fake random bytes.

Where the details are

  • The exact model (realms, tenants, users, credentials, proofs, policies): spec 01.
  • The contract of a flow (protected reads, writes, single use, effects, audit): spec 02.
  • Authenticated and its fields: rust/formats/core/src/proof.rs. Decision and Write: rust/formats/core/src/store.rs.
  • The reasons for the strict rules: decision 001.

Glossary

TermMeaningIn the code
RealmOne set of users, one passkey domain (RP ID), one login originConfig
TenantAn organization or customer inside a realm. Each session belongs to one tenant. Without tenants, everything is in the root tenantTenant, Tenant::ROOT
MembershipPermission for a user to enter a tenant, with your own columns such as a roleMembership, Member
PasskeyA key on a person’s device, checked with WebAuthnPasskey row, passkey flow
Device keyA key that a CLI, app or machine holds. A user device acts as its user; a machine acts as itselfDevice, Subject::Machine
SessionA lasting login: a cookie for page loads, or a key-bound tokenSession
DPoPDemonstration of Proof of Possession: the client signs each request with the session’s key, so a stolen token is useless alonedpop crate
Fresh loginA passkey use within the last few minutes. Risky actions require itFreshLogin<SECS>, step_up_required
First-partyYour own clientsLevel::FirstParty, FirstParty
Connected appAnother company’s app that a user allowedLevel::Connected, ConnectedApp
API keyA secret for a program that can only send a header. Off by default and discouragedApiKey
FlowA function that decides one step and does no I/Ocrates in rust/flows/
DecisionWhat a flow returns: an output and writesDecision { out, writes }
WriteA row change with a conditionWrite
CommitStoring a list of writes, all or nothingStore::commit
CeremonyA two-request step (start, finish) whose state travels in a sealed tokenceremony_invalid
PolicyExtra requirements; the strictest value winsPolicy
HookA point where your application decides or adds its own writesHooks
EventAn audit row for each change to an accountEvent
OutboxWork that runs after a commit, such as sending mail, at least onceOutbox, work
PlaceThe location of a tenant’s or user’s data when it is outside the users’ databasePlace, Placement
EnvelopeAn encrypted copy of an end-to-end encryption secret that one passkey (PRF) or the recovery key opensEnvelope
Recovery keyA long random key that the person stores, used to regain accessRecoveryKey
HoldA period after a recovery when old passkeys cannot be removed, so the owner can undo a thefthold_until
ProfileThe fixed set of algorithms and limits of a releaseAC1 in the spec
†A proposed value that needs a security reviewspec

Map

Summary: how the repository and the Rust crates are laid out, which crate may depend on which, and where to make a change.
Key terms: formats, flows, adapters, crate, feature, no_std, dependency rule.
Related: Interfaces · Data · AGENTS.md

The Rust code has three layers. Formats parse and verify signatures, keys and tokens. Flows apply the authentication rules to the rows they read and return decisions; they do no I/O. Adapters connect the flows to a database, a web framework and the system clock. Dependencies point downward only, so every rule can be tested without a database or a network.

The picture as text
flowchart TB
    subgraph adapters [Adapters: all I/O]
        axum[axum: HTTP API]
        sqlite[sqlite]
        postgres[postgres]
        seaorm[sea-orm]
    end
    subgraph flows [Flows: decisions, no I/O]
        signup
        passkey
        session
        device
        recovery
        more[tenant, place, provider, oidc, e2ee, api-key]
    end
    subgraph formats [Formats: parse and check]
        core
        webauthn
        dpop
        jose
        keys
    end
    adapters --> flows --> formats
    adapters --> formats

The repository

FolderContents
spec/The exact rules. Change it in the same commit as the behavior
schema/Reference SQL for SQLite and PostgreSQL: the core tables and each optional feature
docs/wiki/This wiki
docs/recipes/One page per task. Their Rust code compiles
docs/decisions/Decisions and their reasons
skills/Instructions for coding agents that add auth-chad to an application
rust/The Rust workspace
rust/loco/A separate workspace: the Loco adapter and an example

The crates

CrateLayerJob
auth-chad-coreformatShared types: IDs, rows and tables, writes and decisions, Authenticated, policies, errors, shared state (single-use marks, limits, leases), SQL text
auth-chad-keysformatES256, Ed25519 and RS256 keys, JWK, thumbprints
auth-chad-webauthnformatVerifies passkey registrations and assertions
auth-chad-joseformatA strict subset of JWS, JWK and JWT
auth-chad-dpopformatDPoP proofs and nonces
auth-chad-signupflowOpen, invite-only and external signup
auth-chad-passkeyflowRegister, log in, add and remove passkeys
auth-chad-sessionflowCookie or key-bound sessions, renewal, fresh login, logout, entering a tenant
auth-chad-tenantflowTenants and memberships
auth-chad-placeflowThe location of a tenant’s or user’s data
auth-chad-recoveryflowRecovery key, tenant owners, email
auth-chad-deviceflowDevice login (RFC 8628) and machine keys
auth-chad-api-keyflowAPI keys (optional, discouraged)
auth-chad-oidcflowIdentity proof from another provider
auth-chad-providerflowOAuth for first-party and connected apps
auth-chad-e2eeflowEnd-to-end encryption: identity secrets, envelopes, recovery
auth-chad-sqliteadapterStore on SQLite
auth-chad-postgresadapterStore on PostgreSQL
auth-chad-sea-ormadapterStore on the application’s SeaORM connection
auth-chad-axumadapterThe HTTP API, extractors, hooks, the worker, the browser script
auth-chadfacadeRe-exports the crates by feature. Applications depend on this crate
auth-chad-clientclientThe account API from a CLI, or from wasm in a browser (feature browser)
auth-chad-clitoolThe auth-chad command: schema, features, memberships, after-restore, doctor, docs
auth-chad-testingtestA memory store, a fake clock, fake random bytes, a software authenticator, storage tests
auth-chad-flow-teststestAll flows together
auth-chad-recipestestCompiles the Rust code in the recipes and in this wiki
example-minimalexampleA whole application with passkeys
auth-chad-locoadapterLoco integration (in rust/loco/)
example-locoexampleA Loco application with auth-chad (in rust/loco/)

Dependency rules

  1. formats depend on formats only. flows depend on formats. Adapters depend on both.
  2. A flow depends on no other flow, with these exceptions: signup and recovery use passkey; recovery and tenant use session to end sessions. Shared types are in core.
  3. formats and flows are no_std with alloc: no async runtime, clock, randomness or environment.
  4. Only adapters name a database, a web framework or an async runtime.
  5. No crate knows an application’s domain.

Features of the auth-chad crate

auth-chad = { git = "https://github.com/audiochad/auth-chad", rev = "<commit>", features = ["axum", "postgres"] }
FeatureAdds
passkey, session, signupThe default
tenant, place, recovery, device, provider, oidc, api-key, e2eeOne flow each
sqlite, postgres, sea-ormA store
axumThe HTTP API, with every flow it needs
clientThe Rust client
rs256-signRS256 ID tokens for the provider

Where to make a change

ChangePlace
A table or columnrust/formats/core/src/rows.rs, then AUTH_CHAD_BLESS=1 cargo test -p auth-chad-sqlite -p auth-chad-postgres
A limit or a policyrust/formats/core/src/{config,policy}.rs
A login, session or OAuth rulerust/flows/*
An HTTP route, extractor or hookrust/adapters/axum/src
A refusal coderust/formats/core/src/error.rs and rust/adapters/axum/src/error.rs
A task pagedocs/recipes/, and add it to rust/recipes/src/lib.rs

Code rules

  • Pure functions. Side effects go behind traits, used through generics instead of dyn.
  • Borrow before owning: &str before String.
  • No logging, no unsafe, no unwrap outside tests, no comments that repeat the code.
  • Tests run in parallel and need no network.
  • A new dependency needs a reason in the pull request. Never write cryptography.

Tests

TestCovers
Official vectors, Wycheproofformats
Unit and property tests with a fake clockEvery flow
Storage conformance (auth-chad-testing::conformance)Every store
HTTP tests (rust/adapters/axum/tests)Every route
Browser tests with a virtual authenticatorexample-minimal, the Loco example
Compiled recipes and wikiauth-chad-recipes

All crates share one version and release together. Before 1.0, an application pins a commit.

Data

Summary: the tables that auth-chad keeps, the types that carry a request through the code, and how a row becomes a write.
Key terms: row, table, version, Stored, Write, Decision, Authenticated, Ctx, hash at rest, prefix, feature.
Related: Flows · Interfaces · spec 10

auth-chad stores its data in ordinary tables in your database, prefixed with auth_. Each row has a version that increases with every change, and every write names the version it expects. Tokens, invites and codes are stored as hashes, and keys are stored as public keys. A copy of the database is therefore not enough to log in.

The picture as text
erDiagram
    users ||--o{ passkeys : has
    users ||--o{ sessions : has
    users ||--o{ devices : approved
    users ||--o| recovery_keys : has
    users ||--o{ envelopes : "e2ee only"
    sessions ||--o{ tokens : issues
    devices ||--o{ tokens : issues
    tenants ||--o{ memberships : has
    users ||--o{ memberships : has
    users ||--o{ events : "audit"

The tables

People and their credentials

TableOne row isNotes
usersA userID (16 bytes), optional handle or address, disabled, recovery hold. Names and profiles belong in your tables
passkeysA passkeyPublic key (COSE), sign counter, last use
recovery_keysA recovery keyOnly the public verifier derived from the key
identitiesAn account at another providerProof of identity; it cannot log in
envelopesAn encrypted copy of the e2ee secretOne per passkey (PRF) and one for the recovery key

Lasting logins

TableOne row isNotes
sessionsA loginTenant, kind (browser, cookie, native), key thumbprint, last passkey use, expiry
tokensAn access, cookie, refresh or connected-app tokenStored as a hash. A used refresh token stays, so reuse is detected
devicesAn approved CLI, app or machinePublic key, kind (user or machine), scope, your data
device_requestsA device waiting for approvalUser code (hash), address, state
api_keysAn API keyHash, scopes, expiry (at most 90 days)

Other companies’ apps

TableOne row isNotes
clientsA connected appRedirect URIs, keys
grantsA user’s consent to an appScope, audience, the key it is bound to
codesAn authorization code, a pushed request, or a code to enter a tenantHash, single use

Account recovery

TableOne row isNotes
recoveriesA pending recovery (email or owners)Hash, ready time, expiry
invitesAn inviteHash, optional identifier, your data

Bookkeeping

TableOne row isNotes
eventsAn audit eventTime, user, device, action, target, address. No secrets or names
outboxWork after a commit, such as a mailRetried until it succeeds, at most five times
usedA single-use markThe hash of a used challenge or proof
limitsOne counted call for a rate limitExpires after one minute
leasesThe process that currently owns a piece of workPrevents two processes from sending the same mail
featuresAn optional group of tables that this database hastenants, places

Optional features

TableFeatureOne row is
tenantstenantsAn organization or customer, with its tag for a host or path
membershipstenantsA user who may enter a tenant, plus your own columns
placesplacesThe location of a tenant’s or user’s data

Run auth-chad schema sqlite --with tenants to print the SQL.

The types that carry a request

TypeHoldsCreated by
CtxThe current time, the tenant, the config and keys, the caller’s address and deviceThe adapter, once per request
Stored<T>A row and its versionThe store, on a read
WriteA change with its conditionA flow, or your code
Decision<T>out and writesA flow
AuthenticatedWho, tenant, level, binding, session, device, last passkey use, scopesThe library only
RefusedA refusal code, sent as {"error": "<code>"}Extractors and routes
use auth_chad::core::rows::Session;
use auth_chad::core::row::Field;
use auth_chad::core::StoreError;
use auth_chad::{Reader, UserId};

async fn count_sessions<R: Reader>(db: &R, user: UserId) -> Result<usize, StoreError> {
    let rows = db.find_by::<Session>("user", user.store()).await?;
    Ok(rows.len()) // each item is a Stored<Session>: the row and its version
}

From a row to a write

A read returns Stored<T>. Each write that depends on that read names its version.

WriteConditionUse
Write::insert(row)No row with this key or unique value existsNew rows
stored.replace(row)The row is still at this versionChanges
stored.delete()The row is still at this versionRemovals
stored.require()The row is still at this version; nothing changesA decision depends on the row
stored.touch()Like replace with the same rowTwo commits that depend on the row cannot both succeed
Write::delete_where::<T>(column, value)NoneClean-up, such as ending all sessions of a user

Rules for rows

  • Each table is declared once, with the table! macro in rust/formats/core/src/rows.rs. The SQL for SQLite and PostgreSQL is generated from that declaration.
  • User, tenant, session and device IDs are 16 bytes. Your application maps its own IDs to them.
  • Every tenant-scoped read takes the tenant as an argument. There is no form without it.
  • The prefix (auth_ by default) is set when the store opens. The SQL text is built once.
  • Optional tables exist only when the database was migrated with their feature. check_tables refuses to start a server that needs a feature that the database lacks.
  • Your own data about people (name, picture, role names) lives in your tables, with the user ID as a plain value.

Where the details are

Flows

Summary: how data moves through auth-chad: the check on every request, the decide-then-commit loop, and the main journeys (signup, login, device login, recovery, connected apps).
Key terms: request check, decide, commit, ceremony, DPoP, fresh login, device code, envelope, hold, outbox, worker.
Related: Data · Concepts · spec 02

Every request passes the same check. The auth-chad layer reads the cookie or the signed token, looks up the session in the database, and either creates an Authenticated value or rejects the request; then your handler runs. A request that changes an account calls a flow, which decides the change. The change and its audit event are stored in one transaction. Work that must follow the change, such as a mail, waits in the outbox until the worker runs it.

The check on every request

The picture as text
sequenceDiagram
    participant C as Client
    participant L as auth-chad layer
    participant DB as Users' database
    participant H as Your handler
    C->>L: request + cookie, or token + DPoP proof
    L->>DB: read the session or token, mark the proof as used
    alt valid
        L->>H: Authenticated (who, tenant, level, key, last passkey use)
        H-->>C: your response
    else invalid
        L-->>C: 401 or 403 with {"error": code}
    end
  • The check runs on every request, and its result is never cached. A logout takes effect on the next request, in every process.
  • If the database cannot answer, the request fails with 503.

Decide, then commit

The picture as text
flowchart LR
    R[Request] --> F["Flow<br/>(reads, decides)"]
    F --> D["Decision<br/>out + writes"]
    D --> A["+ your writes<br/>(hooks)"]
    A --> T[["One transaction<br/>all or nothing"]]
    T -->|ok| O[Use out: respond to the client]
    T -->|a condition failed| X[conflict: nothing changed]

A login in code: the passkey flow proves the person, the session flow opens a session, and one commit stores both.

use auth_chad::core::Draws;
use auth_chad::passkey::{self, Assertion};
use auth_chad::session::{self, Bind, Opened};
use auth_chad::{Ctx, Error, Store};

async fn log_in<S: Store>(
    ctx: &Ctx<'_>,
    store: &S,
    draws: &mut impl Draws,
    ceremony: &str,
    assertion: &Assertion,
    jkt: [u8; 32],
) -> Result<Opened, Error> {
    let proved = passkey::login_finish(ctx, store, draws, ceremony, assertion).await?;
    let opened = session::open(ctx, store, draws, &proved.out, Bind::Key { jkt, native: false }).await?;
    let opened = opened.and(proved.writes);
    store.commit(opened.writes).await?;
    Ok(opened.out)
}

The axum adapter’s routes do this for you. Call flows directly only when you build your own routes.

Signup

The picture as text
sequenceDiagram
    participant B as Browser
    participant S as Server
    participant DB as Database
    B->>S: signup/start (invite, names)
    S-->>B: challenge, in a sealed ceremony token
    Note over B: the person creates a passkey
    B->>S: signup/finish (ceremony, new passkey, key proof)
    S->>S: check the passkey and the invite
    S->>DB: one commit: user, passkey, session, invite used, event, your rows (commit_signup)
    S-->>B: session
  • A ceremony takes two requests. Its state travels in a sealed token, and the challenge is marked as used at the end, so each ceremony works once.
  • Your commit_signup hook adds your own rows (a profile, a first project) to the same commit, or refuses the signup.

Login and fresh login

  1. login/start returns a challenge, and the person uses a passkey.
  2. login/finish verifies it and opens a session, bound to the client’s key (DPoP) or, for page loads, to a cookie.
  3. A risky action requires a fresh login: a passkey use within the last few minutes. Without one, the response is step_up_required, and the client asks for the passkey again (step-up).

Device login (CLI, app, machine)

The picture as text
sequenceDiagram
    participant D as Device (CLI)
    participant S as Server
    participant P as Person's browser
    D->>S: device_authorization (name, scope, its public key)
    S-->>D: device code + user code + link
    D->>P: shows the link and the code
    P->>S: opens the link, sees name, scope and address
    P->>S: approve (fresh login, your app data)
    S->>S: hooks: may_approve, device_kind, commit_approve
    loop until approved
        D->>S: token (device code, signed with its key)
    end
    S-->>D: key-bound token
  • A user device acts as the person. A machine acts as itself, with its own scopes.
  • The device holds no copyable secret: it signs every token request with its own key.

Recovery

MethodProofWorks with end-to-end encryption
Recovery keyThe person presents a key they storedYes: the key also opens its envelope
Tenant ownersOwners approveNo
EmailA mailed link, after a waiting periodNo

After a recovery, the account is on hold: old passkeys cannot be removed for a while. During the hold, the real owner can undo a recovery that a thief started. Undo removes everything added since the recovery: passkeys, sessions, devices, connected-app grants and API keys.

Connected apps (OAuth, MCP)

  1. The app sends the person to the login origin with a pushed authorization request.
  2. The person logs in and consents to named scopes, which creates a grant.
  3. The app receives short-lived tokens for one audience. These tokens cannot change passkeys, sessions or recovery.

After the commit: outbox and worker

work(&auth) runs every few seconds, in the web process or in a separate worker process. It:

  • removes expired rows (limits, single-use marks, sessions, codes);
  • sends mail from the outbox and retries failures;
  • runs place work (provision, remove).

Each piece of work holds a lease in the database, so two processes never run it at the same time.

Where the details are

Interfaces

Summary: the traits and types where your code meets auth-chad: what you implement, what you call, and what you put in a handler’s signature.
Key terms: trait, generic, Store, Reader, Clock, Draws, Hooks, Refusal, By, extractor, Placement, Mailer, Http, Passkeys.
Related: Map · Data · Recipes

auth-chad performs no I/O of its own. It receives storage, time, random bytes and your application’s rules through a few Rust traits, passed as generic parameters. Most applications implement one trait, Hooks, and override only the methods they need, since every method has a safe default. Handlers state the proof they require by naming an extractor in their signature.

The picture as text
flowchart LR
    subgraph you [Your application]
        H[Hooks: your rules and rows]
        R[Handlers: name an extractor]
        P[Placement: where data lives]
    end
    subgraph lib [auth-chad]
        A[Auth]
    end
    S[(Store: SQLite, PostgreSQL, SeaORM)]
    C[Clock + Draws]
    A --> H
    R --> A
    A --> P
    A --> S
    A --> C

What you implement, what you call

InterfaceYouDefault
HooksImplement the methods you needEvery method has a safe default
Extractors (FirstParty, FreshLogin, …)Name them in handlers—
Store, ReaderPick a store; call Reader to read rowsSqliteStore, PostgresStore, SeaOrmStore
Clock, DrawsNothing, except in testsSystem time and system random bytes
PlacementImplement it only with the places featureNoPlaces
MailerImplement it only without the axum adapterHooks::send in axum
ColumnsDeclare with member_columns! for your membership columns()
Http, PasskeysImplement them only in a client on a new platformbrowser::Fetch, browser::Passkey
ServiceNothing: Auth implements it—
Row, Field, WorkerNothing: used inside the library—

Hooks

Hooks holds your application’s rules in one type. Every method is optional.

use auth_chad::axum::{Hooks, Refusal};
use auth_chad::core::Store as _;
use auth_chad::signup::Created;
use auth_chad::sqlite::SqliteStore;
use auth_chad::{Authenticated, Code, Tenant, Write};

struct Rules;

impl Hooks<SqliteStore> for Rules {
    async fn may_invite(&self, _: &SqliteStore, who: &Authenticated, tenant: Tenant) -> bool {
        tenant == Tenant::ROOT && who.is_first_party() // ask your own tables: is this an admin?
    }

    async fn commit_signup(
        &self,
        store: &SqliteStore,
        _created: &Created,
        app: &serde_json::Value,
        writes: Vec<Write>,
    ) -> Result<(), Refusal> {
        if app["terms"] != true {
            return Err(Code::InvalidRequest.into());
        }
        Ok(store.commit(writes).await?) // or commit_with: your rows in the same transaction
    }
}
GroupMethodsYou decide
Signupcommit_signup, valid_names, invite_data, may_inviteWho may join, your first rows
Devicesmay_request_device, may_approve, device_kind, commit_approve, commit_revokeWhich devices, who approves, your rows
Recoverycommit_recovery, commit_undo, may_recover, verified_address, find_accountNotices, your clean-up
Tenantsmay_create_tenant, may_manageWho runs a tenant
Othersmay_view, may_create_key, send, exchange, provider_keysSupport access, API keys, mail, external login
  • A commit hook receives the writes of the decision and must commit them, together with any writes of your own.
  • A commit hook refuses with a Refusal: a library code (Code::Forbidden.into()) or your own status and code (Refusal::App(StatusCode::CONFLICT, "name_taken")).
  • commit_approve, commit_revoke and commit_undo receive By { who, ip }: the caller and their address (None with without_addresses).

Extractors: proof in a handler’s signature

ExtractorThe request hasRefused with
FirstPartyA session of your own client, or a user deviceunauthenticated
InPersonThe user in person: not a machine, not someone who views as the userforbidden
FreshLogin<SECS>A passkey use in the last SECS secondsstep_up_required
ConnectedAppA token of an app that the user allowed, for this API. Check its scopesunauthenticated, forbidden
ApiKeyAn API key (only if turned on)unauthenticated
HereThe tenant of the request (the root tenant outside one)—
Member<C>A membership in the request’s tenant, with your columnsnot_found
At<P>The place of the request’s tenant or user503 not_ready or moving
CallerThe result of the layer’s check, for your own extractors and middleware—
use auth_chad::axum::{Caller, Refused};
use axum::extract::FromRequestParts;
use axum::http::request::Parts;

struct Admin(auth_chad::UserId);

impl<S: Sync> FromRequestParts<S> for Admin {
    type Rejection = Refused;

    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Refused> {
        let user = Caller::of(parts)?.first_party()?.user()?;
        Ok(Self(user)) // then ask your tables: is this user an admin?
    }
}

Store and Reader

A store reads rows and commits writes, all or nothing. Use it through generics instead of dyn.

use auth_chad::core::rows::Passkey;
use auth_chad::core::row::Field;
use auth_chad::{Reader, UserId};

async fn has_two_passkeys<R: Reader>(db: &R, user: UserId) -> bool {
    db.find_by::<Passkey>("user", user.store()).await.is_ok_and(|rows| rows.len() >= 2)
}
MethodDoes
Reader::get::<T>(key)One row and its version
Reader::find_by::<T>(column, value)Rows by an indexed column
Store::commit(writes)All or nothing, in order
Store::prune(now)Removes expired rows (the worker calls it)
commit_with(writes, f) (SQLite, PostgreSQL)Your SQL in the same transaction

Clock and Draws

Time and random bytes are injected, so tests are deterministic. Production code uses the defaults.

use auth_chad::UnixTime;
use auth_chad::core::{Clock, Draws};

struct Fixed;

impl Clock for Fixed {
    fn now(&self) -> UnixTime {
        UnixTime(1_800_000_000)
    }
}

struct Counting(u8);

impl Draws for Counting {
    fn fill(&mut self, _name: &'static str, out: &mut [u8]) {
        self.0 = self.0.wrapping_add(1);
        out.fill(self.0); // for tests only: auth-chad-testing has FakeClock and SeqDraws
    }
}

Auth::new(...).with_sources(clock, draws) puts them in.

Placement, Mailer, Columns

TraitMethodsRecipe
Placementchoose a place for a new tenant or user; provision and remove its data (safe to repeat)directory
Mailersend(mail) -> bool; false tries again laterrecovery
ColumnsYour columns of the memberships table, declared with member_columns!tenants

The client: Http and Passkeys

auth-chad-client calls the account API from a CLI, or from wasm in a browser.

TraitYou giveIn a browser
Httpsend(request) -> response, with your HTTP librarybrowser::Fetch
Passkeyscreate, get, prfbrowser::Passkey

See the client recipe.

Type parameters

  • Auth<S, H, C, D, M, P> carries the store, hooks, clock, draws, membership columns and placement as type parameters. Service names those types for handlers.
  • Row and Field map a struct to a table and a Rust value to a database value. The table! macro writes them.
  • Worker is the flow-level form of Placement, for code without the axum adapter.
  • The full list of hooks with their documentation: rust/adapters/axum/src/lib.rs, or cargo doc -p auth-chad-axum --open.

Scaling

Summary: how an application with auth-chad grows from one process and one database to many processes and many databases, without changing its handlers.
Key terms: step, users’ database, directory, place, load balancer, with_proxies, worker, lease, shared state.
Related: Flows · load-balancer recipe · directory recipe · spec 15

An application with auth-chad scales in three steps: one process with one database, many processes with one database, and many processes with data spread over several database servers. Every request checks its session in the users’ database before your code runs, so processes share no state and need no trust between them. Moving to the next step changes configuration and hosting; handlers stay the same. Most applications stay at step 1.

The picture as text
flowchart TB
    subgraph s1 [Step 1]
        direction LR
        A1[One process] --> D1[(One database)]
    end
    subgraph s2 [Step 2]
        direction LR
        L2[Load balancer] --> A2[Process 1] & B2[Process N]
        A2 & B2 --> D2[(PostgreSQL)]
    end
    subgraph s3 [Step 3]
        direction LR
        L3[Load balancer] --> A3[Process 1] & B3[Process N]
        A3 & B3 --> U3[(Users' database:<br/>who and where)]
        A3 & B3 --> X3[(Data server 1)] & Y3[(Data server 2)]
    end
    s1 --> s2 --> s3

Which step

Answer these questions in order and stop at the first that fits.

QuestionStep
Does one process carry the load?Step 1. Most applications. Tenants do not change the answer
Do you need more processes, or a second machine for failover?Step 2. Move to PostgreSQL, put a load balancer in front
Is the data too large for one database, or do you want a database for each customer?Step 3. The users’ database also says where each tenant’s or user’s data is

Multiple regions, and servers that cannot reach the users’ database, are out of scope.

DataProcessesDatabase
Step 1One databaseOneSQLite (recommended) or PostgreSQL
Step 2One databaseMany identical, behind a load balancerPostgreSQL
Step 3Users’ database, and your data on one or many serversMany identicalPostgreSQL

Step 1: one process, one database

  • Signup and your first rows in one transaction. Foreign keys and joins to users. One backup.
  • Limits: one machine (with SQLite, several processes on that machine can share the file, for example during a deploy), and all data must fit in one database.

Step 2: many processes, one database

  • More capacity; deploys and failures without downtime. Any process serves any request.
  • Needs: PostgreSQL (SQLite is not synced between machines), the real client address with with_proxies(n), and the worker. Rate limits, single-use marks and leases are stored in the database, so every process sees them.

Step 3: your data on database servers

  • Any number of PostgreSQL servers, each with one shared database or one database for each customer. A tenant can be moved, restored or deleted alone. The session carries the place, so no extra lookup is needed.
  • Costs: no shared transaction and no foreign keys between users and your data (an outbox joins signup and your data); every process must reach the users’ database and every data server.
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize)]
struct Place {
    server: String,   // "db2": the process maps it to a connection string from its own settings
    database: String, // "customer_7". Never a password
}

Requests get 503 not_ready until provision answers true, and 503 moving during a move.

The three independent decisions

DecisionChoicesWhat it changes for auth
A. DataOne database, or users’ database plus data databasesThe second adds the places feature
B. ProcessesOne, or many identical processes behind a load balancerMany processes need PostgreSQL, with_proxies and a worker
C. Tenant addressNone, a path (/t/acme/), or a host (acme.example.com)The tenants feature, cookies, your DNS. Every step works with every choice
  • A path for each tenant: one host name and one certificate; one cookie per tenant (__Host-session-acme, at most 20† at once). All tenants share one web origin, so a script flaw in one tenant’s pages affects all of them.
  • A host for each tenant: a wildcard DNS record and certificate. Each tenant has its own origin and cookie. A browser enters with a one-use code of 60 seconds. One passkey for the parent domain works on all hosts.

What we assume about the network

AssumptionWhy
Every process reaches the users’ database, and in step 3 every data serverEach request is checked there
The load balancer passes the Host headerHost tenants and key proofs name that host
The load balancer adds the client address to X-Forwarded-For, and the program knows the number of proxies (with_proxies(n))Rate limits count each client; a client cannot write its own entry
The processes are reachable only through the load balancerOtherwise a client can write X-Forwarded-For itself

TLS can end at the load balancer or at the process. Sticky sessions are not needed.

The worker

work(&auth) does the background work: removes expired rows, sends mails that wait, runs the work of places.

  • Axum or your own server: call it every few seconds in a loop, in the web process (step 1) or in a worker process of the same binary, for example with ROLE=worker (steps 2 and 3).
  • Loco: register the task auth_work and run it from Loco’s scheduler, for example every 10 seconds.
  • Any number of processes can run it. Each piece of work holds a lease (a mail one minute, a place five minutes). provision and remove must be safe to repeat.

Rules in every step

SubjectRule
Sessions, tokens, devices, API keys, membershipsOnly in the users’ database
The checkOnce for each request, before your code. Never cached
Logout, removal, disabled userWorks from the next request, in every process
Check not possible503
WebSocket, event streamChecked when it opens; your server closes it after 5 minutes† at the latest
Signed link (media, download)Works until its own end, at most 10 minutes†, also after a logout
What a person may doYour code, with your data
PlaceBy tenant or by user. An application chooses one, never both

Patterns we do not support

PatternWhat goes wrong
Sessions in application databasesEach logout must reach every database
A JWT that processes check without the databaseLogout and removal take effect only when the token expires
Cached answers of the checkThe same, for the time of the cache
A header like X-User from a proxyWhoever reaches the process can write it
A proxy that checks sessions for the processesA second way in, with its own rules
SQLite on several machinesSyncing a database is a problem of its own
Routing tenants to machines at the load balancerNot needed: any process serves any tenant

What lives where

  • With the users: users, passkeys, sessions, tokens, devices, invites, events, the outbox, rate limits, single-use marks, leases; tenants, memberships (with your columns) and places with their features; your own tables about people.
  • Your data: everything else, with the user ID and tenant ID as plain values.
  • auth-chad memberships postgres role:text=member seat:int? prints the migration for your membership columns and the Rust declaration.

Moving between steps

StepWhat you do
1 → 2Move to PostgreSQL. Put a load balancer in front, set with_proxies. Run the worker. Start more processes
2 → 3Move your tables to data servers. Remove foreign keys to users. Implement Placement
BackThe same steps in the other order

Costs of step 3

You loseWhat the library gives
One transaction for auth and your dataAn outbox: provision after signup, perhaps more than once
Foreign keys and joins to usersThe user ID
A consistent backupplace::in_states lists places that wait for their data
Few connectionsNothing: keep pools small, or share a database between customers
Valid sessions after restoring an old users’ databaseauth-chad after-restore prints SQL that ends all sessions, tokens, codes and API keys

Capacity of one process

This estimate uses published SQLite measurements; auth-chad has no benchmark of its own yet. On a 5-dollar machine, one published test reached about 300,000 reads and 28,000 write transactions a second. One million people a day, with 100 requests each, is about 23,000 reads and 6,100 writes a second at peak: well inside one process.

Status: all three steps work today, for SQLite and PostgreSQL, with tenants, memberships and places.

Recipes

Summary: one short page for each task, with code that compiles. Find your task here.
Key terms: recipe, feature, start, route, device, tenant, recovery, client, e2ee.
Related: Interfaces · Concepts · skill for agents

Each recipe shows how to add one capability to an application, with code that compiles. Find the task in the table, copy the code, and adapt the names. The table lists the auth-chad crate feature that each recipe needs.

The recipes

You needRecipeFeature
Passkey accounts in a new applicationstartaxum, sqlite or postgres
A handler that needs a userprotect-a-routeaxum
The passkey again before a risky actionsensitive-actionaxum
Invite only, adminsinvitesaxum
Your own tables in the same transactionown-tablessqlite, postgres
A CLI, device or machinedevicesaxum
Other apps as clients (OAuth, MCP)connected-appsaxum
An API key for a program that can only send a header (not recommended)api-keysaxum
A way back into an accountrecoveryaxum
“Sign in with…”, company loginexternal-loginaxum
Organizations with members (tenants)tenantsaxum
Data of each tenant or user in its own databasedirectoryaxum, postgres
Many processes, a load balancer, the workerload-balanceraxum
A CLI or a Rust/wasm web app as a clientclientclient
End-to-end encryptione2eee2ee
Support staff who see the application as a userview-asaxum
Teststestingdev-dependency auth-chad-testing
A Loco or SeaORM applicationlocoauth-chad-loco, or sea-orm

How recipes stay correct

  • The Rust code on the recipe pages and on the wiki pages compiles: rust/recipes includes each page as a documentation test. A new page goes into rust/recipes/src/lib.rs.
  • A recipe shows one task. The wiki pages explain the reasons, and the spec has the exact rules.

Start

[dependencies]
auth-chad = { git = "https://github.com/audiochad/auth-chad", rev = "<commit>", features = ["axum", "sqlite"] }
use std::{path::Path, sync::Arc};
use auth_chad::{Config, Prefix, axum::Auth, sqlite::SqliteStore};

fn auth(master: &[u8; 32]) -> Result<Arc<Auth<SqliteStore>>, Box<dyn std::error::Error>> {
    let config = Config::new(
        "myapp/v1",                    // never change it
        "https://app.example.com",     // where the API is
        "app.example.com",             // passkeys belong to this domain: never change it
        "My app",
        &["https://app.example.com"],  // pages that may call the API
    )?;
    let store = SqliteStore::open(Path::new("/var/lib/myapp/app.db"), &Prefix::default(), 4)?;
    Ok(Arc::new(Auth::new(config, master, store)?))
}
  • Master key: 32 random bytes from a secret store. Never in the repository.
  • Tables: run the migration as a deploy step, not at start. auth-chad schema sqlite prints the SQL, and SqliteStore::create(path, prefix, readers, &[]) runs it. open never creates tables. Tenants and places are optional features: add them with &[Feature::Tenants] when you use them, and call auth.check_tables() at start.
  • Routes: Router::new()….with_state(auth.clone()).merge(auth.router()). The API is below /auth.
  • Page: import { signup, login, logout, session, stepUp } from "/auth/auth-chad.js". Call them from a click.
  • Behind a proxy: with_proxies(n) (load-balancer).
  • A web app on another host (for example app.example.com calling api.example.com): list its origin in Config origins (for passkeys) and in with_web_origins (for CORS). Its calls carry no cookies, so it logs in with a key-bound token, for example with the Rust client. A key-bound policy refuses cookies everywhere.
  • No client addresses in audit events: without_addresses(). Rate limits still use them.
  • Housekeeping: call auth_chad::axum::work(&auth) every few seconds: it prunes, sends mails and runs places.

A whole application: rust/examples/minimal.

Protect a route

Add Auth::layer to the routes, and an extractor to the handler. The state of the application can be anything.

use std::sync::Arc;
use auth_chad::axum::{Auth, FirstParty, Refused};
use auth_chad::sqlite::SqliteStore;
use axum::Router;
use axum::routing::get;

async fn notes(who: FirstParty) -> Result<String, Refused> {
    let user = who.user()?;   // a UserId; a machine gives `forbidden`
    Ok(format!("notes of {user}"))
}

async fn home(who: Option<FirstParty>) -> &'static str {
    if who.is_some() { "welcome back" } else { "hello" }
}

fn app(auth: &Arc<Auth<SqliteStore>>) -> Router {
    let routes = Router::new().route("/notes", get(notes)).route("/", get(home));
    auth.layer(routes).merge(auth.router())
}

Your own extractor builds on it, for example for a user’s role:

use auth_chad::axum::{Caller, Refused};
use axum::extract::FromRequestParts;
use axum::http::request::Parts;

struct Admin(auth_chad::UserId);

impl<S: Sync> FromRequestParts<S> for Admin {
    type Rejection = Refused;

    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Refused> {
        let user = Caller::of(parts)?.first_party()?.user()?;
        // Ask your database: is this user an admin?
        Ok(Self(user))
    }
}
  • Cookies and DPoP both work. A POST with a cookie must come from a page in Config.origins.
  • The layer runs once per request and refuses nothing. Without it, the extractors answer 503 to everyone.
  • Other middleware can read Caller, for example to log who did what. It must be inside the layer.
  • May this user do this? That is the application’s decision. The library says who it is.

Ask for the passkey again

use auth_chad::axum::FreshLogin;

async fn delete_account(fresh: FreshLogin<300>) -> String {
    format!("{} proved it in the last 5 minutes", fresh.0.user())
}

More than 900 seconds does not compile. In the page:

import { stepUp } from "/auth/auth-chad.js";

button.onclick = async () => {
  let res = await fetch("/account", { method: "DELETE" });
  if (res.status === 401 && (await res.json()).error === "step_up_required") {
    await stepUp("delete account");
    res = await fetch("/account", { method: "DELETE" });
  }
};

Inside the application, take Fresh<300> as an argument. Then no caller can forget the check:

use auth_chad::Fresh;

fn transfer(_proof: Fresh<300>, _to: &str) {}

Invites

use auth_chad::core::policy::Policy;
use auth_chad::{Authenticated, Config, Store, Tenant};
use auth_chad::axum::Hooks;

fn invite_only(config: Config) -> Config {
    config.with_policy(Policy::invite_only())
}

#[derive(Clone)]
struct App;

impl<S: Store> Hooks<S> for App {
    async fn may_invite(&self, _: &S, who: &Authenticated, tenant: Tenant) -> bool {
        tenant == Tenant::ROOT && who.is_first_party()   // replace with: is this user an admin?
    }
}

POST /auth/invites gives a token once. For a tenant: /auth/tenants/{name}/invites, and the new user becomes a member. The link is https://app.example.com/signup?invite=<token>, for one account and 7 days. GET lists and DELETE /auth/invites/{id} cancels.

The first account, from the host: signup::create_invite(&ctx, &mut draws, None, None, "admin"), then commit. The last argument is your own data: it comes back in Created.invite at signup.

data in POST /auth/invites is your own data too, and the list shows it. If it gives rights, check it in Hooks::invite_data: the default stores what the person asked for, so an admin could make admin invites.

Your own tables in the same transaction

use auth_chad::core::CommitError;
use auth_chad::signup::Created;
use auth_chad::sqlite::SqliteStore;
use auth_chad::axum::{Hooks, Refusal};
use auth_chad::{Code, Write};

#[derive(Clone)]
struct App;

impl Hooks<SqliteStore> for App {
    async fn commit_signup(
        &self,
        store: &SqliteStore,
        created: &Created,
        app: &serde_json::Value,
        writes: Vec<Write>,
    ) -> Result<(), Refusal> {
        let user = created.user.id.0;
        let color = app["color"].as_str().unwrap_or("blue").to_owned();   // the signup's own "app" field
        if color.len() > 20 {
            return Err(Code::InvalidRequest.into());
        }
        store
            .commit_with(writes, move |tx| {
                tx.execute("INSERT INTO profiles (owner, color) VALUES (?1, ?2)", (user, color))
                    .map(|_| ())
                    .map_err(|_| CommitError::Backend)
            })
            .await?;
        Ok(())
    }
}

profiles.owner can be BLOB REFERENCES auth_users (id). If your check or your insert fails, the user is not created. The signup’s JSON can carry your own data in "app". To refuse with your own code, return Refusal::App(StatusCode::CONFLICT, "name_taken"): the client gets that status and {"error": "name_taken"}.

An application with its own connections calls auth_chad::sqlite::apply(&tx, &sql, writes) or auth_chad::postgres::apply(&tx, &sql, writes).await inside its own transaction. get and find read with any connection.

CLIs and machines

Merge auth.oauth_router() at the root. A device makes a key, and sends it with a DPoP proof:

StepWhoCall
1DevicePOST /oauth/device_authorization with device_name, scope, data
2DeviceShows user_code, the link, and its fingerprint (device::fingerprint)
3PageGET /auth/device/{code}: show the name, scope and fingerprint. The person compares
4PagePOST /auth/device/{code}/approve with {"machine": false}. Needs a fresh login
5DevicePOST /oauth/token with the device code, every 5 seconds
6DeviceLater: POST /oauth/token with a signed assertion. There is no refresh token to lose

scope and data mean what your application wants. Decide in the hook:

use auth_chad::{Authenticated, Store};
use auth_chad::axum::Hooks;
use auth_chad::core::rows::DeviceKind;

#[derive(Clone)]
struct App;

impl<S: Store> Hooks<S> for App {
    async fn may_request_device(&self, scope: &str, _data: &str) -> bool {
        scope == "user" || scope == "machine"   // anything else: invalid_scope
    }

    async fn may_approve(&self, _who: &Authenticated, scope: &str, _data: &str) -> bool {
        scope == "user"   // also who may see and deny the request
    }

    fn device_kind(&self, scope: &str, _data: &str, _asked: DeviceKind) -> Option<DeviceKind> {
        Some(if scope == "machine" { DeviceKind::Machine } else { DeviceKind::User })   // the scope decides
    }
}
  • commit_approve gets the approval’s own "app" field and the writes: add your rows, for example a key sealed to the device, in the same commit. commit_revoke does the same for a revocation, and can refuse it.
  • These hooks get By { who, ip }: who acts, and the address of the request, for your own audit rows. ip is None with without_addresses.
  • A hook refuses with a Refusal: a library code, or your own status and code (Refusal::App).
  • GET /auth/devices?kind=user lists only one kind.
  • The request page and the list have the device’s public_key (a canonical JWK), and the list has your data: an application can show a fingerprint of its own.

A user device acts as the user. A machine acts as itself (Subject::Machine). Neither is ever fresh.

Apps of others: OAuth and MCP

use std::sync::Arc;
use auth_chad::axum::{Auth, ConnectedApp, Refused};
use auth_chad::provider::{Provider, Scope};
use auth_chad::sqlite::SqliteStore;
use auth_chad::Code;

fn connect(auth: Auth<SqliteStore>) -> Arc<Auth<SqliteStore>> {
    let read = Scope { name: "notes:read".into(), description: "Read your notes".into(), connected: true, write: false };
    let provider = Provider {
        scopes: vec![read],
        audiences: vec!["https://app.example.com/mcp".into()],
        dynamic_registration: true,   // some MCP clients still need it
        ..Provider::default()
    };
    Arc::new(auth.with_provider(provider).with_pages("/consent", "/device"))
}

async fn mcp(app: ConnectedApp) -> Result<&'static str, Refused> {
    if app.0.has_scope("notes:read") { Ok("data") } else { Err(Code::Forbidden.into()) }
}
  • Merge auth.oauth_router() at the root: metadata, authorize, token, revoke, register.
  • Consent page: it gets ?request=<id>. GET /auth/consent/{id} shows the client, its redirect host and the scopes; POST {"allow": true} answers {"redirect": "…"}. Show the host of redirect_uri: a name proves nothing.
  • Client metadata documents: implement Hooks::fetch_client with your HTTP client. Public addresses only, no redirects, 64 KiB, a timeout: the URL comes from a stranger.
  • MCP: answer 401 with WWW-Authenticate: Bearer resource_metadata="https://app.example.com/.well-known/oauth-protected-resource".
  • A connected app never reaches a FirstParty handler.

API keys

We do not recommend them. Whoever has the text of a key can use it. Use a device for your own CLIs and machines, and a connected app for programs of others. Use an API key only if a program can send nothing but a fixed header.

They are off until you turn them on:

use auth_chad::api_key::ApiKeys;
use auth_chad::axum::{ApiKey, Auth, Hooks};
use auth_chad::{Authenticated, Error, Store};

fn turn_on<S: Store, H>(auth: Auth<S, H>) -> Result<Auth<S, H>, Error> {
    Ok(auth.with_api_keys(ApiKeys::new("example_", &["reports:read"])?))
}

struct App;

impl<S: Store> Hooks<S> for App {
    async fn may_create_key(&self, _who: &Authenticated, scopes: &[&str]) -> bool {
        scopes == ["reports:read"]
    }
}

async fn reports(key: ApiKey) -> Result<String, auth_chad::axum::Refused> {
    if !key.0.has_scope("reports:read") {
        return Err(auth_chad::Code::Forbidden.into());
    }
    Ok(format!("reports of {}", key.user()?))
}
CallDoes
POST /auth/keys with name, scopes, lifetime in secondsMakes a key. Needs a fresh login. secret is in the answer once
GET /auth/keysLists them, with the last use and its address (up to five minutes old)
DELETE /auth/keys/{id}Ends one

In the browser: newApiKey({ name, scopes, days }), apiKeys(), endApiKey(id). Show the secret once, and keep it nowhere.

  • A key lives at most 90 days, and has no renewal. Make the next one before it ends.
  • Only ApiKey accepts a key. FirstParty, InPerson, FreshLogin and ConnectedApp refuse it, and so does the whole account API. A route for both a user and a key decides with Caller.
  • ApiKey is the user that made the key, not the user in person. Let a key read before you let it write.
  • Tell your users: never in a page, an app or a repository. The prefix lets secret scanners find it. Never change the prefix: every key stops working.
  • Policy.key_bound refuses every key. Without with_api_keys, no key works.
  • Do not log the Authorization header.

A way back into an account

Offer a second passkey first. Then choose:

MethodRoutes below /authThe application doesStrength
Recovery keyrecovery/key, recovery/key/start, recovery/key/finishNothing, if users have an identifierStrong
Approval by an ownerrecovery/owner, then the linkHooks::may_recoverStrong, if people check each other
Emailrecovery/email, then the linkConfig::with_email_recovery, verified_address, sendWeak: 24 hours of waiting, notices, 72 hours of hold
use auth_chad::axum::{Hooks, Mail};
use auth_chad::sqlite::SqliteStore;
use auth_chad::{Authenticated, UserId};

struct App;

impl Hooks<SqliteStore> for App {
    async fn verified_address(&self, _store: &SqliteStore, address: &str) -> Option<UserId> {
        None   // look up an address that you verified, never one that a person only typed
    }

    async fn may_recover(&self, who: &Authenticated, user: UserId) -> bool {
        false  // is `who` an owner of an organization of `user`?
    }

    async fn send(&self, mail: Mail<'_>) -> bool {
        match mail {
            // A secret. The link opens a page with a button: mail scanners open links.
            Mail::Link { to, token } => false,
            // "Someone asked for a new passkey. It works at … . Cancel it here."
            Mail::Notice { to, ready_at } => false,
        }
    }
}

In the browser (/auth/auth-chad.js):

const text = await newRecoveryKey();                                  // show it once; needs a recent passkey
await recoverWithKey({ identifier: "jane", displayName: "Jane", key: text });
await recoverByEmail("jane@example.com");                             // the same answer if there is no account
await recoverWithLink({ token, userName: "jane", displayName: "Jane" });
const { ready_at, hold_until } = await recovery();                    // show it: cancelRecovery(), undoRecovery()
  • Run the worker (auth_chad::axum::work, see load-balancer): it sends a mail that failed again.
  • Show ready_at on every page of a logged-in user. A cancel there stops someone who has the mailbox.
  • Use Hooks::commit_recovery to add a notice for every other address of the user.

Never use email recovery with e2ee: it cannot restore a key.

Another provider

It proves a claim. It never logs a user in: after it comes a passkey.

use auth_chad::axum::{External, Hooks};
use auth_chad::oidc::KeySet;
use auth_chad::sqlite::SqliteStore;

fn company() -> External {
    External {
        id: "company".into(),
        issuer: "https://login.company.example".into(),
        client_id: "…".into(),
        authorization_endpoint: "https://login.company.example/authorize".into(),
        token_endpoint: "https://login.company.example/token".into(),
        sends_iss: true,
        authoritative_for: vec!["company.example".into()],
    }
}

struct App;

impl Hooks<SqliteStore> for App {
    async fn exchange(&self, provider: &External, form: &[(&'static str, String)]) -> Option<String> {
        // POST `form` to `provider.token_endpoint` with your client secret or key. Return `id_token`.
        None
    }

    async fn provider_keys(&self, provider: &External) -> Option<KeySet> {
        // GET the provider's `jwks_uri`, and keep it for some minutes.
        None
    }
}

Then Auth::new(…)?.with_hooks(App).with_external(vec![company()], "/welcome"). Register the redirect URI <issuer>/auth/external/company/callback at the provider. In the browser:

await external("company", "signup");   // comes back to /welcome?purpose=signup or /welcome?error=…
await signup({ displayName, external: true });

await external("company", "link");     // comes back to /welcome?purpose=link
await linkExternal();                  // from a click, with a recent passkey

await external("company", "refresh");  // for a company rule, when login() fails with external_identity_refused
await login();
  • Sign up: allow SignupMode::External in the policy.
  • Company rule: add the issuer to Policy.external. A login then needs a company login of the last 24 hours.
  • The answer of the provider must be a redirect with a query. A form post (response_mode=form_post) does not work: the browser does not send the cookie with it.

Never look up an account by the email address.

Tenants

A tenant is an organization or a customer: a boundary for sessions, with members. Rules: spec 14. How to grow: the wiki. Load balancer settings for both kinds of address: load-balancer.

use std::sync::Arc;
use auth_chad::{Authenticated, Store, Tenant};
use auth_chad::axum::{Auth, FirstParty, Here, Hooks, Member, Tenancy};
use auth_chad::core::member;

auth_chad::core::member_columns! {
    pub struct Membership { role: String }   // your columns; `auth-chad memberships` writes their migration
}

#[derive(Clone)]
struct App;

impl<S: Store> Hooks<S> for App {
    async fn may_create_tenant(&self, who: &Authenticated) -> bool {
        who.is_first_party()   // replace with your rule
    }

    async fn may_manage(&self, store: &S, who: &Authenticated, tenant: Tenant) -> bool {
        let Ok(user) = who.user() else { return false };
        let found = member::read::<Membership>(store, tenant, user).await;
        matches!(found, Ok(Some(m)) if m.columns.role == "owner")
    }

    async fn may_invite(&self, store: &S, who: &Authenticated, tenant: Tenant) -> bool {
        tenant != Tenant::ROOT && self.may_manage(store, who, tenant).await
    }
}

fn setup<S: Store + 'static>(auth: Auth<S>) -> Arc<impl auth_chad::axum::Service> {
    Arc::new(auth.with_hooks(App).with_members::<Membership>().with_tenancy(Tenancy::Host { parent: "example.com".into() }))
}

async fn report(who: FirstParty, here: Here, member: Member<Membership>) -> String {
    format!("{} in {:?} as {}", who.0.tenant(), here.name, member.0.columns.role)
}
  • Where the tenant is in a request: Tenancy::Host (acme.example.com: each tenant has its own web origin; needs a wildcard DNS record and certificate) or Tenancy::Path (/t/acme/: one host and certificate, one cookie for each tenant). The hosts of your configured origins are the root.
  • Tables: tenants are an optional feature. Migrate with it (SqliteStore::create(…, &[auth_chad::Feature::Tenants]), or auth-chad feature sqlite tenants), and call auth.check_tables() at start: it fails if they are missing.
  • Members: the table is in the database of the users. Your columns need a default: auth-chad memberships sqlite role:text=member prints the migration and the declaration. Member<Membership> reads them with each request in a tenant.
  • Routes, all at the login origin with the root session: GET/POST /auth/tenants, POST /auth/tenants/{name}/enter, /members, /members/{user} (PATCH {"state":"suspended"}, DELETE), /invites, /accept.
  • Entering on a tenant’s host: send the browser to https://acme.example.com/auth/enter/start?return=/. Without a session, the login page of with_login_page comes first. Key-bound clients POST /auth/tenants/{name}/enter with their root token.
  • Signup with an invite of a tenant: add "tenant": "<name>" to both signup calls. The new user is a member.
  • Ending a membership ends the person’s sessions, tokens, devices, grants and API keys in that tenant at once. Machines stay. Add your own changes to the same commit with tenant::end and commit_with.

A separate directory

The users’ database becomes the directory: users, sessions, tenants, memberships and the place of each tenant or user. Your data is on PostgreSQL servers: each with one database for many tenants, or one database for each. Rules: spec 15. When to use it: the wiki.

use std::collections::HashMap;
use std::sync::Arc;
use auth_chad::Store;
use auth_chad::axum::{At, Auth, FirstParty, PlaceBy, Placement, Service, run_places};
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize)]
struct Place {
    server: String,     // a name, for example "db2"
    database: String,   // no password here: it belongs to the process's configuration
}

struct Databases {
    servers: HashMap<String, String>,   // name → connection string, from environment variables
}

impl Databases {
    fn from_env() -> Self {
        let names = std::env::var("DB_SERVERS").unwrap_or_default();   // "db1,db2"
        let url = |name: &str| std::env::var(format!("DB_{}_URL", name.to_uppercase())).ok();
        Self { servers: names.split(',').filter_map(|n| Some((n.to_owned(), url(n)?))).collect() }
    }
}

async fn create_database(url: &str, name: &str) -> bool {
    let _ = (url, name);   // CREATE DATABASE if it is missing, then your migrations
    true
}

async fn drop_database(url: &str, name: &str) -> bool {
    let _ = (url, name);   // DROP DATABASE IF EXISTS
    true
}

impl Placement for Databases {
    type Place = Place;
    const BY: Option<PlaceBy> = Some(PlaceBy::Tenant);

    async fn choose(&self, owner: [u8; 16]) -> Option<Place> {
        let mut names: Vec<&String> = self.servers.keys().collect();
        names.sort();
        let server = names.get(usize::from(owner[0]) % names.len().max(1))?;   // or: where there is room
        let database = format!("tenant_{}", owner.iter().map(|b| format!("{b:02x}")).collect::<String>());
        Some(Place { server: (*server).clone(), database })
    }

    async fn provision(&self, _owner: [u8; 16], place: &Place, _id: [u8; 16]) -> bool {
        let Some(url) = self.servers.get(&place.server) else { return false };
        create_database(url, &place.database).await   // safe to repeat
    }

    async fn remove(&self, _owner: [u8; 16], place: &Place, _id: [u8; 16]) -> bool {
        let Some(url) = self.servers.get(&place.server) else { return false };
        drop_database(url, &place.database).await
    }
}

fn setup<S: Store + 'static>(auth: Auth<S>) -> Arc<impl Service> {
    Arc::new(auth.with_places(Databases::from_env()))
}

async fn after_signup<A: Service>(auth: &A) {
    run_places(auth).await.ok();   // sooner than the next run of the worker
}

async fn notes(who: FirstParty, at: At<Place>) -> String {
    format!("{} uses {} on {}", who.0.tenant(), at.place.database, at.place.server)
}
  • Tables: places are an optional feature (Feature::Places, and Feature::Tenants to place by tenant). Migrate with them and call auth.check_tables() at start.
  • By tenant or by user: BY decides. Never both.
  • One database for many tenants: give them the same database, and give your tables a tenant column.
  • A new tenant or user gets its place in the same commit, in the state creating. Until provision answers true, At gives 503 not_ready with Retry-After.
  • The worker runs provision and remove (load-balancer). Work that fails runs again after its lease of 5 minutes.
  • Moving: place::begin_move (requests get 503 moving), copy the data, then place::finish_move with the new place. The generation grows.
  • Removing: place::remove. Requests get 404 at once, and remove runs until it answers true.
  • Waiting too long: place::in_states(store, PlaceState::Creating).
  • Connections: a PostgreSQL connection is for one database. With a database for each tenant, keep a small pool for each active one.
  • After a restore of the directory: auth-chad after-restore postgres prints the SQL that ends every session.

Many processes behind a load balancer

The same binary runs in every process. Each request is checked in the users’ database, so any process serves any request. Steps and rules: the wiki.

use std::sync::Arc;
use std::time::Duration;
use auth_chad::Store;
use auth_chad::axum::{Auth, Service, work};

fn setup<S: Store + 'static>(auth: Auth<S>) -> Arc<impl Service> {
    Arc::new(auth.with_proxies(1))   // one load balancer adds the client address to X-Forwarded-For
}

async fn worker<A: Service>(auth: Arc<A>) {
    loop {
        work(auth.as_ref()).await.ok();   // prunes, sends mails that wait, runs the work of places
        tokio::time::sleep(Duration::from_secs(5)).await;
    }
}

async fn start<A: Service>(auth: Arc<A>) {
    match std::env::var("ROLE").as_deref() {
        Ok("worker") => worker(auth).await,
        Ok("web") => { /* serve the router only */ }
        _ => {
            tokio::spawn(worker(Arc::clone(&auth)));   // one process does both: good for one machine
            /* serve the router */
        }
    }
}
  • Database: PostgreSQL for more than one machine. Rate limits, single-use marks of key proofs and leases are in it, so every process sees them.
  • Worker: any number of processes can call work at once. Each piece of work has a lease (a mail one minute, a place 5 minutes), so it runs in one place at a time. Work that takes longer, or a crash, can run it twice: provision and remove must be safe to repeat. With Loco: register auth::Work and run the task auth_work from Loco’s scheduler.
  • with_proxies(n): the number of proxies that add an entry to X-Forwarded-For. The address is the entry that the outer one added. The processes must be reachable only through the proxies. Without proxies, keep the default 0.
  • What the load balancer must do: pass the Host header, and add the client address to X-Forwarded-For. Sticky sessions are not needed.

Caddy, a path for each tenant

app.example.com {
	reverse_proxy app1:3000 app2:3000 app3:3000 {
		lb_policy round_robin
		health_uri /healthz
	}
}

Caddy passes Host and sets X-Forwarded-For to the client address: with_proxies(1). /healthz is a route of your application. Tenants are at app.example.com/t/acme/ (Tenancy::Path).

Caddy, a host for each tenant

example.com, *.example.com {
	tls {
		dns cloudflare {env.CLOUDFLARE_API_TOKEN}
	}
	reverse_proxy app1:3000 app2:3000 {
		lb_policy round_robin
		health_uri /healthz
	}
}

A wildcard certificate needs a DNS challenge, so Caddy needs the module of your DNS provider (here caddy-dns/cloudflare). Tenants are at acme.example.com (Tenancy::Host { parent: "example.com" }), and the login origin is example.com.

nginx

upstream app {
    server app1:3000;
    server app2:3000;
}

server {
    listen 443 ssl;
    server_name example.com *.example.com;
    location / {
        proxy_pass http://app;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

$proxy_add_x_forwarded_for adds the client address at the end: with_proxies(1).

Two proxies

A CDN in front of Caddy is two proxies: with_proxies(2). The inner proxy must keep the entry of the outer one. In Caddy, list the CDN’s addresses in trusted_proxies, or Caddy replaces the header.

Other load balancers

An AWS Application Load Balancer adds the client address to X-Forwarded-For: with_proxies(1).

A Rust client: CLI or wasm in a browser

auth_chad::client::Client talks to the account API. It proves its own key with DPoP on each call, renews its token, and with end-to-end encryption seals and opens the identity key. It sends requests through your Http, so the same code runs in a CLI and in a browser.

use auth_chad::client::{Client, Error, Http, Request, Response, Signup};
use auth_chad::core::{Clock, Draws, UnixTime};
use auth_chad::keys::SigningKey;

struct Net;   // your HTTP library: send the method, URL, headers and body, return status, `dpop-nonce` and body

impl Http for Net {
    async fn send(&self, _request: Request) -> Result<Response, Error> {
        Err(Error::Network)
    }
}

async fn device_login<C: Clock, D: Draws + Clone>(clock: C, draws: D, key: SigningKey) -> Result<(), Error> {
    let mut client = Client::new(Net, clock, draws, "https://api.example.com", "myapp/v1", key).mounted_at("/v1/auth");
    let waiting = client.request_device("laptop", "user", "").await?;
    println!("Open {} and enter {}", waiting.verification_uri, waiting.user_code);
    // every `waiting.interval` seconds, until it says Approved:
    client.poll(&waiting).await?;
    let _sessions: serde_json::Value = client.get("/sessions").await?;   // renews the token when needed
    Ok(())
}

fn keep(client: &Client<Net, impl Clock, impl Draws + Clone>) -> Option<(String, UnixTime)> {
    client.token().map(|(t, end)| (t.to_owned(), end))   // store it with the key; `resume` continues
}

In a browser, add the crate with the browser feature and build for wasm32-unknown-unknown. It gives Fetch (no cookies, no redirects), WebClock, WebDraws and Passkey (WebAuthn with the PRF extension). Call passkey methods from a click:

use auth_chad_client::browser::{Fetch, Passkey, WebClock, WebDraws};

let mut client = Client::new(Fetch, WebClock, WebDraws, "https://api.example.com", "myapp/v1", key);
let (_session, keys) = client.signup(&Passkey, Signup { display_name: "Jane", ..Signup::default() }, true).await?;
let keys = keys.expect("with e2ee");      // show keys.recovery.display() once; keep keys.secret in memory only
let back = client.login(&Passkey, true).await?;   // back.secret: the identity secret, opened with the passkey
  • Where the API is: mounted_at follows the server’s Auth::mounted_at; the default is /auth.
  • The page on another host: see start: Config origins and with_web_origins.
  • End-to-end encryption: signup(.., true) makes the identity secret and a recovery key. login, recover, add_passkey(.., Some(&secret)) and new_recovery_key keep the envelopes. A passkey that gives no PRF output at creation is asked once more.
  • Your own routes: call sends a request with the login to any path; call_with adds headers, for example If-Match, and takes a body that is already JSON.
  • Data from the secret in the signup: make the secret first and pass it in Signup::secret, for example to send public keys that come from it in app.
  • Errors: Error::StepUp means: call step_up and try again. Error::Refused carries the server’s code.
  • The text of a user in envelopes is the user ID. An application with envelopes from before can set its own with with_label.

End-to-end encryption

Each user has a 64-byte identity secret. The client makes it and seals it; the server stores envelopes.

use auth_chad::core::Draws;
use auth_chad::e2ee::{self, Context, Method, OpenError, RecoveryKey};

fn seal(draws: &mut impl Draws, prf: &[u8; 32], user: &str, kid: &str, secret: &[u8; 64]) -> Result<e2ee::Envelope, OpenError> {
    let context = Context { namespace: "myapp/v1", user, kid, method: Method::Prf };
    e2ee::seal(draws, prf, context, secret)
}

fn new_recovery_key(draws: &mut impl Draws) -> RecoveryKey {
    RecoveryKey::generate(draws)   // show `display()` once, seal with Method::Recovery
}

Turn the mode on in the routes with Auth::with_e2ee(). The routes then keep each envelope in the commit that adds, uses or removes its passkey:

CallAddsGets
POST /auth/signup/finish"e2ee": { "envelope", "recovery_envelope", "recovery_verifier" }
POST /auth/login/finish"envelope": the one of the passkey that was used
POST /auth/passkeys"envelope" for the new passkey
DELETE /auth/passkeys/{id}its envelope goes too
PUT /auth/recovery/key"envelope" sealed with the new recovery key
POST /auth/recovery/key/start"envelope" sealed with the recovery key; a decoy for an unknown name
POST /auth/recovery/key/finish"envelope" for the new passkey
  • A call without its envelope, or with one when the mode is off, gets 400 invalid_request.
  • A passkey from before the mode logs in without an envelope. Give it one by adding a new passkey with the secret.
  • recovery_verifier is the public key of recovery::recovery_signer(namespace, key): the recovery key both opens its envelope and proves the recovery.
  • Recovery by email, by a link or by an owner gets 403: it cannot restore the key.
  • Ask for the PRF extension with e2ee::prf_input(namespace) in create and get. Never send its output.
  • Without the routes: add e2ee::attach_passkey and attach_recovery to the signup’s commit, and e2ee::detach to a passkey’s removal.
  • New identity: replace_identity, with your own rewrapped data in the same commit.
  • Losing every passkey, the recovery key and every device loses the data. Say so in the page.

Support: see the application as a user

Nobody may, until the application says so.

use auth_chad::axum::{Caller, Hooks, InPerson, ViewMode};
use auth_chad::sqlite::SqliteStore;
use auth_chad::{Authenticated, UserId};

struct App;

impl Hooks<SqliteStore> for App {
    async fn may_view(&self, who: &Authenticated, user: UserId) -> Option<ViewMode> {
        None   // is `who` support staff, and may they see this user?  Some(ViewMode::ReadOnly)
    }
}

// Only the user in person: a billing portal, a data export, an address change.
async fn export(who: InPerson) -> String {
    format!("{:?}", who.user())
}

// For an audit: both people.
fn people(caller: &Caller) -> Option<(UserId, Option<UserId>)> {
    let who = caller.who().ok()?;
    Some((who.user().ok()?, who.view().map(|v| v.by)))
}

In the browser: await viewAs(user) from a click, with a recent passkey. session() then has view: show it on every page, with a button for await endView().

What the library does, without a list of paths to maintain:

  • FreshLogin refuses a view. So every sensitive action of the application refuses it.
  • The account API refuses it: passkeys, sessions, devices, apps, recovery, invites, signed links, events.
  • ReadOnly allows only safe methods. A GET that changes something is a mistake of the application.
  • A view ends after an hour, with the person’s own login, if either account is disabled, and if the user ends it in the list of sessions. It needs the person’s own cookie beside it.
  • After the end, requests fail with view_ended until endView(). They never continue as the person’s own account.
  • Both people have an event with the other’s ID: viewed and view_as.

A handler with FirstParty accepts a view. Use InPerson where only the user may act.

Tests

use auth_chad_testing::{MemStore, World, block_on};
use auth_chad::{Store, passkey};

fn a_login_starts() {
    block_on(async {
        let w = World::default();   // memory store, fake clock, repeatable randomness
        let options = passkey::login_start(&w.ctx(), &mut w.draws()).unwrap();
        assert_eq!(options.rp_id, "login.example.com");
        w.clock.advance(301);       // the ceremony is over
        w.store.commit(vec![]).await.unwrap();
    });
}
  • World::passkey(1) is a passkey in software: create and get.
  • HTTP: Auth::new(config, &[1; 32], MemStore::default())?.with_sources(clock, draws) and router.oneshot(request). rust/adapters/axum/tests/http.rs has every step.
  • Browser: rust/examples/minimal/e2e/run.mjs drives Chromium with a virtual passkey and no packages.
  • Never put a real token, key or address in a test.

auth-chad in a Loco application

It works with Loco 1.1 to 1.3 and SeaORM 2, on SQLite and PostgreSQL. A whole application, with tests, is in rust/loco/example.

You want to seeFile
The wiringsrc/app.rs
Users rows in the signup transactionsrc/accounts.rs
The migrationsrc/migration.rs: auth_chad::sea_orm::create(conn, &prefix, &[]), with features such as Feature::Tenants if you use them; a later migration adds one with upgrade
Extractors for the user’s row and the organizationsrc/extractors/mod.rs
Middleware that knows the caller, and who views (audit)src/middleware/mod.rs
Routes with a user, a visitor, a recent passkeysrc/controllers/home.rs
Data of an organization, with Loco’s tenant scopesrc/controllers/notes.rs
A role and a recent passkey togethersrc/controllers/orgs.rs
Connected apps (MCP)src/controllers/apps.rs
Moving accounts with passwordssrc/controllers/legacy.rs
Tests with Loco’s test servertests/requests.rs
cd rust/loco
cargo run -p example-loco -- start   # in example/: http://localhost:5150
cargo test

Wiring

async fn after_context(ctx: AppContext) -> Result<AppContext> {
    auth::install(&ctx, accounts::build);
    Ok(ctx)
}
async fn initializers(_: &AppContext) -> Result<Vec<Box<dyn Initializer>>> {
    Ok(vec![Box::new(auth::Tables::<AppAuth>::default())])      // refuses to start without the key or the tables
}
async fn before_routes(ctx: &AppContext) -> Result<Router<AppContext>> {
    auth::routes::<AppAuth>(ctx)                                // /auth, /oauth, /.well-known
}
fn middlewares(ctx: &AppContext) -> Vec<Box<dyn MiddlewareLayer>> {
    auth::middlewares::<AppAuth>(ctx)                           // Loco's, and the caller
}
fn register_tasks(tasks: &mut Tasks) {
    tasks.register(auth::Work::<AppAuth>::default());           // auth_work: prune, mails, places
}
settings:
  auth_chad:
    namespace: example/v1
    issuer: https://api.example.com
    rp_id: example.com
    rp_name: Example
    origins: ["https://example.com"]

The environment variable AUTH_CHAD_MASTER has the master key: 32 random bytes, base64url without padding. It is not in the YAML file, because cargo loco doctor --config prints the configuration. The server does not start without it. Tasks of auth-chad need it too; db migrate and other commands do not.

Why it is like this

  • before_routes, not after_routes. Routes that are added in after_routes are outside of Loco’s middleware: no request ID, no panic handler, no remote IP.
  • install takes a function. Loco calls after_context for each command, and before it runs migrations. The function runs once, when the server starts (Tables) or when a task needs it.
  • The middleware is innermost. It runs after Loco knows the remote IP, and not for static files. Your middleware that reads the caller goes to index 0.
  • Extractors read the request, not the state. Loco’s state is always AppContext, a type of Loco.
  • users.pid is the auth-chad user ID. Both are 16 bytes. Your integer keys stay.
  • An organization is data of the application. Use one auth-chad tenant (the root) and memberships in your tables, as OrgContext does. A separate tenant is for separate logins.
  • Reject with a response, not with a Loco error, in extractors. A Loco error loses WWW-Authenticate and is logged as an error for each visitor. auth_chad_loco::refused is for handlers.

What it replaces

Remove auth: from the configuration, the auth feature of loco-rs if you need no password hashes, the auth::JWT and JWTWithUser extractors, Authenticable, and the password, magic link and reset columns. Generated controllers use auth::JWT: replace it with CurrentUser or your own extractor.

Exclude the tables from cargo loco db entities: add them to ignore-tables in [package.metadata.db.entity].

Worker

Run the task auth_work from Loco’s scheduler every few seconds. It removes expired rows, sends the mails that wait and runs the work of places. Any number of processes can run it at once.

scheduler:
  jobs:
    auth_work:
      run: auth_work
      cron: "*/10 * * * * *"

Start the scheduler in the process that should do the work: cargo loco start --scheduler, or a worker process. Behind a load balancer, set Loco’s trusted proxies (remote_ip middleware): auth-chad uses the address that Loco gives.

Gaps

GapEffectPlan
The router serves one tenant (the root)Separate logins need own routes. The extractors already use a Tenant in the requestTenant from the request in adapters/axum
A read of the database for each request with a credentialSlower than a JWT; a logout works at onceAccepted
cargo loco routes does not list /auth and /oauthOnly the listLoco lists its own routes only
API keys are offMachines use a device with its own key, and need DPoPapi-keys, if a program can send only a header
No typed audit detailsThe example records method, path, status and userNeeds a decision
rusqlite (auth-chad-sqlite) and SQLx share one libsqlite3-sysSQLx needs a version below 0.41 and rusqlite 0.43 has 0.40, so both build together today. A newer rusqlite can break thatUse one of them in an application
The SeaORM adapter has more dependencies than the others183 crates with both drivers, and 84 for auth-chad-postgresAn application with SeaORM has them already

Ideas from a Loco application with several organizations

Taken:

  • One middleware finds the caller. Extractors and other middleware read it. It was one check in each extractor.
  • An optional caller, for pages that visitors also see.
  • An extractor for the organization that is the only place that decides membership.
  • An audit middleware inside the authentication layer.
  • View as, for support. It is a property of Authenticated, so Fresh refuses it, and there is no list of paths that someone must keep complete. See view-as.
  • resource_metadata in the challenge of an API for MCP clients. The adapter did not send it, and MCP clients need it.

Worth a decision:

  • Audit details from the handler. A handle in the request that a handler fills, and the middleware stores.

Not taken: stateless JWT sessions, bearer tokens for first-party apps, and API keys that act as the user.

Specification

Draft 0, profile AC1. The key words MUST, MUST NOT, SHOULD and MAY are used as in RFC 2119 and RFC 8174.

FileContent
00-conventionsEncodings, algorithms, labels, the profile
01-modelRealms, tenants, users, credentials, proofs, policies
02-flowsHow a flow decides, preconditions, effects
03-passkeysRegistration and login
04-sessionsCookies, key-bound tokens, fresh login
05-signupOpen, invite only, external proof
06-recoveryRecovery key, owners, email
07-devicesCLIs and machines
08-providerFirst-party and connected apps
09-external-identityOpenID Connect at another provider
10-storageSchema, table prefix, transactions
11-tracesTrace format
12-e2eeIdentity keys for end-to-end encryption
13-api-keysSecrets for programs that cannot hold a key
14-tenantsTenants, memberships, entering a tenant
15-placesWhere the data of a tenant or a user is, with a separate directory
16-encrypted-syncDraft, not built: an encrypted keyring and log for each user

Values marked † are proposals that need a review before the profile is final.

00 Conventions

Encodings

  • Time is an integer: seconds since the Unix epoch. There are no leap seconds.
  • Binary values in JSON and URLs are base64url without padding. A decoder MUST reject padding, other characters and non-zero trailing bits.
  • JSON that is signed, hashed or compared is canonical (RFC 8785). A parser MUST reject duplicate members.
  • A parser MUST reject trailing data. Each format has a maximum size, and a parser checks it first.
  • Random values have at least 128 bits. Tokens and challenges have 256 bits.

Profile AC1

A profile is a fixed set. A deployment runs one profile. There is no negotiation inside a profile.

UseAlgorithms
Passkey signaturesES256, Ed25519, RS256 (COSE -7, -8, -257)
DPoP and device signaturesES256, Ed25519
ID tokens of other providers, client assertionsES256, Ed25519, RS256
ID tokens of this providerES256, or RS256 if the application adds an RSA key
Hash of tokens at restSHA-256 over 256 bits of entropy
DerivationHKDF-SHA256
MACHMAC-SHA256
Encryption (e2ee)XChaCha20-Poly1305; HPKE X25519, HKDF-SHA256, ChaCha20-Poly1305

The key fixes the algorithm. A verifier MUST NOT take the algorithm from a message: it compares the message’s alg with the key’s and rejects a difference. alg: none and symmetric alg values are always rejected.

ECDSA: keys are uncompressed P-256 points on the curve. Ed25519: verification is strict, and small-order keys are rejected. RSA: 2048 to 4096 bits, exponent 65537, PKCS #1 v1.5 with SHA-256. Only passkeys and other parties use RSA: this profile never makes an RSA key for a user, a device or a session.

Labels

Every derivation, MAC and signature has a label <namespace>/<purpose>. The application sets the namespace once, for example example/v1. Two purposes never share a label.

input(label, parts…) = label || for each part: u32_be(len) || part

Server keys

The server holds one 32-byte master key. Nonce, ceremony and cookie keys are derived from it. Provider signing keys are separate, have a kid, and rotate with an overlap that is longer than the longest token.

Errors

A refusal has a stable code. The text for a person is the application’s. Two refusals that would let a caller learn if an account exists MUST have the same code, the same shape and comparable work.

Upper limits

ValueUpper limit †
Ceremony5 minutes
First-party access token15 minutes
Browser session1 day idle, 7 days absolute
Native or CLI session, key-bound90 days idle
Connected-app access token1 hour
Connected-app refresh token90 days idle, one use
Invite7 days
Device code15 minutes
Fresh login15 minutes

An application MAY set shorter values. It cannot set longer ones.

01 Model

Realm and tenant

  • A realm is one set of users, one WebAuthn RP ID and one login origin.
  • A tenant belongs to one realm and has a 16-byte ID. An application without tenants uses the root tenant: 16 zero bytes.
  • A passkey belongs to a realm, because it is bound to the RP ID. Tenants on other domains use the provider (08) and send the user to the login origin. Implementations MUST NOT use related origins to share passkeys between tenants.

Isolation

  • Every tenant-scoped storage operation takes the tenant as an argument. A form without one MUST NOT exist.
  • Every tenant-scoped MAC, derivation and token includes the tenant.
  • Each tenant has its own issuer, and its own provider keys.
  • An identifier from one tenant that is used in another gives the same refusal as an unknown one.

User

A user has an ID (16 bytes, random by default; an application maps its own IDs to 16 bytes), a state (active or disabled) and credentials. Names, addresses and profile data belong to the application. An identifier such as a handle or an email address is optional, and unique in the realm if used.

Disabling a user ends sessions, tokens and device keys in the same commit.

Entering a tenant

A user may enter a tenant with an active membership (14). A session is for one tenant. Entering another tenant creates another session, and can need another login if that tenant’s policy is stricter. The library stores no roles: the application adds its own columns to the memberships table.

Credentials

KindHeld byProves
PasskeyA personThe person
Device keyA CLI, native app or machineThe device, and the user that approved it
Session key (DPoP)A browser or appThe session
API key (13)Whoever has itThe scopes that its user gave it
External identityA person at another providerA claim, never a login
Recovery methodA personPermission to create a passkey

Proof

A successful check gives an Authenticated value:

FieldContent
subjectUser or device
tenantTenant
levelfirst_party, connected(client, scopes) or api_key(id, scopes)
methodsWhat was proved, for example passkey with user verification
proved_atTime of the last passkey assertion
bindingKey thumbprint, or cookie, or bearer

Only the library can create it. A handler states what it needs in its type: level, maximum age, binding. A request that does not have it never reaches the handler.

Policy

A policy is a set of requirements. Policies from the profile, instance, tenant and route combine to the strictest:

RequirementCombine
LifetimesMinimum
Maximum age of a passkey assertionMinimum
Passkey must not sync (BE flag clear)Or
External identity required: list of providersBoth lists must be satisfied
Signup modes, recovery methodsIntersection
Binding requiredOr

Combination MUST be associative, commutative and idempotent. An empty signup set means that nobody can sign up.

A requirement that the current login does not meet gives the refusal step_up_required, with the requirement.

02 Flows

Contract

A flow step is a function that decides:

step(context, reader, draws, input) -> decision | refusal
context  = time, realm, tenant, policy, settings, caller's address
decision = output, writes
refusal  = code
  • A step reads through reader only, and gets random bytes from draws only. With the same answers from both it gives the same decision, in every language.
  • A step MUST NOT read a clock, a random source, the network or the environment, and MUST NOT write.
  • A decision has no effect until its writes are committed. The output MUST NOT be used before that.
  • A refusal changes nothing. A step that must change state and answer with an error (a poll that is too early, a reused token) returns a decision whose output is the error.

Writes and preconditions

Between reads and commit, another request can change the state. Each write therefore has its precondition:

WritePrecondition
insert(row)No row with this key or unique value
replace(row, version)The stored row has this version
delete(key, version)The stored row has this version
require(key, version)The stored row has this version (no change)
delete_where(column, value)None

Writes are plain data. An application can add them to its own transaction. Each row has a version that grows with every change. Writes apply in order.

commit(writes, app_writes) runs in one transaction. If a precondition fails, nothing is stored and the result is conflict. A caller MAY run the flow again, at most three times. It MUST use new draws.

Security decisions MUST depend only on loaded state that a precondition protects, or on state that cannot become less permissive in a harmful way. Each flow lists its protected reads.

Single use

A challenge is used by inserting its hash. An invite or a device request is deleted, and a code or a refresh token is marked as used, with its version. This is in the same commit as the result. Of two requests with one token, exactly one succeeds.

Effects

An effect is work outside the database: send mail, call back a client. Effects are stored in an outbox in the same commit, and run at least once after it. An effect has an ID, so that a receiver can ignore a repeat. Each effect has a lease (10), so that two processes do not run it at the same time. The secret part of a mail is in the outbox only until it is sent.

Audit

Every decision that changes an account gives an event: time, tenant, subject, action, target, the client address and the device of the caller if known, and method. An application can keep addresses out of events. Events have no secrets, no names and no free text from a client. They are writes, so a change without its event cannot exist.

Ceremonies

A ceremony spans two requests. Its state is in a MAC-protected token that the client returns, with the challenge, kind, tenant and expiry. The challenge is stored as used at the end (single use), so a ceremony works once.

03 Passkeys

WebAuthn Level 3, with the following policy.

Both ceremonies

  • User presence and user verification are required.
  • The origin matches a configured origin exactly. crossOrigin: true and any topOrigin are rejected.
  • The RP ID hash matches the realm.
  • Client data is valid UTF-8 JSON. Authenticator data has no trailing bytes. Extension data is one CBOR map.
  • BS without BE is rejected. BE MUST NOT change after registration.

Registration

  • residentKey: required, userVerification: required, attestation: none.
  • The public key has exactly the required COSE parameters.
  • The client sends excludeCredentials for a user that has passkeys.
  • A credential ID is unique in the realm, at most 1023 bytes.
  • The WebAuthn user handle is the user ID. It is not personal data.

Login

  • Discoverable credentials only. The login page asks for no identifier.
  • The assertion carries the user handle, and it matches the credential’s owner.
  • The signature counter MUST increase if either side is non-zero. Otherwise the assertion is refused and an event is written.
  • A login starts a new session. It never continues an old one.

Managing

  • Adding and removing a passkey needs a fresh login on the first-party level.
  • A user keeps at least one passkey. Removing one ends the sessions that it started.
  • A change sends a notice to the user, if the application has a way to.

Client rule

A browser can refuse a second passkey prompt without a new user gesture. A client MUST NOT start two prompts from one gesture.

04 Sessions

Key-bound sessions

For JavaScript clients, native apps and CLIs. The client makes a key pair for the session and proves it with DPoP (RFC 9449).

  • When the policy requires key-bound sessions, a login without a proof is refused with invalid_dpop_proof.
  • The server requires a nonce in each proof, and accepts each jti once in the proof’s window, in all its processes (10).
  • htm, htu, iat, nonce and, with a token, ath are checked. The key’s thumbprint (RFC 7638) is in the token record.
  • The access token is opaque: 256 random bits. The server stores its hash.
  • A renewal needs a proof with the session’s key. It gives a new token and does not extend the absolute limit.
  • Platform hardware keys SHOULD be used where they exist. That is why the profile has ES256.

For page loads, where a browser cannot send a proof.

  • Name __Host-…, with Secure, HttpOnly, Path=/, SameSite=Strict. An application that needs to arrive logged in from a link MAY use Lax.
  • The value is 256 random bits, stored as a hash. It changes at login, at step-up and when the tenant changes.
  • A request that can change state MUST have an allowed Origin, and Sec-Fetch-Site: same-origin if the header is present. GET changes nothing.
  • A cookie session reaches sensitive handlers only with a fresh login.

Fresh login

A fresh login is a new passkey assertion, bound to the session and to the action’s name. It satisfies Fresh<n> for at most n seconds. Sensitive actions include: credentials, recovery, sessions of others, account deletion, approving a device, and consent to a connected app with write scopes.

Media and downloads

Some players and download managers send neither a proof nor a safe cookie. The application can create a signed link: one path, one method, one subject, at most 10 minutes†, MAC with a purpose label. It gives no session.

Ending

Logout ends one session, and the sessions in tenants that it is the root session of (14). “Log out everywhere” ends all sessions, tokens, connected-app grants and API keys of the user, and can keep device keys. Both are commits: after them, no token works.

Refused

Tokens in URLs, tokens in localStorage without encryption, sessions without an absolute limit, and “remember me” that skips the passkey.

View as another user

A person can see the application as another user, for example for support. The application decides who may.

  • It needs a fresh login, and is a session of the user with the person (actor) and the person’s session (parent).
  • It is valid only with the parent session, for one hour†, and not longer than the parent. It opens no other view.
  • It is not a proof of the user: there is no time of a proof, so nothing that needs a fresh login accepts it. Functions that change an account, a session or a credential, or make a link or a grant, refuse it.
  • A read-only view allows safe methods only.
  • With cookies, it has its own cookie beside the person’s cookie. If it is there and not valid, the request is refused, and not treated as the person’s own.
  • Both users have an event that names the other. The user sees it in the list of sessions, and can end it.

05 Signup

Signup has two parts: permission, then a passkey. Permission alone creates nothing.

Modes

ModePermission
openAnyone, with rate limits
inviteA single-use invite
externalA verified claim from an external identity provider (09), that matches an invite or a tenant’s rule
appThe application says so, for example after it checked an old password

A tenant’s policy gives the allowed set. The instance can allow fewer. The application chooses who may create invites.

Grant

Permission gives a signup grant: realm, tenant, mode, optional fixed identifier, optional verified claims, expiry. It is part of the ceremony token, and the step that creates the user consumes its source in the same commit. If an invite is cancelled while a signup runs, that signup is refused.

Creating the user

One commit: consume the permission, insert the user, insert the passkey, insert external identities, insert the recovery method if given, write the event, add the application’s own rows.

Invites

  • 256 random bits, stored as a hash, shown once, at most 7 days, single use.
  • An invite can be listed and cancelled. A list never shows the link.
  • An invite gives no rights by itself. The application can attach its own data to it.

Verifying an email address

A link with a single-use token. Opening the link shows a page with a button; only the button’s request uses the token, because mail scanners open links. A verified address is a claim, not a login.

06 Recovery

Recovery gives permission to create a passkey for an existing user. It is not a login. An application chooses its methods; policy can only remove some.

MethodStrength
Another passkeyNot recovery: log in with it
Recovery keyStrong: 256 bits, shown once, stored as a verifier
Approval by tenant ownersStrong, if people check each other by another channel
EmailWeak. MUST NOT be enabled together with e2ee

All methods

  • All sessions and tokens of the user end in the same commit that adds the new passkey.
  • The user gets a notice on every known channel.
  • Other passkeys stay. For 72 hours† a recovered account cannot remove passkeys that are older than the recovery, change its recovery methods or its addresses. A person who lost the mailbox but has a passkey can therefore take the account back.
  • A login with an older passkey in this time can undo the recovery. One commit removes what was added since the recovery: passkeys and their sessions, devices and their tokens, external identities and a recovery key. It also removes every connected-app grant, authorization code and API key. What the caller did to application data, or to other accounts, belongs to the application: the audit log shows it.

Email

  1. A request gives the same answer, after the same time, for known and unknown addresses. A message that cannot be sent is tried five times and then removed: it has a secret.
  2. The account waits 24 hours†. Notices go out at the start. Any logged-in session can cancel.
  3. After the wait, a single-use link allows one passkey registration.

A tenant with stricter rules can require a longer wait or an owner’s approval in addition.

Recovery key

A user signs a server challenge with a key from the recovery key, or opens an envelope with it (e2ee). The server never sees the recovery key. It can be replaced after a fresh login.

07 Devices

CLIs and machines use RFC 8628, with a key from the first request.

Request

The device makes its keys and sends the public key, a name and a requested scope with a DPoP proof. The answer has a device code, a user code and the verification address. The fingerprint of the device key is shown on the device.

Approval

  • On the first-party level, with a fresh login.
  • The page shows the fingerprint, the name, the requested scope, the time, and the country or network of the request if the application knows it. The user confirms that the fingerprint is the same on the device.
  • A user code alone opens nothing: 8 characters from an unambiguous alphabet, rate-limited, single use, at most 15 minutes.
  • Denying is one click, and ends the request.
  • The application decides which scopes a device may ask for, who may see, approve and deny a request, and the kind of the approved device. It can add its own writes to the commits of an approval and a revocation.

Tokens

  • A device gets access tokens by signing an assertion (RFC 7523) with its key. There is no refresh token and no shared secret.
  • The device key is the only credential. Revoking it ends its tokens in the same commit.

Kinds

KindActs asEnds
User deviceThe user, first-partyWith the user or when revoked
MachineItself, with a scope from the applicationWhen revoked; survives the user that approved it, if the application says so

A machine never satisfies Fresh.

08 Provider

An OAuth 2.1 authorization server with two fixed levels (decision 001).

Both levels

  • Authorization code with PKCE S256 only. A code lives 60 seconds, works once, and reuse revokes what it gave.
  • Redirect URIs match exactly. Loopback addresses (RFC 8252) may differ in port only.
  • A bad request shows an error page and never redirects: anyone can register a client, so a redirect without the user’s choice would make the server an open redirector.
  • iss in every authorization response (RFC 9207). Metadata per RFC 8414.
  • resource (RFC 8707) is required. A token has one audience, and an API MUST check it.
  • Tokens are opaque. ID tokens exist only for openid requests, are signed, and are for the client only.
  • The user is asked for consent by the login origin. No consent is remembered for write scopes of connected apps.

First-party clients

Registered by the application in its configuration. They use pushed requests (RFC 9126) and DPoP. Confidential clients use private_key_jwt. This is the base for login on tenant domains.

Connected apps

Apps by others, for example agents that connect through a protocol with public clients and bearer tokens.

Rule
RegistrationClient ID Metadata Documents first; RFC 7591 where a protocol needs it, rate-limited, removed when unused
Client authenticationprivate_key_jwt if the client offers it, else public with PKCE. No client secrets
TokenBearer, or DPoP if the client offers it. Once a grant used DPoP, it stays with DPoP
Access tokenAt most 1 hour
Refresh tokenOne use. Reuse of an old one revokes the grant
ScopeFrom a list that the application marks as allowed for connected apps
NeverCredentials, sessions, recovery, devices, consent, invites
Protected resource metadataRFC 9728 for each API
The user canList, inspect and revoke grants

A metadata document is fetched over HTTPS from a public address only. The fetcher refuses redirects, private, loopback and link-local addresses after DNS resolution, and more than 64 KiB†, and has a timeout. The consent page shows the client’s host name, because a name in a document proves nothing.

Relation to other profiles

First-party clients follow the direction of FAPI 2.0, plus rules for public clients. ID tokens are signed with ES256. An application whose clients need RS256 adds an RSA key, which OpenID Connect Core requires of a provider. Other parts of OpenID Connect (userinfo, dynamic scopes, front-channel logout) do not exist, so this is not a certified provider.

09 External identity

Another OpenID provider can prove a claim. Uses: permission to sign up, linking, a tenant rule (“a valid company login is required”).

  • Authorization code with PKCE, state and nonce, all bound to the browser. iss is checked (RFC 9207) where the provider sends it, and one redirect URI is used for each provider.
  • The ID token’s signature is always verified, with keys from the provider’s published set. The key fixes the algorithm.
  • The identity is the pair (iss, sub). An email address is never used as a key for an account.
  • email_verified counts only for a provider that the application lists as authoritative for that domain.
  • Tokens from the provider are discarded, unless the application asks for them and stores them itself.

The way back

The provider’s redirect comes from another site, so the browser does not send the session there. The callback checks the answer, opens no session, and puts the checked identity into a __Host- cookie (HttpOnly, SameSite=Lax, five minutes, for one purpose). A page of the application then uses it: for a signup, or with a fresh login for a link. A start needs an allowed Origin.

Required company login

A signup with an identity of this provider has the required login.

A tenant can require a recent login at its own provider and a passkey. The requirement has a maximum age. When the company removes a person, the next check fails, and the person cannot enter the tenant.

Linking needs a fresh login. Two users cannot link one (iss, sub) in a realm.

10 Storage

Schema

schema/ has the reference schema for SQLite and PostgreSQL: the core (sqlite.sql, postgres.sql) and each feature (sqlite.tenants.sql, …). An implementation in any language that uses these tables can run on the same data. Column meanings are part of this specification. Indexes are not.

Secrets in rows are hashes, public keys, verifiers or ciphertexts. No row alone lets its reader act as a user, except an unsent mail in the outbox.

Table prefix

Auth tables live in the application’s database. Their prefix is configurable.

  • Default auth_. Pattern ^([a-z][a-z0-9_]{0,14}_)?$: empty, or at most 16 characters that end with _. A start with sqlite_ or pg_ is refused. A prefix goes into SQL text, so an implementation MUST check the pattern before it builds any SQL.
  • The prefix applies to tables, indexes, constraints, sequences and triggers. Base names have at most 40 characters, so that a full name fits the 63 bytes of PostgreSQL.
  • On PostgreSQL the schema (namespace) is configurable too, with the same pattern without the last _. SQL names it explicitly and does not use search_path.
  • Two installations with different prefixes can share a database. They share nothing else: the prefix is not part of any key derivation, token or trace.
  • Migrations run as an explicit step. Opening a store MUST NOT create tables. With a wrong prefix, opening fails with schema_missing. Otherwise a typing error would start an empty user database, with open bootstrap.
  • rename changes the prefix of an installation in one transaction, while no server runs.

Application tables can refer to <prefix>users.

Transactions

commit(writes, app_writes) (02) runs both in one transaction, at an isolation level where the preconditions hold until commit: SQLite with an immediate transaction; PostgreSQL with row locks for require, replace, delete and consume, and unique keys for insert. Row locks are taken in key order.

app_writes can read and write application tables. If it fails, nothing is stored.

Migrations

The version number of the core is in <prefix>meta. Migrations are append-only and apply in one transaction where the database allows it. A server refuses a version that it does not know. Opening never migrates: the migration step does, from version 4 on.

VersionAdds
6limits, leases, features

Version 5 existed only before a release, and has no migration.

Features

Some tables exist only when the application uses them. The migration step adds the tables of the features that it is given, and records each in <prefix>features with its level. It never removes a feature.

FeatureTablesNeeded for
tenantstenants, membershipsTenants (14)
placesplacesA separate directory (15)

A server that is configured for a feature MUST refuse to start when the database does not have its tables. Columns named tenant in core tables exist in every database: without tenants they hold the root tenant.

Shared state

Any number of server processes can use one store. State that a check needs is in the store, never in the memory of one process:

  • Single-use marks (used): the hash of each DPoP proof’s key and jti, and of each client or device assertion’s subject and jti, until the proof or assertion expires. A second use is refused. A ceremony’s challenge is a mark too.
  • Call limits (limits): one row for each counted call, under the hash of its key (a client address, or a user) and the minute. A refused call writes nothing, so a key has at most its limit of rows. Calls at the same moment can pass the limit by their number. The key is hashed, so the table holds no address.
  • Leases (leases): a piece of background work runs in one process at a time. A lease has an end, so a process that stops does not hold it for ever. Work that takes longer than its lease can run twice.

The client address that limits count is the address of the connection. Behind n proxies it is the n-th entry from the end of X-Forwarded-For, without a port: each proxy adds one, so a client cannot choose it. An entry that is not an address gives no address. The server must be reachable only through these proxies.

Retention

Expired rows (tokens, challenges, invites, single-use marks, limits and leases) are removed in small batches, by background work that runs every few seconds. Audit events and client addresses have separate retention times that the application sets.

11 Traces

A trace is a JSON file that fixes all inputs of a flow and gives the expected decision. Every implementation replays every trace.

{
  "trace": 1,
  "profile": "AC1",
  "name": "invite signup, cancelled while it runs",
  "namespace": "example/v1",
  "settings": { "rp_id": "login.example.com", "origins": ["https://login.example.com"] },
  "steps": [
    {
      "flow": "signup.start",
      "time": 1700000000,
      "tenant": "t1",
      "draws": [ ["user", "AwQF…"], ["challenge", "AAEC…"] ],
      "reads": [ { "get": "invites", "key": ["…"], "row": { "…": "…" }, "version": 1 } ],
      "input": { "invite": "…" },
      "expect": { "output": { "…": "…" }, "writes": [] }
    }
  ]
}

(The values in this example are shortened.)

State: the format is a draft. Traces are not recorded yet; the Rust tests cover the same flows in memory.

Rules

  • time and draws are the only sources of time and randomness. Draws have a name and a length, and come in order. A step that asks for another draw fails, and so does a step that leaves one unused.
  • reads are in order, with their answers. A row that does not exist is null.
  • Comparison is exact, on canonical JSON (RFC 8785). writes are in order and include preconditions.
  • Signatures in traces are deterministic: Ed25519, and ECDSA as in RFC 6979.
  • A trace MUST NOT have data of a real person or a live key.
  • A refusal replaces output in a refused step. Its code is compared, not its text.

Coverage

Each normative sentence with MUST or MUST NOT that a flow can violate has at least one trace that fails if an implementation ignores it. A trace names the sentence by file and heading.

Storage behavior (races, crashes, preconditions) cannot be a trace. The storage conformance tests cover it.

Black-box runner

conformance/ runs scenarios over HTTP against a live test server: wrong origin, replay, reused codes, mixed tenants, downgraded algorithms, missing nonces. It needs no access to the implementation.

12 End-to-end encryption (optional)

Gives each user an identity key pair that the server cannot read. The application builds on it.

  • The identity key is sealed once for each passkey, with the WebAuthn PRF output, and once for the recovery key.
  • The PRF input is fixed: <namespace>/passkey-prf. Each credential has its own PRF secret, so outputs differ. One prompt signs and gives the output.
  • The envelope has a random salt, so that two envelopes never share a wrapping key.
  • PRF output never leaves the client. A client removes it from what it sends.
  • A user device gets the identity key sealed to its own key by the approving client, after both sides compared fingerprints.
  • Replacing the identity key is signed by the old one, needs a passkey assertion, and runs application writes in the same commit, because the application must seal its data again.
  • With e2ee, recovery by email, by a link and by owners cannot restore the key, so the server refuses it. Only a passkey, the recovery key or a user device can.

In the routes

Each envelope is in the commit that adds, uses or removes its passkey. A request without its envelope, or with one when the mode is off, is refused.

  • Signup stores the passkey’s envelope, the recovery envelope and the recovery key’s verifier.
  • Login returns the envelope of the passkey that was used.
  • Adding a passkey stores its envelope; removing it deletes the envelope.
  • A new recovery key replaces the recovery envelope and the verifier together.
  • Recovery with the key returns the recovery envelope before the proof. For an unknown name it returns a decoy that has the same shape and is the same each time, so the answer does not show which names exist. Finishing stores the new passkey’s envelope.
  • Undoing a recovery deletes the envelopes sealed since the recovery.

In a browser

The identity key is kept for the life of the session, encrypted with a non-extractable key. This protects a copy of the browser profile that lacks that key. It does not protect against a script on the origin. See THREATS.md.

13 API keys

For programs that can only send a fixed header. Off unless the application turns them on, and not recommended: a device key (07) or a connected app (08) does the same without a secret that can be copied.

Form

<prefix><secret>. The prefix matches ^[a-z][a-z0-9_]{0,14}_$, belongs to the application and never changes, so that scanners find keys. The secret is 256 random bits in base64url, 43 characters. No other token has this length with the prefix. The server stores SHA-256 of the whole text.

Creation

  • It needs the user in person, with a fresh login. The application decides who may, and for which scopes.
  • Name, scopes and lifetime are required. The lifetime is at most 90 days†. An implementation refuses a longer one and does not shorten it. Use does not extend it, and there is no renewal.
  • Scopes come from the list of the application, which is not empty.
  • The secret is in the answer once.

Use

  • Only Authorization: Bearer. Never a URL, a cookie or a body.
  • The level is api_key, the binding is bearer, and there is no time of a proof. It is not first-party, not fresh, and not a connected app. An account API never accepts it.
  • Scopes that the application no longer offers are not given.
  • The record gets the time and address of the use at most every five minutes. A new address makes an event.
  • A policy that needs key-bound sessions refuses every API key. So does an application that turned them off.

End

A key ends with its lifetime, when its user ends it, with “log out everywhere”, a recovery or the undo of one, and when the user is disabled. Ending it needs no fresh login and works while the key is in use.

14 Tenants and memberships

A tenant is a boundary for sessions, for example an organization or a customer. It is not a role system. Its tables are the feature tenants (10).

Tenant

ColumnContent
id16 random bytes
nameThe tag in a host name or a path: ^[a-z0-9](https://github.com/audiochad/auth-chad/blob/main/spec/[a-z0-9-]{0,30}[a-z0-9])?$, unique
createdTime

The root tenant (01) has no row and no memberships. The HTTP layer refuses a name whose tenant host would be a configured origin.

Tenant names are not secret: a host or a path shows that a tenant exists. What a refusal does not show is whether a person may enter it.

Membership

A membership says who may enter a tenant. The library owns four columns: tenant, user, state (active or suspended) and version. The application MAY add its own columns, for example a role. Each one MUST have a default in the database, because the library inserts only its own columns. The application can set them in the same transaction.

  • Memberships are in the same database as users, so that one commit can end a membership and everything that it allowed.
  • The library reads the application’s columns with each request in a tenant, and hands them to the handler. It does not use them.
  • An unknown tenant, and a tenant that the user may not enter, give the same refusal: not_found.

The rule

A session, token, device, grant or API key in a tenant needs an active membership of its user:

  1. when it is made: the commit has a precondition on the membership row;
  2. with each request: a membership that is gone or suspended refuses the request, also if a row was left behind.

Machines act as themselves (07), so rule 2 does not apply to them.

Entering

A login makes a root session: a session in the root tenant. A user enters a tenant with it.

  • Entering makes a session in the tenant with the root session as parent. It has the passkey of the root session, and its end is not later. Its proof time is the later of its own and the root session’s, so a fresh login at the login origin counts in every tenant.
  • Use of a session in a tenant renews its root session too.
  • The root session MUST be the user’s own: not a view, not a session in a tenant.
  • Ending the root session ends its sessions in tenants in the same commit.
  • A session in a tenant is valid only while its root session is valid.

On the tenant’s own host

A cookie belongs to one host. A tenant at <name>.<parent> therefore gets its session with a code:

  1. The tenant’s host makes a verifier (256 random bits) and keeps it in its own cookie __Host-enter, SameSite=Lax, at most 5 minutes. It sends the browser to the login origin with challenge = SHA-256 of the verifier.
  2. The login origin needs the root session. It makes a code: 256 random bits, stored as a hash, single use, 60 seconds, for one tenant, with the root session and the challenge. It sends the browser back to the tenant’s host.
  3. The tenant’s host sends the code and the verifier. A wrong verifier, another tenant, or a used or late code gives invalid_grant. A root session that ended gives unauthenticated, and a membership that ended gives not_found.

These two GET requests change state, as in the authorization code flow of OAuth. A code alone opens nothing: the verifier is in a cookie of the tenant’s host only. The address to return to MUST be a path on the same host: it starts with one /, and has only printable ASCII without \.

Key-bound clients enter at the login origin with their root token and a proof by the same key. A key-bound token renews in its own tenant, at any path.

Ending

ActionEnds in the tenant, in the same commit
SuspendSessions with their tokens, the user’s devices with their tokens, connected-app grants and their codes, API keys
EndThe same, and the membership row
Remove the tenantThe same for each member, the invites of the tenant, and the tenant row

Resuming a membership opens nothing: the user enters again.

Invites

An invite belongs to one tenant (05).

  • A signup with an invite of a tenant makes the user a member in the same commit. The signup opens a root session. Without an invite of that tenant, a signup in a tenant is closed.
  • A user with an account accepts an invite of a tenant: the invite is used and the membership is made in one commit. An invite for another identifier is refused, and a second membership is taken.

Requests

An application names the tenant of a request in one way, set when it starts:

WayTenantSession cookie
NoneRoot only__Host-session
Host<name>.<parent>. The hosts of the configured origins are the root tenant__Host-session on each host
Path<prefix><name>/… on the login origin__Host-session-<name>
  • With hosts, each tenant has its own web origin. A DPoP proof names the tenant’s host, and a request that changes state accepts the tenant’s own origin.
  • With paths, all tenants share one web origin. A script flaw in one tenant reaches the sessions of all open tenants. Browsers limit the number of cookies of a host: keep the open tenants of a person below 20†.

Accounts, sessions, recovery, invites and members are managed at the login origin with the root session. The application decides who may manage members, often from its own columns. The commit then has a precondition on the manager’s own membership row, so a manager who is suspended meanwhile cannot finish.

15 Places

An application can keep its data apart from the auth tables: the auth database is then the directory database. It has the users, the sessions, the tenants, the memberships, and for each tenant or user its place. The data is in one or many other databases. The table is the feature places (10).

Choice

An application places by tenant or by user. It chooses one when it is set up, and never has both. By tenant, a request outside a tenant has no place.

Place

ColumnContent
ownerThe 16 bytes of the tenant or the user
placeJSON of the application’s own type, at most 4 KiB
statecreating, active, moving or removing
generation1, and one more with each move
createdTime

The library does not read the content. It MUST NOT hold credentials: a password belongs to the configuration of the server that opens the database.

States

StateA requestNext
creating503 not_ready, Retry-Afteractive, when the application’s work says that the data is there
activeThe place and its generationmoving, removing
moving503 moving, Retry-Afteractive with the new place and the next generation, or the old place
removing404 not_foundGone, when the application’s work says that the data is gone

Work

A new place and its work are in the commit that creates the tenant or the user. A removal and its work are in one commit too. The work is in the outbox (02) and runs at least once after the commit.

  • Each call has an ID. A call can come again with the same ID, so the application’s work MUST be safe to repeat.
  • Each piece of work has a lease of 300 seconds†. Any number of runners can run at once, and one piece runs in one place at a time. Work that takes longer than its lease can run twice. Work that fails stays, and runs again when its lease ends.
  • Work to provision a place that no longer waits for it, for example after a removal, is dropped.
  • After a move, the data at the old place is the application’s to delete.
  • The application lists places that wait too long by their state.

Costs

A separate directory has no transaction across users and data, no foreign keys to users, and no consistent backup of both. The application keeps names that it shows in its own data. A restored directory has sessions that ended since the copy: after a restore, end all sessions, tokens and API keys.

16 Encrypted sync (draft, not built)

State: a proposal for review. Nothing here is implemented. Values marked † are proposals.

An application with end-to-end encryption (12) keeps each user’s data on the server as ciphertext and works on a local copy in each client, for example a SQLite database that the client queries directly. The library stores and orders the ciphertext and checks who may write. It never reads the data, and it does not merge it: merging belongs to the client.

Keys

  • The identity secret of 12 is the account key. Each passkey and the recovery key unlock it.
  • The keyring holds the content keys, one for each period, sealed with a key derived from the identity secret. A client adds a period to rotate: data written later uses the new key. Old periods stay, so old data still opens.
  • A new unlock method needs only the identity secret, not the other methods’ secrets.

Keyring

FieldContent
userOwner
version1, and one more with each change
periodThe current period
ciphertextThe sealed keyring, at most 64 KiB†
createdTime
  • A change names the version it replaces (compare-and-swap). A stale version is refused.
  • period grows by exactly one, or stays. A larger jump is refused.
  • The server keeps every version for 30 days† and returns them on request, so a broken update cannot destroy the only copy.
  • A change needs a fresh login, as for credentials (04).

Log

Each user has an append-only log of encrypted entries.

FieldContent
seqAssigned by the server: gap-free, one more for each entry of this user
deviceThe device that wrote it. It MUST be the device of the session
counterThe device’s own counter: one more for each entry of that device
periodThe period of the key that sealed it
previousThe hash of the entry before it, as the writing client saw it
ciphertextAt most 1 MiB†
signatureBy the writing device’s key, over all fields above except seq
  • An entry with an old period after the keyring moved on is refused.
  • A retry with the same device and counter and the same bytes returns the first seq. The same pair with other bytes is refused.
  • A read gives entries after a seq, in pages of at most 1000†, and the current head (seq and hash).
  • The application gets a hook when the head moves, for example to tell open clients.

Snapshots

  • A snapshot is the sealed state up to a seq (covers). A client writes one when its log is long, for example every 300 entries†.
  • The server keeps the 2† newest snapshots, and may delete entries up to the older one’s covers. A client that asks for deleted entries gets 410 compacted, and starts from the newest snapshot.
  • Snapshot bodies can be in an object store. The table keeps the place, the size and the hash.

What a client checks

  • Every entry’s signature, by a device that the client knows as the user’s.
  • The chain: each previous is the hash of the entry before it. A gap or a fork means the server withheld or changed entries: the client stops writing and tells the person.
  • The counter of each device: a gap or a repeat is a warning.
  • The newest head it has seen is kept in the keyring, so the next device can check that the server did not roll back.

Revoking

  • Revoking a device or removing a passkey and the keyring update with a new period are one server transaction. The request carries the new keyring. Without it, the revocation is refused.
  • The identity secret does not change on a revocation. A device that kept a copy can still open later keyrings that it obtains. A person who fears that replaces the identity key (12), which seals everything again.

The local copy

  • The local copy holds plaintext. A client SHOULD encrypt it at rest with a key that the page cannot export, and lock it when idle.
  • A browser cannot protect it from a script on the same origin (THREATS.md).

What the server sees

Per entry: user, seq, device, counter, period, size and time. Per snapshot: size and time. The keyring’s version and period. Activity times. Not the content, and not the shape of the data inside the ciphertext.

Quotas

Each user has a limit for log bytes, snapshot bytes and entries per minute†. A write over the limit is refused with 413 or 429.

Open questions

  1. Is the signed chain worth its cost for every application, or an option?
  2. Should the library also hold the blobs of large files (images), each with its own key, or leave them to an object store that the application signs URLs for?
  3. Should the hook for a moving head be a server-sent event stream in the library, or only a callback?
  4. Is 30 days of keyring versions right, and who may read old versions: every device, or only after a fresh login?

Threat model

Assets

Accounts, sessions, credentials, the link between a person and an account, tenant boundaries, and (with the e2ee part) the users’ identity keys.

Attackers

AttackerCan doMust not be able toDefence
Phisher with a look-alike pageShow any page, relay messages liveLog in as the userPasskeys are bound to the RP ID and origin
Thief of a database copyRead every rowLog in, or call an APIPublic keys and hashes only; no reusable secret at rest
Thief of a logRead metadataLog inThe library writes no logs; tokens are never in URLs, except single-use links
Thief of a first-party tokenReplay itUse itDPoP with server nonces
Thief of a session cookieUse it until it endsChange credentials, stay foreverShort life, hashed, fresh proof for sensitive actions
Thief of a connected-app tokenUse its scopes at one audience until it endsChange the account, use another API, renew after reuseAudience, scope, one-use refresh tokens
Thief of an API keyUse its scopes until it ends or the owner ends itChange the account, reach a first-party routeOff by default, own level, hashed, at most 90 days, last use and address shown
Malicious connected appAsk for consentGet more than the consent, pose as another appVerified client identity, exact redirect URIs, consent page
Owner of a mailboxReceive linksLog in silently, remove the owner’s passkeysDelay, notices, cancel, frozen credential removal
Malicious identity providerClaim any identityLog in without the passkeyRule 3
Tenant administratorSet rules, remove membersLog in as a member, weaken a rule, see another tenantPolicies tighten only; tenant in every key
Network attackerRead and change trafficAnythingTLS; iss checks (RFC 9207); exact origins
Cross-site pageSend requests with cookiesChange stateOrigin and Sec-Fetch-Site checks, SameSite
BotSend many requestsLock out users, enumerate accounts at scaleRate limits; discoverable login needs no identifier

What the design does not protect against

  • Code on the application’s own origin. A script there can act as the user, and can read keys that the page can read. The defence is a strict CSP and no third-party code.
  • A compromised user device, while it is unlocked.
  • A malicious server operator. The operator can log in anyone, except that the e2ee part keeps content keys from the operator. A malicious page can still steal those keys when the user unlocks them.
  • A compromised passkey provider. A synced passkey is as strong as the account that syncs it. A policy can require passkeys that do not sync.
  • A user who approves a device that is not theirs. RFC 8628 can be phished. The approval page shows the device key’s fingerprint and where the request came from, and the user must compare it.
  • Denial of service beyond rate limits.
  1. Recovery by email, where an application enables it.
  2. Device approval by a careless user.
  3. API keys, where an application turns them on.
  4. Session cookies.
  5. The passkey provider’s account recovery.

A change that adds a weaker link than these needs a change to the thesis first.

Decisions

Summary: what we decided, and why, one short page each. The wiki explains how things work; these pages keep the reasons.
Key terms: decision, reason, refused, not now.
Related: wiki · spec

Each page has: the date, what was decided, why, and what it rules out. A new decision gets the next number. A decision that changes gets a new page that names the old one.

No.DecisionDate
001Authentication only, keys only, one strict profile2026-11-24
002One program and a scaling path of three steps2026-11-25
003Tenants as session boundaries; places by tenant or by user2026-11-25
004Tenants and places are optional table features2026-11-25
005End-to-end encryption and app hooks in the HTTP routes2026-11-26

001 Authentication only, keys only, one strict profile

Summary: why auth-chad logs people in with keys only, leaves authorization to the application, and has no weaker settings.
Key terms: passkey, device key, profile, policy, refused, not now.
Related: Concepts · Threats

Date: 2026-11-24. State: in force.

Decided

  • Login is proof of a key. Anything that can be copied must be short-lived, single-use or limited. A stolen database, log line or token must not let a thief log in.
  • Authentication only. The library answers who, how, how recently, with which key, in which tenant. The application answers what they may do. Roles, permissions and sharing are out of scope.
  • One profile. A release has one set of algorithms, checks and upper limits. Policies only tighten.
  • The application owns its data. Auth tables live in its database, next to its own.
  • Nothing hidden. Clock, randomness, storage, network and mail are inputs. No logs; events are writes.
  • The spec is the product. Each language implements it. Rust is the first.

Refused

RefusedReason
Passwords, SMS codes, TOTP as loginThey can be phished or copied
Sign-in by email link aloneThe mailbox becomes the credential
Sign-in at another provider aloneThat provider, or its account recovery, becomes the credential
OAuth implicit and password grants, PKCE plainReplaced by RFC 9700
SAMLXML signatures are a large attack surface
Algorithm negotiation, alg: noneDowngrade attacks
API keys without an end, or that act as the userA device key does the same without a copyable secret
A compatibility modeEvery mode is a weaker way in

Not now

Not nowWhat can change it
Email links as loginAn application that needs them. Then only as an opt-in, with short sessions, no fresh login, never with e2ee
PasswordsOnly to move old accounts: check an old password once, and use the result as permission to create a passkey

What we write and what we use

We write protocol logic and small, strict parsers, because they must match in every language. We use well-reviewed libraries for curves, hashes, ciphers, TLS and database drivers. Fewer dependencies is a goal; own cryptography is not.

Before 1.0

A short working example, a doctor command, ready screens that an application can replace, runbooks (key rotation, stolen database, lost passkeys), and an external security review.

002 One program and a scaling path of three steps

Summary: why the same binary runs in every process, every request is checked in the users’ database, and growth happens in three steps.
Key terms: step, users’ database, shared state, worker, with_proxies.
Related: Scaling · spec 10

Date: 2026-11-25. State: in force. It replaced an earlier list of four separate architectures.

Decided

SubjectDecision
FrameA scaling path with three independent decisions: where the data is, how many processes, how a request names its tenant
ProgramOne binary everywhere. Configuration chooses web, worker or both
The checkEvery request, in the users’ database. No cache of answers, so a logout works from the next request
Shared stateRate limits, single-use marks and leases live in the database, pruned by the worker
Proxies and signed passesNone. Any load balancer in front of identical processes
SQLiteRecommended for step 1. Never on several machines
Step 3PostgreSQL only. Any number of data servers, each with one database or one for each customer
Database credentialsIn the process’s configuration, never in the places table
WebSocket and event streamA new check after 5 minutes† at the latest

Why

A process that trusts another process’s word about a session, or a cache of the answer, lets access outlive a logout. Putting shared state in the database that every process already reads makes one process and many behave the same, with nothing to configure.

Not now

Regions and processes that cannot reach the users’ database. Signed passes are one possible answer, with a delay before a logout works.

003 Tenants as session boundaries; places by tenant or by user

Summary: why a tenant is a boundary for sessions and not a role system, and why the data’s place is chosen by tenant or by user, never both.
Key terms: tenant, membership, place, directory, PlaceBy.
Related: Scaling · spec 14 · spec 15

Date: 2026-11-25. State: in force, built.

Decided

  • A tenant is a boundary for sessions. A session belongs to one tenant. Entering another tenant makes another session, and may need a new passkey use if its rules are stricter. An unknown tenant and a forbidden one give the same refusal.
  • Memberships without roles. The library keeps tenant, user and state. The application adds its own columns, such as a role, and decides what they mean. Ending a membership ends that user’s sessions, tokens, devices, grants and API keys in that tenant, in the same commit.
  • Memberships live with the users, in every step, so a removal ends access in one commit.
  • A place is chosen by tenant or by user. An application chooses one when it is set up. “Both” would give three answers to one question.
  • Tenant address: a path or a host; both supported, with recipes.
  • No gateway. Every process reaches the users’ database and checks the request itself.

Why

Roles differ in every application, and a library that stores them must also judge them. A session boundary is generic, and it is needed for security: a token of one tenant must open nothing in another.

004 Tenants and places are optional table features

Summary: why the tenants, memberships and places tables exist only in databases that ask for them.
Key terms: feature, migration, check_tables, schema version.
Related: Data · spec 10

Date: 2026-11-25. State: in force, built.

Decided

  • The core tables exist in every database. tenants (tenants and memberships) and places are features.
  • migrate, create and upgrade take the list of features. auth-chad schema --with and auth-chad feature print the SQL.
  • A server that is configured to use a feature refuses to start if the database lacks its tables (check_tables).
  • The features table records which features a database has.

Why

An application without tenants should not carry empty tables that look important. Failing at start is better than failing on the first request that needs a missing table.

005 End-to-end encryption and app hooks in the HTTP routes

Summary: why the HTTP routes carry encryption envelopes, recovery by key only, and hooks where an application adds its rules and rows.
Key terms: e2ee mode, envelope, recovery verifier, decoy, hook, Refusal, By, mount path.
Related: Interfaces · spec 12 · e2ee recipe

Date: 2026-11-26. State: in force, built. The first application with end-to-end encryption moved onto these routes.

Decided

  • E2EE mode (Auth::with_e2ee): signup, passkey add, recovery-key set and recovery finish carry envelopes; login returns the passkey’s envelope; passkey removal deletes it.
  • Recovery with a key only. In e2ee mode, email, link and owner recovery are refused, because they cannot open the encryption key. Recovery start returns the envelope, or a decoy for an unknown user, after the same work, so an answer does not show which accounts exist.
  • Undo of a recovery deletes the envelopes made since the recovery; the commit_undo hook lets the application treat the removed devices as revoked.
  • Hooks for the application’s rules and rows: names, invite data, device requests, who may approve, the device kind, and commit hooks for signup, approve, revoke and undo.
  • Refusals from hooks keep the application’s own codes (Refusal::App), and commit hooks get the request’s address (By { who, ip }) for the application’s audit.
  • One error format ({"error": code}) and base64url IDs. No compatibility mode for older client formats.
  • A configurable mount path (mounted_at), with /auth as the default.
  • One client crate for CLIs and wasm, with a browser feature, instead of a client in each application.

Why

An application with end-to-end encryption needs the encryption secret to travel with every credential change, in the same commit. Doing it in the library once is safer than doing it in every application.

auth-chad wiki index

For coding agents and search. One line for each page: what it answers, and its key terms. Read the page you need, not all of them. Exact rules are in spec/; task code is in docs/recipes/.

  • index.md: what auth-chad is, what it is for and not for, where to start. Terms: passkey, device key, authentication, authorization, status.
  • concepts.md: the mental model in seven ideas, and the glossary. Terms: flow, decision, write, commit, Authenticated, tenant, realm, policy, DPoP, ceremony, envelope, hold.
  • map.md: repository and crate layout, dependency rules, where to change things, code rules, tests. Terms: formats, flows, adapters, crate, feature, no_std.
  • data.md: every table, the request types, rows and versions, writes and their conditions. Terms: row, version, Stored, Write, Decision, Ctx, hash at rest, prefix.
  • flows.md: the request check, decide-then-commit, signup, login, device login, recovery, connected apps, outbox and worker. Terms: ceremony, fresh login, device code, grant, lease.
  • interfaces.md: traits and extractors: Hooks, Refusal, By, Store, Reader, Clock, Draws, Placement, Mailer, Columns, Http, Passkeys, Service, Row, Field, Worker; FirstParty, InPerson, FreshLogin, ConnectedApp, ApiKey, Member, Here, At, Caller.
  • scaling.md: from one process to many, and from one database to many; network assumptions; the worker; unsupported patterns. Terms: step, users’ database, directory, place, with_proxies.
  • recipes.md: the task index, with the feature each task needs.
  • ../decisions/README.md: decisions and their reasons.
  • ../../spec/README.md: the normative spec, by topic.
  • ../../THREATS.md: what the design protects against, and what it does not.

Build the site: scripts/wiki.py build (output in rust/target/wiki). Check it: scripts/wiki.py check. From the CLI: auth-chad docs, auth-chad docs <page>, auth-chad docs --open.