// WebAuthn ceremonies. Two of them: // // - register (attestation): creates a user + credential. Adding a credential // to an EXISTING user (a second passkey = recovery redundancy) requires a // FRESH ceremony proof — never a link token; otherwise a brand-new // anonymous user is minted. // - login (discoverable assertion): proves possession of an enrolled // passkey; success mints a device link token + a short-lived ceremony proof. // // The PRF extension is requested and evaluated entirely CLIENT-side (its // output derives the KEK — see web/static/crypto.js). The server never asks // for it and never receives its output; it merely tolerates whatever // clientExtensionResults arrive (the library parses them as an opaque map). package main import ( "encoding/base64" "encoding/json" "errors" "net/http" "time" "github.com/go-webauthn/webauthn/protocol" "github.com/go-webauthn/webauthn/webauthn" ) // waRelyingParty wraps the library handle so main.go stays import-clean. type waRelyingParty struct{ *webauthn.WebAuthn } func newRelyingParty(rpID, origin string) (*waRelyingParty, error) { wa, err := webauthn.New(&webauthn.Config{ // The display name is deliberately constant and generic: passkey managers // show it, and it must not carry anything user-identifying. There is no // account name here by design, so the slot names the SERVICE the passkey // belongs to — the system sheet reads «… with your passkey for "Sign in // with Eleven"». (The label is baked into a credential at enrolment, so // existing passkeys keep their old name unless renamed in the user's // passkey manager.) RPDisplayName: "Sign in with Eleven", RPID: rpID, RPOrigins: []string{origin}, }) if err != nil { return nil, err } return &waRelyingParty{wa}, nil } // homeUser adapts our anonymous user row to the library's User interface. The // name/display-name are the same fixed string for everyone — an account here // has no name, and the passkey entry in the user's manager shouldn't invent one. type homeUser struct { id string creds []webauthn.Credential } func (u *homeUser) WebAuthnID() []byte { return []byte(u.id) } func (u *homeUser) WebAuthnName() string { return "Sign in with Eleven" } func (u *homeUser) WebAuthnDisplayName() string { return "Sign in with Eleven" } func (u *homeUser) WebAuthnCredentials() []webauthn.Credential { return u.creds } // ---- in-flight ceremony sessions ------------------------------------------- // // Between begin and finish the only state a ceremony needs is the library's // SessionData plus a couple of our own fields — and the client already // round-trips an opaque handle through the ?session= query param. So instead // of an in-memory map (which pinned a ceremony to one process), the whole // entry is AES-GCM sealed into that param (stateless.go) and the server keeps // nothing. Same param, same endpoints — the wire flow is unchanged. // // One deliberate trade against the old map: sessions are no longer single-use // (there is nothing to delete on take). Within sessionTTL a captured finish // request could be replayed — but its bearer already holds everything that // finish returned, and the authenticator's signed response is still bound to // this one challenge, so replay buys nothing a first read didn't. const sessionTTL = 5 * time.Minute type sessionEntry struct { Data *webauthn.SessionData `json:"d"` Kind string `json:"k"` // "register" | "login" // UserID + Existing carry the register flow's decision from begin to // finish: which user the new credential attaches to, and whether that user // already exists (vs. is created on finish). UserID string `json:"u,omitempty"` Existing bool `json:"e,omitempty"` Expires int64 `json:"x"` // unix seconds; enforced server-side on open } // sealSession stamps the expiry and seals the entry into the opaque string the // client will echo back on finish. func (s *Server) sealSession(e sessionEntry) (string, error) { e.Expires = time.Now().Add(sessionTTL).Unix() b, err := json.Marshal(e) if err != nil { return "", err } return s.keys.seal(b) } // openSession unseals a presented session param and checks it's the right // kind of ceremony and still fresh. Tampering, a wrong key, garbage — all // fail the GCM open and land here as !ok. func (s *Server) openSession(token, kind string) (sessionEntry, bool) { raw, ok := s.keys.open(token) if !ok { return sessionEntry{}, false } var e sessionEntry if json.Unmarshal(raw, &e) != nil || e.Kind != kind || e.Data == nil || time.Now().Unix() > e.Expires { return sessionEntry{}, false } return e, true } // ---- register --------------------------------------------------------------- func (s *Server) registerBegin(w http.ResponseWriter, r *http.Request) { // A fresh ceremony proof means "add a passkey to MY account"; with none, // this is a brand-new enrolment. A link token is deliberately NOT accepted // here: an enrolled credential can log in and mint fresh ceremony proofs, // so accepting one would escalate a stolen read/write token into permanent // account takeover (enrol attacker passkey -> ceremony -> destroy blob, // revoke devices). Link tokens authorise exactly blob read/write and the // devices listing — nothing else. A presented token is refused outright // rather than ignored, so a client that meant "add to my account" can't // silently enrol a second, empty account instead. userID, existing := s.ceremonyUser(r) if !existing { if bearerToken(r) != "" { http.Error(w, "fresh passkey ceremony required to add a passkey", http.StatusForbidden) return } id, err := randToken() if err != nil { http.Error(w, "server error", http.StatusInternalServerError) return } // The new user id is minted now but only written to the DB when the // ceremony verifies, so abandoned ceremonies leave no rows behind. userID = id } u := &homeUser{id: userID} // Discoverable (resident) credentials are required: login is by credential, // not by naming an account — there is nothing to name an account by. User // verification is required too — a ceremony proof means "the user just did // Face ID / PIN", not merely "the authenticator was present". opts := []webauthn.RegistrationOption{ webauthn.WithAuthenticatorSelection(protocol.AuthenticatorSelection{ ResidentKey: protocol.ResidentKeyRequirementRequired, UserVerification: protocol.VerificationRequired, }), // Applied after WithAuthenticatorSelection: also sets the legacy // requireResidentKey bool for older clients. webauthn.WithResidentKeyRequirement(protocol.ResidentKeyRequirementRequired), } if existing { creds, err := s.store.credentialsFor(userID) if err != nil { http.Error(w, "db error", http.StatusInternalServerError) return } u.creds = creds var excl []protocol.CredentialDescriptor for _, c := range creds { excl = append(excl, c.Descriptor()) } opts = append(opts, webauthn.WithExclusions(excl)) } creation, session, err := s.wa.BeginRegistration(u, opts...) if err != nil { http.Error(w, "begin registration failed", http.StatusInternalServerError) return } sid, err := s.sealSession(sessionEntry{Data: session, Kind: "register", UserID: userID, Existing: existing}) if err != nil { http.Error(w, "server error", http.StatusInternalServerError) return } writeJSON(w, http.StatusOK, map[string]any{"session": sid, "options": creation}) } func (s *Server) registerFinish(w http.ResponseWriter, r *http.Request) { ent, ok := s.openSession(r.URL.Query().Get("session"), "register") if !ok { http.Error(w, "unknown or expired session", http.StatusBadRequest) return } u := &homeUser{id: ent.UserID} if ent.Existing { creds, err := s.store.credentialsFor(ent.UserID) if err != nil { http.Error(w, "db error", http.StatusInternalServerError) return } u.creds = creds } cred, err := s.wa.FinishRegistration(u, *ent.Data, r) if err != nil { http.Error(w, "registration failed", http.StatusBadRequest) return } if !ent.Existing { if err := s.store.createUser(ent.UserID); err != nil { http.Error(w, "db error", http.StatusInternalServerError) return } } if err := s.store.insertCredential(ent.UserID, cred); err != nil { http.Error(w, "db error", http.StatusInternalServerError) return } s.finishCeremony(w, ent.UserID, cred) } // ---- login -------------------------------------------------------------------- func (s *Server) loginBegin(w http.ResponseWriter, r *http.Request) { // Discoverable login: no allowCredentials, the authenticator offers whatever // passkeys it holds for this RP. The client adds the PRF eval extension to // these options itself — the server has no business in that exchange. assertion, session, err := s.wa.BeginDiscoverableLogin( webauthn.WithUserVerification(protocol.VerificationRequired)) if err != nil { http.Error(w, "begin login failed", http.StatusInternalServerError) return } sid, err := s.sealSession(sessionEntry{Data: session, Kind: "login"}) if err != nil { http.Error(w, "server error", http.StatusInternalServerError) return } writeJSON(w, http.StatusOK, map[string]any{"session": sid, "options": assertion}) } func (s *Server) loginFinish(w http.ResponseWriter, r *http.Request) { ent, ok := s.openSession(r.URL.Query().Get("session"), "login") if !ok { http.Error(w, "unknown or expired session", http.StatusBadRequest) return } var userID string cred, err := s.wa.FinishDiscoverableLogin(func(rawID, userHandle []byte) (webauthn.User, error) { uid := string(userHandle) creds, err := s.store.credentialsFor(uid) if err != nil || len(creds) == 0 { return nil, errors.New("unknown user") } userID = uid return &homeUser{id: uid, creds: creds}, nil }, *ent.Data, r) if err != nil { http.Error(w, "login failed", http.StatusUnauthorized) return } // Persist the updated sign count / backup flags for clone detection. if err := s.store.updateCredential(cred); err != nil { http.Error(w, "db error", http.StatusInternalServerError) return } s.finishCeremony(w, userID, cred) } // finishCeremony is the shared tail of both verified ceremonies: mint a device // link token (ongoing bearer auth) and a ceremony proof (the short-lived // "I just did Face ID" credential destructive ops demand), and tell the client // which credential id it used, so it can pick its wrapped DEK out of the blob. func (s *Server) finishCeremony(w http.ResponseWriter, userID string, cred *webauthn.Credential) { tok, err := s.store.createLinkToken(userID) if err != nil { http.Error(w, "db error", http.StatusInternalServerError) return } writeJSON(w, http.StatusOK, map[string]any{ "token": tok, "proof": s.keys.mintCeremonyProof(userID), "credential_id": base64.RawURLEncoding.EncodeToString(cred.ID), }) }