plainauth

package module
v0.0.0-...-a9ad9ac Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 68 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Plain Auth

Verify Go Reference

Plain Auth is an authentication library for Go servers. Mount its http.Handler on your router, then use the same instance in your own handlers to read the signed-in user. Your application keeps its listener, middleware, routes, database and screens, and any frontend or HTTP client can call the JSON API.

Developer preview. APIs and SQL migrations may change before the first tagged release. The roadmap shows what is finished and what remains, with a test linked to every completed behavior.

What it does

  • Sign in with email and password, usernames, magic links, email or SMS codes, passkeys, social providers, Google One Tap, Ethereum wallets or guest accounts.
  • Sessions that are database-backed and revocable, with optional cookie caching, several accounts per browser, device authorization and cross-subdomain cookies.
  • Security: two-factor authentication, rate limits shared through Redis or Valkey, CAPTCHA, breached-password checks and trusted origins.
  • Organizations and teams with roles, permissions, invitations and member limits, plus administrator accounts and API keys.
  • Enterprise: OIDC and SAML single sign-on, and SCIM directory provisioning.
  • OAuth 2.0 and OpenID Connect provider: authorization code with PKCE, refresh tokens, client registration, introspection, revocation and JWKS.
  • Billing with Stripe subscriptions and seats, or Polar checkout.
  • Storage and tools: SQLite, PostgreSQL and MySQL, the authctl schema CLI, an OpenAPI document, error messages in 22 languages and test helpers.
  • Extend with Go plugins and endpoint hooks that reject, rewrite or answer requests and change their results.

Every capability has a guide in the documentation index.

Quickstart

Use a patched Go 1.26 or newer toolchain and a C compiler (for SQLite). Clone the repository, generate a signing secret and start the example app.

git clone https://github.com/Plain-Org/plain-auth.git
cd plain-auth
export "$(go run ./cmd/authctl secret)"
export AUTH_URL=http://127.0.0.1:3000
go run ./examples/basic

The example listens on http://127.0.0.1:3000 and creates auth.db in the working directory (set AUTH_DB to change it). In another terminal, create an account, call a protected route and sign out:

curl -sS -c cookies.txt http://127.0.0.1:3000/api/auth/sign-up/email \
  -H 'Content-Type: application/json' \
  -d '{"name":"Ada","email":"ada@example.com","password":"example-password"}'

curl -sS -b cookies.txt http://127.0.0.1:3000/me

curl -sS -b cookies.txt -c cookies.txt http://127.0.0.1:3000/api/auth/sign-out \
  -H 'Origin: http://127.0.0.1:3000' -H 'Content-Type: application/json' -d '{}'

Add it to your app

Install the SQLite adapter, which also brings in the core library, from main:

go get github.com/Plain-Org/plain-auth/adapters/sqlite@main

Create one instance and mount it under its base path (/api/auth by default):

import (
    "strings"

    "github.com/Plain-Org/plain-auth"
    "github.com/Plain-Org/plain-auth/adapters/sqlite"
)

store, err := sqlite.Open("auth.db")
if err != nil {
    return err
}
defer store.Close() // in the function that owns the application's lifetime

auth, err := plainauth.New(plainauth.Options{
    Store:            store,
    EmailAndPassword: true,
})
if err != nil {
    return err
}
mux.Handle(strings.TrimSuffix(auth.BasePath(), "/")+"/", auth)

Inside your own handlers, auth.GetSession(r.Context(), r.Header) returns the signed-in user, or nil when the request is anonymous. New reads AUTH_SECRET and AUTH_URL from the environment; see environment configuration for every setting. The module path is github.com/Plain-Org/plain-auth and the package name is plainauth.

Project

A hosted Plain Auth service is coming soon for teams that would rather not run it themselves.

Documentation

Overview

Package plainauth embeds authentication in the host application's HTTP server.

An Auth instance implements net/http.Handler. Mount it under its base path on any router, and use the same instance inside your own handlers to read the signed-in user:

auth, err := plainauth.New(plainauth.Options{
	Store:            store, // for example sqlite.Open("auth.db")
	EmailAndPassword: true,
})
if err != nil {
	return err
}
mux.Handle(strings.TrimSuffix(auth.BasePath(), "/")+"/", auth)

mux.HandleFunc("GET /me", func(w http.ResponseWriter, r *http.Request) {
	session, err := auth.GetSession(r.Context(), r.Header)
	// session is nil when the request is not signed in.
})

The application owns the listener, routes, middleware, database lifetime and every screen. Any HTTP client can call the JSON API, and the client package provides a typed Go client.

New reads AUTH_SECRET and AUTH_URL from the environment when the matching options are empty. Storage adapters live in the adapters directory, optional features in plugins, and sign-in providers in providers. The guides at https://github.com/Plain-Org/plain-auth/tree/main/docs cover each feature.

Index

Constants

View Source
const (
	FieldString  = sessionfields.String
	FieldNumber  = sessionfields.Number
	FieldBoolean = sessionfields.Boolean
	FieldDate    = sessionfields.Date
)
View Source
const DeviceGrantType = "urn:ietf:params:oauth:grant-type:device_code"

Variables

View Source
var (
	// ErrLoginPlanned ends a dry run. The store rolls back and returns it.
	ErrLoginPlanned = errors.New("plainauth: sign-in planned and rolled back")
	// ErrLoginPlanChanged ends an approved run whose writes differ from the dry run.
	ErrLoginPlanChanged = errors.New("plainauth: sign-in changed while its hooks ran")
)
View Source
var (
	ErrTransferSessionExpired = errors.New("one-time token session expired")
	ErrTransferSessionMissing = errors.New("one-time token session absent")
)
View Source
var (
	// ErrNotFound reports a missing record. Stores also return it for a token
	// that expired, was spent or belongs to another account.
	ErrNotFound = errors.New("authn: record not found")
	// ErrEmailTaken reports that a store write found another user with the
	// address: CreateUser, AccountLifecycleStore.ChangeAccountEmail, admin
	// user writes and phone sign-up.
	ErrEmailTaken = errors.New("authn: email already registered")
)
View Source
var ErrAdminExists = errors.New("an administrative account already exists")

ErrAdminExists indicates that an account already holds a role the bootstrap would grant.

View Source
var ErrIDTokenUsed = errors.New("ID token has already been used")
View Source
var ErrInvalidJWT = errors.New("jwt: invalid service token")
View Source
var ErrLastAccount = errors.New("auth: cannot unlink last account")
View Source
var ErrMagicLinkSignUpDisabled = errors.New("magic link registration disabled")
View Source
var ErrNotAnonymous = errors.New("user is not anonymous")
View Source
var ErrOAuthAccountAlreadyLinked = errors.New("social identity belongs to another account")
View Source
var ErrOAuthEmailUnverified = errors.New("OAuth account requires email verification")
View Source
var ErrOAuthLinkEmailMismatch = errors.New("provider email does not match the account email")

ErrOAuthLinkEmailMismatch refuses an explicit link whose provider email differs from the account's email.

View Source
var ErrOAuthLinkNotAllowed = errors.New("provider email is not verified and the provider is not trusted")

ErrOAuthLinkNotAllowed refuses an explicit link from a provider that is not trusted and did not verify the email.

View Source
var ErrOAuthLinkRequired = errors.New("account must be linked by its existing owner")
View Source
var ErrOAuthLinkingDisabled = errors.New("account linking is disabled")
View Source
var ErrOAuthProfileConflict = errors.New("provider profile conflicts with an existing profile")
View Source
var ErrOAuthSignupDisabled = errors.New("OAuth account creation disabled")
View Source
var ErrPasswordAlreadySet = errors.New("authn: password already set")
View Source
var ErrPhoneNumberExists = &APIError{400, "PHONE_NUMBER_EXIST", "Phone number already exists"}
View Source
var ErrSCIMUserInactive = errors.New("the SCIM user the sign-in relies on is no longer active")

ErrSCIMUserInactive refuses a sign-in whose required SCIM User is no longer active.

View Source
var ErrSkipWrite = errors.New("plainauth: write skipped by a database hook")

ErrSkipWrite cancels a write from a database before hook. The operation then fails with its usual error for a write that did not happen, such as FAILED_TO_CREATE_USER.

View Source
var ErrUsernameImmutable = errors.New("plainauth: username is immutable")
View Source
var ErrUsernameTaken = errors.New("plainauth: username already taken")
View Source
var ErrVerificationPending = errors.New("plainauth: a verification record awaits its before hooks")

ErrVerificationPending ends a store call that a VerificationGate stopped because a record it was about to write awaits its before hooks. The store returns it, alone or joined with errors.Join, after rolling back, never retries it and commits nothing.

Functions

func DefaultAdminRoles

func DefaultAdminRoles() map[string]AdminPermissions

DefaultAdminRoles returns an independent copy of the built-in "admin" and "user" roles that AdminOptions uses when Roles is nil. The admin role grants every built-in action except user:impersonate-admins, and the user role grants none.

func HashPassword

func HashPassword(ctx context.Context, password string) (string, error)

HashPassword uses the built-in salted scrypt credential format. Hosts can delegate to it when adapting an existing password database.

func OAuthAdditionalData

func OAuthAdditionalData(ctx context.Context) map[string]any

OAuthAdditionalData returns the additionalData object the browser sent to /sign-in/social, /link-social or /oauth-popup/start, during that flow's callback. The values are browser input: treat them as untrusted and do not modify the map. Numbers decode as float64. OAuthStateFrom returns the same data with the rest of the flow's state. On the OAuth proxy's production instance OAuthStateFrom reports false, but OAuthAdditionalData still returns the data to the provider's callbacks and the hooks.

func OAuthStateFailure

func OAuthStateFailure(err error) string

OAuthStateFailure returns the browser error code of a state failure from ConsumeEnterpriseFlow or ConsumeEnterprisePostFlow: state_not_found, state_mismatch or state_invalid. It returns "" for any other error.

func ValidEnterpriseProfile

func ValidEnterpriseProfile(p OAuthProfile) bool

ValidEnterpriseProfile reports whether a provider profile has a usable subject and email; CompleteEnterpriseFlow refuses one that does not.

func VerifyPasswordHash

func VerifyPasswordHash(ctx context.Context, hash, password string) (bool, error)

VerifyPasswordHash checks the built-in scrypt format. It returns false for an incorrect password and an error for a malformed stored credential.

Types

type APIError

type APIError struct {
	Status  int    `json:"-"`
	Code    string `json:"code,omitempty"`
	Message string `json:"message"`
}

APIError exposes a public status and error code shared by Go and HTTP callers.

func UserInfoRefusal

func UserInfoRefusal(err error) *APIError

UserInfoRefusal returns the 403 error of a ValidateUserInfo refusal, or nil when err is not one, so a plugin can render it before its own mappings.

func (*APIError) Error

func (e *APIError) Error() string

type AccessTokenResult

type AccessTokenResult struct {
	AccessToken          string     `json:"accessToken"`
	AccessTokenExpiresAt *time.Time `json:"accessTokenExpiresAt,omitempty"`
	Scopes               []string   `json:"scopes"`
	IDToken              string     `json:"idToken,omitempty"`
}

type AccountField

type AccountField = sessionfields.Field

AccountField declares an attribute of a provider or credential account.

type AccountFieldRule

type AccountFieldRule struct {
	ValidateInput  func(any) error
	TransformInput func(any) (any, error)
}

AccountFieldRule customizes one declared account field. ValidateInput checks mapped provider values. TransformInput runs when a value is saved, including creation defaults. Both receive the normalized scalar and should be pure.

type AccountFieldStore

type AccountFieldStore interface {
	WithAccountFields(map[string]AccountField, map[string]AccountFieldRule) (Store, error)
}

AccountFieldStore binds validated account declarations to one auth instance. Its returned store supplies defaults on account creation and lists only public fields.

type AccountInfoResult

type AccountInfoResult struct {
	User struct {
		Name          string  `json:"name"`
		Email         string  `json:"email"`
		EmailVerified bool    `json:"emailVerified"`
		Image         *string `json:"image,omitempty"`
	} `json:"user"`
	Account struct {
		ID         string `json:"id"`
		ProviderID string `json:"providerId"`
		AccountID  string `json:"accountId"`
	} `json:"account"`
	Data any `json:"data"`
}

type AccountLifecycleStore

type AccountLifecycleStore interface {
	SetInitialPassword(ctx context.Context, userID, sessionToken, newHash string, now time.Time) error
	SaveDeletionToken(ctx context.Context, t PasswordResetToken) error
	DeleteAccount(ctx context.Context, userID, sessionToken, expectedHash, deleteToken string, now time.Time) error
	ChangeAccountEmail(ctx context.Context, userID, currentEmail, newEmail string, verified bool, now time.Time) (User, error)
}

AccountLifecycleStore provides owner-bound account writes. Session-based mutations check the current session and user in the same transaction.

type AccountSelection

type AccountSelection struct {
	AccountID, UserID string
	UseAccountCookie  bool
}

AccountSelection identifies a local linked-account record. UserID is only used by trusted server calls with nil session headers.

type AccountStore

type AccountStore interface {
	// UpdateProfile applies the update and sets UpdatedAt to now.
	UpdateProfile(ctx context.Context, userID string, update ProfileUpdate, now time.Time) error
	// CreateCredentialSession stores the session only while the user's hash
	// is still expectedHash; otherwise it returns ErrNotFound.
	CreateCredentialSession(ctx context.Context, expectedHash string, session StoredSession) error
	// ChangeCredential replaces oldHash, or returns ErrNotFound when the
	// stored hash differs. A replacement session leaves only that session.
	ChangeCredential(ctx context.Context, userID, oldHash, newHash string, replacement *StoredSession) error
	// FindAccountUser matches the address case-insensitively.
	FindAccountUser(ctx context.Context, email string) (User, error)
	SavePasswordResetToken(context.Context, PasswordResetToken) error
	// FindPasswordResetToken treats a token as expired once now reaches
	// ExpiresAt.
	FindPasswordResetToken(ctx context.Context, token string, now time.Time) (PasswordResetToken, error)
	// FinishPasswordReset spends the token with the new hash; revokeSessions
	// deletes every session of the user.
	FinishPasswordReset(ctx context.Context, token, newHash string, now time.Time, revokeSessions bool) error
	// VerifyAccountEmail requires the user's current address; a repeat
	// returns nil.
	VerifyAccountEmail(ctx context.Context, userID, email string, now time.Time) error
}

AccountStore extends a credential store with atomic profile, credential and verification operations. Its password methods serialize credential changes with creation of sessions for the old password. Expired or spent tokens, changed passwords, and mismatched account bindings return ErrNotFound.

type AdminBootstrap

type AdminBootstrap struct {
	Name, Email, Password string
	// Roles are the roles granted; empty grants "admin".
	Roles         []string
	EmailVerified bool
	Image         *string
	// UserFields declares the application's additional user fields; Values
	// sets some of them, and declared defaults fill the rest.
	UserFields map[string]UserField
	Values     map[string]any
}

AdminBootstrap describes the administrator BootstrapAdminAccount creates.

type AdminBootstrapFieldStore

type AdminBootstrapFieldStore interface {
	CreateFirstAdminWithFields(ctx context.Context, user User, hash string, fields UserFieldValues) error
}

AdminBootstrapFieldStore creates the first holder of the bootstrap roles together with additional user field columns.

type AdminBootstrapStore

type AdminBootstrapStore interface {
	CreateFirstAdmin(context.Context, User, string) error
}

AdminBootstrapStore creates the first holder of the bootstrap roles. It refuses with ErrAdminExists when an account already holds one of the user's roles, so concurrent bootstraps create at most one.

type AdminCreateUserRequest

type AdminCreateUserRequest struct {
	Name     string         `json:"name"`
	Email    string         `json:"email"`
	Password string         `json:"password,omitempty"`
	Role     []string       `json:"role,omitempty"`
	Data     map[string]any `json:"data,omitempty"`
}

AdminCreateUserRequest contains a trusted or session-authorized administrative request.

type AdminHostCreateStore

type AdminHostCreateStore interface {
	AdminCreateTransaction(context.Context, time.Time, func(AdminUserCreator) error) error
}

AdminHostCreateStore runs the explicitly trusted, in-process create operation.

type AdminOptions

type AdminOptions struct {
	// DefaultRole is stored on accounts created without a role, by sign-up
	// or by an administrator. It defaults to "user" and must be a key of
	// Roles.
	DefaultRole string
	// AdminRoles lists the protected roles. Impersonating a holder needs
	// user:impersonate-admins or AllowImpersonatingAdmins, and only another
	// protected operator can change a holder's phone number. It defaults to
	// ["admin"] and replaces that default when set. Each name must match a
	// key of Roles exactly, including case.
	AdminRoles []string
	// AdminUserIDs grants every administrative permission to these account
	// IDs and protects them like AdminRoles holders.
	AdminUserIDs []string
	// Roles maps role names to grants. Nil selects DefaultAdminRoles; a
	// non-nil map replaces the built-in roles.
	Roles map[string]AdminPermissions
	// DefaultBanReason is stored when a ban gives no reason. It defaults to
	// "No reason".
	DefaultBanReason string
	// BannedUserMessage is the BANNED_USER message a banned account
	// receives.
	BannedUserMessage string
	// BannedUserMessageFunc, when set, builds the BANNED_USER message from
	// the banned account, with its role, ban fields and public additional
	// fields, for example to quote BanReason. It runs after the store call
	// that refused the session has returned, never inside a store
	// transaction; its result is what endpoint after hooks, OnAPIError and
	// the HTTP error response see, and the error_description of a magic-link
	// error redirect. An empty result or a panic keeps BannedUserMessage, as
	// do native Go calls. The store must implement AdminUserReader.
	BannedUserMessageFunc func(ctx context.Context, user User) string
	// DefaultBanDuration sets the expiry of a ban that gives no duration.
	// Zero keeps the ban until an administrator lifts it.
	DefaultBanDuration time.Duration
	// ImpersonationSessionDuration bounds an impersonation session. It
	// defaults to one hour.
	ImpersonationSessionDuration time.Duration
	// AllowImpersonatingAdmins lets an operator with user:impersonate
	// impersonate holders of AdminRoles and AdminUserIDs.
	AllowImpersonatingAdmins bool
}

func (AdminOptions) HasPermission

func (o AdminOptions) HasPermission(id, role string, want AdminPermissions) bool

HasPermission evaluates one complete grant against each assigned role. Resource/action grants from different roles remain independent.

type AdminPage

type AdminPage struct {
	Users  []User `json:"users"`
	Total  int    `json:"total"`
	Limit  int    `json:"limit,omitempty"`
	Offset int    `json:"offset,omitempty"`
}

type AdminPermissions

type AdminPermissions map[string][]string

type AdminQuery

type AdminQuery struct {
	Limit, Offset                                                                                int
	SearchField, SearchOperator, SearchValue, FilterField, FilterOperator, SortBy, SortDirection string
	FilterValues                                                                                 []string
}

AdminQuery configures a paginated search. Field and operator names are validated by the SQL adapter.

type AdminRequest

type AdminRequest struct {
	Operation, UserID, Name, Email, Password, SessionToken, BanReason string
	Role                                                              []string
	BanDuration                                                       time.Duration
	Data                                                              map[string]any
	Query                                                             AdminQuery
	Permissions                                                       AdminPermissions
}

AdminRequest invokes an administrative operation using an authenticated caller. Operation is the endpoint name without "/admin/". Data contains approved public profile fields.

type AdminResult

type AdminResult struct {
	User     *User
	Session  *SessionResult
	Sessions []Session
	Page     *AdminPage
	Allowed  bool
	// contains filtered or unexported fields
}

type AdminStore

type AdminStore interface {
	Store
	WithAdminConfig(defaultRole, denialMessage string) (AdminStore, error)
	// AdminTransaction locks and validates the authoritative actor session and
	// account, serializing target mutations with account deletion and sign-in.
	AdminTransaction(ctx context.Context, actorToken, targetID string, now time.Time, fn func(AdminTransaction, SessionResult) error) error
}

type AdminTransaction

type AdminTransaction interface {
	User(string) (User, error)
	Users(AdminQuery) (AdminPage, error)
	CreateUser(User, string) error
	UpdateUser(User) error
	SetPassword(string, string) error
	UserSessions(string) ([]Session, error)
	RevokeSession(string) error
	RevokeListedSession(userID, sessionID string) error
	RevokeUserSessions(string) error
	DeleteUser(string) error
	Impersonate(StoredSession, Session) error
	RestoreSession(current Session, originalToken string, now time.Time) (SessionResult, error)
}

type AdminUserCreator

type AdminUserCreator interface {
	CreateUser(User, string) error
}

AdminUserCreator writes a profile and its optional password in one transaction.

type AdminUserFieldTransaction

type AdminUserFieldTransaction interface {
	CreateAdminUserWithFields(User, string, UserFieldValues) error
	User(string) (User, error)
	SelectAdminUserFields(map[string]UserField, func(*User, map[string]any) error) error
}

AdminUserFieldTransaction persists validated columns during creation and projects the public columns from the same row as the ordinary User fields.

type AdminUserFieldUpdater

type AdminUserFieldUpdater interface {
	UpdateAdminUserFields(userID string, values UserFieldValues) error
}

AdminUserFieldUpdater writes validated configured fields in the administrative transaction, alongside the profile update.

type AdminUserFields

type AdminUserFields struct {
	Role       string     `json:"role"`
	Banned     bool       `json:"banned"`
	BanReason  *string    `json:"banReason"`
	BanExpires *time.Time `json:"banExpires"`
}

AdminUserFields is present on profiles managed by the administration plugin.

type AdminUserReader

type AdminUserReader interface {
	AdminUser(ctx context.Context, userID string) (User, error)
}

AdminUserReader reads one account with its role and ban fields, outside any session or transaction. ErrNotFound reports an unknown ID.

type AnonymousLink struct {
	AnonymousUser, NewUser SessionResult
	Request                *http.Request
	Tx                     *sql.Tx
}

AnonymousLink is delivered when a live guest session becomes a verified permanent session. SQL callbacks can transfer application records with Tx.

type AnonymousOptions

type AnonymousOptions struct {
	EmailDomainName            string
	GenerateRandomEmail        func(context.Context) (string, error)
	GenerateName               func(context.Context, *http.Request) (string, error)
	OnLinkAccount              func(context.Context, AnonymousLink) error
	DisableDeleteAnonymousUser bool
}

type AnonymousStore

type AnonymousStore interface {
	CheckAnonymousSchema(context.Context) error
	IsAnonymous(ctx context.Context, userID string) (bool, error)
	CreateAnonymous(ctx context.Context, user User, session StoredSession) error
	// DeleteAnonymous removes the guest's user, its sessions and its other
	// account rows together; when it returns an error it has removed
	// nothing. It returns ErrNotAnonymous when the user is not a guest, and
	// ErrNotFound when the session is no longer live or not the user's.
	DeleteAnonymous(ctx context.Context, userID, token string, now time.Time) error
	LinkAnonymous(ctx context.Context, sourceToken, targetToken string, now time.Time, retain bool, callback func(context.Context, AnonymousLink) error) error
}

type Auth

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

Auth is safe for concurrent use by application handlers.

func New

func New(opts Options) (*Auth, error)

New constructs an http.Handler for mounting in an existing router.

func (*Auth) AccountInfo

func (a *Auth) AccountInfo(ctx context.Context, h http.Header, s AccountSelection) (AccountInfoResult, error)

func (*Auth) Admin

func (a *Auth) Admin(ctx context.Context, headers http.Header, req AdminRequest) (AdminResult, error)

Admin runs the same transaction and permission checks as the administrative HTTP endpoints. For impersonation and restoration, use the HTTP handler to receive the browser credentials.

func (*Auth) AdminCreateUser

func (a *Auth) AdminCreateUser(ctx context.Context, in AdminCreateUserRequest) (*User, error)

AdminCreateUser lets trusted application code provision an account, including server-owned fields. Do not expose this method directly as an HTTP handler.

func (*Auth) AdminUserHasPermission

func (a *Auth) AdminUserHasPermission(ctx context.Context, userID string, permissions AdminPermissions) (bool, error)

AdminUserHasPermission reports whether the stored account userID holds every permission, for trusted server code without a session. It reads the account's current role and honours AdminUserIDs. POST /admin/has-permission checks the caller's own session and ignores userId and role, as another runtime does over HTTP; do not expose this method directly as an HTTP handler. The store must implement AdminUserReader.

func (*Auth) AppName

func (a *Auth) AppName() string

AppName returns the application name shown in authenticator apps.

func (*Auth) BasePath

func (a *Auth) BasePath() string

BasePath reports the effective mount path after configuration resolution.

func (*Auth) BindOneTapNonce

func (a *Auth) BindOneTapNonce(w http.ResponseWriter, origin, audience, nonce string) error

BindOneTapNonce records a five-minute browser challenge generated by host server code. Pass a fresh, cryptographically random nonce generated for this browser, the configured Google audience and the trusted page origin. Expose the nonce through the page or a host session, never as user input.

func (*Auth) BootstrapAdmin

func (a *Auth) BootstrapAdmin(ctx context.Context, name, email, password string) (User, error)

BootstrapAdmin provisions the first administrator using the instance's password policy and credential hasher, with the same minimum as authctl.

func (*Auth) CallbackURL

func (a *Auth) CallbackURL(raw string) (string, error)

CallbackURL resolves an application callback using this instance's static trusted origins. Endpoint code uses EndpointContext.CallbackURL, which also trusts the origins TrustedOriginsForRequest adds.

func (*Auth) ChangeEmail

func (a *Auth) ChangeEmail(ctx context.Context, h http.Header, newEmail, callback string) error

ChangeEmail requests confirmation for a new address. The token is bound to both the current owner and their current address.

func (*Auth) ChangeEmailOTP

func (a *Auth) ChangeEmailOTP(ctx context.Context, h http.Header, newEmail, code string) error

ChangeEmailOTP consumes the new mailbox's proof for the authenticated account.

func (*Auth) ChangePassword

func (a *Auth) ChangePassword(ctx context.Context, h http.Header, in ChangePasswordInput, meta RequestMeta) (AuthResult, error)

ChangePassword optionally revokes all prior sessions and issues a replacement for the caller in the same transaction as the password update.

func (*Auth) CheckEmailOTP

func (a *Auth) CheckEmailOTP(ctx context.Context, email, code string, purpose EmailOTPPurpose) error

CheckEmailOTP preserves a successful proof for a subsequent action.

func (*Auth) CheckRequestOrigin

func (a *Auth) CheckRequestOrigin(r *http.Request) error

CheckRequestOrigin applies the handler's cross-site request check to a request the application serves itself, such as its own route that changes state for a cookie-authenticated browser. Direct Go calls skip the check the handler applies, so a host route should call this first. A request without cookies passes. One with cookies needs an Origin, or a Referer, that is trusted: the base URL, TrustedOrigins, TrustedOriginsForRequest or, with DynamicBaseURL, an allowed host it reached. A null Origin passes only as a same-origin request. Otherwise it returns a 403 *APIError with code INVALID_ORIGIN or MISSING_OR_NULL_ORIGIN. With DisableCSRFCheck it returns nil.

func (*Auth) CompleteEmailVerificationOTP

func (a *Auth) CompleteEmailVerificationOTP(ctx context.Context, email, code string, meta RequestMeta) (AuthResult, error)

CompleteEmailVerificationOTP optionally issues a session according to the plugin's policy.

func (*Auth) ConsumePhoneNumberOTP

func (a *Auth) ConsumePhoneNumberOTP(ctx context.Context, number, code string) error

ConsumePhoneNumberOTP spends a verification code without changing the user or creating a session. This method has no HTTP endpoint.

func (*Auth) Cookie

func (a *Auth) Cookie(name, value string, maxAge int) *http.Cookie

Cookie returns a cookie named with this instance's cookie prefix and its cookie attributes: Path=/, HttpOnly, SameSite=Lax, Secure for an HTTPS base URL and the shared domain when cross-subdomain cookies are enabled. The session cookie is Cookie("session_token", ...).

func (*Auth) CreateEmailOTP

func (a *Auth) CreateEmailOTP(ctx context.Context, email string, purpose EmailOTPPurpose) (string, error)

CreateEmailOTP creates a fresh code without sending mail. Only trusted Go application code can call this method, including for an unregistered address. A verification create hook that declines the code makes it return a code that was never stored.

func (*Auth) DecryptRecord

func (a *Auth) DecryptRecord(purpose, record string) ([]byte, error)

DecryptRecord opens a record EncryptRecord sealed for purpose, with any configured secret version. It fails for another purpose, a retired key that is no longer configured or a damaged record.

func (*Auth) DeleteUser

func (a *Auth) DeleteUser(ctx context.Context, h http.Header, in DeleteUserInput) (bool, error)

DeleteUser either requests confirmation or deletes the authenticated account. The return value is true when deletion is complete.

func (*Auth) DescribeHTTP

func (a *Auth) DescribeHTTP() HTTPDescription

DescribeHTTP lists the effective routes, including option-dependent core and plugin routes. The server URL is derived from configuration and never trusts an incoming Host header.

func (*Auth) EncryptRecord

func (a *Auth) EncryptRecord(purpose string, plaintext []byte) (string, error)

EncryptRecord seals plaintext for storage with the active versioned secret, bound to purpose: DecryptRecord opens it only with the same purpose. Plugins use it for values they must read back, such as an encrypted OAuth client secret. The envelope is this library's own, so another runtime cannot read it.

func (*Auth) ErrorPageURL

func (a *Auth) ErrorPageURL() string

ErrorPageURL is the host-controlled destination for browser protocol errors. With DynamicBaseURL it uses the fallback, and plugin endpoints use EndpointContext.ErrorPageURL for the request's own host.

func (*Auth) ExplicitlyTrustedOrigin

func (a *Auth) ExplicitlyTrustedOrigin(raw string) bool

ExplicitlyTrustedOrigin permits server-side discovery only at an exact configured origin. Browser wildcard rules do not grant network access.

func (*Auth) ExplicitlyTrustedOriginFor

func (a *Auth) ExplicitlyTrustedOriginFor(ctx context.Context, raw string) bool

ExplicitlyTrustedOriginFor is ExplicitlyTrustedOrigin for the request ctx belongs to: an exact origin TrustedOriginsForRequest returned for it also counts, as another runtime lets a trusted origins function add identity provider origins. The request's origins were resolved when it entered the handler, so the check runs no host code.

func (*Auth) GenerateOneTimeToken

func (a *Auth) GenerateOneTimeToken(ctx context.Context, h http.Header) (string, error)

GenerateOneTimeToken creates a short-lived transfer credential for the caller's active session. A token a verification create hook declines is still returned, but was never stored, so it cannot be redeemed; a hook that should fail the call returns an APIError.

func (*Auth) GenerateTOTP

func (a *Auth) GenerateTOTP(secret string) (string, error)

GenerateTOTP computes the current code for a raw provisioning secret in trusted application code.

func (*Auth) GetAccessToken

func (a *Auth) GetAccessToken(ctx context.Context, h http.Header, s AccountSelection) (AccessTokenResult, error)

func (*Auth) GetSession

func (a *Auth) GetSession(ctx context.Context, headers http.Header) (*SessionResult, error)

GetSession returns nil for an unauthenticated request.

func (*Auth) HTTPPathDisabled

func (a *Auth) HTTPPathDisabled(r *http.Request) bool

HTTPPathDisabled reports whether the request selects an HTTP path disabled on this mount. Auth and the bundled SCIM wrapper check this before authentication. Host handlers that extend the same mount can apply the same policy.

func (*Auth) HasDatabaseHooks

func (a *Auth) HasDatabaseHooks() bool

HasDatabaseHooks reports whether the instance or a plugin configured any database hook. A handler that wraps the Auth and writes users or sessions itself refuses a host with hooks it would bypass.

func (*Auth) HasOAuthProvider

func (a *Auth) HasOAuthProvider(id string) bool

HasOAuthProvider reports whether an account provider ID belongs to a startup-configured OAuth integration, in any case, because SQL collations may fold provider IDs.

func (*Auth) HasPlugin

func (a *Auth) HasPlugin(id string) bool

HasPlugin reports whether a plugin with the given ID is installed.

func (*Auth) HasUserInfoValidation

func (a *Auth) HasUserInfoValidation() bool

HasUserInfoValidation reports whether Options.ValidateUserInfo is set, so a wrapping handler that creates users can refuse a host it does not gate.

func (*Auth) HashPassword

func (a *Auth) HashPassword(ctx context.Context, password string) (string, error)

HashPassword hashes password with this instance's Options.PasswordHash, or the built-in scrypt format, within its limit on concurrent hashing.

func (*Auth) ImportTOTP

func (a *Auth) ImportTOTP(ctx context.Context, userID, base32Secret string) error

ImportTOTP enrolls an existing account with an externally provisioned SHA-1 authenticator secret. The caller must authorize the import and obtain the seed through a trusted channel. An existing or pending factor is preserved.

func (*Auth) IsUsernameAvailable

func (a *Auth) IsUsernameAvailable(ctx context.Context, name string) (bool, error)

func (*Auth) IssueJWT

func (a *Auth) IssueJWT(ctx context.Context, h http.Header) (string, error)

IssueJWT creates an audience-bound assertion from an active authenticated session.

func (*Auth) JWTSigningAlgorithm

func (a *Auth) JWTSigningAlgorithm() string

JWTSigningAlgorithm returns the configured primary algorithm, or an empty string when the JWT plugin is disabled.

func (*Auth) ListSessions

func (a *Auth) ListSessions(ctx context.Context, headers http.Header) ([]Session, error)

func (*Auth) ListUserAccounts

func (a *Auth) ListUserAccounts(ctx context.Context, h http.Header) ([]LinkedAccount, error)

func (*Auth) LocalJWKS

func (a *Auth) LocalJWKS() bool

LocalJWKS reports whether the jwt plugin is enabled and keeps its keys in this instance, so a resource server in the same process can read them without a request: it has no RemoteJWKSURL.

func (*Auth) Logger

func (a *Auth) Logger() *slog.Logger

Logger returns this instance’s logger for host handlers and plugins.

func (*Auth) OAuthIssuer

func (a *Auth) OAuthIssuer() string

OAuthIssuer returns the authorization-server issuer advertised by OAuth discovery. An explicit JWT issuer takes precedence over the public auth URL. The issuer is published without a query, fragment or trailing slash, as another runtime publishes it. Tokens this server signs name it too, where that runtime stamps the configured spelling, because clients compare iss with the discovered issuer exactly.

func (*Auth) OAuthProviderName

func (a *Auth) OAuthProviderName(id string) (string, bool)

OAuthProviderName returns the display name of the configured provider id, which defaults to id, and whether it is configured.

func (*Auth) PublicJWKS

func (a *Auth) PublicJWKS(ctx context.Context) (jose.JSONWebKeySet, error)

PublicJWKS returns public verification material. Private key data is excluded from the store query used to publish the set.

func (*Auth) PublicJWKSURL

func (a *Auth) PublicJWKSURL() string

PublicJWKSURL returns RemoteJWKSURL when set, otherwise the served key-set endpoint, or an empty string when that path is disabled.

func (*Auth) PublicURL

func (a *Auth) PublicURL() string

PublicURL returns the configured public URL of the auth mount.

func (*Auth) ReadEmailOTP

func (a *Auth) ReadEmailOTP(ctx context.Context, email string, purpose EmailOTPPurpose) (*string, error)

ReadEmailOTP returns a recoverable stored proof, or nil when absent or expired. This trusted Go operation has no HTTP route. Hashed proofs cannot be recovered.

func (*Auth) RefreshToken

func (a *Auth) RefreshToken(ctx context.Context, h http.Header, s AccountSelection) (RefreshTokenResult, error)

func (*Auth) RequestContext

func (a *Auth) RequestContext(r *http.Request) (context.Context, error)

RequestContext returns a context for direct Go calls on behalf of r. It carries the origin DynamicBaseURL resolves for r and the origins TrustedOriginsForRequest adds, so links and callback checks match a request to the handler. Without either option it returns r's context.

func (*Auth) RequestEmailChangeOTP

func (a *Auth) RequestEmailChangeOTP(ctx context.Context, h http.Header, newEmail, currentOTP string) error

RequestEmailChangeOTP delivers a proof to the new address, bound to the authenticated account.

func (*Auth) RequestPasswordReset

func (a *Auth) RequestPasswordReset(ctx context.Context, email, redirectTo string) error

RequestPasswordReset privately delivers a one-time link for a registered email.

func (*Auth) RequestPhonePasswordReset

func (a *Auth) RequestPhonePasswordReset(ctx context.Context, number string) error

RequestPhonePasswordReset delivers a separate code only to eligible registered numbers.

func (*Auth) ResetPassword

func (a *Auth) ResetPassword(ctx context.Context, token, newPassword string) error

ResetPassword consumes an unexpired recovery token atomically with the credential update.

func (*Auth) ResetPasswordEmailOTP

func (a *Auth) ResetPasswordEmailOTP(ctx context.Context, email, code, password string) error

ResetPasswordEmailOTP consumes the recovery proof under the configured password policy.

func (*Auth) ResetPhonePassword

func (a *Auth) ResetPhonePassword(ctx context.Context, number, code, password string) error

ResetPhonePassword changes the bound account's credential atomically with proof consumption.

func (*Auth) RevokeOtherSessions

func (a *Auth) RevokeOtherSessions(ctx context.Context, h http.Header) error

func (*Auth) RevokeSession

func (a *Auth) RevokeSession(ctx context.Context, h http.Header, token string) error

func (*Auth) RevokeSessions

func (a *Auth) RevokeSessions(ctx context.Context, h http.Header) error

func (*Auth) RunInBackground

func (a *Auth) RunInBackground(ctx context.Context, task func(context.Context))

RunInBackground runs task after the current work: through Options.BackgroundTasks, also from inside another task, or on a new goroutine without a runner. The task's context keeps ctx's values but not its cancellation or deadline. A panic is logged.

func (*Auth) RunInBackgroundOrAwait

func (a *Auth) RunInBackgroundOrAwait(ctx context.Context, task func(context.Context) error)

RunInBackgroundOrAwait runs task through Options.BackgroundTasks, or before it returns without one. An error is logged, not returned; a handed-off task's panic is logged too.

func (*Auth) SendEmailOTP

func (a *Auth) SendEmailOTP(ctx context.Context, email string, purpose EmailOTPPurpose) error

SendEmailOTP requests delivery to Email under the supplied purpose.

func (*Auth) SendPhoneNumberOTP

func (a *Auth) SendPhoneNumberOTP(ctx context.Context, number string) error

SendPhoneNumberOTP stores a fresh verification code and passes the raw value only to SendOTP.

func (*Auth) SendVerificationEmail

func (a *Auth) SendVerificationEmail(ctx context.Context, h http.Header, email, callback string) error

SendVerificationEmail delivers a verification link bound to the email's current owner.

func (*Auth) ServeHTTP

func (a *Auth) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves the auth endpoints beneath the configured base path.

func (*Auth) SessionCookie

func (a *Auth) SessionCookie(token string, persistent bool) *http.Cookie

SessionCookie returns the HTTP-only cookie for a token obtained through SignUpEmail or SignInEmail. The caller owns the response writer.

func (*Auth) SetPassword

func (a *Auth) SetPassword(ctx context.Context, h http.Header, password string) error

SetPassword is a server-only operation for adding a first credential to an existing account. An existing password requires ChangePassword instead.

func (*Auth) SignInEmail

func (a *Auth) SignInEmail(ctx context.Context, in SignInInput, meta RequestMeta) (AuthResult, error)

SignInEmail verifies credentials and returns a new session or a pending second-factor challenge.

func (*Auth) SignInEmailOTP

func (a *Auth) SignInEmailOTP(ctx context.Context, in EmailOTPSignInInput, meta RequestMeta) (AuthResult, error)

SignInEmailOTP consumes a sign-in code and creates a session.

func (*Auth) SignInPhoneNumber

func (a *Auth) SignInPhoneNumber(ctx context.Context, number, password string, meta RequestMeta) (AuthResult, error)

SignInPhoneNumber authenticates a stored credential and uses the same MFA and ban policy as email sign-in.

func (*Auth) SignInUsername

func (a *Auth) SignInUsername(ctx context.Context, in UsernameSignInInput, meta RequestMeta) (AuthResult, error)

func (*Auth) SignJWT

func (a *Auth) SignJWT(ctx context.Context, subject string, settings JWTSignOptions) (string, error)

SignJWT signs an assertion for a server-chosen subject. Only trusted host code should decide who can obtain an assertion and which claims to include.

func (*Auth) SignOAuthConsentQuery

func (a *Auth) SignOAuthConsentQuery(fields url.Values, expires time.Time, clearedSessionID string) string

SignOAuthConsentQuery signs a consent page after the issuer has verified its post-login step for clearedSessionID. An empty ID omits that attestation.

func (*Auth) SignOAuthQuery

func (a *Auth) SignOAuthQuery(fields url.Values, expires time.Time) string

SignOAuthQuery signs the fields for a validated, issuer-controlled interaction. The returned form includes the expiry and the names of all covered fields.

func (*Auth) SignOut

func (a *Auth) SignOut(ctx context.Context, headers http.Header) error

func (*Auth) SignUpEmail

func (a *Auth) SignUpEmail(ctx context.Context, in SignUpInput, meta RequestMeta) (AuthResult, error)

SignUpEmail creates a credential account and its first session atomically.

func (*Auth) SignedCookie

func (a *Auth) SignedCookie(name, value string, maxAge int) *http.Cookie

SignedCookie returns Cookie(name, value, maxAge) with value signed by the instance secret, in the same format as the session cookie.

func (*Auth) SignedCookieValue

func (a *Auth) SignedCookieValue(r *http.Request, name string) (string, bool)

SignedCookieValue returns the value of the request's SignedCookie of that name. It reports false when the cookie is missing or its signature does not match the current or a previous secret.

func (*Auth) TrustedDeviceCookieName

func (a *Auth) TrustedDeviceCookieName() string

TrustedDeviceCookieName returns the incoming cookie name for this instance. Native callers can pass its opaque value through RequestMeta.TrustedDeviceCookie.

func (*Auth) TrustedProviderIDs

func (a *Auth) TrustedProviderIDs(r *http.Request) ([]string, error)

TrustedProviderIDs returns the provider IDs trusted for account linking on this request, from TrustedProviders or TrustedProvidersForRequest.

func (*Auth) TwoFactorChallengeCookie

func (a *Auth) TwoFactorChallengeCookie(challenge LoginChallenge) *http.Cookie

TwoFactorChallengeCookie serializes a pending native sign-in result for the browser to carry to the verification endpoint. It cannot authenticate GetSession.

func (*Auth) UnlinkAccount

func (a *Auth) UnlinkAccount(ctx context.Context, h http.Header, recordID string) error

func (*Auth) UpdateSession

func (a *Auth) UpdateSession(ctx context.Context, h http.Header, patch map[string]any) (Session, error)

UpdateSession changes configured, browser-writable fields of the direct session. Built-in authority fields never participate in this operation.

func (*Auth) UpdateTrustedUserFields

func (a *Auth) UpdateTrustedUserFields(ctx context.Context, userID string, changes map[string]any) error

UpdateTrustedUserFields patches explicitly configured fields, including hidden and server-owned attributes. Call it only after the host authorizes userID.

func (*Auth) UpdateUser

func (a *Auth) UpdateUser(ctx context.Context, h http.Header, update ProfileUpdate) error

UpdateUser applies the permitted profile fields to the current account.

func (*Auth) ValidateNewPassword

func (a *Auth) ValidateNewPassword(ctx context.Context, path, password string) error

ValidateNewPassword runs configured plugin checks for a credential-setting operation. Custom server endpoints pass their stable path under the auth mount.

func (*Auth) ValidateUserInfo

func (a *Auth) ValidateUserInfo(ctx context.Context, v UserInfoValidation) error

ValidateUserInfo runs Options.ValidateUserInfo for code that creates users or links identities itself. It returns nil when the option is unset or admits the identity, and otherwise a 403 *APIError.

func (*Auth) VerifyEmail

func (a *Auth) VerifyEmail(ctx context.Context, raw string) error

VerifyEmail validates a plain address verification link, including its original owner. Existing accounts remain verified when a link is revisited.

func (*Auth) VerifyEmailOTP

func (a *Auth) VerifyEmailOTP(ctx context.Context, email, code string) (User, error)

VerifyEmailOTP confirms an address without creating a session.

func (*Auth) VerifyJWT

func (a *Auth) VerifyJWT(ctx context.Context, token string, settings JWTVerifyOptions) (map[string]any, error)

VerifyJWT verifies a compact assertion using the configured algorithms and published keys. The caller receives claims only after signature, identity, audience, expiry and activation checks have succeeded.

func (*Auth) VerifyOAuthPageQuery

func (a *Auth) VerifyOAuthPageQuery(raw string) (url.Values, error)

VerifyOAuthPageQuery extracts verified fields from a host interaction page. Page-local query parameters outside the signed manifest are omitted.

func (*Auth) VerifyOAuthQuery

func (a *Auth) VerifyOAuthQuery(raw string) (url.Values, error)

VerifyOAuthQuery authenticates the exact form submitted to the issuer.

func (*Auth) VerifyOneTimeToken

func (a *Auth) VerifyOneTimeToken(ctx context.Context, token string) (*SessionResult, error)

VerifyOneTimeToken consumes one transfer credential and resolves its original active session.

func (*Auth) VerifyPassword

func (a *Auth) VerifyPassword(ctx context.Context, h http.Header, password string) error

VerifyPassword reauthenticates a signed-in user with their current password.

func (*Auth) VerifyPasswordHash

func (a *Auth) VerifyPasswordHash(ctx context.Context, hash, password string) (bool, error)

VerifyPasswordHash checks password against hash with this instance's Options.PasswordVerify, or the built-in scrypt format.

func (*Auth) VerifyPhoneNumber

VerifyPhoneNumber consumes a verification proof and links, creates or signs in the account.

func (*Auth) VerifySignedSessionToken

func (a *Auth) VerifySignedSessionToken(signed string) string

VerifySignedSessionToken verifies a signed wire credential. Session lookup still checks revocation and expiry in the store.

func (*Auth) ViewBackupCodes

func (a *Auth) ViewBackupCodes(ctx context.Context, userID string) ([]string, error)

ViewBackupCodes reads the remaining codes for a trusted, server-supplied user ID. Applications must authorize the administrator or owner before calling this method.

func (*Auth) WellKnownJSON

func (a *Auth) WellKnownJSON(path string) (json.RawMessage, bool)

WellKnownJSON returns a private copy of a discovery document at its exact path.

func (*Auth) WellKnownPaths

func (a *Auth) WellKnownPaths() []string

WellKnownPaths returns the absolute, escaped paths to mount on the public router. Some protocols locate discovery outside the auth handler's base path.

func (*Auth) WithTrustedSessionFields

func (a *Auth) WithTrustedSessionFields(row StoredSession, overrides map[string]any) (StoredSession, error)

WithTrustedSessionFields prepares an unpersisted row using configured defaults and trusted overrides, including ServerOnly fields. It never writes to storage.

type AuthResult

type AuthResult struct {
	// TrustedDeviceCookie contains the rotated or expired cookie after a credential login.
	TrustedDeviceCookie *http.Cookie    `json:"-"`
	Challenge           *LoginChallenge `json:"-"`
	TwoFactorRedirect   bool            `json:"twoFactorRedirect,omitempty"`
	TwoFactorMethods    []string        `json:"twoFactorMethods,omitempty"`
	Token               string          `json:"token"`
	User                User            `json:"user"`
	// contains filtered or unexported fields
}

AuthResult contains a newly issued token or a pending second-factor challenge.

type BannedUserError

type BannedUserError struct {
	*APIError
	UserID string `json:"-"`
}

BannedUserError refuses a session to a banned account. It unwraps to the BANNED_USER APIError, and UserID names the account so the message can be built once the store call has returned.

func (*BannedUserError) Unwrap

func (e *BannedUserError) Unwrap() error

type ChangePasswordInput

type ChangePasswordInput struct {
	CurrentPassword, NewPassword string
	RevokeOtherSessions          bool
}

type ClientAssertionFunc

type ClientAssertionFunc func(context.Context, TokenRequest) (string, error)

ClientAssertionFunc returns a fresh signed client assertion for one token request; providers.PrivateKeyJWT builds one. It may run concurrently.

type ClientIPOptions

type ClientIPOptions struct {
	// TrustedProxies contains the CIDR ranges of the reverse proxies in front
	// of the application. Address headers are read only from these peers.
	TrustedProxies []netip.Prefix
	// Headers lists the headers that carry the client address, in order, and
	// the first one that yields an address wins. A proxy must overwrite a
	// single-address header such as CF-Connecting-IP, or append the peer to a
	// list such as X-Forwarded-For, whose hops are read from the application
	// toward the client. The default is X-Forwarded-For.
	Headers []string
	// IPv6Subnet is the per-rate-limit prefix length (0–128, default 64).
	IPv6Subnet *int
	// DisableTracking omits the IP address from sessions and disables IP-based limits.
	DisableTracking bool
}

ClientIPOptions controls how the application identifies the connection peer.

type CookieAttributes

type CookieAttributes struct {
	Domain, Path     string
	SameSite         http.SameSite
	Secure, HttpOnly *bool
	Partitioned      bool
}

CookieAttributes overrides cookie attributes. Zero fields keep the default: Path=/, HttpOnly, SameSite=Lax, Secure for an HTTPS base URL and the shared domain with cross-subdomain cookies. A Path must cover the auth base path, and a Domain gets the same checks as CrossSubDomainCookies.

type CookieOptions

type CookieOptions struct {
	// Name replaces the prefixed name, such as "authn.session_token". With
	// Secure cookies the name still gets the __Secure- prefix.
	Name       string
	Attributes CookieAttributes
}

CookieOptions overrides one cookie's name and attributes.

type CredentialSession

type CredentialSession struct {
	Identity SessionResult
	Allows   func(string, string) bool
	// Bind may attach a verified proof for transaction-level revalidation.
	Bind func(context.Context) context.Context
}

type CredentialSessionResolver

type CredentialSessionResolver struct {
	// SelectRequest is an alternative to Matches and Resolve. Return nil for an
	// absent credential. A selected verifier runs only after checking for a
	// conflicting browser credential, so probing must not consume quota.
	SelectRequest func(*http.Request) (CredentialVerifier, error)
	Matches       func(http.Header) bool
	Resolve       func(context.Context, http.Header, RequestMeta, time.Duration) (*CredentialSession, error)
}

CredentialSessionResolver authenticates an application credential for the request. Resolve must validate the credential before returning its principal.

type CrossSubDomainCookiesOptions

type CrossSubDomainCookiesOptions struct {
	Domain string
}

CrossSubDomainCookiesOptions selects the host and descendants that receive shared cookies. Use a parent domain to share cookies with sibling hosts.

type DatabaseHooks

type DatabaseHooks struct {
	User    ModelHooks[UserRecord]
	Session ModelHooks[SessionRecord]
	// Account hooks observe and may cancel credential and linked account
	// writes. They may not change the account.
	Account ModelHooks[LinkedAccount]
	// Verification hooks observe and may cancel the creation and spending of
	// password reset links, account deletion links, browser OAuth flows,
	// magic links, one-time tokens, email and phone codes, two-factor sign-in
	// challenges, delivered codes and remembered browsers, passkey challenges,
	// wallet nonces, enterprise sign-in state, SAML logout bindings and
	// requests, SSO domain tokens and OAuth authorization codes. Spending or
	// removing a record is its delete. A wrong guess counted against a code
	// or a two-factor challenge is its update, which has no before hook: the
	// delete before hooks run before every guess. Renewing a session that
	// carries a SAML logout binding is the binding's update, which runs only
	// its after hooks. They may not change the record.
	Verification ModelHooks[VerificationRecord]
}

DatabaseHooks run your code around the writes that create, update and delete users, sessions, accounts and verification records, for HTTP requests and direct Go calls alike. Plugin hooks run first, in plugin order, then the Options hooks.

A before hook runs just before the write and may edit the row or return ErrSkipWrite to cancel it. An after hook runs once the row is stored. Hooks never run inside a database transaction, so they may use the Auth and the store. When one operation stores several rows, such as a sign-up's user and first session, every before hook runs before anything is written.

New refuses a hook that an enabled feature would bypass, naming the feature. User update and delete hooks are not supported yet.

type DeleteUserInput

type DeleteUserInput struct{ Password, Token, CallbackURL string }

type DeletionTokenFinder

type DeletionTokenFinder interface {
	FindDeletionToken(ctx context.Context, userID, token string, now time.Time) (PasswordResetToken, error)
}

DeletionTokenFinder reads an account deletion token without spending it, for verification delete hooks. A token that is unknown, expired or issued to another user is ErrNotFound.

type DeletionTokenStore

type DeletionTokenStore interface {
	ConsumeDeletionToken(ctx context.Context, userID, token string, now time.Time) error
}

DeletionTokenStore spends an account deletion token before any deletion hook runs. The token is spent whoever presents it, as in the reference, and ErrNotFound reports one that is unknown, expired or issued to another user. A store without it checks the token while deleting.

type DetailedError

type DetailedError struct {
	*APIError
	Details         map[string]any `json:"details"`
	OriginalMessage string         `json:"originalMessage,omitempty"`
}

DetailedError is an APIError whose response also carries a details object, such as the tryAgainIn milliseconds of a rate-limited API key. Clients receive it through errors.As. Numbers in Details are float64, as JSON decoding gives them, whether the error comes from a server call or the Go client.

func (*DetailedError) Unwrap

func (e *DetailedError) Unwrap() error

type DeviceAuthorizationOptions

type DeviceAuthorizationOptions struct {
	ExpiresIn, Interval                  time.Duration
	DeviceCodeLength, UserCodeLength     int
	VerificationURI                      string
	GenerateDeviceCode, GenerateUserCode func(context.Context) (string, error)
	ValidateClient                       func(context.Context, string) (bool, error)
	OnDeviceAuthRequest                  func(ctx context.Context, clientID, scope string) error
}

type DeviceAuthorizationStore

type DeviceAuthorizationStore interface {
	CheckDeviceSchema(context.Context) error
	CreateDeviceGrant(context.Context, DeviceGrant) (created bool, err error)
	ReviewDeviceGrant(context.Context, DeviceReview) (grant DeviceGrant, outcome string, err error)
	// PollDeviceGrant binds the session to the approving owner and consumes an
	// approved grant in the same transaction. Pending polls update lastPolledAt.
	PollDeviceGrant(ctx context.Context, code, clientID string, session StoredSession) (scope, outcome string, err error)
}

type DeviceGrant

type DeviceGrant struct {
	ID, DeviceCode, UserCode, UserID, ClientID, Scope, Status string
	ExpiresAt                                                 time.Time
	Interval                                                  time.Duration
}

DeviceGrant is persisted in the device-authorization schema profile.

type DeviceReview

type DeviceReview struct {
	Code, NormalizedCode, UserID, SessionToken, Action string
	Now                                                time.Time
}

DeviceReview identifies an optional live browser session and a decision. Action is one of review, approve or deny.

type DeviceSessionStore

type DeviceSessionStore interface {
	DeviceSessions(context.Context, []string, time.Time) (map[string]SessionResult, error)
	DeleteDeviceSessions(context.Context, []string) error
	RevokeDeviceSession(ctx context.Context, activeToken, targetToken string, now time.Time) error
}

DeviceSessionStore operates on sessions proven by signed device cookies. The map keys are exact, case-sensitive tokens. RevokeDeviceSession checks the active session in the same transaction as the deletion and returns ErrNotFound if the active login has expired or was revoked.

type DisplayUsernameFields

type DisplayUsernameFields struct {
	DisplayUsername *string `json:"displayUsername"`
}

type DynamicBaseURLOptions

type DynamicBaseURLOptions struct {
	// AllowedHosts lists hosts such as "app.example.com", "*.example.com" or
	// "localhost:3000". A request for another host uses Fallback, or fails
	// with a 500 without one.
	AllowedHosts []string
	// Protocol is "http" or "https" to fix the scheme of every link. The
	// default ("" or "auto") takes a trusted X-Forwarded-Proto, then the
	// connection's TLS, and otherwise uses http for loopback hosts and https
	// for others. Allowed hosts are trusted origins over https, and over
	// http too for loopback hosts, with "auto", or with "http" alone.
	Protocol string
	// Fallback is the public URL for requests to unlisted hosts and for
	// values without a request, such as issuers and direct Go calls.
	Fallback string
	// TrustedProxyHeaders reads X-Forwarded-Host and X-Forwarded-Proto from
	// the peers in ClientIP.TrustedProxies.
	TrustedProxyHeaders bool
}

DynamicBaseURLOptions lists the hosts one instance answers for.

type EmailOTPAction

type EmailOTPAction struct {
	EmailOTPRequest
	// CheckOnly preserves a valid proof. Every other successful action consumes it.
	CheckOnly, AllowSignUp, RevokeSessions bool
	MaxAttempts                            int
	NewUser                                User
	Session                                StoredSession
	PasswordHash                           string
}

type EmailOTPChangeOptions

type EmailOTPChangeOptions struct {
	Enabled            bool
	VerifyCurrentEmail bool
}

EmailOTPChangeOptions controls confirmation at the current and new mailboxes.

type EmailOTPFinder

type EmailOTPFinder interface {
	FindEmailOTP(ctx context.Context, req EmailOTPRequest) (id string, expiresAt time.Time, err error)
}

EmailOTPFinder reads an email code without spending it, for verification update and delete hooks. FindEmailOTP returns the ID and expiry of the newest code stored for req's purpose and address, and for an email change req.Source's account, live or expired, without counting an attempt, taking a lock or joining a LoginPlan. With none it returns ErrNotFound.

A store that implements it honours EmailOTPRequest's ProofID, CurrentProofID, Decided and CurrentDecided in its email code methods. A call that judges a code first refuses, untouched, any code but the bound one. It reports PhoneRemoveProof when it removes the code: a spend, an expired or exhausted code, or a refusal that spends it, such as an unknown account, closed sign-up, invalid registration fields, an address already in use or a changed owner. It reports PhoneCountAttempt when it counts a wrong guess, and PhoneKeepProof for a successful check, a refusal that writes nothing, and every call whose write rolls back. New requires it for verification update and delete hooks with the email OTP plugin.

type EmailOTPMessage

type EmailOTPMessage struct {
	Email, OTP string
	Type       EmailOTPPurpose
}

EmailOTPMessage carries the raw code exclusively for delivery to Email.

type EmailOTPObservation

type EmailOTPObservation struct {
	ID, ExistingToken string
	ExpiresAt         time.Time
	NewSession        *StoredSession
}

EmailOTPObservation carries the single-use continuation for a spent code.

type EmailOTPOptions

type EmailOTPOptions struct {
	// A custom hash is one-way. A custom cipher supplies both reversible transforms.
	Hash, Encrypt, Decrypt      EmailOTPTransform
	ChangeEmail                 EmailOTPChangeOptions
	AutoSignInAfterVerification bool
	Send                        func(context.Context, EmailOTPMessage) error
	GenerateOTP                 func(context.Context, string, EmailOTPPurpose) (string, error)
	Length, AllowedAttempts     int
	ExpiresIn                   time.Duration
	// StoreOTP accepts plain (default), encrypted, or hashed.
	StoreOTP string
	// ResendStrategy accepts rotate (default) or reuse.
	ResendStrategy                   string
	DisableSignUp                    bool
	SendVerificationOnSignUp         bool
	OverrideDefaultEmailVerification bool
	RateLimit                        *RateLimitRule
}

EmailOTPOptions configures code generation, delivery, storage and registration policy.

type EmailOTPPurpose

type EmailOTPPurpose string

EmailOTPPurpose binds a delivered proof to one operation.

const (
	OTPVerifyEmail   EmailOTPPurpose = "email-verification"
	OTPSignIn        EmailOTPPurpose = "sign-in"
	OTPResetPassword EmailOTPPurpose = "forget-password"
	OTPChangeEmail   EmailOTPPurpose = "change-email"
)

type EmailOTPRecord

type EmailOTPRecord struct {
	Stored    string
	Attempts  int
	ExpiresAt time.Time
}

type EmailOTPRegistrationFields

type EmailOTPRegistrationFields func() (UserFieldValues, error)

EmailOTPRegistrationFields prepares configured attributes for a new mailbox owner. It has no storage or delivery side effects and can be retried.

type EmailOTPRegistrationStore

type EmailOTPRegistrationStore interface {
	UseEmailOTPRegistration(context.Context, EmailOTPAction, func(string) (bool, error), EmailOTPRegistrationFields) (User, error)
}

EmailOTPRegistrationStore consumes a valid proof before applying the new-account field policy. A rejected field set spends the proof without creating a user or session. Existing mailbox owners sign in without evaluating registration data.

type EmailOTPRequest

type EmailOTPRequest struct {
	// Observation is present only while completing host-observed verification.
	Observation *EmailOTPObservation
	// Source binds email changes to the authenticated original account.
	Source         *EmailOTPSource
	CurrentMatches func(string) (bool, error)
	// Decided and CurrentDecided, when set, receive what the call did to the
	// codes ProofID and CurrentProofID name: PhoneCountAttempt for a counted
	// wrong guess, PhoneRemoveProof for a code it spent or removed, and
	// PhoneKeepProof otherwise, including whenever its write did not commit.
	Decided, CurrentDecided *PhoneOTPDecision
	MaxAttempts             int
	// ProofID and CurrentProofID bind the call to stored codes, for
	// verification database hooks. SaveEmailOTP stores its new code under
	// ProofID. A call that judges a code judges only the one ProofID names,
	// and CurrentMatches only the current address's code CurrentProofID
	// names; it refuses any other with INVALID_OTP without writing to it.
	// Empty lets the store choose the ID and judge the newest code.
	ProofID, CurrentProofID string
	Email                   string
	Purpose                 EmailOTPPurpose
	Now                     time.Time
}

func (EmailOTPRequest) ObservationAttempt

func (req EmailOTPRequest) ObservationAttempt(owner User) EmailVerificationAttempt

func (EmailOTPRequest) ObservationReceipt

func (req EmailOTPRequest) ObservationReceipt(owner User) EmailVerificationReceipt

type EmailOTPResetHookStore

type EmailOTPResetHookStore interface {
	UseEmailOTPBeforeVerification(context.Context, EmailOTPAction, func(string) (bool, error)) (User, error)
	VerifyAccountEmail(ctx context.Context, userID, email string, now time.Time) error
}

EmailOTPResetHookStore separates a successful credential reset from promotion of the same mailbox. The latter runs only after the host callback succeeds.

type EmailOTPSignInInput

type EmailOTPSignInInput struct {
	AdditionalFields map[string]any `json:"-"`
	Email            string         `json:"email"`
	OTP              string         `json:"otp"`
	Name             string         `json:"name,omitempty"`
	Image            *string        `json:"image,omitempty"`
}

type EmailOTPSource

type EmailOTPSource struct {
	UserID, Email, SessionToken string
}

type EmailOTPStore

type EmailOTPStore interface {
	ReadEmailOTP(context.Context, EmailOTPRequest) (*EmailOTPRecord, error)
	// SaveEmailOTP serializes replacement or reuse for the same purpose and mailbox.
	// Returns an empty code when delivery would disclose account existence.
	SaveEmailOTP(ctx context.Context, req EmailOTPRequest, allowNew bool, expires time.Time, prepare func(previous *EmailOTPRecord) (raw, stored string, attempts int, err error)) (string, error)
	// UseEmailOTP commits the retry count or consumes the proof atomically with the requested mutation.
	UseEmailOTP(ctx context.Context, action EmailOTPAction, matches func(stored string) (bool, error)) (User, error)
}

type EmailOTPTransform

type EmailOTPTransform func(context.Context, string) (string, error)

EmailOTPTransform is an application-provided hash, encrypt or decrypt operation.

type EmailOTPVerificationObserverStore

type EmailOTPVerificationObserverStore interface {
	ConsumeObservedEmailOTP(context.Context, EmailOTPRequest, func(string) (bool, error)) (User, error)
	FinishObservedEmailOTP(context.Context, EmailOTPRequest, User) (User, error)
}

EmailOTPVerificationObserverStore consumes an email verification or change proof before calling the host. Finish must reauthorize the exact original account, address and (for changes) direct session when committing the update.

type EmailVerificationAttempt

type EmailVerificationAttempt struct {
	ProfileUpdatedAtMillis                 *int64
	OwnerID, Email, ProofID, ExistingToken string
	Now, IssuedAt, ExpiresAt               time.Time
	NewSession                             *StoredSession
	// The explicit OTP sign-in route issues a new session even for its current owner.
	AlwaysCreateSession bool
}

EmailVerificationAttempt is a validated ordinary address proof. A nil NewSession requests verification only. ExistingToken, when present, came from a signed browser cookie. ProofID is a digest of the signed proof, never the raw link.

func (EmailVerificationAttempt) MatchesProfileRevision

func (v EmailVerificationAttempt) MatchesProfileRevision(created, updated time.Time) bool

MatchesProfileRevision checks the signed profile revision before issuing a browser session. Older proofs have only a whole-second issue time. Within that second, only an account whose original profile is unchanged qualifies.

func (EmailVerificationAttempt) SessionReceipt

func (v EmailVerificationAttempt) SessionReceipt(owner User) EmailVerificationReceipt

SessionReceipt binds a session handoff to the proved account and exact candidate. A replacement token or a second finish cannot claim the receipt.

type EmailVerificationHook

type EmailVerificationHook func(context.Context, User, *http.Request) error

EmailVerificationHook receives the account before or after the verified mailbox transition. The request is a metadata-only copy for HTTP calls.

type EmailVerificationObserverStore

type EmailVerificationObserverStore interface {
	InspectEmailVerification(context.Context, EmailVerificationAttempt) (User, error)
	CompleteObservedEmailVerification(context.Context, EmailVerificationAttempt) (VerifiedEmailChange, error)
	FinishObservedEmailSession(context.Context, EmailVerificationAttempt, User) (string, error)
	DiscardEmailVerificationReceipt(context.Context, EmailVerificationReceipt) error
}

EmailVerificationObserverStore splits the verified mailbox commit from optional session issuance. Finish rechecks the committed user and current session restrictions after the host's callback, before granting a session.

type EmailVerificationReceipt

type EmailVerificationReceipt struct {
	Identifier, Value string
	ExpiresAt         time.Time
}

EmailVerificationReceipt is an expiring, single-use continuation between an accepted proof and its next storage transaction. Value contains a digest.

func (EmailVerificationReceipt) ValidScope

func (r EmailVerificationReceipt) ValidScope() bool

ValidScope limits cleanup operations to this feature's canonical namespace.

type EmailVerificationSessionStore

type EmailVerificationSessionStore interface {
	CompleteEmailVerification(context.Context, EmailVerificationAttempt) (string, error)
}

EmailVerificationSessionStore atomically verifies the exact owner and address and spends the proof until expiry. A first eligible browser verification may return a direct existing token for that owner or insert the requested session. Replays, active bans, MFA enrollment and restricted sessions return no token. A missing or reassigned owner/address returns ErrNotFound.

type EmptyResponse

type EmptyResponse struct{}

EmptyResponse sends a successful endpoint response with its declared status and no body.

type EndedSession

type EndedSession struct {
	ID, UserID   string
	OAuthClients []string
}

EndedSession is a session a store ended. OAuthClients lists the OAuth clients that held access or refresh tokens on it, revoked or not, when it ended.

type Endpoint

type Endpoint struct {
	// OpenAPI is optional JSON operation metadata for this endpoint. It is copied at registration.
	OpenAPI   json.RawMessage
	RateLimit *RateLimitRule
	// SuccessStatus defaults to 200. A 204 response omits the body.
	SuccessStatus int
	Method        string
	Path          string
	RawBody       bool
	Handler       func(EndpointContext) (any, error)
	// contains filtered or unexported fields
}

Endpoint declares the HTTP operation and its optional IP-based limit.

type EndpointContext

type EndpointContext struct {
	Auth           *Auth
	Request        *http.Request
	Body           map[string]any
	ResponseHeader http.Header
}

EndpointContext gives a plugin access to the host auth instance, incoming request, decoded JSON fields, and headers for its JSON response. Body is nil for GET and raw-body endpoints.

func (EndpointContext) BeginEnterpriseFlow

func (c EndpointContext) BeginEnterpriseFlow(provider, reference, redirectURI string, signup bool) (OAuthFlow, error)

BeginEnterpriseFlow keeps the provider reference and browser return destinations for the callback. The database strategy stores them and puts only a random browser binding in the cookie; OAuthStateCookie seals the whole flow into the cookie instead.

func (EndpointContext) BeginEnterprisePostFlow

func (c EndpointContext) BeginEnterprisePostFlow(provider, reference, redirectURI string, signup bool, lifetime time.Duration) (OAuthFlow, error)

BeginEnterprisePostFlow binds a cross-site form return to an independent Secure, SameSite=None cookie. The ordinary session cookie may be absent on POST. The flow lasts lifetime, or ten minutes when lifetime is zero.

func (EndpointContext) CallbackURL

func (c EndpointContext) CallbackURL(raw string) (string, error)

CallbackURL resolves an application callback like Auth.CallbackURL, also trusting the origins TrustedOriginsForRequest added for this request.

func (EndpointContext) CheckOAuthJWTRevocation

func (c EndpointContext) CheckOAuthJWTRevocation(token string, resourceKnown func(context.Context, string) (bool, error)) (bool, error)

CheckOAuthJWTRevocation recognizes self-contained tokens during revocation. A recognized inactive token needs no further action. A live access token returns unsupported_token_type. Unknown signatures and issuers fall through to stored-token lookup. This check never authorizes access to a resource.

func (EndpointContext) CompleteEnterpriseFlow

func (c EndpointContext) CompleteEnterpriseFlow(f OAuthFlow, method string, p OAuthProfile, tokens OAuthTokens, disableSignup bool, complete OAuthCompletion) (any, error)

CompleteEnterpriseFlow applies the host's account and token policy and emits the usual session cookies only after the store's transaction has committed. method is "sso-oidc" or "sso-saml", as ValidateUserInfo sees it. With The completion receives the profile's prepared user fields in OAuthLoginOptions.ProfileFields. With ValidateUserInfo set, complete must follow the LoginPlan protocol, as the SQL store's sign-in methods do; a completion that commits in the dry run is refused, though a user it already stored stays.

func (EndpointContext) CompleteEnterpriseFlowWith

func (c EndpointContext) CompleteEnterpriseFlowWith(f OAuthFlow, method string, p OAuthProfile, tokens OAuthTokens, o EnterpriseCompletion, complete OAuthCompletion) (any, error)

CompleteEnterpriseFlowWith is CompleteEnterpriseFlow with options.

func (*EndpointContext) ConsumeEnterpriseFlow

func (c *EndpointContext) ConsumeEnterpriseFlow() (OAuthFlow, error)

ConsumeEnterpriseFlow accepts the browser-bound state at the auth host and callback path originally selected during sign-in. The database strategy consumes it once. OAuthStateCookie only expires the cookie, so a captured copy stays valid until it expires: a plugin that needs replay protection relies on the provider's single-use code or keeps its own receipt. A state it cannot use is a 400 INVALID_OAUTH_STATE whose browser error code OAuthStateFailure returns.

func (*EndpointContext) ConsumeEnterprisePostFlow

func (c *EndpointContext) ConsumeEnterprisePostFlow(state string) (OAuthFlow, error)

ConsumeEnterprisePostFlow consumes the RelayState received in the form body.

func (EndpointContext) CreateVerification

func (c EndpointContext) CreateVerification(rec VerificationRecord, save func(context.Context) error) (declined bool, err error)

CreateVerification runs the verification create database hooks around save, for a plugin that keeps a verification record in its own store, such as a passkey challenge or a wallet nonce. rec describes the record save stores. Hooks may log it, so it must never carry the token, nonce, code or challenge that redeems the record, nor the data stored with it: give it the record's kind as Identifier, the stored row's ID or one derived from the stored key by a one-way function, its owner if any, and its expiry, which CreateVerification truncates to the millisecond in UTC.

declined reports that a before hook cancelled the create: save was not called and nothing is stored. An error from save or an after hook is returned as it is; after an after hook's error the record stays stored. The hooks and save run with the request's context, outside any transaction save opens.

func (EndpointContext) DirectBrowserSession

func (c EndpointContext) DirectBrowserSession(token string) bool

DirectBrowserSession reports whether the current browser supplied the signed cookie for this session. Provider logout cannot be initiated with a bearer credential.

func (EndpointContext) EndSession

func (c EndpointContext) EndSession(token string) error

EndSession ends the session with this token, running the session delete hooks as sign-out does, so a store that reports session ends reports it. When the browser's signed session cookie names it, the response also expires the browser's session cookies, and with multi-session its device cookie. A delete hook that skips the write keeps the session; the cookies still expire, as with sign-out.

func (EndpointContext) ErrorPageURL

func (c EndpointContext) ErrorPageURL() (string, error)

ErrorPageURL returns the browser error destination for this request.

func (EndpointContext) GateVerifications

func (c EndpointContext) GateVerifications(call func(context.Context) error) error

GateVerifications runs call, a store call that creates, updates or deletes verification records inside its own transaction, with a VerificationGate in the context it passes, so that the records' database hooks run outside that transaction. call runs again each time the store stops for hooks that have yet to run, at most four times, so it must be able to start over and should take the current time inside. Once call returns nil, the after hooks run for the records the store was allowed to write, in the order it asked, before GateVerifications returns; their error is returned with the records written. Any other error from call or a before hook is returned as it is. With no verification hook set, call runs once and every record is allowed. A plugin that calls it sets Plugin.ValidateVerificationStore, so that New refuses hooks on a store that does not ask the gate.

func (EndpointContext) IssueSession

func (c EndpointContext) IssueSession(userID string, commit func(context.Context, StoredSession) (User, error)) (*SessionResult, error)

IssueSession lets an authentication plugin persist its verified proof and the resulting session in one transaction. The callback must verify the current proof owner and commit the provided session before returning its user.

func (EndpointContext) IssueSessionOr

func (c EndpointContext) IssueSessionOr(skipped error, userID string, commit func(context.Context, StoredSession) (User, error)) (*SessionResult, error)

IssueSessionOr is IssueSession for an endpoint that answers skipped, instead of 401 FAILED_TO_CREATE_SESSION, when a session create before hook skips the session. A nil skipped keeps 401 FAILED_TO_CREATE_SESSION.

func (EndpointContext) IssueSessionWithFields

func (c EndpointContext) IssueSessionWithFields(userID string, fields map[string]any, commit func(context.Context, StoredSession) (User, error)) (*SessionResult, error)

IssueSessionWithFields applies trusted overrides before evaluating defaults, then publishes the session only after commit persists it.

func (EndpointContext) OAuthIDTokenHint

func (c EndpointContext) OAuthIDTokenHint(token string) (map[string]any, error)

OAuthIDTokenHint verifies an ID token this server signed for its OAuth issuer and returns its claims without checking exp or nbf, because RP-Initiated Logout accepts an expired ID token as a hint. Any other token returns nil claims, including one typed as an access or logout token, which another runtime would accept; an error reports a key store failure.

func (EndpointContext) OAuthJWTPayload

func (c EndpointContext) OAuthJWTPayload(token string) (claims map[string]any, recognized bool, err error)

OAuthJWTPayload checks a compact token against this server's configured signing keys, OAuth issuer and time claims. A recognized token with nil claims is inactive. An unrecognized value can still identify a stored opaque token. Callers must check the authorized party, audiences and session before using any claims to authorize a request.

func (EndpointContext) PopulateUserProfile

func (c EndpointContext) PopulateUserProfile(user *User) error

PopulateUserProfile loads the user's public fields from enabled plugins and the host's profile schema for a plugin that has authenticated this account.

func (EndpointContext) PublicURL

func (c EndpointContext) PublicURL() (string, error)

PublicURL returns the auth handler's public URL for this request: BaseURL and BasePath, or with DynamicBaseURL the request's own allowed host.

func (EndpointContext) Redirect

func (c EndpointContext) Redirect(callback string) (any, error)

Redirect returns a 302 endpoint result for a callback allowed by this Auth instance.

func (EndpointContext) RegisteredOAuthRedirect

func (c EndpointContext) RegisteredOAuthRedirect(target string) any

RegisteredOAuthRedirect delivers the result of an authorization request to a URI the issuer has already validated against the client's registration, or to an issuer-controlled page. Fetch clients consume the URL as JSON.

func (EndpointContext) ReissueSessionCookie

func (c EndpointContext) ReissueSessionCookie(session Session)

ReissueSessionCookie emits the current session cookie and its normal response hooks after a plugin changes that session's active context. It preserves the browser's persistence choice and leaves the stored session lifetime intact.

func (EndpointContext) RequestMetadata

func (c EndpointContext) RequestMetadata() *http.Request

RequestMetadata returns a detached copy of the HTTP request headers and URL for a host callback. The body and parsed form data are excluded.

func (EndpointContext) RequestOrigin

func (c EndpointContext) RequestOrigin() (string, bool)

RequestOrigin returns the origin this request reached with DynamicBaseURL: its host, or the host a trusted proxy forwarded, whether or not it is allowed, so compare it with a URL built for the request. It is "" for an invalid host and reports false without DynamicBaseURL.

func (EndpointContext) RequireFreshSession

func (c EndpointContext) RequireFreshSession() (*SessionResult, error)

RequireFreshSession checks the authoritative session and the configured age for a sensitive operation such as enrolling an additional credential.

func (EndpointContext) ResumeOAuthAuthorization

func (c EndpointContext) ResumeOAuthAuthorization(r *http.Request) (any, error)

ResumeOAuthAuthorization re-enters the mounted GET authorization endpoint. Route hooks, disabled paths and rate limits run on the resumed request.

func (EndpointContext) SAMLIDPLogoutCompleted

func (c EndpointContext) SAMLIDPLogoutCompleted(target, token string, revoked bool) any

SAMLIDPLogoutCompleted returns the signed response to the registered IdP.

func (EndpointContext) SAMLLogoutBrowserToken

func (c EndpointContext) SAMLLogoutBrowserToken() string

SAMLLogoutBrowserToken identifies the one signed local browser cookie so an IdP logout can clear it only when its underlying session was revoked.

func (EndpointContext) SAMLLogoutCompleted

func (c EndpointContext) SAMLLogoutCompleted()

SAMLLogoutCompleted expires the logout binding. A new login that happened while the identity provider processed the request keeps its own session.

func (EndpointContext) SAMLLogoutCookie

func (c EndpointContext) SAMLLogoutCookie() string

SAMLLogoutCookie returns the independent browser proof for a logout round trip.

func (EndpointContext) SAMLLogoutStarted

func (c EndpointContext) SAMLLogoutStarted(token, target, binding string, ttl time.Duration) any

SAMLLogoutStarted clears the just-revoked session's browser credentials and redirects to the already validated identity provider's signed protocol URL.

func (EndpointContext) Session

func (c EndpointContext) Session() (*SessionResult, error)

Session returns the caller's current session, or nil when the request is not authenticated.

func (EndpointContext) SignUpAllowed

func (c EndpointContext) SignUpAllowed() bool

SignUpAllowed reports whether a plugin may create a new account.

func (EndpointContext) SpendVerification

func (c EndpointContext) SpendVerification(find func(context.Context) (VerificationRecord, error), spend func(context.Context) error) (refused bool, err error)

SpendVerification runs the verification delete database hooks around spend, for a plugin that spends a verification record in its own store. When delete hooks are set, find first reads the record spend is about to spend, without spending or locking it, and returns ErrNotFound for one that is unknown or expired, which runs no hooks; the before hooks run on the record it returns, built under CreateVerification's rules. spend returns ErrNotFound when it spent nothing.

refused reports a before hook's cancel, which keeps the record and does not call spend; a spend that spent nothing; and a spend of a record find did not see, whose hooks never ran. The plugin answers each as an unusable record. The after hooks run once spend succeeded, before SpendVerification returns; their error is returned with the record spent. With no delete hook set, find is not called. A plugin that calls SpendVerification sets Plugin.ValidateVerificationStore, so that New refuses delete hooks on a store without a finder.

func (EndpointContext) Store

func (c EndpointContext) Store() Store

Store returns the current instance's configured identity store.

func (EndpointContext) TrustedUserFields

func (c EndpointContext) TrustedUserFields() map[string]UserField

TrustedUserFields returns the installed profile schema for in-process readers. It includes configured private attributes and the active plugins' stored columns.

func (EndpointContext) TryReissueSessionCookie

func (c EndpointContext) TryReissueSessionCookie(session Session) error

TryReissueSessionCookie reissues the cookie and reports host configuration errors to plugins that need to fail the response when publication fails.

type EndpointHook

type EndpointHook struct {
	Match func(*HookContext) bool
	Run   func(*HookContext) error
}

EndpointHook runs Run for each endpoint call Match accepts. A nil Match accepts every endpoint.

In a before hook, an error rejects the request: it is written as the response and neither the endpoint nor the after hooks run. A hook may also answer with HookContext.Respond, or edit HookContext.Body and the request's query and headers for the endpoint to read.

In an after hook, HookContext.Result and HookContext.Err hold the outcome so far and may be replaced. A returned APIError or OAuthError replaces the outcome and the remaining after hooks still run.

Any other error, or a panic, ends the call with a 500 response.

type EndpointHooks

type EndpointHooks struct {
	Before []EndpointHook
	After  []EndpointHook
}

EndpointHooks run around the mounted HTTP endpoints. Options hooks run first, then each plugin's hooks in plugin order.

Before hooks run once a request has passed disabled paths, rate limits, the origin check and body decoding, and before the endpoint reads its input. After hooks run once the endpoint returns, before the response is written. Neither runs for direct Go method calls such as Auth.SignUpEmail.

type EnterpriseCompletion

type EnterpriseCompletion struct {
	// DisableSignUp refuses to create an account.
	DisableSignUp bool
	// OverrideUserInfo writes the provider's email, name, image and writable
	// AdditionalFields to a returning owner, as OverrideUserInfoOnSignIn
	// does for a social provider. A changed email is stored unverified
	// unless the profile verifies it.
	OverrideUserInfo bool
	// Committed runs once the store has committed and the after hooks have
	// run, before any cookie is set and outside any transaction; created
	// reports whether the sign-in created the user. An error removes the
	// session the sign-in would have issued and is returned; a user it
	// created stays.
	Committed func(ctx context.Context, u User, created bool) error
}

EnterpriseCompletion adjusts how CompleteEnterpriseFlowWith signs a provider identity in.

type ErrorContext

type ErrorContext struct {
	Request *http.Request
	User    *User
}

ErrorContext contains the request and the user authenticated for this request, when available. Reporting an error never triggers authentication.

type ErrorPageOptions

type ErrorPageOptions struct {
	Background        string // page and grid fade; white / oklch(0.15 0 0)
	Foreground        string // headings, code and text; oklch(0.271 0 0) / oklch(0.98 0 0)
	Primary           string // Go Home button; black / white
	PrimaryForeground string // Go Home label; white / black
	MutedForeground   string // CODE label and description; oklch(0.545 0 0) / oklch(0.65 0 0)
	Border            string // card, divider, code box, button and grid lines; oklch(0.89 0 0) / oklch(0.27 0 0)
	Destructive       string // title border unless TitleBorder is set; oklch(0.55 0.15 25.723) / oklch(0.65 0.15 25.723)
	TitleBorder       string // border around the ERROR title; defaults to Destructive
	TitleColor        string // ERROR title; defaults to Foreground
	GridColor         string // background grid lines; defaults to Border
	CardBackground    string // card; defaults to Background
	CornerBorder      string // card corner marks; #404040 / #a0a0a0

	RadiusSm string // sets --radius (0.625rem), which no element uses: the page has square corners
	TextSm   string // code and description; 0.875rem
	Text2xl  string // "Something went wrong"; 1.5rem
	Text4xl  string // sets --text-4xl (2.25rem), which no element uses
	Text6xl  string // ERROR title; 3rem

	// The page loads no web fonts, so name fonts installed on the viewer's
	// device.
	FontFamily     string // page text; -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif
	MonoFontFamily string // the error code; monospace

	DisableTitleBorder       bool // draws the title border transparent and keeps its width
	DisableCornerDecorations bool // removes the card's four corner marks
	DisableBackgroundGrid    bool // removes the background grid and its fade
}

ErrorPageOptions styles the error page at <mount>/error. Each string is one CSS value, such as "#0070f3", "oklch(0.55 0.15 25.7)", "1.25rem" or "'Inter', sans-serif"; an empty string keeps the default shown as light / dark. A color replaces its light and its dark default alike. Screens up to 640px wide use fixed smaller TextSm, Text2xl and Text6xl sizes. New refuses a value with a control character, a CSS comment or its end, url(), any of ; { } [ ] < > \ or an unbalanced parenthesis or quote.

type FactorBackupOptions

type FactorBackupOptions struct {
	Amount, Length   int
	Generate         func(context.Context) ([]string, error)
	Store            string
	Encrypt, Decrypt EmailOTPTransform
	// AllowPasswordless, when set, replaces TwoFactorOptions.AllowPasswordless
	// for /two-factor/generate-backup-codes.
	AllowPasswordless *bool
}

type FactorChange

type FactorChange struct {
	SaveDelivery                        *FactorDelivery
	RemoveDelivery                      bool
	CreateTrustedGrant                  string
	TrustedUntil                        time.Time
	SaveRecord                          *FactorRecord
	DeleteRecord                        bool
	Enabled                             *bool
	CreateChallenge                     string
	ChallengeExpires                    time.Time
	IncrementAttempts, ConsumeChallenge bool
	UsedTOTPStep                        *int64
	UsedTOTPPeriod                      time.Duration
	RevokeSessions                      bool
	Session                             *StoredSession
	// ChallengeID and TrustedGrantID are the row IDs to store CreateChallenge
	// and CreateTrustedGrant under, which the verification hooks name them
	// by. A store that is not a FactorRecordReporter may choose its own.
	ChallengeID, TrustedGrantID string
}

FactorChange is committed under the same owner lock used to load FactorState. SaveRecord and DeleteRecord are mutually exclusive. Sessions are persisted only after the corresponding authentication decision succeeds.

type FactorDelivery

type FactorDelivery struct {
	ID                   string
	Pending              bool // a code an earlier release staged while its sender ran; a guess at it is refused
	Stored               string
	Attempts             int
	CreatedAt, ExpiresAt time.Time
}

FactorDelivery is a single-use out-of-band code scoped to an existing login challenge or session.

type FactorLockoutOptions

type FactorLockoutOptions struct {
	Disabled          bool
	MaxFailedAttempts int
	Duration          time.Duration
}

type FactorOTPMessage

type FactorOTPMessage struct {
	User User
	Code string
}

type FactorOTPOptions

type FactorOTPOptions struct {
	Send                    func(context.Context, FactorOTPMessage) error
	Period                  time.Duration
	Digits, AllowedAttempts int
	Store                   string
	Hash, Encrypt, Decrypt  EmailOTPTransform
}

type FactorRecord

type FactorRecord struct {
	ID, Secret, BackupCodes string
	Verified                bool
	Failures                int
	LockedUntil             *time.Time
}

type FactorRecordReporter

type FactorRecordReporter interface{ ReportsFactorRecords() }

FactorRecordReporter is a TwoFactorStore whose WithTwoFactor the verification hooks can follow. New requires it for any verification database hook with the two-factor plugin. Its WithTwoFactor:

  • fills FactorState's ChallengeID and ChallengeExpires from the challenge row it locked, and TrustedGrantID and TrustedGrantExpires from the remembered browser's row it locked;
  • stores CreateChallenge under FactorChange.ChallengeID, CreateTrustedGrant under FactorChange.TrustedGrantID and a delivered code under its ID;
  • calls decide once per transaction attempt, again only after rolling an attempt back, and commits exactly the change the last call returned, or nothing;
  • writes nothing and returns decide's error when decide fails;
  • for an empty change writes nothing but the normalizations any call makes, such as lifting an expired ban.

type FactorState

type FactorState struct {
	Delivery       *FactorDelivery
	TrustedGrant   string
	User           User
	Enabled        bool
	Record         *FactorRecord
	PasswordHash   string
	Attempts       int
	LastTOTPStep   int64
	LastTOTPPeriod time.Duration
	Session        *Session
	// ChallengeID and ChallengeExpires are the stored row ID and expiry of
	// the challenge the subject names, and TrustedGrantID and
	// TrustedGrantExpires those of TrustedGrant. A FactorRecordReporter fills
	// them for the verification hooks.
	ChallengeID, TrustedGrantID           string
	ChallengeExpires, TrustedGrantExpires time.Time
}

type FactorSubject

type FactorSubject struct {
	ApplicationKeyID, ApplicationOperation string
	ReadDelivery                           bool
	TrustedGrant                           string
	UserID, SessionToken, Challenge        string
	Now                                    time.Time
}

FactorSubject identifies an existing signed-in session, a login after a password check, or a short-lived first-factor challenge.

type FactorTOTPOptions

type FactorTOTPOptions struct {
	Digits   int
	Period   time.Duration
	Disabled bool
	// AllowPasswordless, when set, replaces TwoFactorOptions.AllowPasswordless
	// for /two-factor/get-totp-uri.
	AllowPasswordless *bool
}

FactorTOTPOptions configures authenticator apps. Digits accepts 6 or 8. Period must be a whole number of seconds.

type HTMLError

type HTMLError struct {
	Status int
	Page   HTMLPage
}

HTMLError answers an endpoint call with a trusted page and an error status, such as the page a browser shows for a refused request. Headers the endpoint set, such as a Content-Security-Policy, are kept.

func (*HTMLError) Error

func (e *HTMLError) Error() string

type HTMLPage

type HTMLPage string

HTMLPage is trusted HTML returned by an endpoint. Escape all dynamic text before constructing it.

type HTTPDescription

type HTTPDescription struct {
	SessionFields              map[string]HTTPSessionField
	UserFields                 map[string]HTTPField
	OrganizationRoleFields     map[string]HTTPField
	RoleFieldsRequiredOnCreate bool
	// RequiredUserInputs lists writable fields that have no registration default.
	RequiredUserInputs                      []string
	EmailOTPRegistration, PhoneRegistration bool
	// OAuthLoginContinuation indicates that a host can resume a signed issuer login.
	OAuthLoginContinuation bool
	// OAuthSelectionContinuation indicates that organization and team selection can resume a signed post-login request.
	OAuthSelectionContinuation bool

	ServerURL, SessionCookie string
	// OAuthProxyStateCookie binds a preview return to the initiating browser.
	OAuthProxyStateCookie string
	// SSOStateCookie is the browser binding cookie for installed enterprise OIDC callbacks.
	SSOStateCookie string
	// SAMLStateCookie is set when the SP-initiated SAML form handler is installed.
	SAMLStateCookie          string
	SAMLLogoutCookie         string
	Routes                   []HTTPRoute
	Providers                []string
	MinPassword, MaxPassword int
	DisplayUsername          bool
	CustomSession            bool
}

HTTPDescription describes public settings used to document the handler.

type HTTPField

type HTTPField struct {
	Type                         SessionFieldType
	Required, Writable, Returned bool
}

HTTPField describes the public input and output permissions of a configured scalar.

type HTTPRoute

type HTTPRoute struct {
	Method, Path, Plugin string
	RawBody              bool
	// SuccessStatus is the endpoint's declared success status. Zero defaults to 200.
	SuccessStatus int
	OpenAPI       json.RawMessage
}

HTTPRoute describes one registered, enabled HTTP operation. OpenAPI is a private copy for the caller.

type HTTPSessionField

type HTTPSessionField = HTTPField

HTTPSessionField describes a configured session field.

type HookContext

type HookContext struct {
	EndpointContext
	// Path is the endpoint's route relative to the auth mount, with
	// ":name" segments, such as "/sign-up/email" or "/reset-password/:token".
	Path string
	// Params holds the values of the ":name" segments in Path.
	Params map[string]string
	// Result and Err hold the endpoint's outcome in after hooks.
	Result any
	Err    error
	// contains filtered or unexported fields
}

HookContext describes one HTTP endpoint call to its hooks. Request is a copy of the incoming request, so header and query edits never reach the host's request. ResponseHeader collects the response headers and cookies.

func (*HookContext) AddOAuthServerContext

func (c *HookContext) AddOAuthServerContext(values map[string]any)

AddOAuthServerContext keeps values with the browser OAuth flow this request starts. OAuthState.ServerContext returns them to the start's after hooks and to the callback. Call it from a before hook on /sign-in/social, /link-social or /oauth-popup/start. The browser cannot read, set or change the values, but the database strategy stores them as plain JSON, so keep secrets out. Calls merge, and a later value for a key replaces an earlier one. The values are kept as JSON, so numbers come back as float64, and a value JSON cannot encode fails the start. A request that starts no browser flow, such as an ID-token sign-in, keeps none, and a call after the start has built its flow has no effect.

func (*HookContext) DeleteSessionCookie

func (c *HookContext) DeleteSessionCookie()

DeleteSessionCookie removes the session cookies and the Set-Auth-Token header this response would issue, including the multi-session cookie for the new session, and expires the browser's session cookies instead. Call it when an after hook turns a successful sign-in into an error.

func (*HookContext) NewSession

func (c *HookContext) NewSession() (*SessionResult, error)

NewSession returns the session whose cookie this response issues, or nil when it issues none. Use it in after hooks, for example to notify a new user after sign-up. It is nil after a failed sign-in, after a sign-out and after DeleteSessionCookie.

func (*HookContext) Respond

func (c *HookContext) Respond(result any)

Respond answers the request with result from a before hook. The remaining before hooks, the endpoint and the after hooks do not run. A result is written as JSON unless it is a Redirect, HTMLPage, XMLDocument or EmptyResponse.

func (*HookContext) SetCookie

func (c *HookContext) SetCookie(cookie *http.Cookie)

SetCookie adds a Set-Cookie header to the response. Auth.Cookie and Auth.SignedCookie build cookies with the instance's prefix and attributes.

type JWTKeyLookup

type JWTKeyLookup interface {
	JWTKeyByID(context.Context, string) (StoredJWTKey, error)
}

type JWTOptions

type JWTOptions struct {
	Algorithm            string
	AdditionalAlgorithms []string
	// RSAModulusBits sets the size of RS256 and PS256 keys. It defaults to
	// 2048 and must be an even number of at least 2048 bits.
	RSAModulusBits               int
	Issuer, Audience, JWKSPath   string
	Expiration, RotationInterval time.Duration
	GracePeriod                  *time.Duration
	DisableHeader                bool
	DefinePayload                func(context.Context, SessionResult) (map[string]any, error)
	// KeyStore keeps signing keys outside the main Store, for example in
	// memory, in a secret manager or in a per-tenant keyring chosen from the
	// context. It may also implement JWTKeyLookup to support
	// JWTSignOptions.KeyID. When nil, the main Store must implement JWTStore.
	// The store, not the plugin, picks the active key and serializes its
	// generation, so concurrent requests share one new key.
	KeyStore JWTStore
	// DisablePrivateKeyEncryption stores new private keys as plain JWK JSON
	// and reads stored keys that way. Encryption is on by default. Turn it
	// off only when another system must read the keys and protects the
	// table itself. An instance cannot sign with a key stored the other way.
	DisablePrivateKeyEncryption bool
	// RemoteJWKSURL publishes the key set at another address, such as a CDN.
	// The JWKSPath route is not served, and discovery advertises this URL.
	// Algorithm must be set. Keep every active and recently retired public
	// key there, for example by copying Auth.PublicJWKS. Verification here
	// still reads the key store and never fetches the URL.
	RemoteJWKSURL string
	// Sign replaces local signing for every token the plugin issues, for
	// example by calling a remote key service. It receives the finished
	// claims and returns a compact JWS whose header carries the signer's alg
	// and kid plus the requested typ and cty. It requires RemoteJWKSURL.
	// Verification here reads public keys from KeyStore or the main Store,
	// so supply a KeyStore that lists the signer's public keys when this
	// server must verify its own tokens.
	Sign func(ctx context.Context, request JWTSigningRequest) (string, error)
	// SessionCookieCache signs SessionCacheJWT browser snapshots with the
	// plugin's primary key instead of the application secret, so services
	// holding the published key set can verify them. It requires
	// Options.SessionCookieCache with the jwt strategy and DisableHeader, and
	// cannot be combined with Sign.
	SessionCookieCache bool
}

type JWTSignOptions

type JWTSignOptions struct {
	Claims                         map[string]any
	Algorithm, KeyID               string
	Type, ContentType              string
	Issuer                         string
	Audience                       []string
	IssuedAt, ExpiresAt, NotBefore time.Time
}

JWTSignOptions applies to a single trusted server-side issuance. Reserved claims come from the typed fields. Algorithm and KeyID may select a provisioned key.

type JWTSigningRequest

type JWTSigningRequest struct {
	// Claims is the complete claim set; the server has set sub, iss, aud,
	// iat and exp, and nbf when requested.
	Claims map[string]any
	// Type and ContentType are the typ and cty header values the caller
	// requires, such as at+jwt for OAuth access tokens; merge them into the
	// signed header.
	Type, ContentType string
	// Algorithm and KeyID are the algorithm or key the caller pinned, such
	// as an OAuth resource's key; both are empty for ordinary tokens, which
	// use JWTOptions.Algorithm.
	Algorithm, KeyID string
}

JWTSigningRequest is what JWTOptions.Sign receives for each token.

type JWTStore

type JWTStore interface {
	// ActiveJWTKey returns the newest key for algorithm that has not expired
	// at now. With none, it calls generate, saves the new key and returns
	// it. Serialize generation so concurrent callers share one key.
	ActiveJWTKey(ctx context.Context, algorithm string, now time.Time, generate func() (StoredJWTKey, error)) (StoredJWTKey, error)
	// PublicJWTKeys returns the keys with no expiry or an expiry after
	// cutoff, oldest first.
	PublicJWTKeys(ctx context.Context, cutoff time.Time) ([]PublicJWTKey, error)
}

JWTStore keeps the plugin's signing keys. Both methods receive the request context, or the context a host passes to SignJWT and VerifyJWT, so an implementation can choose a tenant's keyring from values a host middleware adds.

type JWTVerifyOptions

type JWTVerifyOptions struct {
	Issuer, Audience, Subject string
}

JWTVerifyOptions allows a service to require its own issuer, audience and subject.

type LinkedAccount

type LinkedAccount struct {
	AdditionalFields map[string]any `json:"-"`
	ID               string         `json:"id"`
	AccountID        string         `json:"accountId"`
	ProviderID       string         `json:"providerId"`
	UserID           string         `json:"userId"`
	Scopes           []string       `json:"scopes"`
	CreatedAt        time.Time      `json:"createdAt"`
	UpdatedAt        time.Time      `json:"updatedAt"`
}

LinkedAccount contains fields safe to return to the signed-in account owner.

func (LinkedAccount) MarshalJSON

func (a LinkedAccount) MarshalJSON() ([]byte, error)

func (*LinkedAccount) UnmarshalJSON

func (a *LinkedAccount) UnmarshalJSON(data []byte) error

type LinkedAccountStore

type LinkedAccountStore interface {
	ListUserAccounts(ctx context.Context, userID string) ([]LinkedAccount, error)
	UnlinkAccount(ctx context.Context, userID, recordID string, allowLast bool) error
}

type LocalizedError

type LocalizedError struct {
	*APIError
	OriginalMessage string `json:"originalMessage"`
}

LocalizedError exposes the translated APIError and its original server message.

func (*LocalizedError) Unwrap

func (e *LocalizedError) Unwrap() error

type LoginChallenge

type LoginChallenge struct{ Identifier string }

type LoginPlan

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

LoginPlan lets the create before hooks run, outside any transaction, for a sign-in whose store decides inside its transaction whether to create the user or which session to issue: social sign-in, One Tap, SSO, magic links, email codes, phone verification, two-factor sign-in and verification, device grants and the sign-in after an email link.

The Auth runs the store method twice with a plan in its context. The dry run records the user and session the sign-in would insert and rolls back. The hooks then run on those rows, and the approved run inserts them with the hooks' edits. If the approved run would write different rows, because another request changed the data in between, it fails with ErrLoginPlanChanged and the Auth starts again.

A store supports plans by implementing LoginPlanner and, in those sign-in methods, calling Attempt when it begins each transaction attempt, including retries, PlanUser just before inserting a new user, PlanIdentity in a provider sign-in just before signing in or linking an existing user, PlanSession just before inserting the session and Commit just before committing, returning their errors. The methods do nothing on a nil plan, so a store can call them with LoginPlanFrom(ctx) unconditionally.

A sign-in's store may also ask the request's VerificationGate about records it writes with the session, such as a SAML logout binding. The Auth gives the dry run no gate, so only the approved run, or the only run, asks.

func LoginPlanFrom

func LoginPlanFrom(ctx context.Context) *LoginPlan

LoginPlanFrom returns the plan of the sign-in ctx belongs to, or nil.

func (*LoginPlan) Attempt

func (p *LoginPlan) Attempt()

Attempt is called when a store begins a transaction attempt. It forgets what an earlier, rolled-back attempt of the same run recorded or wrote.

func (*LoginPlan) Commit

func (p *LoginPlan) Commit() error

Commit is called just before a store commits. It returns ErrLoginPlanned for a dry run, and ErrLoginPlanChanged when an approved run did not write what the dry run planned.

func (*LoginPlan) PlanIdentity

func (p *LoginPlan) PlanIdentity(userID string, linked bool) error

PlanIdentity is called in a provider sign-in just before a store signs in the user who already owns the identity (linked) or links the identity to an existing user (not linked). A dry run records it; an approved run checks that it did not change.

func (*LoginPlan) PlanSession

func (p *LoginPlan) PlanSession(s *StoredSession) error

PlanSession is called with the session a store is about to insert. A dry run records it; an approved run replaces it with the hooks' version.

func (*LoginPlan) PlanUser

func (p *LoginPlan) PlanUser(u *User) error

PlanUser is called with the user a store is about to insert. A dry run records it; an approved run applies the hooks' edits to it.

type LoginPlanner

type LoginPlanner interface{ PlansLogins() }

LoginPlanner is implemented by a store whose sign-in methods support plans.

type MagicLinkChallenge

type MagicLinkChallenge struct {
	Key, Email, Name     string
	CreatedAt, ExpiresAt time.Time
}

MagicLinkChallenge describes a mailbox proof under a purpose-specific key. Key is the stored token representation, after MagicLinkOptions.HashTokens or HashToken and then Options.StoreVerificationIdentifier, without its database namespace.

type MagicLinkFinder

type MagicLinkFinder interface {
	FindMagicLink(ctx context.Context, key string, now time.Time) (MagicLinkChallenge, error)
}

MagicLinkFinder reads a magic link without spending it, for verification delete hooks. It returns the Key, Email, Name and ExpiresAt of the newest well-formed link stored under key that is live at now. It judges only the stored row: a link whose address another account now owns is still found, and CompleteMagicLink refuses it. Anything else is ErrNotFound.

type MagicLinkMessage

type MagicLinkMessage struct {
	Email, URL, Token string
	Metadata          map[string]any
	// Request contains independent HTTP request metadata for the delivery callback.
	// It is excluded when serializing the message for an email queue.
	Request *http.Request `json:"-"`
}

MagicLinkMessage contains private authentication material for delivery to Email.

type MagicLinkOptions

type MagicLinkOptions struct {
	Send          func(context.Context, MagicLinkMessage) error
	ExpiresIn     time.Duration
	DisableSignUp bool
	HashTokens    bool
	HashToken     func(context.Context, string) (string, error)
	GenerateToken func(ctx context.Context, email string) (string, error)
	RateLimit     *RateLimitRule
}

MagicLinkOptions configures delivery, token storage and registration.

type MagicLinkStore

type MagicLinkStore interface {
	SaveMagicLink(context.Context, MagicLinkChallenge) error
	CompleteMagicLink(ctx context.Context, key, newUserID string, session StoredSession, allowSignUp bool) (User, bool, error)
}

MagicLinkStore consumes a mailbox proof atomically with user promotion and session creation. CompleteMagicLink and CompleteMagicLinkWithUserFields spend the link when they sign in, and when they refuse a new address with ErrMagicLinkSignUpDisabled or with the error of defaults.Columns. Verification delete hooks rely on this.

type MagicLinkUserFieldStore

type MagicLinkUserFieldStore interface {
	CompleteMagicLinkWithUserFields(ctx context.Context, key, newUserID string, session StoredSession, defaults RegistrationUserFields) (User, bool, error)
}

MagicLinkUserFieldStore writes registration defaults in the transaction that proves mailbox ownership and creates the first session. Existing users keep their stored values, including when a required field has no default.

type MailLink struct {
	User                 User
	URL, Token, NewEmail string
	// Request is a copy of the HTTP request that caused the mail, without its
	// body, or nil for a direct Go call.
	Request *http.Request `json:"-"`
}

MailLink is delivered to the application's configured mail sender. Its Token and URL are sensitive and should only be delivered to User.Email.

type MailSender

type MailSender func(context.Context, MailLink) error

type MappedAccountFields

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

MappedAccountFields carries the declared provider values for an account write.

func (*MappedAccountFields) Get

func (f *MappedAccountFields) Get(name string) (any, bool)

Get returns a value by logical name. A present nil explicitly clears a nullable field.

type Middleware

type Middleware struct {
	Path string
	Run  func(*HookContext) error
}

Middleware runs Run before the endpoint hooks for each HTTP request whose mount-relative path matches Path. It can reject, rewrite or answer a request like a before hook.

Path is an exact path such as "/sign-in/email", or a pattern where "*" or ":name" matches one segment and a final "**" matches any remaining segments, such as "/organization/**" or "/**". Broader patterns run first: "/**", then "/x/**", then "/x/*", then exact paths, in plugin order within each.

type MissingPermissionsError

type MissingPermissionsError struct {
	*APIError
	MissingPermissions []string `json:"missingPermissions"`
	OriginalMessage    string   `json:"originalMessage,omitempty"`
}

MissingPermissionsError identifies individual grants that an actor may not delegate.

func (*MissingPermissionsError) Unwrap

func (e *MissingPermissionsError) Unwrap() error

type ModelHooks

type ModelHooks[T any] struct {
	Create, Update, Delete OperationHooks[T]
}

ModelHooks holds the hooks for one model's create, update and delete writes.

type MultiSessionOptions

type MultiSessionOptions struct {
	// MaximumSessions defaults to five. An explicit zero disables remembering new accounts.
	MaximumSessions *int
}

type OAuthAccountFieldInput

type OAuthAccountFieldInput struct {
	// ExchangedToken exposes TokenType and provider-specific Extra values for code exchanges.
	ExchangedToken                        *oauth2.Token
	Profile                               OAuthProfile
	Tokens                                OAuthTokens
	ClientAccessToken, ClientRefreshToken string
}

OAuthAccountFieldInput distinguishes credentials verified by the provider flow from optional, unverified strings submitted by a native client.

type OAuthCompletion

OAuthCompletion persists the verified identity, account credentials and session in one transaction after checking any plugin-owned identity binding.

type OAuthError

type OAuthError struct {
	Status      int    `json:"-"`
	Code        string `json:"error,omitempty"`
	Description string `json:"error_description"`
}

OAuthError represents the public error fields of an OAuth protocol response.

func (*OAuthError) Error

func (e *OAuthError) Error() string

type OAuthFlow

type OAuthFlow struct {
	// IssuerLoginQuery is the host's verified login request, retained in the
	// flow store, or sealed in the state cookie, while the browser visits the
	// identity provider.
	IssuerLoginQuery string `json:",omitempty"`
	// ProxyOrigin is the preview that owns the browser state and final session.
	ProxyOrigin string `json:",omitempty"`
	// AdditionalData is the additionalData object the browser sent when it
	// started the flow, without the reserved names.
	AdditionalData map[string]any `json:",omitempty"`
	// ServerContext holds the values hooks added with
	// HookContext.AddOAuthServerContext when the flow started. A custom
	// OAuthFlowStore must keep it.
	ServerContext                                     map[string]any `json:",omitempty"`
	ProviderReference                                 string         `json:",omitempty"`
	RedirectURI                                       string         `json:",omitempty"`
	RequestSignUp                                     bool           `json:",omitempty"`
	AnonymousSessionProof                             string         `json:",omitempty"`
	State, Binding, Provider, Verifier, Nonce         string
	CallbackURL, ErrorCallbackURL, NewUserCallbackURL string
	LinkUserID                                        string
	ExpiresAt                                         time.Time
}

OAuthFlow is the temporary state of a browser authorization. Binding ties a request to the initiating browser, provider and existing session.

type OAuthFlowFinder

type OAuthFlowFinder interface {
	FindOAuthFlow(ctx context.Context, state, binding string, now time.Time) (OAuthFlow, error)
}

OAuthFlowFinder reads a browser OAuth flow without spending it, for verification delete hooks. A flow that is unknown, expired or bound to another browser is ErrNotFound.

type OAuthFlowStore

type OAuthFlowStore interface {
	SaveOAuthFlow(context.Context, OAuthFlow, time.Time) error
	ConsumeOAuthFlow(ctx context.Context, state, binding string, now time.Time) (OAuthFlow, error)
}

OAuthFlowStore keeps shared, single-use browser flow state. It is needed unless OAuthStateStrategy is OAuthStateCookie.

type OAuthIdentityStore

type OAuthIdentityStore interface {
	CompleteOAuth(ctx context.Context, provider, subject string, tokens OAuthTokens, candidate User, session StoredSession, options OAuthLoginOptions) (User, bool, error)
}

OAuthIdentityStore completes a provider sign-in atomically. CompleteOAuth returns the actual account owner and whether it created a user.

type OAuthLinkRefreshStore

type OAuthLinkRefreshStore interface {
	RefreshOwnedOAuthLink(context.Context, string, string, OAuthTokens, User, StoredSession, OAuthLoginOptions) (User, bool, error)
}

OAuthLinkRefreshStore updates an already-owned provider identity after verifying the live owner session and the provider subject in the same transaction. Implement it to permit redundant mobile link requests when linking is disabled.

type OAuthLoginContinuation

type OAuthLoginContinuation func(Session) (*http.Request, error)

OAuthLoginContinuation builds the issuer authorization request after a login endpoint actually issues a new browser session. The host installs its signed cookie and dispatches the request through the normal authorization route.

type OAuthLoginOptions

type OAuthLoginOptions struct {
	// AccountFields holds validated provider values keyed by logical account field name.
	AccountFields *MappedAccountFields
	DisableSignUp bool
	// RequireEmailVerification commits an unverified identity without issuing a session.
	RequireEmailVerification bool
	// DisableAccountUpdateOnSignIn skips the existing account row update during
	// login. Adapters still claim single-use grants and apply the session policy.
	DisableAccountUpdateOnSignIn bool
	// DisableImplicitLinking also takes precedence over directory-based trust in custom stores.
	DisableImplicitLinking bool
	OneTapNonce            string
	OneTapExpires          time.Time
	AllowVerifiedEmailLink bool
	// TrustedProvider accepts a provider email that is not verified for a
	// link. An implicit link still needs a verified local email.
	TrustedProvider bool
	// AllowDifferentEmails lets an explicit link attach to LinkUserID
	// whatever the provider email.
	AllowDifferentEmails bool
	// UpdateUserInfoOnLink writes the candidate's non-empty Name, non-nil
	// Image and the LinkUserFields values to the owner when this call links
	// the identity to an existing user or refreshes it through an explicit
	// link. The email and its verification never change.
	UpdateUserInfoOnLink bool
	// LinkUserFields prepares the user fields to copy. Call it only when the
	// copy applies. It reports false when the profile fails validation, and
	// then nothing is copied.
	LinkUserFields               func() (UserFieldValues, bool)
	LinkUserID, LinkSessionToken string
	IDTokenValidUntil            time.Time
	// IDTokenHash binds single-use grants independently of randomized storage encryption.
	IDTokenHash [32]byte
	// SelectUserID signs the identity in to this existing user, as an SSO
	// resolver chose, instead of matching by email or creating a user. The
	// store refuses with ErrNotFound when the user is gone and with
	// ErrOAuthAccountAlreadyLinked when another user owns the identity.
	SelectUserID string
	// UpdateSelectedProfile copies the provider's name, image and email to
	// the selected user; a changed email takes the provider's verification.
	// Without it the selected user's profile is kept.
	UpdateSelectedProfile bool
	// RequireActiveSCIMUser, with SelectUserID, makes the store confirm under
	// the selected user's lock that this SCIM User is still active, links to
	// SelectUserID and belongs to an active connection, or refuse with
	// ErrSCIMUserInactive.
	RequireActiveSCIMUser *SCIMUserReference
	// ProfileFields carries an enterprise sign-in's prepared user fields to
	// its store: Create for a new user and, when set, Update for a returning
	// owner whose profile the provider overrides.
	ProfileFields *OAuthProfileFields
}

OAuthLoginOptions binds an explicit link to a live session or a direct ID-token grant to the verified token's expiry.

type OAuthPopupOptions

type OAuthPopupOptions struct {
	// MessageType defaults to plainauth:oauth-popup. A custom value is namespace:event.
	MessageType string
}

OAuthPopupOptions configures the fixed browser message protocol for a deployment.

type OAuthProfile

type OAuthProfile struct {
	// AdditionalFields is an explicit mapping from the authenticated provider
	// profile to writable user attributes at registration and optional sign-in updates.
	AdditionalFields map[string]any `json:"-"`

	// Data is the authenticated provider profile returned by the account-info endpoint.
	Data                 any `json:"-"`
	Subject, Email, Name string
	Image                *string
	EmailVerified        bool
}

OAuthProfile identifies a person by their stable provider subject.

type OAuthProfileFields

type OAuthProfileFields struct {
	Create OAuthRegistrationFields
	Update func() (UserFieldValues, error)
}

OAuthProfileFields supplies the creation defaults or the mapped update for the selected owner. Call only the matching resolver inside the transaction.

type OAuthProfileSyncStore

type OAuthProfileSyncStore interface {
	CompleteOAuthProfile(ctx context.Context, provider, subject string, tokens OAuthTokens, candidate User, session StoredSession, options OAuthLoginOptions, fields OAuthProfileFields) (User, bool, error)
}

OAuthProfileSyncStore applies an authenticated provider profile to the owner selected by the ordinary sign-in and linking rules. Profile, credentials, token consumption and session creation must commit together.

type OAuthProvider

type OAuthProvider struct {
	// GetAccountFields maps a verified social grant to declared writable account attributes.
	GetAccountFields func(context.Context, OAuthAccountFieldInput) (map[string]any, error)
	// Config holds the client credentials, endpoints and scopes. RedirectURL
	// defaults to the callback route, BaseURL+BasePath+"/callback/"+id. Set it
	// to an absolute URL that forwards to that route to use another address.
	Config oauth2.Config
	// EndSessionEndpoint is the provider's registered OIDC logout endpoint.
	EndSessionEndpoint string
	// PostLogoutRedirectURI is the default application return URI after provider logout.
	PostLogoutRedirectURI string
	DisableProviderLogout bool
	// CustomizeAuthorization adapts fixed provider-specific parameter names.
	CustomizeAuthorization func(*url.URL)
	// ExchangeCode handles providers with a nonstandard token endpoint protocol.
	ExchangeCode func(context.Context, oauth2.Config, string, string, url.Values) (*oauth2.Token, error)
	Resolve      func(context.Context, *oauth2.Token, string) (OAuthProfile, error)
	// UserInfoURL is the profile endpoint of a provider without Resolve. An ID
	// token in the token response that names a subject and an email is used
	// instead, without checking its signature; use providers.OpenIDConnect
	// for verified ID tokens. Otherwise the endpoint is called with the
	// access token, and the profile's id, email, email_verified, name and
	// picture are read.
	UserInfoURL   string
	VerifyIDToken func(ctx context.Context, raw, nonce string) (OAuthProfile, time.Time, error)
	// VerifyAccessToken signs in with a provider access token that the client
	// sends as idToken.token and repeats as idToken.accessToken on social
	// sign-in and linking. A token that is not a three-part JWS goes here
	// instead of VerifyIDToken and needs no nonce. It must confirm the token
	// was issued to this application before returning the profile it names:
	// a profile endpoint alone also accepts tokens issued to other
	// applications. A token that signs in is refused for an hour.
	VerifyAccessToken func(ctx context.Context, token string) (OAuthProfile, error)
	// DisableIDTokenSignIn closes the direct ID-token and access-token grants
	// on social sign-in and linking. Browser code exchanges and the One Tap
	// plugin verify independently.
	DisableIDTokenSignIn bool
	// Refresh overrides the standard OAuth 2.0 refresh request.
	Refresh func(context.Context, oauth2.Config, string) (*oauth2.Token, error)
	// Name is a display label; it defaults to the SocialProviders key.
	Name string
	// AccessType is sent as access_type on the authorization URL, such as
	// "offline"; AuthorizationParams and a call's additionalParams override
	// it.
	AccessType string
	// DefaultAccessTokenLifetime is the access token lifetime assumed when a
	// token response has no expires_in; zero assumes none.
	DefaultAccessTokenLifetime time.Duration
	// TokenParams are extra form fields for the standard code exchange, such
	// as audience or resource, with one value each. New refuses the grant
	// and client authentication fields, and ExchangeCode, which replaces
	// that request.
	TokenParams url.Values
	// TokenHeaders are added to the code exchange and refresh requests sent
	// to the token endpoint, and never replace a header the request already
	// has. New refuses them together with ExchangeCode or Refresh.
	TokenHeaders http.Header
	// RefreshParams returns extra form fields for one refresh-token request;
	// nil adds none. It runs before the account is locked. Header values come
	// from the caller, so check anything derived from them against the
	// owner's entitlements. New refuses it together with Refresh.
	RefreshParams func(context.Context, OAuthRefreshRequest) (url.Values, error)
	// TokenEndpointAuth chooses how the code exchange and refresh
	// authenticate the client. It cannot be combined with ExchangeCode or
	// Refresh, which replace these requests.
	TokenEndpointAuth      TokenEndpointAuth
	DisableRefresh         bool
	HTTPClient             *http.Client
	AllowVerifiedEmailLink bool
	// AllowIdPInitiated restarts a callback that brings a code and no state,
	// as a provider-initiated sign-in such as Clever's does: the code is
	// discarded and a fresh authorization starts, returning to BaseURL. It
	// cannot link an account or request sign-up.
	AllowIdPInitiated bool
	// DisableSignUp prevents this provider from creating new accounts.
	DisableSignUp bool
	// DisableImplicitSignUp requires requestSignUp for new browser and direct ID-token accounts.
	DisableImplicitSignUp bool
	// OverrideUserInfoOnSignIn updates the local profile from this provider on
	// successful sign-in. Explicit account linking preserves the owner's profile.
	OverrideUserInfoOnSignIn bool
	// RequireEmailVerification withholds a session until the local mailbox is verified.
	RequireEmailVerification bool
	// GoogleHostedDomain restricts the verified Google Workspace hd claim. Use * for any Workspace.
	GoogleHostedDomain  string
	AuthorizationParams url.Values
	DisablePKCE         bool
	OmitNonce           bool
	FormPostName        bool
}

OAuthProvider configures an authorization-code provider. Resolve must obtain identity from an authenticated provider endpoint or a verified ID token. For OpenID Connect it must verify the supplied nonce.

type OAuthProxyOptions

type OAuthProxyOptions struct {
	ProductionURL, CurrentURL string
	MaxAge                    time.Duration
	Secret                    string
	Secrets                   []VersionedSecret
	// contains filtered or unexported fields
}

OAuthProxyOptions configures an OAuth callback shared by production and previews. ProductionURL is the origin registered with the identity provider. CurrentURL overrides current-origin discovery. MaxAge controls the lifetime of a returned profile. All participating hosts must have the same dedicated secret or key ring.

type OAuthRefreshRequest

type OAuthRefreshRequest struct {
	// Header is a copy of the triggering request's headers, or nil for a
	// trusted server call.
	Header http.Header
	// UserID owns the account and AccountID is its local record ID.
	UserID, AccountID string
}

OAuthRefreshRequest describes the request that triggered a provider token refresh.

type OAuthRegistrationFields

type OAuthRegistrationFields func() (UserFieldValues, error)

OAuthRegistrationFields resolves configured columns for a new account.

type OAuthRegistrationStore

type OAuthRegistrationStore interface {
	CompleteOAuthRegistration(ctx context.Context, provider, subject string, tokens OAuthTokens, candidate User, session StoredSession, options OAuthLoginOptions, fields OAuthRegistrationFields) (User, bool, error)
}

OAuthRegistrationStore resolves fields only for new users after selecting the exact identity. It commits them with the user, account link and initial session.

type OAuthState

type OAuthState struct {
	// CallbackURL, NewUserURL and ErrorURL are the destinations the start
	// chose. During the callback of a redirect flow, ErrorURL is where a
	// failure returns: the error page when the start chose none. A popup flow
	// posts its failures to the opener instead.
	CallbackURL, NewUserURL, ErrorURL string
	// LinkUserID is the user /link-social links the provider account to, or
	// "" for a sign-in.
	LinkUserID string
	// RequestSignUp reports whether the start asked to create an account.
	RequestSignUp bool
	// ExpiresAt is when the flow expires, ten minutes after it started.
	ExpiresAt time.Time
	// AdditionalData is the browser's additionalData: untrusted input.
	// Numbers decode as float64.
	AdditionalData map[string]any
	// ServerContext holds what hooks added with
	// HookContext.AddOAuthServerContext before the flow started. The browser
	// cannot read or set it. Numbers decode as float64.
	ServerContext map[string]any
}

OAuthState is what hooks may read of a browser OAuth flow. It leaves out the flow's secrets: its PKCE verifier, nonce, URL state and browser binding. Do not modify its maps.

func OAuthStateFrom

func OAuthStateFrom(ctx context.Context) (OAuthState, bool)

OAuthStateFrom returns the state of the browser OAuth flow ctx belongs to. A start has it once it has built its flow, so after hooks on /sign-in/social, /link-social and /oauth-popup/start read it through c.Request.Context(). A callback has it once it has read the flow: in the provider's ExchangeCode, Resolve and GetAccountFields, in ValidateUserInfo and database hooks, and through c.Request.Context() in after hooks on /callback/:id and, behind the OAuth proxy, on the preview's /callback/:id/oauth-proxy. It reports false in before hooks, in the verification delete hooks that spend the flow, for an ID-token sign-in, which starts no flow, and on the OAuth proxy's production instance, which relays the provider's answer without completing a sign-in.

type OAuthStateStrategy

type OAuthStateStrategy string

OAuthStateStrategy chooses where a browser OAuth flow waits for the provider's callback.

const (
	// OAuthStateDatabase stores the flow through OAuthFlowStore, and the
	// callback consumes it once. It is the default.
	OAuthStateDatabase OAuthStateStrategy = "database"
	// OAuthStateCookie seals the whole flow into the state cookie, so no flow
	// is stored. The cookie is expired on use, but a copy captured before
	// then stays valid until it expires, so a replay is stopped by the
	// provider's single-use authorization code rather than by the store.
	OAuthStateCookie OAuthStateStrategy = "cookie"
)

type OAuthStore

type OAuthStore interface {
	OAuthFlowStore
	OAuthIdentityStore
}

OAuthStore supports shared, single-use flow state and atomic identity login.

type OAuthTokens

type OAuthTokens struct {
	AccessToken, RefreshToken, IDToken, Scope string
	ExpiresAt, RefreshExpiresAt               time.Time
}

OAuthTokens are the provider-issued account credentials kept by the adapter.

type OAuthVerifiedEmailStore

type OAuthVerifiedEmailStore interface {
	CompleteOAuthVerifiedEmail(ctx context.Context, provider, subject string, tokens OAuthTokens, candidate User, session StoredSession, options OAuthLoginOptions, fields OAuthProfileFields) (User, bool, error)
}

OAuthVerifiedEmailStore checks the locked owner's email before inserting a session. For an unverified owner it commits the user, provider credential and single-use proof, then returns the owner, creation flag and ErrOAuthEmailUnverified. A nil fields.Update preserves the existing profile on returning sign-ins.

type OneTapOptions

type OneTapOptions struct {
	ClientID      string
	DisableSignUp bool
}

OneTapOptions configures Google's first-party browser credential prompt.

type OneTimeTokenFinder

type OneTimeTokenFinder interface {
	FindOneTimeToken(ctx context.Context, key string, now time.Time) (userID string, expiresAt time.Time, err error)
}

OneTimeTokenFinder reads a one-time token without spending it, for verification delete hooks. For the newest token stored under key that is live at now, it returns the user whose session it transfers, empty when that is unknown, and the token's expiry. It judges only the stored token: one whose session has ended, or whose key another live token shares, is still found, and ConsumeOneTimeToken refuses it. A token unknown or expired at now is ErrNotFound.

type OneTimeTokenOptions

type OneTimeTokenOptions struct {
	ExpiresIn time.Duration
	// ExpireImmediately explicitly selects a zero lifetime. An unset ExpiresIn uses three minutes.
	ExpireImmediately                                                    bool
	DisableClientRequest, DisableSetSessionCookie, SetHeaderOnNewSession bool
	HashTokens                                                           bool
	HashToken                                                            func(context.Context, string) (string, error)
	GenerateToken                                                        func(context.Context, SessionResult) (string, error)
	// GenerateTokenWithRequest receives request metadata for HTTP issuance and nil for native calls.
	GenerateTokenWithRequest func(context.Context, SessionResult, *http.Request) (string, error)
}

type OneTimeTokenStore

type OneTimeTokenStore interface {
	SaveOneTimeToken(ctx context.Context, key string, source Session, now, expires time.Time) error
	ConsumeOneTimeToken(ctx context.Context, key string, now time.Time) (SessionResult, error)
}

OneTimeTokenStore keeps single-use session transfers. ConsumeOneTimeToken spends the token also when it returns ErrTransferSessionMissing or ErrTransferSessionExpired. Verification delete hooks rely on this. key is the token as stored, after OneTimeTokenOptions.HashTokens or HashToken and then Options.StoreVerificationIdentifier.

type OperationHooks

type OperationHooks[T any] struct {
	Before func(ctx context.Context, row *T, c *HookContext) error
	After  func(ctx context.Context, row T, c *HookContext) error
}

OperationHooks run before and after one kind of write. c describes the HTTP endpoint call that caused the write, or is nil for a direct Go call and for work handed to Options.BackgroundTasks.

Before may change the fields the write stores; changing any other field fails the write with a 500. It returns ErrSkipWrite to cancel the write, an APIError to answer with that error, or another error to fail it.

After receives the stored row. An error from After is returned to the caller; the row stays stored, but a session that has not been delivered yet is removed.

type Options

type Options struct {
	UserAdditionalFields    map[string]UserField
	SessionAdditionalFields map[string]SessionField
	AccountAdditionalFields map[string]AccountField
	AccountFieldRules       map[string]AccountFieldRule

	// AppName names the application where users see it, such as the issuer
	// in authenticator apps. It defaults to "Auth".
	AppName string
	// Logger receives diagnostics for this instance. A nil logger uses slog.Default().
	Logger *slog.Logger
	// BackgroundTasks runs work that need not finish before the response,
	// such as mail after sign-up, a social sign-in or an organization
	// invitation. It is called with a ready task and must run it once,
	// usually on another goroutine: pass a sync.WaitGroup's Go method and
	// Wait after http.Server.Shutdown. The task keeps the request's context
	// values but not its cancellation or deadline, and logs its own failures.
	// When nil, that work finishes before the response.
	BackgroundTasks func(task func())
	// SkipTrailingSlashes serves a path with trailing slashes, such as
	// /sign-in/email/, as the path without them.
	SkipTrailingSlashes bool
	// DisableCSRFCheck turns off the Origin, Referer and Fetch Metadata checks
	// on requests that change state. This exposes cookie-authenticated
	// endpoints to cross-site request forgery.
	DisableCSRFCheck bool
	// DisableOriginCheck accepts any callbackURL, redirectTo and other redirect
	// target instead of only trusted origins and relative paths, which allows
	// open redirects. Request origins are still checked unless DisableCSRFCheck
	// is also set.
	DisableOriginCheck bool
	// Cookies overrides the name and attributes of individual cookies, by
	// their base name such as "session_token", "session_data" or
	// "dont_remember".
	Cookies map[string]CookieOptions
	// DefaultCookieAttributes applies to every cookie before the per-cookie
	// overrides.
	DefaultCookieAttributes CookieAttributes
	// Hooks run before and after each mounted HTTP endpoint.
	Hooks EndpointHooks
	// DatabaseHooks run before and after user, session, account and
	// verification writes, after the plugins' database hooks.
	DatabaseHooks DatabaseHooks
	// OnAPIError observes an HTTP endpoint error before its response is written.
	// It runs synchronously and may use the request's context for cancellation.
	OnAPIError func(ErrorContext, error) error
	// SessionCookieCache enables authenticated snapshots for public browser session reads.
	SessionCookieCache *SessionCookieCacheOptions
	// Store persists identities and sessions. Configure one store per auth instance.
	Store Store
	// BaseURL is the public HTTP(S) address. BasePath defaults to /api/auth.
	BaseURL  string
	BasePath string
	// DynamicBaseURL serves several public hosts from one instance in place
	// of a fixed BaseURL. Each request's host chooses the origin of its links
	// and callbacks.
	DynamicBaseURL *DynamicBaseURLOptions
	// DisabledPaths hides exact HTTP paths relative to this instance’s mount.
	DisabledPaths []string
	// TrustedOrigins allows exact HTTP(S) origins, hostname or port wildcard
	// patterns, and custom-scheme URLs such as myapp:// or
	// chrome-extension://ID, for browser requests and callbacks.
	TrustedOrigins []string
	// TrustedOriginsForRequest adds origins for one HTTP request, such as
	// tenant domains loaded from a database, to TrustedOrigins,
	// AUTH_TRUSTED_ORIGINS and the BaseURL origin. It takes the same patterns
	// as TrustedOrigins and receives a copy of the request without its body,
	// once per request to the handler. A returned *APIError with a 4xx or
	// 5xx status is sent as the response; another error or an invalid
	// pattern fails the request with a 500. Calls made outside the handler,
	// BindOneTapNonce and the public CallbackURL use the static origins only.
	// Its exact entries also let OIDC discovery, OIDC endpoint checks and
	// requests to the identity provider reach that origin for the request,
	// through the configured HTTP client and without the public-address check.
	TrustedOriginsForRequest func(*http.Request) ([]string, error)
	CookiePrefix             string
	// CrossSubDomainCookies selects the Domain attribute for shared browser cookies.
	// A nil value keeps cookies host-only. An empty Domain uses the BaseURL hostname.
	CrossSubDomainCookies *CrossSubDomainCookiesOptions
	// UseSecureCookies overrides the HTTPS-based default for session cookies.
	UseSecureCookies *bool
	// ErrorRedirectURL receives browser errors in place of the page at
	// <mount>/error, with error and error_description added to its query.
	// It takes precedence over ErrorPage.
	ErrorRedirectURL string
	// ErrorPage serves a styled page at <mount>/error in place of the plain
	// one, also with AUTH_ENV=production, where the plain page redirects to
	// "/". An empty value uses the built-in light and dark theme. New keeps
	// its own copy.
	ErrorPage *ErrorPageOptions
	// Secret signs credentials. Secrets configures ordered keys for rotation.
	Secret  string
	Secrets []VersionedSecret

	// PasswordHash derives a stored credential from a plaintext password.
	// PasswordVerify checks a stored credential against a plaintext password.
	// A nil callback uses the built-in scrypt implementation for that operation.
	PasswordHash   func(ctx context.Context, password string) (string, error)
	PasswordVerify func(ctx context.Context, encoded, password string) (bool, error)

	// OnExistingUserSignUp receives the persisted mailbox owner on a protected duplicate
	// sign-up. An HTTP call supplies request metadata; direct calls supply nil.
	OnExistingUserSignUp func(context.Context, User, *http.Request) error
	// ValidateUserInfo decides which identities the instance admits. It runs
	// before a user is created, before a provider identity is linked to an
	// existing user, and before an existing user signs in again through a
	// provider, outside any store transaction and before the user create
	// database hooks. Return nil to admit, or an *APIError to refuse with its
	// Code and Message. Every refusal answers 403; browser flows redirect to
	// their error URL with error and error_description. Any other error, an
	// APIError without a Code, or a panic refuses with validation_failed.
	ValidateUserInfo func(context.Context, UserInfoValidation) error
	// CustomSyntheticUser shapes the user an HTTP sign-up returns for an email
	// that already exists, when RequireEmailVerification or DisableAutoSignIn
	// hides that the email is taken. The returned values replace the
	// generated ones for the fields a real sign-up returns, in that field's
	// format; other keys are dropped and a value that does not fit keeps the
	// generated one. Built-in plugin fields are already filled in.
	CustomSyntheticUser func(SyntheticUser) map[string]any

	EmailAndPassword         bool
	MinPasswordLength        int
	MaxPasswordLength        int
	DisableSignUp            bool
	DisableAutoSignIn        bool
	RequireEmailVerification bool
	// AutoSignInAfterVerification issues or reuses a browser session on first email-link verification.
	AutoSignInAfterVerification   bool
	SendVerificationOnSignUp      *bool
	SendVerificationOnSignIn      bool
	SendVerificationEmail         MailSender
	EmailVerificationTokenTTL     time.Duration
	SendResetPassword             MailSender
	PasswordResetTokenTTL         time.Duration
	RevokeSessionsOnPasswordReset bool
	// BeforeEmailVerification and AfterEmailVerification run outside store locks.
	BeforeEmailVerification, AfterEmailVerification EmailVerificationHook

	// OnPasswordReset runs after a recovery proof is consumed, the password is
	// replaced, and any requested session revocation commits. Mounted endpoints
	// pass the HTTP request. Direct Go calls pass nil.
	OnPasswordReset func(context.Context, User, *http.Request) error

	// Account lifecycle operations with destructive or identity-changing effects are opt-in.
	DeleteUserEnabled bool
	// BeforeDeleteUser runs before a user is deleted, with a body-free copy of
	// the request or nil for a Go call. An error cancels the deletion and is
	// returned to the caller.
	BeforeDeleteUser func(context.Context, User, *http.Request) error
	// AfterDeleteUser runs once a user is deleted. Its error is returned to
	// the caller; the user stays deleted.
	AfterDeleteUser                func(context.Context, User, *http.Request) error
	SendDeleteAccountVerification  MailSender
	DeleteTokenTTL                 time.Duration
	ChangeEmailEnabled             bool
	UpdateEmailWithoutVerification bool
	SendChangeEmailConfirmation    MailSender
	// DisableAccountLinking prevents attaching another provider to an existing account.
	DisableAccountLinking bool
	// DisableImplicitAccountLinking requires an authenticated owner to link an additional provider.
	DisableImplicitAccountLinking bool
	// TrustedProviders lists social provider IDs whose identities may link
	// without a verified email from the provider, such as "google", which also
	// covers One Tap. A sign-in can then attach to an existing user with the
	// same verified email, and a signed-in user can link the identity. Trust
	// never marks an email as verified, and it raises the risk of account
	// takeover: list only providers that own their users' email addresses.
	TrustedProviders []string
	// TrustedProvidersForRequest chooses the trusted providers per request,
	// for example per tenant, instead of TrustedProviders. It receives a copy
	// of the request without its body whenever a social sign-in or link
	// reaches the store and when an SSO provider is registered. An error
	// fails that request.
	TrustedProvidersForRequest func(*http.Request) ([]string, error)
	// AllowDifferentEmails lets a signed-in user link a provider identity
	// whose email differs from their own. The user's email does not change,
	// and whoever controls that provider account can then sign in as them.
	AllowDifferentEmails bool
	// UpdateUserInfoOnLink copies the provider's name, image and writable
	// UserAdditionalFields onto the user whenever an identity is linked,
	// through /link-social or by a sign-in that links by email. An empty name
	// or missing image keeps the stored value, and the email and its
	// verification never change.
	UpdateUserInfoOnLink bool
	// DisableAccountUpdateOnSignIn preserves credentials on existing provider
	// accounts during sign-in. New links and explicit reauthorization still store grants.
	DisableAccountUpdateOnSignIn bool
	AllowUnlinkingAll            bool

	SessionTTL time.Duration
	// SecondaryStorage keeps a copy of each live session in a shared store,
	// such as Redis, so session reads can skip the database. Sessions also
	// stay in the database, which StoreSessionInDatabase must confirm, and
	// the store must implement SessionMirrorStore.
	SecondaryStorage       SecondaryStorage
	StoreSessionInDatabase bool
	// PreserveSessionInDatabase keeps the row of an ended session, for
	// example after a sign-out or revocation, instead of deleting it. The row
	// is marked ended and is never served again. Deleting the user still
	// removes its rows. It requires SecondaryStorage.
	PreserveSessionInDatabase bool
	// DisableVerificationCleanup stops the store from deleting expired
	// verification records, such as OAuth states, passkey challenges, reset
	// links and email codes, as it writes new ones. Expired records are still refused.
	// A write that reuses an expired record's key still replaces that one
	// record. Prune the table yourself. Every Auth sharing a store must use
	// the same setting.
	DisableVerificationCleanup bool
	// StoreVerificationIdentifier sets how the identifiers of password reset
	// links, account deletion links, magic links and one-time tokens are
	// stored. The zero value stores each token after its purpose prefix, such
	// as "reset-password:", as it is. Hashing keeps the prefix and stores a
	// hash of the whole identifier in place of the token, so the verification
	// table holds nothing that redeems a link. Links issued before the setting
	// changes can no longer be redeemed. Every Auth sharing a store must use
	// the same settings. Email and phone codes, OAuth and SAML states and other
	// verification records are not affected.
	StoreVerificationIdentifier VerificationIdentifierStorage
	// StoreVerificationIdentifierOverrides replaces StoreVerificationIdentifier
	// for the purpose whose prefix a key starts, such as "reset-password" or
	// "magic-link:"; an empty VerificationIdentifierStorage keeps that purpose
	// plain. New refuses a key that is not the start of "reset-password:",
	// "delete-account-", "magic-link:" or "one-time-token:", and two keys for
	// one purpose.
	StoreVerificationIdentifierOverrides map[string]VerificationIdentifierStorage
	// FreshAge is how recent a session must be for sensitive account changes,
	// such as deleting the user or unlinking an account. It defaults to one
	// day; a negative value turns the check off.
	FreshAge time.Duration
	// SessionUpdateAge controls sliding expiration. A pointer to zero refreshes on every eligible read.
	SessionUpdateAge      *time.Duration
	DisableSessionRefresh bool
	DeferSessionRefresh   bool

	// RateLimit overrides the environment's enablement policy. By default
	// counters live on the auth instance, or in SecondaryStorage when one is
	// set. RateLimitStorage chooses where they live instead;
	// NewMemoryRateLimitStorage keeps them on the instance.
	RateLimit        *bool
	RateLimitStorage RateLimitStorage
	// RateLimitDefault applies to routes without their own rule. RateLimitRules
	// overrides built-in and plugin rules by exact route or trailing /* prefix.
	// A nil map value exempts the matching route from the limiter.
	// RateLimitRuleFuncs does the same with a function that chooses the limit
	// for each request. The closest entry in either map wins, and a route may
	// appear in only one of them.
	RateLimitDefault   *RateLimitRule
	RateLimitRules     map[string]*RateLimitRule
	RateLimitRuleFuncs map[string]RateLimitRuleFunc
	ClientIP           ClientIPOptions
	SocialProviders    map[string]OAuthProvider
	// OAuthStateStrategy keeps a browser OAuth flow in the store
	// (OAuthStateDatabase, the default) or sealed in the state cookie
	// (OAuthStateCookie), which needs no OAuthFlowStore.
	OAuthStateStrategy OAuthStateStrategy
	// StoreAccountCookie records in an account_data cookie which linked
	// provider account a browser signed in with, so get-access-token,
	// refresh-token and account-info accept useAccountCookie. The cookie
	// names the account; its tokens stay in the store. It lasts as long as
	// SessionCookieCache.MaxAge, or five minutes, and an HTTP token refresh
	// it selected, or a session cache re-issued for its user, renews it.
	StoreAccountCookie bool
	// EncryptOAuthTokens encrypts linked provider credentials at rest using the configured key ring.
	EncryptOAuthTokens bool
	Plugins            []Plugin
}

Options configures one isolated authentication instance.

type PasswordResetToken

type PasswordResetToken struct {
	ID, Token, UserID, Email string
	CreatedAt, ExpiresAt     time.Time
}

PasswordResetToken records a reset or deletion link and its owner in verification storage. Token is the link's token as stored: the token itself, or its hash under Options.StoreVerificationIdentifier. The token arguments of FindPasswordResetToken, FinishPasswordReset and the deletion token methods are in the same form.

type PhoneAccountAction

type PhoneAccountAction struct {
	Use                   PhoneOTPUse
	SourceID, SourceToken string
	// Create is optional and is used only if no account exists for this number.
	Create                              *User
	Session                             *StoredSession
	PasswordHash                        string
	RevokeSessions, RequireVerification bool
}

type PhoneAccountResult

type PhoneAccountResult struct {
	User         User
	NeedsFactor  bool
	ExpectedHash string
}

type PhoneAccountStore

type PhoneAccountStore interface {
	PhoneNumberStore
	ReadPhoneOTP(ctx context.Context, number string, purpose PhoneOTPPurpose) (*PhoneOTPRecord, error)
	ReadPhoneNumber(ctx context.Context, userID string) (*PhoneNumberFields, error)
	PhoneCredential(ctx context.Context, number string) (User, string, error)
	SavePhoneReset(ctx context.Context, r PhoneOTPRecord, requireVerified bool) (bool, error)
	// A successful password reset returns the account selected by the consumed proof.
	ApplyPhoneOTP(context.Context, PhoneAccountAction) (PhoneAccountResult, error)
	ClearPhoneProfile(ctx context.Context, userID, token string, p ProfileUpdate, now time.Time) error
}

type PhoneLoginBinding

type PhoneLoginBinding struct {
	Number          string
	RequireVerified bool
}

PhoneLoginBinding identifies the number a password or pending factor login proved.

func PhoneLoginFrom

func PhoneLoginFrom(ctx context.Context) (PhoneLoginBinding, bool)

PhoneLoginFrom is used by stores to recheck a phone login under the session owner's lock.

func (PhoneLoginBinding) Matches

type PhoneNumberFields

type PhoneNumberFields struct {
	PhoneNumber         *string `json:"phoneNumber"`
	PhoneNumberVerified *bool   `json:"phoneNumberVerified"`
}

PhoneNumberFields is present when the phone plugin is enabled. A user may have no number.

type PhoneNumberOptions

type PhoneNumberOptions struct {
	SendPasswordResetOTP func(context.Context, PhoneOTPMessage) error
	VerifyOTP            func(context.Context, PhoneOTPMessage) (bool, error)
	OnVerification       func(context.Context, string, User) error
	SignUpOnVerification *PhoneSignUpOptions
	RequireVerification  bool
	SendOTP              func(context.Context, PhoneOTPMessage) error
	Validate             func(context.Context, string) (bool, error)
	OTPLength            int
	// AllowedAttempts defaults to three. An explicit zero rejects every proof.
	AllowedAttempts *int
	ExpiresIn       time.Duration
}

type PhoneNumberStore

type PhoneNumberStore interface {
	CheckPhoneNumberSchema(context.Context) error
	SavePhoneOTP(context.Context, PhoneOTPRecord) error
	ConsumePhoneOTP(context.Context, PhoneOTPUse) error
}

type PhoneOTPDecision

type PhoneOTPDecision uint8

PhoneOTPDecision is what a store commits to a phone or email code it judges: it keeps the code, counts a wrong guess, or removes the code.

const (
	PhoneKeepProof PhoneOTPDecision = iota
	PhoneCountAttempt
	PhoneRemoveProof
)

type PhoneOTPMessage

type PhoneOTPMessage struct {
	PhoneNumber, Code string
	Purpose           PhoneOTPPurpose
}

type PhoneOTPPurpose

type PhoneOTPPurpose string

PhoneOTPPurpose keeps number verification and password recovery proofs separate.

const (
	PhoneVerify        PhoneOTPPurpose = "verification"
	PhonePasswordReset PhoneOTPPurpose = "password-reset"
)

type PhoneOTPRecord

type PhoneOTPRecord struct {
	BoundOwner            string
	OwnerBound            bool
	ID, PhoneNumber, Code string
	Purpose               PhoneOTPPurpose
	Attempts              int
	CreatedAt, ExpiresAt  time.Time
}

PhoneOTPRecord is one generation of a proof. The value is for server-side delivery only.

type PhoneOTPReporter

type PhoneOTPReporter interface{ ReportsPhoneOTPDecisions() }

PhoneOTPReporter is a PhoneAccountStore whose ConsumePhoneOTP, ApplyPhoneOTP and ApplyPhoneRegistration report through PhoneOTPUse.Decided what they committed to the code. They report PhoneRemoveProof when they spend or remove it, including by a refusal after a spend, such as an owner mismatch, a held number or a missing session, and PhoneKeepProof for a code another use bound, a missing code, and every rolled-back write. New requires it for verification update and delete hooks with the phone number plugin.

type PhoneOTPUse

type PhoneOTPUse struct {
	// ProviderProof binds the use to one stored code: the one an external
	// verifier answered for, or the one verification hooks saw.
	ProviderProof    string
	ProviderAccepted bool
	// Decided, when set, receives what the call did to the code
	// ProviderProof names: Check's decision once its write committed, and
	// PhoneKeepProof otherwise.
	Decided           *PhoneOTPDecision
	PhoneNumber, Code string
	Purpose           PhoneOTPPurpose
	AllowedAttempts   int
	Now               time.Time
}

func (PhoneOTPUse) Check

Check returns the storage mutation to commit together with any verification result.

type PhoneRegistrationStore

type PhoneRegistrationStore interface {
	ApplyPhoneRegistration(context.Context, PhoneAccountAction, RegistrationUserFields) (PhoneAccountResult, error)
}

PhoneRegistrationStore consumes the exact verified proof and atomically writes the user, profile columns and optional first session. A profile validation error spends the proof only on first registration. Existing users and links keep their fields.

type PhoneSignUpOptions

type PhoneSignUpOptions struct{ GetTempEmail, GetTempName func(string) string }

type PhoneVerificationInput

type PhoneVerificationInput struct {
	// AdditionalFields supplies writable user attributes only for first-time registration.
	AdditionalFields  map[string]any `json:"-"`
	PhoneNumber       string         `json:"phoneNumber"`
	Code              string         `json:"code"`
	UpdatePhoneNumber bool           `json:"updatePhoneNumber,omitempty"`
	DisableSession    bool           `json:"disableSession,omitempty"`
}

func (PhoneVerificationInput) CheckProfileKeys

func (in PhoneVerificationInput) CheckProfileKeys() error

CheckProfileKeys prevents a caller from placing a verification input in the profile.

type PhoneVerificationResult

type PhoneVerificationResult struct {
	Factor *AuthResult `json:"-"`
	Status bool        `json:"status"`
	Token  *string     `json:"token"`
	User   User        `json:"user"`
}

type Plugin

type Plugin struct {
	// StoredUserFields declares this plugin's scalar user columns for trusted
	// profile readers. The keys are logical names and may map to different columns.
	StoredUserFields map[string]UserField
	// OrganizationRoleFields describes fields on the installed role endpoints.
	OrganizationRoleFields map[string]SessionField

	// TranslateError returns a localized HTTP error message for the request.
	// An empty result preserves the original error response.
	TranslateError     func(ErrorContext, APIError) string
	CredentialSessions *CredentialSessionResolver

	// Hooks run before and after each mounted HTTP endpoint, after the
	// Options hooks and the hooks of earlier plugins.
	Hooks EndpointHooks
	// DatabaseHooks run before and after user, session, account and
	// verification writes, before the Options database hooks and after those
	// of earlier plugins.
	DatabaseHooks DatabaseHooks
	// OnRequest runs for each mounted HTTP request before routing, after the
	// disabled-path check. An error interrupts the request and is written as
	// the response. Request is a copy the hook may edit: header and query
	// changes reach the endpoint. Path is relative to the auth mount and is
	// not re-resolved. ClientIP follows the host's proxy policy.
	OnRequest func(RequestContext) error
	// OnResponse runs once for each response to a request that passed
	// OnRequest, before anything is written to the client, and may change its
	// status, headers and body. Each plugin's OnResponse runs, in plugin order.
	OnResponse func(*ResponseContext)
	// Middleware runs before the endpoint hooks for the routes its path matches.
	Middleware []Middleware
	// OnSessionsEnded observes sessions the store ended, after its
	// transaction commits and outside it, when the store implements
	// SessionEndReporter. Observers run in plugin order; a panic is logged.
	OnSessionsEnded func(context.Context, SessionsEnded)
	// PrepareOAuthLogin verifies a signed oauth_query before credential handling.
	PrepareOAuthLogin func(EndpointContext, string) (OAuthLoginContinuation, error)
	// PrepareOAuthSelection verifies a signed post-login query before an
	// organization or team switch. It resumes only after a session cookie is issued.
	PrepareOAuthSelection func(EndpointContext, string) (OAuthLoginContinuation, error)
	// SessionResponse shapes the authenticated GET /get-session JSON response.
	// One plugin per instance may supply it. An anonymous response stays null.
	SessionResponse SessionResponseFunc
	// ProjectDeviceSessions also applies SessionResponse to each remembered account.
	ProjectDeviceSessions bool

	// ConfigureStore returns the store view this instance uses, such as one
	// that reads the plugin's declared columns. New calls it once, in plugin
	// order, and later plugins and ValidateStore see the returned view.
	ConfigureStore func(Store) (Store, error)
	ValidateStore  func(Store) error
	// ValidateVerificationStore is set by a plugin that keeps verification
	// records in its own store and runs their hooks with
	// EndpointContext.CreateVerification and SpendVerification, or with
	// GateVerifications when its store decides them in a transaction. When
	// verification hooks are set, New calls it with the store and the hooks
	// that are set, and fails with its error, which names what the store
	// lacks, rather than let the plugin spend a record its hooks never saw.
	ValidateVerificationStore func(Store, VerificationHookSet) error

	// OnValidateNewPassword checks a proposed credential before it is stored.
	OnValidateNewPassword func(ctx context.Context, path, password string) error

	// OnReadSession populates fields owned by an enabled plugin after session authentication.
	OnReadSession func(context.Context, *SessionResult) error
	ID            string
	Endpoints     []Endpoint
	// WellKnown publishes static JSON documents at issuer-relative discovery
	// paths. It runs once per host after all plugins and stores are configured.
	WellKnown func(*Auth, Store) (map[string]WellKnownDocument, error)
	// SessionToken can supply an alternate credential for session lookups.
	SessionToken func(*Auth, http.Header) string
	// OnSessionCookie runs when a handler issues a session cookie.
	OnSessionCookie func(SessionCookieEvent)
	// contains filtered or unexported fields
}

Plugin contributes HTTP endpoints to an Auth instance.

func NewAdmin

func NewAdmin(options AdminOptions) (Plugin, error)

func NewAnonymous

func NewAnonymous(o AnonymousOptions) (Plugin, error)

func NewDeviceAuthorization

func NewDeviceAuthorization(o DeviceAuthorizationOptions) (Plugin, error)

func NewEmailOTP

func NewEmailOTP(o EmailOTPOptions) (Plugin, error)

NewEmailOTP enables single-use mailbox codes for registration, sign-in, verification and password recovery.

func NewJWT

func NewJWT(opts JWTOptions) (Plugin, error)
func NewMagicLink(options MagicLinkOptions) (Plugin, error)

NewMagicLink registers mail delivery and one-time mailbox verification endpoints.

func NewMultiSession

func NewMultiSession(options MultiSessionOptions) (Plugin, error)

func NewOAuthPopup

func NewOAuthPopup() Plugin

NewOAuthPopup installs popup sign-in with the standard message type.

func NewOAuthPopupWithOptions

func NewOAuthPopupWithOptions(options OAuthPopupOptions) (Plugin, error)

NewOAuthPopupWithOptions installs a client-specific message type selected by the host.

func NewOAuthProxy

func NewOAuthProxy(o OAuthProxyOptions) (Plugin, error)

NewOAuthProxy enables provider code exchange on production followed by a browser-bound sign-in or account link on the originating preview.

func NewOneTap

func NewOneTap(o OneTapOptions, fallback OAuthProvider) Plugin

NewOneTap constructs the server plugin. The Google provider configured on the auth instance supplies the verifier unless the plugin has a distinct client ID.

func NewOneTimeToken

func NewOneTimeToken(opts OneTimeTokenOptions) (Plugin, error)

func NewPhoneNumber

func NewPhoneNumber(o PhoneNumberOptions) (Plugin, error)

NewPhoneNumber enables phone-number proofs with an application-provided SMS sender.

func NewTwoFactor

func NewTwoFactor(opts TwoFactorOptions) Plugin

NewTwoFactor implements credential login with authenticator codes or backup codes.

func NewUsername

func NewUsername(options UsernameOptions) (Plugin, error)

type ProfileUpdate

type ProfileUpdate struct {
	AdditionalFields map[string]any

	ClearPhoneNumber                                bool
	Username, DisplayUsername                       *string
	Name, Image                                     *string
	ClearImage, ClearUsername, ClearDisplayUsername bool
	// contains filtered or unexported fields
}

ProfileUpdate changes the supplied fields. A Clear flag removes its field and takes precedence over a supplied value.

func (ProfileUpdate) PhysicalUserFields

func (p ProfileUpdate) PhysicalUserFields() map[string]any

PhysicalUserFields provides only the columns previously validated by Auth.

type ProviderAccountCredential

type ProviderAccountCredential struct {
	ID, UserID, ProviderID, Subject string
	OAuthTokens                     `json:"-"`
}

ProviderAccountCredential is internal adapter data. Credential values stay out of the serialized representation.

type ProviderCredentialStore

type ProviderCredentialStore interface {
	ProviderCredential(ctx context.Context, userID, id string) (ProviderAccountCredential, error)
	UpdateProviderCredential(ctx context.Context, userID, id string, update func(ProviderAccountCredential) (ProviderAccountCredential, bool, error)) (ProviderAccountCredential, error)
}

ProviderCredentialStore locks a single owned account during rotation so concurrent refreshes cannot spend the same rotating refresh token twice.

type ProviderLogoutResult

type ProviderLogoutResult struct {
	Success  bool   `json:"success"`
	URL      string `json:"url"`
	Redirect bool   `json:"redirect"`
}

ProviderLogoutResult is returned after local sign-out when a linked provider has an end-session endpoint. Redirect reports whether the client should follow URL.

type PublicJWTKey

type PublicJWTKey struct {
	ID, Algorithm, Curve, PublicKey string
	CreatedAt                       time.Time
	ExpiresAt                       *time.Time
}

type RateLimitRule

type RateLimitRule struct {
	Max    int
	Window time.Duration
}

RateLimitRule configures the maximum number of requests per peer and route during Window.

type RateLimitRuleFunc

type RateLimitRuleFunc func(r *http.Request, current RateLimitRule) *RateLimitRule

RateLimitRuleFunc chooses the limit for one request. It receives the plugin, built-in or default rule for the route, never a RateLimitRules entry, and returns the rule to use, or nil to not limit the request.

type RateLimitStorage

type RateLimitStorage interface {
	ConsumeRateLimit(ctx context.Context, key string, maximum int, window time.Duration, now time.Time) (time.Duration, error)
}

RateLimitStorage atomically admits one request, or returns how long the caller must wait. An error prevents the request from reaching its handler.

func NewMemoryRateLimitStorage

func NewMemoryRateLimitStorage() RateLimitStorage

NewMemoryRateLimitStorage returns counters kept in this process, which is where rate limits live by default. Set it as Options.RateLimitStorage to keep them local while SecondaryStorage holds sessions.

type Redirect

type Redirect string

Redirect is an endpoint result answered with a 302 and this Location.

type RefreshTokenResult

type RefreshTokenResult struct {
	AccessToken           string     `json:"accessToken"`
	RefreshToken          string     `json:"refreshToken"`
	AccessTokenExpiresAt  *time.Time `json:"accessTokenExpiresAt,omitempty"`
	RefreshTokenExpiresAt *time.Time `json:"refreshTokenExpiresAt"`
	Scope                 *string    `json:"scope"`
	IDToken               *string    `json:"idToken"`
	ProviderID            string     `json:"providerId"`
	AccountID             string     `json:"accountId"`
}

type RegistrationUserFields

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

RegistrationUserFields holds the prepared values or validation error for a new profile. Adapters inspect it only after determining that the verified identity is new.

func (RegistrationUserFields) Columns

func (f RegistrationUserFields) Columns() (map[string]any, error)

Columns returns validated physical columns or the registration validation error.

type RequestContext

type RequestContext struct {
	Request        *http.Request
	Path, ClientIP string
}

type RequestMeta

type RequestMeta struct {
	// TrustedDeviceCookie is the incoming signed browser cookie value, if any.
	TrustedDeviceCookie  string
	CallbackURL          string
	IPAddress, UserAgent string
	RememberMe           *bool
}

RequestMeta records the originating client information for a login.

type ResponseContext

type ResponseContext struct {
	Request *http.Request
	// Path is the request's path relative to the auth mount.
	Path   string
	Status int
	Header http.Header
	Body   []byte
}

ResponseContext describes a response before it is written. OnResponse may change Status, Header and Body.

type SCIMUserReference

type SCIMUserReference struct{ ConnectionID, ExternalID string }

SCIMUserReference names one SCIM connection's User by its exact, case-sensitive externalId.

type SecondaryStorage

type SecondaryStorage interface {
	Get(ctx context.Context, key string) (string, bool, error)
	Set(ctx context.Context, key, value string, ttl time.Duration) error
	Delete(ctx context.Context, key string) error
	GetAndDelete(ctx context.Context, key string) (string, bool, error)
	Increment(ctx context.Context, key string, ttl time.Duration) (int64, error)
}

SecondaryStorage is a shared key-value store, such as Redis, that every replica reads. Implementations are safe for concurrent use. Get and GetAndDelete report whether the key was present. Set replaces the value and expiry, and a ttl of zero or less stores it without expiry. Increment adds one atomically and sets ttl only when it creates the key. Plain Auth passes whole seconds.

type Session

type Session struct {
	CredentialType string `json:"credentialType,omitempty"`

	ImpersonatedBy       *string   `json:"impersonatedBy,omitempty"`
	ActiveTeamID         *string   `json:"activeTeamId,omitempty"`
	ActiveOrganizationID *string   `json:"activeOrganizationId,omitempty"`
	ID                   string    `json:"id"`
	UserID               string    `json:"userId"`
	Token                string    `json:"token"`
	IPAddress            string    `json:"ipAddress"`
	UserAgent            string    `json:"userAgent"`
	CreatedAt            time.Time `json:"createdAt"`
	UpdatedAt            time.Time `json:"updatedAt"`
	ExpiresAt            time.Time `json:"expiresAt"`
	// contains filtered or unexported fields
}

Session identifies one authenticated login.

func (Session) AdditionalField

func (s Session) AdditionalField(name string) (any, bool)

AdditionalField reads a public field returned by the configured instance. Numbers use int64. A present null is distinct from an absent field.

func (Session) AllowsCredentialAction

func (s Session) AllowsCredentialAction(resource, action string) bool

AllowsCredentialAction reports whether this verified credential can exercise a specific application operation. Regular sessions use the route’s own authorization.

func (Session) IsApplicationCredential

func (s Session) IsApplicationCredential() bool

IsApplicationCredential identifies a per-request application-key session.

func (Session) MarshalJSON

func (s Session) MarshalJSON() ([]byte, error)

func (Session) RequireOwner

func (s Session) RequireOwner() error

RequireOwner requires a direct sign-in for operations that reveal credentials or change an account's authentication or permissions.

func (*Session) UnmarshalJSON

func (s *Session) UnmarshalJSON(data []byte) error

type SessionCacheStore

type SessionCacheStore interface {
	AllowSessionCookieCache(context.Context) (bool, error)
}

SessionCacheStore opts a store into browser snapshots. Return false when changes in storage require live validation even for a public session view.

type SessionCookieCacheOptions

type SessionCookieCacheOptions struct {
	// Strategy defaults to compact. JWT signs the snapshot with HS256, or
	// with the JWT plugin's key when jwt.Options.SessionCookieCache is set.
	// JWE encrypts it using a symmetric key derived for this cookie.
	Strategy SessionCookieCacheStrategy
	// MaxAge defaults to five minutes for persistent logins. A browser-session
	// cookie holds a one-minute compact snapshot or a five-minute JWT or JWE.
	MaxAge time.Duration
	// Version defaults to "1". Change it across replicas to invalidate older snapshots.
	Version string
	// VersionFor derives the version from the session and user being issued or read.
	// It may perform I/O with ctx and must be safe for concurrent requests.
	// Choose either Version or VersionFor.
	VersionFor func(ctx context.Context, session Session, user User) (string, error)
}

SessionCookieCacheOptions configures authenticated snapshots for browser session views. GetSession and authenticated operations continue to read the backing store.

type SessionCookieCacheStrategy

type SessionCookieCacheStrategy string

SessionCookieCacheStrategy selects the wire format of a browser session snapshot.

const (
	SessionCacheCompact SessionCookieCacheStrategy = "compact"
	SessionCacheJWT     SessionCookieCacheStrategy = "jwt"
	SessionCacheJWE     SessionCookieCacheStrategy = "jwe"
)

type SessionCookieEvent

type SessionCookieEvent struct {
	Auth    *Auth
	Cookie  http.Cookie
	Route   string
	Request *http.Request
	Header  http.Header
}

SessionCookieEvent lets an extension add response headers when a session is issued.

type SessionEndReporter

type SessionEndReporter interface {
	ReportSessionEnds(report func(context.Context, []EndedSession))
}

SessionEndReporter is a store that reports every session it ends, whatever path ends it. After the transaction commits, and outside it, the store calls the attached report once with the context of the call. New attaches one report when a plugin sets OnSessionsEnded; attaching another replaces it, so the Auth created last on a store hears its session ends.

type SessionField

type SessionField = sessionfields.Field

SessionField declares a scalar session attribute. Column defaults to the public name. ServerOnly disables browser writes; Hidden omits the output.

type SessionFieldStore

type SessionFieldStore interface {
	ValidateSessionFields(map[string]SessionField) error
	ReadSessionFields(context.Context, []Session, map[string]SessionField) (map[string]map[string]any, error)
	UpdateSessionFields(context.Context, Session, map[string]SessionField, map[string]any, time.Time) error
}

SessionFieldStore persists configured physical columns. Reads must return only rows with the requested token, session ID and owner. Update must reauthorize that exact direct session and apply its patch atomically.

type SessionFieldType

type SessionFieldType = sessionfields.Type

type SessionMirrorOptions

type SessionMirrorOptions struct {
	// PreserveEndedSessions keeps the row of an ended session, marked ended,
	// instead of deleting it. Deleting the user still removes its rows.
	PreserveEndedSessions bool
}

SessionMirrorOptions configures how a store mirrors sessions into SecondaryStorage.

type SessionMirrorStore

type SessionMirrorStore interface {
	MirrorSessions(SecondaryStorage, SessionMirrorOptions) error
}

SessionMirrorStore keeps a copy of each live session in SecondaryStorage, so a session read can skip the database. It writes the copy only while it holds the session's row locks, and deletes it before any revocation, user change or refresh of that session commits. Attaching the same storage with the same options again does nothing; anything else is an error.

type SessionRecord

type SessionRecord struct {
	Session
	// Fields holds the Options.SessionAdditionalFields values this write sets,
	// by name. Defaults for the fields it omits are applied after the hooks.
	Fields map[string]any
}

SessionRecord is a session row in a database hook. When creating a session, a hook may change ExpiresAt, IPAddress, UserAgent and Fields. A refresh lets it change ExpiresAt, and a field update the Fields a caller may set.

type SessionRefreshStore

type SessionRefreshStore interface {
	// RefreshSession sets the new expiry and UpdatedAt and returns true only
	// when the stored expiry equals previousExpiry and is after now; an
	// unknown token returns false and a nil error.
	RefreshSession(ctx context.Context, token string, previousExpiry, now, nextExpiry time.Time) (bool, error)
	// DeleteExpiredSession deletes the session only when its ExpiresAt is at
	// or before now; a missing token returns nil.
	DeleteExpiredSession(ctx context.Context, token string, now time.Time) error
}

SessionRefreshStore supports sliding expiration without reviving an expired or revoked session. Implementations compare the previously read expiry atomically with the update. A lost comparison returns false.

type SessionResponseFunc

type SessionResponseFunc func(EndpointContext, SessionResult) (any, error)

SessionResponseFunc projects a validated HTTP session into a JSON response.

type SessionResult

type SessionResult struct {
	// NeedsRefresh is present for eligible deferred HTTP reads.
	NeedsRefresh *bool   `json:"needsRefresh,omitempty"`
	Session      Session `json:"session"`
	User         User    `json:"user"`
}

SessionResult pairs the current session with its authenticated user.

type SessionsEnded

type SessionsEnded struct {
	Auth     *Auth
	Store    Store
	Sessions []EndedSession
}

SessionsEnded describes sessions a store ended to Plugin.OnSessionsEnded.

type SignInInput

type SignInInput struct {
	Email, Password string
	RememberMe      *bool
}

SignInInput authenticates an existing email credential.

type SignUpInput

type SignUpInput struct {
	AdditionalFields          map[string]any
	Username, DisplayUsername *string
	Name, Email, Password     string
	Image                     *string
	// contains filtered or unexported fields
}

SignUpInput describes a new email credential and public profile.

type StatusOnlyError

type StatusOnlyError int

StatusOnlyError writes an HTTP status without a response body. Native callers can also retrieve its status and standard text with errors.As and *APIError.

func (StatusOnlyError) Error

func (e StatusOnlyError) Error() string

func (StatusOnlyError) Unwrap

func (e StatusOnlyError) Unwrap() error

type Store

type Store interface {
	CreateUser(ctx context.Context, user User, passwordHash string, initial *StoredSession) error
	Credential(ctx context.Context, email string) (User, string, error)
	CreateSession(ctx context.Context, session StoredSession) error
	Session(ctx context.Context, token string) (StoredSession, User, error)
	DeleteSession(ctx context.Context, token string) error
	ListSessions(ctx context.Context, userID string) ([]StoredSession, error)
	DeleteOtherSessions(ctx context.Context, userID, keepToken string) error
	DeleteUserSession(ctx context.Context, userID, token string) error
}

Store persists users, credentials, and sessions. CreateUser commits its three writes atomically. Deletions are idempotent. An empty keep token revokes all sessions for that user. Implementations must support concurrent requests. Package storetest checks an implementation.

type StoredJWTKey

type StoredJWTKey struct {
	PublicJWTKey
	// EncryptedPrivateKey holds the sealed private JWK, or the plain private
	// JWK JSON when DisablePrivateKeyEncryption is set.
	EncryptedPrivateKey string
}

type StoredSession

type StoredSession struct {
	Session
	// contains filtered or unexported fields
}

StoredSession is the record passed to the storage adapter.

func (StoredSession) PhysicalSessionFields

func (s StoredSession) PhysicalSessionFields() (map[string]any, error)

PhysicalSessionFields supplies an adapter with validated column names and their scalar values for the same transaction that inserts a session.

func (StoredSession) WithStoredSessionPatch

func (s StoredSession) WithStoredSessionPatch(fields map[string]SessionField, patch map[string]any) (StoredSession, error)

WithStoredSessionPatch is for memory-backed adapters applying a validated patch while holding their session lock. It preserves fields from other nodes.

type SyntheticUser

type SyntheticUser struct {
	ID, Name, Email      string
	EmailVerified        bool
	Image                *string
	CreatedAt, UpdatedAt time.Time
	// AdditionalFields holds the public UserAdditionalFields after defaults.
	AdditionalFields map[string]any
}

SyntheticUser is the generated user for a sign-up with an existing email.

type TokenAuthMethod

type TokenAuthMethod string

TokenAuthMethod is how a social provider's client authenticates at the token endpoint.

const (
	// TokenAuthClientSecretBasic sends the client ID and secret in an HTTP
	// Basic header.
	TokenAuthClientSecretBasic TokenAuthMethod = "client_secret_basic"
	// TokenAuthClientSecretPost sends them in the form.
	TokenAuthClientSecretPost TokenAuthMethod = "client_secret_post"
	// TokenAuthNone sends only the client ID, for a public client using PKCE.
	TokenAuthNone TokenAuthMethod = "none"
	// TokenAuthPrivateKeyJWT sends a signed client assertion from
	// TokenEndpointAuth.ClientAssertion.
	TokenAuthPrivateKeyJWT TokenAuthMethod = "private_key_jwt"
	// TokenAuthCustom lets TokenEndpointAuth.CustomizeRequest set the client
	// ID and credentials.
	TokenAuthCustom TokenAuthMethod = "custom"
)

type TokenEndpointAuth

type TokenEndpointAuth struct {
	Method TokenAuthMethod
	// ClientAssertion is required with TokenAuthPrivateKeyJWT and refused
	// otherwise.
	ClientAssertion ClientAssertionFunc
	// CustomizeRequest is required with TokenAuthCustom and refused
	// otherwise. It sets the client ID and credentials in form or header;
	// form holds the grant fields and any TokenParams or RefreshParams
	// fields, which it must not change.
	CustomizeRequest func(ctx context.Context, r TokenRequest, form url.Values, header http.Header) error
}

TokenEndpointAuth authenticates a social provider's code exchange and refresh. The zero value keeps Config.Endpoint.AuthStyle; a Method replaces it. New refuses a Method that does not fit the configuration, such as a secret method without a secret.

type TokenRequest

type TokenRequest struct {
	ClientID, TokenURL string
	// GrantType is "authorization_code" or "refresh_token".
	GrantType string
}

TokenRequest identifies one request to a provider's token endpoint. It carries no secret.

type TwoFactorOptions

type TwoFactorOptions struct {
	TOTP                                        FactorTOTPOptions
	Backup                                      FactorBackupOptions
	Lockout                                     FactorLockoutOptions
	OTP                                         FactorOTPOptions
	AllowPasswordless, SkipVerificationOnEnable bool
	Issuer                                      string
	ChallengeLifetime                           time.Duration
	TrustDeviceMaxAge                           time.Duration
}

type TwoFactorStore

type TwoFactorStore interface {
	FactorEnabled(context.Context, string) (bool, error)
	WithTwoFactor(ctx context.Context, subject FactorSubject, decide func(FactorState) (FactorChange, error)) error
}

type User

type User struct {
	*PhoneNumberFields
	*UsernameFields
	LastLoginMethod *string `json:"lastLoginMethod,omitempty"`
	IsAnonymous     *bool   `json:"isAnonymous,omitempty"`
	*AdminUserFields
	TwoFactorEnabled *bool     `json:"twoFactorEnabled,omitempty"`
	ID               string    `json:"id"`
	Name             string    `json:"name"`
	Email            string    `json:"email"`
	EmailVerified    bool      `json:"emailVerified"`
	Image            *string   `json:"image"`
	CreatedAt        time.Time `json:"createdAt"`
	UpdatedAt        time.Time `json:"updatedAt"`
	// contains filtered or unexported fields
}

User is the public account profile shared by all authentication methods.

func BootstrapAdmin

func BootstrapAdmin(ctx context.Context, s AdminBootstrapStore, name, email, password string) (User, error)

BootstrapAdmin provisions the first default administrator through a trusted database connection, with the "admin" role and an unverified email. Applications should use the authenticated admin service for subsequent grants. This operation is available only through Go and authctl.

func BootstrapAdminAccount

func BootstrapAdminAccount(ctx context.Context, s AdminBootstrapStore, in AdminBootstrap) (User, error)

BootstrapAdminAccount provisions an administrator through a trusted database connection. The store refuses with ErrAdminExists when an account already holds one of the roles. No hooks run; use Auth.BootstrapAdmin for an instance's hooks and password hasher.

func (User) AdditionalField

func (u User) AdditionalField(name string) (any, bool)

AdditionalField returns a public profile value, with int64 for numbers and a separate presence flag for nullable fields.

func (User) MarshalJSON

func (u User) MarshalJSON() ([]byte, error)

func (*User) UnmarshalJSON

func (u *User) UnmarshalJSON(data []byte) error

type UserField

type UserField = sessionfields.Field

UserField configures a scalar profile attribute. Column names its storage column. ServerOnly reserves writes for the host. Hidden excludes the field from responses.

type UserFieldStore

type UserFieldStore interface {
	ValidateUserFields(map[string]UserField) error
	CreateUserWithFields(context.Context, User, string, *StoredSession, UserFieldValues) error
	ReadUserFields(context.Context, string, map[string]UserField) (map[string]any, error)
	UpdateUserFields(context.Context, string, *Session, ProfileUpdate, time.Time) error
}

UserFieldStore commits configured fields with their user/credential/session or profile writes. ReadUserFields returns public columns only, keyed by physical name. UpdateUserFields must lock the exact user and revalidate any supplied direct session.

type UserFieldValues

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

UserFieldValues carries validated physical values into the account creation transaction.

func (UserFieldValues) Columns

func (v UserFieldValues) Columns() map[string]any

Columns returns a copy keyed by physical column name.

func (UserFieldValues) Present

func (v UserFieldValues) Present() bool

Present reports whether any configured columns participate in this write.

type UserInfoAction

type UserInfoAction string

UserInfoAction says what a ValidateUserInfo check is about to admit.

const (
	// UserInfoCreateUser checks a user about to be created.
	UserInfoCreateUser UserInfoAction = "create-user"
	// UserInfoLinkAccount checks a provider identity about to be linked to
	// an existing user.
	UserInfoLinkAccount UserInfoAction = "link-account"
	// UserInfoSignIn checks an existing user signing in again through a
	// provider, with the provider's fresh profile.
	UserInfoSignIn UserInfoAction = "sign-in"
)

type UserInfoValidation

type UserInfoValidation struct {
	Action UserInfoAction
	// Method says how the user arrives: "email-password", "oauth",
	// "sso-oidc", "sso-saml", "magic-link", "email-otp", "phone-number",
	// "anonymous", "siwe", "admin", "scim", "passkey" or a plugin's own name.
	Method string
	// Provider is the social, generic OAuth or SSO provider ID for the
	// "oauth", "sso-oidc" and "sso-saml" methods.
	Provider string
	// Profile is the provider's raw profile, when there is one, with JSON
	// numbers as json.Number.
	Profile map[string]any
	// User is the user about to be created or, for a link or a provider
	// sign-in, the provider's fresh profile with the existing user's ID.
	// Fields holds its additional-field input.
	User UserRecord
	// Request is a copy of the request without its body, or nil for a
	// direct Go call.
	Request *http.Request
}

UserInfoValidation describes an identity that Options.ValidateUserInfo admits or refuses.

type UserRecord

type UserRecord struct {
	User
	// Fields holds the Options.UserAdditionalFields values this write sets,
	// by name. Defaults for the fields it omits are applied after the hooks.
	Fields map[string]any
}

UserRecord is a user row in a database hook. When creating a user, a hook may change Name, Email, Image, EmailVerified and Fields, except during a sign-in the store decides, such as social sign-in or a magic link, which allows only Name and Image and leaves Fields empty. When updating a profile, a hook may change Name, Image and Fields. Email changes and verification allow no edits.

type UsernameFields

type UsernameFields struct {
	Username *string `json:"username"`
	*DisplayUsernameFields
}

UsernameFields preserves the distinction between an optional public name and a disabled plugin.

type UsernameOptions

type UsernameOptions struct {
	MinLength, MaxLength                                                 int
	Validate, ValidateDisplay                                            func(context.Context, string) bool
	Normalize, NormalizeDisplay                                          func(string) string
	DisableNormalization, DisableDisplay, Immutable, DisableAvailability bool
	ValidateAfterNormalization, ValidateDisplayAfterNormalization        bool
}

type UsernameSignInInput

type UsernameSignInInput struct {
	Username, Password string
	RememberMe         *bool
}

type UsernameStore

type UsernameStore interface {
	CheckUsernameSchema(context.Context, bool) error
	UpdateUsernameProfile(context.Context, string, string, ProfileUpdate, time.Time, bool) error
	UsernameExists(context.Context, string) (bool, error)
	UsernameCredential(context.Context, string) (User, string, error)
	ReadUsername(context.Context, string, bool) (*UsernameFields, error)
}

type VerificationCleanupStore

type VerificationCleanupStore interface {
	KeepExpiredVerifications(keep bool) error
}

VerificationCleanupStore deletes expired verification records, such as OAuth states, passkey challenges and reset tokens, while it writes new ones. KeepExpiredVerifications(true) stops that. The first call fixes the setting for the store and every copy of it; the same value again does nothing, and the other value is an error.

type VerificationGate

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

VerificationGate runs the verification database hooks of the records a store creates, updates or deletes inside its own transaction, where no hook may run. A plugin makes such a store call through EndpointContext.GateVerifications; the store finds the gate with VerificationGateFrom.

Just before each write, after every check that could refuse the call, the store asks Create, Update or Delete. The first time the gate is asked about a record whose before hooks are set, it answers ErrVerificationPending. The store first asks about the call's other records, so that their hooks run in one pass, then returns the error and rolls back. The hooks then run outside the transaction and the call runs again. On that run the same record gets their answer, and a record that changed is asked about again. A declined record is left as it is, and the store goes on as its plugin documents: without that write, or with the plugin's refusal. Once the call returns nil, the after hooks run for the records it was allowed to write, in the order it asked.

A record's fields must be the same on every run, so a store dates a record it creates from Now or from values fixed before the call, and judges expiry with its own clock. A record names the stored row by its ID, kind, owner and expiry, and never carries what redeems it. A nil gate allows every record and runs no hook, so a store calls it unconditionally.

func VerificationGateFrom

func VerificationGateFrom(ctx context.Context) *VerificationGate

VerificationGateFrom returns the gate of the store call ctx belongs to, or nil.

func (*VerificationGate) Attempt

func (g *VerificationGate) Attempt()

Attempt starts a new transaction attempt of the store call: a store that retries its transaction inside one call calls it at the start of each attempt, so that only the last attempt's records run their after hooks.

func (*VerificationGate) Create

func (g *VerificationGate) Create(rec VerificationRecord) (bool, error)

Create reports whether the store may store rec. false means a before hook declined it; ErrVerificationPending means the hooks have yet to see it.

func (*VerificationGate) Delete

func (g *VerificationGate) Delete(rec VerificationRecord) (bool, error)

Delete reports, as Create does, whether the store may spend or remove rec.

func (*VerificationGate) Now

func (g *VerificationGate) Now() time.Time

Now returns the time the gate was made, in UTC to the millisecond, or the current time for a nil gate. It is fixed for the request.

func (*VerificationGate) Update

func (g *VerificationGate) Update(rec VerificationRecord) (bool, error)

Update reports, as Create does, whether the store may change rec, which carries the record as the change leaves it.

type VerificationHookSet

type VerificationHookSet struct {
	// CreateBefore reports create before hooks, which may decline a record.
	CreateBefore bool
	// UpdateBefore reports update before hooks, which may decline a change.
	UpdateBefore bool
	// Delete reports delete hooks, which read a record before it is spent.
	Delete bool
}

VerificationHookSet tells a plugin's ValidateVerificationStore which verification database hooks are set.

type VerificationIdentifierStorage

type VerificationIdentifierStorage struct {
	// Hashed stores, in place of the token, the SHA-256 of the whole
	// identifier, purpose prefix included, as unpadded URL-safe Base64: 43
	// characters. It uses no secret, so changing Secret does not change it.
	Hashed bool
	// Hash, when set, stores its result in place of the token. It receives
	// the whole identifier, such as "reset-password:" followed by the token,
	// and must return the same value for the same input: 1 to 240 bytes of
	// UTF-8 without NUL. An error or panic fails the request. Set Hashed or
	// Hash, not both.
	Hash func(ctx context.Context, identifier string) (string, error)
}

VerificationIdentifierStorage sets how the token in a verification identifier is stored. The zero value stores the token as it is.

type VerificationRecord

type VerificationRecord struct {
	// ID identifies the record. A magic link's, one-time token's or passkey
	// challenge's ID is derived from its stored key, and a wallet nonce's from
	// the nonce; each is the row ID the SQL store gives it. An email or phone
	// code's ID is its stored row's; each send stores a new one. A two-factor
	// record's, a SAML logout binding's or request's, an SSO domain token's
	// and an authorization code's ID is its stored row's too; a new code's is derived from its stored identifier.
	// It cannot redeem the record, but keep it private.
	ID string
	// Identifier is the kind of record: "reset-password", "delete-account",
	// "oauth-state", "magic-link", "one-time-token", an email code's
	// "sign-in-otp", "email-verification-otp", "forget-password-otp" or
	// "change-email-otp", a phone code's "phone-number-otp" or
	// "phone-number-reset", a two-factor sign-in challenge's "2fa", a
	// delivered second-factor code's "2fa-otp", a remembered browser's
	// "trust-device", a passkey challenge's "passkey-registration" or
	// "passkey-authentication", a wallet nonce's "siwe", a SAML logout
	// binding's "saml-logout-session" or request's "saml-logout-request", an
	// SSO domain token's "sso-domain-verification", or an OAuth
	// authorization code's "authorization-code".
	Identifier string
	// UserID is the record's owner. An OAuth flow has one only when it
	// links an account to a signed-in user. A one-time token names the user
	// whose session it transfers. An email change code names the signed-in
	// user who asked for it. A magic link and other email and phone codes,
	// which prove an address or number rather than an account, have none.
	// A two-factor record names the account it proves. A passkey challenge
	// names the signed-in user it is for; a first-use registration's, whose
	// account may not exist yet, and a signed-out sign-in's name none. A
	// wallet nonce, bound to no wallet until a signed message redeems it,
	// names none. An enterprise sign-in's flow names none. A SAML logout
	// binding names its session's user, while a logout request, bound to a
	// browser, and an SSO domain token, which proves a domain, name none. An
	// authorization code names the user who approved it.
	UserID    string
	ExpiresAt time.Time
}

VerificationRecord is a verification record in a database hook. It leaves out the token and the data that redeem it; the request in the hook's HookContext may still carry the token it presents.

type VerifiedEmailChange

type VerifiedEmailChange struct {
	User            User
	SessionEligible bool
}

VerifiedEmailChange is returned only for the transaction that changed the verified state. A zero User indicates an already-verified link replay.

type VersionedSecret

type VersionedSecret struct {
	Version int
	Value   string
}

VersionedSecret identifies a signing key. The first entry issues credentials. Keep previous entries only for as long as credentials they signed should work.

type WellKnownDocument

type WellKnownDocument struct {
	Body    json.RawMessage
	Headers http.Header
}

WellKnownDocument is a JSON discovery response, captured at host initialization. Headers may customize caching and cross-origin access.

func (WellKnownDocument) ServeHTTP

func (d WellKnownDocument) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves GET and HEAD when the document is mounted directly by the host.

type XMLDocument

type XMLDocument []byte

XMLDocument is an XML representation encoded by a trusted plugin, served with a sandboxing Content-Security-Policy.

Source Files

Directories

Path Synopsis
adapters
memory
Package memory provides process-local storage for development and tests.
Package memory provides process-local storage for development and tests.
mysql
Package mysql implements authentication storage using MySQL.
Package mysql implements authentication storage using MySQL.
postgres
Package postgres implements authentication storage using PostgreSQL.
Package postgres implements authentication storage using PostgreSQL.
sqlite
Package sqlite implements durable authentication storage using SQLite.
Package sqlite implements durable authentication storage using SQLite.
sqlstore
Package sqlstore persists authentication data in SQLite, PostgreSQL, and MySQL.
Package sqlstore persists authentication data in SQLite, PostgreSQL, and MySQL.
Package authtest provides in-process fixtures for applications testing their Plain Auth integration.
Package authtest provides in-process fixtures for applications testing their Plain Auth integration.
Account management through the mounted authentication API.
Account management through the mounted authentication API.
stripe
Package stripe calls the hosted Checkout and subscription endpoints with an existing Plain Auth client.
Package stripe calls the hosted Checkout and subscription endpoints with an existing Plain Auth client.
cmd
authctl command
Command authctl manages a host application's auth schema and secrets.
Command authctl manages a host application's auth schema and secrets.
conformance
fixture command
Command fixture serves a disposable instance to the differential client tests.
Command fixture serves a disposable instance to the differential client tests.
fixture/env command
Command env reports only public configuration and the signature of a fixed test value.
Command env reports only public configuration and the signature of a fixed test value.
schemafixture command
Command schemafixture batches independent differential tests over a JSON-lines stream.
Command schemafixture batches independent differential tests over a JSON-lines stream.
scimfixture command
Command scimfixture exercises server-only catalog methods from a test process.
Command scimfixture exercises server-only catalog methods from a test process.
examples
basic command
The application owns the listener, routes and database lifetime.
The application owns the listener, routes and database lifetime.
internal
clientassertion
Package clientassertion signs RFC 7523 private_key_jwt client assertions for the social providers and the enterprise SSO plugin.
Package clientassertion signs RFC 7523 private_key_jwt client assertions for the social providers and the enterprise SSO plugin.
configenv
Package configenv validates server and CLI configuration.
Package configenv validates server and CLI configuration.
emailaddress
Package emailaddress implements mailbox validation for wallet contact claims.
Package emailaddress implements mailbox validation for wallet contact claims.
httporigin
Package httporigin parses HTTP origins and matches configured trust rules.
Package httporigin parses HTTP origins and matches configured trust rules.
jsjson
Package jsjson encodes Go values using JSON.stringify string escaping.
Package jsjson encodes Go values using JSON.stringify string escaping.
kvtest
Package kvtest is an in-memory SecondaryStorage for tests, with expiry, a record of the operations and injected failures.
Package kvtest is an in-memory SecondaryStorage for tests, with expiry, a record of the operations and injected failures.
polarledger
Package polarledger describes the tables shared by the migration CLI and the optional Polar checkout module.
Package polarledger describes the tables shared by the migration CLI and the optional Polar checkout module.
popupwire
Package popupwire defines the popup protocol shared by the handler and browser clients.
Package popupwire defines the popup protocol shared by the handler and browser clients.
publicnet
Package publicnet classifies network addresses used in identity metadata.
Package publicnet classifies network addresses used in identity metadata.
sessionfields
Package sessionfields validates the common configuration used by session issuance, public updates and the three relational schema generators.
Package sessionfields validates the common configuration used by session issuance, public updates and the three relational schema generators.
walletschema
Package walletschema describes physical names in the wallet association model.
Package walletschema describes physical names in the wallet association model.
plugins
access
Package access evaluates resource and action permissions for application roles.
Package access evaluates resource and action permissions for application roles.
admin
Package admin provides role-checked user and session administration.
Package admin provides role-checked user and session administration.
anonymous
Package anonymous creates guest sessions and transfers application data on sign-in.
Package anonymous creates guest sessions and transfers application data on sign-in.
apikey
Package apikey provides user- and organization-owned credentials with independent expiration, scoped permissions, usage budgets and per-key rate limits.
Package apikey provides user- and organization-owned credentials with independent expiration, scoped permissions, usage budgets and per-key rate limits.
bearer
Package bearer adds session authentication through the Authorization header.
Package bearer adds session authentication through the Authorization header.
captcha
Package captcha verifies challenge tokens on selected authentication HTTP routes.
Package captcha verifies challenge tokens on selected authentication HTTP routes.
cimd
Package cimd identifies OAuth clients by Client ID Metadata Documents (draft-ietf-oauth-client-id-metadata-document-02), as another runtime's cimd plugin does: a client ID that is an HTTPS URL names a JSON document with the client's metadata, which the provider fetches, validates and stores through a client discovery.
Package cimd identifies OAuth clients by Client ID Metadata Documents (draft-ietf-oauth-client-id-metadata-document-02), as another runtime's cimd plugin does: a client ID that is an HTTPS URL names a JSON document with the client's metadata, which the provider fetches, validates and stores through a client discovery.
customsession
Package customsession lets an application return its own authenticated session view.
Package customsession lets an application return its own authenticated session view.
deviceauthorization
Package deviceauthorization adds RFC 8628 first-party device sign-in.
Package deviceauthorization adds RFC 8628 first-party device sign-in.
emailotp
Package emailotp adds single-use email verification, login and recovery codes.
Package emailotp adds single-use email verification, login and recovery codes.
i18n
Package i18n translates coded authentication errors for each request.
Package i18n translates coded authentication errors for each request.
jwt
Package jwt signs short-lived service assertions and publishes public verification keys.
Package jwt signs short-lived service assertions and publishes public verification keys.
lastlogin
Package lastlogin remembers the last login method in a browser-readable cookie.
Package lastlogin remembers the last login method in a browser-readable cookie.
magiclink
Package magiclink adds single-use mailbox sign-in links.
Package magiclink adds single-use mailbox sign-in links.
mcp
Package mcp protects Model Context Protocol servers with the OAuth provider's access tokens, as another runtime's MCP package does.
Package mcp protects Model Context Protocol servers with the OAuth provider's access tokens, as another runtime's MCP package does.
multisession
Package multisession lets one browser remember and switch among signed-in accounts.
Package multisession lets one browser remember and switch among signed-in accounts.
oauthpopup
Package oauthpopup supports OAuth sign-in in a first-party popup window.
Package oauthpopup supports OAuth sign-in in a first-party popup window.
oauthprovider
Package oauthprovider provides OAuth authorization-server and protected-resource integrations.
Package oauthprovider provides OAuth authorization-server and protected-resource integrations.
oauthproxy
Package oauthproxy exchanges social sign-in codes at a registered production callback and completes the browser session on its originating preview.
Package oauthproxy exchanges social sign-in codes at a registered production callback and completes the browser session on its originating preview.
onetap
Package onetap adds Google Identity Services browser sign-in.
Package onetap adds Google Identity Services browser sign-in.
onetimetoken
Package onetimetoken transfers an active login between clients using a short-lived credential.
Package onetimetoken transfers an active login between clients using a short-lived credential.
openapi
Package openapi publishes an OpenAPI 3.1 description of an auth handler.
Package openapi publishes an OpenAPI 3.1 description of an auth handler.
organization
Package organization provides member-scoped groups, active selections and invitations.
Package organization provides member-scoped groups, active selections and invitations.
passkey
Package passkey authenticates users with WebAuthn public-key credentials.
Package passkey authenticates users with WebAuthn public-key credentials.
phonenumber
Package phonenumber provides SMS verification of phone numbers.
Package phonenumber provides SMS verification of phone numbers.
pwnedpassword
Package pwnedpassword checks proposed credentials against the Pwned Passwords range API.
Package pwnedpassword checks proposed credentials against the Pwned Passwords range API.
scim
Package scim provisions directory-owned Users and Groups through the SCIM 2.0 protocol.
Package scim provisions directory-owned Users and Groups through the SCIM 2.0 protocol.
siwe
Package siwe authenticates externally owned Ethereum accounts using signed EIP-4361 messages and one-use server challenges.
Package siwe authenticates externally owned Ethereum accounts using signed EIP-4361 messages and one-use server challenges.
sso
Package sso administers persisted enterprise OpenID Connect providers.
Package sso administers persisted enterprise OpenID Connect providers.
stripe
Package stripe authenticates Stripe webhook deliveries and dispatches their events.
Package stripe authenticates Stripe webhook deliveries and dispatches their events.
twofactor
Package twofactor adds authenticator codes and single-use backup codes to credential sign-in.
Package twofactor adds authenticator codes and single-use backup codes to credential sign-in.
username
Package username adds optional public usernames and credential sign-in.
Package username adds optional public usernames and credential sign-in.
Package providers configures supported social sign-in providers.
Package providers configures supported social sign-in providers.
Package schema generates fresh-database DDL for authentication and plugin tables.
Package schema generates fresh-database DDL for authentication and plugin tables.
Package storetest checks a plainauth.Store implementation against the contract Plain Auth relies on.
Package storetest checks a plainauth.Store implementation against the contract Plain Auth relies on.

Jump to

Keyboard shortcuts

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