passkey

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

README

github.com/ubgo/auth/plugin/passkey

Lets users sign in with a passkey (Face ID, Touch ID, Windows Hello, a security key) without typing an identifier, and add and remove passkeys from their account.

Install

go get github.com/ubgo/auth/plugin/passkey

This is its own module (Go 1.25) because it wraps github.com/go-webauthn/webauthn, whose CBOR, JWT and TPM dependencies no app without passkeys should inherit.

Wire it

From examples/passkeys:

auth.New(
	auth.WithDB(db, sqlb.SQLiteDialect{}),
	auth.WithBaseURL(baseURL),
	auth.WithPlugins(
		email.New(email.Login(), email.Recover(), email.WithMailer(m)),
		password.New(),
		passkey.New(passkey.DisplayName(appName)),
	),
)

A user adds a passkey while signed in, so the app needs another way to create accounts and sign in first (password, magic link, OAuth…). auth.New fails with ErrNoRelyingParty (passkey: needs auth.WithBaseURL or passkey.RelyingParty) when there is neither a base URL nor RelyingParty, when the base URL has no host, or when no allowed origin can be worked out. A relying party id the WebAuthn library refuses fails auth.New with an error starting passkey: .

Options

Option What it does Default
DisplayName(name) App name the browser shows in the passkey prompt. Not stored with the passkey. "App" (DefaultDisplayName)
AccountName(fn) Names the account in a new passkey, such as the user's email address, which the device shows when it offers the passkey. fn is an AccountNameFunc, func(ctx, a *auth.Auth, u auth.User) string: it receives the core, so it can look the address up with a.Identities. It runs at registration only; an empty result falls back to the user id. For a user without a name it is also the prompt's display name. the user id
RelyingParty(id, origins...) Relying party id and allowed origins. A passkey is bound to its relying party id for good: changing it later strands every registered passkey. id: host of auth.WithBaseURL; origins: the base URL's origin plus auth.WithTrustedOrigins
WithCeremonyTTL(d) How long a begun ceremony can be finished. 5 minutes (DefaultCeremonyTTL)
RegistrationExtensions(ext) WebAuthn extensions sent with every registration's options (Extensions, keyed by extension id: credProps, prf, largeBlob…). The browser's results come back as JSON in Passkey.Extensions from register-finish and sign-up-finish, unread by the plugin. none
AuthenticationExtensions(ext) WebAuthn extensions sent with every sign-in's assertion options; results in SignInResult.Extensions from login-finish. Either option holding a value JSON cannot encode (a NaN, a channel) fails auth.New with ErrExtensionsInvalid, since every ceremony would fail on it. none
AuthenticatorSelection(Selection{ResidentKey, UserVerification, Attachment}) better-auth's authenticatorSelection: each level RequirementRequired, RequirementPreferred or RequirementDiscouraged, the attachment AttachmentPlatform or AttachmentCrossPlatform; an empty field keeps the default and any other value fails auth.New (ErrSelectionInvalid). Lowering a level stays safe: a sign-in whose authenticator did not verify the user is one factor, so a user with a second factor gets a pending session (secondFactorRequired), and a non-discoverable passkey signs in only under AllowCredentialsForSession. better-auth's default is preferred for both and counts every passkey sign-in as complete. required, required, any attachment
AllowCredentialsForSession() Login-begin with a session names that user's passkeys and their transports in allowCredentials, as better-auth does: a re-authentication offers only the user's own passkeys, the browser knows how to reach each, and a non-discoverable one can be used. Login-finish then accepts only that user's passkey. Signed out, or with no passkey, the sign-in stays discoverable. off: always discoverable, so a signed-in browser can still sign in to another account
Attestation(c) The attestation conveyance asked at registration: ConveyanceNone, ConveyanceIndirect, ConveyanceDirect or ConveyanceEnterprise; anything else fails auth.New (ErrAuthenticatorPolicy). none, or direct under WithMetadata
WithMetadata(m) Checks every registration's attestation against a FIDO Metadata Service provider (MetadataProvider, the WebAuthn library's metadata.Provider; its metadata/providers/memory and cached packages build one): trust anchor, attestation types and status reports, as the provider configures. A failure is passkey.invalid, with the reason in the log. none
AllowAuthenticators(aaguids...) New passkeys only from these models, by AAGUID (any case, dashes optional), such as the company's issued security keys. A model kept private (zero AAGUID) is refused, and so is any registration whose attestation does not prove the model: the type must be basic, AttCA or AnonCA, and the plugin itself checks that the attestation certificate chains to the metadata entry's root for that AAGUID, because the WebAuthn library accepts none and self attestation whatever the metadata says and skips the chain check for a certificate whose subject and issuer names match. Needs WithMetadata, and excludes DenyAuthenticators (ErrAuthenticatorPolicy). Passkeys registered before the list keep signing in. none
DenyAuthenticators(aaguids...) Refuses new passkeys from these models, by AAGUID. Without WithMetadata the AAGUID is what the client claims, so this steers honest clients rather than stopping a crafted one; a model kept private is not refused. none
WithSignUp() Passkey-first registration: public sign-up-begin and sign-up-finish create the account with a passkey as its first credential, no session and no password. Needs an identifier plugin (ErrSignUpNeedsKind); rate limited per IP like password sign-up. off

Per request, RegisterBeginRequest.AuthenticatorAttachment ("platform" or "cross-platform", constants AttachmentPlatform and AttachmentCrossPlatform) restricts the kind of authenticator the browser offers for that registration; anything else is ErrAttachmentInvalid.

By default user verification (PIN or biometric) and discoverable (resident) credentials are required on every ceremony, which is what lets a passkey sign-in count as two factors.

Routes and Go API

Routes are mounted under the authhttp prefix (/auth in the examples).

Route Go method Requirement Rate limit
POST /auth/passkey/register-begin RegisterBegin(ctx) or RegisterBeginWith(ctx, RegisterBeginRequest{AuthenticatorAttachment}) returns BeginResult FreshSignIn none
POST /auth/passkey/register-finish RegisterFinish(ctx, FinishRequest{Ceremony, Credential, Name}) returns Passkey FreshSignIn none
POST /auth/passkey/login-begin LoginBegin(ctx) returns BeginResult Public 30/minute per IP (loginBeginIPLimit)
POST /auth/passkey/login-finish LoginFinish(ctx, FinishRequest{Ceremony, Credential}) returns SignInResult Public none
POST /auth/passkey/reauthenticate-begin ReauthenticateBegin(ctx) returns BeginResult for the user's own passkeys, bound to the current session (ErrNoPasskeys without one) SignedIn 30/minute per IP
POST /auth/passkey/reauthenticate-finish ReauthenticateFinish(ctx, ReauthFinishRequest{Ceremony, Credential}) returns auth.Reauthentication: the session is fresh again (re-authentication) SignedIn 30/minute per IP, 10 per 15 minutes per signed-in user
GET /auth/passkey/list List(ctx) returns []Passkey SignedIn none
POST /auth/passkey/remove Remove(ctx, id) FreshSignIn none
POST /auth/passkey/rename Rename(ctx, id, name) SignedIn none
POST /auth/passkey/sign-up-begin SignUpBegin(ctx, SignUpBeginRequest{Identifier, Name, AuthenticatorAttachment}) returns BeginResult Public 10/hour per IP (signUpIPLimit); exists only with WithSignUp
POST /auth/passkey/sign-up-finish SignUpFinish(ctx, FinishRequest{Ceremony, Credential, Name}) returns SignUpResult{User, Passkey, VerificationRequired} Public none; exists only with WithSignUp
(Go only) SignInCredentials(ctx, userID, exceptID) none none

Each ceremony is two calls:

  1. Begin returns {"ceremony": "…", "options": {…}}. The browser passes options to navigator.credentials.create (register) or navigator.credentials.get (login).
  2. Finish takes {"ceremony": "…", "credential": <the PublicKeyCredential as JSON>, "name": "MacBook"}; name is for register only and is cut to 64 characters.

Login-finish sets a full session (cookie or bearer token) and returns the user (a pending one with secondFactorRequired: true when a lowered UserVerification let the device skip verifying the user and the user has a second factor: that sign-in reaches second-factor policies as SignInAttempt.SingleFactor, and the two-factor plugin's default asks after it, where better-auth counts every passkey sign-in as complete); the token is never in the JSON body. List returns {"passkeys": [{"id", "name", "createdAt", "lastUsedAt", "aaguid", "backedUp", "transports"}]}, oldest first: aaguid is the authenticator model as a UUID (empty when the device declined to say, as Apple devices do), backedUp whether the platform syncs it, transports how it is reached (internal, usb, hybrid…). AuthenticatorName(aaguid) turns a known AAGUID into "1Password", "Windows Hello" and the like, for a list entry the user did not name. Remove takes {"id": "…"}; rename takes {"id": "…", "name": "…"} and cuts the name to 64 characters like registration.

  • Sign-up (with WithSignUp) creates an account from a passkey: begin takes the identifier the account will hold (checked against the identifier plugins first) and the display name, mints the user id so the authenticator's user handle is the account id, and returns the creation options; finish verifies the attestation, creates the user and the unverified identity, stores the passkey, and signs the user in with a full session, or answers verificationRequired: true and no session when the identifier's kind has RequireVerified(). A value someone already verified is handled as password sign-up handles it: the owner is told, this sign-up still succeeds as a separate account, and the answer reveals nothing.

  • Moving to a new domain. A passkey is bound to its relying party id for good. Keep the old id with RelyingParty("old.example", "https://new.example", …) and serve pk.WellKnown() at https://old.example/.well-known/webauthn (WellKnownPath): it answers {"origins": [...]} with the plugin's origins, the Related Origin Requests document that lets a browser use the old id from the new origin (Chrome 128 and Safari 18 do; elsewhere the page must still be served from the old domain). GET and HEAD only.

SecurityKeys() returns the twofactor.SecurityKeyStore that makes security keys a second factor (twofactor.WithSecurityKeys(pk.SecurityKeys())); the routes for it are two-factor's, under /auth/twofactor/security-key/. See two-factor › Several factors, and security keys.

Tables and columns

Table Columns Notes
auth_passkey (TableNamePasskey, alias pk) id (primary key), user_id (deleted with the user by a.DeleteUser; no foreign key), credential_id (unique), credential_json (the whole webauthn.Credential: public key, sign count, flags), name, created_at, last_used_at Index auth_passkey_user_idx on user_id.
auth_passkey_security_key (TableNameSecurityKey, alias pksk) the same columns as auth_passkey Security keys registered as a second factor through twofactor.WithSecurityKeys(pk.SecurityKeys()). No sign-in, re-authentication, list or remove operation of this plugin reads it, so a key here never signs anyone in.

Migrations 0001_passkey and 0002_passkey_security_key, owner passkey. Typed columns for reads: TablePasskey, PasskeyID, UserID, CredentialID, Credential, Name, CreatedAt, LastUsedAt. This table is not part of the core's stable-column contract (stability_test.go covers auth_user, auth_identity and auth_session only), so treat its columns as internal.

Errors

Variable Code HTTP When
ErrCeremonyInvalid passkey.ceremony_invalid 400 Ceremony unknown, expired, already used, or begun by another user.
ErrPasskeyInvalid passkey.invalid 401 The authenticator's answer does not parse or verify, the user handle names nobody, the sign count went backwards (cloned credential), or the credential is already registered to an account.
ErrNotFound passkey.not_found 404 Remove or rename with an id that is not one of the user's passkeys.
ErrAttachmentInvalid passkey.attachment_invalid 400 authenticatorAttachment other than platform or cross-platform.
ErrAuthenticatorNotAllowed passkey.authenticator_not_allowed 403 Register-finish or sign-up-finish from a model AllowAuthenticators does not take (or cannot prove), or one DenyAuthenticators names. Nothing is stored.
ErrSignUpNeedsKind (start-up) — WithSignUp with no identifier plugin registered.
ErrAuthenticatorPolicy (start-up) — An AAGUID that is not a UUID, both lists, an allow-list without WithMetadata, or an unknown conveyance.

Core errors you will also see: auth.ErrLastSignInMethod (remove would leave the user no way in), auth.ErrFreshSessionRequired, auth.ErrRateLimited (login-begin over its limit). A database failure during sign-in surfaces as itself, not as ErrPasskeyInvalid.

Security notes

Property Pinned by
A ceremony works once, only before its TTL, and only for the user who began it. TestPasskey_RegisterSignInRemove, TestFactors_PasskeyCeremonyRefusals
An answer made for another origin, a forged signature, or a sign count that went backwards is refused. TestFactors_PasskeyCeremonyRefusals, TestPasskey_RegisterSignInRemove
A passkey sign-in is a full session even with TOTP on: user verification makes it multi-factor by itself. One whose device skipped user verification is single-factor, and the two-factor default policy makes it pending. TestPasskey_RegisterSignInRemove, TestPasskey_UnverifiedSignInIsOneFactorForTwoFactor
One authenticator credential cannot be registered to a second account. TestFactors_PasskeyCredentialOfAnotherUser
A user whose only way in is a passkey cannot remove it; one user cannot remove another's. TestPasskey_OnlyWayInCannotBeRemoved, TestFactors_PasskeyTwoDevices
A stored credential that does not decode fails the ceremony instead of being skipped. TestFactors_PasskeyCorruptStoredCredential
Every database failure surfaces as an error, never as a refused passkey. TestFactors_PasskeyFaults
Login-begin, the one anonymous operation that writes (a ceremony row per call), is limited per IP. TestFactors_PasskeyLoginBeginRateLimited
AccountName names the account the device stores; without it the name is the user id, never an address. TestFactors_PasskeyAccountName
Passkey-first sign-up mints the user id before the ceremony so the authenticator's handle equals the account id; the ceremony is single use; the identifier follows password sign-up's rules (unverified row, owner of a taken verified value told, RequireVerified kinds issue no session); the operations exist only with WithSignUp. TestFactors_PasskeySignUp, TestFactors_PasskeySignUpRequireVerified, TestFactors_PasskeySignUpFaults
Configured extensions reach the options and the browser's results come back in the finish results, absent when there are none; the list never carries them. TestFactors_PasskeyExtensions
Extensions JSON cannot encode fail auth.New. TestValidate_RefusesExtensionsJSONCannotHold

Limits: login-begin and the re-authentication routes have rate rules; guessing is not a threat on the other routes (a signature cannot be guessed, and they need a ceremony or a signed-in user). Go API calls carry no IP, so the per-IP rule counts HTTP requests only. The WebAuthn verification itself is the library's; this plugin owns storage, ceremony state and the rules above.

Example

Documentation

Overview

Package passkey signs users in with passkeys (WebAuthn discoverable credentials), and lets a signed-in user add and remove them.

It is a separate module because it wraps github.com/go-webauthn/webauthn, whose CBOR, JWT and TPM dependencies no app without passkeys should inherit. The WebAuthn protocol lives in that library; this plugin owns the storage, the ceremonies' state, and the rules: a ceremony is a single-use core verification token, user verification is required, and a passkey sign-in is multi-factor by itself.

Index

Constants

View Source
const (
	EndpointRegisterBegin  auth.EndpointID = "passkey.register-begin"
	EndpointRegisterFinish auth.EndpointID = "passkey.register-finish"
	EndpointLoginBegin     auth.EndpointID = "passkey.login-begin"
	EndpointLoginFinish    auth.EndpointID = "passkey.login-finish"
	EndpointList           auth.EndpointID = "passkey.list"
	EndpointRemove         auth.EndpointID = "passkey.remove"
	EndpointRename         auth.EndpointID = "passkey.rename"
	// EndpointSignUpBegin and EndpointSignUpFinish create an account with a
	// passkey as its first credential, with no session; they exist only
	// with WithSignUp.
	EndpointSignUpBegin  auth.EndpointID = "passkey.sign-up-begin"
	EndpointSignUpFinish auth.EndpointID = "passkey.sign-up-finish"
)

Operation ids, the permanent names hooks, rate rules and transports address the plugin's operations by.

View Source
const (
	PurposeRegister auth.Purpose = "passkey.register"
	PurposeLogin    auth.Purpose = "passkey.login"
	// PurposeSignUp is a passkey-first sign-up ceremony. Its Identifier is
	// the id the new user will have, minted at begin so the authenticator's
	// user handle equals the user id; Meta is the JSON of signUpMeta.
	PurposeSignUp auth.Purpose = "passkey.sign-up"
)

Ceremony purposes. A register ceremony's Identifier is the user id; a login ceremony's is empty, because a discoverable login does not know the user until the authenticator answers, or the signed-in user's id under AllowCredentialsForSession. Meta is the JSON of webauthn.SessionData.

View Source
const (
	//ds:def id=tablenamepasskey-euzk3h7u owner=@khanakia stability=stable
	TableNamePasskey  = "auth_passkey"
	TableAliasPasskey = "pk"
	ColID             = "id"
	ColUserID         = "user_id"
	ColCredentialID   = "credential_id"
	// ColCredential holds the whole webauthn.Credential as JSON: public key,
	// sign count, flags, attestation. The library owns its shape and can read
	// its older forms, so the plugin does not split it into columns.
	ColCredential = "credential_json"
	ColName       = "name"
	ColCreatedAt  = "created_at"
	ColLastUsedAt = "last_used_at"
)

The plugin's table: one row per registered passkey, looked up by user for the list and by credential id (unique) at sign-in.

View Source
const (
	AttachmentPlatform      = string(protocol.Platform)
	AttachmentCrossPlatform = string(protocol.CrossPlatform)
)

Authenticator attachments, the two values WebAuthn defines.

View Source
const (
	// EndpointReauthBegin starts an assertion ceremony for the signed-in
	// user's own passkeys, bound to their current session.
	EndpointReauthBegin auth.EndpointID = "passkey.reauthenticate-begin"
	// EndpointReauthFinish verifies it and refreshes the session.
	EndpointReauthFinish auth.EndpointID = "passkey.reauthenticate-finish"
)

Operation ids and paths of re-authentication.

View Source
const (
	//ds:def id=tablenamesecuritykey-4kt9wm2q owner=@khanakia stability=stable
	TableNameSecurityKey  = "auth_passkey_security_key"
	TableAliasSecurityKey = "pksk"
)

The security-key table: one row per key, the same shape as auth_passkey.

View Source
const (
	PurposeSecurityKeyRegister auth.Purpose = "passkey.security-key-register"
	PurposeSecurityKeyAssert   auth.Purpose = "passkey.security-key"
)

Ceremony purposes of security keys, distinct from the passkey ones so a passkey ceremony can never finish as a security-key one or the reverse. The Identifier of both is the user id.

View Source
const DefaultCeremonyTTL = 5 * time.Minute

DefaultCeremonyTTL is how long a user has to touch the authenticator.

View Source
const DefaultDisplayName = "App"

DefaultDisplayName is the app name the browser's passkey prompt shows without DisplayName.

View Source
const PluginName = "passkey"

PluginName is the plugin's permanent identity. It owns the plugin's rows in the migration ledger and its tables and columns, so renaming it would make the next migrate see a new plugin; it never changes.

View Source
const PurposePresence auth.Purpose = "passkey.presence"

PurposePresence is a proof-of-presence ceremony: an assertion that a signed-in user is physically at an authenticator, for an approval such as plugin/agentauth's. Its Identifier is the user id and the scope joined by presenceSeparator, so a ceremony begun for one approval never completes another; Meta is the JSON of webauthn.SessionData.

View Source
const PurposeReauth auth.Purpose = "passkey.reauth"

PurposeReauth is a re-authentication ceremony. Its Identifier is the id of the session it was begun on, so a ceremony from another session (a second tab after a sign-out, a captured value) is refused; Meta is the JSON of webauthn.SessionData.

View Source
const WellKnownPath = "/.well-known/webauthn"

WellKnownPath is where a browser fetches the related origins of a relying party: https://<rp id>/.well-known/webauthn (WebAuthn Level 3, Related Origin Requests).

Variables

Typed columns, for an app that reads the table (reads are open; only the plugin writes it).

View Source
var (
	ErrCeremonyInvalid = auth.NewError("passkey.ceremony_invalid", http.StatusBadRequest, "This passkey request has expired. Try again.")
	ErrPasskeyInvalid  = auth.NewError("passkey.invalid", http.StatusUnauthorized, "This passkey could not be verified.")
	ErrNotFound        = auth.NewError("passkey.not_found", http.StatusNotFound, "Not found.")
	// ErrAttachmentInvalid: RegisterBeginRequest.AuthenticatorAttachment is
	// not one of the two WebAuthn values.
	ErrAttachmentInvalid = auth.NewError("passkey.attachment_invalid", http.StatusBadRequest, "Choose platform or cross-platform.")
	ErrNoRelyingParty    = errors.New("passkey: needs auth.WithBaseURL or passkey.RelyingParty")
	// ErrSignUpNeedsKind: WithSignUp needs an identifier plugin, or a
	// sign-up could name no address and no user could ever be contacted.
	ErrSignUpNeedsKind = errors.New("passkey: WithSignUp needs an identifier plugin (email, phone or username)")
	// ErrExtensionsInvalid: RegistrationExtensions or
	// AuthenticationExtensions holds a value JSON cannot encode, which every
	// ceremony would fail on.
	ErrExtensionsInvalid = errors.New("passkey: RegistrationExtensions and AuthenticationExtensions must hold JSON values")
	// ErrSelectionInvalid: AuthenticatorSelection named a level or an
	// attachment WebAuthn does not define, which every browser would reject
	// at the first ceremony.
	ErrSelectionInvalid = errors.New("passkey: AuthenticatorSelection levels are required, preferred or discouraged, the attachment platform or cross-platform")
)

Errors. The *auth.Error values are what a client sees; ErrNoRelyingParty is a configuration mistake auth.New refuses at start-up.

View Source
var (
	// ErrAuthenticatorNotAllowed refuses a registration from an authenticator
	// model the policy does not take: one outside AllowAuthenticators (or one
	// that hides its model), or one in DenyAuthenticators. It is reached only
	// by a signed-in user or a finished sign-up ceremony and names the policy,
	// never the user.
	//
	//ds:def id=errauthenticatornotallowed-r25pk02 owner=@khanakia stability=stable
	ErrAuthenticatorNotAllowed = auth.NewError("passkey.authenticator_not_allowed", http.StatusForbidden, "This kind of passkey is not accepted here. Use another one.")

	// ErrAuthenticatorPolicy is a configuration mistake auth.New refuses:
	// an AAGUID that is not a UUID, both an allow-list and a deny-list, an
	// allow-list without WithMetadata, or a conveyance WebAuthn does not
	// define.
	ErrAuthenticatorPolicy = errors.New("passkey: authenticator policy: AAGUIDs are UUIDs, AllowAuthenticators and DenyAuthenticators exclude each other, AllowAuthenticators needs WithMetadata, and Attestation takes none, indirect, direct or enterprise")
)
View Source
var (
	TableSecurityKey        = sqlb.Table{Name: TableNameSecurityKey, Alias: TableAliasSecurityKey}
	SecurityKeyID           = sqlb.Col[string](TableSecurityKey, ColID)
	SecurityKeyUserID       = sqlb.Col[string](TableSecurityKey, ColUserID)
	SecurityKeyCredentialID = sqlb.Col[[]byte](TableSecurityKey, ColCredentialID)
	SecurityKeyCredential   = sqlb.Col[string](TableSecurityKey, ColCredential)
	SecurityKeyName         = sqlb.Col[string](TableSecurityKey, ColName)
	SecurityKeyCreatedAt    = sqlb.Col[time.Time](TableSecurityKey, ColCreatedAt)
	SecurityKeyLastUsedAt   = sqlb.Col[*time.Time](TableSecurityKey, ColLastUsedAt)
)

Typed columns of auth_passkey_security_key, for an app that reads it.

ConveyanceValues is the canonical iteration order over conveyances.

View Source
var ErrNoPasskeys = auth.NewError("passkey.none", http.StatusBadRequest, "Add a passkey first, or confirm with your password.")

ErrNoPasskeys is returned by reauthenticate-begin for a user with no passkey: there is nothing to assert, and the client offers the password.

RequirementValues is the canonical iteration order over requirement levels.

Functions

func AuthenticatorName

func AuthenticatorName(aaguid string) string

AuthenticatorName returns the provider name for a Passkey.AAGUID, or "" when it is unknown or empty, so a settings page can show `pk.Name`, else `AuthenticatorName(pk.AAGUID)`, else "Passkey". Case and surrounding spaces do not matter.

Types

type AccountNameFunc

type AccountNameFunc func(ctx context.Context, a *auth.Auth, u auth.User) string

AccountNameFunc names a user's account in a new passkey, such as their email address: the name the device shows when it offers the passkey. It receives the core, so it can read what the plugin cannot know (a.Identities) without the app capturing its *auth.Auth before auth.New has returned it. An empty result falls back to the user id. It runs at registration only: the device stores the name with the passkey, so a later change of address does not rename passkeys already made.

type BeginResult

type BeginResult struct {
	Ceremony string          `json:"ceremony"`
	Options  json.RawMessage `json:"options"`
}

BeginResult starts a ceremony. The client passes Options to navigator.credentials.create or .get, and sends Ceremony back with the authenticator's answer. Ceremony is a single-use handle, like an OAuth state, so it is sent in the clear.

type Conveyance

type Conveyance string

Conveyance is the WebAuthn attestation conveyance preference: how much the relying party asks an authenticator to prove about its make and model at registration (WebAuthn §5.4.7).

const (
	// ConveyanceNone asks for no attestation: the browser may strip it and
	// zero the AAGUID. The default, and better-auth's.
	ConveyanceNone Conveyance = "none"
	// ConveyanceIndirect lets the browser anonymize the attestation.
	ConveyanceIndirect Conveyance = "indirect"
	// ConveyanceDirect asks for the authenticator's own attestation
	// statement, which WithMetadata can verify against the FIDO Metadata
	// Service. The browser may ask the user's consent.
	ConveyanceDirect Conveyance = "direct"
	// ConveyanceEnterprise asks for an attestation that can identify the
	// individual device, for managed fleets whose browsers are configured to
	// allow it for this relying party.
	ConveyanceEnterprise Conveyance = "enterprise"
)

The four conveyance preferences.

type Extensions

Extensions are WebAuthn client extension inputs, keyed by extension identifier ("credProps", "prf", "largeBlob", …), as the browser receives them in the options. The value shapes belong to each extension's specification and are JSON, so this is the protocol library's own open type rather than a struct per extension; the plugin passes it through unread.

type FinishRequest

type FinishRequest struct {
	Ceremony   string          `json:"ceremony"`
	Credential json.RawMessage `json:"credential"`
	// Name labels a new passkey in the list, such as "MacBook". Register only.
	Name string `json:"name,omitempty"`
}

FinishRequest completes a ceremony. Credential is the JSON the browser's PublicKeyCredential serializes to.

type ListResult

type ListResult struct {
	Passkeys []Passkey `json:"passkeys"`
}

ListResult is the output of list, oldest passkey first.

type MetadataProvider

type MetadataProvider = metadata.Provider

MetadataProvider is a FIDO Metadata Service source from the WebAuthn library (its metadata/providers/memory or metadata/providers/cached packages build one). The plugin hands it to the library unread, which then checks each registration's attestation against the authenticator's trust anchors, attestation types and status reports, as the provider asks.

type Option

type Option func(*Plugin)

Option configures the plugin; pass options to New.

func AccountName

func AccountName(fn AccountNameFunc) Option

AccountName sets how a new passkey names the account. Without it the name is the user id, which is stable and never an address, but means nothing to a person choosing between passkeys.

func AllowAuthenticators

func AllowAuthenticators(aaguids ...string) Option

AllowAuthenticators accepts new passkeys only from these authenticator models, by AAGUID (the UUID strings of the passkey-authenticator-aaguids list, any case), such as a company's issued security keys. An authenticator that hides its model (a zero AAGUID) is refused. Without an attestation check an AAGUID is whatever the client claims, so a crafted client could pass any allow-list: auth.New refuses AllowAuthenticators without WithMetadata. Passkeys registered before the list existed keep signing in; remove them to enforce the list on them too.

func AllowCredentialsForSession

func AllowCredentialsForSession() Option

AllowCredentialsForSession makes login-begin name the signed-in user's own passkeys, with their transports, in allowCredentials, as better-auth does when a session exists: a re-authentication then offers only that user's passkeys, the browser knows how to reach each (usb, nfc, ble, internal, hybrid), and a non-discoverable passkey can be used at all. The finish is checked against that user. Without a session, or with no passkey, the sign-in stays discoverable. Off by default, so a signed-in browser can still sign in to another account with that account's passkey.

func Attestation

func Attestation(c Conveyance) Option

Attestation sets the attestation conveyance preference sent at every registration. Without it the plugin asks for none, or for direct under WithMetadata, since a metadata check needs the authenticator's statement.

func AuthenticationExtensions

func AuthenticationExtensions(ext Extensions) Option

AuthenticationExtensions adds WebAuthn extensions to every sign-in's assertion options (login-begin). The results come back in SignInResult.Extensions at login-finish.

func AuthenticatorSelection

func AuthenticatorSelection(s Selection) Option

AuthenticatorSelection replaces what the plugin asks of an authenticator, better-auth's authenticatorSelection option. The default asks for a discoverable credential and user verification on every ceremony, which is what lets a passkey sign-in count as two factors and skip the second step.

Lowering either keeps sign-in safe rather than pretending: a sign-in whose assertion does not carry the user-verified flag is one factor, so a user with a second factor gets a pending session and secondFactorRequired; and a non-discoverable passkey cannot be found by the identifier-free sign-in, so it signs in only under AllowCredentialsForSession. better-auth's default is preferred for both; it counts every passkey sign-in as complete.

func DenyAuthenticators

func DenyAuthenticators(aaguids ...string) Option

DenyAuthenticators refuses new passkeys from these authenticator models, by AAGUID: a model with a known flaw, or a provider the product does not support. Without WithMetadata the AAGUID is self-reported, so this steers honest clients rather than stopping a determined one; it needs no metadata for that reason. An authenticator that hides its model is not refused.

func DisplayName

func DisplayName(name string) Option

DisplayName is the app name the browser shows in the passkey prompt. It is not stored with the passkey, so it can change at any time.

func RegistrationExtensions

func RegistrationExtensions(ext Extensions) Option

RegistrationExtensions adds WebAuthn extensions to every registration's options (register-begin and sign-up-begin): {"credProps": true} to learn whether the credential is discoverable, "prf" or "largeBlob" for apps that derive keys or store data on the authenticator. The browser's results come back in Passkey.Extensions at finish, unread by the plugin.

func RelyingParty

func RelyingParty(id string, origins ...string) Option

RelyingParty overrides the relying party id and the allowed origins, which otherwise come from the host of auth.WithBaseURL and the trusted origins. Without origins, the BaseURL's origin and the trusted origins are used. A passkey is bound to its relying party id for good: changing it later strands every registered passkey.

func WithCeremonyTTL

func WithCeremonyTTL(d time.Duration) Option

WithCeremonyTTL overrides DefaultCeremonyTTL, how long a begun ceremony can be finished. After it the ceremony is ErrCeremonyInvalid.

func WithMetadata

func WithMetadata(m MetadataProvider) Option

WithMetadata verifies every registration's attestation against a FIDO Metadata Service provider: the attestation must chain to the model's trust anchor, and a model with a compromised status is refused, as the provider configures. It is what makes an AAGUID evidence rather than a claim, so AllowAuthenticators requires it. A registration that fails the check is passkey.invalid, with the reason in the log.

func WithSignUp

func WithSignUp() Option

WithSignUp adds passkey-first registration: a public ceremony that creates the account with a passkey as its first credential, so a user never has a password. Off by default, because it is a public route that creates accounts; it is bounded per IP like password sign-up, and the account exists only after a verified attestation, which no script can forge. It needs an identifier plugin, so the new user has an address to show and to verify.

type Passkey

type Passkey struct {
	ID         string     `json:"id"`
	Name       string     `json:"name"`
	CreatedAt  time.Time  `json:"createdAt"`
	LastUsedAt *time.Time `json:"lastUsedAt"`
	// AAGUID identifies the authenticator model (1Password, Windows Hello…)
	// as a UUID string; AuthenticatorName turns it into a label. Empty, or
	// all zeros, when the authenticator declined to say, which Apple devices
	// do under the default attestation.
	AAGUID string `json:"aaguid"`
	// BackedUp reports whether the passkey is synced by the platform (iCloud
	// Keychain, Google Password Manager) rather than bound to one device.
	BackedUp bool `json:"backedUp"`
	// Transports are the ways the authenticator reported it can be reached
	// ("internal", "usb", "hybrid"…), for a settings page's icon.
	Transports []string `json:"transports"`
	// Extensions are the browser's client extension results from the
	// registration that made this passkey (RegistrationExtensions), as JSON,
	// set only on the Passkey that register-finish or sign-up-finish
	// returns; the list does not keep them.
	Extensions json.RawMessage `json:"extensions,omitempty"`
}

Passkey is one row of the list: what a settings page shows. The credential itself never leaves the plugin; AAGUID, BackedUp and Transports are read from it.

type Plugin

type Plugin struct {
	// contains filtered or unexported fields
}

Plugin is the passkey sign-in method. Build it with New and pass it to auth.WithPlugins; its Go methods and its HTTP routes run the same operations.

func New

func New(opts ...Option) *Plugin

New builds the plugin. The relying party comes from auth.WithBaseURL unless RelyingParty names it.

func (*Plugin) BeginPresence

func (p *Plugin) BeginPresence(ctx context.Context, userID, scope string) (string, json.RawMessage, error)

BeginPresence starts an assertion over userID's passkeys with user verification required, whatever AuthenticatorSelection says, because presence means a person proved it, not a device that was merely touched. It returns the ceremony handle and the options for navigator.credentials.get; a user with no passkey is ErrNotFound.

func (*Plugin) DataHooks

func (p *Plugin) DataHooks() auth.DataHooks

DataHooks sets a new user's id to the sign-up ceremony's pre-minted id when the creating context carries one, and touches nothing else: every other CreateUser in the process has no id in its context and gets the core's.

func (*Plugin) Init

func (p *Plugin) Init(a *auth.Auth) error

Init builds the WebAuthn relying party. User verification (PIN or biometric) is required on every ceremony: it is what makes a passkey sign-in multi-factor, so the plugin may skip the SecondFactor plugins.

func (*Plugin) List

func (p *Plugin) List(ctx context.Context) ([]Passkey, error)

List returns the signed-in user's passkeys, oldest first.

func (*Plugin) LoginBegin

func (p *Plugin) LoginBegin(ctx context.Context) (BeginResult, error)

LoginBegin starts a discoverable passkey sign-in: no identifier is asked for, the authenticator offers the passkeys it holds for this site.

func (*Plugin) LoginFinish

func (p *Plugin) LoginFinish(ctx context.Context, in FinishRequest) (SignInResult, error)

LoginFinish verifies the authenticator's answer and signs the user in.

func (*Plugin) Name

func (p *Plugin) Name() string

Name is PluginName, the plugin's permanent identity in the migration ledger.

func (*Plugin) Operations

func (p *Plugin) Operations() []auth.Operation

Operations lists register (begin, finish), login (begin, finish), re-authentication (begin, finish), list, remove and rename, and sign-up (begin, finish) with WithSignUp.

func (*Plugin) OptionErr

func (p *Plugin) OptionErr() error

OptionErr is every error the options recorded, such as auth.ErrNilOption naming an option given nil; auth.New refuses to start while it is not nil (auth.OptionChecker).

func (*Plugin) PresenceEnrolled

func (p *Plugin) PresenceEnrolled(ctx context.Context, userID string) (bool, error)

PresenceEnrolled reports whether userID has a passkey. With BeginPresence and VerifyPresence it satisfies agentauth.PresenceVerifier.

func (*Plugin) RateLimits

func (p *Plugin) RateLimits() []auth.RateRule

RateLimits bounds login-begin per IP (loginBeginIPLimit a minute), the re-authentication ceremony per IP and per user (reauthRules) and, with WithSignUp, sign-up-begin (signUpIPLimit an hour). The other operations need a signed-in user or a ceremony from a begin, so these rules bound every anonymous write the plugin makes.

func (*Plugin) ReauthenticateBegin

func (p *Plugin) ReauthenticateBegin(ctx context.Context) (BeginResult, error)

ReauthenticateBegin starts an assertion for the signed-in user's own passkeys, bound to the current session.

func (*Plugin) ReauthenticateFinish

func (p *Plugin) ReauthenticateFinish(ctx context.Context, in ReauthFinishRequest) (auth.Reauthentication, error)

ReauthenticateFinish verifies the assertion and makes the current session fresh again; see auth.Reauthentication for an answer that asks for the second factor. Every refused assertion is ErrPasskeyInvalid.

func (*Plugin) RegisterBegin

func (p *Plugin) RegisterBegin(ctx context.Context) (BeginResult, error)

RegisterBegin starts adding a passkey for the signed-in user. The user's existing passkeys are excluded, so an authenticator that already holds one is not registered twice.

func (*Plugin) RegisterBeginWith

func (p *Plugin) RegisterBeginWith(ctx context.Context, in RegisterBeginRequest) (BeginResult, error)

RegisterBeginWith is RegisterBegin with a request, to restrict the authenticator kind.

func (*Plugin) RegisterFinish

func (p *Plugin) RegisterFinish(ctx context.Context, in FinishRequest) (Passkey, error)

RegisterFinish verifies the authenticator's answer and stores the new passkey. A ceremony works once, and only for the user who began it.

func (*Plugin) Remove

func (p *Plugin) Remove(ctx context.Context, id string) error

Remove deletes a passkey, unless it is the last way into the account.

func (*Plugin) Rename

func (p *Plugin) Rename(ctx context.Context, id, name string) error

Rename relabels one of the signed-in user's passkeys; the name is cut to the same length as at registration. An id that is not the user's is ErrNotFound.

func (*Plugin) SecurityKeys

func (p *Plugin) SecurityKeys() twofactor.SecurityKeyStore

SecurityKeys is the store twofactor.WithSecurityKeys takes: this plugin's security keys as second factors. Register the plugin itself with auth.WithPlugins too; until auth.New has initialised it, every method is auth.ErrOperationNotWired.

func (*Plugin) SignInCredentials

func (p *Plugin) SignInCredentials(ctx context.Context, userID, exceptID string) (int, error)

SignInCredentials counts a user's passkeys for the core's last-way-in check, leaving out exceptID, the one about to be removed.

func (*Plugin) SignUpBegin

func (p *Plugin) SignUpBegin(ctx context.Context, in SignUpBeginRequest) (BeginResult, error)

SignUpBegin starts a passkey-first sign-up (WithSignUp): no session, no password; the account is created at SignUpFinish from a verified attestation. The identifier is checked against the identifier plugins before any ceremony starts.

func (*Plugin) SignUpFinish

func (p *Plugin) SignUpFinish(ctx context.Context, in FinishRequest) (SignUpResult, error)

SignUpFinish verifies the authenticator's answer, creates the user with the identifier and the passkey, and signs them in unless the identifier's kind requires verification first.

func (*Plugin) SignsIn

func (p *Plugin) SignsIn() bool

SignsIn reports that a passkey is a way in, so auth.New counts the plugin as a sign-in method and the core refuses to remove a user's last one.

func (*Plugin) Tables

func (p *Plugin) Tables() []sqlb.Table

Tables declares the plugin's table, so auth.New can refuse another plugin claiming the same name or alias.

func (*Plugin) TypedMigrations

func (p *Plugin) TypedMigrations(engine string, t auth.SQLTypes) ([]auth.Migration, error)

TypedMigrations creates auth_passkey and its user index for engine, then the security-key table (securitykey.go). MySQL has no CREATE INDEX IF NOT EXISTS, so there the index is declared inside the CREATE TABLE, which already has IF NOT EXISTS.

func (*Plugin) UserTables

func (p *Plugin) UserTables() []auth.UserTable

UserTables declares that auth_passkey and auth_passkey_security_key rows belong to the user in user_id, so DeleteUser removes them (no foreign key does, ADR-0002).

func (*Plugin) Validate

func (p *Plugin) Validate(c *auth.Config) error

Validate needs a relying party: an explicit one, or a BaseURL to take it from. Without one no ceremony could ever verify. WithSignUp also needs an identifier kind to hold the new user's address.

func (*Plugin) VerifyPresence

func (p *Plugin) VerifyPresence(ctx context.Context, userID, scope, ceremony string, credential json.RawMessage) error

VerifyPresence spends the ceremony and checks the assertion: begun for userID and scope, signed by one of userID's passkeys, with the user verified, and no clone warning. It updates the passkey's counter. Every refusal is ErrPasskeyInvalid, or ErrCeremonyInvalid for a spent or unknown ceremony.

func (*Plugin) WellKnown

func (p *Plugin) WellKnown() http.Handler

WellKnown serves the Related Origin Requests document for the relying party, {"origins": [...]}, listing the plugin's origins. It is how a deployment that moves to a new domain keeps its passkeys: they are bound to the old relying party id for good, so keep RelyingParty("old.example", "https://new.example", …), and serve this handler at https://old.example/.well-known/webauthn (WellKnownPath), so the browser lets the new origin use the old id. Browsers without Related Origin Requests still need the old domain. It answers GET and HEAD only, and works after auth.New.

type ReauthFinishRequest

type ReauthFinishRequest struct {
	Ceremony   string          `json:"ceremony"`
	Credential json.RawMessage `json:"credential"`
}

ReauthFinishRequest completes a re-authentication ceremony. Credential is the JSON the browser's PublicKeyCredential serializes to.

type RegisterBeginRequest

type RegisterBeginRequest struct {
	// AuthenticatorAttachment restricts the kind of authenticator the browser
	// offers: "platform" (the device's own, Face ID, Windows Hello) or
	// "cross-platform" (a security key, a phone). Empty lets the browser
	// offer both, which is the usual choice.
	AuthenticatorAttachment string `json:"authenticatorAttachment,omitempty"`
}

RegisterBeginRequest is the optional input of register-begin.

type RemoveRequest

type RemoveRequest struct {
	ID string `json:"id"`
}

RemoveRequest names a passkey of the signed-in user by its id.

type RenameRequest

type RenameRequest struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

RenameRequest gives a passkey of the signed-in user a new label.

type Requirement

type Requirement string

Requirement is a WebAuthn requirement level, for the resident-key and user-verification choices of AuthenticatorSelection.

const (
	RequirementRequired    Requirement = "required"
	RequirementPreferred   Requirement = "preferred"
	RequirementDiscouraged Requirement = "discouraged"
)

The three WebAuthn requirement levels (WebAuthn §5.4.6, §5.8.6).

type Selection

type Selection struct {
	// ResidentKey asks for a discoverable credential, the kind a sign-in
	// with no identifier can find. Below required, a passkey may be
	// non-discoverable and then signs in only under
	// AllowCredentialsForSession, which names it to the browser.
	ResidentKey Requirement
	// UserVerification asks for a PIN or a biometric. Below required, a
	// sign-in whose authenticator did not verify the user is one factor:
	// it goes through the second-factor step like a password.
	UserVerification Requirement
	// Attachment is AttachmentPlatform or AttachmentCrossPlatform, or ""
	// for either.
	Attachment string
}

Selection is better-auth's authenticatorSelection: what the relying party asks of an authenticator. An empty field keeps the plugin's default, RequirementRequired for both levels and any attachment. A request's own AuthenticatorAttachment still narrows the attachment per registration.

type SignInResult

type SignInResult struct {
	User  auth.UserView `json:"user"`
	Token auth.Token    `json:"-"`
	// SecondFactorRequired is true when the authenticator did not verify
	// the user (possible only below RequirementRequired, see
	// AuthenticatorSelection) and the user has a second factor: the session
	// is pending until that step passes.
	SecondFactorRequired bool `json:"secondFactorRequired,omitempty"`
	// Extensions are the browser's client extension results for the
	// assertion (AuthenticationExtensions), as JSON; empty when there are
	// none.
	Extensions json.RawMessage `json:"extensions,omitempty"`
}

SignInResult is the output of login-finish. Token is for Go callers and bearer transports, never encoded into JSON.

type SignUpBeginRequest

type SignUpBeginRequest struct {
	Identifier              string `json:"identifier"`
	Name                    string `json:"name,omitempty"`
	AuthenticatorAttachment string `json:"authenticatorAttachment,omitempty"`
}

SignUpBeginRequest starts a passkey-first sign-up: the identifier the new account will hold (an email address, phone number or username one of the identifier plugins accepts), the user's display name, and optionally the authenticator kind, as on RegisterBeginRequest.

type SignUpResult

type SignUpResult struct {
	User                 auth.UserView `json:"user"`
	Passkey              Passkey       `json:"passkey"`
	VerificationRequired bool          `json:"verificationRequired"`
	Token                auth.Token    `json:"-"`
}

SignUpResult is the output of sign-up-finish: the new user, their first passkey, and either a session (Token, for Go callers and bearer clients) or VerificationRequired when the identifier's kind demands verification before the first sign-in, exactly as password sign-up behaves.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL