plainauth

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

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 62 Imported by: ? modules, 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

Plain Auth embeds authentication in your Go API. Mount the auth handler on your router and use the same instance to read the signed-in user inside your own handlers. Your application owns its listener, database lifetime, middleware, and routes. Any HTTP client can use the API. Your application chooses the sign-in screens, organization and team controls, and navigation.

Run locally · Install in a Go app · Supported workflows · Roadmap

Developer preview. Start with email and password, persistent sessions, and a protected route in your own Go server. APIs and SQL migrations may change during the preview. Each supported workflow below links to its tests or guide. The roadmap tracks the remaining features and the evidence for each completed behavior.

Run it locally

Use a currently patched Go 1.26 or newer toolchain and a C compiler for SQLite. The example creates its tables on first start. Clone the repository, generate a signing secret, and start the app.

git clone https://github.com/Plain-Auth/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 the path. Keep the same secret and database when restarting the example to preserve sessions.

In another terminal, create an account, call an application-owned 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 '{}'

Mount it in an application

From your application's Go module, install the SQLite adapter and the core library from main.

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

Import the library and mount it on your router.

import (
    "strings"

    "github.com/Plain-Auth/plain-auth"
    "github.com/Plain-Auth/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

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

This reads the signing secret and public URL from the host environment configured above. Explicit options, environment settings and their precedence are documented in the configuration guide.

Go records the resolved commit in the consuming project’s go.mod. The module path is github.com/Plain-Auth/plain-auth. Its Go package name is plainauth. The SQLite adapter lives at github.com/Plain-Auth/plain-auth/adapters/sqlite. A complete host application, including a protected route and graceful shutdown, is in examples/basic.

Supported workflows

  • Register with email, sign in, read a session, and sign out. Client lifecycle test
  • Register a username, authenticate by handle, and apply account policies and MFA. Username sign-in
  • Issue revocable API keys, check permissions, and enforce usage limits on application routes. API keys
  • Use the same handler with ServeMux, chi, Gorilla Mux, Gin, Echo, or Fiber. Router tests
  • Generate auth tables and persist sessions on SQLite, PostgreSQL, and MySQL. Storage contract
  • Store application fields on users and sessions, control which values clients can read or write, and migrate their SQL columns with authctl. User fields · Session fields · Schema commands
  • Recover a password and verify an email address through an application-provided sender. Account tests
  • Register a passkey and authenticate with it. Software authenticator tests
  • Sign in with a built-in provider. Use providers.Names() for the current catalog. Browser fixtures · OpenID Connect fixtures · Apple and Microsoft
  • Sign in through an OAuth popup from a top-level page or a cross-site iframe. Popup setup and Chrome tests
  • Share a registered OAuth callback across trusted previews and create the session on the preview that started sign-in. OAuth proxy setup
  • Configure tenant-specific sign-in with Auth0, Keycloak, Okta or Entra ID and additional OAuth profiles including LINE and HubSpot. Provider setup
  • Verify a phone number, link it to an account and recover a password through the application’s SMS sender. Phone accounts
  • Verify an email address, sign in, change an address and reset a password using single-use email codes. Email OTP
  • Approve or deny a device login from a signed-in browser. Device authorization
  • Remember multiple accounts in one browser and switch or revoke them. Account switching
  • Create a guest account and transfer its application records on sign-up. Guest sessions
  • Verify an authenticator, delivered code or single-use backup code and remember a trusted browser. Two-factor authentication
  • Create organizations and teams, accept scoped invitations and enforce fixed or application-defined membership and team limits. Organization membership
  • Create, list, look up, update, and retire organization roles over HTTP. Set per-organization role limits, control delegated permissions, and store application fields on roles. Organization role management
  • Open a Polar checkout or customer portal, read the customer’s billing state, and reconcile signed checkout updates. Polar setup and recovery
  • Verify Stripe webhook signatures and open an authenticated customer’s billing portal. Webhook tests · Billing portal tests
  • Start recurring Checkout, confirm a personal plan change, schedule a price for the next billing period, cancel or restore the subscription. Subscription billing
  • Choose licensed seat quantities for personal and organization checkout, review quantity changes in Stripe, and list confirmed subscriptions. Organization billing
  • Bill organization seats monthly or annually, with an optional fixed base price, and synchronize the quantity after membership changes. Automatic seats
  • Register enterprise OIDC or SAML providers, optionally verify their domains with DNS, sign in with a browser, and provision members in the provider’s organization. Enterprise single sign-on
  • Provision directory Users and Groups, synchronize direct memberships and rotate or revoke scoped SCIM credentials. Directory provisioning
  • Map directory Group memberships to application roles and withdraw grants when their last source is removed. SCIM role mapping

Stripe Checkout and signed billing updates support a single metered price or metered add-ons with a licensed base. IdP-initiated SAML, SAML single logout, and plan switches involving metered prices remain open. The complete checklist records which parts of each integration have passing tests.

For integration tests, create fixture users and organizations, capture email or SMS codes, or import an existing test login into a browser. Test helpers

Documentation

Task Guide
Load signing secrets, the public URL, and trusted origins from the environment Environment configuration
Mount on ServeMux, chi, Gorilla Mux, Gin, Echo, or Fiber Router integrations
Configure users, cookies, origins, and session management Authentication
Remember the last sign-in method in a browser or across a user's devices Login preferences
Add account switching to a shared device Device sessions
Share login cookies across approved sibling hosts Cookie configuration
Access application routes with revocable API keys API keys
Check a member’s organization permissions or define roles for your own handlers Organization permissions · Custom organization roles · Application roles
Share a request limit across server instances using Redis or Valkey Redis secondary storage
Return translated authentication errors in 22 bundled languages Localization
Generate an OpenAPI document and browse the routes enabled in this application OpenAPI reference
Authorize a TV, CLI or input-constrained device Device authorization
Transfer an active session using a single-use credential One-time tokens
Integrate the Google One Tap prompt or sign-in button Google One Tap
Sign in with an Ethereum wallet Wallet sign-in
Register and use a WebAuthn passkey Passkeys
Verify an address, sign in or recover a password with an email code Email one-time passwords
Let users sign in through a single-use email link Magic links
Enroll an authenticator and manage backup codes Two-factor authentication
Generate optional organization, team, passkey, rate-limit, subscription, and two-factor tables Schema profiles
Require a CAPTCHA verdict on selected routes CAPTCHA providers
Include a host-approved entitlement in an ID token and reevaluate it on refresh Application-defined ID-token claims
Connect a relying party using the issuer URL and discover its public signing keys OpenID Connect discovery
Sign a user into an OAuth client with a verifiable ID token, then renew it with an offline grant OpenID Connect code and refresh exchanges
Read current OIDC profile and email claims using a signed or opaque access token OpenID Connect UserInfo
Publish OAuth issuers and scopes, verify DPoP proofs and return authentication challenges from a protected API Resource discovery and challenges
Discover machine grant endpoints, authentication methods and signing keys from an issuer URL Authorization-server discovery
Sign in, choose an account, collect consent and exchange a PKCE code for access or offline refresh tokens Browser authorization and code exchange
Register OAuth resources, change their policies, and link registered clients Resource management
List, inspect, update and remove a user’s OAuth consent grants Authorized applications
Register OAuth clients and rotate confidential client secrets OAuth client registration
Grant or revoke machine-to-machine scopes from Go server code Machine scope management
Issue signed or opaque machine tokens with resource audiences, scoped permissions and sender binding Machine access tokens · Token introspection
Authenticate an OAuth application with its own signing key and rotate its keys Signed client assertions
Rotate a refresh token, narrow its scopes or check its session Refresh exchange · Refresh token introspection
Inspect a delegated opaque token using an application or resource server credential Delegated token introspection
Check signed OAuth access tokens against current client, session and resource state Signed token introspection
Revoke an OAuth token or invalidate a replayed refresh-token family Token revocation
List or delete registered applications and show client details on a consent screen Manage registered applications
Issue signed service tokens and publish verification keys JWT and JWKS
Check new passwords against a breached-password service Password screening
Configure profile updates, password reset, and verification email Account management and recovery
Generate tables and migrate SQLite, PostgreSQL, or MySQL Databases and CLI
Register a username and sign in with a password Username sign-in
Manage users, ban accounts and grant administrative access Administrator accounts
Switch organizations and teams, read a shared organization directory, grant memberships and accept invitations Organizations
Page through an organization's member directory and filter by role or join date Member directory
Deliver invitation emails from your application and accept grants over HTTP or Go Invitation delivery · Invitation acceptance
Start recurring Checkout, synchronize subscription changes, cancel, and restore Subscription billing
Set up Polar checkout, billing state, the customer portal and signed webhooks Polar hosted checkout
Add a custom endpoint, verify Stripe webhooks, or open the billing portal Plugins and Stripe
Configure browser sign-in, native ID tokens and linked provider credentials Social sign-in
Call the API from a Go service Go client
Work on a feature, run checks, and update the checklist in GitHub Contributing

License

Maintained by Nabil Abu-Hadba and distributed under the MIT license.

Documentation

Overview

Device authorization lets an input-constrained device obtain a first-party session.

HTTP request handling for the core authentication endpoints.

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

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 (
	ErrTransferSessionExpired = errors.New("one-time token session expired")
	ErrTransferSessionMissing = errors.New("one-time token session absent")
)
View Source
var (
	ErrNotFound   = errors.New("authn: record not found")
	ErrEmailTaken = errors.New("authn: email already registered")
)
View Source
var ErrAdminExists = errors.New("an administrative account already exists")

ErrAdminExists indicates that the target database already has an admin role holder.

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 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 ErrUsernameImmutable = errors.New("plainauth: username is immutable")
View Source
var ErrUsernameTaken = errors.New("plainauth: username already taken")

Functions

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 OAuthPopupAdditionalData

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

OAuthPopupAdditionalData returns application data from the initiating browser to the provider's exchange and profile callbacks. Values are untrusted input.

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 (*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(context.Context, string, ProfileUpdate, time.Time) error
	CreateCredentialSession(ctx context.Context, expectedHash string, session StoredSession) error
	ChangeCredential(ctx context.Context, userID, oldHash, newHash string, replacement *StoredSession) error
	FindAccountUser(ctx context.Context, email string) (User, error)
	SavePasswordResetToken(context.Context, PasswordResetToken) error
	FindPasswordResetToken(ctx context.Context, token string, now time.Time) (PasswordResetToken, error)
	FinishPasswordReset(ctx context.Context, token, newHash string, now time.Time, revokeSessions bool) error
	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 AdminBootstrapStore

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

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                                      string
	AdminRoles, AdminUserIDs                         []string
	Roles                                            map[string]AdminPermissions
	DefaultBanReason, BannedUserMessage              string
	DefaultBanDuration, ImpersonationSessionDuration time.Duration
	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 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 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(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) 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 trusted origins.

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) 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) 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.

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) ErrorPageURL

func (a *Auth) ErrorPageURL() string

ErrorPageURL is the host-controlled destination for browser protocol errors.

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) 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.

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) HasOAuthProvider

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

HasOAuthProvider reports whether an account provider ID belongs to a startup-configured OAuth integration. 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) 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) 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.

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 the configured key-set endpoint when it is served.

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) 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) 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) 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) 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) 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) 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"`
}

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

type ChangePasswordInput

type ChangePasswordInput struct {
	CurrentPassword, NewPassword string
	RevokeOtherSessions          bool
}

type ClientIPOptions

type ClientIPOptions struct {
	// TrustedProxies contains the CIDR ranges of reverse proxies which
	// overwrite or append the actual connection address to ForwardedHeader.
	TrustedProxies []netip.Prefix
	// ForwardedHeader defaults to X-Forwarded-For. Comma-separated hops are
	// processed from the application toward the client.
	ForwardedHeader 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 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 DeleteUserInput

type DeleteUserInput struct{ Password, Token, CallbackURL string }

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 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 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)
	MaxAttempts    int
	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 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 persists the provider reference and browser return destinations. Only the random browser binding is placed in a cookie.

func (EndpointContext) BeginEnterprisePostFlow

func (c EndpointContext) BeginEnterprisePostFlow(provider, reference, redirectURI string, signup bool) (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.

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, 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.

func (*EndpointContext) ConsumeEnterpriseFlow

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

ConsumeEnterpriseFlow accepts only a single use of the browser-bound state at the auth host and callback path originally selected during sign-in.

func (*EndpointContext) ConsumeEnterprisePostFlow

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

ConsumeEnterprisePostFlow consumes the RelayState received in the form body.

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) 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) 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) 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) 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) 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) SignUpAllowed

func (c EndpointContext) SignUpAllowed() bool

SignUpAllowed reports whether a plugin may create a new account.

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 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 FactorBackupOptions

type FactorBackupOptions struct {
	Amount, Length    int
	Generate          func(context.Context) ([]string, error)
	Store             string
	Encrypt, Decrypt  EmailOTPTransform
	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
}

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
	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 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
}

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 *bool
}

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

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 JWTKeyLookup

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

type JWTOptions

type JWTOptions struct {
	Algorithm                    string
	AdditionalAlgorithms         []string
	RSAModulusBits               int
	Issuer, Audience, JWKSPath   string
	Expiration, RotationInterval time.Duration
	GracePeriod                  *time.Duration
	DisableHeader                bool
	DefinePayload                func(context.Context, SessionResult) (map[string]any, error)
}

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 JWTStore

type JWTStore interface {
	ActiveJWTKey(ctx context.Context, algorithm string, now time.Time, generate func() (StoredJWTKey, error)) (StoredJWTKey, error)
	PublicJWTKeys(ctx context.Context, cutoff time.Time) ([]PublicJWTKey, error)
}

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 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, without its database namespace.

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.

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
}

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 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 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 only in
	// the local flow store 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"`
	PopupAdditionalData                               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 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
	LinkUserID, LinkSessionToken string
	IDTokenValidUntil            time.Time
	// IDTokenHash binds single-use grants independently of randomized storage encryption.
	IDTokenHash [32]byte
}

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           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)
	VerifyIDToken func(ctx context.Context, raw, nonce string) (OAuthProfile, time.Time, error)
	// DisableIDTokenSignIn closes the direct token grant 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)
	DisableRefresh         bool
	HTTPClient             *http.Client
	AllowVerifiedEmailLink 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 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 OAuthStore

type OAuthStore interface {
	SaveOAuthFlow(context.Context, OAuthFlow, time.Time) error
	ConsumeOAuthFlow(ctx context.Context, state, binding string, now time.Time) (OAuthFlow, error)
	CompleteOAuth(ctx context.Context, provider, subject string, tokens OAuthTokens, candidate User, session StoredSession, options OAuthLoginOptions) (User, bool, error)
}

OAuthStore supports shared, single-use flow state and atomic identity login. CompleteOAuth returns the actual account owner and whether it created a user.

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 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)
}

type Options

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

	// Logger receives diagnostics for this instance. A nil logger uses slog.Default().
	Logger *slog.Logger
	// 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
	// DisabledPaths hides exact HTTP paths relative to this instance’s mount.
	DisabledPaths []string
	// TrustedOrigins allows exact HTTP(S) origins and hostname or port wildcard patterns for browser requests and callbacks.
	TrustedOrigins []string
	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 string
	// 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

	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
	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
	// 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
	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. Supply RateLimitStorage to share them.
	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.
	RateLimitDefault *RateLimitRule
	RateLimitRules   map[string]*RateLimitRule
	ClientIP         ClientIPOptions
	SocialProviders  map[string]OAuthProvider
	// 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 link and its owner in verification storage.

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
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 PhoneOTPUse

type PhoneOTPUse struct {
	// ProviderProof binds an external verifier's answer to the exact local issuance.
	ProviderProof     string
	ProviderAccepted  bool
	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

	// OnRequest can reject an HTTP request before endpoint dispatch. Path is
	// relative to the auth mount. ClientIP follows the host's proxy policy.
	OnRequest func(RequestContext) error
	// 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

	ValidateStore func(Store) 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 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.

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 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.
	// 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 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 SessionRefreshStore

type SessionRefreshStore interface {
	RefreshSession(ctx context.Context, token string, previousExpiry, now, nextExpiry time.Time) (bool, error)
	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 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
}

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(context.Context, User, string, *StoredSession) error
	Credential(context.Context, string) (User, string, error)
	CreateSession(context.Context, StoredSession) error
	Session(context.Context, string) (StoredSession, User, error)
	DeleteSession(context.Context, string) error
	ListSessions(context.Context, string) ([]StoredSession, error)
	DeleteOtherSessions(context.Context, string, string) error
	DeleteUserSession(context.Context, string, 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.

type StoredJWTKey

type StoredJWTKey struct {
	PublicJWTKey
	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 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. Applications should use the authenticated admin service for subsequent grants. This operation is available only through Go and authctl.

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 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 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.

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
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.
jsjson
Package jsjson encodes Go values using JSON.stringify string escaping.
Package jsjson encodes Go values using JSON.stringify string escaping.
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.
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.
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.

Jump to

Keyboard shortcuts

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