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
- Variables
- func AuthenticatorName(aaguid string) string
- type AccountNameFunc
- type BeginResult
- type Conveyance
- type Extensions
- type FinishRequest
- type ListResult
- type MetadataProvider
- type Option
- func AccountName(fn AccountNameFunc) Option
- func AllowAuthenticators(aaguids ...string) Option
- func AllowCredentialsForSession() Option
- func Attestation(c Conveyance) Option
- func AuthenticationExtensions(ext Extensions) Option
- func AuthenticatorSelection(s Selection) Option
- func DenyAuthenticators(aaguids ...string) Option
- func DisplayName(name string) Option
- func RegistrationExtensions(ext Extensions) Option
- func RelyingParty(id string, origins ...string) Option
- func WithCeremonyTTL(d time.Duration) Option
- func WithMetadata(m MetadataProvider) Option
- func WithSignUp() Option
- type Passkey
- type Plugin
- func (p *Plugin) BeginPresence(ctx context.Context, userID, scope string) (string, json.RawMessage, error)
- func (p *Plugin) DataHooks() auth.DataHooks
- func (p *Plugin) Init(a *auth.Auth) error
- func (p *Plugin) List(ctx context.Context) ([]Passkey, error)
- func (p *Plugin) LoginBegin(ctx context.Context) (BeginResult, error)
- func (p *Plugin) LoginFinish(ctx context.Context, in FinishRequest) (SignInResult, error)
- func (p *Plugin) Name() string
- func (p *Plugin) Operations() []auth.Operation
- func (p *Plugin) OptionErr() error
- func (p *Plugin) PresenceEnrolled(ctx context.Context, userID string) (bool, error)
- func (p *Plugin) RateLimits() []auth.RateRule
- func (p *Plugin) ReauthenticateBegin(ctx context.Context) (BeginResult, error)
- func (p *Plugin) ReauthenticateFinish(ctx context.Context, in ReauthFinishRequest) (auth.Reauthentication, error)
- func (p *Plugin) RegisterBegin(ctx context.Context) (BeginResult, error)
- func (p *Plugin) RegisterBeginWith(ctx context.Context, in RegisterBeginRequest) (BeginResult, error)
- func (p *Plugin) RegisterFinish(ctx context.Context, in FinishRequest) (Passkey, error)
- func (p *Plugin) Remove(ctx context.Context, id string) error
- func (p *Plugin) Rename(ctx context.Context, id, name string) error
- func (p *Plugin) SecurityKeys() twofactor.SecurityKeyStore
- func (p *Plugin) SignInCredentials(ctx context.Context, userID, exceptID string) (int, error)
- func (p *Plugin) SignUpBegin(ctx context.Context, in SignUpBeginRequest) (BeginResult, error)
- func (p *Plugin) SignUpFinish(ctx context.Context, in FinishRequest) (SignUpResult, error)
- func (p *Plugin) SignsIn() bool
- func (p *Plugin) Tables() []sqlb.Table
- func (p *Plugin) TypedMigrations(engine string, t auth.SQLTypes) ([]auth.Migration, error)
- func (p *Plugin) UserTables() []auth.UserTable
- func (p *Plugin) Validate(c *auth.Config) error
- func (p *Plugin) VerifyPresence(ctx context.Context, userID, scope, ceremony string, ...) error
- func (p *Plugin) WellKnown() http.Handler
- type ReauthFinishRequest
- type RegisterBeginRequest
- type RemoveRequest
- type RenameRequest
- type Requirement
- type Selection
- type SignInResult
- type SignUpBeginRequest
- type SignUpResult
Constants ¶
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.
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.
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.
const ( AttachmentPlatform = string(protocol.Platform) AttachmentCrossPlatform = string(protocol.CrossPlatform) )
Authenticator attachments, the two values WebAuthn defines.
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.
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.
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.
const DefaultCeremonyTTL = 5 * time.Minute
DefaultCeremonyTTL is how long a user has to touch the authenticator.
const DefaultDisplayName = "App"
DefaultDisplayName is the app name the browser's passkey prompt shows without DisplayName.
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.
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.
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.
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 ¶
var ( TablePasskey = sqlb.Table{Name: TableNamePasskey, Alias: TableAliasPasskey} PasskeyID = sqlb.Col[string](TablePasskey, ColID) UserID = sqlb.Col[string](TablePasskey, ColUserID) CredentialID = sqlb.Col[[]byte](TablePasskey, ColCredentialID) Credential = sqlb.Col[string](TablePasskey, ColCredential) Name = sqlb.Col[string](TablePasskey, ColName) CreatedAt = sqlb.Col[time.Time](TablePasskey, ColCreatedAt) LastUsedAt = sqlb.Col[*time.Time](TablePasskey, ColLastUsedAt) )
Typed columns, for an app that reads the table (reads are open; only the plugin writes it).
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.
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") )
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.
var ConveyanceValues = []Conveyance{ConveyanceNone, ConveyanceIndirect, ConveyanceDirect, ConveyanceEnterprise}
ConveyanceValues is the canonical iteration order over conveyances.
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.
var RequirementValues = []Requirement{RequirementRequired, RequirementPreferred, RequirementDiscouraged}
RequirementValues is the canonical iteration order over requirement levels.
Functions ¶
func AuthenticatorName ¶
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 ¶
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. 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 ¶
type Extensions = protocol.AuthenticationExtensions
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 ¶
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 ¶
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 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 ¶
AuthenticatorSelection replaces what the plugin asks of an authenticator. 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.
func DenyAuthenticators ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) 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) Operations ¶
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 ¶
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 ¶
PresenceEnrolled reports whether userID has a passkey. With BeginPresence and VerifyPresence it satisfies agentauth.PresenceVerifier.
func (*Plugin) RateLimits ¶
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 ¶
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) Rename ¶
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 ¶
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 ¶
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 ¶
Tables declares the plugin's table, so auth.New can refuse another plugin claiming the same name or alias.
func (*Plugin) TypedMigrations ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 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.