authgen

package module
v0.0.0-...-2eeba3b Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: ISC Imports: 49 Imported by: 1 module, 0 packages

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

README

authgen

Backend-only authentication for Go, inspired by Auth.js. No UI, no frontend code: authgen gives you a REST API, a GraphQL API and a Go API, and your application owns the database. authgen never creates or alters tables.

go get github.com/mjahidhasand10/authgen

Requires Go 1.25+ and PostgreSQL 13+. Build with a current Go patch release (the module's toolchain line asks for go1.26.9, which has the latest standard-library security fixes).

Features

Sign-in methods

Method Notes
Email + password Argon2id, email verification, reset, change, breached-password check (HIBP k-anonymity)
Passkeys / WebAuthn Usernameless (discoverable) login with user verification, so the session starts at AAL2
Magic link Single-use, 15 min, optional frontend landing page to defeat link scanners
Email one-time code 6 digits, 10 min, 5 attempts
SMS one-time code E.164 normalization; you supply the SMS provider
OAuth 2.0 / OIDC PKCE (S256) + state + nonce; presets for Google, GitHub, Apple, Microsoft, Discord, GitLab, Okta, Auth0, Keycloak, Cognito, LinkedIn, Slack, Twitch, Facebook, Spotify, X, Zoom, Bitbucket; generic OIDC/OAuth; automatic access-token refresh
Enterprise SSO (SAML 2.0) Per-organization IdP connections routed by email domain, Redirect and POST bindings, JIT provisioning, replay cache, SP-initiated single logout
API keys / PATs Scoped, expiring, hashed, shown once
Anonymous / guest Upgrade in place (same user ID) via any other method

Multi-factor authentication: TOTP authenticator apps, WebAuthn security keys/passkeys, email or SMS codes, and one-time recovery codes. Also covers step-up reauthentication, session AAL/AMR tracking, and an optional policy that requires MFA for everyone or for selected users.

Security defaults (always on)

  • Opaque, revocable database sessions. Only a SHA-256 hash of each token is stored. Tokens rotate on login, MFA and reauthentication. Sessions have idle and absolute expiry, and users can list devices and revoke them.
  • Every token, code, recovery code and API key is stored hashed. Low-entropy codes use a keyed HMAC. Comparisons are constant-time.
  • TOTP secrets and provider tokens are encrypted with AES-256-GCM. Keys are derived with HKDF from your secrets, and secrets can be rotated.
  • __Host- cookies with HttpOnly, Secure and SameSite=Lax. Origin and Fetch-Metadata checks plus a signed double-submit CSRF token. Endpoints require a JSON content type.
  • Sliding-window rate limits per IP and per account, with lockout. They are store-backed, so they are shared across instances, and they fail closed: a limiter outage returns 503 instead of disabling throttling.
  • No account enumeration: sign-up, password reset and code requests give identical responses, and unknown accounts still incur dummy password hashing.
  • Pre-account-takeover defense:
    • Guest sign-ups stay pending until the email is verified.
    • Verification links work on the sign-up device, or anywhere if the account password is supplied, so a victim can't activate an attacker's password by clicking.
    • When the real owner proves an unverified address, everything an unverified party attached is wiped: password, phone, linked identities, API keys, passkeys, MFA factors and sessions.
  • An email or SMS code is never accepted as the second factor after signing in through that same channel. Email codes are also suspended for 24 hours after a password reset.
  • A new OAuth or SAML identity never auto-links to an existing verified account (as in Auth.js) unless you enable OAuth.AllowEmailLinking / SAML.AllowEmailLinking. Even then, OAuth requires a trusted email_verified claim, and a SAML IdP is trusted only for its connection's own domains. Public email domains (gmail.com, …) can't be assigned to a SAML connection.
  • SAML responses are bound to the browser that started the sign-in, and OAuth state is cookie-bound. This prevents login CSRF and "finish my sign-in" hijacks.
  • TOTP replay protection, single-use MFA challenges, attempt limits, WebAuthn clone detection and open-redirect protection.
  • Sensitive operations (changing password or MFA, API keys, unlinking, deleting the account) require a fresh session. For users with MFA that also means AAL2.
  • Stored password hashes with out-of-range Argon2 parameters are rejected, so a corrupted or imported hash can't exhaust memory.
  • Timing doesn't reveal whether an account exists:
    • Emails and SMS are sent in the background (call a.Shutdown(ctx) on exit; SyncNotifications makes them synchronous).
    • The dummy password check uses your configured Argon2 settings.
  • Password reset validates and rate-limits the token before calling the breach checker.
  • New-device sign-in alerts by email.
  • Audit events for every security-relevant action (OnEvent), optionally stored in an audit_events table.

1. Create the tables (your way)

authgen only runs SELECT/INSERT/UPDATE/DELETE. Pick one of these:

# a) migration files for your tool: plain | goose | migrate | atlas | dbmate
go run github.com/mjahidhasand10/authgen/cmd/authgen@latest schema generate --format goose --out ./migrations

# b) copy the reference SQL
cat schema/postgres/001_authgen_init.up.sql

# c) map onto tables you already have (same flags work for generate/print)
authgen schema generate --format migrate --table users=users --column users.email=email_address --skip users

# verify a database (read-only)
authgen schema check --database-url "$DATABASE_URL"

Use the same mapping in code:

Schema: schema.Mapping{
    Tables:  map[string]string{"users": "users"},
    Columns: map[string]map[string]string{"users": {"email": "email_address"}},
},

A mapped users table must have a uuid id and the columns listed by authgen schema tables.

2. Configure

a, err := authgen.New(authgen.Config{
    Pool:           pool,                                   // your *pgxpool.Pool
    BaseURL:        "https://api.example.com/auth",         // where the REST handler is mounted
    Secrets:        []string{os.Getenv("AUTHGEN_SECRET")},  // >= 32 bytes; add old ones to rotate
    AppName:        "Acme",
    TrustedOrigins: []string{"https://app.example.com"},    // your frontend(s)
    URLs: authgen.URLs{
        SignIn:        "https://app.example.com/",
        Error:         "https://app.example.com/auth/error",
        MFA:           "https://app.example.com/auth/mfa",
        ResetPassword: "https://app.example.com/reset",
    },
    Methods: authgen.Methods{Password: true, MagicLink: true, EmailOTP: true, SMSOTP: true,
        Passkey: true, Anonymous: true, APIKeys: true, SAML: true},
    OAuth: authgen.OAuthConfig{Providers: []*oauth.Provider{
        oauth.Google(id, secret), oauth.GitHub(id, secret), oauth.Microsoft(id, secret, "common"),
    }},
    WebAuthn: authgen.WebAuthnConfig{RPID: "example.com", RPOrigins: []string{"https://app.example.com"}},
    SAML:     authgen.SAMLConfig{Certificate: spCertPEM, PrivateKey: spKeyPEM},
    Email:    myEmailSender, // implements notify.EmailSender (SES, Postmark, ...)
    SMS:      mySMSSender,   // implements notify.SMSSender (Twilio, ...)
    OnEvent:  func(ctx context.Context, e authgen.Event) { auditLog(e) },
})
if err := a.CheckSchema(ctx); err != nil { log.Fatal(err) } // read-only

3. Mount

mux := http.NewServeMux()
rest.Mount(mux, "/auth", a)                                         // REST + redirect endpoints
mux.Handle("/auth/graphql", graphql.MustNew(a, graphql.Options{}))  // optional GraphQL

mux.Handle("GET /api/me", a.RequireSession(meHandler))             // signed-in users
mux.Handle("POST /api/pay", a.RequireMFA(payHandler))              // AAL2 sessions only
mux.Handle("GET /api/data", a.RequireAPIKey("read")(dataHandler))  // API keys with scope
// a.Middleware(next) attaches the principal when present; authgen.UserFromContext(ctx)

go func() { for range time.Tick(time.Hour) { a.Cleanup(ctx) } }()

A runnable example is in examples/server.

Hardening options

authgen.Config{
    MFA:           authgen.MFAConfig{Require: true},                 // or RequireFor: func(ctx, u) bool { return isAdmin(u) }
    BotProtection: authgen.BotProtectionConfig{Verifier: captcha.Turnstile(secret)}, // or HCaptcha / ReCaptchaV3
    SMSPolicy:     authgen.SMSPolicyConfig{AllowedCountryCodes: []string{"+1", "+44"}, DailyLimit: 500},
    Audit:         authgen.AuditConfig{Enabled: true},              // needs the audit_events table
    Templates: authgen.Templates{Email: func(ctx context.Context, m *notify.Email) {
        m.Subject, m.Text = render(m.Kind, m.Locale, m)              // your templates and translations
    }},
    OAuth:         authgen.OAuthConfig{AllowEmailLinking: false, StoreTokens: true},
    RateLimit:     authgen.RateLimitConfig{FailOpen: false},          // default: fail closed
    Password:      authgen.PasswordConfig{BreachCheckFailClosed: true},
    Alerts:        authgen.AlertsConfig{DisableNewDevice: false},
    WebAuthn:      authgen.WebAuthnConfig{Attestation: "direct", AllowedAAGUIDs: []string{"…"}, MDS: mdsProvider},
}
  • Enforced MFA. Users without a factor can still sign in, but their session only allows enrollment. Sign-in responses include "mfaEnrollmentRequired": true, and the Require* middlewares answer mfa_enrollment_required until a factor is enrolled. The /auth/* account endpoints (enrollment, password change, linking, and so on) stay available to such sessions.
  • CAPTCHA. Clients send the token in X-Captcha-Token. Protected by default: sign-up, password reset, magic link, email/SMS codes, guest sessions and verification resends. Add "signin" to also protect password sign-in.
  • Behind a proxy. Set TrustProxyHeaders and either TrustedProxyHops (default 1) or TrustedProxies (CIDRs). The client IP is read from the right of X-Forwarded-For; the leftmost entries are client-controlled.
  • Remember me. Send "rememberMe": false (or ?rememberMe=false on redirect flows) to get a browser-session cookie and a 12-hour session.
  • New-device alerts. Browsers get a long-lived device cookie and native apps can send X-Device-Id. The first device is recorded silently; later unknown devices trigger an email and a new_device_sign_in event.

Clients

Browsers (cookie mode, default). authgen sets an HttpOnly session cookie. Call GET /auth/csrf once and send the token as X-CSRF-Token on every POST/PATCH/DELETE. The frontend and API must be same-site (for example app.example.com and api.example.com), or you must set Session.SameSite = http.SameSiteNoneMode. Use fetch(..., {credentials: "include"}).

The same CSRF check applies to your own cookie-authenticated routes behind a.Middleware / a.RequireSession / a.RequireMFA; send the same header there. RequireMFA returns mfa_required for users with no second factor enrolled, so route those users to enrollment.

Mobile, native and server clients (token mode). Send X-Auth-Mode: token. Session tokens come back in the JSON token field; use Authorization: Bearer <token>. No CSRF token is needed.

Native apps and redirect flows (OAuth, SAML, magic links). List your app's redirect URIs in NativeRedirectURIs (e.g. com.example.app:/auth). Start the flow with that callbackUrl and a PKCE codeChallenge (S256 of a random verifier). authgen redirects to com.example.app:/auth?code=…, never setting cookies. The app redeems the code once, within 2 minutes, at POST /auth/token/exchange {"code","codeVerifier"} and receives a token-mode response. An intercepted redirect is useless without the verifier. Redirect URIs match on exact path segments (/cb allows /cb/x, never /cbx or /cb/../x), and the session behind an unredeemed code expires with the code.

Sign-in responses are either {"status":"authenticated", ...} or {"status":"mfa_required","mfa":{"challenge":"…","methods":["totp","webauthn","recovery_code"]}}. In the second case, complete with POST /auth/mfa/verify.

The full REST API is described as OpenAPI 3.1 at GET /auth/openapi.json (transport/rest/openapi.json).

REST endpoints (prefix /auth)
GET /csrf, GET /providers, GET /session, POST /signout basics
GET /sessions, DELETE /sessions/{id}, POST /sessions/revoke-others device management
POST /signup, POST /signin/password, GET|POST /verify-email, POST /verify-email/resend password
POST /password/forgot, POST /password/reset, POST /password/change, POST /email/change, GET|POST /email/change/confirm account recovery and changes
POST /magic-link, GET|POST /magic-link/verify magic link
POST /otp/email/send|verify, POST /otp/sms/send|verify, POST /phone, POST /phone/confirm one-time codes
GET /signin/{provider}, GET|POST /callback/{provider}, POST /link/{provider}, GET /accounts, DELETE /accounts/{id} OAuth/OIDC
POST /token/exchange native apps
POST /passkeys/login/options, POST /passkeys/login, POST /passkeys/register/options, POST /passkeys/register, GET /passkeys, PATCH|DELETE /passkeys/{id} passkeys
GET /mfa, POST /mfa/verify, POST /mfa/send, POST /mfa/webauthn/options, POST /mfa/totp/enroll|confirm, DELETE /mfa/totp, POST /mfa/recovery-codes, POST|DELETE /mfa/channels/{email|sms} MFA
POST /reauthenticate, POST /reauthenticate/send, POST /reauthenticate/webauthn/options step-up
POST /anonymous guest session
POST /biometric/challenge, POST /biometric/signin, POST /biometric/enroll/challenge, POST /biometric/enroll dedicated biometric scanners
GET|POST /api-keys, DELETE /api-keys/{id} API keys
GET|POST /sso, GET /sso/metadata/{id}, POST /sso/acs/{id}, GET /sso/post, GET|POST /sso/slo/{id} SAML SSO
GET /openapi.json API description
PATCH /user, DELETE /user profile

The GraphQL schema is in transport/graphql/schema.graphql. It covers every JSON flow. Browser redirects (OAuth/SAML callbacks, email links) always use REST. Each request resolves the session once and is limited to 20 root fields and 1 mutation (Options.MaxRootFields / MaxMutations), so aliases can't multiply expensive work.

Email verification. GET /verify-email and POST /verify-email work without extra input on the device that signed up. On another device, send {"token", "password"}; otherwise the error is password_required and the link stays valid.

Passkeys need ~20 lines of browser JavaScript

WebAuthn can only run in the browser. authgen produces and verifies the JSON; your frontend calls the platform API:

// login (usernameless)
const { options, ceremonyId } = await post("/auth/passkeys/login/options");
const cred = await navigator.credentials.get({
  publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(options.publicKey),
});
await post("/auth/passkeys/login", { ceremonyId, response: cred.toJSON() });

// registration (signed in)
const opts = await post("/auth/passkeys/register/options");
const created = await navigator.credentials.create({
  publicKey: PublicKeyCredential.parseCreationOptionsFromJSON(opts.publicKey),
});
await post("/auth/passkeys/register", { name: "MacBook", response: created.toJSON() });

Passkey-first sign-up: POST /auth/anonymous, then register a passkey. The guest becomes a regular user. For passkey autofill, request POST /auth/passkeys/login/options?mediation=conditional and pass mediation: "conditional" to navigator.credentials.get.

Biometrics: fingerprint, face, iris

authgen supports two kinds of biometric sign-in. Neither ever receives or stores fingerprints, iris codes or face templates, because biometric data cannot be revoked if leaked and is regulated (GDPR special category, BIPA).

1. On the user's own devices (passkeys). The phone's or laptop's sensor checks the finger or face (Touch ID, Face ID, Windows Hello incl. iris, Android biometrics) and authgen verifies the passkey signature. To use the same finger on every device:

  • Synced passkeys. iCloud Keychain, Google Password Manager, Windows or a password manager sync the passkey to the user's other devices, where they unlock it with their own finger. GET /passkeys shows backupEligible/backedUp for synced credentials.
  • New or borrowed devices. The browser offers "use a phone": scan the QR code and touch the phone's sensor. No setup is needed.
  • Several passkeys per account. Users can register one per device.
WebAuthn: authgen.WebAuthnConfig{
    RPID: "example.com",
    RequireUserVerification: true, // always ask for the fingerprint/face/iris (or device PIN)
    PlatformOnly: true,            // only the device's built-in sensor, not USB keys or another phone
},

Sessions verified this way carry uv in their AMR. WebAuthn deliberately doesn't reveal whether the user used a biometric or the device PIN. PlatformOnly also blocks registering through "use a phone", so leave it off if users should be able to add passkeys that way.

2. Dedicated scanners (kiosks, attendance, door access). Your scanner vendor's SDK matches the person against the vendor's template store. Your scanner gateway then signs a short-lived match token, and authgen verifies it. Only the vendor's opaque person id is stored, as a linked account (biometric:scanner).

v, _ := biometric.NewJWTVerifier("authgen:acme-hq",
    biometric.Device{ID: "lobby-1", Key: lobbyPublicKey, Modalities: []string{biometric.Fingerprint, biometric.Iris}},
)
authgen.Config{Methods: authgen.Methods{Biometric: true}, Biometric: authgen.BiometricConfig{Verifier: v}}
  1. Kiosk: POST /auth/biometric/challenge returns a single-use nonce (2 minutes).
  2. The scanner recognizes the person, and the gateway signs biometric.Sign(deviceKey, "lobby-1", "authgen:acme-hq", biometric.Match{Subject: vendorPersonID, Modality: biometric.Fingerprint, Nonce: nonce}, 30*time.Second).
  3. Kiosk: POST /auth/biometric/signin {"assertion": "<token>"} signs the user in (AMR fpt, iris or face; AAL1, and the user's MFA policy still applies).

Enrollment links a person to their account: a signed-in user with a fresh session calls POST /auth/biometric/enroll/challenge, scans, and posts the token to POST /auth/biometric/enroll. HR onboarding can use a.LinkBiometricSubject(ctx, userID, vendorPersonID) instead. Unlink with DELETE /auth/accounts/{id}.

Protections:

  • tokens must be signed by a registered device key (ES256 or EdDSA)
  • tokens are bound to your audience, at most 60 seconds old, and limited to the device's allowed modalities
  • each challenge works once and only for its own purpose (sign-in vs. one user's enrollment)
  • one scanner identity can't be linked to two accounts
  • revoke a scanner by removing its key from the verifier
SAML connections

Connections are admin data. Manage them through the admin API below or the Go API:

conn, _ := a.CreateSAMLConnection(ctx, authgen.SAMLConnectionInput{
    OrgID: "acme", Domains: []string{"acme.com"}, IdPMetadataXML: xml, Enabled: true,
})
// Give the IdP: GET /auth/sso/metadata/{conn.ID}
// Users start at: GET /auth/sso?email=jane@acme.com

For IdPs that only accept the POST binding, /sso redirects to a single-use /sso/post page that auto-submits the request. It is served with a strict CSP and is the only HTML authgen serves. When a SAML session signs out, POST /signout returns the IdP's logoutUrl (SP-initiated single logout). IdP-initiated logout requests are not supported.

Admin API

mux.Handle("/admin/auth/", http.StripPrefix("/admin/auth", admin.New(a, admin.Options{
    Authorize: func(r *http.Request, p *authgen.Principal) bool { return isAdmin(p.User) },
})))

GET /users?search=&after=, GET /users/{id}, POST /users/{id}/disable|enable, DELETE /users/{id}, DELETE /users/{id}/sessions, DELETE /users/{id}/mfa[?passkeys=true], GET|POST /saml-connections, PUT|DELETE /saml-connections/{id}, GET /audit.

Every admin request needs a session that passes Authorize, has verified a second factor, authenticated recently, and passes CSRF. API keys are rejected. Each change is recorded as an admin_action event naming the admin. Impersonation is deliberately not offered.

Go API

Every flow is also a method on *authgen.Auth, for apps that want their own routes: SignUp, SignInWithPassword, RequestMagicLink, VerifyEmailOTP, BeginOAuth/HandleOAuthCallback, BeginPasskeyLogin/FinishPasskeyLogin, VerifyMFA, Reauthenticate, CreateAPIKey, ValidateSession, RevokeSession, and so on. Attach client metadata with authgen.WithRequestMeta(ctx, ...) or a.ContextWithRequest(r).

Testing

go test ./...                                   # memstore + httptest; no network
AUTHGEN_EMBEDDED_PG=1 go test ./store/postgres/ # downloads and runs a real PostgreSQL
AUTHGEN_TEST_DATABASE_URL=postgres://... go test ./store/postgres/

The suite drives every flow over HTTP. It includes:

  • a mock OIDC provider, including Microsoft-style tenant issuers and token refresh
  • offline tests for every provider preset
  • a software WebAuthn authenticator
  • a SAML IdP covering the Redirect and POST bindings and logout
  • fuzz targets for input normalization, redirect validation, hash parsing and decryption
  • benchmarks

The store conformance suite runs against both memstore and PostgreSQL (default mapping, custom mapping, search_path). CI runs Go 1.25 and 1.26 with -race.

License

ISC, the same license as Auth.js.

Documentation

Overview

Package authgen is a backend-only authentication library for Go, inspired by Auth.js. It provides email/password, passkeys (WebAuthn), magic links, email/SMS one-time codes, OAuth 2.0/OIDC, SAML SSO, API keys and anonymous sessions, with MFA (TOTP, WebAuthn, email/SMS codes, recovery codes) on top of opaque, revocable database sessions.

The application owns the database: authgen runs only DML against the PostgreSQL pool it is given and never creates or alters tables. See the schema package and cmd/authgen to generate the DDL.

Example

A typical production setup: your pool, your tables, REST mounted at /auth.

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/jackc/pgx/v5/pgxpool"

	"github.com/mjahidhasand10/authgen"
	"github.com/mjahidhasand10/authgen/notify"
	"github.com/mjahidhasand10/authgen/providers/oauth"
	"github.com/mjahidhasand10/authgen/transport/rest"
)

type noopEmail struct{}

func (noopEmail) SendEmail(context.Context, notify.Email) error { return nil }

func main() {
	ctx := context.Background()
	pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	a, err := authgen.New(authgen.Config{
		Pool:           pool,
		BaseURL:        "https://api.example.com/auth",
		Secrets:        []string{os.Getenv("AUTHGEN_SECRET")},
		TrustedOrigins: []string{"https://app.example.com"},
		Methods:        authgen.Methods{Password: true, MagicLink: true, Passkey: true},
		WebAuthn:       authgen.WebAuthnConfig{RPID: "example.com"},
		OAuth:          authgen.OAuthConfig{Providers: []*oauth.Provider{oauth.Google("id", "secret")}},
		Email:          noopEmail{}, // your provider
		MFA:            authgen.MFAConfig{Require: true},
	})
	if err != nil {
		log.Fatal(err)
	}
	if err := a.CheckSchema(ctx); err != nil { // read-only
		log.Fatal(err)
	}
	mux := http.NewServeMux()
	rest.Mount(mux, "/auth", a)
	mux.Handle("GET /api/me", a.RequireSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, authgen.UserFromContext(r.Context()).ID)
	})))
	log.Fatal(http.ListenAndServe(":8080", mux))
}
Example (SchemaMapping)

Map authgen onto an existing users table and generate the remaining DDL for your migration tool.

package main

import (
	"fmt"

	"github.com/mjahidhasand10/authgen/schema"
)

func main() {
	m := schema.Mapping{
		Tables:  map[string]string{"users": "users"},
		Columns: map[string]map[string]string{"users": {"email": "email_address"}},
	}
	r := m.MustResolve()
	fmt.Println(r.Table("users"), r.Col("users", "email"), r.Table("sessions"))
}
Output:
"users" "email_address" "authgen_sessions"

Index

Examples

Constants

View Source
const (
	MFATOTP     = "totp"
	MFAWebAuthn = "webauthn"
	MFARecovery = "recovery_code"
	MFAEmail    = "email"
	MFASMS      = "sms"
)

MFA method identifiers.

View Source
const (
	CaptchaHeader  = "X-Captcha-Token"
	DeviceIDHeader = "X-Device-Id"
)

Header names read by MetaFromRequest.

View Source
const (
	AMRPassword  = "pwd"
	AMRMagicLink = "magic_link"
	AMREmailOTP  = "email_otp"
	AMRSMSOTP    = "sms_otp"
	AMRPasskey   = "passkey"
	// AMRUserVerified marks that a WebAuthn authenticator verified the user
	// on the device (fingerprint, face, iris or device PIN; WebAuthn does not
	// reveal which).
	AMRUserVerified = "uv"
	AMRAnonymous    = "anonymous"
	AMRTOTP         = "totp"
	AMRWebAuthn     = "webauthn"
	AMRRecovery     = "recovery_code"
	AMRMFAEmail     = "mfa_email"
	AMRMFASMS       = "mfa_sms"
)

Authentication method references recorded on sessions (AMR).

View Source
const CSRFHeader = "X-CSRF-Token"

CSRFHeader is the request header carrying the double-submit CSRF token.

View Source
const EmailFactorLockout = 24 * time.Hour

EmailFactorLockout is how long email codes cannot serve as a second factor after a password reset (which already proved only the inbox).

View Source
const ExchangeTTL = 2 * time.Minute

ExchangeTTL is the lifetime of an exchange code.

Variables

View Source
var (
	ErrInvalidRequest       = newErr("invalid_request", http.StatusBadRequest, "The request is invalid.")
	ErrInvalidCredentials   = newErr("invalid_credentials", http.StatusUnauthorized, "Invalid credentials.")
	ErrUnauthorized         = newErr("unauthorized", http.StatusUnauthorized, "Authentication required.")
	ErrForbidden            = newErr("forbidden", http.StatusForbidden, "Not allowed.")
	ErrAccessDenied         = newErr("access_denied", http.StatusForbidden, "Sign-in was denied.")
	ErrInvalidToken         = newErr("invalid_token", http.StatusBadRequest, "The token or code is invalid or has expired.")
	ErrRateLimited          = newErr("rate_limited", http.StatusTooManyRequests, "Too many attempts. Try again later.")
	ErrConflict             = newErr("conflict", http.StatusConflict, "The resource already exists.")
	ErrNotFound             = newErr("not_found", http.StatusNotFound, "Not found.")
	ErrEmailNotVerified     = newErr("email_not_verified", http.StatusForbidden, "Email address is not verified.")
	ErrMethodDisabled       = newErr("method_disabled", http.StatusNotFound, "This sign-in method is not enabled.")
	ErrReauthRequired       = newErr("reauthentication_required", http.StatusForbidden, "Please confirm your identity again.")
	ErrMFARequired          = newErr("mfa_required", http.StatusForbidden, "A second factor is required.")
	ErrMFAEnrollment        = newErr("mfa_enrollment_required", http.StatusForbidden, "Set up two-step verification to continue.")
	ErrUnavailable          = newErr("temporarily_unavailable", http.StatusServiceUnavailable, "The service is temporarily unavailable. Try again shortly.")
	ErrPasswordRequired     = newErr("password_required", http.StatusForbidden, "Enter your password to confirm this email address, or open the link on the device you signed up from.")
	ErrCaptcha              = newErr("captcha_required", http.StatusForbidden, "Please complete the bot check and try again.")
	ErrAccountNotLinked     = newErr("account_not_linked", http.StatusConflict, "This email is already used by another sign-in method. Sign in with that method and link this account from your settings.")
	ErrWeakPassword         = newErr("weak_password", http.StatusBadRequest, "The password does not meet the requirements.")
	ErrBreachedPassword     = newErr("breached_password", http.StatusBadRequest, "This password has appeared in a data breach. Choose a different password.")
	ErrCSRF                 = newErr("csrf", http.StatusForbidden, "Cross-site request rejected.")
	ErrLastSignInMethod     = newErr("last_sign_in_method", http.StatusConflict, "You cannot remove your only sign-in method.")
	ErrInternal             = newErr("internal_error", http.StatusInternalServerError, "Something went wrong.")
	ErrUnsupportedMediaType = newErr("unsupported_media_type", http.StatusUnsupportedMediaType, "Content-Type must be application/json.")
)

Sentinel errors.

View Source
var DefaultRateLimits = map[string]ratelimit.Rule{
	"signin:ip":       {Limit: 50, Window: 15 * time.Minute},
	"signin:account":  {Limit: 10, Window: 15 * time.Minute},
	"signup:ip":       {Limit: 10, Window: time.Hour},
	"email:send":      {Limit: 5, Window: time.Hour},
	"email:send:ip":   {Limit: 20, Window: time.Hour},
	"sms:send":        {Limit: 5, Window: time.Hour},
	"sms:send:ip":     {Limit: 10, Window: time.Hour},
	"otp:verify":      {Limit: 10, Window: 15 * time.Minute},
	"mfa:verify":      {Limit: 10, Window: 15 * time.Minute},
	"reauth":          {Limit: 10, Window: 15 * time.Minute},
	"anonymous:ip":    {Limit: 20, Window: time.Hour},
	"oauth:ip":        {Limit: 60, Window: 15 * time.Minute},
	"apikey:ip":       {Limit: 600, Window: time.Minute},
	"webauthn:ip":     {Limit: 60, Window: 15 * time.Minute},
	"saml:ip":         {Limit: 60, Window: 15 * time.Minute},
	"biometric:ip":    {Limit: 120, Window: 15 * time.Minute},
	"token:verify:ip": {Limit: 30, Window: 15 * time.Minute},
	"exchange:ip":     {Limit: 30, Window: 15 * time.Minute},
}

DefaultRateLimits are the built-in rate limit rules.

Functions

func AnonymousUserID

func AnonymousUserID(u *store.User) string

AnonymousUserID returns the user ID if u is a guest, else "".

func HasAMR

func HasAMR(s *store.Session, method string) bool

HasAMR reports whether the session used the given authentication method.

func HasScope

func HasScope(k *store.APIKey, scope string) bool

HasScope reports whether the key carries scope (or the "*" wildcard).

func NormalizeEmail

func NormalizeEmail(s string) (string, bool)

NormalizeEmail lower-cases and validates an email address.

func NormalizePhone

func NormalizePhone(s string) (string, bool)

NormalizePhone strips formatting and validates an E.164 phone number.

func UserFromContext

func UserFromContext(ctx context.Context) *store.User

UserFromContext returns the authenticated user, if any.

func ValidCodeChallenge

func ValidCodeChallenge(c string) bool

ValidCodeChallenge reports whether c is a well-formed S256 PKCE challenge.

func WithActor

func WithActor(ctx context.Context, userID string) context.Context

WithActor records which administrator performs the operations made with ctx; it is written to admin_action events. transport/admin sets it.

func WithPrincipal

func WithPrincipal(ctx context.Context, p *Principal) context.Context

WithPrincipal attaches p to ctx.

func WithRequestMeta

func WithRequestMeta(ctx context.Context, m RequestMeta) context.Context

WithRequestMeta attaches request metadata to ctx. The REST and GraphQL handlers do this automatically; call it when using the Go API directly.

func WithSessionOptions

func WithSessionOptions(ctx context.Context, o SessionOptions) context.Context

WithSessionOptions attaches options for sessions created with ctx.

func WriteError

func WriteError(w http.ResponseWriter, err error)

WriteError writes a client-safe JSON error.

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, v any)

WriteJSON writes v as JSON with no-store caching.

Types

type APIKeyConfig

type APIKeyConfig struct {
	// Prefix is the visible key prefix. Default "ag".
	Prefix string
	// MaxTTL caps key lifetime. Zero means keys may be non-expiring.
	MaxTTL time.Duration
	// AllowedScopes restricts the scopes keys may carry. Empty allows any.
	AllowedScopes []string
}

APIKeyConfig controls personal access tokens.

type APIKeyInput

type APIKeyInput struct {
	Name      string
	Scopes    []string
	ExpiresIn time.Duration // 0 = no expiry (unless APIKeys.MaxTTL is set)
}

APIKeyInput describes a new API key.

type APIKeyView

type APIKeyView struct {
	ID         string     `json:"id"`
	Name       string     `json:"name"`
	Prefix     string     `json:"prefix"` // shown to help users identify keys
	Scopes     []string   `json:"scopes"`
	ExpiresAt  *time.Time `json:"expiresAt"`
	LastUsedAt *time.Time `json:"lastUsedAt"`
	RevokedAt  *time.Time `json:"revokedAt"`
	CreatedAt  time.Time  `json:"createdAt"`
}

APIKeyView is the client-facing view of an API key (never the secret).

type AccountView

type AccountView struct {
	ID        string    `json:"id"`
	Provider  string    `json:"provider"`
	Type      string    `json:"type"`
	CreatedAt time.Time `json:"createdAt"`
}

AccountView is the client-facing view of a linked identity.

type AlertsConfig

type AlertsConfig struct {
	// DisableNewDevice turns off "new sign-in to your account" emails.
	DisableNewDevice bool
	// KnownDeviceTTL is how long a device stays recognized. Default 180 days.
	KnownDeviceTTL time.Duration
}

AlertsConfig controls security notifications.

type AnonymousConfig

type AnonymousConfig struct {
	// TTL of inactivity after which unconverted guests are removed by
	// Cleanup (guests with a session used within TTL are kept). Default 30 days.
	TTL time.Duration
}

AnonymousConfig controls guest users.

type AuditConfig

type AuditConfig struct {
	// Enabled stores events in the audit_events table.
	Enabled bool
	// Skip lists event types not stored. Default: rate_limited, which
	// unauthenticated clients can trigger at will. OnEvent still receives
	// every event.
	Skip []EventType
}

AuditConfig controls the built-in audit table.

type Auth

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

Auth is the authgen engine. It is safe for concurrent use.

func New

func New(cfg Config) (*Auth, error)

New validates cfg and returns an Auth.

func (*Auth) AccountTokens

func (a *Auth) AccountTokens(ctx context.Context, userID, provider string) (*oauth2.Token, error)

AccountTokens decrypts the stored provider tokens of a linked account (requires OAuth.StoreTokens). Use them to call provider APIs on behalf of the user.

func (*Auth) AdminDeleteUser

func (a *Auth) AdminDeleteUser(ctx context.Context, actorID, userID string) error

AdminDeleteUser deletes a user.

func (*Auth) AdminResetMFA

func (a *Auth) AdminResetMFA(ctx context.Context, actorID, userID string, includePasskeys bool) error

AdminResetMFA removes a user's second factors (authenticator app, email/SMS channels, recovery codes and, if includePasskeys, WebAuthn credentials) and signs out all their sessions. Use it for account recovery after verifying the user's identity out of band.

func (*Auth) AdminRevokeSessions

func (a *Auth) AdminRevokeSessions(ctx context.Context, actorID, userID string) (int64, error)

AdminRevokeSessions signs a user out everywhere.

func (*Auth) AdminSetDisabled

func (a *Auth) AdminSetDisabled(ctx context.Context, actorID, userID string, disabled bool) error

AdminSetDisabled disables (and signs out) or re-enables a user.

func (*Auth) Authenticate

func (a *Auth) Authenticate(r *http.Request) (*Principal, error)

Authenticate resolves the request's principal from the session cookie, a bearer session token, or a bearer API key.

func (*Auth) AuthenticateAPIKey

func (a *Auth) AuthenticateAPIKey(ctx context.Context, key string) (*store.APIKey, *store.User, error)

AuthenticateAPIKey validates an API key and returns it with its owner.

func (*Auth) BeginBiometricEnrollment

func (a *Auth) BeginBiometricEnrollment(ctx context.Context, s *store.Session, u *store.User) (*BiometricChallenge, error)

BeginBiometricEnrollment returns a challenge for linking the signed-in user to their scanner identity. Requires a fresh session.

func (*Auth) BeginBiometricSignIn

func (a *Auth) BeginBiometricSignIn(ctx context.Context) (*BiometricChallenge, error)

BeginBiometricSignIn returns a challenge for a scanner sign-in.

func (*Auth) BeginOAuth

func (a *Auth) BeginOAuth(ctx context.Context, providerID string, opts OAuthStartOptions) (*OAuthStart, error)

BeginOAuth starts an OAuth/OIDC authorization-code flow with PKCE, state and nonce.

func (*Auth) BeginPasskeyLogin

func (a *Auth) BeginPasskeyLogin(ctx context.Context) (options *protocol.CredentialAssertion, ceremonyID string, err error)

BeginPasskeyLogin starts a usernameless (discoverable credential) login. Returns the options for navigator.credentials.get() and a ceremony ID the client sends back to FinishPasskeyLogin.

func (*Auth) BeginPasskeyLoginWithOptions

func (a *Auth) BeginPasskeyLoginWithOptions(ctx context.Context, o PasskeyLoginOptions) (options *protocol.CredentialAssertion, ceremonyID string, err error)

BeginPasskeyLoginWithOptions is BeginPasskeyLogin with options.

func (*Auth) BeginPasskeyRegistration

func (a *Auth) BeginPasskeyRegistration(ctx context.Context, s *store.Session, u *store.User) (*protocol.CredentialCreation, error)

BeginPasskeyRegistration starts registering a passkey / security key for the signed-in user. Returns PublicKeyCredentialCreationOptions to pass to navigator.credentials.create(). Requires a fresh session.

func (*Auth) BeginSAML

func (a *Auth) BeginSAML(ctx context.Context, opts SAMLStartOptions) (*SAMLStart, error)

BeginSAML starts SP-initiated SSO.

func (*Auth) BeginTOTPEnrollment

func (a *Auth) BeginTOTPEnrollment(ctx context.Context, s *store.Session, u *store.User) (*TOTPEnrollment, error)

BeginTOTPEnrollment generates a new TOTP secret (unconfirmed). Requires a fresh session.

func (*Auth) BeginWebAuthnMFA

func (a *Auth) BeginWebAuthnMFA(ctx context.Context, challengeToken string) (*protocol.CredentialAssertion, error)

BeginWebAuthnMFA returns assertion options for completing a pending MFA challenge with a security key or passkey.

func (*Auth) BeginWebAuthnReauth

func (a *Auth) BeginWebAuthnReauth(ctx context.Context, s *store.Session, u *store.User) (*protocol.CredentialAssertion, error)

BeginWebAuthnReauth returns assertion options for reauthenticating the current session with a passkey or security key.

func (*Auth) ChangePassword

func (a *Auth) ChangePassword(ctx context.Context, s *store.Session, u *store.User, currentPassword, newPassword string) error

ChangePassword changes the password of a signed-in user. If the user already has a password, currentPassword must match; otherwise the session must be fresh. Other sessions are revoked.

func (*Auth) CheckCSRF

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

CheckCSRF protects state-changing requests:

  • Origin (or Sec-Fetch-Site) must be BaseURL's origin or a trusted origin.
  • Requests authenticated by the session cookie must carry a valid double-submit token in X-CSRF-Token matching the CSRF cookie (unless CSRF.DisableToken). Bearer-token requests are exempt.

func (*Auth) CheckSchema

func (a *Auth) CheckSchema(ctx context.Context) error

CheckSchema verifies (read-only) that the database has every table and column authgen needs. Only available with the PostgreSQL store. Tables for disabled features are skipped.

func (*Auth) Cleanup

func (a *Auth) Cleanup(ctx context.Context) (CleanupResult, error)

Cleanup deletes expired sessions and tokens, stale rate-limit counters, and guest users older than Anonymous.TTL. Run it periodically (e.g. hourly) from a cron job or a goroutine.

func (*Auth) ClearMFACookie

func (a *Auth) ClearMFACookie(w http.ResponseWriter)

ClearMFACookie deletes the MFA challenge cookie.

func (*Auth) ClearOAuthCookie

func (a *Auth) ClearOAuthCookie(w http.ResponseWriter)

ClearOAuthCookie expires the OAuth state cookie.

func (*Auth) ClearSAMLCookie

func (a *Auth) ClearSAMLCookie(w http.ResponseWriter)

ClearSAMLCookie expires the SSO binding cookie.

func (*Auth) ClearSessionCookie

func (a *Auth) ClearSessionCookie(w http.ResponseWriter)

ClearSessionCookie deletes the session cookie.

func (*Auth) Config

func (a *Auth) Config() Config

Config returns a copy of the effective configuration.

func (*Auth) ConfirmEmailChange

func (a *Auth) ConfirmEmailChange(ctx context.Context, token string) (*store.User, error)

ConfirmEmailChange applies an email change.

func (*Auth) ConfirmPhone

func (a *Auth) ConfirmPhone(ctx context.Context, u *store.User, phone, code string) (*store.User, error)

ConfirmPhone verifies the code sent by RequestPhoneVerification.

func (*Auth) ConfirmTOTPEnrollment

func (a *Auth) ConfirmTOTPEnrollment(ctx context.Context, s *store.Session, u *store.User, code string) (recoveryCodes []string, err error)

ConfirmTOTPEnrollment verifies the first code and activates TOTP. If this is the user's first factor, recovery codes are generated and returned (show them once). The session is upgraded to AAL2.

func (*Auth) ContextWithRequest

func (a *Auth) ContextWithRequest(r *http.Request) context.Context

ContextWithRequest returns ctx with metadata from r attached.

func (*Auth) CreateAPIKey

func (a *Auth) CreateAPIKey(ctx context.Context, s *store.Session, u *store.User, in APIKeyInput) (*CreatedAPIKey, error)

CreateAPIKey creates a personal access token. Requires a fresh session.

func (*Auth) CreateExchangeCode

func (a *Auth) CreateExchangeCode(ctx context.Context, res *AuthResult, codeChallenge string) (string, error)

CreateExchangeCode wraps the result of a redirect-based sign-in into a single-use code for a native app. codeChallenge is the app's S256 PKCE challenge.

func (*Auth) CreateSAMLConnection

func (a *Auth) CreateSAMLConnection(ctx context.Context, in SAMLConnectionInput) (*store.SAMLConnection, error)

CreateSAMLConnection registers an organization's IdP. This is an admin operation: expose it only to trusted administrators.

func (*Auth) DeletePasskey

func (a *Auth) DeletePasskey(ctx context.Context, s *store.Session, u *store.User, id string) error

DeletePasskey removes a credential. Requires a fresh session and refuses to remove the user's last way to sign in.

func (*Auth) DeleteSAMLConnection

func (a *Auth) DeleteSAMLConnection(ctx context.Context, id string) error

DeleteSAMLConnection removes a connection.

func (*Auth) DeleteUser

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

DeleteUser permanently deletes a user and (via cascades) all their data.

func (*Auth) DisableMFAChannel

func (a *Auth) DisableMFAChannel(ctx context.Context, s *store.Session, u *store.User, channel string) error

DisableMFAChannel removes email or SMS codes as a second factor.

func (*Auth) DisableTOTP

func (a *Auth) DisableTOTP(ctx context.Context, s *store.Session, u *store.User) error

DisableTOTP removes the authenticator app. Requires a fresh session.

func (*Auth) DisableUser

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

DisableUser blocks a user from signing in and revokes their sessions.

func (*Auth) EnableMFAChannel

func (a *Auth) EnableMFAChannel(ctx context.Context, s *store.Session, u *store.User, channel string) ([]string, error)

EnableMFAChannel enables email or SMS codes as a second factor. The email/phone must already be verified. Requires a fresh session. Returns recovery codes if this is the first factor.

func (*Auth) EnableUser

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

EnableUser re-enables a disabled user.

func (*Auth) ExchangeCode

func (a *Auth) ExchangeCode(ctx context.Context, code, verifier string) (*AuthResult, error)

ExchangeCode redeems a code from CreateExchangeCode. verifier is the PKCE code_verifier. The result carries either a session (with its token) or a pending MFA challenge.

func (*Auth) FinishBiometricEnrollment

func (a *Auth) FinishBiometricEnrollment(ctx context.Context, s *store.Session, u *store.User, assertion string) error

FinishBiometricEnrollment links the scanner subject in the assertion to the signed-in user.

func (*Auth) FinishPasskeyLogin

func (a *Auth) FinishPasskeyLogin(ctx context.Context, ceremonyID string, response []byte) (*AuthResult, error)

FinishPasskeyLogin verifies the assertion and signs the user in. User verification is required, so the session starts at AAL2 without a separate second factor.

func (*Auth) FinishPasskeyRegistration

func (a *Auth) FinishPasskeyRegistration(ctx context.Context, s *store.Session, u *store.User, name string, response []byte) (*PasskeyRegistration, error)

FinishPasskeyRegistration verifies the attestation response (JSON from navigator.credentials.create()) and stores the credential. Guest users become regular users with a passkey.

func (*Auth) GetUser

func (a *Auth) GetUser(ctx context.Context, id string) (*store.User, error)

GetUser returns a user by ID.

func (*Auth) GetUserDetails

func (a *Auth) GetUserDetails(ctx context.Context, userID string) (*UserDetails, error)

GetUserDetails returns everything authgen knows about a user (no secrets).

func (*Auth) HandleOAuthCallback

func (a *Auth) HandleOAuthCallback(ctx context.Context, providerID string, r *http.Request) (*OAuthOutcome, error)

HandleOAuthCallback completes the flow. r is the callback request (GET query or form_post body).

func (*Auth) HandleSAMLACS

func (a *Auth) HandleSAMLACS(ctx context.Context, connectionID string, r *http.Request) (*SAMLOutcome, error)

HandleSAMLACS validates a SAML response posted to the ACS endpoint and signs the user in (JIT-provisioning new users).

func (*Auth) HandleSAMLLogoutResponse

func (a *Auth) HandleSAMLLogoutResponse(ctx context.Context, connectionID string, r *http.Request) error

HandleSAMLLogoutResponse validates the IdP's LogoutResponse (the end of SP-initiated single logout). IdP-initiated logout requests are not supported; sessions end through authgen's own expiry and revocation.

func (*Auth) IsNativeRedirect

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

IsNativeRedirect reports whether raw matches one of Config.NativeRedirectURIs (same scheme and host, path prefix).

func (*Auth) IsSafeRedirect

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

IsSafeRedirect reports whether raw is an allowed post-auth redirect: a same-site relative path, or an absolute URL on BaseURL's origin or a trusted origin. Prevents open redirects.

func (*Auth) IsTrustedOrigin

func (a *Auth) IsTrustedOrigin(origin string) bool

IsTrustedOrigin reports whether origin may make credentialed requests.

func (*Auth) LinkBiometricSubject

func (a *Auth) LinkBiometricSubject(ctx context.Context, userID, subject string) error

LinkBiometricSubject links a scanner subject to a user directly, e.g. during HR onboarding where identity was checked in person. Administrative: expose only to trusted operators.

func (*Auth) ListAPIKeys

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

ListAPIKeys lists a user's API keys.

func (*Auth) ListAccounts

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

ListAccounts returns the user's linked identities.

func (*Auth) ListAuditEvents

func (a *Auth) ListAuditEvents(ctx context.Context, q store.AuditQuery) ([]*store.AuditEvent, error)

ListAuditEvents returns stored audit events (requires Audit.Enabled).

func (*Auth) ListPasskeys

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

ListPasskeys returns the user's WebAuthn credentials.

func (*Auth) ListSAMLConnections

func (a *Auth) ListSAMLConnections(ctx context.Context) ([]*store.SAMLConnection, error)

ListSAMLConnections lists connections.

func (*Auth) ListSessions

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

ListSessions returns the user's active sessions.

func (*Auth) ListUsers

func (a *Auth) ListUsers(ctx context.Context, q store.UserQuery) ([]*store.User, error)

ListUsers pages through users for administration.

func (*Auth) MFAChallengeFromRequest

func (a *Auth) MFAChallengeFromRequest(r *http.Request) string

MFAChallengeFromRequest returns the challenge token from the MFA cookie.

func (*Auth) MFAEnrollmentRequired

func (a *Auth) MFAEnrollmentRequired(ctx context.Context, u *store.User) (bool, error)

MFAEnrollmentRequired reports whether policy (MFA.Require / MFA.RequireFor) obliges u to enroll a second factor before using the application.

func (*Auth) MFAMethods

func (a *Auth) MFAMethods(ctx context.Context, u *store.User) ([]string, error)

MFAMethods returns the second-factor methods available to a user.

func (*Auth) MetaFromRequest

func (a *Auth) MetaFromRequest(r *http.Request) RequestMeta

MetaFromRequest extracts RequestMeta from an HTTP request, honoring TrustProxyHeaders.

func (*Auth) Middleware

func (a *Auth) Middleware(next http.Handler) http.Handler

Middleware authenticates requests when credentials are present and attaches the Principal to the context. Unauthenticated requests pass through (combine with the Require* middlewares); cookie-authenticated, state-changing requests that fail the CSRF check are rejected with 403.

func (*Auth) NewCSRFToken

func (a *Auth) NewCSRFToken(w http.ResponseWriter) string

NewCSRFToken returns a signed CSRF token and sets it as a cookie. The client must echo the token in the X-CSRF-Token header on state-changing cookie-authenticated requests.

func (*Auth) PrepareRequest

func (a *Auth) PrepareRequest(w http.ResponseWriter, r *http.Request) context.Context

PrepareRequest returns ctx with request metadata attached and makes sure browsers carry a long-lived device cookie (used for new-device alerts). The REST and GraphQL handlers call it for every request.

func (*Auth) Providers

func (a *Auth) Providers() []*oauth.Provider

Providers returns the configured OAuth providers.

func (*Auth) Reauthenticate

func (a *Auth) Reauthenticate(ctx context.Context, s *store.Session, u *store.User, in ReauthInput) (string, error)

Reauthenticate refreshes the session's authentication time (and AAL when a second factor is used) and rotates the session token. Returns the new session token.

func (*Auth) RecoveryCodesRemaining

func (a *Auth) RecoveryCodesRemaining(ctx context.Context, userID string) (int, error)

RecoveryCodesRemaining returns the number of unused recovery codes.

func (*Auth) RegenerateRecoveryCodes

func (a *Auth) RegenerateRecoveryCodes(ctx context.Context, s *store.Session, u *store.User) ([]string, error)

RegenerateRecoveryCodes replaces all recovery codes. Requires MFA to be enrolled and a fresh session.

func (*Auth) RenamePasskey

func (a *Auth) RenamePasskey(ctx context.Context, userID, id, name string) error

RenamePasskey renames a credential.

func (*Auth) RequestEmailChange

func (a *Auth) RequestEmailChange(ctx context.Context, s *store.Session, u *store.User, newEmail string) error

RequestEmailChange sends a confirmation link to a new email address. Requires a fresh session.

func (*Auth) RequestEmailOTP

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

RequestEmailOTP emails a one-time sign-in code.

func (a *Auth) RequestMagicLink(ctx context.Context, email, callbackURL string) error

RequestMagicLink emails a single-use sign-in link. It always returns nil for valid input to avoid account enumeration. Accounts are created on first successful verification.

func (*Auth) RequestMagicLinkWithOptions

func (a *Auth) RequestMagicLinkWithOptions(ctx context.Context, o MagicLinkOptions) error

RequestMagicLinkWithOptions is RequestMagicLink with native-app and session options.

func (*Auth) RequestPasswordReset

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

RequestPasswordReset emails a reset link if the account exists. It always returns nil (unless rate limited by IP) to avoid enumeration.

func (*Auth) RequestPhoneVerification

func (a *Auth) RequestPhoneVerification(ctx context.Context, s *store.Session, u *store.User, phone string) error

RequestPhoneVerification texts a code to add or change the phone number of a signed-in user. Requires a fresh session.

func (*Auth) RequestSMSOTP

func (a *Auth) RequestSMSOTP(ctx context.Context, phone string) error

RequestSMSOTP texts a one-time sign-in code to a phone number (E.164).

func (*Auth) RequireAPIKey

func (a *Auth) RequireAPIKey(scopes ...string) func(http.Handler) http.Handler

RequireAPIKey accepts only API keys carrying all the given scopes.

func (*Auth) RequireFresh

func (a *Auth) RequireFresh(ctx context.Context, s *store.Session, u *store.User) error

RequireFresh returns ErrReauthRequired unless the session recently authenticated (and passed MFA if the user has it enrolled).

func (*Auth) RequireFreshSession

func (a *Auth) RequireFreshSession(next http.Handler) http.Handler

RequireFreshSession rejects sessions that have not authenticated within Session.FreshAge (clients should call /auth/reauthenticate).

func (*Auth) RequireMFA

func (a *Auth) RequireMFA(next http.Handler) http.Handler

RequireMFA rejects sessions below AAL2 (second factor not verified).

func (*Auth) RequireSession

func (a *Auth) RequireSession(next http.Handler) http.Handler

RequireSession rejects requests without a (non-guest) user session. API keys are not accepted.

func (*Auth) RequireUser

func (a *Auth) RequireUser(next http.Handler) http.Handler

RequireUser rejects requests without a session or API key.

func (*Auth) ResetPassword

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

ResetPassword sets a new password using a reset token. All sessions are revoked and MFA is still required at the next sign-in; the email second factor is suspended for EmailFactorLockout because the reset itself used the inbox. Resetting an unverified account claims it for the inbox owner.

func (*Auth) ResolveRedirect

func (a *Auth) ResolveRedirect(raw, fallback string) string

ResolveRedirect returns an absolute redirect target, falling back to fallback (or "/") when raw is empty or unsafe.

func (*Auth) RevokeAPIKey

func (a *Auth) RevokeAPIKey(ctx context.Context, userID, id string) error

RevokeAPIKey revokes one of the user's API keys.

func (*Auth) RevokeOtherSessions

func (a *Auth) RevokeOtherSessions(ctx context.Context, userID, keepID string) (int64, error)

RevokeOtherSessions deletes all of the user's sessions except keepID.

func (*Auth) RevokeSession

func (a *Auth) RevokeSession(ctx context.Context, userID, sessionID string) error

RevokeSession deletes one of the user's sessions.

func (*Auth) SAMLLogoutURL

func (a *Auth) SAMLLogoutURL(ctx context.Context, s *store.Session, u *store.User) (string, error)

SAMLLogoutURL returns the IdP single-logout URL for a session that was created through SAML SSO, or "" when not applicable (non-SAML session, or the IdP has no HTTP-Redirect SLO endpoint). Call it before signing out.

func (*Auth) SAMLMetadata

func (a *Auth) SAMLMetadata(ctx context.Context, connectionID string) ([]byte, error)

SAMLMetadata returns this service provider's metadata XML for a connection, to be uploaded to the IdP.

func (*Auth) SendMFACode

func (a *Auth) SendMFACode(ctx context.Context, challengeToken, method string) error

SendMFACode sends an email or SMS code for a pending challenge.

func (*Auth) SendReauthCode

func (a *Auth) SendReauthCode(ctx context.Context, s *store.Session, u *store.User, channel string) error

SendReauthCode sends an email/SMS code for reauthentication to any verified contact (useful for passwordless users).

func (*Auth) SendVerificationEmail

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

SendVerificationEmail (re)sends the verification email. It always succeeds from the caller's perspective to avoid account enumeration.

func (*Auth) SessionCookieName

func (a *Auth) SessionCookieName() string

SessionCookieName returns the session cookie name.

func (*Auth) SessionFromRequest

func (a *Auth) SessionFromRequest(r *http.Request) (*store.Session, *store.User, error)

SessionFromRequest validates the session carried by r.

func (*Auth) SessionPayload

func (a *Auth) SessionPayload(ctx context.Context, s *store.Session, u *store.User) (map[string]any, error)

SessionPayload builds the /session response, applying Callbacks.Session.

func (*Auth) SetMFACookie

func (a *Auth) SetMFACookie(w http.ResponseWriter, p *MFAPending)

SetMFACookie stores a pending MFA challenge in an HttpOnly cookie, used by redirect-based flows (OAuth, SAML, magic links).

func (*Auth) SetSessionCookie

func (a *Auth) SetSessionCookie(w http.ResponseWriter, is *IssuedSession)

SetSessionCookie writes the session cookie for an issued session.

func (*Auth) SetSessionToken

func (a *Auth) SetSessionToken(w http.ResponseWriter, token string, s *store.Session)

SetSessionToken writes the session cookie for a rotated token.

func (*Auth) Shutdown

func (a *Auth) Shutdown(ctx context.Context) error

Shutdown waits for background email/SMS deliveries to finish (or ctx to end). Call it during graceful shutdown.

func (*Auth) SignInAnonymously

func (a *Auth) SignInAnonymously(ctx context.Context) (*IssuedSession, error)

SignInAnonymously creates a guest user and session. Guests can later be upgraded (keeping their user ID) by signing up with a password, verifying an email/SMS code or magic link, completing OAuth, or registering a passkey while the guest session is active.

func (*Auth) SignInWithBiometric

func (a *Auth) SignInWithBiometric(ctx context.Context, assertion string) (*AuthResult, error)

SignInWithBiometric signs in the person a scanner recognized. The usual MFA policy applies; a scan on a shared scanner is one factor (AAL1).

func (*Auth) SignInWithPassword

func (a *Auth) SignInWithPassword(ctx context.Context, email, password string) (*AuthResult, error)

SignInWithPassword authenticates with email and password.

func (*Auth) SignOut

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

SignOut deletes the session identified by token.

func (*Auth) SignUp

func (a *Auth) SignUp(ctx context.Context, in SignUpInput) (*SignUpResult, error)

SignUp registers a user with email and password.

func (*Auth) Store

func (a *Auth) Store() store.Store

Store returns the underlying store.

func (*Auth) TakeSAMLPostForm

func (a *Auth) TakeSAMLPostForm(ctx context.Context, token string) (*SAMLPostForm, error)

TakeSAMLPostForm consumes a stashed POST-binding request.

func (*Auth) TokenFromRequest

func (a *Auth) TokenFromRequest(r *http.Request) (token string, fromCookie bool)

TokenFromRequest returns the session token from the Authorization bearer header or the session cookie. fromCookie reports where it came from.

func (*Auth) UnlinkAccount

func (a *Auth) UnlinkAccount(ctx context.Context, s *store.Session, u *store.User, accountID string) error

UnlinkAccount removes a linked identity. Requires a fresh session and refuses to remove the last way to sign in.

func (*Auth) UpdateProfile

func (a *Auth) UpdateProfile(ctx context.Context, userID string, p ProfileUpdate) (*store.User, error)

UpdateProfile changes non-security profile fields.

func (*Auth) UpdateSAMLConnection

func (a *Auth) UpdateSAMLConnection(ctx context.Context, id string, in SAMLConnectionInput) (*store.SAMLConnection, error)

UpdateSAMLConnection replaces a connection's settings.

func (*Auth) ValidateSession

func (a *Auth) ValidateSession(ctx context.Context, token string) (*store.Session, *store.User, error)

ValidateSession resolves a session token. Expired, idle or disabled-user sessions are rejected (and expired ones deleted).

func (*Auth) VerifyEmail

func (a *Auth) VerifyEmail(ctx context.Context, token, password string) (*store.User, error)

VerifyEmail consumes an email verification token. Opening the link on the device that signed up is enough; on any other device the account's password must be supplied (ErrPasswordRequired otherwise, and the token stays valid). This stops a victim who clicks a link for an account they never created from activating the attacker's password.

func (*Auth) VerifyEmailOTP

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

VerifyEmailOTP checks an email sign-in code and signs the user in.

func (*Auth) VerifyMFA

func (a *Auth) VerifyMFA(ctx context.Context, in MFAVerifyInput) (*IssuedSession, error)

VerifyMFA completes a challenge and issues an AAL2 session.

func (a *Auth) VerifyMagicLink(ctx context.Context, token, anonymousUserID string) (*MagicLinkOutcome, error)

VerifyMagicLink consumes a magic-link token and signs the user in. The outcome carries the validated callbackUrl requested when the link was sent.

func (*Auth) VerifySMSOTP

func (a *Auth) VerifySMSOTP(ctx context.Context, phone, code, anonymousUserID string) (*AuthResult, error)

VerifySMSOTP checks an SMS sign-in code and signs the user in.

type AuthResult

type AuthResult struct {
	Session *IssuedSession
	MFA     *MFAPending
	User    *store.User
	// MFAEnrollmentRequired is set when policy requires MFA and the user
	// has no second factor yet: the session only allows enrollment.
	MFAEnrollmentRequired bool
}

AuthResult is the outcome of a first-factor sign-in: either a session or a pending MFA challenge.

type BiometricChallenge

type BiometricChallenge struct {
	Nonce     string    `json:"nonce"`
	ExpiresAt time.Time `json:"expiresAt"`
}

BiometricChallenge is a single-use challenge for a scanner.

type BiometricConfig

type BiometricConfig struct {
	// Verifier checks scanner match tokens, e.g. biometric.NewJWTVerifier.
	Verifier biometric.Verifier
	// ID names this scanner system; linked accounts use provider
	// "biometric:<ID>". Default "scanner".
	ID string
	// ChallengeTTL bounds the time between challenge and scan. Default 2 minutes.
	ChallengeTTL time.Duration
}

BiometricConfig connects dedicated scanners (see package biometric). authgen never receives biometric data, only signed match results.

type BotProtectionConfig

type BotProtectionConfig struct {
	// Verifier checks tokens (captcha.Turnstile, captcha.HCaptcha,
	// captcha.ReCaptchaV3, or your own). Nil disables bot protection.
	Verifier captcha.Verifier
	// Actions to protect. Default: signup, password_forgot, magic_link,
	// email_otp, sms_otp, anonymous, verify_resend. Add "signin" to also
	// protect password sign-in.
	Actions []string
	// FailOpen allows the action when the CAPTCHA provider is unreachable.
	// By default authgen fails closed.
	FailOpen bool
}

BotProtectionConfig requires CAPTCHA tokens (X-Captcha-Token header) for abuse-prone actions.

type CSRFConfig

type CSRFConfig struct {
	// DisableToken disables the double-submit token requirement. Origin /
	// Fetch-Metadata checks always apply.
	DisableToken bool
}

CSRFConfig controls CSRF protection for cookie-authenticated requests.

type Callbacks

type Callbacks struct {
	// SignIn is called before a session is created. Return an error to deny.
	SignIn func(ctx context.Context, attempt SignInAttempt) error
	// Session customizes the session view returned to clients.
	Session func(ctx context.Context, user *store.User, session *store.Session, view map[string]any)
}

Callbacks customize authgen decisions.

type CleanupResult

type CleanupResult struct {
	Sessions           int64
	VerificationTokens int64
	AnonymousUsers     int64
	RateLimits         int64
}

CleanupResult reports what Cleanup removed.

type Config

type Config struct {
	// Pool is the application's PostgreSQL pool. authgen only runs DML on
	// it, never DDL.
	Pool *pgxpool.Pool
	// Store overrides the storage backend (e.g. memstore in tests). When
	// set, Pool and Schema are ignored.
	Store store.Store
	// Schema maps authgen's tables/columns onto the application's names.
	Schema schema.Mapping

	// BaseURL is the public URL where the authgen REST handler is mounted,
	// e.g. "https://api.example.com/auth". Used to build callback and
	// email links.
	BaseURL string
	// Secrets are master secrets (>= 32 bytes each). The first one is used
	// for new values; the others are accepted for rotation.
	Secrets []string
	// AppName is shown in authenticator apps, passkey prompts and emails.
	AppName string
	// TrustedOrigins are the frontend origins (scheme://host[:port]) allowed
	// to make credentialed requests and to be used as redirect targets.
	TrustedOrigins []string

	// URLs are frontend pages authgen redirects to or links to in emails.
	URLs URLs
	// Methods enables sign-in methods. OAuth is enabled by configuring providers.
	Methods Methods

	Session   SessionConfig
	Password  PasswordConfig
	Tokens    TokenConfig
	MFA       MFAConfig
	OAuth     OAuthConfig
	WebAuthn  WebAuthnConfig
	SAML      SAMLConfig
	Biometric BiometricConfig
	APIKeys   APIKeyConfig
	Anonymous AnonymousConfig
	RateLimit RateLimitConfig
	CSRF      CSRFConfig

	// Email and SMS deliver messages through the application's providers.
	Email notify.EmailSender
	SMS   notify.SMSSender
	// SMSPolicy limits SMS abuse (toll fraud / SMS pumping).
	SMSPolicy SMSPolicyConfig
	// Templates customize email/SMS content (and translate it).
	Templates Templates
	// BotProtection requires a CAPTCHA token for abuse-prone actions.
	BotProtection BotProtectionConfig
	// Alerts configures security notifications to users.
	Alerts AlertsConfig
	// NativeRedirectURIs allow native/mobile apps to receive the result of
	// redirect-based flows (OAuth, SAML, magic links). Each entry is a URI
	// prefix such as "com.example.app:/auth". A callbackUrl matching one of
	// them receives a short-lived, single-use code (never a cookie) that the
	// app redeems at POST /auth/token/exchange with its PKCE code_verifier.
	NativeRedirectURIs []string
	// SyncNotifications delivers emails/SMS synchronously. By default they
	// are sent in the background (see Auth.Shutdown) so that response times
	// do not reveal whether an account exists.
	SyncNotifications bool
	// Audit stores every event in the audit_events table, in addition to OnEvent.
	Audit AuditConfig

	Callbacks Callbacks
	// OnEvent receives audit/security events. It is called synchronously;
	// do slow work asynchronously.
	OnEvent func(ctx context.Context, e Event)

	// TrustProxyHeaders derives the client IP from X-Forwarded-For. Proxies
	// append to that header, so the client controls its leftmost entries;
	// authgen walks it from the right instead (see TrustedProxyHops and
	// TrustedProxies). X-Real-IP is used only when X-Forwarded-For is
	// absent, so only trust it behind a proxy that overwrites it.
	TrustProxyHeaders bool
	// TrustedProxyHops is the number of proxies in front of the app that
	// append to X-Forwarded-For (default 1: e.g. a single load balancer).
	TrustedProxyHops int
	// TrustedProxies lists proxy CIDRs (e.g. "10.0.0.0/8"). When set, the
	// headers are honored only for requests from these addresses, and the
	// client IP is the rightmost X-Forwarded-For entry outside them.
	TrustedProxies []string
	// HTTPClient is used for outbound calls (OAuth, HIBP). Default has a 10s timeout.
	HTTPClient *http.Client
	Logger     *slog.Logger
	// Now overrides the clock (tests).
	Now func() time.Time
}

Config configures authgen. Pool (or Store), BaseURL and Secrets are required.

type CreatedAPIKey

type CreatedAPIKey struct {
	Key  string     `json:"key"`
	View APIKeyView `json:"apiKey"`
}

CreatedAPIKey holds a new key. Key is shown once and never stored.

type Error

type Error struct {
	Code       string
	Status     int
	Message    string
	RetryAfter time.Duration
	// contains filtered or unexported fields
}

Error is a client-safe error with a stable machine-readable code. Messages never reveal whether an account exists.

func AsError

func AsError(err error) *Error

AsError converts any error into a client-safe *Error. Unknown errors become ErrInternal (details are kept only in the cause for logging).

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is matches errors by code, so errors.Is(err, authgen.ErrInvalidCredentials) works.

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorBody

type ErrorBody struct {
	Error struct {
		Code    string `json:"code"`
		Message string `json:"message"`
	} `json:"error"`
}

ErrorBody is the JSON error envelope.

type Event

type Event struct {
	Type      EventType
	Time      time.Time
	UserID    string
	SessionID string
	Method    string
	IP        string
	UserAgent string
	Metadata  map[string]any
}

Event is an audit/security event.

type EventType

type EventType string

EventType identifies an audit/security event.

const (
	EventSignIn             EventType = "sign_in"
	EventSignInFailed       EventType = "sign_in_failed"
	EventSignOut            EventType = "sign_out"
	EventUserCreated        EventType = "user_created"
	EventUserUpdated        EventType = "user_updated"
	EventUserDeleted        EventType = "user_deleted"
	EventEmailVerified      EventType = "email_verified"
	EventPhoneVerified      EventType = "phone_verified"
	EventPasswordChanged    EventType = "password_changed"
	EventPasswordReset      EventType = "password_reset"
	EventAccountLinked      EventType = "account_linked"
	EventAccountUnlinked    EventType = "account_unlinked"
	EventMFAEnrolled        EventType = "mfa_enrolled"
	EventMFARemoved         EventType = "mfa_removed"
	EventMFAVerified        EventType = "mfa_verified"
	EventMFAFailed          EventType = "mfa_failed"
	EventRecoveryCodeUsed   EventType = "recovery_code_used"
	EventRecoveryRegenerate EventType = "recovery_codes_regenerated"
	EventSessionRevoked     EventType = "session_revoked"
	EventPasskeyAdded       EventType = "passkey_added"
	EventPasskeyRemoved     EventType = "passkey_removed"
	EventAPIKeyCreated      EventType = "api_key_created"
	EventAPIKeyRevoked      EventType = "api_key_revoked"
	EventAnonymousUpgraded  EventType = "anonymous_upgraded"
	EventRateLimited        EventType = "rate_limited"
	EventSuspicious         EventType = "suspicious_activity"
	EventNewDevice          EventType = "new_device_sign_in"
	EventAdminAction        EventType = "admin_action"
)

type HIBPChecker

type HIBPChecker struct {
	Client  *http.Client
	BaseURL string // default https://api.pwnedpasswords.com/range/
}

HIBPChecker queries the Have I Been Pwned range API using k-anonymity: only the first 5 hex characters of the SHA-1 hash leave the server, and response padding is requested.

func (*HIBPChecker) IsBreached

func (h *HIBPChecker) IsBreached(ctx context.Context, password string) (bool, error)

IsBreached implements PasswordChecker.

type IssuedSession

type IssuedSession struct {
	Token   string
	Session *store.Session
	User    *store.User
}

IssuedSession is a newly created session. Token is the bearer secret; it is never stored and cannot be recovered later.

type MFAConfig

type MFAConfig struct {
	// Issuer shown in authenticator apps. Default AppName.
	Issuer string
	// RecoveryCodeCount is the number of recovery codes. Default 10.
	RecoveryCodeCount int
	// ChallengeTTL is how long a pending MFA challenge is valid. Default 10 minutes.
	ChallengeTTL time.Duration
	// MaxAttempts per challenge. Default 5.
	MaxAttempts int
	// DisableEmail / DisableSMS remove email/SMS codes as second factors.
	// SMS is never phishing-resistant; prefer TOTP or WebAuthn.
	DisableEmail bool
	DisableSMS   bool
	// Require enforces MFA for every (non-guest) user. Users without a
	// second factor can still sign in, but their sessions are limited to
	// MFA enrollment: the Require* middlewares answer
	// "mfa_enrollment_required" until a factor is enrolled.
	Require bool
	// RequireFor enforces MFA for selected users (e.g. admins). It is
	// consulted in addition to Require.
	RequireFor func(ctx context.Context, u *store.User) bool
}

MFAConfig controls multi-factor authentication.

type MFAPending

type MFAPending struct {
	Token     string
	Methods   []string
	ExpiresAt time.Time
}

MFAPending describes a second-factor challenge the client must complete via VerifyMFA.

type MFAVerifyInput

type MFAVerifyInput struct {
	ChallengeToken string
	Method         string // totp, recovery_code, email, sms, webauthn
	Code           string
	// WebAuthnResponse is the JSON PublicKeyCredential from navigator.credentials.get().
	WebAuthnResponse []byte
}

MFAVerifyInput completes a pending MFA challenge.

type MagicLinkOptions

type MagicLinkOptions struct {
	Email       string
	CallbackURL string
	// CodeChallenge is a native app's S256 PKCE challenge (required when
	// CallbackURL is a native redirect URI).
	CodeChallenge string
	// Ephemeral creates a "remember me: off" session.
	Ephemeral bool
}

MagicLinkOptions configures RequestMagicLinkWithOptions.

type MagicLinkOutcome

type MagicLinkOutcome struct {
	Result        *AuthResult
	CallbackURL   string
	CodeChallenge string
}

MagicLinkOutcome is the result of VerifyMagicLink.

type Methods

type Methods struct {
	Password  bool // email + password
	MagicLink bool // email magic link
	EmailOTP  bool // email one-time code sign-in
	SMSOTP    bool // phone one-time code sign-in
	Passkey   bool // passwordless WebAuthn sign-in (requires WebAuthn config)
	Anonymous bool // guest sessions
	APIKeys   bool // personal access tokens
	SAML      bool // enterprise SSO (requires SAML config)
	Biometric bool // dedicated fingerprint/iris/face scanners (requires Biometric.Verifier)
}

Methods enables sign-in methods.

type OAuthConfig

type OAuthConfig struct {
	Providers []*oauth.Provider
	// StoreTokens keeps provider tokens (encrypted) in the accounts table.
	// AccountTokens refreshes expired access tokens automatically.
	StoreTokens bool
	// AllowEmailLinking links a new OAuth identity to an existing user with
	// the same email when the provider vouches for the email
	// (TrustEmailVerified and email_verified). Off by default, like
	// Auth.js: users must sign in first and link from their settings,
	// which protects against compromised or misconfigured providers.
	AllowEmailLinking bool
	// StateTTL bounds the time between sign-in start and callback. Default 10 minutes.
	StateTTL time.Duration
}

OAuthConfig configures OAuth / OIDC providers.

type OAuthOutcome

type OAuthOutcome struct {
	Result      *AuthResult // nil when linking or on error
	Linked      bool
	CallbackURL string
	// CodeChallenge is set for native-app flows (see CreateExchangeCode).
	CodeChallenge string
}

OAuthOutcome is the result of an OAuth callback. When HandleOAuthCallback fails after the state was validated, it still returns an outcome carrying CallbackURL/CodeChallenge so errors can be reported to native apps.

type OAuthStart

type OAuthStart struct {
	URL    string
	Cookie *http.Cookie
}

OAuthStart is the redirect to the provider plus the state cookie the caller must set on the response.

type OAuthStartOptions

type OAuthStartOptions struct {
	// CallbackURL is where to send the browser after sign-in (validated).
	CallbackURL string
	// LinkUserID links the identity to this signed-in user instead of signing in.
	LinkUserID string
	// AnonymousUserID upgrades this guest user if the identity is new.
	AnonymousUserID string
	// CodeChallenge is the S256 PKCE challenge of a native app; required
	// when CallbackURL is a native redirect URI (see NativeRedirectURIs).
	CodeChallenge string
	// Ephemeral creates a "remember me: off" session.
	Ephemeral bool
}

OAuthStartOptions configures BeginOAuth.

type PasskeyLoginOptions

type PasskeyLoginOptions struct {
	// Conditional requests conditional mediation (passkey autofill in the
	// username field: <input autocomplete="username webauthn">).
	Conditional bool
}

PasskeyLoginOptions configures BeginPasskeyLoginWithOptions.

type PasskeyRegistration

type PasskeyRegistration struct {
	Passkey       PasskeyView
	RecoveryCodes []string // set when this is the user's first second factor
}

PasskeyRegistration is the result of FinishPasskeyRegistration.

type PasskeyView

type PasskeyView struct {
	ID             string     `json:"id"`
	Name           string     `json:"name"`
	CreatedAt      time.Time  `json:"createdAt"`
	LastUsedAt     *time.Time `json:"lastUsedAt"`
	BackupEligible bool       `json:"backupEligible"` // synced passkey
	BackedUp       bool       `json:"backedUp"`
	Transports     []string   `json:"transports"`
}

PasskeyView is the client-facing view of a WebAuthn credential.

type PasswordChecker

type PasswordChecker interface {
	IsBreached(ctx context.Context, password string) (bool, error)
}

PasswordChecker reports whether a password is known to be compromised.

type PasswordCheckerFunc

type PasswordCheckerFunc func(ctx context.Context, password string) (bool, error)

PasswordCheckerFunc adapts a function to PasswordChecker.

func (PasswordCheckerFunc) IsBreached

func (f PasswordCheckerFunc) IsBreached(ctx context.Context, p string) (bool, error)

type PasswordConfig

type PasswordConfig struct {
	MinLength int // default 8
	MaxLength int // default 128
	Argon2    secure.Argon2Params
	// Checker rejects compromised passwords. Default: Have I Been Pwned
	// k-anonymity API (fails open on network errors).
	Checker PasswordChecker
	// DisableBreachCheck turns off the default breach checker.
	DisableBreachCheck bool
	// BreachCheckFailClosed rejects passwords (with 503) when the breach
	// checker is unreachable. By default the check fails open.
	BreachCheckFailClosed bool
	// AllowUnverifiedSignIn lets users sign in before verifying their email.
	// When false (default) sign-up never creates a session, so the
	// response does not reveal whether the email was already registered.
	AllowUnverifiedSignIn bool
}

PasswordConfig controls password policy and hashing.

type Principal

type Principal struct {
	User    *store.User
	Session *store.Session // nil for API-key requests
	APIKey  *store.APIKey  // nil for session requests
	// Token is the raw session token (used internally for rotation).
	Token string
	// MFAEnrollmentRequired is true when policy requires MFA and this
	// session's user has not enrolled a factor yet. The Require*
	// middlewares reject such sessions; check it if you only use
	// Middleware.
	MFAEnrollmentRequired bool
}

Principal is the authenticated caller of a request: a user with either a session or an API key.

func FromContext

func FromContext(ctx context.Context) (*Principal, bool)

FromContext returns the request's principal, if authenticated.

type ProfileUpdate

type ProfileUpdate struct {
	Name  *string
	Image *string
}

ProfileUpdate holds optional profile changes.

type RateLimitConfig

type RateLimitConfig struct {
	// Disabled turns rate limiting off (tests only).
	Disabled bool
	// FailOpen allows requests when the limiter's store errors. By default
	// authgen fails closed (503) so an outage cannot disable throttling.
	FailOpen bool
	// Limiter overrides the store-backed limiter.
	Limiter ratelimit.Limiter
	// Rules overrides default rules by name (see DefaultRateLimits).
	Rules map[string]ratelimit.Rule
}

RateLimitConfig controls throttling.

type ReauthInput

type ReauthInput struct {
	// Method is "password" or an MFA method (totp, recovery_code, email, sms, webauthn).
	Method           string
	Password         string
	Code             string
	WebAuthnResponse []byte
}

ReauthInput proves the user's identity again for sensitive operations.

type RequestMeta

type RequestMeta struct {
	IP        string
	UserAgent string
	// Origin of the request (for WebAuthn), if known.
	Origin string
	// CaptchaToken is the bot-protection token (X-Captcha-Token header).
	CaptchaToken string
	// Locale is the preferred language (first Accept-Language tag), passed
	// to message templates.
	Locale string
	// DeviceID identifies the client device for new-device alerts (the
	// device cookie, or the X-Device-Id header for native apps).
	DeviceID string
}

RequestMeta carries client information used for sessions, rate limits and audit events.

type SAMLConfig

type SAMLConfig struct {
	// Certificate and PrivateKey (PEM) identify this service provider.
	Certificate string
	PrivateKey  string
	// AllowIdPInitiated accepts unsolicited responses. Off by default
	// because IdP-initiated SSO is vulnerable to login CSRF.
	AllowIdPInitiated bool
	// AllowEmailLinking lets a connection's IdP sign in EXISTING verified
	// users whose email is within the connection's domains. Off by default:
	// whoever can create a connection (an administrator, or a stolen admin
	// session) could otherwise point a domain at their own IdP and sign in
	// as its users. New users are always provisioned.
	AllowEmailLinking bool
	// EmailAttributes are attribute names checked for the email address
	// before falling back to the NameID. Default common names.
	EmailAttributes []string
}

SAMLConfig configures the SAML service provider.

type SAMLConnectionInput

type SAMLConnectionInput struct {
	OrgID          string
	Domains        []string // email domains routed to this IdP
	IdPMetadataXML string
	Enabled        bool
}

SAMLConnectionInput creates or updates a SAML connection.

type SAMLOutcome

type SAMLOutcome struct {
	Result        *AuthResult
	CallbackURL   string
	CodeChallenge string
}

SAMLOutcome is the result of an ACS request.

type SAMLPostForm

type SAMLPostForm struct {
	URL         string `json:"url"`
	SAMLRequest string `json:"samlRequest"`
	RelayState  string `json:"relayState"`
}

SAMLPostForm is an AuthnRequest for IdPs that only accept the HTTP-POST binding. The browser must POST SAMLRequest and RelayState to URL.

type SAMLStart

type SAMLStart struct {
	URL    string
	Cookie *http.Cookie
}

BeginSAML starts SP-initiated SSO and returns the IdP redirect URL. SAMLStart is the IdP redirect plus a browser-binding cookie the caller must set on the response. The ACS only honors the request (its callbackUrl, guest upgrade and native PKCE challenge) when the response is posted by the browser that carries this cookie, which prevents SSO login CSRF and "complete my sign-in" hijacks.

type SAMLStartOptions

type SAMLStartOptions struct {
	Email        string // routes by email domain
	ConnectionID string // or explicit connection
	CallbackURL  string
	// AnonymousUserID upgrades this guest user if the identity is new.
	AnonymousUserID string
	// CodeChallenge is a native app's S256 PKCE challenge (required when
	// CallbackURL is a native redirect URI).
	CodeChallenge string
	// Ephemeral creates a "remember me: off" session.
	Ephemeral bool
}

SAMLStartOptions selects the connection for SP-initiated SSO.

type SMSPolicyConfig

type SMSPolicyConfig struct {
	// AllowedCountryCodes restricts destinations to E.164 prefixes such as
	// "+1" or "+44". Empty allows all countries (not recommended: SMS
	// pumping fraud targets premium-rate destinations).
	AllowedCountryCodes []string
	// DailyLimit caps SMS messages per 24 hours across the whole
	// deployment. Default 1000; negative disables the cap.
	DailyLimit int
}

SMSPolicyConfig limits where and how many SMS messages are sent.

type SessionConfig

type SessionConfig struct {
	// AbsoluteTTL is the maximum session lifetime. Default 30 days.
	AbsoluteTTL time.Duration
	// IdleTTL expires sessions not used for this long. Default 7 days.
	IdleTTL time.Duration
	// TouchInterval limits last-seen writes. Default 5 minutes.
	TouchInterval time.Duration
	// FreshAge is how recently the user must have authenticated to perform
	// sensitive operations (change password, manage MFA, API keys). Default 10 minutes.
	FreshAge time.Duration
	// CookieName overrides the session cookie name. Default
	// "__Host-authgen.session" (or "authgen.session" with InsecureCookies).
	CookieName string
	// CookieDomain shares the cookie with subdomains. Disables the __Host- prefix.
	CookieDomain string
	// SameSite for the session cookie. Default Lax.
	SameSite http.SameSite
	// InsecureCookies drops the Secure flag. Local HTTP development only.
	InsecureCookies bool
	// RevokeOthersOnPasswordChange signs out other sessions. Default true
	// (set KeepOthersOnPasswordChange to disable).
	KeepOthersOnPasswordChange bool
	// EphemeralTTL is the lifetime of sessions created with "remember me"
	// off (see WithSessionOptions). Their cookie has no Max-Age, so it is
	// dropped when the browser closes. Default 12 hours.
	EphemeralTTL time.Duration
}

SessionConfig controls sessions and cookies.

type SessionOptions

type SessionOptions struct {
	// Ephemeral ("remember me" off) limits the session to
	// Session.EphemeralTTL and makes the cookie a browser-session cookie.
	Ephemeral bool
}

SessionOptions customize the session created by a sign-in.

type SessionView

type SessionView struct {
	ID              string     `json:"id"`
	CreatedAt       time.Time  `json:"createdAt"`
	ExpiresAt       time.Time  `json:"expiresAt"`
	LastSeenAt      time.Time  `json:"lastSeenAt"`
	AuthenticatedAt time.Time  `json:"authenticatedAt"`
	IP              *string    `json:"ip"`
	UserAgent       *string    `json:"userAgent"`
	AAL             int        `json:"aal"`
	AMR             []string   `json:"amr"`
	MFAVerifiedAt   *time.Time `json:"mfaVerifiedAt"`
	Current         bool       `json:"current"`
}

SessionView is the client-facing representation of a session.

func ViewSession

func ViewSession(s *store.Session, currentID string) SessionView

ViewSession converts a session to its client-facing view.

type SignInAttempt

type SignInAttempt struct {
	User      *store.User
	Method    string
	Provider  string
	Profile   *oauth.Profile
	IsNewUser bool
}

SignInAttempt describes a sign-in about to succeed.

type SignUpInput

type SignUpInput struct {
	Email    string
	Password string
	Name     string
	// AnonymousUserID upgrades this guest user instead of creating a new
	// one (set automatically by the HTTP handlers for guest sessions).
	AnonymousUserID string
}

SignUpInput is the email + password sign-up request.

type SignUpResult

type SignUpResult struct {
	VerificationSent bool
	Auth             *AuthResult
}

SignUpResult is returned by SignUp. When email verification is required (the default) Session is nil and the response is identical whether or not the email was already registered.

type TOTPEnrollment

type TOTPEnrollment struct {
	Secret    string `json:"secret"`
	URL       string `json:"otpauthUrl"`
	QRCodePNG string `json:"qrCodePng"` // data: URL
}

TOTPEnrollment is returned when starting TOTP enrollment. Show the QR code (or secret) to the user and confirm with a code.

type Templates

type Templates struct {
	Email func(ctx context.Context, msg *notify.Email)
	SMS   func(ctx context.Context, msg *notify.SMS)
}

Templates rewrite outgoing messages. Each function may change Subject, Text (or anything else) in place; msg.Locale carries the request language.

type TokenConfig

type TokenConfig struct {
	VerifyEmailTTL time.Duration // default 24h
	ResetTTL       time.Duration // default 30m
	MagicLinkTTL   time.Duration // default 15m
	OTPTTL         time.Duration // default 10m
	OTPLength      int           // default 6
	MaxOTPAttempts int           // default 5
}

TokenConfig controls one-time tokens and codes.

type URLs

type URLs struct {
	// SignIn is where browsers land after a redirect-based sign-in
	// (OAuth, SAML, magic link) when no callbackUrl was given.
	SignIn string
	// Error receives ?error=<code> after a failed redirect-based flow.
	Error string
	// MFA is where browsers are sent when a redirect-based sign-in needs a
	// second factor. The challenge is in an HttpOnly cookie.
	MFA string
	// VerifyEmail, if set, is used in verification emails (…?token=) and
	// the page must POST the token to /auth/verify-email. Otherwise the
	// email links to authgen's GET endpoint directly.
	VerifyEmail string
	// ResetPassword is the page that collects a new password (…?token=)
	// and POSTs it to /auth/password/reset.
	ResetPassword string
	// MagicLink, if set, is used in magic-link emails (…?token=) and the
	// page must POST the token to /auth/magic-link/verify. This protects
	// links from being consumed by email security scanners.
	MagicLink string
}

URLs are frontend URLs. All are optional.

type UserDetails

type UserDetails struct {
	User       UserView      `json:"user"`
	Disabled   bool          `json:"disabled"`
	MFAMethods []string      `json:"mfaMethods"`
	Sessions   []SessionView `json:"sessions"`
	Accounts   []AccountView `json:"accounts"`
	Passkeys   []PasskeyView `json:"passkeys"`
	APIKeys    []APIKeyView  `json:"apiKeys"`
}

UserDetails is an administrative view of a user.

type UserView

type UserView struct {
	ID            string    `json:"id"`
	Email         *string   `json:"email"`
	EmailVerified bool      `json:"emailVerified"`
	Phone         *string   `json:"phone"`
	PhoneVerified bool      `json:"phoneVerified"`
	Name          *string   `json:"name"`
	Image         *string   `json:"image"`
	IsAnonymous   bool      `json:"isAnonymous"`
	HasPassword   bool      `json:"hasPassword"`
	CreatedAt     time.Time `json:"createdAt"`
}

UserView is the client-facing representation of a user.

func ViewUser

func ViewUser(u *store.User) UserView

ViewUser converts a user to its client-facing view.

type WebAuthnConfig

type WebAuthnConfig struct {
	RPID          string   // e.g. "example.com"
	RPDisplayName string   // default AppName
	RPOrigins     []string // e.g. ["https://app.example.com"]
	// CeremonyTTL bounds a registration/login ceremony. Default 5 minutes.
	CeremonyTTL time.Duration
	// RequireUserVerification makes the device always verify the user
	// (fingerprint, face, iris or the device PIN) when registering a passkey
	// and when it is used as a second factor or for reauthentication.
	// Passwordless passkey sign-in always requires it.
	RequireUserVerification bool
	// PlatformOnly accepts only the device's built-in authenticator (Touch ID,
	// Windows Hello, Android biometrics) at registration, not roaming
	// security keys or another phone.
	PlatformOnly bool
	// Attestation is the attestation conveyance preference for
	// registration: "none" (default, best privacy), "indirect", "direct"
	// or "enterprise".
	Attestation string
	// AllowedAAGUIDs restricts registration to these authenticator models
	// (AAGUIDs as UUID strings). AAGUIDs are self-reported unless
	// attestation is verified, so combine this with Attestation "direct"
	// and MDS for a real guarantee.
	AllowedAAGUIDs []string
	// MDS validates attestation against the FIDO Metadata Service
	// (github.com/go-webauthn/webauthn/metadata).
	MDS metadata.Provider
}

WebAuthnConfig configures WebAuthn (passkeys and security keys). Setting RPID enables WebAuthn as a second factor; Methods.Passkey additionally enables passwordless sign-in.

Directories

Path Synopsis
Package biometric connects dedicated biometric scanners (fingerprint, iris, face readers at kiosks, attendance terminals or door controllers) to authgen without authgen ever handling biometric data.
Package biometric connects dedicated biometric scanners (fingerprint, iris, face readers at kiosks, attendance terminals or door controllers) to authgen without authgen ever handling biometric data.
Package captcha verifies bot-protection tokens (Cloudflare Turnstile, hCaptcha, Google reCAPTCHA v3) before authgen performs abuse-prone actions (sign-up, sign-in, sending emails/SMS).
Package captcha verifies bot-protection tokens (Cloudflare Turnstile, hCaptcha, Google reCAPTCHA v3) before authgen performs abuse-prone actions (sign-up, sign-in, sending emails/SMS).
cmd
authgen command
Command authgen generates the database schema authgen needs, in the format of your migration tool.
Command authgen generates the database schema authgen needs, in the format of your migration tool.
examples
server command
Command server is a runnable example of authgen with PostgreSQL.
Command server is a runnable example of authgen with PostgreSQL.
internal
secure
Package secure contains authgen's cryptographic primitives: random tokens, token hashing, constant-time comparison, Argon2id password hashing and a rotating keyring for authenticated encryption and MACs.
Package secure contains authgen's cryptographic primitives: random tokens, token hashing, constant-time comparison, Argon2id password hashing and a rotating keyring for authenticated encryption and MACs.
Package notify defines how authgen delivers emails and SMS messages.
Package notify defines how authgen delivers emails and SMS messages.
providers
oauth
Package oauth defines OAuth 2.0 / OpenID Connect provider configurations for authgen, plus presets for popular identity providers.
Package oauth defines OAuth 2.0 / OpenID Connect provider configurations for authgen, plus presets for popular identity providers.
Package ratelimit provides the rate limiter used to throttle authentication attempts.
Package ratelimit provides the rate limiter used to throttle authentication attempts.
Package schema describes the database tables authgen needs and lets the host application map them onto its own table and column names.
Package schema describes the database tables authgen needs and lets the host application map them onto its own table and column names.
Package store defines the persistence interface authgen uses and the records it persists.
Package store defines the persistence interface authgen uses and the records it persists.
memstore
Package memstore is an in-memory store.Store for tests and prototyping.
Package memstore is an in-memory store.Store for tests and prototyping.
postgres
Package postgres implements store.Store on PostgreSQL using pgx/v5 and raw SQL.
Package postgres implements store.Store on PostgreSQL using pgx/v5 and raw SQL.
storetest
Package storetest is a conformance suite for store.Store implementations.
Package storetest is a conformance suite for store.Store implementations.
transport
admin
Package admin exposes authgen's administrative operations over HTTP: user search and inspection, disabling, deleting, signing users out, resetting MFA, SAML connection management and the audit log.
Package admin exposes authgen's administrative operations over HTTP: user search and inspection, disabling, deleting, signing users out, resetting MFA, SAML connection management and the audit log.
graphql
Package graphql exposes authgen's JSON flows as a GraphQL endpoint.
Package graphql exposes authgen's JSON flows as a GraphQL endpoint.
rest
Package rest exposes authgen as a JSON REST API (plus the browser redirect endpoints OAuth, SAML and email links require).
Package rest exposes authgen as a JSON REST API (plus the browser redirect endpoints OAuth, SAML and email links require).

Jump to

Keyboard shortcuts

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