theauth

package module
v2.10.0 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: MIT Imports: 78 Imported by: 2 modules, 1 package

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 ¶

theAuth

theauth-go

Go authentication library: OAuth 2.1 authorization server, MCP authorization, passkeys, SAML, SCIM and DPoP.
Mount it into your own net/http, chi, Gin, Echo or Fiber server. Your data stays in your own database (memory, SQLite, Postgres or MySQL). Self-hosted, MIT licensed, no hosted service.

Go Reference Go version Latest release CI CodeQL Go Report Card Coverage OpenSSF Scorecard SLSA 3 Discord Context7

Website · Quickstart · Docs · pkg.go.dev · Examples · Discussions · Discord


What it is

theauth-go is the Go library for theAuth. It handles sign-in for people (passwords, magic links, social login, passkeys, TOTP, SAML SSO, SCIM provisioning) and for software (an OAuth 2.1 authorization server with PKCE, DPoP, device login, token exchange and agent identities, plus a resource server module for MCP).

It runs inside your process as an http.Handler. You keep your users, sessions and tokens in your own database. The root module is Go 1.25, MIT licensed, and every release is signed and ships an SBOM. The TypeScript library is glincker/theauth.

Contents

Install

go get github.com/glincker/theauth-go/v2
go get github.com/glincker/theauth-go/storage/sqlite   # optional, embedded SQLite backend

The module path ends in /v2. The first resolvable v2 tag is v2.6.0, and the old path without /v2 is frozen at v1.0.0. See Migrating to /v2.

Verify releases

Release assets are signed keyless with cosign through GitHub Actions OIDC. Download checksums.txt, checksums.txt.sig and checksums.txt.cert from the release, then verify (replace v2.8.0 with your tag):

cosign verify-blob \
  --certificate-identity "https://github.com/glincker/theauth-go/.github/workflows/release.yml@refs/tags/v2.8.0" \
  --certificate-oidc-issuer "https://token.actions.githubusercontent.com" \
  --signature checksums.txt.sig --certificate checksums.txt.cert checksums.txt
sha256sum --ignore-missing -c checksums.txt

Each theauth-go-v*.tar.gz and its .sbom.json also ship with .sig and .cert files that verify the same way.

Packages

One Go module at the root plus three nested modules (mcpresource, storage/sqlite, audit/sinks/otlp) that carry their own dependencies. Everything else is a package inside the root module. Full index on pkg.go.dev.

Group Packages
Core theauth-go/v2 (server, sessions, OAuth 2.1 authorization server, agent identity, MCP authorization), admin, crypto, email, policy, clientauth (device login for Go CLIs), otp, openapi, mcpresource (separate module)
Storage storage, storage/memory, storage/postgres, storage/mysql, storage/sqlite (separate module), storagetest
Audit sinks audit/sinks/splunkhec, audit/sinks/webhook, audit/sinks/otlp (separate module)
Gin adapter adapters/gin (separate module): native Authn, RequireAuth, RequireAbility, accessors and Mount
Echo adapter adapters/echo (separate module): the same set for Echo v4
Fiber adapter adapters/fiber (separate module): the same set for Fiber v2 through its net/http adaptor (responses are buffered)
Providers provider/ apple, bitbucket, discord, facebook, github, gitlab, google, linkedin, microsoft, slack, twitch, x, oidc, and generic for 16 more (Spotify, Dropbox, Zoom, Kakao, Naver, Patreon, Box, Salesforce, Figma, Codeberg, Linear, PayPal, Kick, Hugging Face, Vercel, Yandex)
Commands theauth-go (secrets, OpenAPI), theauth-doctor (security doctor), theauth-migrate (Auth0 and Cognito import)

Modules on pkg.go.dev

Module Go Reference
github.com/glincker/theauth-go/v2 1.25 pkg.go.dev
github.com/glincker/theauth-go/mcpresource 1.25 pkg.go.dev
github.com/glincker/theauth-go/storage/sqlite 1.26 pkg.go.dev
github.com/glincker/theauth-go/adapters/gin 1.26 pkg.go.dev
github.com/glincker/theauth-go/adapters/echo 1.26 pkg.go.dev
github.com/glincker/theauth-go/adapters/fiber 1.26 pkg.go.dev

The TypeScript packages are listed in the theAuth README.

Quick start: net/http and SQLite

A complete server with sign-up, sign-in, magic links, sessions and one protected route, stored in a single SQLite file. Errors are checked; paste it into a main package. The storage/sqlite module needs Go 1.26.

package main

import (
	"context"
	"database/sql"
	"log"
	"net/http"

	"github.com/glincker/theauth-go/v2"
	sqlitestore "github.com/glincker/theauth-go/storage/sqlite"
	_ "modernc.org/sqlite"
)

func main() {
	ctx := context.Background()
	db, err := sql.Open("sqlite", "file:app.db?_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_txlock=immediate")
	if err != nil {
		log.Fatal(err)
	}
	if err := sqlitestore.Migrate(ctx, db); err != nil {
		log.Fatal(err)
	}
	store, err := sqlitestore.New(db)
	if err != nil {
		log.Fatal(err)
	}

	a, err := theauth.New(theauth.Config{CoreStorage: store, BaseURL: "http://localhost:8080"})
	if err != nil {
		log.Fatal(err)
	}
	defer a.Close()

	mux := http.NewServeMux()
	mux.Handle("/auth/", a.Handler()) // sign-up, sign-in, magic link, sessions
	mux.Handle("GET /me", a.RequireAuth()(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user, _ := theauth.UserFromContext(r.Context())
		w.Write([]byte("hello " + user.Email))
	})))
	log.Fatal(http.ListenAndServe(":8080", mux))
}

For Postgres, chi or a runnable CLI with API tokens and device login, see examples/single-binary-sqlite and the Quick Start.

Mounting: a.Handler() returns a plain http.Handler for net/http's ServeMux and keeps the routes at their configured paths (/auth/..., /oauth/...), so no http.StripPrefix is needed. With chi, call a.Mount(r) on your router instead. Both register the same routes.

Quick start: agent identity and delegation

Give an agent its own credential, then let it act for a user with a narrower scope. This needs Config.AuthorizationServer (which requires a 32 byte EncryptionKey) and Config.AgentIdentity, on a storage backend with agent identity support (memory, Postgres or MySQL; not SQLite). RegisterAgent creates the agent and, because Resource is set, a delegation grant from the user to the agent in one call.

package main

import (
	"context"
	"log"

	"github.com/glincker/theauth-go/v2"
	"github.com/glincker/theauth-go/v2/storage/memory"
)

func main() {
	ctx := context.Background()
	a, err := theauth.New(theauth.Config{
		Storage:       memory.New(),
		BaseURL:       "https://as.example.com",
		EncryptionKey: []byte("0123456789abcdef0123456789abcdef"), // 32 bytes, load from your secrets manager
		AuthorizationServer: &theauth.AuthorizationServerConfig{
			Issuer: "https://as.example.com",
			Resources: []theauth.ProtectedResource{
				{Identifier: "https://api.example.com", Scopes: []string{"read", "write"}},
			},
		},
		AgentIdentity: &theauth.AgentConfig{},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer a.Close()

	// The human who owns the agent. In a real app this is a signed-in user.
	user, err := a.UserByID(ctx, ownerID)
	if err != nil {
		log.Fatal(err)
	}

	// 1. Create the agent and a delegation grant for "read" on one resource.
	reg, err := a.RegisterAgent(ctx, theauth.RegisterAgentInput{
		OwnerID:  user.ID,
		Name:     "report-bot",
		Scope:    []string{"read"},
		Resource: "https://api.example.com",
	})
	if err != nil {
		log.Fatal(err)
	}
	// reg.Secret.ClientID and reg.Secret.Secret are the agent's credential.
	// The secret is shown once and only its Argon2id hash is stored.

	// 2. The agent authenticates as itself (client credentials).
	self, err := a.ClientCredentialsToken(ctx, theauth.TokenRequest{
		GrantType:    "client_credentials",
		ClientID:     reg.Secret.ClientID,
		ClientSecret: reg.Secret.Secret,
		Resource:     "https://api.example.com",
		Scope:        []string{"read"},
	})
	if err != nil {
		log.Fatal(err)
	}
	_ = self.AccessToken // sub is "agent:<id>"

	// 3. The agent trades a user's access token for a delegated one
	// (RFC 8693). The result carries the user as sub and the agent in act.
	delegated, err := a.ExchangeToken(ctx, theauth.TokenExchangeRequest{
		ClientID:         reg.Secret.ClientID,
		ClientSecret:     reg.Secret.Secret,
		SubjectToken:     userAccessToken, // issued to the user by this authorization server
		SubjectTokenType: "urn:ietf:params:oauth:token-type:access_token",
		Resource:         "https://api.example.com",
		Scope:            []string{"read"},
	})
	if err != nil {
		log.Fatal(err)
	}
	log.Println("delegated token expires in", delegated.ExpiresIn, "seconds")
}

ownerID and userAccessToken stand in for values from your sign-in flow (the user's ULID and an access token the authorization server issued to that user). Revoke access at any point with RevokeDelegation, SuspendAgent or RevokeAgent; resource servers see the change on their next introspection. Details: Agent identity and revocation, Agent delegation and Authorization server.

What you can build

Add sign-in to a Go web app

Email and password, magic links, 12 OAuth login providers, generic OIDC and 16 more catalog providers, with server-side sessions. Start with the net/http quick start or the Gin, Echo and Fiber adapters. Guide: Add an OAuth provider.

Run an OAuth 2.1 authorization server in Go

Authorization code with PKCE, refresh rotation, client_credentials, token exchange, PAR, JAR, CIBA and DPoP, with dynamic client registration and client ID metadata documents. Guide: Authorization server.

Secure an MCP server

Use theauth-go as the authorization server for MCP clients, and the separate mcpresource module to validate tokens and guard tools in your MCP resource server. Example: examples/mcp-server. Guides: MCP authorization, Protect MCP tools.

Passkeys and WebAuthn

Discoverable passkey login and TOTP with recovery codes, plus step-up checks with RequireRecentAuth. Example: examples/webauthn-passkey. Guide: Enable passkeys.

Device login for Go CLIs

RFC 8628 device authorization on the server and the clientauth package in your CLI. Example: examples/cli-login. Guide: CLI login.

SAML SSO and SCIM provisioning

SAML 2.0 single sign-on, SCIM 2.0 user provisioning, organizations, RBAC and an append-only audit log with Splunk, webhook and OTLP sinks. Needs memory, Postgres or MySQL storage (not SQLite). Guide: Splunk audit streaming.

Agent identity and delegation

Give an AI agent its own credential and let it act for a user with a narrower scope. See the agent quick start.

Features

Area What you get Docs
Sign-in Email and password (Argon2id, 12 character minimum), magic links, 12 OAuth login providers, generic OIDC Add an OAuth provider
Second factors WebAuthn passkeys with discoverable login, TOTP with recovery codes, step-up with RequireRecentAuth Enable passkeys
Sessions Opaque server-side sessions, session list and revoke, idle timeout Configuration
API tokens and CLIs Scoped tokens with RequireAbility, RFC 8628 device login via the clientauth package API tokens, CLI login
OAuth 2.1 server Authorization code with PKCE, refresh rotation, client_credentials, token exchange, CIBA, PAR, JAR, DPoP OAuth 2.1 primer, Authorization server
Token policy, RAR and ID-JAG Per-client signing algorithm (EdDSA, ES256, RS256) and opaque access tokens, RFC 9396 authorization_details end to end, and ID-JAG issue and redeem over token exchange and jwt-bearer Token policy, RAR, ID-JAG
OpenID Provider ID tokens with nonce and at_hash, userinfo, RP-initiated and back-channel logout, pairwise subjects, OpenID discovery fields OpenID Provider
Multi-replica and abuse controls Pluggable rate limiter, DPoP replay cache and CIMD cache (memory, SQL, Redis or your own), per-IP and per-client limits and an Argon2id concurrency cap on the OAuth endpoints Pluggable stores, Endpoint limits, Request admission
Browserless OAuth RFC 8628 device authorization grant on the authorization server with a themable verification page, plus scoped one-time registration tokens for agents Device grant, Registration tokens
One-time codes Email and SMS OTP with pluggable senders (Twilio built in), resend cooldown, attempt limit, lockout, constant-time compare OTP
More sign-in providers Table-driven catalog of 16 more OAuth providers, custom specs, and OIDC discovery overrides Provider catalog
Developer CLI and OpenAPI theauth-go secret and theauth-go openapi, plus openapi.Generate for your own router CLI
MCP and agents MCP authorization (protected resource metadata, CIMD), agent identities with delegation, mcpresource SDK module (scope and step-up guards, tool security metadata) MCP authorization, Resource server, Protect MCP tools
Enterprise SAML 2.0 SSO, SCIM 2.0, organizations, RBAC, append-only audit log with SIEM sinks Splunk audit streaming, Threat model
Policy Authorization policy engine Policy engine
Observability OpenTelemetry spans, Prometheus metrics OpenTelemetry tracing, Metrics
Supply chain SBOM and Sigstore signed release artifacts, SLSA 3 provenance Releases and verification

Running more than one replica

Rate limits, DPoP replay records and the CIMD cache are per process by default. Share them through the database you already have:

db := stdlib.OpenDBFromPool(pool) // pgx stdlib
kvStore, _ := sqlkv.New(db, sqlkv.Postgres)
_ = kvStore.EnsureSchema(ctx)

auth, _ := theauth.New(theauth.Config{
    // ...
    Stores: kv.FromCache(kvStore), // or kv/redis, or your own kv.RateLimiter / kv.ReplayCache / kv.Cache
})

Details and the Redis adapter are in docs/pluggable-stores.md.

Choosing between a library and a hosted service

theauth-go is a library you embed and run yourself, so you own the database and the operations. It does not include a hosted login UI or a managed service. If you need either, it is not the right shape for you. The TypeScript library at glincker/theauth covers Node, Bun, Deno and Workers backends.

Storage backends

Persistence is split into small capability interfaces, and New fails at startup if a feature you enabled has no matching capability. Full matrix: Capability interfaces.

Capability memory sqlite postgres mysql
Users, sessions, magic links, passwords Yes Yes Yes Yes
OAuth accounts, passkeys, TOTP, audit log Yes Yes Yes Yes
Scoped API tokens, device grant, session management Yes Yes Yes Yes
Organizations, SAML, SCIM, RBAC Yes No Yes Yes
OAuth 2.1 authorization server, agent identity Yes No Yes Yes
CIBA backchannel auth Yes No Yes No
OAuth device grant (RFC 8628) and registration tokens Yes No Yes Yes
Durable JWT-bearer jti replay, policy engine storage Yes No No No

Postgres and MySQL implement the newer token, device, session and throttle capabilities and pass the new storagetest suites against live PostgreSQL 16 and MySQL 8. The older shared contract gate for those two adapters is still off in CI because some older subtests fail, so treat their support for the newer features as newly added. You can write your own backend and verify it with the public storagetest suite.

Stability

Packages and APIs that were Stable before v2.6 keep their SemVer guarantees. Among the additions in v2.6, only the storage capability split, Handler() and Config.PathPrefix are Stable. Experimental: storage/sqlite, clientauth, policy, the agent identity and revocation APIs, Doctor, Config.ProviderResolver and the new optional storage capabilities. Experimental APIs may change in a minor release. The SemVer rules and the list of stable packages are in STABILITY.md.

Security

  • Passwords are hashed with Argon2id, sessions are opaque and stored server side, and agent secrets are shown once and stored only as hashes.
  • Release assets are signed with cosign, ship an SBOM and carry SLSA 3 provenance. See Verify releases.
  • CI runs CodeQL, govulncheck, dependency review and OpenSSF Scorecard.
  • The threat model and the theauth-doctor security doctor describe what is covered and how to check a deployment.
  • Report vulnerabilities privately through GitHub advisories or support@glinr.com, as described in the security policy. Do not open a public issue.

Migrating

FAQ

Does theauth-go work without Postgres? Yes. Use storage/sqlite for a single static binary with one database file, storage/memory for tests, or MySQL. SQLite has no organizations, SAML, SCIM, RBAC or OAuth authorization server.

How do I add passkeys to a Go app? Set Config.WebAuthn and use a storage backend that implements WebAuthnStorage (all four built in backends do). Register and login routes are then mounted under your auth handler. See the passkeys guide and examples/webauthn-passkey.

Does it support MCP authorization? Yes. The library can act as the OAuth 2.1 authorization server and publishes protected resource metadata. The separate zero dependency mcpresource module validates tokens inside an MCP resource server. See MCP authorization and examples/mcp-server.

How do I migrate from Auth0, Cognito or Keycloak? Follow Migrate from Auth0, Migrate from Cognito or Migrate from Keycloak. Password hashes carry over and upgrade to Argon2id at each user's first login. Coming from hand-rolled sessions: Migrate from hand-rolled sessions.

Which Go versions are supported? The root module declares Go 1.25. storage/sqlite is a separate module and needs Go 1.26.

Is it a hosted service? No. It is a library you run inside your own process, under the MIT license.

Examples

Runnable apps live in examples/, each with its own go.mod and a short README. More in the example apps guide.

Area Examples
Frameworks single-binary-sqlite, chi-app, gin-app, echo-app, stdlib-app
OAuth providers oauth-multi-provider, oauth-apple, oauth-bitbucket, oauth-facebook, oauth-gitlab, oauth-linkedin, oauth-slack, oauth-twitch, oauth-x
Second factors webauthn-passkey, totp-stepup
Agents and CLIs mcp-server, cli-login
Operations doctor-admin, observability-otel, observability-prom

Made by GLINCKER, a GLINR STUDIOS company

theAuth is built and maintained in the open by GLINCKER, the open-source division of GLINR STUDIOS. Founder: thegdsks.com. The TypeScript library is glincker/theauth.

Partner project What it is Site Source
LevelRail Self-hosted deployment platform: push to git, get a running app. levelrail.com glincker/levelrail
theSVG Open-source brand SVG icons. thesvg.org glincker/thesvg
GLINUI Open-source liquid glass UI components for React. theauth.dev is designed with it. glinui.com glincker/glinui

Documentation ¶

Overview ¶

Package theauth is auth for AI agents and humans in Go. It embeds into a net/http or chi server and keeps all data in your own database (memory, SQLite, Postgres or MySQL).

For agents it provides an OAuth 2.1 authorization server (PKCE-mandatory authorization code, client_credentials, refresh token rotation, RFC 8693 token exchange, CIBA, PAR, JAR, DPoP-bound tokens), MCP authorization with RFC 9728 protected resource metadata, and agent identities with revocable delegation chains. Per-client token policy, RFC 9396 rich authorization requests and ID-JAG are supported on top of token exchange.

For humans it provides email and password, magic links, email and SMS one-time codes, WebAuthn passkeys, TOTP, OAuth and OIDC login providers, RFC 8628 device login for CLIs, SAML SSO, SCIM, organizations with RBAC, and an async audit log.

Quick start:

a, err := theauth.New(theauth.Config{Storage: memory.New(), BaseURL: "http://localhost:8080"})
if err != nil {
	log.Fatal(err)
}
defer a.Close()
mux := http.NewServeMux()
mux.Handle("/auth/", a.Handler())

Here memory is github.com/glincker/theauth-go/v2/storage/memory. See docs/AGENTS.md or https://docs.theauth.dev/go for the full feature list and guides.

Index ¶

Constants ¶

View Source
const (
	// CodeAdmissionRateLimited is the 429 code written by Admission.
	CodeAdmissionRateLimited = "RATE_LIMITED"
	// CodeAdmissionCSRFRejected is the 403 code written by Admission.
	CodeAdmissionCSRFRejected = "CSRF_REJECTED"
)

Error codes written by the admission middleware. They match the codes the TypeScript library and the client SDKs (IsCSRFRejected, IsRateLimited) key on.

View Source
const (
	AbilityRoot             = apitokens.AbilityRoot
	OwnerKindUser           = apitokens.OwnerKindUser
	OwnerKindServiceAccount = apitokens.OwnerKindServiceAccount
	APITokenKindPersonal    = apitokens.APITokenKindPersonal
	APITokenKindAgent       = apitokens.APITokenKindAgent
	DeviceStatusPending     = apitokens.DeviceStatusPending
	DeviceStatusApproved    = apitokens.DeviceStatusApproved
	DeviceStatusDenied      = apitokens.DeviceStatusDenied
	DeviceStatusRedeemed    = apitokens.DeviceStatusRedeemed
)

Ability, owner, token kind and device status constants.

View Source
const (
	PrincipalSession = apitokens.PrincipalSession
	PrincipalToken   = apitokens.PrincipalToken
	ActorKindUser    = apitokens.ActorKindUser
	ActorKindAgent   = apitokens.ActorKindAgent
)

Principal kinds and actor kinds.

View Source
const (
	RevocationSession         = revocation.Session
	RevocationAPIToken        = revocation.APIToken
	RevocationAgent           = revocation.Agent
	RevocationAgentCredential = revocation.AgentCredential
	RevocationDelegation      = revocation.Delegation
	// RevocationOwner means a user was disabled or deleted: every credential
	// that user owns or delegated is void.
	RevocationOwner = revocation.Owner
)

Revocation kinds.

View Source
const (
	PermissionBillingRead    = models.PermissionBillingRead
	PermissionBillingWrite   = models.PermissionBillingWrite
	PermissionBillingAdmin   = models.PermissionBillingAdmin
	PermissionUsersRead      = models.PermissionUsersRead
	PermissionUsersInvite    = models.PermissionUsersInvite
	PermissionUsersAdmin     = models.PermissionUsersAdmin
	PermissionRolesRead      = models.PermissionRolesRead
	PermissionRolesAdmin     = models.PermissionRolesAdmin
	PermissionAuditRead      = models.PermissionAuditRead
	PermissionSAMLAdmin      = models.PermissionSAMLAdmin
	PermissionSCIMAdmin      = models.PermissionSCIMAdmin
	PermissionSessionsRevoke = models.PermissionSessionsRevoke

	// v2.0 phase 6 additions. agents:admin grants organization-scoped
	// agent CRUD via /admin/v1/.../agents; delegations:admin grants
	// delegation CRUD via /admin/v1/.../delegations. Seeded into every
	// organization's "owner" and "admin" default roles.
	PermissionAgentsAdmin      = models.PermissionAgentsAdmin
	PermissionDelegationsAdmin = models.PermissionDelegationsAdmin

	// v2.3 identity-linking permissions. Both are user-scoped (caller can
	// only link/merge their own account); admin override paths go through
	// the /admin/v1 surface.
	PermissionAccountLink  = models.PermissionAccountLink
	PermissionAccountMerge = models.PermissionAccountMerge
)

Seeded permission catalog. Every consumer's permission set extends (never shrinks) this list; New returns an error if a custom Permission name duplicates a seeded one with a different description (defensive against silent overrides).

The catalog values live in internal/models so storage adapters can reference the same string literals without importing the root package. The list is intentionally finite and small. Wildcards and ABAC are deferred to v1.x per the v1.0 design document.

View Source
const (
	CodeWeakPassword         = models.CodeWeakPassword
	CodeEmailTaken           = models.CodeEmailTaken
	CodeInvalidCredentials   = models.CodeInvalidCredentials
	CodeRateLimited          = models.CodeRateLimited
	CodePasswordResetExpired = models.CodePasswordResetExpired
	CodePasswordResetInvalid = models.CodePasswordResetInvalid

	// v0.5 codes.
	CodeTOTPRequired    = models.CodeTOTPRequired
	CodeInvalidTOTP     = models.CodeInvalidTOTP
	CodeAlreadyEnrolled = models.CodeAlreadyEnrolled
	CodeWebAuthn        = models.CodeWebAuthn

	// v2.3 identity-linking codes.
	CodeIdentityConflict = models.CodeIdentityConflict
	CodeStepUpRequired   = models.CodeStepUpRequired
	CodeLastAuthMethod   = models.CodeLastAuthMethod
)

Stable error codes that callers can switch on. New endpoints return TheAuthError; old endpoints keep returning the sentinels above. Re-exported from internal/models (PR D architecture reorg, 2026-06-20) so internal service packages can construct TheAuthError with these codes without taking an import cycle on the root package.

View Source
const (
	// CodePasswordChangeRequired is returned at sign-in when the account is
	// flagged MustChangePassword; the user must complete a password reset.
	CodePasswordChangeRequired = models.CodePasswordChangeRequired
	// CodeAccountDisabled is returned at sign-in for a disabled account.
	CodeAccountDisabled = models.CodeAccountDisabled
	// CodeReauthRequired means the session needs a recent authentication.
	CodeReauthRequired = models.CodeReauthRequired
	// CodeSessionLimit means the concurrent session cap rejected the sign-in.
	CodeSessionLimit = models.CodeSessionLimit
	// CodeProviderGrantRevoked means the upstream provider rejected the refresh token.
	CodeProviderGrantRevoked = models.CodeProviderGrantRevoked
	// CodeProviderNoRefresh means the stored provider grant cannot be refreshed.
	CodeProviderNoRefresh = models.CodeProviderNoRefresh
)

Account lifecycle codes.

View Source
const (
	OAuthErrInvalidRequest          = "invalid_request"
	OAuthErrInvalidClient           = "invalid_client"
	OAuthErrInvalidGrant            = "invalid_grant"
	OAuthErrInvalidScope            = "invalid_scope"
	OAuthErrUnsupportedGrantType    = "unsupported_grant_type"
	OAuthErrUnsupportedResponseType = "unsupported_response_type"
	OAuthErrAccessDenied            = "access_denied"
	OAuthErrServerError             = "server_error"
	OAuthErrInvalidTarget           = "invalid_target"
)

OAuth 2.1 standard error codes returned in JSON error bodies.

View Source
const (
	CodeAccountLocked     = models.CodeAccountLocked
	CodeSignupClosed      = models.CodeSignupClosed
	CodeSetupTokenInvalid = models.CodeSetupTokenInvalid
	CodeBadRequest        = models.CodeBadRequest
	CodeUnauthorized      = models.CodeUnauthorized
	CodeForbidden         = models.CodeForbidden
	CodeNotFound          = models.CodeNotFound
	CodeConflict          = models.CodeConflict
	CodeInternal          = models.CodeInternal
)

Error codes added with the auth hardening work.

View Source
const (
	SigninStepFull         = password.SigninStepFull
	SigninStepTOTPRequired = password.SigninStepTOTPRequired
)

SigninStep values re-exported for the v0.5 public surface.

View Source
const (
	AuthLevelFull       = models.AuthLevelFull
	AuthLevelPending2FA = models.AuthLevelPending2FA
)
View Source
const (
	OrgRoleOwner  = models.OrgRoleOwner
	OrgRoleAdmin  = models.OrgRoleAdmin
	OrgRoleMember = models.OrgRoleMember
)
View Source
const (
	JWKSStateNext     = models.JWKSStateNext
	JWKSStateCurrent  = models.JWKSStateCurrent
	JWKSStatePrevious = models.JWKSStatePrevious
	JWKSStateRetired  = models.JWKSStateRetired
)

JWKS key state constants.

View Source
const (
	ClientOwnerKindUser         = models.ClientOwnerKindUser
	ClientOwnerKindOrganization = models.ClientOwnerKindOrganization
	ClientOwnerKindAgent        = models.ClientOwnerKindAgent
	ClientOwnerKindAnonymous    = models.ClientOwnerKindAnonymous
)

Client owner kind constants persisted in oauth_clients.owner_kind.

View Source
const (
	ClientAuthSecretBasic = models.ClientAuthSecretBasic
	ClientAuthSecretPost  = models.ClientAuthSecretPost
	ClientAuthNone        = models.ClientAuthNone
)

Client authentication method constants.

View Source
const (
	GrantTypeAuthorizationCode = models.GrantTypeAuthorizationCode
	GrantTypeRefreshToken      = models.GrantTypeRefreshToken
	GrantTypeClientCredentials = models.GrantTypeClientCredentials
	GrantTypeTokenExchange     = models.GrantTypeTokenExchange
)

Grant type constants.

View Source
const (
	AgentStatusActive    = models.AgentStatusActive
	AgentStatusSuspended = models.AgentStatusSuspended
	AgentStatusRevoked   = models.AgentStatusRevoked
)

Agent lifecycle status values persisted in agents.status.

View Source
const (
	AgentCredentialKindSecret = models.AgentCredentialKindSecret
	AgentCredentialKindX509   = models.AgentCredentialKindX509
	AgentCredentialKindJWK    = models.AgentCredentialKindJWK
)

Agent credential kind constants persisted in agent_credentials.kind.

View Source
const (
	BackchannelStatusPending  = models.BackchannelStatusPending
	BackchannelStatusApproved = models.BackchannelStatusApproved
	BackchannelStatusDenied   = models.BackchannelStatusDenied
)

CIBA status constants.

View Source
const (
	AccessTokenFormatJWT    = models.AccessTokenFormatJWT
	AccessTokenFormatOpaque = models.AccessTokenFormatOpaque
)

Access token formats a client can be registered with (OAuthClient.AccessTokenFormat).

View Source
const (
	SubjectTypePublic   = models.SubjectTypePublic
	SubjectTypePairwise = models.SubjectTypePairwise
)

Subject identifier types a client can be registered with (OAuthClient.SubjectType).

View Source
const (
	DeviceAuthPending  = models.DeviceAuthPending
	DeviceAuthApproved = models.DeviceAuthApproved
	DeviceAuthDenied   = models.DeviceAuthDenied
	DeviceAuthConsumed = models.DeviceAuthConsumed
)

DeviceAuthorization status values.

View Source
const (
	DeviceStatusActive  = models.DeviceStatusActive
	DeviceStatusRevoked = models.DeviceStatusRevoked
)

Device status values.

View Source
const (
	StatusSuccess = observability.StatusSuccess
	StatusError   = observability.StatusError

	SpanOAuthToken             = observability.SpanOAuthToken
	SpanOAuthIntrospect        = observability.SpanOAuthIntrospect
	SpanOAuthRevoke            = observability.SpanOAuthRevoke
	SpanOAuthAuthorize         = observability.SpanOAuthAuthorize
	SpanOAuthDCRRegister       = observability.SpanOAuthDCRRegister
	SpanSessionCreate          = observability.SpanSessionCreate
	SpanSessionRevoke          = observability.SpanSessionRevoke
	SpanPasswordVerify         = observability.SpanPasswordVerify
	SpanWebauthnRegisterBegin  = observability.SpanWebauthnRegisterBegin
	SpanWebauthnRegisterFinish = observability.SpanWebauthnRegisterFinish
	SpanWebauthnLoginBegin     = observability.SpanWebauthnLoginBegin
	SpanWebauthnLoginFinish    = observability.SpanWebauthnLoginFinish
	SpanTOTPVerify             = observability.SpanTOTPVerify
	SpanSAMLACS                = observability.SpanSAMLACS
	SpanSCIMUsersList          = observability.SpanSCIMUsersList
	SpanSCIMUsersGet           = observability.SpanSCIMUsersGet
	SpanSCIMUsersPost          = observability.SpanSCIMUsersPost
	SpanSCIMUsersPatch         = observability.SpanSCIMUsersPatch
	SpanSCIMUsersDelete        = observability.SpanSCIMUsersDelete
	SpanAgentCreate            = observability.SpanAgentCreate
	SpanAgentSuspend           = observability.SpanAgentSuspend
	SpanAgentRevoke            = observability.SpanAgentRevoke
	SpanDelegationGrant        = observability.SpanDelegationGrant
	SpanDelegationRevoke       = observability.SpanDelegationRevoke

	MetricOAuthTokenRequestsTotal      = observability.MetricOAuthTokenRequestsTotal
	MetricOAuthTokenLatency            = observability.MetricOAuthTokenLatency
	MetricOAuthIntrospectRequestsTotal = observability.MetricOAuthIntrospectRequestsTotal
	MetricOAuthIntrospectLatency       = observability.MetricOAuthIntrospectLatency
	MetricClientAuthCacheHits          = observability.MetricClientAuthCacheHits
	MetricClientAuthCacheMisses        = observability.MetricClientAuthCacheMisses
	MetricClientAuthCacheSize          = observability.MetricClientAuthCacheSize
	MetricRateLimitBlockedTotal        = observability.MetricRateLimitBlockedTotal
	MetricAuditDroppedTotal            = observability.MetricAuditDroppedTotal
	MetricAuditQueueDepth              = observability.MetricAuditQueueDepth
	MetricSessionActive                = observability.MetricSessionActive
	MetricWebAuthnChallengesInFlight   = observability.MetricWebAuthnChallengesInFlight
	MetricSAMLInFlightAuthnReq         = observability.MetricSAMLInFlightAuthnReq

	AttrStatus    = observability.AttrStatus
	AttrGrantType = observability.AttrGrantType
	AttrClientID  = observability.AttrClientID
	AttrErrorCode = observability.AttrErrorCode
	AttrSubject   = observability.AttrSubject
	AttrScope     = observability.AttrScope
	AttrResource  = observability.AttrResource
	AttrTenantID  = observability.AttrTenantID
	AttrRule      = observability.AttrRule
	AttrKind      = observability.AttrKind
)

Span / metric / attribute names re-exported so consumers building dashboards or alerts can reference them by symbol rather than by stringly-typed name.

View Source
const (
	AuthEventLoginSuccess           = authevents.LoginSuccess
	AuthEventLoginFailure           = authevents.LoginFailure
	AuthEventMFASuccess             = authevents.MFASuccess
	AuthEventMFAFailure             = authevents.MFAFailure
	AuthEventPasswordChanged        = authevents.PasswordChanged
	AuthEventPasswordResetRequested = authevents.PasswordResetRequested
	AuthEventPasswordResetCompleted = authevents.PasswordResetCompleted
	AuthEventPasskeyAdded           = authevents.PasskeyAdded
	AuthEventPasskeyRemoved         = authevents.PasskeyRemoved
	AuthEventPasskeyRenamed         = authevents.PasskeyRenamed
	AuthEventPasskeyCloneWarning    = authevents.PasskeyCloneWarning
	AuthEventTOTPEnrolled           = authevents.TOTPEnrolled
	AuthEventTOTPDisabled           = authevents.TOTPDisabled
	AuthEventRecoveryCodesRegen     = authevents.RecoveryCodesRegen
	AuthEventSessionRevoked         = authevents.SessionRevoked
	AuthEventTokenMinted            = authevents.TokenMinted
	AuthEventTokenRevoked           = authevents.TokenRevoked
	AuthEventOAuthLinked            = authevents.OAuthLinked
)

The AuthEventType values emitted by the library. The strings are stable.

View Source
const (
	SeverityCritical = doctor.SeverityCritical
	SeverityHigh     = doctor.SeverityHigh
	SeverityMedium   = doctor.SeverityMedium
	SeverityLow      = doctor.SeverityLow
	SeverityInfo     = doctor.SeverityInfo
)

Doctor severities, most serious first.

View Source
const (
	DoctorSignupOpen        = doctor.DoctorSignupOpen
	DoctorBootstrapOff      = doctor.DoctorBootstrapOff
	DoctorTrustedProxies    = doctor.DoctorTrustedProxies
	DoctorSecureCookie      = doctor.DoctorSecureCookie
	DoctorCSRFDisabled      = doctor.DoctorCSRFDisabled
	DoctorThrottleDisabled  = doctor.DoctorThrottleDisabled
	DoctorThrottleLax       = doctor.DoctorThrottleLax
	DoctorPasswordMinLength = doctor.DoctorPasswordMinLength
	DoctorPasswordNoBreach  = doctor.DoctorPasswordNoBreach
	DoctorAdminNoTOTP       = doctor.DoctorAdminNoTOTP
	DoctorNoSecondFactor    = doctor.DoctorNoSecondFactor
	DoctorSessionTTLLong    = doctor.DoctorSessionTTLLong
	DoctorSessionNoIdle     = doctor.DoctorSessionNoIdle
	DoctorTokenNoExpiry     = doctor.DoctorTokenNoExpiry
	DoctorTokenLongExpiry   = doctor.DoctorTokenLongExpiry
	DoctorTokenRoot         = doctor.DoctorTokenRoot
	DoctorAgentTokenLong    = doctor.DoctorAgentTokenLong
	DoctorTokensUnpruned    = doctor.DoctorTokensUnpruned
	DoctorSessionsUnpruned  = doctor.DoctorSessionsUnpruned
	DoctorEncryptionKey     = doctor.DoctorEncryptionKey
	DoctorAuditSink         = doctor.DoctorAuditSink
	DoctorWebAuthnRPID      = doctor.DoctorWebAuthnRPID
	DoctorRedirectAllowList = doctor.DoctorRedirectAllowList
)

Doctor finding IDs. They are stable and appear in docs/SECURITY-DOCTOR.md.

View Source
const (
	StepUpMethodPassword = "password"
	StepUpMethodTOTP     = "totp"
	StepUpMethodPasskey  = "passkey"
)

Step-up methods accepted by StepUp.

View Source
const AgentSubjectPrefix = models.AgentSubjectPrefix

AgentSubjectPrefix is prepended to an agent ID inside JWT sub and act.sub claims so resource servers can distinguish a user subject from an agent subject without consulting storage.

View Source
const DeviceAttestationJoinToken = models.DeviceAttestationJoinToken

DeviceAttestationJoinToken is the attestation kind of a device enrolled with a join token.

View Source
const GrantTypeCIBA = models.GrantTypeCIBA

GrantTypeCIBA is the CIBA grant type URN per RFC 9509.

View Source
const GrantTypeDeviceCode = models.GrantTypeDeviceCode

GrantTypeDeviceCode is the RFC 8628 grant type URN.

View Source
const MinPasswordLength = password.MinPasswordLength

MinPasswordLength is enforced at the library level (NIST 2024 baseline).

View Source
const PasswordResetTTL = password.PasswordResetTTL

PasswordResetTTL is how long a reset token stays valid after issuance.

View Source
const (
	ResponseTypeCode = models.ResponseTypeCode
)

Response type constants. OAuth 2.1 supports only "code".

View Source
const SystemRoleSuperAdmin = models.SystemRoleSuperAdmin

SystemRoleSuperAdmin is the global role whose presence on a user bypasses every permission check.

View Source
const (
	TokenTypeAccessToken = models.TokenTypeAccessToken
)

Token type URNs used by the RFC 8693 token-exchange grant.

View Source
const TokenTypeIDJAG = models.TokenTypeIDJAG

TokenTypeIDJAG is the token type URN of an Identity Assertion JWT Authorization Grant, used as requested_token_type and issued_token_type.

Variables ¶

View Source
var (
	ErrAPITokensDisabled          = apitokens.ErrAPITokensDisabled
	ErrAPITokenInvalid            = apitokens.ErrAPITokenInvalid
	ErrAbilityInvalid             = apitokens.ErrAbilityInvalid
	ErrAbilityNotHeld             = apitokens.ErrAbilityNotHeld
	ErrTokenTTLInvalid            = apitokens.ErrTokenTTLInvalid
	ErrDeviceUserCodeTaken        = apitokens.ErrDeviceUserCodeTaken
	ErrDeviceDisabled             = apitokens.ErrDeviceDisabled
	ErrDeviceAuthorizationPending = apitokens.ErrDeviceAuthorizationPending
	ErrDeviceSlowDown             = apitokens.ErrDeviceSlowDown
	ErrDeviceExpired              = apitokens.ErrDeviceExpired
	ErrDeviceDenied               = apitokens.ErrDeviceDenied
	ErrDeviceInvalid              = apitokens.ErrDeviceInvalid
	ErrDeviceAttemptsExceeded     = apitokens.ErrDeviceAttemptsExceeded
	ErrDeviceListUnsupported      = apitokens.ErrDeviceListUnsupported
	ErrAgentIdentityDisabled      = agent.ErrIdentityDisabled
)

Errors returned by the API token service and the device grant.

View Source
var (
	ErrInvalidToken     = models.ErrInvalidToken
	ErrSessionExpired   = models.ErrSessionExpired
	ErrUserNotFound     = errors.New("theauth: user not found")
	ErrMagicLinkExpired = models.ErrMagicLinkExpired
	ErrMagicLinkUsed    = errors.New("theauth: magic link already used")
	ErrEmailNotVerified = errors.New("theauth: email not verified")

	// ErrStorageNotFound is the canonical "row missing" sentinel that
	// storage adapters return on lookup misses.
	ErrStorageNotFound = models.ErrStorageNotFound

	// ErrBadCursor is returned by storage adapters when a caller-supplied
	// keyset pagination cursor fails to decode.
	ErrBadCursor = models.ErrBadCursor

	// ErrReplayDetected (v0.5) is returned by storage on a WebAuthn sign
	// count update where the new count is not strictly greater than the
	// stored value. The library treats this as a clone-attempt and refuses
	// the login (with the standard 0-stays-0 carve-out for authenticators
	// that do not implement counters; that case is handled by the caller).
	// PR D architecture reorg (2026-06-20): the canonical sentinel lives
	// in internal/webauthn so the extracted Service can return it; root
	// re-aliases here.
	ErrReplayDetected = internalwebauthn.ErrReplayDetected

	// ErrAlreadyEnrolled (v0.5) is returned when /auth/totp/enroll/finish is
	// called against a user who already has a confirmed TOTP secret. Callers
	// must DELETE /auth/totp first to re-enroll. PR D architecture reorg
	// (2026-06-20): canonical sentinel in internal/totp.
	ErrAlreadyEnrolled = internaltotp.ErrAlreadyEnrolled

	// ErrSCIMRequiresOrganizations is returned by New when Config.SCIM is
	// non-nil but Config.Organizations is nil. SCIM is meaningless without
	// multi-tenancy because every token is bound to one organization.
	ErrSCIMRequiresOrganizations = errors.New("theauth: SCIM requires Organizations to be enabled")
	// ErrSAMLRequiresOrganizations is returned by New when Config.SAML is
	// non-nil but Config.Organizations is nil. Single-tenant SAML is
	// meaningless; per-connection routing keys off organization ownership.
	ErrSAMLRequiresOrganizations = errors.New("theauth: SAML requires Organizations to be enabled")
	// ErrSAMLUnsignedAssertion is returned by FinishSAMLLogin when the
	// inbound SAML Response parses but its assertion is not signed.
	// PR D architecture reorg (2026-06-20): the canonical sentinel lives
	// in internal/saml so the extracted Service can return it; root
	// re-aliases here so errors.Is checks against the root name still
	// match.
	ErrSAMLUnsignedAssertion = internalsaml.ErrSAMLUnsignedAssertion
	// ErrSAMLMissingEmail is returned by FinishSAMLLogin when the mapped
	// email attribute is empty (the find-or-create email fallback path
	// cannot proceed).
	ErrSAMLMissingEmail = internalsaml.ErrSAMLMissingEmail
	// ErrSAMLInvalidAssertion wraps the underlying crewjam/saml validation
	// error for failed signature / conditions / replay checks.
	ErrSAMLInvalidAssertion = internalsaml.ErrSAMLInvalidAssertion
	// ErrLastOwner is returned when an org member removal would leave the
	// organization with zero owners.
	ErrLastOwner = models.ErrLastOwner
	// ErrUnsupportedFilter is returned by the SCIM filter parser on any
	// filter shape outside the documented eq-only whitelist.
	ErrUnsupportedFilter = errors.New("theauth: scim filter not supported")
	// ErrSlugTaken is returned when the supplied organization slug already
	// exists. PR F architecture reorg (2026-06-20): canonical sentinel
	// lives in internal/models so the extracted organization handler
	// package can reference it without importing root.
	ErrSlugTaken = models.ErrSlugTaken

	// ErrAdminRequiresRBAC is returned by New when Config.Admin is non-nil
	// but Config.RBAC is nil. The admin endpoints are permission-gated and
	// meaningless without RBAC.
	ErrAdminRequiresRBAC = errors.New("theauth: Admin requires RBAC to be enabled")
	// ErrForbidden indicates the caller lacks a required permission for
	// the requested operation. Handlers map this to 403 with code
	// "rbac.forbidden" in the RFC 7807 problem body.
	ErrForbidden = models.ErrForbidden
	// ErrUnknownPermission indicates a permission name not present in the
	// seeded or extended catalog. Mapped to 400 "rbac.unknown_permission".
	ErrUnknownPermission = models.ErrUnknownPermission
	// ErrRoleInUse indicates a DELETE role would leave the organization
	// without any user holding the "users:admin" permission. Mapped to
	// 409 "rbac.role_in_use".
	ErrRoleInUse = models.ErrRoleInUse
	// ErrNoActiveOrg indicates the session has no active_organization_id
	// set. Mapped to 403 "rbac.no_active_org".
	ErrNoActiveOrg = errors.New("theauth: session has no active organization")
	// ErrOrgMismatch indicates the session's active_organization_id does
	// not match the resource organization. Mapped to 403 "rbac.org_mismatch".
	ErrOrgMismatch = errors.New("theauth: session active organization does not match resource")
	// ErrRBACDisabled is returned by RBAC service methods invoked when
	// Config.RBAC is nil. The RequirePermission middleware short-circuits
	// to 500 rather than returning this error directly.
	ErrRBACDisabled = models.ErrRBACDisabled
)

Sentinel errors retained for backward compatibility with v0.1 callers that errors.Is-check against them. New code should prefer TheAuthError + the Code* constants below.

Model-layer sentinels (storage misses, expiry states, RBAC catalog rejections, organization invariants) are defined in internal/models and re-exported here via var aliases. Service-flow and admin precondition sentinels remain defined locally.

View Source
var (
	// ErrASRequiresEncryptionKey is returned by New when
	// Config.AuthorizationServer is non-nil but Config.EncryptionKey is not a
	// 32-byte AES-256 key. The encryption key protects JWKS private keys at
	// rest; running the AS without it would persist signing keys in plaintext.
	ErrASRequiresEncryptionKey = models.ErrASRequiresEncryptionKey

	// ErrASIssuerRequired is returned by New when Config.AuthorizationServer
	// is non-nil but Issuer is empty. RFC 8414 mandates an issuer identifier.
	ErrASIssuerRequired = models.ErrASIssuerRequired

	// ErrASUnsupportedAlg is returned by New for any signing algorithm other
	// than EdDSA. Phase 1 + 2 ships Ed25519 only; RS256 is the documented
	// fallback for a later phase.
	ErrASUnsupportedAlg = models.ErrASUnsupportedAlg

	// ErrOAuthInvalidRequest maps to the OAuth 2.1 "invalid_request" error.
	ErrOAuthInvalidRequest = models.ErrOAuthInvalidRequest

	// ErrOAuthInvalidClient maps to the OAuth 2.1 "invalid_client" error.
	ErrOAuthInvalidClient = models.ErrOAuthInvalidClient

	// ErrOAuthInvalidGrant maps to the OAuth 2.1 "invalid_grant" error,
	// covering expired or replayed authorization codes and refresh tokens.
	ErrOAuthInvalidGrant = models.ErrOAuthInvalidGrant

	// ErrOAuthInvalidScope maps to the OAuth 2.1 "invalid_scope" error.
	ErrOAuthInvalidScope = models.ErrOAuthInvalidScope

	// ErrOAuthUnsupportedGrantType maps to "unsupported_grant_type".
	ErrOAuthUnsupportedGrantType = models.ErrOAuthUnsupportedGrantType

	// ErrOAuthUnsupportedResponseType maps to "unsupported_response_type".
	ErrOAuthUnsupportedResponseType = models.ErrOAuthUnsupportedResponseType

	// ErrOAuthInvalidAuthorizationDetails maps to the RFC 9396 error
	// "invalid_authorization_details".
	ErrOAuthInvalidAuthorizationDetails = models.ErrOAuthInvalidAuthorizationDetails

	// ErrOAuthInvalidResource maps to RFC 8707 "invalid_target".
	ErrOAuthInvalidResource = models.ErrOAuthInvalidResource

	// ErrOAuthRegistrationDenied is returned when DCR is attempted without
	// a valid initial access token and AllowAnonymousRegistration is false.
	ErrOAuthRegistrationDenied = models.ErrOAuthRegistrationDenied

	// ErrOAuthRedirectURIMismatch is returned when the token request's
	// redirect_uri does not equal the value bound to the authorization code.
	ErrOAuthRedirectURIMismatch = models.ErrOAuthRedirectURIMismatch

	// ErrOAuthPKCEMismatch is returned when the supplied code_verifier does
	// not match the stored code_challenge under S256.
	ErrOAuthPKCEMismatch = models.ErrOAuthPKCEMismatch

	// ErrOAuthAudienceMismatch is returned at introspection when a token's
	// aud claim does not match the caller's expected resource identifier.
	ErrOAuthAudienceMismatch = models.ErrOAuthAudienceMismatch

	// ErrNotImplemented is returned by service paths that exist for forward
	// compatibility but whose body lands in a later phase. Currently used by
	// agent credential mints for kind = x509 and kind = jwk.
	ErrNotImplemented = models.ErrNotImplemented

	// ErrAgentNotFound is returned by lookups whose target agent is absent.
	ErrAgentNotFound = models.ErrAgentNotFound

	// ErrAgentInactive is returned when an operation depends on an agent
	// whose status is suspended or revoked.
	ErrAgentInactive = models.ErrAgentInactive

	// ErrDelegationNotFound is returned when no delegation_grants row
	// matches the (user, agent, resource) tuple. Token exchange surfaces
	// this as access_denied to the caller.
	ErrDelegationNotFound = models.ErrDelegationNotFound

	// ErrDelegationRevoked is returned when a delegation grant exists but
	// its revoked_at is set. Token exchange surfaces this as access_denied;
	// introspection returns active=false.
	ErrDelegationRevoked = models.ErrDelegationRevoked

	// ErrChainDepthExceeded is returned by the token exchange path when
	// adding the requesting agent to the actor chain would exceed the
	// AgentConfig.MaxChainDepth (default 3).
	ErrChainDepthExceeded = models.ErrChainDepthExceeded

	// ErrSubjectTokenInvalid is returned when the supplied subject_token
	// fails signature, issuer, expiry, or audience checks.
	ErrSubjectTokenInvalid = models.ErrSubjectTokenInvalid

	// ErrActorTokenInvalid is returned when the supplied actor_token fails
	// signature, issuer, expiry, or audience checks, or when it does not
	// resolve to the authenticated agent client.
	ErrActorTokenInvalid = models.ErrActorTokenInvalid

	// ErrAgentRequiresAS is returned by New when Config.AgentIdentity is
	// non-nil but Config.AuthorizationServer is nil. Agents and delegations
	// only make sense alongside the OAuth 2.1 AS that mints their tokens.
	ErrAgentRequiresAS = models.ErrAgentRequiresAS

	// ErrAgentChainDepthTooHigh is returned by New when
	// AgentConfig.MaxChainDepth exceeds the v2.0 hard ceiling of 3.
	ErrAgentChainDepthTooHigh = models.ErrAgentChainDepthTooHigh

	// ErrAccountUXRequiresAgents is returned by New when Config.AccountUX is
	// true but Config.AgentIdentity is nil. The account routes have no
	// service surface to back them otherwise.
	ErrAccountUXRequiresAgents = models.ErrAccountUXRequiresAgents

	// ErrIdentityConflict is returned by LinkOAuthToCurrentUser when the
	// OAuth account being linked is already bound to a different user.
	// errors.As it to *models.IdentityConflictError to read ConflictingUserID.
	ErrIdentityConflict = models.ErrIdentityConflict

	// ErrStepUpRequired is returned by any identity-linking or merge method
	// when the session's AuthLevel is not AuthLevelFull.
	ErrStepUpRequired = models.ErrStepUpRequired

	// ErrLastAuthMethod is returned when an unlink operation would leave
	// the account with zero authentication methods.
	ErrLastAuthMethod = models.ErrLastAuthMethod

	// ErrCIBAAuthorizationPending is returned by PollBackchannelToken when
	// the user has not yet approved or denied the request.
	ErrCIBAAuthorizationPending = models.ErrCIBAAuthorizationPending

	// ErrCIBASlowDown is returned when the client polls faster than
	// CIBAConfig.MinPollInterval.
	ErrCIBASlowDown = models.ErrCIBASlowDown

	// ErrCIBAAccessDenied is returned when the user denied the request.
	ErrCIBAAccessDenied = models.ErrCIBAAccessDenied

	// ErrCIBAExpiredToken is returned when the auth_req_id has expired.
	ErrCIBAExpiredToken = models.ErrCIBAExpiredToken

	// ErrCIBAInvalidRequest is returned when required hint parameters are
	// missing or mutually exclusive constraints are violated.
	ErrCIBAInvalidRequest = models.ErrCIBAInvalidRequest

	// ErrCIBADisabled is returned when a CIBA operation is attempted but
	// CIBA is not enabled (Config.AuthorizationServer.CIBA is nil or the
	// storage does not implement CIBAStorage).
	ErrCIBADisabled = models.ErrCIBADisabled

	// ErrCIBAUserMismatch is returned by ApproveBackchannelAuth /
	// DenyBackchannelAuth when the supplied userID does not match the
	// resolved subject on the pending request.
	ErrCIBAUserMismatch = models.ErrCIBAUserMismatch

	// ErrDeviceAuthUserCodeTaken is returned by
	// DeviceAuthorizationStorage.InsertDeviceAuthorization on a user code hash
	// collision with a live record.
	ErrDeviceAuthUserCodeTaken = models.ErrDeviceAuthUserCodeTaken

	// ErrDeviceUserCodeInvalid is returned by the device verification page when the
	// code is unknown, expired or already decided.
	ErrDeviceUserCodeInvalid = models.ErrDeviceUserCodeInvalid

	// ErrDeviceTooManyAttempts is returned when a subject exhausted its
	// user-code attempt budget.
	ErrDeviceTooManyAttempts = models.ErrDeviceTooManyAttempts

	// ErrRegistrationTokenInvalid covers unknown, expired, revoked and
	// exhausted registration tokens.
	ErrRegistrationTokenInvalid = models.ErrRegistrationTokenInvalid

	// ErrRegistrationTokensDisabled is returned when the storage cannot hold
	// registration tokens.
	ErrRegistrationTokensDisabled = models.ErrRegistrationTokensDisabled

	// ErrDeviceEnrollmentInvalid covers unknown, revoked and mismatched
	// devices and join tokens.
	ErrDeviceEnrollmentInvalid = models.ErrDeviceEnrollmentInvalid

	// ErrDeviceConflict is returned when a device SPIFFE ID is already
	// registered.
	ErrDeviceConflict = models.ErrDeviceConflict

	// ErrDevicesDisabled is returned when device tokens are not configured.
	ErrDevicesDisabled = models.ErrDevicesDisabled

	// ErrOIDCDisabled is returned when AuthorizationServer.OIDC is not set.
	ErrOIDCDisabled = models.ErrOIDCDisabled
)
View Source
var (
	// ErrCredentialRevoked is returned by a CredentialChecker when the
	// upstream credential a session is tied to is no longer valid.
	ErrCredentialRevoked = models.ErrCredentialRevoked

	// ErrSessionLinkInvalid is returned when a session link cannot be
	// exchanged for any reason.
	ErrSessionLinkInvalid = models.ErrSessionLinkInvalid
)

Session management sentinels.

View Source
var (
	// ErrProviderGrantRevoked means the upstream provider no longer honors the
	// stored refresh token. The stored tokens are cleared; the user must sign
	// in with the provider again.
	ErrProviderGrantRevoked = models.ErrProviderGrantRevoked
	// ErrProviderRefreshUnsupported means the provider cannot refresh tokens
	// or no refresh token is stored for the account.
	ErrProviderRefreshUnsupported = models.ErrProviderRefreshUnsupported
	// ErrProviderNotLinked means the user has no linked account for the provider.
	ErrProviderNotLinked = models.ErrProviderNotLinked
)
View Source
var DefaultSAMLAttributeMap = models.DefaultSAMLAttributeMap

DefaultSAMLAttributeMap returns the WS-Federation claim URIs that Microsoft, Okta, and OneLogin emit by default.

View Source
var ErrAccountStateDisabled = models.ErrAccountStateDisabled

ErrAccountStateDisabled is returned by the forced-password-change and disable APIs when Config.AccountState is false.

View Source
var ErrAuthorizationServerNotConfigured = errors.New("theauth: authorization server not configured")

ErrAuthorizationServerNotConfigured is returned by authorization-server methods when Config.AuthorizationServer was not set at New time. Callers can use errors.Is(err, theauth.ErrAuthorizationServerNotConfigured) to distinguish this condition from other errors.

View Source
var ErrImportDuplicate = models.ErrImportDuplicate

ErrImportDuplicate is returned by the Import helpers when the record already exists; callers may treat it as already imported.

View Source
var ErrImportInvalid = importer.ErrImportInvalid

ErrImportInvalid wraps every Import helper validation failure.

View Source
var ErrStorageMissingCapability = models.ErrStorageMissingCapability

ErrStorageMissingCapability is returned by New when an enabled feature needs a capability interface the configured storage lacks, and by the stub methods of a storage assembled from Config.CoreStorage.

View Source
var ErrStorageMissingOAuthMethods = models.ErrStorageMissingOAuthMethods

ErrStorageMissingOAuthMethods is returned by New when Config.AuthorizationServer is non-nil but Config.Storage does not satisfy OAuthServerStorage. The actual error value lives in internal/models (PR B architecture reorg, 2026-06-20) so subpackages can compare against it without importing root.

LatencyBuckets is the shared histogram bucket layout used by every _latency_seconds metric the library emits. Consumers pre-registering Prometheus histograms MUST use this exact slice so bucket boundaries align between library call sites and consumer registrations.

Functions ¶

func DefaultRedactor ¶

func DefaultRedactor(metadata map[string]any) map[string]any

DefaultRedactor masks values for keys named password, secret, token, code, refresh_token, access_token (case-insensitive) at any nesting depth.

func DoctorFindingIDs ¶

func DoctorFindingIDs() []string

DoctorFindingIDs lists every finding ID a check can emit.

func FormatUserCode ¶

func FormatUserCode(code string) string

FormatUserCode renders a user code as XXXX-XXXX for display.

func HashEmailForAudit ¶

func HashEmailForAudit(email string) string

HashEmailForAudit returns sha256(lowercase(email)) hex-encoded.

func ImportTOTPSecretTo ¶

func ImportTOTPSecretTo(ctx context.Context, store TOTPStorage, encryptionKey []byte, in ImportedTOTP) error

ImportTOTPSecretTo encrypts the plaintext secret with encryptionKey and stores it as confirmed, with no TheAuth instance.

func IsLoginRequired ¶

func IsLoginRequired(err error) bool

IsLoginRequired reports whether the supplied error signals the authorize path needs an authenticated user. Forwards to internalas.IsLoginRequired; both packages share the same sentinel pointer so existing errors.Is callers keep working.

func IsReauthRequired ¶ added in v2.10.0

func IsReauthRequired(err error) bool

IsReauthRequired reports whether a StartAuthorize error means the user must authenticate again (max_age exceeded or acr_values not met).

func NewMemoryOAuthStateStore ¶

func NewMemoryOAuthStateStore() *internaloauth.MemoryStateStore

NewMemoryOAuthStateStore returns the default in-process OAuthStateStore. It sweeps expired entries in the background; call Close when done.

func SeededSecretKeys ¶

func SeededSecretKeys() []string

SeededSecretKeys returns a copy of the case-insensitive key blocklist applied by the default redactor.

func WithAuditMetadata ¶

func WithAuditMetadata(ctx context.Context, md AuditMetadata) context.Context

WithAuditMetadata attaches an AuditMetadata to ctx; EmitAudit reads it.

func WithAuthContext ¶ added in v2.10.0

func WithAuthContext(ctx context.Context, ac AuthContext) context.Context

WithAuthContext returns a context carrying ac for StartAuthorize.

Types ¶

type APIToken ¶

type APIToken = apitokens.APIToken

Token, device and principal types.

func ImportAPITokenTo ¶

func ImportAPITokenTo(ctx context.Context, store APITokenStorage, in ImportedToken) (APIToken, error)

ImportAPITokenTo inserts an existing token by hash straight into store, with no TheAuth instance.

Abilities are checked for syntax only, since there is no configured allowlist.

type APITokenStorage ¶

type APITokenStorage = apitokens.APITokenStorage

Token, device and principal types.

type APITokensConfig ¶

type APITokensConfig = apitokens.Config

Token, device and principal types.

type ASMetadata ¶

type ASMetadata = internalas.ASMetadata

ASMetadata is the JSON document served at /.well-known/oauth-authorization-server. Field names and shape follow RFC 8414 section 2.

type ASRateLimits ¶ added in v2.8.0

type ASRateLimits = internalas.RateLimits

ASRateLimits is the root alias for the AS endpoint limits.

type AccountDeleteStorage ¶ added in v2.10.0

type AccountDeleteStorage interface {
	DeleteUserCascade(ctx context.Context, userID ULID) error
}

AccountDeleteStorage is the optional capability behind account deletion. DeleteUserCascade removes the user and every row that belongs to it (sessions, tokens, identities, passkeys, TOTP, API tokens, memberships, account state, trusted devices) so nothing is left behind. Audit rows are kept with the actor cleared. It returns ErrStorageNotFound for an unknown user.

type AccountDeletionConfig ¶ added in v2.10.0

type AccountDeletionConfig struct {
	// RecentAuthMaxAge is how recently the session must have authenticated
	// (sign-in or step-up). Default 10 minutes.
	RecentAuthMaxAge time.Duration
}

AccountDeletionConfig mounts DELETE /account for self-service deletion. It needs a storage implementing AccountDeleteStorage.

type AccountState ¶ added in v2.10.0

type AccountState = models.AccountState

AccountState holds per-user lifecycle flags (forced password change, disabled).

type AccountStateStorage ¶ added in v2.10.0

type AccountStateStorage interface {
	// AccountStateByUserID returns the user's flags. A user with no recorded
	// state returns the zero AccountState and no error.
	AccountStateByUserID(ctx context.Context, userID ULID) (AccountState, error)
	// SetMustChangePassword sets or clears the forced password change flag.
	// It returns ErrStorageNotFound for an unknown user.
	SetMustChangePassword(ctx context.Context, userID ULID, required bool) error
	// SetUserDisabledAt disables the user at the given time, or re-enables it
	// when at is nil. It returns ErrStorageNotFound for an unknown user.
	SetUserDisabledAt(ctx context.Context, userID ULID, at *time.Time) error
}

AccountStateStorage is the optional capability behind forced password change and account disable. It is detected by type assertion and is not part of Storage. Without it those features answer ErrStorageMissingCapability and sign-in is unchanged. Memory, SQLite, Postgres and MySQL implement it.

type Actor ¶

type Actor = apitokens.Actor

Token, device and principal types.

type ActorClaim ¶

type ActorClaim = models.ActorClaim

type AdminConfig ¶

type AdminConfig struct {
	// PathPrefix where admin routes mount. Defaults to "/admin/v1".
	PathPrefix string
}

AdminConfig mounts /admin/v1/* when non-nil on the same chi router passed to Mount.

type AdmissionLimit ¶ added in v2.10.0

type AdmissionLimit struct {
	Max    int
	Window time.Duration
}

AdmissionLimit is one tier's budget: Max requests per Window per client. A zero field takes the tier default.

type AdmissionLimits ¶ added in v2.10.0

type AdmissionLimits struct {
	// Strict covers token, registration and authorization endpoints.
	Strict AdmissionLimit
	// Mutation covers every other POST, PUT, PATCH and DELETE route.
	Mutation AdmissionLimit
	// Read covers GET, HEAD and OPTIONS routes.
	Read AdmissionLimit
}

AdmissionLimits are the per-tier budgets. Defaults: Strict 30, Mutation 120 and Read 300 requests per 60 seconds.

type AdmissionOptions ¶ added in v2.10.0

type AdmissionOptions struct {
	// DisableRateLimit turns rate limiting off, for example when a gateway
	// already does it. The cross-site check still applies.
	DisableRateLimit bool
	// Limits overrides the default per-tier budgets.
	Limits AdmissionLimits
	// Skip returns true to leave a request out of rate limiting (health
	// checks, your own network). The cross-site check still applies.
	Skip func(r *http.Request) bool
	// Key replaces the default client key (client IP, then credential digest).
	// Return "" to fall back to the default for that request.
	Key func(r *http.Request) string
	// TrustedOrigins are extra origins (scheme://host[:port]) allowed to send
	// cookie-authenticated writes, on top of Config.BaseURL, the request's own
	// origin and Config.TrustedOrigins.
	TrustedOrigins []string
	// DisableCSRF turns the cross-site check off.
	DisableCSRF bool
}

AdmissionOptions configures Admission. The zero value enables the default tiered rate limits and the cross-site check.

type Agent ¶

type Agent = models.Agent

type AgentConfig ¶

type AgentConfig struct {
	// MaxChainDepth caps the actor chain length. Defaults to 3 (root subject
	// plus two agents). Operators may lower (to 2, disabling sub-delegation)
	// but never raise above 3 in v2.0; New returns an error if asked to.
	MaxChainDepth int

	// MaxDelegationDuration caps any single delegation_grants.max_duration.
	// Defaults to 90 days. Per-grant max_duration_seconds MUST be <= this.
	MaxDelegationDuration time.Duration

	// DefaultDelegatedTokenTTL is the default exp window for tokens minted
	// via the token-exchange grant when the requester does not narrow it
	// further. Defaults to 15 minutes.
	DefaultDelegatedTokenTTL time.Duration

	// AgentSecretLength controls bytes of entropy in generated agent
	// secrets. Defaults to 32 (256 bits). Stored hashed (Argon2id);
	// transmitted exactly once at creation or rotation.
	AgentSecretLength int
}

AgentConfig wires the agent-identity policy. Set on Config.AgentIdentity to enable Phase 3 + 4 behavior (agents + delegations + token-exchange). The zero value AgentConfig{} is valid and is interpreted as accept-all- defaults at New.

type AgentCredential ¶

type AgentCredential = models.AgentCredential

type AgentOwner ¶

type AgentOwner = models.AgentOwner

type AgentRegistration ¶

type AgentRegistration = agent.Registration

Token, device and principal types.

type AgentSecret ¶

type AgentSecret = models.AgentSecret

type Attr ¶

type Attr = observability.Attr

Attr is one key/value pair attached to a span.

func BoolAttr ¶

func BoolAttr(k string, v bool) Attr

BoolAttr wraps a bool span attribute.

func ErrAttr ¶

func ErrAttr(err error) Attr

ErrAttr wraps an error as a string span attribute under the key "error".

func IntAttr ¶

func IntAttr(k string, v int64) Attr

IntAttr wraps an int64 span attribute.

func StringAttr ¶

func StringAttr(k, v string) Attr

StringAttr wraps a string-valued span attribute.

type AuditConfig ¶

type AuditConfig struct {
	// BufferSize is the channel buffer between EmitAudit and the writer
	// goroutine. Defaults to 4096. When full, EmitAudit drops the event
	// and increments Stats.AuditDropped.
	BufferSize int

	// BatchSize is the maximum events per INSERT. Defaults to 100.
	BatchSize int

	// FlushInterval is the maximum delay before a partial batch flushes.
	// Defaults to 1 second.
	FlushInterval time.Duration

	// Redactor optionally transforms metadata before storage. The default
	// redactor strips the keys "password", "secret", "token", "code",
	// "refresh_token", "access_token" (case-insensitive) at any nesting
	// depth and replaces their values with the string "[REDACTED]".
	Redactor func(metadata map[string]any) map[string]any

	// DrainTimeout caps how long Close waits for the writer goroutine to
	// drain remaining events. Defaults to 5 seconds.
	DrainTimeout time.Duration

	// Sinks is the optional list of external SIEM streaming destinations.
	// After each successful canonical storage write the writer goroutine
	// fans out to every sink in a separate goroutine. A failing sink is
	// logged at Warn level, counted in Stats.AuditSinkFailed, and
	// silently dropped: sink failures NEVER block storage writes or delay
	// the next batch. Built-in implementations are in sub-packages of
	// audit/sinks/.
	Sinks []AuditSink
}

AuditConfig configures the async audit writer. All fields have safe defaults; the zero value AuditConfig{} is valid.

type AuditEvent ¶

type AuditEvent = models.AuditEvent

type AuditMetadata ¶

type AuditMetadata = audit.AuditMetadata

AuditMetadata is the optional bundle a caller may attach to a context to override the auto-derived actor / org / IP / UA. Re-exported from internal/audit so the v1.0 public surface is unchanged.

type AuditQuery ¶

type AuditQuery = models.AuditQuery

type AuditSink ¶

type AuditSink interface {
	// Stream sends a batch of audit events to the external system.
	// Implementations should apply a reasonable timeout internally.
	// A non-nil error is logged and counted in Stats.AuditSinkFailed;
	// it does not affect storage writes.
	Stream(ctx context.Context, batch []AuditEvent) error

	// Name identifies the sink for logging and metrics labels.
	Name() string
}

AuditSink streams audit events to an external SIEM or observability system. Implementations must be best-effort: a failed Stream call must never block writes to the canonical storage layer. Failures increment Stats.AuditSinkFailed.

Built-in implementations live under audit/sinks/:

  • audit/sinks/otlp: OTLP/HTTP logs exporter
  • audit/sinks/splunkhec: Splunk HTTP Event Collector
  • audit/sinks/webhook: generic CloudEvents 1.0 POST

type AuditStorage ¶

type AuditStorage interface {
	// InsertAuditEvents writes a batch in one round trip. Append-only;
	// adapters MUST NOT expose UPDATE or DELETE for audit rows. Failure
	// returns an error; the writer goroutine logs it and increments
	// Stats.AuditFailed without retrying (documented tradeoff).
	InsertAuditEvents(ctx context.Context, events []AuditEvent) error
	QueryAuditEvents(ctx context.Context, q AuditQuery) (events []AuditEvent, nextCursor string, err error)
}

AuditStorage covers the append-only audit log.

type AuthContext ¶ added in v2.10.0

type AuthContext = internalas.AuthContext

AuthContext describes how and when the user behind an authorize request authenticated (auth_time and amr). The /oauth/authorize handler builds it from the session; callers of StartAuthorize that bypass the handler attach one with WithAuthContext so tokens carry auth_time, acr and amr and max_age and acr_values on AuthorizeRequest can be honored.

type AuthEvent ¶

type AuthEvent = authevents.Event

AuthEvent is the PII-minimal record handed to Config.AuthEventSink. It carries a user id and a truncated IP prefix, never an email, name or token.

type AuthEventSink ¶

type AuthEventSink = authevents.Sink

AuthEventSink receives every AuthEvent synchronously on the emitting goroutine. Implementations must return quickly and must not block; a panic is recovered and logged.

func AuthEventChannelSink ¶

func AuthEventChannelSink(ch chan<- AuthEvent) AuthEventSink

AuthEventChannelSink returns an AuthEventSink that forwards events to ch without ever blocking: when ch is full the event is dropped.

type AuthEventType ¶

type AuthEventType = authevents.Type

AuthEventType names one security-relevant authentication event.

type AuthenticationDevice ¶

type AuthenticationDevice interface {
	Notify(ctx context.Context, req CIBANotification) error
}

AuthenticationDevice is the operator-supplied interface that bridges the AS to the actual push delivery mechanism (FCM, APNs, SMS, etc.). See internal/as.AuthenticationDevice for the full contract.

type AuthorizationCode ¶

type AuthorizationCode = models.AuthorizationCode

type AuthorizationServerConfig ¶

type AuthorizationServerConfig struct {
	// Issuer is the canonical https URL identifying this authorization
	// server. Becomes the iss claim on every issued JWT. RFC 8414
	// mandates no query or fragment; trailing slash is stripped at New().
	Issuer string

	// Resources lists the protected resources advertised by this AS.
	// Every authorize and token request MUST carry a resource parameter
	// that matches one of these identifiers; the resulting JWT's aud
	// claim is set from the resource (RFC 8707 + RFC 9068).
	Resources []ProtectedResource

	// SigningAlg defaults to EdDSA (Ed25519). Phase 1 + 2 ships Ed25519
	// only.
	SigningAlg string

	// KeyRotationPeriod defaults to 30 days. The rotation goroutine
	// promotes next -> current -> previous and generates a fresh next at
	// every cadence.
	KeyRotationPeriod time.Duration

	// KeyRetention caps how long a retired key remains visible in
	// /oauth/jwks. Defaults to 90 days.
	KeyRetention time.Duration

	// AccessTokenTTL caps the lifetime of issued access tokens. Defaults
	// to 1 hour.
	AccessTokenTTL time.Duration

	// RefreshTokenTTL caps the lifetime of refresh tokens. Defaults to 30
	// days. Refresh tokens are rotated on every use; presenting an old
	// token after rotation revokes the family (RFC 9700 section 4.14).
	RefreshTokenTTL time.Duration

	// AuthorizationCodeTTL caps the lifetime of authorization codes.
	// Defaults to 60 seconds per OAuth 2.1 guidance.
	AuthorizationCodeTTL time.Duration

	// RegistrationAccessTokenTTL caps the lifetime of registration access
	// tokens minted on POST /oauth/register. Defaults to 365 days.
	RegistrationAccessTokenTTL time.Duration

	// AllowAnonymousRegistration permits POST /oauth/register without an
	// initial access token. Off by default. When on, the AS hard-pins
	// the endpoint to 1 request/min/IP and stamps the client row with
	// AnonymousRegistered = true for operator auditing.
	AllowAnonymousRegistration bool

	// RegistrationTokens is the operator-supplied set of bearer initial
	// access tokens that POST /oauth/register accepts when DCR is bearer
	// gated (the default). Each entry is the raw token string; it is
	// sha256-hashed at New time and the plaintext is dropped, so the
	// in-memory state never carries the secret value. Token comparisons
	// run under crypto/subtle.ConstantTimeCompare so token-presence
	// timing is not observable.
	//
	// When AllowAnonymousRegistration is false (the default and the
	// production-recommended value) and RegistrationTokens is empty,
	// POST /oauth/register returns 401 access_denied to every caller,
	// because no operator-issued token can possibly match. Operators
	// that want a truly open DCR endpoint must flip
	// AllowAnonymousRegistration to true explicitly (security audit H1,
	// 2026-06-20).
	RegistrationTokens []string

	// RegistrationRateLimitPerMinute caps POST /oauth/register at this
	// many requests per source IP per minute. Defaults: 1 when
	// AllowAnonymousRegistration is true (matches the documented public
	// MCP profile), 5 otherwise. Set to a negative value to disable the
	// per-IP cap entirely (operator opt-out; not recommended on a
	// public-internet bind) (security audit H2, 2026-06-20).
	RegistrationRateLimitPerMinute int

	// IntrospectionCacheTTL is the Cache-Control max-age the
	// introspection endpoint emits. Defaults to 60 seconds. Resource
	// servers may cache responses up to this duration.
	IntrospectionCacheTTL time.Duration

	// Clock is the time source used by the introspection cache and the
	// chain-cache TTL. Defaults to a wrapper around time.Now when nil.
	// Tests pass a fake clock to assert revocation propagation
	// deterministically (e.g. introspecting immediately after revoke)
	// instead of sleeping past IntrospectionCacheTTL.
	Clock Clock

	// LoginURL is the path on this origin where unauthenticated
	// authorize requests are redirected. Defaults to "/auth/login". The
	// handler appends a `next` query parameter with the original
	// authorize URL.
	LoginURL string

	// DisableRotation skips the background JWKS rotation goroutine.
	// Tests use this to assert key state from a known fixture;
	// production must leave it false.
	DisableRotation bool

	// CIMD wires the Client ID Metadata Documents resolver per the MCP
	// authorization spec 2025-11-25. When non-nil, incoming
	// /oauth/authorize and /oauth/token requests whose client_id parses
	// as an https URL are resolved by fetching that URL and parsing the
	// JSON metadata document, instead of consulting OAuthServerStorage.
	// Nil disables CIMD and the AS falls back to RFC 7591 DCR for every
	// client_id (the pre-CIMD behavior).
	//
	// Default policy MUST be DenyAll (fail-closed); operators opt in to
	// AllowAnyHTTPS or AllowHTTPSHosts explicitly.
	CIMD *CIMDConfig

	// DPoP, when non-nil, enables RFC 9449 sender-constrained access
	// tokens. The token endpoint inspects each request for a DPoP
	// header, verifies the proof JWT, and embeds an RFC 7800 cnf.jkt
	// confirmation claim in the issued access token. Resource servers
	// (mcpresource) re-verify the same proof on every protected call,
	// so a stolen access token cannot be replayed without the private
	// key that signed the proof. Leave nil for pre-PR behavior
	// (Bearer tokens, no sender constraint).
	DPoP *DPoPConfig

	// RequireState, when true, causes the /oauth/authorize endpoint to
	// reject any request that omits a non-empty state parameter, returning
	// invalid_request. Default false preserves existing behavior for
	// backwards compatibility. Operators deploying browser-based clients
	// should set this to true to enforce CSRF protection for every
	// authorization request (security re-audit L5, 2026-06-22).
	RequireState bool

	// AccessTokenRevocation enables the store-backed access-token jti
	// denylist (opt-in). When true and the Storage implements the denylist
	// capability (memory, postgres and mysql do), revoking an access token
	// at /oauth/revoke, replaying an authorization code, and token
	// exchange all honor it, and /oauth/introspect reports revoked tokens
	// inactive. Resource servers that verify JWTs locally never consult
	// the denylist; they must introspect. Default false keeps access
	// tokens stateless.
	AccessTokenRevocation bool

	// ClientCompat relaxes individual strictness checks so real-world MCP
	// clients (Claude Desktop, Cursor, ChatGPT) interoperate: an optional
	// resource parameter, dropping unknown scopes, port-agnostic loopback
	// redirect URIs and sub-path audiences. Every switch defaults to false
	// (strict). LoopbackAnyPort and DropUnknownScopes carry real security
	// tradeoffs; see docs/client-compat.md before enabling them.
	ClientCompat ClientCompatConfig

	// ACRValues maps an authentication method set to the acr string put in
	// access tokens and introspection responses (RFC 9470 step-up). Keys are
	// the distinct amr methods sorted and joined with "+", for example
	// "pwd", "otp+pwd" or "hwk". A method set without an entry uses the
	// default: "urn:theauth:acr:1fa" for one method, "urn:theauth:acr:mfa"
	// for "mfa" or two or more methods. Non-empty values are advertised as
	// acr_values_supported. Nil keeps the defaults and advertises nothing.
	ACRValues map[string]string

	// SessionAMR reports the RFC 8176 authentication methods the session
	// was established with, for the amr and acr claims. Sessions do not
	// record their sign-in method, so nil assumes ["pwd"]; supply this
	// (for example from your own login records) to emit "otp", "hwk" or
	// "mfa" and satisfy a higher acr. Called on /oauth/authorize only.
	SessionAMR func(ctx context.Context, sess *Session) []string

	// PAR wires RFC 9126 Pushed Authorization Requests. When non-nil and
	// the Storage backend implements PARStorage, POST /oauth/par is
	// registered and GET /oauth/authorize accepts request_uri. Nil (the
	// default) disables PAR; existing deployments see no behavior change.
	PAR *PARConfig

	// JAR wires RFC 9101 JWT-Secured Authorization Requests. When
	// non-nil, /oauth/authorize and /oauth/par accept a "request"
	// parameter containing a signed JWT. Nil (the default) disables JAR.
	JAR *JARConfig

	// JWTBearer, when non-nil, enables two RFC 7523 features:
	//
	// (1) private_key_jwt / client_secret_jwt client authentication on the
	//     token endpoint (RFC 7523 section 2.2). Clients registered with
	//     token_endpoint_auth_method = "private_key_jwt" or
	//     "client_secret_jwt" authenticate by presenting a signed JWT as
	//     client_assertion instead of a client_secret.
	//
	// (2) The urn:ietf:params:oauth:grant-type:jwt-bearer grant type (RFC
	//     7523 section 2.1). A JWT issued by a configured trusted external
	//     issuer (e.g. Google, k8s OIDC, AWS IAM Roles Anywhere) is
	//     exchanged for an AS-issued access token.
	//
	// When nil both features are disabled and the AS behaves as before
	// (client_secret_basic / client_secret_post only).
	JWTBearer *JWTBearerConfig

	// CIBA enables Client-Initiated Backchannel Authentication (RFC 9509)
	// when non-nil. The storage backend must also implement CIBAStorage;
	// if it does not, CIBA endpoints are not mounted regardless of this
	// setting. Default nil disables CIBA.
	CIBA *CIBAConfig

	// DeviceAuthorization enables the RFC 8628 device grant when non-nil:
	// POST /oauth/device_authorization, the device_code grant at
	// /oauth/token, and a user-code page at /oauth/device. The storage must
	// also implement DeviceAuthorizationStorage (memory, Postgres and MySQL
	// do). Clients opt in by registering the
	// urn:ietf:params:oauth:grant-type:device_code grant type. Default nil
	// disables it.
	DeviceAuthorization *DeviceAuthorizationConfig

	// TokenPolicy enables per-client access token policy: extra signing
	// algorithms (ES256, RS256) and opaque reference tokens. Nil keeps every
	// client on EdDSA JWTs. Opaque tokens need a storage that implements
	// OpaqueTokenStorage (memory, Postgres and MySQL do).
	TokenPolicy *TokenPolicyConfig

	// RAR enables RFC 9396 Rich Authorization Requests: the
	// authorization_details parameter on /oauth/authorize, PAR, JAR and the
	// token endpoint, and the claim in access tokens and introspection. Nil
	// rejects the parameter.
	RAR *RARConfig

	// IDJAG enables issuing Identity Assertion JWT Authorization Grants
	// through token exchange, and redeeming them at the jwt-bearer grant
	// (which also needs JWTBearer with the issuing server as a trusted
	// issuer). Nil disables both.
	IDJAG *IDJAGConfig

	// RateLimits tunes the per-IP and per-client limits on /oauth/token,
	// /oauth/revoke, /oauth/introspect, /oauth/par, /oauth/bc-authorize and
	// /oauth/device_authorization, and the cap on concurrent Argon2id
	// client-secret verifications. Nil applies the defaults (120 requests per
	// IP per minute, 300 secret-bearing requests per client per minute, up to
	// 8 concurrent verifications). Set a field negative to turn it off.
	RateLimits *ASRateLimits

	// RegistrationTokenTTL is the default lifetime of an initial access token
	// created through CreateRegistrationToken or the admin API. Default 24h.
	RegistrationTokenTTL time.Duration

	// DeviceTokens enables constrained device identity when non-nil: admin
	// minted single-use join tokens, enrollment at /oauth/devices/enroll, and
	// the RFC 7523 jwt-bearer grant for registered devices, which issues
	// short-lived access tokens with no refresh token. The storage must also
	// implement DeviceIdentityStorage (memory, Postgres, MySQL and SQLite do).
	DeviceTokens *DeviceTokensConfig

	// OIDC turns the server into an OpenID Provider when non-nil: ID tokens
	// for requests with the openid scope, GET/POST /oauth/userinfo,
	// /oauth/end_session (RP-initiated logout), back-channel logout and
	// pairwise subjects. See docs/oidc-provider.md.
	OIDC *OIDCConfig
}

AuthorizationServerConfig wires the OAuth 2.1 + MCP authorization server surface. Set on Config.AuthorizationServer to enable /.well-known/ and /oauth/ routes. Leave nil for v1.0 behavior.

Phase 1 + 2 scope: authorization_code + refresh_token + revoke + introspect + RFC 7591 dynamic client registration + JWKS rotation. Agents, delegations, and RFC 8693 token exchange land in phase 3 + 4.

type AuthorizeRequest ¶

type AuthorizeRequest = internalas.AuthorizeRequest

AuthorizeRequest is the parsed GET /oauth/authorize query string. PKCE fields are required; OAuth 2.1 forbids the legacy implicit and password flows so response_type MUST be "code" and code_challenge_method MUST be "S256".

type AuthorizeResult ¶

type AuthorizeResult = internalas.AuthorizeResult

AuthorizeResult is the outcome of a successful authorize call: the redirect URL the handler should 302 the user agent to.

type BackchannelRequest ¶

type BackchannelRequest = models.BackchannelRequest

BackchannelRequest is the persistent record for one CIBA flow.

type BootstrapConfig ¶

type BootstrapConfig = bootstrap.Config

BootstrapConfig closes public signup and gates creation of the first user behind a one-time setup token. The storage must implement UserCountStorage.

While no user exists, password signup requires the token in the X-Setup-Token header or a "setupToken" body field. After the first user exists, signup is refused with CodeSignupClosed unless OpenSignupAfterFirstUser is set. Magic-link account creation follows the same rule but can never present a token, so the first admin must sign up with a password. Granting the new user an admin role is left to OnFirstUser.

type BreachChecker ¶

type BreachChecker = password.BreachChecker

BreachChecker reports whether a password appears in a known breach corpus.

type CIBAConfig ¶

type CIBAConfig struct {
	// AuthenticationDevice is required. The AS calls Notify on every
	// POST /oauth/bc-authorize so the user's device receives the push.
	AuthenticationDevice AuthenticationDevice

	// DefaultExpiry is the default auth_req_id lifetime. Defaults to 300s.
	DefaultExpiry time.Duration

	// DefaultInterval is the default client poll interval. Defaults to 5s.
	DefaultInterval time.Duration

	// MaxRequestedExpiry caps the requested_expiry parameter. Defaults to 600s.
	MaxRequestedExpiry time.Duration

	// MinPollInterval is the floor that triggers slow_down when breached.
	// Defaults to 3s.
	MinPollInterval time.Duration
}

CIBAConfig wires the CIBA feature on the authorization server. Set Config.AuthorizationServer.CIBA to enable. Leave nil (default) to disable CIBA entirely.

type CIBANotification ¶

type CIBANotification struct {
	AuthReqID      string
	UserID         string
	ClientID       string
	Scopes         []string
	BindingMessage string
	ExpiresAt      time.Time
}

CIBANotification is the payload delivered to AuthenticationDevice.Notify.

type CIBAStorage ¶

type CIBAStorage interface {
	// InsertBackchannelRequest persists a new backchannel auth request.
	InsertBackchannelRequest(ctx context.Context, req BackchannelRequest) error

	// BackchannelRequestByID returns the request keyed by auth_req_id.
	// Returns ErrStorageNotFound when absent.
	BackchannelRequestByID(ctx context.Context, authReqID string) (BackchannelRequest, error)

	// UpdateBackchannelRequest writes status changes and the approved token
	// strings atomically.
	UpdateBackchannelRequest(ctx context.Context, req BackchannelRequest) error

	// DeleteBackchannelRequest removes the row. The library never calls this
	// automatically; operators call it for housekeeping.
	DeleteBackchannelRequest(ctx context.Context, authReqID string) error

	// TouchBackchannelPoll records the current time as the last poll instant
	// and stores a new poll interval, then returns the updated row.
	TouchBackchannelPoll(ctx context.Context, authReqID string, now time.Time, newInterval int) (BackchannelRequest, error)
}

CIBAStorage is the optional persistence extension that storage backends must implement for CIBA to be active. When the storage passed to New does not also satisfy CIBAStorage, the /oauth/bc-authorize endpoint is not mounted and the AS metadata does not advertise CIBA fields.

Memory and Postgres adapters in storage/memory and storage/postgres both implement CIBAStorage. Custom adapters only need to add these five methods before enabling Config.AuthorizationServer.CIBA.

type CIMDConfig ¶

type CIMDConfig = cimd.Config

CIMDConfig wires the CIMD service onto the AS. Set on AuthorizationServerConfig.CIMD to enable https-URL client_id resolution. Defaults to DenyAll (fail-closed); operators must opt in to a permissive policy explicitly.

Aliased from internal/cimd so consumers can wire CIMDConfig{...} at the public surface without importing the internal package.

type CIMDTrustPolicy ¶

type CIMDTrustPolicy = cimd.TrustPolicy

CIMDTrustPolicy decides which https client_id URLs the AS is allowed to fetch as CIMD documents. Aliased from internal/cimd.TrustPolicy.

func AllowAnyHTTPS ¶

func AllowAnyHTTPS() CIMDTrustPolicy

AllowAnyHTTPS returns a CIMDTrustPolicy that permits every absolute https URL. Use only in deployments that intentionally federate with the open MCP ecosystem; production deployments that know their clients ahead of time should prefer AllowHTTPSHost.

func AllowHTTPSHost ¶

func AllowHTTPSHost(host string) CIMDTrustPolicy

AllowHTTPSHost returns a CIMDTrustPolicy that permits one specific host (case-insensitive, exact match).

func AllowHTTPSHosts ¶

func AllowHTTPSHosts(hosts ...string) CIMDTrustPolicy

AllowHTTPSHosts returns a CIMDTrustPolicy that permits any of the supplied hosts (case-insensitive, exact match). An empty list produces a permanently-deny policy so a typo cannot silently allow every host.

func DenyAll ¶

func DenyAll() CIMDTrustPolicy

DenyAll returns a CIMDTrustPolicy that rejects every URL. This is the fail-closed default applied when CIMDConfig.TrustPolicy is nil and is the default returned here so operator code reads naturally:

cfg.AuthorizationServer.CIMD = &theauth.CIMDConfig{
    TrustPolicy: theauth.DenyAll(), // explicit acknowledgement
}

DenyAll mirrors the security audit H4 default for TrustedProxies: trust must be explicit, never implicit.

type ClientCompatConfig ¶ added in v2.10.0

type ClientCompatConfig = internalas.ClientCompat

ClientCompatConfig is the root-package alias for as.ClientCompat. Set it on Config.AuthorizationServer.ClientCompat; the zero value is fully strict.

type ClientOwner ¶

type ClientOwner = models.ClientOwner

type ClientRegistrationRequest ¶

type ClientRegistrationRequest = internalas.ClientRegistrationRequest

ClientRegistrationRequest is the parsed JSON body of POST /oauth/register. Field names match RFC 7591 client metadata exactly so the wire form maps 1:1 onto the struct.

type Clock ¶

type Clock interface {
	Now() time.Time
}

Clock is the time source used by the introspection cache and the chain-cache TTL. Tests pass a fake clock to assert revocation propagation deterministically instead of sleeping past IntrospectionCacheTTL.

type CloneWarningPolicy ¶

type CloneWarningPolicy string

CloneWarningPolicy selects the response to a sign count regression.

const (
	// CloneWarningReject refuses a login whose sign count did not advance.
	CloneWarningReject CloneWarningPolicy = "reject"
	// CloneWarningFlag allows the login and records an audit event.
	CloneWarningFlag CloneWarningPolicy = "flag"
)

type Config ¶

type Config struct {
	Storage Storage
	// CoreStorage is the alternative to Storage for adapters that implement
	// only the capabilities the enabled features need. It must cover users,
	// sessions, magic links and passwords; New returns
	// ErrStorageMissingCapability when an enabled feature needs more.
	CoreStorage CoreStorage

	EmailSender email.Sender
	BaseURL     string
	// PathPrefix is the route prefix Mount and Handler serve under, and the
	// prefix of every URL the library generates. Default "/auth". It must
	// start with "/" and not end with one, for example "/api/v1/auth".
	PathPrefix string
	SigningKey ed25519.PrivateKey
	// SessionTTL is the absolute session lifetime. Defaults to 24h.
	SessionTTL time.Duration
	// SessionIdleTimeout expires a session unused for this long. Zero
	// disables it. Needs a storage implementing SessionManagementStorage.
	SessionIdleTimeout time.Duration
	// SessionTouchInterval throttles last-seen writes to at most one per
	// session per interval. Defaults to 1m; negative disables last-seen
	// tracking. Must be shorter than SessionIdleTimeout when that is set.
	SessionTouchInterval time.Duration
	// StepUpTTL is how long a successful POST /auth/step-up elevates a
	// session. Defaults to 5m.
	StepUpTTL time.Duration
	// SessionLinks enables programmatic session links when non-nil. Needs a
	// storage implementing SessionLinkStorage and SessionManagementStorage.
	SessionLinks *SessionLinksConfig
	MagicLinkTTL time.Duration
	CookieName   string
	// SecureCookie forces the Secure attribute on every session cookie. It
	// defaults to true when BaseURL is https. When false, Secure is still
	// set per request if BaseURL is https, the
	// connection is TLS, or a TrustedProxies peer sent X-Forwarded-Proto: https.
	SecureCookie bool
	// SuppressSecureCookieWarning silences the v2.2 deprecation WARN logged
	// when SecureCookie is false. Set this to true in local/dev environments
	// that run without TLS so the startup log stays clean. In production,
	// prefer enabling SecureCookie instead.
	SuppressSecureCookieWarning bool
	// RateLimitPerIP is the per-IP per-minute budget applied to credential
	// endpoints (signup/signin/forgot/reset). Defaults to 5 when zero.
	RateLimitPerIP int
	// RateLimitPerEmail is the per-email per-minute budget applied to signin
	// + forgot. Defaults to 3 when zero.
	RateLimitPerEmail int

	// TrustedProxies is the operator-supplied allowlist of reverse-proxy
	// networks whose X-Forwarded-For header is trusted by the rate
	// limiter and the audit IP capture path. Default: empty slice (no
	// XFF trust). Existing deployments that depend on XFF must opt in
	// explicitly by listing their reverse-proxy CIDR(s) here (security
	// audit H4, 2026-06-20).
	//
	// Example values: netip.MustParsePrefix("10.0.0.0/8"),
	// netip.MustParsePrefix("172.16.0.0/12"). For a single-host LB front
	// end pass a /32 (or /128 for IPv6) literal.
	TrustedProxies []netip.Prefix

	// Stores plugs in the shared state backends: the rate limiter behind
	// RateLimitByIP, RateLimitByEmail and the AS endpoint limits, the DPoP
	// proof replay cache, and the CIMD document cache. Nil fields keep the
	// in-process defaults, which are per replica. Behind several replicas set
	// them to a shared adapter (kv.FromCache(sqlkv or kv/redis)) so limits and
	// replay protection hold across instances. See the kv package.
	Stores kv.Stores

	// TrustedOrigins lists extra origins (scheme://host[:port]) allowed to
	// send cookie-authenticated state-changing requests. The BaseURL origin
	// is always trusted. Cross-origin SPAs on a sibling domain add theirs here.
	TrustedOrigins []string

	// DisableCSRFProtection turns off the Origin/Referer check on
	// cookie-authenticated POST/PUT/PATCH/DELETE requests. Leave false
	// unless a fronting layer already enforces it.
	DisableCSRFProtection bool

	// Admission, when set, runs the Admission middleware ahead of every
	// route Mount and Handler register: tiered per-client rate limits and a
	// cross-site check, with counters in Stores.RateLimiter. Nil leaves it
	// off. It stacks with the per-route credential limits.
	Admission *AdmissionOptions

	// ErrorResponder, when set, writes every error response the root
	// middleware produces (Authn family, RequireAuth, RequirePermission,
	// RequireAbility, the Origin check, rate limiters) so an app can emit its
	// own error envelope. status is the HTTP status, code the stable machine
	// code (for example "auth.unauthenticated") and message the human text.
	// On a 401 the WWW-Authenticate challenge header is already set before
	// the call. Nil keeps the built-in RFC 7807 / {"code","message"} bodies
	// byte for byte. Handler-level routes under Mount keep their own bodies.
	ErrorResponder func(w http.ResponseWriter, r *http.Request, status int, code, message string)

	// SuppressTrustedProxiesWarning silences the startup WARN logged when
	// TrustedProxies is empty. Set it when the server is exposed directly
	// with no reverse proxy in front.
	SuppressTrustedProxiesWarning bool

	// Providers is the list of OAuth providers exposed under
	// /auth/providers/{name}/start and /callback. Leave nil to disable
	// OAuth entirely (v0.1 / v0.2 behavior). Each provider's Name() must
	// be unique within the slice.
	Providers []Provider

	// ProviderResolver, when set, supplies OAuth/OIDC providers that are not
	// in Providers, looked up per request by name. Static providers win
	// unless ProviderResolverFirst is set. A resolver error fails the flow
	// closed. EncryptionKey is required when a resolver is set.
	ProviderResolver ProviderResolver
	// ProviderResolverFirst makes the resolver take precedence over Providers.
	ProviderResolverFirst bool
	// ProviderResolverTTL caches resolver answers, including "not found",
	// for this long. Zero disables caching; use InvalidateProvider to
	// drop an entry early.
	ProviderResolverTTL time.Duration

	// EncryptionKey is the 32-byte AES-256 key used to encrypt provider
	// access/refresh tokens before they hit storage. Required when
	// len(Providers) > 0; New returns an error otherwise. Source this from
	// a secrets manager; never commit it.
	EncryptionKey []byte

	// PostLoginRedirect is where the OAuth callback handler 302s to after
	// a successful sign-in. Defaults to "/" when empty. Set to a path on
	// your own origin; cross-origin redirects are not validated here.
	PostLoginRedirect string

	// APITokens enables scoped API tokens, RequireAbility and, via its Device
	// field, the device authorization grant. Needs APITokenStorage (and
	// DeviceCodeStorage for Device).
	APITokens *APITokensConfig

	// WebAuthn enables passkey registration + discoverable login when non-nil.
	// RPID and RPOrigins are mandatory per spec. Leave nil to keep v0.4 behavior.
	WebAuthn *WebAuthnConfig

	// OAuth tunes OAuth login hardening: state store, return-to allow-list
	// and signup policy. Nil keeps the defaults documented on OAuthConfig.
	OAuth *OAuthConfig

	// AuthEventSink, when set, receives every security-relevant
	// authentication event (login, MFA, password, passkey, TOTP, session,
	// token) as a PII-minimal AuthEvent. Independent of Config.Audit.
	AuthEventSink AuthEventSink

	// SharedSignals enables the OpenID Shared Signals Framework 1.0
	// transmitter (CAEP and RISC events, push and poll delivery) and an
	// optional receiver. Requires AuthorizationServer. See
	// docs/shared-signals.md. Nil keeps it off.
	SharedSignals *SharedSignalsConfig

	// TOTP enables time-based second-factor enrollment + verification when non-nil.
	// Requires Config.EncryptionKey (already required by v0.3 OAuth) so the stored
	// secret is encrypted at rest. New returns an error if TOTP is set without a key.
	TOTP *TOTPConfig

	// Organizations (v0.7) enables multi-tenancy when non-nil. Single-tenant
	// deployments leave this nil; organization-scoped routes (SAML connection
	// CRUD, SCIM token CRUD, /auth/orgs/*) are not mounted.
	Organizations *OrganizationsConfig

	// SAML (v0.7) enables the per-connection Service Provider routes when
	// non-nil. The SP keypair lives on the config so multi-tenant deployments
	// can rotate it centrally; every connection signs AuthnRequests with this
	// single keypair. Requires Organizations to be non-nil.
	SAML *SAMLConfig

	// SCIM (v0.7) enables the /scim/v2 endpoints when non-nil. Requires
	// Organizations to be non-nil.
	SCIM *SCIMConfig

	// RBAC (v1.0) enables organization-scoped role and permission
	// management when non-nil. The zero value RBACConfig{} accepts the
	// seeded permissions and default org roles documented in
	// service_rbac.go; consumers extend (never shrink) the seeded lists.
	// New returns an error if Admin is non-nil and RBAC is nil because the
	// admin endpoints are permission-gated and meaningless without RBAC.
	RBAC *RBACConfig

	// Audit (v1.0) enables the async batched audit writer when non-nil.
	// When nil, EmitAudit is a silent no-op and no writer goroutine starts;
	// the v0.7 stub call sites keep working as no-ops, so deployments that
	// do not configure audit continue to behave exactly as before.
	Audit *AuditConfig

	// Admin (v1.0) mounts /admin/v1/* when non-nil. Requires RBAC to be
	// non-nil. The PathPrefix can be moved (e.g. "/api/admin/v1") but the
	// trailing version segment is always v1.
	Admin *AdminConfig

	// AuthorizationServer (v2.0 phase 1 + 2) enables the OAuth 2.1 + MCP
	// authorization server. When non-nil, /.well-known/oauth-authorization-server,
	// /oauth/authorize, /oauth/token, /oauth/revoke, /oauth/introspect,
	// /oauth/register, and /oauth/jwks are mounted. Requires
	// Config.EncryptionKey (32 bytes) and a Storage that satisfies
	// OAuthServerStorage.
	AuthorizationServer *AuthorizationServerConfig

	// AgentIdentity (v2.0 phase 3 + 4) enables the agent identity service
	// surface (Create / Rotate / Suspend / Resume / Revoke), the
	// client_credentials grant on /oauth/token, the delegation_grants
	// service surface, and the RFC 8693 token-exchange grant on /oauth/token.
	// Requires AuthorizationServer to be non-nil. Defaults applied at New:
	// MaxChainDepth=3, MaxDelegationDuration=90d, DefaultDelegatedTokenTTL=15m,
	// AgentSecretLength=32.
	AgentIdentity *AgentConfig

	// RevocationBus carries revocation events to long-lived connections.
	// Defaults to an in-process bus; supply one backed by Postgres NOTIFY or
	// Redis when streams and revokes can land on different processes.
	RevocationBus RevocationBus

	// AccountUX (v2.0 phase 6) mounts /account/agents and /account/delegations
	// when true. Requires AgentIdentity to be configured. Routes are gated by
	// session cookie auth only (no special permission): they manage the
	// authenticated user's own agents and the user's own granted delegations.
	AccountUX bool

	// Observability optionally wires consumer-supplied Tracer + Metrics
	// adapters. When nil the library uses no-op adapters and emits no
	// spans or metrics. The adapter pattern keeps OpenTelemetry,
	// Prometheus, and every other vendor out of theauth-go/go.mod;
	// consumers pick the stack they want and bridge it via the
	// Tracer/Metrics interfaces re-exported from this package.
	//
	// See observability.go for the re-exported types and
	// examples/observability-otel + examples/observability-prom for
	// reference implementations.
	Observability *Hooks

	// PasswordPolicy controls optional extensions to the password-verification
	// path. The zero value is safe (all extensions disabled).
	PasswordPolicy PasswordPolicyConfig

	// LifecycleHooks (v2.5) lets consumers react to authentication-lifecycle
	// events (signup, signin, password change, MFA enable, token issuance,
	// org switch) without forking handlers or wrapping every endpoint at the
	// HTTP boundary. Optional; nil is a silent no-op. See the LifecycleHooks
	// type doc for semantics, error handling, and current wiring status.
	LifecycleHooks *LifecycleHooks

	// Tenancy (v2.5) wires opt-in tenant-provisioning behavior. When
	// Tenancy.AutoCreatePersonalOrg is true and Config.Organizations is
	// also non-nil, every signup automatically creates a personal
	// organization, adds the user as its owner, and sets the session's
	// active organization to it. Removes the SQL-seeding friction
	// consumers previously hit on first signup. Nil = no auto-provisioning.
	Tenancy *TenancyConfig

	// LoginThrottle tunes password-login backoff, per-user lockout and the
	// per-user TOTP/recovery-code attempt limit. Nil selects safe defaults
	// (enabled); set LoginThrottle.Disabled to opt out.
	LoginThrottle *LoginThrottleConfig

	// Bootstrap, when non-nil, closes public signup and requires a one-time
	// setup token to create the first user. Needs a storage implementing
	// UserCountStorage.
	Bootstrap *BootstrapConfig

	// EmailNFKC additionally applies Unicode NFKC folding when canonicalizing
	// email addresses. Trimming and lowercasing always apply.
	EmailNFKC bool

	// AccountState enforces per-user lifecycle flags at every sign-in: the
	// forced password change flag (SetMustChangePassword, ResetPasswordAdmin
	// with RequirePasswordChange, importers) and DisableUser. Needs a
	// storage implementing AccountStateStorage and its migration applied.
	AccountState bool

	// AccountDeletion mounts DELETE /account for self-service deletion when
	// non-nil. The session must have authenticated recently (RequireRecentAuth).
	AccountDeletion *AccountDeletionConfig

	// SessionPolicy caps concurrent sessions per user. Nil means no cap.
	SessionPolicy *SessionPolicy

	// TrustedDevices enables remember-this-device for TOTP when non-nil.
	TrustedDevices *TrustedDevicesConfig
	// contains filtered or unexported fields
}

Config holds the wiring for a TheAuth instance.

BaseURL and exactly one of Storage or CoreStorage are required. Everything else has sensible defaults applied by New: SessionTTL=24h, MagicLinkTTL=15m, CookieName="theauth_session", EmailSender=email.Noop{}. SigningKey is reserved for future JWT signing (v0.2+); v0.1 uses opaque tokens and leaves the field nil.

type CoreStorage ¶

CoreStorage is the minimal capability set for email and password sign-in, sessions and magic links. Set it as Config.CoreStorage to skip the organization, SAML, SCIM, WebAuthn, TOTP and RBAC methods.

type Counter ¶

type Counter = observability.Counter

Counter is a monotonic counter.

type CreateAgentInput ¶

type CreateAgentInput = models.CreateAgentInput

type CreateDeviceJoinTokenInput ¶ added in v2.10.0

type CreateDeviceJoinTokenInput = internalas.CreateDeviceJoinTokenInput

CreateDeviceJoinTokenInput describes a device join token to mint.

type CreateRegistrationTokenInput ¶ added in v2.8.0

type CreateRegistrationTokenInput = internalas.CreateRegistrationTokenInput

CreateRegistrationTokenInput describes an initial access token to mint.

type CredentialChecker ¶

type CredentialChecker interface {
	CheckCredential(ctx context.Context, credentialID string) error
}

CredentialChecker reports whether the upstream credential a session is tied to is still valid. It must return ErrCredentialRevoked when the credential is revoked, expired or unknown; any other error is treated as transient and fails the session check closed.

type CredentialCheckerFunc ¶

type CredentialCheckerFunc func(ctx context.Context, credentialID string) error

CredentialCheckerFunc adapts a function to CredentialChecker.

func (CredentialCheckerFunc) CheckCredential ¶

func (f CredentialCheckerFunc) CheckCredential(ctx context.Context, credentialID string) error

CheckCredential calls f.

type DPoPConfig ¶

type DPoPConfig struct {
	// RequireDPoPForClients lists OAuth client IDs that MUST present a
	// DPoP proof on every token request. Clients not on this list may
	// still opt in by sending DPoP voluntarily; if they do, the issued
	// token is sender constrained. For clients on this list, the
	// absence of a proof is a 400 invalid_dpop_proof.
	RequireDPoPForClients []string

	// AllowedSignAlgs is the whitelist of signing algorithms a proof
	// JWT may use. Defaults to ES256, ES384, RS256, PS256, EdDSA. HMAC
	// algorithms (HS*) and "none" are always rejected per RFC 9449
	// section 4.2.
	AllowedSignAlgs []string

	// ProofMaxAge bounds how far in the past or future the proof's iat
	// claim may be. Defaults to 60 seconds; values much above 5 minutes
	// substantially weaken the protection.
	ProofMaxAge time.Duration

	// NonceTTL bounds how long an issued DPoP-Nonce remains acceptable.
	// Defaults to 10 minutes. Increasing this widens the window during
	// which a captured nonce remains replayable; decreasing it forces
	// clients to handle the use_dpop_nonce retry path more often.
	NonceTTL time.Duration

	// RequireNonceForTokens forces the token endpoint to demand a nonce
	// on every DPoP proof. A first-call proof without a nonce returns
	// HTTP 400 use_dpop_nonce + a DPoP-Nonce response header for the
	// retry. Off by default; turn this on when running an AS exposed to
	// untrusted clients to bound proof replay.
	RequireNonceForTokens bool

	// NonceSecret is the HMAC-SHA256 secret used to mint + verify
	// DPoP-Nonce headers. Leave empty to let New generate a fresh
	// 32-byte secret at startup; supply a stable value here when
	// running multiple AS instances behind a load balancer so any
	// instance can verify a nonce issued by any other.
	NonceSecret []byte

	// JTIReplayWindow caps the in-memory jti LRU size used to reject
	// replayed proofs within ProofMaxAge. Defaults to 4096; raise for
	// high-throughput AS deployments and lower for memory-constrained
	// ones. A value of 0 means default.
	JTIReplayWindow int
}

DPoPConfig configures the RFC 9449 DPoP verifier wired into both the authorization server and the mcpresource validator. All fields are optional; New populates sensible defaults when the operator does not override them. The wire shape matches the internal dpop.Config 1:1 because every field is operator-visible policy.

type DelegationGrant ¶

type DelegationGrant = models.DelegationGrant

type Device ¶ added in v2.10.0

type Device = models.Device

Device is a registered constrained device (see DeviceTokensConfig).

type DeviceAuthStart ¶

type DeviceAuthStart = apitokens.DeviceAuthStart

Token, device and principal types.

type DeviceAuthorization ¶ added in v2.8.0

type DeviceAuthorization = models.DeviceAuthorization

DeviceAuthorization is the persistent record of one OAuth device flow served at /oauth/device_authorization. It is unrelated to DeviceCode, which belongs to the API-token device flow.

type DeviceAuthorizationConfig ¶ added in v2.8.0

type DeviceAuthorizationConfig = internalas.DeviceConfig

DeviceAuthorizationConfig is the root alias for the RFC 8628 settings.

type DeviceAuthorizationStorage ¶ added in v2.8.0

type DeviceAuthorizationStorage interface {
	InsertDeviceAuthorization(ctx context.Context, d DeviceAuthorization) error
	DeviceAuthorizationByDeviceCodeHash(ctx context.Context, hash []byte) (*DeviceAuthorization, error)
	DeviceAuthorizationByUserCodeHash(ctx context.Context, hash []byte) (*DeviceAuthorization, error)
	DecideDeviceAuthorization(ctx context.Context, id ULID, status string, userID ULID, now time.Time) (bool, error)
	RecordDeviceAuthorizationPoll(ctx context.Context, id ULID, polledAt time.Time, intervalSeconds int) error
	ConsumeDeviceAuthorization(ctx context.Context, id ULID, now time.Time) (bool, error)
	DeleteExpiredDeviceAuthorizations(ctx context.Context, before time.Time) (int64, error)
}

DeviceAuthorizationStorage is the optional persistence extension for the OAuth device grant (Config.AuthorizationServer.DeviceAuthorization). Lookups return ErrStorageNotFound on a miss. Decide and Consume are conditional updates that report whether they applied. Memory, Postgres and MySQL implement it; run storagetest.RunDeviceAuthorizations against a custom one.

type DeviceCode ¶

type DeviceCode = apitokens.DeviceCode

Token, device and principal types.

type DeviceCodeLister ¶

type DeviceCodeLister = apitokens.DeviceCodeLister

Token, device and principal types.

type DeviceCodeStorage ¶

type DeviceCodeStorage = apitokens.DeviceCodeStorage

Token, device and principal types.

type DeviceConfig ¶

type DeviceConfig = apitokens.DeviceConfig

Token, device and principal types.

type DeviceDecision ¶

type DeviceDecision = apitokens.DeviceDecision

Token, device and principal types.

type DeviceIdentityStorage ¶ added in v2.10.0

type DeviceIdentityStorage interface {
	InsertDevice(ctx context.Context, d Device) error
	DeviceByID(ctx context.Context, id ULID) (*Device, error)
	ListDevices(ctx context.Context, orgID *ULID) ([]Device, error)
	RevokeDevice(ctx context.Context, id ULID, at time.Time) (bool, error)
	TouchDevice(ctx context.Context, id ULID, at time.Time) error

	InsertDeviceJoinToken(ctx context.Context, t DeviceJoinToken) error
	DeviceJoinTokenByHash(ctx context.Context, hash []byte) (*DeviceJoinToken, error)
	DeviceJoinTokenByID(ctx context.Context, id ULID) (*DeviceJoinToken, error)
	RevokeDeviceJoinToken(ctx context.Context, id ULID, at time.Time) (bool, error)
	RedeemDeviceJoinToken(ctx context.Context, id, deviceID ULID, now time.Time) (bool, error)
	RefundDeviceJoinToken(ctx context.Context, id ULID) error
}

DeviceIdentityStorage is the optional persistence extension for registered constrained devices and their join tokens (AuthorizationServer.DeviceTokens). Run storagetest.RunDeviceIdentity against a custom implementation.

type DeviceJoinToken ¶ added in v2.10.0

type DeviceJoinToken = models.DeviceJoinToken

DeviceJoinToken is a single-use device enrollment token.

type DevicePage ¶ added in v2.8.0

type DevicePage = internalas.DevicePage

DevicePage is the view model handed to DeviceAuthorizationConfig.Page.

type DevicePendingFilter ¶

type DevicePendingFilter = apitokens.DevicePendingFilter

Token, device and principal types.

type DeviceRequestInfo ¶

type DeviceRequestInfo = apitokens.DeviceRequestInfo

Token, device and principal types.

type DeviceRequestSummary ¶

type DeviceRequestSummary = apitokens.DeviceRequestSummary

Token, device and principal types.

type DeviceToken ¶

type DeviceToken = apitokens.DeviceToken

Token, device and principal types.

type DeviceTokensConfig ¶ added in v2.10.0

type DeviceTokensConfig = internalas.DeviceTokensConfig

DeviceTokensConfig is the root alias for the device identity settings.

type DoctorAdminLister ¶

type DoctorAdminLister interface {
	// ListAdminUserIDs returns the IDs of every user holding an admin role.
	ListAdminUserIDs(ctx context.Context) ([]ULID, error)
}

DoctorAdminLister is the optional storage capability that lets Doctor check second-factor coverage for administrators.

type DoctorSessionCounter ¶

type DoctorSessionCounter interface {
	// CountExpiredSessions counts sessions whose expiry is before the cutoff.
	CountExpiredSessions(ctx context.Context, before time.Time) (int, error)
}

DoctorSessionCounter is the optional storage capability that lets Doctor count sessions that expired but were never pruned.

type EmailMapper ¶

type EmailMapper struct {
	// Lookup finds a user by their email address. Wire in
	// Storage.UserByEmail at startup.
	Lookup func(email string) (ULID, error)
}

EmailMapper is the built-in SubjectMapper that looks up the user by email. The Lookup function must be provided (the AS wires in Storage.UserByEmail). Returns ErrStorageNotFound when no user with that email exists.

func (EmailMapper) Resolve ¶

func (m EmailMapper) Resolve(claims map[string]any) (ULID, error)

Resolve implements SubjectMapper by resolving claims["email"] to a user ID.

type EnrollTOTPResult ¶

type EnrollTOTPResult = totp.EnrollResult

EnrollTOTPResult is returned by BeginTOTPEnrollment for the caller to render. Re-exported as an alias so the v0.5 public surface is unchanged.

type Finding ¶

type Finding = doctor.Finding

Finding is one security-posture observation.

type Gauge ¶

type Gauge = observability.Gauge

Gauge is a settable, incrementable, decrementable instantaneous value.

type GrantDelegationInput ¶

type GrantDelegationInput = models.GrantDelegationInput

type Group ¶

type Group = models.Group

type HIBPBreachChecker ¶

type HIBPBreachChecker = password.HIBPChecker

HIBPBreachChecker is a BreachChecker backed by the Have I Been Pwned k-anonymity range API.

type Histogram ¶

type Histogram = observability.Histogram

Histogram is a distribution histogram.

type Hooks ¶

type Hooks = observability.Hooks

Hooks bundles the consumer-supplied observability adapters. Attach to Config.Observability to wire tracing + metrics into TheAuth. Either field MAY be nil; the library falls back to no-op adapters per field.

type IDJAGConfig ¶ added in v2.8.0

type IDJAGConfig = internalas.IDJAGConfig

IDJAGConfig is the root alias for the ID-JAG settings.

type IdentityConflictError ¶

type IdentityConflictError = models.IdentityConflictError

IdentityConflictError is returned (wrapped inside ErrIdentityConflict) by LinkOAuthToCurrentUser when the OAuth account is already bound to a different user. errors.As to this type to read ConflictingUserID and surface a merge-confirmation flow in the consumer UI.

type ImportUserStorage ¶

type ImportUserStorage interface {
	UserStorage
	SetUserPassword(ctx context.Context, userID ULID, passwordHash string) error
}

ImportUserStorage is the storage surface ImportUserTo needs.

type ImportedTOTP ¶

type ImportedTOTP = importer.ImportedTOTP

ImportedTOTP is an existing, already-enrolled TOTP secret.

type ImportedToken ¶

type ImportedToken = apitokens.ImportedToken

Token, device and principal types.

type ImportedUser ¶

type ImportedUser = importer.ImportedUser

ImportedUser is an existing account to insert. PasswordHash is stored verbatim and may be empty.

type ImportedWebAuthnCredential ¶

type ImportedWebAuthnCredential = importer.ImportedWebAuthnCredential

ImportedWebAuthnCredential is an existing passkey or security key.

type IntrospectionResponse ¶

type IntrospectionResponse = internalas.IntrospectionResponse

IntrospectionResponse mirrors the JSON shape mandated by RFC 7662 section 2.2 plus the v2.0 act chain and delegation_grant_id forward-compatibility fields.

type JARConfig ¶

type JARConfig = internalas.JARConfig

JARConfig is the root-package alias for as.JARConfig. Consumers set Config.AuthorizationServer.JAR to enable RFC 9101 support.

type JWKSKey ¶

type JWKSKey = models.JWKSKey

type JWTBearerConfig ¶

type JWTBearerConfig struct {
	// TrustedJWTIssuers is the list of external issuers whose JWTs may be
	// exchanged for AS-issued access tokens via the jwt-bearer grant (RFC
	// 7523 section 2.1). Each entry must specify Issuer and JWKSURL;
	// AllowedAlgorithms defaults to ["ES256","RS256","EdDSA"].
	TrustedJWTIssuers []TrustedJWTIssuer

	// ClientAssertionMaxAge bounds how far in the past the client assertion
	// JWT's iat claim may be. Defaults to 60 seconds (RFC 7523 recommends
	// short-lived assertions). Operators may tighten but rarely need to
	// widen this.
	ClientAssertionMaxAge time.Duration

	// AssertionMaxAge bounds how far in the past the bearer grant assertion
	// JWT's iat claim may be. Defaults to 300 seconds.
	AssertionMaxAge time.Duration

	// ReplayCacheTTL is the duration JTIs remain in the replay cache.
	// Defaults to 600 seconds (covers the maximum assertion lifetime with
	// comfortable margin). Backed by JWTBearerStorage.InsertJTI; backends
	// that do not implement JWTBearerStorage fall back to an in-process
	// sync.Map and lose replay protection across restarts.
	ReplayCacheTTL time.Duration

	// MaxActorChainDepth caps on-behalf-of actor chains in the RFC 8693
	// token-exchange grant. Defaults to 5. Values above 10 are not
	// recommended: each additional link adds a storage round-trip at
	// token-exchange time.
	MaxActorChainDepth int

	// JWKSCacheTTL is how long a JWKS fetched from a client jwks_uri or a
	// TrustedJWTIssuer.JWKSURL is reused before being fetched again, so key
	// rotation is picked up. Failed fetches are never cached. Defaults to
	// 5 minutes.
	JWKSCacheTTL time.Duration

	// JWKSCacheMaxEntries bounds how many distinct JWKS URLs are cached.
	// Defaults to 256.
	JWKSCacheMaxEntries int

	// JWKSFetchTimeout is the total time allowed for one JWKS fetch.
	// Defaults to 5 seconds.
	JWKSFetchTimeout time.Duration

	// AllowPrivateJWKSNetworks disables the dial-time block on loopback,
	// private, link-local and cloud metadata addresses when fetching JWKS
	// documents, and also permits plain http JWKS URLs. Development only:
	// it re-opens SSRF to internal hosts. Default false.
	AllowPrivateJWKSNetworks bool

	// JWKSHTTPClient, when non-nil, replaces the default SSRF-guarded
	// client used for JWKS fetches. It is used as-is, so it must provide
	// equivalent protection (no redirects, address guard). Intended for
	// tests that inject an httptest server.
	JWKSHTTPClient *http.Client
}

JWTBearerConfig controls RFC 7523 JWT client authentication and the JWT Bearer grant type. All fields have safe defaults.

type JWTBearerStorage ¶

type JWTBearerStorage interface {
	// InsertJTI records a new jti. Returns ErrStorageNotFound when the jti
	// already exists within the replay window (the name is intentional: the
	// replay cache shares the same sentinel as other "not found" checks;
	// callers detect duplicates by inspecting whether the returned error is
	// ErrStorageNotFound). expiresAt is when the jti may be pruned.
	//
	// Implementation note: use a unique constraint on (jti) and return
	// ErrStorageNotFound on conflict (the generic "duplicate" signal).
	InsertJTI(ctx context.Context, jti string, expiresAt time.Time) error
	// SweepExpiredJTIs removes all jti rows whose expiresAt is before the
	// supplied time. A no-op on an empty table.
	SweepExpiredJTIs(ctx context.Context, before time.Time) error
}

JWTBearerStorage is an optional extension that backends may implement to provide durable JTI replay prevention for RFC 7523 client assertions and bearer grant assertions. When the Storage passed to New also satisfies JWTBearerStorage, the AS uses it for all JTI checks; otherwise an in-process sync.Map is used (replay protection is lost on restart).

Replay protection requires only two methods; SweepExpiredJTIs is a maintenance helper that operators call on a schedule (or via a background goroutine).

type Labels ¶

type Labels = observability.Labels

Labels is the (name -> value) label set for a single metric instance. Cardinality discipline: callers MUST NOT put high-cardinality identifiers into Labels.

type LifecycleHooks ¶

type LifecycleHooks struct {
	OnSignup         func(ctx context.Context, user *User, method SignupMethod) error
	OnSignin         func(ctx context.Context, user *User, sess *Session) error
	OnPasswordChange func(ctx context.Context, user *User) error
	OnMFAEnabled     func(ctx context.Context, user *User, kind MFAKind) error
	OnTokenIssued    func(ctx context.Context, claims map[string]any) (map[string]any, error)
	OnOrgSwitch      func(ctx context.Context, user *User, orgID string) error
	// OnAccountDeleted fires after an account was deleted (DELETE /account,
	// DeleteUser). It is observe-only: the delete already committed, user is
	// the snapshot taken just before it, and an error or panic is only
	// logged. Use it to clean up host-side data keyed by the user.
	OnAccountDeleted func(ctx context.Context, user *User) error
	// OnOAuthConflict fires when a sign-in OAuth email matches an existing user
	// registered via a different provider. The hook must create a short-lived
	// verification challenge and return the redirect URL for it. When nil the
	// sign-in proceeds normally (silent provider linking).
	OnOAuthConflict func(ctx context.Context, p OAuthConflictPayload) (redirectURL string, err error)

	// OnHookError, when set, is called with the hook name (for example
	// "OnSignup") and the error whenever an observe-only hook returns an
	// error or panics (a panic is wrapped in an error). It runs in addition
	// to the slog line, never instead of it, so hosts can alert or count
	// failures instead of only logging them. It runs synchronously on the
	// request goroutine, so keep it fast; a panic inside it is recovered.
	// It does not change request outcomes. Nil keeps the default behavior.
	OnHookError func(ctx context.Context, hook string, err error)
}

type LoggingAuthenticationDevice ¶

type LoggingAuthenticationDevice struct{}

LoggingAuthenticationDevice satisfies AuthenticationDevice by logging notifications to log/slog at INFO level. Suitable for staging environments.

func (LoggingAuthenticationDevice) Notify ¶

Notify satisfies AuthenticationDevice. It logs the notification details and returns nil.

type LoginThrottleCASStore ¶

type LoginThrottleCASStore = throttle.CASStore

LoginThrottleCASStore is the optional LoginThrottleStore capability that lets several processes share counters without losing updates.

type LoginThrottleConfig ¶

type LoginThrottleConfig struct {
	Disabled bool
	// Store defaults to an in-memory store.
	Store LoginThrottleStore
	// GraceFailures is how many failed logins per (IP, identifier) pass
	// before backoff starts. Default 3.
	GraceFailures int
	// BaseDelay is the first backoff delay, doubled per further failure. Default 1s.
	BaseDelay time.Duration
	// MaxDelay caps the backoff. Default 15m.
	MaxDelay time.Duration
	// ResetAfter forgets failure counts after this much idle time. Default 15m.
	ResetAfter time.Duration
	// UserMaxFailures consecutive failures against one identifier, from any
	// IP, trigger a lockout. Default 10.
	UserMaxFailures int
	// UserLockout is how long that lockout lasts before auto-expiring. Default 15m.
	UserLockout time.Duration
	// MFAMaxFailures wrong TOTP or recovery codes per user, across all
	// pending sessions, trigger an MFA lockout. Default 5.
	MFAMaxFailures int
	// MFALockout is how long the MFA lockout lasts. Default 15m.
	MFALockout time.Duration
	// MaxEntries caps the default in-memory store. Default 100000.
	MaxEntries int
}

LoginThrottleConfig tunes login backoff, per-user lockout and MFA attempt limits. The nil Config.LoginThrottle selects the defaults below; set Disabled to turn the feature off.

type LoginThrottleEntry ¶

type LoginThrottleEntry = throttle.Entry

LoginThrottleEntry is one record held by a LoginThrottleStore.

type LoginThrottleEntryDeleter ¶ added in v2.7.0

type LoginThrottleEntryDeleter = throttle.LoginEntryDeleter

LoginThrottleEntryDeleter is the optional LoginThrottleStore capability that lets ResetPasswordAdmin clear an email's backoff entries across all client IPs.

type LoginThrottleStore ¶

type LoginThrottleStore = throttle.Store

LoginThrottleStore persists login and MFA throttle counters. The default is an in-memory store; supply your own to share state across processes.

func NewMemoryLoginThrottleStore ¶

func NewMemoryLoginThrottleStore(maxEntries int) LoginThrottleStore

NewMemoryLoginThrottleStore returns the default in-memory store, capped at maxEntries (zero selects 100000). Expired entries are swept on writes.

type MFAKind ¶

type MFAKind string

MFAKind identifies which second factor a user just enabled. Passed to LifecycleHooks.OnMFAEnabled.

const (
	MFAKindTOTP          MFAKind = "totp"
	MFAKindWebAuthn      MFAKind = "webauthn"
	MFAKindRecoveryCodes MFAKind = "recovery_codes"
)
type MagicLink = models.MagicLink

type MagicLinkStorage ¶

type MagicLinkStorage interface {
	CreateMagicLink(ctx context.Context, ml MagicLink) error
	ConsumeMagicLink(ctx context.Context, tokenHash []byte) (*MagicLink, error)
}

MagicLinkStorage covers single-use magic-link tokens.

type MemoryRevocationBus ¶

type MemoryRevocationBus = revocation.MemoryBus

MemoryRevocationBus is the in-process RevocationBus.

func NewMemoryRevocationBus ¶

func NewMemoryRevocationBus() *MemoryRevocationBus

NewMemoryRevocationBus returns an empty in-process bus.

type Metrics ¶

type Metrics = observability.Metrics

Metrics is the instrument factory adapters implement. See internal/observability.Metrics for the full contract.

type MintAPITokenInput ¶

type MintAPITokenInput = apitokens.MintAPITokenInput

Token, device and principal types.

type MintAgentTokenInput ¶

type MintAgentTokenInput = apitokens.MintAgentTokenInput

Token, device and principal types.

type MintSessionLinkInput ¶

type MintSessionLinkInput struct {
	UserID ULID
	// CredentialID ties the resulting session to an upstream credential that
	// is re-checked on every use. Empty mints an unbound link.
	CredentialID string
	// TTL overrides Config.SessionLinks.TTL when positive.
	TTL time.Duration
	// SessionTTL bounds the resulting session when positive.
	SessionTTL time.Duration
}

MintSessionLinkInput describes a session link to mint.

type NonceProvider ¶

type NonceProvider = internaloauth.NonceProvider

NonceProvider is the optional Provider extension for OIDC providers that validate an ID token nonce. The OAuth service detects it automatically.

type NoopAuthenticationDevice ¶

type NoopAuthenticationDevice struct{}

NoopAuthenticationDevice satisfies AuthenticationDevice by discarding every notification. Suitable for unit tests and operator deployments that manage notifications out of band.

func (NoopAuthenticationDevice) Notify ¶

Notify satisfies AuthenticationDevice. It is a no-op and always returns nil.

type OAuthAccount ¶

type OAuthAccount = models.OAuthAccount

type OAuthAccountStorage ¶

type OAuthAccountStorage interface {
	// UpsertOAuthAccount inserts or updates the row keyed by
	// (provider, provider_user_id). Returns the resulting row so callers
	// can use the assigned ID and timestamps. Implementations must encrypt
	// any token bytes before they reach storage; this layer only persists
	// what it is given.
	UpsertOAuthAccount(ctx context.Context, a OAuthAccount) (OAuthAccount, error)
	// OAuthAccountByProviderUserID looks up the row for a provider/user
	// pair. Returns ErrStorageNotFound when no row exists.
	OAuthAccountByProviderUserID(ctx context.Context, provider, providerUserID string) (*OAuthAccount, error)

	// OAuthAccountsByUserID returns all OAuth accounts linked to userID.
	// Returns an empty slice (not an error) when none exist.
	OAuthAccountsByUserID(ctx context.Context, userID ULID) ([]OAuthAccount, error)

	// MoveOAuthAccount reassigns the OAuth account row identified by
	// (provider, providerUserID) to newUserID. Returns ErrStorageNotFound
	// when no matching row exists.
	MoveOAuthAccount(ctx context.Context, provider, providerUserID string, newUserID ULID) error

	// DeleteOAuthAccountByProvider removes a single oauth_accounts row for
	// (userID, provider). Returns ErrStorageNotFound when no row exists.
	DeleteOAuthAccountByProvider(ctx context.Context, userID ULID, provider string) error
}

OAuthAccountStorage covers linked third-party OAuth accounts.

type OAuthCallbackResult ¶ added in v2.7.0

type OAuthCallbackResult = internaloauth.CallbackResult

OAuthCallbackResult is what OAuthCallback returns on success.

type OAuthClient ¶

type OAuthClient = models.OAuthClient

type OAuthConfig ¶

type OAuthConfig struct {
	// StateStore overrides the default in-memory state store.
	StateStore OAuthStateStore
	// StateTTL bounds how long a flow may take. Defaults to 10 minutes.
	StateTTL time.Duration
	// AllowedReturnTo lists the post-login destinations a caller may request
	// with ?return_to=. Entries are exact absolute URLs or paths beginning
	// with "/" (matched as exact path, or prefix when ending in "*").
	// Anything else is ignored and Config.PostLoginRedirect is used.
	AllowedReturnTo []string
	// Signup selects the new-user policy. Defaults to OAuthSignupOpen.
	Signup OAuthSignupPolicy
	// AllowedEmailDomains is required for OAuthSignupAllowedDomains.
	AllowedEmailDomains []string
	// InviteCheck is required for OAuthSignupInvite. It receives the
	// provider-verified, lower-cased email.
	InviteCheck func(ctx context.Context, email string) (bool, error)
	// RedirectURI, when set, builds the redirect_uri sent to the provider
	// instead of BaseURL + prefix + "/providers/{name}/callback". Use it to
	// keep callback URLs already registered at the provider. r is the
	// request that began the flow. The value is stored with the state and
	// reused verbatim at code exchange. It must be an absolute https URL
	// (http only for loopback or with AllowInsecureRedirectURI) with no
	// fragment or userinfo; any error fails the start. Deriving the host
	// from an unvalidated Host or X-Forwarded-Host header is unsafe: set
	// RedirectURIAllowedHosts. Experimental.
	RedirectURI func(r *http.Request, provider string) (string, error)
	// RedirectURIAllowedHosts, when non-empty, restricts the host (or
	// host:port) RedirectURI may return; anything else fails closed.
	// Experimental.
	RedirectURIAllowedHosts []string
	// AllowInsecureRedirectURI permits an http:// RedirectURI result on a
	// non-loopback host. For development only. Experimental.
	AllowInsecureRedirectURI bool
}

OAuthConfig tunes OAuth login hardening. The zero value keeps v2 behavior: in-memory state with a 10 minute TTL, no return-to parameter, and open signup.

type OAuthConflictPayload ¶

type OAuthConflictPayload struct {
	Provider        string
	ProviderUserID  string
	ProviderEmail   string
	ProviderName    string
	ProviderAvatar  string
	ExistingUserID  string // ULID string of the existing user
	AccessTokenEnc  []byte // AES-GCM encrypted provider access token
	RefreshTokenEnc []byte // AES-GCM encrypted provider refresh token (may be nil)
	ExpiresAt       *time.Time
	Scope           string
}

LifecycleHooks lets consumers react to authentication-lifecycle events without forking handlers. All fields are optional; nil hooks are silent no-ops. Hooks run synchronously after the underlying operation succeeds and before the HTTP response is written.

OnSignup, OnSignin, OnPasswordChange, OnMFAEnabled and OnOrgSwitch are observe-only, running after the action has committed. A returned error is logged at Warn level and reported to OnHookError when set; it does NOT fail the request. Use them for provisioning, analytics and notifications. To refuse a signup or sign-in before it is committed, gate it at the route wrapper or identity check, not via a hook.

Panics in hooks are recovered and logged; the request continues as if the hook returned nil.

OnTokenIssued is the only hook permitted to mutate state: it receives the claims map about to be signed into a JWT and returns the updated map. A non-nil error fails token issuance.

Wiring status: OnSignup fires from password, magic-link, OAuth, SAML, and a user's first WebAuthn credential. OnSignin fires from password (without second factor), the TOTP/recovery-code step that completes a password sign-in at pending_2fa, magic-link, OAuth, passkey login and SAML. OnMFAEnabled fires when TOTP enrollment is confirmed. OnTokenIssued fires from every OAuth access-token grant. OnOrgSwitch fires from explicit SetActiveOrganization only.

type OAuthServerStorage ¶

type OAuthServerStorage interface {
	// OAuth clients (RFC 7591).
	InsertOAuthClient(ctx context.Context, c OAuthClient) (OAuthClient, error)
	OAuthClientByClientID(ctx context.Context, clientID string) (*OAuthClient, error)
	UpdateOAuthClient(ctx context.Context, c OAuthClient) (OAuthClient, error)
	DeleteOAuthClient(ctx context.Context, clientID string) error

	// Authorization codes (single-use, 60-second TTL).
	InsertAuthorizationCode(ctx context.Context, c AuthorizationCode) error
	// ConsumeAuthorizationCode atomically loads-and-deletes a code row,
	// returning it. ErrStorageNotFound when absent or already consumed.
	ConsumeAuthorizationCode(ctx context.Context, code string) (*AuthorizationCode, error)

	// Refresh tokens (rotated on every use per RFC 9700 BCP).
	InsertRefreshToken(ctx context.Context, t RefreshToken) error
	RefreshTokenByHash(ctx context.Context, hash []byte) (*RefreshToken, error)
	RevokeRefreshToken(ctx context.Context, hash []byte, reason string) error
	RevokeRefreshTokenFamily(ctx context.Context, familyID ULID, reason string) error

	// JWKS keys. Private bytes arrive encrypted; storage layer is unaware of
	// the encryption envelope.
	InsertJWKSKey(ctx context.Context, k JWKSKey) error
	JWKSKeyByKID(ctx context.Context, kid string) (*JWKSKey, error)
	JWKSKeysAll(ctx context.Context) ([]JWKSKey, error)
	UpdateJWKSKeyState(ctx context.Context, kid, state string, at time.Time) error

	// Agents (v2.0 phase 3). Status transitions are recorded via
	// UpdateAgentStatus; last_active_at is updated by the introspection +
	// token paths so operators can see which agents are warm.
	InsertAgent(ctx context.Context, a Agent) (Agent, error)
	AgentByID(ctx context.Context, id ULID) (*Agent, error)
	AgentByClientID(ctx context.Context, clientID string) (*Agent, error)
	AgentsByOwner(ctx context.Context, owner AgentOwner) ([]Agent, error)
	UpdateAgentStatus(ctx context.Context, id ULID, status string, at time.Time) error
	UpdateAgentLastActive(ctx context.Context, id ULID, at time.Time) error

	// Agent credentials. Multiple rows per agent so a rotation can issue a
	// fresh credential before revoking the previous one. RevokeAgentCredential
	// sets revoked_at; AgentCredentialsByAgentID returns every row (callers
	// filter on RevokedAt themselves so audit views can list history).
	InsertAgentCredential(ctx context.Context, c AgentCredential) error
	AgentCredentialsByAgentID(ctx context.Context, agentID ULID) ([]AgentCredential, error)
	RevokeAgentCredential(ctx context.Context, id ULID, at time.Time) error
	UpdateAgentCredentialLastUsed(ctx context.Context, id ULID, at time.Time) error

	// Delegations (v2.0 phase 4). Uniqueness on (user_id, agent_id, resource)
	// is enforced at the database layer; InsertDelegationGrant returns a
	// wrapped error when violated. RevokeDelegationGrant sets revoked_at;
	// introspection on every resource server call honors the change inside
	// AuthorizationServerConfig.IntrospectionCacheTTL.
	InsertDelegationGrant(ctx context.Context, g DelegationGrant) (DelegationGrant, error)
	DelegationGrantByID(ctx context.Context, id ULID) (*DelegationGrant, error)
	DelegationGrantByUserAgentResource(ctx context.Context, userID, agentID ULID, resource string) (*DelegationGrant, error)
	DelegationGrantsByUserID(ctx context.Context, userID ULID) ([]DelegationGrant, error)
	DelegationGrantsByAgentID(ctx context.Context, agentID ULID) ([]DelegationGrant, error)
	RevokeDelegationGrant(ctx context.Context, id ULID, at time.Time, reason string) error
}

OAuthServerStorage is the subset of persistence required by the OAuth 2.1 authorization server, the JWKS rotation goroutine, and dynamic client registration. Phase 1 + 2 only. Agent and delegation methods land in phase 3 + 4 alongside the corresponding service code.

type OAuthSignupPolicy ¶

type OAuthSignupPolicy string

OAuthSignupPolicy decides whether an OAuth sign-in may create a new user.

const (
	// OAuthSignupOpen lets any provider-authenticated identity create an
	// account. It is the default so existing v2 deployments are unchanged.
	OAuthSignupOpen OAuthSignupPolicy = "open"
	// OAuthSignupClosed refuses to create users from OAuth; only existing
	// users and linked accounts can sign in.
	OAuthSignupClosed OAuthSignupPolicy = "closed"
	// OAuthSignupAllowedDomains creates users only when the provider-verified
	// email domain is listed in OAuthConfig.AllowedEmailDomains.
	OAuthSignupAllowedDomains OAuthSignupPolicy = "allowed_domains"
	// OAuthSignupInvite creates users only when OAuthConfig.InviteCheck
	// approves the verified email.
	OAuthSignupInvite OAuthSignupPolicy = "invite"
)

type OAuthStartResult ¶ added in v2.7.0

type OAuthStartResult = internaloauth.StartResult

OAuthStartResult is what OAuthStart returns: the provider authorization URL to redirect the browser to and the Binding secret to set as an HttpOnly cookie (presented again to OAuthCallback).

type OAuthState ¶

type OAuthState = internaloauth.State

OAuthState is the per-flow record kept between /start and /callback.

type OAuthStateStore ¶

type OAuthStateStore = internaloauth.StateStore

OAuthStateStore holds OAuth flow state between /start and /callback. Implement it over a shared store (Redis, SQL) to run several replicas behind a load balancer; the default in-memory store is single-process.

type OIDCConfig ¶ added in v2.10.0

type OIDCConfig = internalas.OIDCConfig

OIDCConfig is the root alias for the OpenID Provider settings.

type OpaqueAccessToken ¶ added in v2.8.0

type OpaqueAccessToken = models.OpaqueAccessToken

OpaqueAccessToken is the server-side record behind a reference access token. Only the SHA-256 hash of the token is stored.

type OpaqueTokenStorage ¶ added in v2.8.0

type OpaqueTokenStorage interface {
	InsertOpaqueAccessToken(ctx context.Context, t OpaqueAccessToken) error
	OpaqueAccessTokenByHash(ctx context.Context, hash []byte) (*OpaqueAccessToken, error)
	RevokeOpaqueAccessToken(ctx context.Context, hash []byte) error
}

OpaqueTokenStorage is the optional persistence extension behind opaque (reference) access tokens, enabled per client through AuthorizationServerConfig.TokenPolicy. Only token hashes are stored. Lookups return ErrStorageNotFound on a miss. Revoking an unknown token is not an error. Run storagetest.RunOpaqueTokens against a custom implementation.

type Organization ¶

type Organization = models.Organization

type OrganizationMember ¶

type OrganizationMember = models.OrganizationMember

type OrganizationStorage ¶

type OrganizationStorage interface {
	InsertOrganization(ctx context.Context, o Organization) (Organization, error)
	OrganizationByID(ctx context.Context, id ULID) (*Organization, error)
	OrganizationBySlug(ctx context.Context, slug string) (*Organization, error)
	UpdateOrganization(ctx context.Context, o Organization) error
	DeleteOrganization(ctx context.Context, id ULID) error

	UpsertOrganizationMember(ctx context.Context, m OrganizationMember) error
	DeleteOrganizationMember(ctx context.Context, orgID, userID ULID) error
	OrganizationMembersByOrg(ctx context.Context, orgID ULID) ([]OrganizationMember, error)
	OrganizationsByUser(ctx context.Context, userID ULID) ([]Organization, error)
	OrganizationMemberRole(ctx context.Context, orgID, userID ULID) (string, error)

	SetSessionActiveOrganization(ctx context.Context, sessionID ULID, orgID *ULID) error
}

OrganizationStorage covers organizations, membership and the session active-organization pointer.

type OrganizationsConfig ¶

type OrganizationsConfig struct{}

OrganizationsConfig is currently empty: there are no tunables for v0.7. The presence of a non-nil value is the signal that multi-tenancy is on. Future fields (default member role, invitation TTL, etc.) land here without breaking the existing zero-value wiring.

type PARConfig ¶

type PARConfig = internalas.PARConfig

PARConfig is the root-package alias for as.PARConfig. Consumers set Config.AuthorizationServer.PAR to enable RFC 9126 support.

type PasswordPolicyConfig ¶

type PasswordPolicyConfig struct {
	// AllowLegacyBcrypt enables the legacy-hash fallback in VerifyPassword for
	// migrated users. When true, bcrypt hashes ("$2a$", "$2b$", "$2x$", from
	// Auth0 and others) and PBKDF2 hashes ("$pbkdf2-sha256$", "$pbkdf2-sha512$",
	// from Keycloak) are verified. On a successful match the password is
	// transparently re-hashed with Argon2id and persisted by the library;
	// hosts that mirror hashes can observe it via OnLegacyHashAccepted.
	// With false, a bcrypt hash fails as invalid credentials. Set to false (default) in all non-migration deployments.
	AllowLegacyBcrypt bool

	// HashConcurrency bounds how many Argon2id hashes or verifications run at
	// once across the process; extra sign-ins wait their turn instead of each
	// allocating 64 MiB. Default NumCPU/4 (at least 1), which measured as the
	// throughput knee. The bound is process-wide, the last New call wins.
	HashConcurrency int

	// MinLength is the minimum password length in bytes. Default 12.
	MinLength int

	// MaxBytes is the maximum password length in bytes. Longer passwords are
	// rejected with CodeWeakPassword (HTTP 400). Default 72, the bcrypt limit.
	MaxBytes int

	// BreachChecker, when set, rejects passwords found in a breach corpus on
	// signup and password change. Lookup errors fail open. Default nil (off).
	BreachChecker BreachChecker

	// OnLegacyHashAccepted is invoked after the library has persisted the new
	// Argon2id hash for a user who signed in or stepped up with a legacy
	// bcrypt hash, from a separate goroutine, with (userID, newArgon2idHash).
	// A host that mirrors password hashes can update its own copy. The
	// library does not need it to work, so leaving it nil is fine. It is not
	// called if the rehash or persist failed, a panic in it is recovered and
	// logged, and it never blocks or fails the login.
	OnLegacyHashAccepted func(userID string, newArgon2idHash string)
}

PasswordPolicyConfig holds optional password-verification extensions. These are designed for migration windows; disable them once users have been migrated and re-hashed.

type PasswordResetToken ¶

type PasswordResetToken = models.PasswordResetToken

PasswordResetToken backs the /auth/email-password/forgot+reset flow.

type PasswordStorage ¶

type PasswordStorage interface {
	SetUserPassword(ctx context.Context, userID ULID, passwordHash string) error
	// UserByEmailWithPassword fetches a user along with their stored PHC hash.
	// passwordHash is "" if the account exists but has never set a password
	// (e.g. magic-link-only signup). Callers should treat empty hash as
	// "no password credential available" and surface invalid_credentials.
	UserByEmailWithPassword(ctx context.Context, email string) (user *User, passwordHash string, err error)
	CreatePasswordResetToken(ctx context.Context, t PasswordResetToken) error
	ConsumePasswordResetToken(ctx context.Context, tokenHash []byte) (*PasswordResetToken, error)
	// UserPasswordHashByID returns the stored Argon2id PHC string for the
	// user, or "" when the user has no password set.
	UserPasswordHashByID(ctx context.Context, userID ULID) (string, error)

	// MovePasswordHash copies the Argon2id hash from secondaryID to
	// primaryID (overwriting any hash primaryID already has) and then
	// clears secondaryID's hash. A no-op if secondaryID has no hash.
	MovePasswordHash(ctx context.Context, primaryID, secondaryID ULID) error
}

PasswordStorage covers password hashes and reset tokens.

type Permission ¶

type Permission = models.Permission

func SeededPermissions ¶

func SeededPermissions() []Permission

SeededPermissions returns the v1.0 canonical permission catalog. The slice is returned by value (callers may not mutate the library state).

type Principal ¶

type Principal = apitokens.Principal

Token, device and principal types.

func PrincipalFromContext ¶

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

PrincipalFromContext returns the Principal attached by RequireAbility.

type PrincipalKind ¶

type PrincipalKind = apitokens.PrincipalKind

Token, device and principal types.

type ProtectedResource ¶

type ProtectedResource = models.ProtectedResource

ProtectedResource describes one resource server protected by this AS.

type ProtectedResourceMetadata ¶

type ProtectedResourceMetadata = internalas.ProtectedResourceMetadata

ProtectedResourceMetadata is the JSON document mandated by RFC 9728.

type Provider ¶

type Provider = internaloauth.Provider

Provider is the contract every OAuth 2.0 / OIDC provider implements. Each concrete provider lives in its own sub-package under provider/<name>/ so consumers can pick what to import (avoids dragging in HTTP clients for providers they will never use).

The type moved to internal/oauth in PR H (2026-06-22); this alias keeps the v0.3+ public surface byte-stable.

type ProviderLister ¶

type ProviderLister = internaloauth.ProviderLister

ProviderLister is optionally implemented by a ProviderResolver so ListProviders can include its providers.

type ProviderResolver ¶

type ProviderResolver = internaloauth.ProviderResolver

ProviderResolver supplies OAuth/OIDC providers at request time. Resolve returns (nil, false, nil) for an unknown name and an error when the lookup itself failed. The returned provider's Name() must equal name.

type ProviderToken ¶

type ProviderToken = internaloauth.ProviderToken

ProviderToken is the normalized shape of an OAuth token exchange response. Providers vary in which fields they populate (e.g. GitHub typically omits RefreshToken and ExpiresAt for "no-expiry" tokens). Storage encrypts the access/refresh tokens at rest via crypto.Encrypt.

The type moved to internal/oauth in PR H (2026-06-22); this alias keeps the v0.3+ public surface byte-stable.

type ProviderUser ¶

type ProviderUser = internaloauth.ProviderUser

ProviderUser is the normalized shape of a provider's userinfo response. ID is the provider-stable user identifier (e.g. GitHub numeric id as a string) and is what oauth_accounts.provider_user_id stores. Email may be empty when the user denied the email scope or has no public email on the provider; EmailVerified is true only when the provider attests to it.

The type moved to internal/oauth in PR H (2026-06-22); this alias keeps the v0.3+ public surface byte-stable.

type RARConfig ¶ added in v2.8.0

type RARConfig = internalas.RARConfig

RARConfig is the root alias for the RFC 9396 settings.

type RBACConfig ¶

type RBACConfig struct {
	// Permissions extends the seeded catalog. Names are deduped by case-
	// sensitive equality with the seeded list. New returns an error if any
	// supplied name contains whitespace or non-ASCII (permission names are
	// program identifiers, not user input).
	Permissions []Permission

	// DefaultRoles seeds every new organization. When empty the three
	// default roles ("owner", "admin", "member") are used. Reserved names
	// ("owner", "admin", "member") must remain present when consumers
	// override; New returns an error otherwise.
	DefaultRoles []RoleSeed
}

RBACConfig configures organization-scoped roles and permissions. The zero value is valid and accepts the seeded permission list plus the seeded "owner", "admin", "member" roles.

type RBACStorage ¶

type RBACStorage interface {
	// Permissions form a global catalog (no org scope). Insert is idempotent
	// on the name unique index; duplicate names return the existing row
	// rather than an error so seed runs at app start are safe.
	InsertPermission(ctx context.Context, p Permission) (Permission, error)
	PermissionByName(ctx context.Context, name string) (*Permission, error)
	ListPermissions(ctx context.Context) ([]Permission, error)

	InsertRole(ctx context.Context, r Role) (Role, error)
	UpdateRoleRow(ctx context.Context, r Role) (Role, error)
	DeleteRole(ctx context.Context, id ULID) error
	RoleByID(ctx context.Context, id ULID) (*Role, error)
	RoleByOrgAndName(ctx context.Context, orgID *ULID, name string) (*Role, error)
	RolesByOrganization(ctx context.Context, orgID *ULID) ([]Role, error)

	SetRolePermissions(ctx context.Context, roleID ULID, permissionIDs []ULID) error
	// PermissionsByRole returns the permission-name slice for one role.
	// The names are looked up by joining role_permissions to permissions.
	PermissionsByRole(ctx context.Context, roleID ULID) ([]string, error)

	GrantUserRole(ctx context.Context, ur UserRole) error
	RevokeUserRole(ctx context.Context, userID, roleID ULID) error
	RolesForUser(ctx context.Context, userID ULID, orgID *ULID) ([]Role, error)
	PermissionsForUser(ctx context.Context, userID ULID, orgID *ULID) ([]string, error)
	CountUsersWithPermissionInOrg(ctx context.Context, orgID ULID, perm string) (int, error)
}

RBACStorage covers permissions, roles and user-role grants.

type RecoveryCode ¶

type RecoveryCode = models.RecoveryCode

type RecoveryCodeStorage ¶

type RecoveryCodeStorage interface {
	// CountUnusedRecoveryCodes returns how many unused codes userID holds.
	CountUnusedRecoveryCodes(ctx context.Context, userID ULID) (int, error)
	// ReplaceRecoveryCodes atomically deletes every code of userID and
	// inserts codes.
	ReplaceRecoveryCodes(ctx context.Context, userID ULID, codes []RecoveryCode) error
}

RecoveryCodeStorage is the optional capability behind GET /auth/totp (remaining recovery codes) and POST /auth/totp/recovery-codes. Without it the status route reports -1 remaining and regeneration answers 501.

type RefreshProvider ¶ added in v2.10.0

type RefreshProvider = internaloauth.RefreshProvider

RefreshProvider is the optional Provider capability behind GetProviderToken. RefreshToken exchanges a refresh token for a fresh access token (RFC 6749 section 6). It must return an error wrapping ErrProviderGrantRevoked when the provider rejects the refresh token as invalid or revoked. The returned token's RefreshToken may be empty when the provider does not rotate it; the stored one is then kept. Providers that do not implement it keep working for sign-in; GetProviderToken answers ErrProviderRefreshUnsupported for them once the token expired.

type RefreshToken ¶

type RefreshToken = models.RefreshToken

type RegisterAgentInput ¶

type RegisterAgentInput = agent.RegisterInput

Token, device and principal types.

type RegisteredClient ¶

type RegisteredClient = models.RegisteredClient

RegisteredClient is the JSON body returned on a successful registration (RFC 7591 section 3.2.1).

type RegistrationToken ¶ added in v2.8.0

type RegistrationToken = models.RegistrationToken

RegistrationToken is an initial access token for POST /oauth/register.

type RegistrationTokenStorage ¶ added in v2.8.0

type RegistrationTokenStorage interface {
	InsertRegistrationToken(ctx context.Context, t RegistrationToken) error
	RegistrationTokenByHash(ctx context.Context, hash []byte) (*RegistrationToken, error)
	RegistrationTokenByID(ctx context.Context, id ULID) (*RegistrationToken, error)
	ListRegistrationTokens(ctx context.Context, orgID *ULID) ([]RegistrationToken, error)
	RevokeRegistrationToken(ctx context.Context, id ULID, at time.Time) (bool, error)
	RedeemRegistrationToken(ctx context.Context, id ULID, now time.Time) (bool, error)
	RefundRegistrationToken(ctx context.Context, id ULID) error
}

RegistrationTokenStorage is the optional persistence extension for initial access tokens (admin API plus POST /oauth/register). Run storagetest.RunRegistrationTokens against a custom implementation.

type Report ¶

type Report = doctor.Report

Report is the result of TheAuth.Doctor.

type ResetPasswordOption ¶ added in v2.10.0

type ResetPasswordOption func(*resetPasswordOptions)

ResetPasswordOption customizes ResetPasswordAdmin.

func RequirePasswordChange ¶ added in v2.10.0

func RequirePasswordChange() ResetPasswordOption

RequirePasswordChange makes ResetPasswordAdmin flag the account so the user must choose a new password before the next sign-in completes (it returns CodePasswordChangeRequired until the user finishes a password reset). It needs Config.AccountState.

type RevocationBus ¶

type RevocationBus = revocation.Bus

RevocationBus fans revocation events out to subscribers.

type RevocationEvent ¶

type RevocationEvent = revocation.Event

RevocationEvent reports one revocation. An empty ID means "every credential of this kind belonging to UserID".

type RevocationKind ¶

type RevocationKind = revocation.Kind

RevocationKind says what was revoked.

type RevocationTarget ¶

type RevocationTarget = revocation.Target

RevocationTarget names the credential a stream was opened with.

func TargetForPrincipal ¶

func TargetForPrincipal(p *Principal) RevocationTarget

TargetForPrincipal builds the watch target for an authenticated principal.

type Role ¶

type Role = models.Role

type RoleSeed ¶

type RoleSeed = rbac.RoleSeed

RoleSeed describes one organization-scoped role created at SeedOrganizationRoles time. Permissions are permission names; unknown names cause New to return a validation error so typos surface at startup instead of on the first permission check.

func DefaultRoleSeeds ¶

func DefaultRoleSeeds() []RoleSeed

DefaultRoleSeeds returns the three default organization roles seeded into every new organization. Consumers may extend with additional roles via Config.RBAC.DefaultRoles; the three reserved names ("owner", "admin", "member") must always remain present.

type SAMLAttributeMap ¶

type SAMLAttributeMap = models.SAMLAttributeMap

type SAMLConfig ¶

type SAMLConfig struct {
	// SPCertificatePEM and SPPrivateKeyPEM are PEM-encoded; they sign every
	// outbound AuthnRequest and identify the SP in metadata XML. New returns
	// an error if either is missing or unparseable.
	SPCertificatePEM []byte
	SPPrivateKeyPEM  []byte

	// AuthnRequestTTL caps how long an outstanding SP-initiated AuthnRequest
	// ID is tracked for replay protection. Defaults to 10 minutes.
	AuthnRequestTTL time.Duration

	// ClockSkew accepted on Conditions.NotBefore / NotOnOrAfter. Defaults to
	// 30 seconds (matches crewjam default). Some IdPs (Okta on slow clocks)
	// need 60s.
	ClockSkew time.Duration

	// AllowedRelayStates lists extra post-login destinations accepted as
	// RelayState (exact absolute URLs, or "/" prefixes ending in "*").
	// Same-site paths and Config.PostLoginRedirect are always accepted;
	// any other RelayState falls back to PostLoginRedirect.
	AllowedRelayStates []string
}

SAMLConfig wires the Service Provider keypair and base behavior. Per-IdP configuration lives in saml_connections rows, not here.

type SAMLConnection ¶

type SAMLConnection = models.SAMLConnection

type SAMLConnectionInput ¶

type SAMLConnectionInput struct {
	OrganizationID ULID
	IdPEntityID    string
	IdPSSOURL      string
	IdPX509Cert    string
	SPEntityID     string
	SPACSURL       string
	AttributeMap   SAMLAttributeMap
}

SAMLConnectionInput is the consumer-facing payload for create / update. Mirrors internal/saml.SAMLConnectionInput field-for-field so the public type is unchanged.

type SAMLIdentity ¶

type SAMLIdentity = models.SAMLIdentity

type SAMLStorage ¶

type SAMLStorage interface {
	InsertSAMLConnection(ctx context.Context, c SAMLConnection) (SAMLConnection, error)
	UpdateSAMLConnectionRow(ctx context.Context, c SAMLConnection) error
	DeleteSAMLConnection(ctx context.Context, id ULID) error
	SAMLConnectionByID(ctx context.Context, id ULID) (*SAMLConnection, error)
	SAMLConnectionsByOrg(ctx context.Context, orgID ULID) ([]SAMLConnection, error)

	UpsertSAMLIdentity(ctx context.Context, i SAMLIdentity) (SAMLIdentity, error)
	SAMLIdentityByConnectionAndNameID(ctx context.Context, connectionID ULID, nameID string) (*SAMLIdentity, error)
	TouchSAMLIdentityLastLogin(ctx context.Context, id ULID, at time.Time) error
}

SAMLStorage covers SAML connections and identities.

type SCIMAuthResult ¶

type SCIMAuthResult struct {
	OrgID   ULID
	TokenID ULID
}

SCIMAuthResult is the value returned by AuthenticateSCIMToken. Bundling OrgID and TokenID avoids the second SCIMTokenByHash storage call the middleware previously performed after a successful authentication (perf re-audit 2026-06-21, item 1).

type SCIMConfig ¶

type SCIMConfig struct {
	// RequireHTTPS rejects requests whose r.TLS is nil and whose
	// X-Forwarded-Proto header is not "https". Default true. Set false only
	// when SCIM is fronted by a TLS-terminating proxy that strips the header
	// (in which case the proxy is responsible for TLS).
	RequireHTTPS bool

	// MaxPageSize caps the count parameter on list endpoints. Defaults to
	// 200. RFC 7644 section 3.4.2 lets the server enforce a maximum.
	MaxPageSize int
}

SCIMConfig wires the SCIM 2.0 endpoint behavior.

type SCIMGroupFilter ¶

type SCIMGroupFilter = models.SCIMGroupFilter

type SCIMStorage ¶

type SCIMStorage interface {
	InsertSCIMToken(ctx context.Context, t SCIMToken) (SCIMToken, error)
	SCIMTokenByHash(ctx context.Context, hash []byte) (*SCIMToken, error)
	SCIMTokensByOrg(ctx context.Context, orgID ULID) ([]SCIMToken, error)
	RevokeSCIMTokenByID(ctx context.Context, id ULID, at time.Time) error
	TouchSCIMTokenLastUsed(ctx context.Context, id ULID, at time.Time) error

	// SCIM user + group lookups scoped to a single organization
	ListUsersByOrganization(ctx context.Context, orgID ULID, offset, limit int, filter SCIMUserFilter) (users []User, total int, err error)
	ListGroupsByOrganization(ctx context.Context, orgID ULID, offset, limit int, filter SCIMGroupFilter) (groups []Group, total int, err error)
	UserByExternalIDInOrg(ctx context.Context, orgID ULID, externalID string) (*User, error)
	UpdateUserSCIM(ctx context.Context, u User) error

	// Groups (SCIM)
	InsertGroup(ctx context.Context, g Group) (Group, error)
	GroupByID(ctx context.Context, id ULID) (*Group, error)
	GroupByExternalIDInOrg(ctx context.Context, orgID ULID, externalID string) (*Group, error)
	UpdateGroup(ctx context.Context, g Group) error
	DeleteGroup(ctx context.Context, id ULID) error
	SetGroupMembers(ctx context.Context, groupID ULID, userIDs []ULID) error
	AddGroupMembers(ctx context.Context, groupID ULID, userIDs []ULID) error
	RemoveGroupMembers(ctx context.Context, groupID ULID, userIDs []ULID) error
	GroupMembers(ctx context.Context, groupID ULID) ([]ULID, error)
}

SCIMStorage covers SCIM tokens, organization-scoped user lookups and groups.

type SCIMToken ¶

type SCIMToken = models.SCIMToken

type SCIMUserFilter ¶

type SCIMUserFilter = models.SCIMUserFilter

type Session ¶

type Session = models.Session

func SessionFromContext ¶

func SessionFromContext(ctx context.Context) (*Session, bool)

SessionFromContext returns the Session attached by Authn middleware, if any. Returns false when the request is anonymous.

type SessionInfo ¶

type SessionInfo struct {
	ID          ULID      `json:"id"`
	DeviceLabel string    `json:"deviceLabel"`
	IPPrefix    string    `json:"ipPrefix,omitempty"`
	CreatedAt   time.Time `json:"createdAt"`
	LastSeenAt  time.Time `json:"lastSeenAt"`
	ExpiresAt   time.Time `json:"expiresAt"`
	Current     bool      `json:"current"`
}

SessionInfo is the end-user view of one session.

type SessionLink = models.SessionLink

SessionLink is a short-lived, single-use grant that exchanges for a session.

type SessionLinkStorage ¶

type SessionLinkStorage interface {
	CreateSessionLink(ctx context.Context, l SessionLink) error
	// ConsumeSessionLink atomically marks the link used and returns it. It
	// returns ErrStorageNotFound when the hash is unknown, already used, or
	// expired at now.
	ConsumeSessionLink(ctx context.Context, tokenHash []byte, now time.Time) (*SessionLink, error)
}

SessionLinkStorage is the optional capability behind programmatic session links.

type SessionLinksConfig ¶

type SessionLinksConfig struct {
	// TTL is how long a minted link can be exchanged. Defaults to 2m.
	TTL time.Duration
	// CredentialChecker is consulted at mint, at exchange, and on every use
	// of a session that carries a CredentialID. Required.
	CredentialChecker CredentialChecker
}

SessionLinksConfig enables programmatic session links.

type SessionManagementStorage ¶

type SessionManagementStorage interface {
	// ListUserSessions returns the user's sessions that are neither revoked
	// nor past ExpiresAt, newest first.
	ListUserSessions(ctx context.Context, userID ULID) ([]Session, error)
	// TouchSession advances LastSeenAt to at. It never moves it backwards
	// and returns ErrStorageNotFound for an unknown id.
	TouchSession(ctx context.Context, id ULID, at time.Time) error
	// RevokeOtherUserSessions revokes every live session of userID except
	// keep and returns how many it revoked.
	RevokeOtherUserSessions(ctx context.Context, userID, keep ULID) (int, error)
	// RevokeSessionsByCredential revokes every live session tied to
	// credentialID and returns how many it revoked.
	RevokeSessionsByCredential(ctx context.Context, credentialID string) (int, error)
	// SetSessionElevatedUntil sets or clears ElevatedUntil on one session.
	SetSessionElevatedUntil(ctx context.Context, id ULID, until *time.Time) error
}

SessionManagementStorage is the optional capability behind end-user session lists, idle timeout, last-seen tracking and step-up. It is detected by type assertion and is not part of Storage.

type SessionOverflow ¶ added in v2.10.0

type SessionOverflow string

SessionOverflow says what happens when a sign-in would exceed SessionPolicy.MaxConcurrentSessions.

const (
	// SessionEvictOldest revokes the user's oldest sessions to make room.
	// It is the default.
	SessionEvictOldest SessionOverflow = "evict_oldest"
	// SessionReject refuses the new sign-in with CodeSessionLimit.
	SessionReject SessionOverflow = "reject"
)

type SessionPolicy ¶ added in v2.10.0

type SessionPolicy struct {
	// MaxConcurrentSessions is the cap. Zero disables it.
	MaxConcurrentSessions int
	// Overflow is SessionEvictOldest (default) or SessionReject.
	Overflow SessionOverflow
}

SessionPolicy bounds how many full sessions one user may hold at once. It needs a storage implementing SessionManagementStorage. Pending 2FA sessions do not count. The check is best effort under concurrency: two simultaneous sign-ins can both pass it.

type SessionStorage ¶

type SessionStorage interface {
	CreateSession(ctx context.Context, s Session) (Session, error)
	SessionByTokenHash(ctx context.Context, hash []byte) (*Session, error)
	SessionByID(ctx context.Context, id ULID) (*Session, error)
	RevokeSession(ctx context.Context, id ULID) error
	RevokeUserSessions(ctx context.Context, userID ULID) error
	// CreateSessionWithAuthLevel mints a session whose AuthLevel column is
	// set to the supplied value (typically AuthLevelPending2FA). Mirrors
	// CreateSession otherwise. CreateSession itself continues to default
	// to AuthLevelFull at the DDL layer so older callers see no change.
	CreateSessionWithAuthLevel(ctx context.Context, s Session) (Session, error)
	// UpdateSessionAuthLevel rewrites a single session's AuthLevel column.
	// Used by /auth/totp/verify to promote a pending session to full.
	UpdateSessionAuthLevel(ctx context.Context, id ULID, level string) error
}

SessionStorage covers session issuance, lookup, revocation and auth-level step-up.

type Severity ¶

type Severity = doctor.Severity

Severity ranks a doctor finding.

type SharedSignalsConfig ¶ added in v2.10.0

type SharedSignalsConfig struct {
	// Authenticate resolves the calling receiver of the stream management
	// and poll endpoints, typically by validating an access token. It
	// returns a stable receiver id that owns the streams it creates.
	// Required. signals.StaticBearerAuth covers simple setups.
	Authenticate func(r *http.Request) (receiverID string, ok bool)

	// Issuer is the SET issuer. Default: AuthorizationServer.Issuer, which
	// the feature requires (SETs are signed with the AS keys and the JWKS
	// served at /oauth/jwks verifies them).
	Issuer string
	// BaseURL is the public URL the handler is mounted at, used for
	// endpoint URLs in the metadata document. Default: Issuer.
	BaseURL string
	// Store holds streams and the delivery queue. Default: in memory, which
	// loses queued events on restart; use the sqlite or postgres
	// SignalsStore for production.
	Store signals.Store

	// EmitFromAudit emits SSF events from the library's own audit actions
	// (session revoke, sessions revoke, password change, passkey and TOTP
	// changes, account disable and enable). Off by default.
	EmitFromAudit bool
	// SubjectFor builds the subject identifier of a local user. Default is
	// an iss_sub subject with the issuer and the user id.
	SubjectFor signals.SubjectFunc

	// AllowPrivateNetworks and AllowInsecureHTTP relax push URL validation.
	// Leave both false in production.
	AllowPrivateNetworks bool
	AllowInsecureHTTP    bool
	// MaxAttempts, BackoffBase and BackoffMax tune push retry. Defaults 8,
	// 2s and 15m.
	MaxAttempts int
	BackoffBase time.Duration
	BackoffMax  time.Duration

	// Receiver, when non-nil, builds a receiver for incoming SETs.
	Receiver *SharedSignalsReceiverConfig
}

SharedSignalsConfig enables the OpenID Shared Signals Framework 1.0 transmitter (with CAEP and RISC events) and, optionally, a receiver. See docs/shared-signals.md. Nil keeps the feature off and adds no routes, no goroutines and no per-event work.

type SharedSignalsReceiverConfig ¶ added in v2.10.0

type SharedSignalsReceiverConfig struct {
	// Audience is this receiver's identifier, matched against SET aud.
	Audience string
	// Issuers lists trusted transmitters: iss value to optional jwks_uri.
	Issuers map[string]string
	// Authenticate approves push requests. Strongly recommended.
	Authenticate func(r *http.Request) bool
	// ResolveUser maps a subject to a local user id for the default
	// session revocation handler. Default: email subjects are looked up by
	// address; other formats are ignored.
	ResolveUser func(ctx context.Context, sub signals.Subject) (userID ULID, ok bool, err error)
	// Handlers run after the default revocation handler.
	Handlers []signals.Handler
	// DisableDefaultRevocation turns the default handler off.
	DisableDefaultRevocation bool

	AllowPrivateNetworks bool
	AllowInsecureHTTP    bool
}

SharedSignalsReceiverConfig configures the receiver half.

type SigninStep ¶

type SigninStep = password.SigninStep

SigninStep mirrors the v0.5 step indicator returned by signinWithPassword.

type SignupMethod ¶

type SignupMethod string

SignupMethod identifies which credential path created a user. Passed to LifecycleHooks.OnSignup so consumers can branch tenant-provisioning, welcome-email, or analytics by the path the user came in on.

const (
	SignupMethodPassword  SignupMethod = "password"
	SignupMethodMagicLink SignupMethod = "magic_link"
	SignupMethodOAuth     SignupMethod = "oauth"
	SignupMethodPasskey   SignupMethod = "passkey"
	SignupMethodSAML      SignupMethod = "saml"
)

type Span ¶

type Span = observability.Span

Span is the per-operation span handle.

type StartDeviceAuthInput ¶

type StartDeviceAuthInput = apitokens.StartDeviceAuthInput

Token, device and principal types.

type Stats ¶

type Stats = models.Stats

type Status ¶

type Status = observability.Status

Status is the canonical span / metric status enum used across every instrumented operation in the library.

type StepUpInput ¶

type StepUpInput struct {
	Method    string
	Password  string
	Code      string
	Challenge string
	Assertion []byte
}

StepUpInput carries the proof for StepUp. Password uses Password, TOTP uses Code, passkey uses Challenge (from BeginStepUpPasskey) and Assertion (the browser's JSON credential response).

type Storage ¶

Storage is the full persistence contract: the embedding of every capability interface in this file. Adapters live in sub-packages (storage/memory, storage/postgres) and the storage package re-exports it as storage.Storage. It is defined here so service code can reference it without an import cycle.

type SubMapper ¶

type SubMapper struct{}

SubMapper is the built-in SubjectMapper that parses the "sub" claim directly as a ULID. Use when the external issuer's subject is the theauth user ID (e.g. for internal workload tokens).

func (SubMapper) Resolve ¶

func (SubMapper) Resolve(claims map[string]any) (ULID, error)

Resolve implements SubjectMapper by parsing claims["sub"] as a ULID.

type SubjectMapper ¶

type SubjectMapper interface {
	// Resolve returns the local user ULID for the supplied claim map, or
	// ErrStorageNotFound when no mapping exists. Any other error is
	// treated as a transient failure and returned as server_error.
	Resolve(claims map[string]any) (ULID, error)
}

SubjectMapper resolves claims from a trusted external JWT to a local user ULID. Two built-in implementations are provided:

  • SubMapper: treats the "sub" claim as a ULID directly.
  • EmailMapper: looks up the user by the "email" claim value.

Custom implementations may consult any claim in the map; the AS passes the full decoded payload.

type TOTPConfig ¶

type TOTPConfig struct {
	// Issuer is shown in the authenticator app, e.g. "GLINR Quarter".
	Issuer string
	// RecoveryCodeCount defaults to 10 when zero. Each code is 10 hex chars
	// (40 bits of entropy) generated via crypto/rand.
	RecoveryCodeCount int
}

TOTPConfig wires the second-factor TOTP behavior. Algorithm is fixed at SHA-1 / 30s / 6 digits for compatibility with Google Authenticator, Authy, 1Password, and every other mainstream authenticator app. Skew is fixed at one period before/after (the pquerna/otp default) to absorb client clock drift.

type TOTPReplayStorage ¶

type TOTPReplayStorage interface {
	// AdvanceTOTPStep atomically records step as the user's last used TOTP
	// time-step. It returns false, and changes nothing, when step is not
	// strictly greater than the stored value (a replayed or older code).
	AdvanceTOTPStep(ctx context.Context, userID ULID, step int64) (advanced bool, err error)
}

TOTPReplayStorage is an optional capability that makes TOTP replay protection durable and shared across processes. Without it the library tracks the last used step in process memory only.

type TOTPSecret ¶

type TOTPSecret = models.TOTPSecret

type TOTPStatus ¶

type TOTPStatus = totp.Status

TOTPStatus reports whether TOTP is enrolled and how many recovery codes remain (-1 when the storage cannot count them).

type TOTPStorage ¶

type TOTPStorage interface {
	// MoveTOTPSecret reassigns the TOTP secret row of secondaryID to
	// primaryID. If primaryID already has a confirmed secret the secondary
	// secret is dropped (not overwritten) to preserve the active primary
	// factor. A no-op if secondaryID has no TOTP secret.
	MoveTOTPSecret(ctx context.Context, primaryID, secondaryID ULID) error
	// UpsertPendingTOTPSecret writes an encrypted secret with
	// confirmed_at = NULL. Replaces any prior unconfirmed secret for the
	// same user; preserves a confirmed one untouched (re-enrollment
	// requires DeleteTOTPSecret first).
	UpsertPendingTOTPSecret(ctx context.Context, s TOTPSecret) error
	// ConfirmTOTPSecret sets confirmed_at on the user's pending secret.
	// Returns ErrStorageNotFound when no pending row exists.
	ConfirmTOTPSecret(ctx context.Context, userID ULID, at time.Time) error
	TOTPSecretByUserID(ctx context.Context, userID ULID) (*TOTPSecret, error)
	DeleteTOTPSecret(ctx context.Context, userID ULID) error

	InsertRecoveryCodes(ctx context.Context, codes []RecoveryCode) error
	// ConsumeRecoveryCode walks the user's unused codes, locates the one
	// whose hash matches via crypto.VerifyRecoveryCode, and marks it used
	// atomically. Returns ErrStorageNotFound when no matching unused code
	// exists (covers wrong code, reused code, and cross-user mismatch).
	ConsumeRecoveryCode(ctx context.Context, userID ULID, code string, at time.Time) error
}

TOTPStorage covers TOTP secrets and recovery codes.

type TargetRef ¶

type TargetRef = models.TargetRef

type TenancyConfig ¶

type TenancyConfig struct {
	// AutoCreatePersonalOrg controls whether a personal organization is
	// created automatically on every signup that goes through the wired
	// hook paths (password, magic-link, OAuth callback). The user is
	// added as the organization owner and the session's active
	// organization is set to it. When false (default) the library does
	// not touch organizations at signup; consumers wire their own
	// provisioning logic via LifecycleHooks.OnSignup.
	AutoCreatePersonalOrg bool

	// PersonalOrgNameFn produces the human-readable organization name.
	// Default: the user's email address.
	PersonalOrgNameFn func(*User) string

	// PersonalOrgSlugFn produces the URL-safe slug. Default: the lowercased
	// ULID of the user prefixed with "personal-" (e.g. "personal-01h...");
	// guarantees uniqueness without requiring a slug-conflict retry loop.
	PersonalOrgSlugFn func(*User) string
}

TenancyConfig (v2.5) wires opt-in tenant-provisioning behavior so consumers do not need to seed organization_members + roles + active-org SQL on every fresh signup. Only takes effect when Config.Organizations is also non-nil; otherwise auto-provisioning silently no-ops.

type TheAuth ¶

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

TheAuth is the public entry point, constructed once at app start and shared across handlers.

func New ¶

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

New validates the Config, applies defaults, and returns a ready TheAuth. Validation and service wiring are delegated to helpers in wiring.go so this function stays a short orchestrator.

func (*TheAuth) ASMetadataDoc ¶

func (a *TheAuth) ASMetadataDoc() (ASMetadata, error)

ASMetadataDoc builds the RFC 8414 metadata document. The result is deterministic across calls so handler caching is trivial. Forwards to as.ASMetadataDoc.

func (*TheAuth) AddOrganizationMember ¶

func (a *TheAuth) AddOrganizationMember(ctx context.Context, orgID, userID ULID, role string) error

AddOrganizationMember adds (or updates the role of) a user inside an organization. Roles must be one of "owner", "admin", "member".

security audit M2 (2026-06-20): when the upsert would demote the last remaining owner (role != owner on a user who is currently the sole owner), the call is rejected with ErrLastOwner. Forwards to orgsSvc.AddMember.

func (*TheAuth) Admission ¶ added in v2.10.0

func (a *TheAuth) Admission(opts AdmissionOptions) func(http.Handler) http.Handler

Admission returns net/http middleware that runs before authentication and refuses an anonymous flood cheaply. It applies tiered per-client rate limits (429 with Retry-After) and a cross-site check for cookie-authenticated unsafe methods (403). Counters live in Config.Stores.RateLimiter when set, so replicas share budgets; otherwise a per-process memory limiter is used. A store failure lets the request through. Set Config.Admission to apply it to every route Mount registers.

func (*TheAuth) ApproveBackchannelAuth ¶

func (a *TheAuth) ApproveBackchannelAuth(ctx context.Context, authReqID string, userID ULID) error

ApproveBackchannelAuth marks the pending CIBA request as approved and provisions the access + refresh tokens that the next poll will return.

userID MUST be the resolved identity of the authenticating user. When the original request supplied a login_hint that the operator resolved to this user, pass the matching ULID. If the request was already bound to a different user, ApproveBackchannelAuth returns ErrCIBAUserMismatch.

Returns ErrCIBADisabled when CIBA is not configured or the storage does not implement CIBAStorage.

func (*TheAuth) AuthenticateAPIToken ¶

func (a *TheAuth) AuthenticateAPIToken(ctx context.Context, raw string) (*Principal, error)

AuthenticateAPIToken resolves a raw bearer secret to a Principal, re-checking expiry, revocation, owner status and the owner's current abilities.

func (*TheAuth) AuthenticatePrincipal ¶

func (a *TheAuth) AuthenticatePrincipal(w http.ResponseWriter, r *http.Request) (*http.Request, *Principal, bool)

AuthenticatePrincipal resolves the request's session or API bearer token into a Principal with its current abilities, writing the 401 or 500 response itself when it cannot. The returned request carries the Principal and user in its context. Needs Config.APITokens.

func (*TheAuth) AuthenticateSCIMToken ¶

func (a *TheAuth) AuthenticateSCIMToken(ctx context.Context, presented string) (SCIMAuthResult, error)

AuthenticateSCIMToken is the entry point invoked by the SCIM bearer middleware on every request. Returns OrgID + TokenID in a single storage round-trip, or an error on failure. Touches last_used_at asynchronously on success. Forwards to scimSvc.Authenticate.

func (*TheAuth) Authn ¶

func (a *TheAuth) Authn() func(http.Handler) http.Handler

Authn looks for a session cookie, validates it, and adds the user + session to the request context. Does NOT reject anonymous requests. Pair with RequireAuth (full) or RequirePendingOrFull (TOTP verify routes only).

func (*TheAuth) BeginPasskeyLogin ¶

func (a *TheAuth) BeginPasskeyLogin(ctx context.Context) (*protocol.CredentialAssertion, string, error)

BeginPasskeyLogin starts a WebAuthn assertion ceremony. Returns a serialised PublicKeyCredentialRequestOptions and an opaque challenge token. Forwards to webauthnSvc.BeginLogin.

func (*TheAuth) BeginPasskeyRegistration ¶

func (a *TheAuth) BeginPasskeyRegistration(ctx context.Context, userID ULID) (*protocol.CredentialCreation, string, error)

BeginPasskeyRegistration starts a WebAuthn credential creation ceremony: returns a serialised PublicKeyCredentialCreationOptions plus an opaque challenge token the caller stores in a short-lived cookie. Forwards to webauthnSvc.BeginRegistration.

func (*TheAuth) BeginSAMLLogin ¶

func (a *TheAuth) BeginSAMLLogin(ctx context.Context, connectionID ULID, relayState string) (string, error)

BeginSAMLLogin returns the redirect URL for an SP-initiated SSO.

func (*TheAuth) BeginTOTPEnrollment ¶

func (a *TheAuth) BeginTOTPEnrollment(ctx context.Context, userID ULID, accountName string) (EnrollTOTPResult, error)

BeginTOTPEnrollment generates a fresh shared secret and otpauth URL, returns them to the caller (the secret is displayed exactly once), and stashes the plaintext in the in-memory pending map. Forwards to totpSvc.BeginEnrollment.

func (*TheAuth) ChangePassword ¶

func (a *TheAuth) ChangePassword(ctx context.Context, cur Session, currentPassword, newPassword string) (string, error)

ChangePassword verifies the current password, sets the new one, revokes all of the user's sessions and returns a fresh session token for the caller.

func (*TheAuth) ClientCredentialsToken ¶

func (a *TheAuth) ClientCredentialsToken(ctx context.Context, req TokenRequest) (TokenResponse, error)

ClientCredentialsToken mints a self-token for the authenticated agent client. The token's sub is "agent:<id>"; aud is bound to the resource parameter (RFC 8707); scope is intersected with both the agent's registered scope set and the resource catalog. Suspended / revoked agents fail with ErrAgentInactive (mapped to access_denied at the wire).

Audit emission: agent.token_minted on success. Forwards to as.ClientCredentialsToken.

func (*TheAuth) Close ¶

func (a *TheAuth) Close()

Close releases background resources started by New: the OAuth state GC loop (v0.3), the WebAuthn challenge / TOTP enrollment GC loops (v0.5), the SAML AuthnRequest GC loop (v0.7), and the audit writer goroutine (v1.0). Audit drain waits up to Config.Audit.DrainTimeout (default 5 seconds) for the writer to flush. Safe to call multiple times.

func (*TheAuth) ConsumeRecoveryCode ¶

func (a *TheAuth) ConsumeRecoveryCode(ctx context.Context, pendingSessionToken, code string) (string, Session, error)

ConsumeRecoveryCode upgrades a pending session by consuming one unused recovery code. Forwards to totpSvc.ConsumeRecoveryCode, then fires OnSignin like VerifyTOTP.

func (a *TheAuth) ConsumeSessionLink(ctx context.Context, token, userAgent, ip string) (string, Session, error)

ConsumeSessionLink exchanges a link token for a session token. Every failure mode returns ErrSessionLinkInvalid.

func (*TheAuth) CreateAgent ¶

func (a *TheAuth) CreateAgent(ctx context.Context, in CreateAgentInput) (Agent, AgentSecret, error)

CreateAgent persists a fresh agent owned by the supplied user or organization, mints a backing OAuthClient + client secret, records the secret on an agent_credentials row, and returns both the Agent record and the one-shot AgentSecret.

func (*TheAuth) CreateDeviceJoinToken ¶ added in v2.10.0

func (a *TheAuth) CreateDeviceJoinToken(ctx context.Context, in CreateDeviceJoinTokenInput) (DeviceJoinToken, string, error)

CreateDeviceJoinToken mints a single-use join token for enrolling one constrained device and returns the stored record plus the plaintext, shown once. The token fixes the name, SPIFFE ID and scopes the device receives. Requires AuthorizationServer.DeviceTokens.

func (*TheAuth) CreateOrganization ¶

func (a *TheAuth) CreateOrganization(ctx context.Context, name, slug string, ownerUserID ULID) (Organization, error)

CreateOrganization writes a new org row and adds the supplied user as its owner. Slug is lowercased and validated against the slug rules in the internal package; the storage layer enforces uniqueness. Forwards to orgsSvc.Create, mapping organizations.ErrOrganizationsDisabled to the legacy root error string.

func (*TheAuth) CreateRegistrationToken ¶ added in v2.8.0

func (a *TheAuth) CreateRegistrationToken(ctx context.Context, in CreateRegistrationTokenInput) (RegistrationToken, string, error)

CreateRegistrationToken mints a one-time (or limited-use), scoped, expiring initial access token for POST /oauth/register and returns the stored record plus the plaintext token. The plaintext is shown once and never stored; the record keeps only a SHA-256 digest. Requires Config.AuthorizationServer and a storage that implements RegistrationTokenStorage.

func (*TheAuth) CreateRole ¶

func (a *TheAuth) CreateRole(ctx context.Context, orgID ULID, name, description string, perms []string) (Role, error)

CreateRole adds a new role to orgID with the listed permissions. Names are unique per org; returns the storage error (typically a unique-violation translation) on collision. Emits "role.created". Forwards to rbacSvc.CreateRole.

func (*TheAuth) CreateSAMLConnection ¶

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

CreateSAMLConnection inserts a fresh saml_connections row.

func (*TheAuth) CreateSCIMToken ¶

func (a *TheAuth) CreateSCIMToken(ctx context.Context, orgID ULID, name string) (string, SCIMToken, error)

CreateSCIMToken mints a fresh 256-bit token, stores its sha256 hash, and returns the plaintext to the caller. The plaintext is the only point at which it leaves the library; subsequent reads only ever see the hash. Forwards to scimSvc.CreateToken, mapping internalscim.ErrSCIMDisabled to the legacy root error string.

func (*TheAuth) DCRRegister ¶

DCRRegister is a convenience wrapper around RegisterClient that registers a new OAuth client with AllowAnonymousRegistration semantics. The returned RegisteredClient carries ClientID and ClientSecret. This is the same operation as POST /oauth/register but callable from Go code directly.

func (*TheAuth) DecideDeviceRequest ¶

func (a *TheAuth) DecideDeviceRequest(ctx context.Context, approver *User, ip, userCode string, approve bool, abilities []string) error

DecideDeviceRequest approves or denies a pending request as approver. On approval the abilities are the requested set (or the narrower subset in abilities) capped to what the approver holds now. Root is granted only when requested and the approver holds root; it is never downgraded silently.

func (*TheAuth) DecideDeviceRequestByID ¶

func (a *TheAuth) DecideDeviceRequestByID(ctx context.Context, approver *User, id ULID, approve bool, abilities []string) error

DecideDeviceRequestByID approves or denies a pending request by its ID with the same rules as DecideDeviceRequest. An unknown, expired or already decided ID returns ErrDeviceInvalid or ErrDeviceExpired.

func (*TheAuth) DelegatedAbilities ¶

func (a *TheAuth) DelegatedAbilities(ctx context.Context, userID ULID, agentScopes []string) ([]string, error)

DelegatedAbilities returns the intersection of an agent's allowed scopes and what the user holds right now, for resource servers that authenticate agents by another path (for example an OAuth access token) and want the same per-request cut as agent API tokens. Needs Config.APITokens.

func (*TheAuth) DeleteRole ¶

func (a *TheAuth) DeleteRole(ctx context.Context, roleID ULID) error

DeleteRole removes a role. Returns ErrRoleInUse when the role is the sole grantor of users:admin in its organization (lockout protection). Emits "role.deleted". Forwards to rbacSvc.DeleteRole.

func (*TheAuth) DeleteSAMLConnection ¶

func (a *TheAuth) DeleteSAMLConnection(ctx context.Context, id ULID) error

DeleteSAMLConnection removes the connection + cascades its identities.

func (*TheAuth) DeleteUser ¶ added in v2.10.0

func (a *TheAuth) DeleteUser(ctx context.Context, userID ULID) error

DeleteUser permanently deletes userID and everything that belongs to them: sessions, tokens, linked identities, passkeys, TOTP, API tokens, trusted devices, organization memberships and role grants. Audit rows are kept with the actor cleared. It refuses with ErrLastOwner when the user is the only owner of an organization. It fires LifecycleHooks.OnAccountDeleted after the delete committed. It needs a storage implementing AccountDeleteStorage.

func (*TheAuth) DenyBackchannelAuth ¶

func (a *TheAuth) DenyBackchannelAuth(ctx context.Context, authReqID string, userID ULID) error

DenyBackchannelAuth marks the pending CIBA request as denied. The next client poll returns access_denied.

Returns ErrCIBADisabled when CIBA is not configured.

func (*TheAuth) DisableUser ¶ added in v2.10.0

func (a *TheAuth) DisableUser(ctx context.Context, userID ULID) error

DisableUser blocks sign-in for userID and revokes their sessions and API tokens. It needs Config.AccountState. EnableUser reverses the block but not the revocations.

func (*TheAuth) Doctor ¶

func (a *TheAuth) Doctor(ctx context.Context) Report

Doctor inspects the live Config and storage and reports security-posture findings, most serious first. It never mutates state and never includes secrets in the report.

func (*TheAuth) EmitAudit ¶

func (a *TheAuth) EmitAudit(ctx context.Context, action string, target TargetRef, metadata map[string]any)

EmitAudit enqueues an audit event for asynchronous batched write. Non- blocking: when the writer channel is full the event is dropped and Stats.AuditDropped increments by 1.

EmitAudit may be called from any goroutine. The metadata map is mutated in place by the redactor; callers must not retain references after the call (or, equivalently, must defensively copy before passing in).

When Config.Audit is nil EmitAudit is a silent no-op. When Close has been called EmitAudit is also a silent no-op. Forwards to auditSvc.Emit.

func (*TheAuth) EnableUser ¶ added in v2.10.0

func (a *TheAuth) EnableUser(ctx context.Context, userID ULID) error

EnableUser lifts a DisableUser block. It needs Config.AccountState.

func (*TheAuth) ExchangeAuthorizationCode ¶

func (a *TheAuth) ExchangeAuthorizationCode(ctx context.Context, req TokenRequest) (TokenResponse, error)

ExchangeAuthorizationCode redeems a one-time authorization code for an access token + refresh token pair. Enforces PKCE S256, redirect_uri equality, audience binding (RFC 8707), and client authentication. Forwards to as.ExchangeAuthorizationCode.

func (*TheAuth) ExchangeToken ¶

func (a *TheAuth) ExchangeToken(ctx context.Context, req TokenExchangeRequest) (TokenResponse, error)

ExchangeToken implements RFC 8693 token exchange. Forwards to as.ExchangeToken.

func (*TheAuth) FinishPasskeyLogin ¶

func (a *TheAuth) FinishPasskeyLogin(ctx context.Context, challengeToken string, body io.Reader, ua, ip string) (string, Session, error)

FinishPasskeyLogin validates the navigator.credentials.get response, looks up the credential by ID, advances the stored sign counter, and issues a session. Forwards to webauthnSvc.FinishLogin, then fires OnSignin for the session just issued. A passkey login is a single strong factor, so there is no pending intermediate to skip.

func (*TheAuth) FinishPasskeyRegistration ¶

func (a *TheAuth) FinishPasskeyRegistration(ctx context.Context, userID ULID, challengeToken, name string, body io.Reader) (WebAuthnCredential, error)

FinishPasskeyRegistration validates the navigator.credentials.create response, stores the resulting credential, and returns the stored row. Forwards to webauthnSvc.FinishRegistration. Fires OnSignup with SignupMethodPasskey when this was the user's first-ever credential: WebAuthn registration always requires an already-authenticated user, so there is no true account-creation moment the way password/magic-link/ OAuth signup have one; the first passkey is the closest equivalent.

func (*TheAuth) FinishSAMLLogin ¶

func (a *TheAuth) FinishSAMLLogin(ctx context.Context, connectionID ULID, samlResponseB64 string, ua, ip string) (string, Session, error)

FinishSAMLLogin validates an inbound SAMLResponse, runs find-or-create, issues a session, and returns its token. Fires OnSignup with SignupMethodSAML when the user row was created during this call, then OnSignin for the session just issued.

func (*TheAuth) FinishTOTPEnrollment ¶

func (a *TheAuth) FinishTOTPEnrollment(ctx context.Context, userID ULID, enrollmentID, code string) ([]string, error)

FinishTOTPEnrollment validates one code against the pending secret, confirms the row, generates recovery codes, and returns them to the caller. Forwards to totpSvc.FinishEnrollment, then fires OnMFAEnabled on success.

func (*TheAuth) GetAgent ¶

func (a *TheAuth) GetAgent(ctx context.Context, agentID ULID) (*Agent, error)

GetAgent returns the agent record by ID.

func (*TheAuth) GetProviderToken ¶ added in v2.10.0

func (a *TheAuth) GetProviderToken(ctx context.Context, userID ULID, provider string) (ProviderToken, error)

GetProviderToken returns a usable upstream access token for the user's linked provider account, for calling the provider's API on the user's behalf. The stored AES-GCM encrypted token is decrypted and returned when still valid; an expired one is refreshed with the stored refresh token, the rotated tokens are persisted, and concurrent calls for the same user and provider share one upstream refresh.

Errors can be matched with errors.Is against ErrProviderNotLinked, ErrProviderRefreshUnsupported (provider cannot refresh, or no refresh token was granted) and ErrProviderGrantRevoked (the user revoked access; they must sign in with the provider again), or by TheAuthError code CodeProviderNoRefresh and CodeProviderGrantRevoked. It needs at least one configured provider and Config.EncryptionKey.

func (*TheAuth) GrantDelegation ¶

func (a *TheAuth) GrantDelegation(ctx context.Context, in GrantDelegationInput) (DelegationGrant, error)

GrantDelegation persists a delegation_grants row. Scope MUST be a subset of the configured ProtectedResource scopes; resource MUST match a known ProtectedResource identifier; max_duration_seconds MUST be > 0 and <= AgentConfig.MaxDelegationDuration. Forwards to delegationSvc.GrantDelegation.

func (*TheAuth) GrantRole ¶

func (a *TheAuth) GrantRole(ctx context.Context, actor, target, roleID ULID) error

GrantRole assigns roleID to the target user. The actor must already have permission to grant; callers should run the RequirePermission middleware upstream of this method. Idempotent on (user_id, role_id). Emits action "role.granted" with role_id and role_name in metadata. Forwards to rbacSvc.GrantRole.

func (*TheAuth) Handler ¶

func (a *TheAuth) Handler() http.Handler

Handler returns a stdlib http.Handler serving every route Mount would register, for consumers on net/http's ServeMux without chi. Routes keep their configured paths (Config.PathPrefix, default /auth/..., and /oauth/...), so no http.StripPrefix is needed when the prefix matches the mount point.

func (*TheAuth) HasPermission ¶

func (a *TheAuth) HasPermission(ctx context.Context, userID ULID, orgID *ULID, perm string) (bool, error)

HasPermission returns true when the user holds the named permission in the given organization, OR when the user holds the system super_admin role (which bypasses every check). orgID may be nil to ask only about system permissions. Forwards to rbacSvc.HasPermission.

func (*TheAuth) ImportAPIToken ¶

func (a *TheAuth) ImportAPIToken(ctx context.Context, in ImportedToken) (APIToken, error)

ImportAPIToken inserts an existing token by its SHA-256 hash. The hash must cover the full raw secret as presented by clients; tokens lacking the configured prefix authenticate only when Config.APITokens.AcceptUnprefixed is set.

func (*TheAuth) ImportTOTPSecret ¶

func (a *TheAuth) ImportTOTPSecret(ctx context.Context, in ImportedTOTP) error

ImportTOTPSecret encrypts a plaintext secret with Config.EncryptionKey and stores it as confirmed; see ImportTOTPSecretTo.

func (*TheAuth) ImportUser ¶

func (a *TheAuth) ImportUser(ctx context.Context, in ImportedUser) (User, error)

ImportUser inserts an existing user through the configured storage; see ImportUserTo.

func (*TheAuth) ImportWebAuthnCredential ¶

func (a *TheAuth) ImportWebAuthnCredential(ctx context.Context, in ImportedWebAuthnCredential) (WebAuthnCredential, error)

ImportWebAuthnCredential inserts an existing credential through the configured storage; see ImportWebAuthnCredentialTo.

func (*TheAuth) IntrospectToken ¶

func (a *TheAuth) IntrospectToken(ctx context.Context, token, clientID, clientSecret, expectedAud string) (IntrospectionResponse, []byte, error)

IntrospectToken validates the supplied token and returns the structured introspection response. Token type detection: JWTs are recognised by the three dot-separated base64 segments; everything else is treated as a refresh token (looked up by hash).

Audience binding: when expectedAud is non-empty (resource server passes its own identifier), tokens with a mismatching aud return active=false. Forwards to as.IntrospectToken.

func (*TheAuth) InvalidateProvider ¶

func (a *TheAuth) InvalidateProvider(name string)

InvalidateProvider drops the cached ProviderResolver answer for name so a provider edited or removed at runtime takes effect on the next request.

func (*TheAuth) IssuePending2FA ¶

func (a *TheAuth) IssuePending2FA(ctx context.Context, userID ULID, ua, ip string) (string, Session, error)

IssuePending2FA mints a short-lived session whose AuthLevel is AuthLevelPending2FA. Forwards to totpSvc.IssuePending2FA.

func (*TheAuth) IssueSessionByUserID ¶

func (a *TheAuth) IssueSessionByUserID(ctx context.Context, userID ULID, userAgent, ip string) (string, error)

IssueSessionByUserID mints a full session for the given user without requiring an existing session token. Used by the account-linking flow after OTP verification to sign the user in to their existing account.

func (*TheAuth) JWTBearerGrant ¶

func (a *TheAuth) JWTBearerGrant(ctx context.Context, req TokenRequest, assertion string) (TokenResponse, error)

JWTBearerGrant implements RFC 7523 section 2.1: an externally-issued JWT is exchanged for an AS-issued access token. The assertion parameter must be the compact serialized JWT from a configured TrustedJWTIssuer.

Requires Config.AuthorizationServer.JWTBearer to be non-nil; returns ErrOAuthUnsupportedGrantType when not configured.

func (*TheAuth) LinkOAuthProviderBySession ¶

func (a *TheAuth) LinkOAuthProviderBySession(
	ctx context.Context,
	sessionToken, providerName, providerUserID string,
	accessTokenEnc, refreshTokenEnc []byte,
	expiresAt *time.Time,
	scope string,
) error

LinkOAuthProviderBySession links an OAuth provider account to the user identified by sessionToken. Intended for the post-OTP account-linking flow where the session was just issued by IssueSessionByUserID.

func (*TheAuth) ListAPITokens ¶

func (a *TheAuth) ListAPITokens(ctx context.Context, ownerID ULID) ([]APIToken, error)

ListAPITokens returns the owner's tokens, newest first.

func (*TheAuth) ListAgentsByOwner ¶

func (a *TheAuth) ListAgentsByOwner(ctx context.Context, owner AgentOwner) ([]Agent, error)

ListAgentsByOwner returns every agent the supplied owner has created.

func (*TheAuth) ListAllAPITokens ¶

func (a *TheAuth) ListAllAPITokens(ctx context.Context) ([]APIToken, error)

ListAllAPITokens returns every token. Intended for admin tooling.

func (*TheAuth) ListDelegationsForAgent ¶

func (a *TheAuth) ListDelegationsForAgent(ctx context.Context, agentID ULID) ([]DelegationGrant, error)

ListDelegationsForAgent returns every grant naming the supplied agent. Forwards to delegationSvc.ListDelegationsForAgent.

func (*TheAuth) ListDelegationsForUser ¶

func (a *TheAuth) ListDelegationsForUser(ctx context.Context, userID ULID) ([]DelegationGrant, error)

ListDelegationsForUser returns every grant the user has issued, including revoked ones (for audit / display). Forwards to delegationSvc.ListDelegationsForUser.

func (*TheAuth) ListDeviceRequests ¶

func (a *TheAuth) ListDeviceRequests(ctx context.Context) ([]DeviceRequestSummary, error)

ListDeviceRequests returns the pending, unexpired device requests, newest first, without any device or user code.

func (*TheAuth) ListDevices ¶ added in v2.10.0

func (a *TheAuth) ListDevices(ctx context.Context, orgID *ULID) ([]Device, error)

ListDevices lists registered devices, newest first. A nil orgID lists all.

func (*TheAuth) ListOrganizationMembers ¶

func (a *TheAuth) ListOrganizationMembers(ctx context.Context, orgID ULID) ([]OrganizationMember, error)

ListOrganizationMembers returns every member of the supplied organization. Forwards to orgsSvc.ListMembers.

func (*TheAuth) ListProviders ¶

func (a *TheAuth) ListProviders(ctx context.Context) ([]Provider, error)

ListProviders returns the static providers plus those a ProviderResolver that implements ProviderLister reports.

func (*TheAuth) ListRegistrationTokens ¶ added in v2.8.0

func (a *TheAuth) ListRegistrationTokens(ctx context.Context, orgID *ULID) ([]RegistrationToken, error)

ListRegistrationTokens lists registration tokens, newest first. A nil orgID lists every token. Hashes are included on the model; do not expose them.

func (*TheAuth) ListSAMLConnections ¶

func (a *TheAuth) ListSAMLConnections(ctx context.Context, orgID ULID) ([]SAMLConnection, error)

ListSAMLConnections returns every connection for one organization.

func (*TheAuth) ListSCIMTokens ¶

func (a *TheAuth) ListSCIMTokens(ctx context.Context, orgID ULID) ([]SCIMToken, error)

ListSCIMTokens returns every token (revoked or not) for the supplied org. Forwards to scimSvc.ListTokens.

func (*TheAuth) ListSessions ¶

func (a *TheAuth) ListSessions(ctx context.Context, userID, currentID ULID) ([]SessionInfo, error)

ListSessions returns the user's live sessions, marking currentID, newest first. Pending-2FA sessions and idle-expired sessions are omitted.

func (*TheAuth) ListTrustedDevices ¶ added in v2.10.0

func (a *TheAuth) ListTrustedDevices(ctx context.Context, userID ULID) ([]TrustedDeviceInfo, error)

ListTrustedDevices returns the user's live trusted devices, newest first.

func (*TheAuth) ListUserOrganizations ¶

func (a *TheAuth) ListUserOrganizations(ctx context.Context, userID ULID) ([]Organization, error)

ListUserOrganizations returns every organization the user is a member of. Forwards to orgsSvc.ListUserOrganizations.

func (*TheAuth) LookupDeviceRequest ¶

func (a *TheAuth) LookupDeviceRequest(ctx context.Context, approver *User, ip, userCode string) (*DeviceRequestInfo, error)

LookupDeviceRequest returns the pending request behind a user code so the approver can review it. Failed lookups count against a per-approver budget (ErrDeviceAttemptsExceeded once spent).

func (*TheAuth) MintAPIToken ¶

func (a *TheAuth) MintAPIToken(ctx context.Context, in MintAPITokenInput) (string, APIToken, error)

MintAPIToken creates a token and returns the secret, which is never retrievable again.

func (*TheAuth) MintAgentCredential ¶

func (a *TheAuth) MintAgentCredential(ctx context.Context, agentID ULID, kind string) (AgentSecret, error)

MintAgentCredential mints a fresh credential of the requested kind on an existing agent. Only kind = AgentCredentialKindSecret is implemented in phase 3; X.509 and JWK kinds return ErrNotImplemented.

func (*TheAuth) MintAgentToken ¶

func (a *TheAuth) MintAgentToken(ctx context.Context, in MintAgentTokenInput) (string, APIToken, error)

MintAgentToken mints an API token with kind=agent acting for UserID. It returns ErrAbilityNotHeld when Abilities exceeds what the user holds now. Needs Config.APITokens.

func (a *TheAuth) MintSessionLink(ctx context.Context, in MintSessionLinkInput) (string, SessionLink, error)

MintSessionLink mints a single-use token that ConsumeSessionLink exchanges for a session for in.UserID. The raw token is returned once; only its hash is stored. The caller authorizes the mint.

func (*TheAuth) Mount ¶

func (a *TheAuth) Mount(r chi.Router)

Mount wires TheAuth's HTTP routes onto the supplied chi router under /auth.

POST /auth/magic-link - request a magic link GET /auth/magic-link/verify - consume a magic link, set session cookie POST /auth/email-password/signup - create user with email + password (rate-limited) POST /auth/email-password/signin - sign in with email + password (rate-limited) POST /auth/email-password/forgot - request a password reset link (rate-limited) POST /auth/email-password/reset - consume a reset token + set new password (rate-limited) GET /auth/me - return the authenticated user (RequireAuth) DELETE /auth/sessions/current - revoke the current session (RequireAuth) GET /auth/sessions - list the caller's sessions (SessionManagementStorage) DELETE /auth/sessions/{id} - revoke one of the caller's sessions POST /auth/sessions/revoke-others - revoke every session but the current one POST /auth/step-up - elevate the session (password, totp or passkey) POST /auth/password/change - change password, rotate the session POST /auth/session-link/consume - exchange a session link (Config.SessionLinks)

Default rate limits: 5/min per source IP on every credential endpoint, plus 3/min per email on signin + forgot. All limits are in-memory unless Config.Stores.RateLimiter supplies a shared one.

func (*TheAuth) NormalizeEmail ¶

func (a *TheAuth) NormalizeEmail(raw string) string

NormalizeEmail returns the canonical form this instance uses for every email lookup: trimmed, lowercased, and NFKC-folded when Config.EmailNFKC is set.

func (*TheAuth) NotifyOwnerDisabled ¶

func (a *TheAuth) NotifyOwnerDisabled(ctx context.Context, userID ULID, reason string) error

NotifyOwnerDisabled tells watchers that a user was disabled or deleted. The library cannot see host-side disable flags, so the host calls this when it flips them (the same flag Config.APITokens.OwnerActive reads).

func (*TheAuth) OAuthCallback ¶ added in v2.7.0

func (a *TheAuth) OAuthCallback(r *http.Request, provider, code, state, binding string) (OAuthCallbackResult, *User, error)

OAuthCallback completes the login flow for an app that hosts its own callback route, using the user agent and client IP of r. It fires the same hooks as the built-in callback; the caller sets the session cookie from the returned SessionToken and clears the binding cookie.

func (*TheAuth) OAuthStart ¶ added in v2.7.0

func (a *TheAuth) OAuthStart(r *http.Request, provider, returnTo string) (OAuthStartResult, error)

OAuthStart begins the login flow for the named provider and returns the authorization URL. It lets an app host its own start route; r feeds OAuthConfig.RedirectURI. The caller must store Binding in a cookie.

func (*TheAuth) OIDCLogout ¶ added in v2.10.0

func (a *TheAuth) OIDCLogout(ctx context.Context, userID, sessionID ULID) error

OIDCLogout sends back-channel logout tokens to every OpenID client that took part in sessionID, for logouts that do not go through end_session (admin revocation, account deletion). It does not revoke the session. Deliveries run in the background; failures are logged. Requires AuthorizationServer.OIDC.

func (*TheAuth) ObservabilityHooks ¶

func (a *TheAuth) ObservabilityHooks() *Hooks

Hooks returns the observability bundle in use. Returns a non-nil pointer even when no Observability was configured (the no-op bundle). Exposed so consumers writing custom services on top of theauth-go can share the same Tracer / Metrics adapters without re-wiring.

func (*TheAuth) OrganizationByID ¶

func (a *TheAuth) OrganizationByID(ctx context.Context, id ULID) (*Organization, error)

OrganizationByID looks up an organization by ULID. Forwards to orgsSvc.ByID.

func (*TheAuth) OrganizationBySlug ¶

func (a *TheAuth) OrganizationBySlug(ctx context.Context, slug string) (*Organization, error)

OrganizationBySlug looks up an organization by URL-safe slug. Forwards to orgsSvc.BySlug.

func (*TheAuth) PasskeyAuthenticatorName ¶ added in v2.8.0

func (a *TheAuth) PasskeyAuthenticatorName(aaguid []byte) string

PasskeyAuthenticatorName returns the display name configured through WebAuthnConfig.AuthenticatorName or AuthenticatorNames for a credential's AAGUID, or "" when none is known or WebAuthn is not configured.

func (*TheAuth) PermissionsForUser ¶

func (a *TheAuth) PermissionsForUser(ctx context.Context, userID ULID, orgID *ULID) ([]string, error)

PermissionsForUser returns the user's permission set scoped to orgID (nil orgID returns only system-role permissions, i.e. super_admin). Sorted alphabetically for deterministic output. Forwards to rbacSvc.PermissionsForUser.

func (*TheAuth) ProtectedResourceMetadataDoc ¶

func (a *TheAuth) ProtectedResourceMetadataDoc(resourceID string) (ProtectedResourceMetadata, error)

ProtectedResourceMetadataDoc builds the RFC 9728 document for the resource matching the supplied identifier. Returns an error when the identifier is not one of the configured resources. Forwards to as.ProtectedResourceMetadataDoc.

func (*TheAuth) PublishRevocation ¶

func (a *TheAuth) PublishRevocation(ctx context.Context, ev RevocationEvent) error

PublishRevocation sends ev on the revocation bus, stamping At when zero.

func (*TheAuth) PurgeExpiredDeviceCodes ¶

func (a *TheAuth) PurgeExpiredDeviceCodes(ctx context.Context, before time.Time) (int, error)

PurgeExpiredDeviceCodes deletes requests that expired before the cutoff.

func (*TheAuth) QueryAudit ¶

func (a *TheAuth) QueryAudit(ctx context.Context, q AuditQuery) ([]AuditEvent, string, error)

QueryAudit returns up to q.Limit events plus an opaque cursor for the next page. Caller is responsible for permission-checking; this method does no auth. Forwards to auditSvc.Query (or to storage.QueryAuditEvents when Config.Audit is nil).

func (*TheAuth) RateLimitByEmail ¶

func (a *TheAuth) RateLimitByEmail(perMinute int) func(http.Handler) http.Handler

RateLimitByEmail returns a middleware that limits requests per email body field. Reads the JSON body up to 16 KiB, extracts "email", restores the body so downstream handlers can re-read it. Requests without a parseable email are passed through unlimited (handler will reject them on its own).

func (*TheAuth) RateLimitByIP ¶

func (a *TheAuth) RateLimitByIP(perMinute int) func(http.Handler) http.Handler

RateLimitByIP returns a middleware that limits requests per source IP to perMinute per minute. Use on credential endpoints (signin, signup, forgot, reset). The limiter lives on the returned handler. Multiple calls produce independent buckets, so wire it once per route group at startup.

X-Forwarded-For is honored only when r.RemoteAddr is inside one of the Config.TrustedProxies prefixes. Deployments behind a reverse proxy MUST opt in by listing the proxy network in TrustedProxies; the default is the empty allowlist (no XFF trust), which is the safe behavior on a direct public-internet bind (security audit H4, 2026-06-20).

func (*TheAuth) RecordTokenMinted ¶

func (a *TheAuth) RecordTokenMinted(ctx context.Context, userID ULID, kind string)

RecordTokenMinted is the hook point for token issuers (API tokens, device codes, service tokens) to report a mint. kind is a short label such as "api" or "device"; it must not contain the token itself.

func (*TheAuth) RecordTokenRevoked ¶

func (a *TheAuth) RecordTokenRevoked(ctx context.Context, userID ULID, kind string)

RecordTokenRevoked is the revoke counterpart of RecordTokenMinted.

func (*TheAuth) RedeemDeviceCode ¶

func (a *TheAuth) RedeemDeviceCode(ctx context.Context, deviceCode string) (DeviceToken, error)

RedeemDeviceCode exchanges an approved device code for a token. The approved to redeemed transition is one atomic claim, so concurrent polls mint at most one token. Polling faster than the interval returns ErrDeviceSlowDown and widens the interval.

func (*TheAuth) RefreshAccessToken ¶

func (a *TheAuth) RefreshAccessToken(ctx context.Context, req TokenRequest) (TokenResponse, error)

RefreshAccessToken rotates a refresh token, returning a new access token + refresh token pair. The old refresh token is revoked; presenting it again triggers family-wide revocation per RFC 9700 section 4.14. Forwards to as.RefreshAccessToken.

func (*TheAuth) RegenerateRecoveryCodes ¶

func (a *TheAuth) RegenerateRecoveryCodes(ctx context.Context, userID ULID) ([]string, error)

RegenerateRecoveryCodes replaces the user's recovery codes and returns the new plaintext codes once. The user must have TOTP enrolled.

func (*TheAuth) RegisterAgent ¶

func (a *TheAuth) RegisterAgent(ctx context.Context, in RegisterAgentInput) (AgentRegistration, error)

RegisterAgent creates an agent owned by a user and, when Resource is set, the delegation grant that lets it exchange tokens for that user. Needs Config.AgentIdentity and Config.AuthorizationServer.

func (*TheAuth) RegisterClient ¶

func (a *TheAuth) RegisterClient(ctx context.Context, req ClientRegistrationRequest, anonymous bool) (RegisteredClient, error)

RegisterClient validates the request, mints a client_id (and a secret for confidential clients), persists the OAuthClient row, and returns the RFC 7591 response body. The plaintext secret is in the return value; callers must surface it to the caller exactly once and never log it. Forwards to as.RegisterClient.

func (*TheAuth) RemoveOrganizationMember ¶

func (a *TheAuth) RemoveOrganizationMember(ctx context.Context, orgID, userID ULID) error

RemoveOrganizationMember removes a user from an organization. Refuses to remove the last remaining owner (returns ErrLastOwner). Forwards to orgsSvc.RemoveMember.

func (*TheAuth) RenamePasskey ¶

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

RenamePasskey changes the display name of one of the user's passkeys.

func (*TheAuth) RequireAbility ¶

func (a *TheAuth) RequireAbility(ability string) func(http.Handler) http.Handler

RequireAbility accepts either a full session or an API bearer token and rejects callers that do not currently hold ability. A presented bearer token never falls back to the cookie. Needs Config.APITokens.

func (*TheAuth) RequireAuth ¶

func (a *TheAuth) RequireAuth() func(http.Handler) http.Handler

RequireAuth runs Authn, then rejects requests that don't have a FULL session. Pending_2fa sessions are treated as unauthorized here. The two TOTP verify routes opt in to RequirePendingOrFull instead.

Errors are emitted as RFC 7807 problem+json with a WWW-Authenticate header per RFC 7235. Two failure codes are surfaced:

  • auth.unauthenticated when no session cookie was presented or it failed validation (cookie missing, expired, revoked, or storage rejected).
  • auth.step_up_required when a pending_2fa session is present and the caller must complete the second factor before proceeding.

Frontends can distinguish the step-up case from a fresh login without special-casing string bodies.

func (*TheAuth) RequirePendingOrFull ¶

func (a *TheAuth) RequirePendingOrFull() func(http.Handler) http.Handler

RequirePendingOrFull (v0.5) accepts both pending_2fa and full sessions. Used exclusively by /auth/totp/verify and /auth/totp/recovery so a user mid-step-up can complete the second factor.

func (*TheAuth) RequirePermission ¶

func (a *TheAuth) RequirePermission(perms ...string) func(http.Handler) http.Handler

RequirePermission (v1.0) returns a middleware that enforces the caller holds every named permission inside session.active_organization_id. A session without active_organization_id is 403 rbac.no_active_org. A user with the system super_admin role bypasses the check entirely. The permission lookup hits storage once per request; subsequent middleware in the same chain hit the per-request cache attached to ctx.

When Config.RBAC is nil the middleware short-circuits to 500: an admin trying to wire RequirePermission without enabling RBAC is a programming error worth surfacing loudly.

func (*TheAuth) RequireRecentAuth ¶

func (a *TheAuth) RequireRecentAuth(maxAge time.Duration) func(http.Handler) http.Handler

RequireRecentAuth rejects with 403 auth.recent_auth_required unless the session logged in or stepped up within maxAge. It implies RequireAuth.

func (*TheAuth) ResetPasswordAdmin ¶

func (a *TheAuth) ResetPasswordAdmin(ctx context.Context, emailAddr, newPassword string, opts ...ResetPasswordOption) error

ResetPasswordAdmin sets a new password for the user with the given email without a reset token, revokes their sessions and clears login and MFA lockouts. It enforces the configured password policy and is meant for a recover-admin command run by someone with host access. Pass RequirePasswordChange to force the user to choose their own password.

func (*TheAuth) ResumeAgent ¶

func (a *TheAuth) ResumeAgent(ctx context.Context, agentID ULID) error

ResumeAgent flips status back to active. Only valid on a suspended agent; resuming a revoked agent returns ErrAgentInactive.

func (*TheAuth) RevokeAPIToken ¶

func (a *TheAuth) RevokeAPIToken(ctx context.Context, id ULID) error

RevokeAPIToken revokes one token by ID without an ownership check.

func (*TheAuth) RevokeAgent ¶

func (a *TheAuth) RevokeAgent(ctx context.Context, agentID ULID, reason string) error

RevokeAgent flips status to revoked. Terminal: a revoked agent cannot be resumed (operators create a fresh agent instead).

func (*TheAuth) RevokeDelegation ¶

func (a *TheAuth) RevokeDelegation(ctx context.Context, grantID ULID, reason string) error

RevokeDelegation marks a grant revoked. Cascade: every token already minted under this grant becomes invalid on the next resource server introspection refresh (worst case IntrospectionCacheTTL, default 60s). Forwards to delegationSvc.RevokeDelegation.

func (*TheAuth) RevokeDevice ¶ added in v2.10.0

func (a *TheAuth) RevokeDevice(ctx context.Context, id ULID) error

RevokeDevice revokes a device. Its assertions are refused from then on and introspection reports its tokens inactive. Revoking twice succeeds.

func (*TheAuth) RevokeDeviceJoinToken ¶ added in v2.10.0

func (a *TheAuth) RevokeDeviceJoinToken(ctx context.Context, id ULID) error

RevokeDeviceJoinToken revokes an unspent device join token.

func (*TheAuth) RevokeOtherSessions ¶

func (a *TheAuth) RevokeOtherSessions(ctx context.Context, userID, keep ULID) (int, error)

RevokeOtherSessions revokes every live session of userID except keep and returns how many it revoked.

func (*TheAuth) RevokeOwnedSession ¶

func (a *TheAuth) RevokeOwnedSession(ctx context.Context, userID, sessionID ULID) error

RevokeOwnedSession revokes one session after confirming it belongs to userID. A session owned by someone else reports ErrStorageNotFound so ids cannot be probed.

func (*TheAuth) RevokeOwnerAPITokens ¶

func (a *TheAuth) RevokeOwnerAPITokens(ctx context.Context, ownerID ULID) (int, error)

RevokeOwnerAPITokens revokes every live token of an owner. Call it when a user is deleted or a service account is retired.

func (*TheAuth) RevokeRegistrationToken ¶ added in v2.8.0

func (a *TheAuth) RevokeRegistrationToken(ctx context.Context, id ULID) error

RevokeRegistrationToken revokes a registration token. Revoking an already revoked token succeeds.

func (*TheAuth) RevokeRole ¶

func (a *TheAuth) RevokeRole(ctx context.Context, actor, target, roleID ULID) error

RevokeRole removes roleID from the target user. Emits "role.revoked". Forwards to rbacSvc.RevokeRole.

func (*TheAuth) RevokeSCIMToken ¶

func (a *TheAuth) RevokeSCIMToken(ctx context.Context, id ULID) error

RevokeSCIMToken marks the named token as revoked. Revoked tokens still resolve via SCIMTokenByHash but the middleware refuses them. Forwards to scimSvc.RevokeToken.

func (*TheAuth) RevokeSession ¶

func (a *TheAuth) RevokeSession(ctx context.Context, id ULID) error

RevokeSession revokes a single session by id. Callers must authorize (confirm the session belongs to the caller, or the caller is an admin) before calling this, RevokeSession itself does no ownership check.

func (*TheAuth) RevokeSessionsByCredential ¶

func (a *TheAuth) RevokeSessionsByCredential(ctx context.Context, credentialID string) (int, error)

RevokeSessionsByCredential revokes every live session tied to credentialID. Call it when the upstream credential is revoked to cut sessions at once; sessions are also re-checked lazily on every use.

func (*TheAuth) RevokeToken ¶

func (a *TheAuth) RevokeToken(ctx context.Context, token, tokenTypeHint, clientID, clientSecret string) error

RevokeToken invalidates a refresh token. Authorization codes and access tokens are out of scope for this entry: codes are single-use anyway, and access tokens are stateless JWTs whose lifetime is bounded by exp. Forwards to as.RevokeToken.

func (*TheAuth) RevokeTrustedDevice ¶ added in v2.10.0

func (a *TheAuth) RevokeTrustedDevice(ctx context.Context, userID, id ULID) error

RevokeTrustedDevice revokes one of the user's trusted devices. It returns ErrStorageNotFound when the device is unknown, not theirs or already revoked.

func (*TheAuth) RevokeTrustedDevices ¶ added in v2.10.0

func (a *TheAuth) RevokeTrustedDevices(ctx context.Context, userID ULID) (int, error)

RevokeTrustedDevices revokes every trusted device of the user and returns how many it revoked.

func (*TheAuth) RevokeUserSessions ¶

func (a *TheAuth) RevokeUserSessions(ctx context.Context, userID ULID) error

RevokeUserSessions revokes every session belonging to userID. Callers wanting to preserve one session (e.g. "sign out other devices") must re-issue or otherwise except that session themselves, this revokes unconditionally.

func (*TheAuth) RotateAgentSecret ¶

func (a *TheAuth) RotateAgentSecret(ctx context.Context, agentID ULID) (AgentSecret, error)

RotateAgentSecret mints a fresh secret credential and revokes every prior unrevoked credential. Use this on suspected compromise; use MintAgentCredential when overlapping live credentials are desired.

func (*TheAuth) RotateSession ¶

func (a *TheAuth) RotateSession(ctx context.Context, old Session) (string, Session, error)

RotateSession issues a fresh token for the same user, UA and IP and revokes old. Use it after a privilege change so a token an attacker may hold stops working.

func (*TheAuth) RotateSigningKey ¶

func (a *TheAuth) RotateSigningKey(ctx context.Context) error

RotateSigningKey advances the JWKS state machine one step: previous (if any) is retired, current becomes previous, next becomes current, and a fresh next is minted. Idempotent under concurrent callers (each call mints one fresh next). Operators can invoke this on emergency without waiting for the scheduled tick.

func (*TheAuth) SAMLConnectionByID ¶

func (a *TheAuth) SAMLConnectionByID(ctx context.Context, id ULID) (*SAMLConnection, error)

SAMLConnectionByID looks up one connection.

func (*TheAuth) SAMLMetadataXML ¶

func (a *TheAuth) SAMLMetadataXML(ctx context.Context, connectionID ULID) ([]byte, error)

SAMLMetadataXML serialises the per-connection SP metadata as XML.

func (*TheAuth) SeedOrganizationRoles ¶

func (a *TheAuth) SeedOrganizationRoles(ctx context.Context, orgID ULID) error

SeedOrganizationRoles creates the three default roles (or whatever the consumer configured) for one organization. Idempotent on (organization_id, name); existing roles keep their IDs and have their permission set reconciled against the seed. Forwards to rbacSvc.SeedOrgRoles.

func (*TheAuth) SeedPermissions ¶

func (a *TheAuth) SeedPermissions(ctx context.Context) ([]Permission, error)

SeedPermissions ensures every seeded + consumer-extended permission row exists in storage. Idempotent on the permissions.name unique index. Returns the canonical permission rows (with their persisted IDs) so the caller can reuse them for role assignments.

SeedPermissions runs lazily on first SeedOrganizationRoles / CreateRole invocation; consumers wanting eager seeding at app start may call it directly from their bootstrap. Forwards to rbacSvc.SeedPermissions.

func (*TheAuth) SessionByID ¶

func (a *TheAuth) SessionByID(ctx context.Context, id ULID) (*Session, error)

SessionByID returns a session's current state (including RevokedAt and ExpiresAt) by id, or ErrNotFound. Exists so callers with a session id from another source (e.g. an audit log actor_session_id) can resolve its live status without a token hash.

func (*TheAuth) SetActiveOrganization ¶

func (a *TheAuth) SetActiveOrganization(ctx context.Context, sessionID ULID, orgID *ULID) error

SetActiveOrganization sets (or clears, when orgID is nil) the active organization on a session. The caller is responsible for verifying that the session's user is a member of orgID before calling. Forwards to orgsSvc.SetActive, then fires OnOrgSwitch on success. orgID being nil (clearing the active org) still fires the hook with an empty string so consumers can observe both directions.

func (*TheAuth) SetMustChangePassword ¶ added in v2.10.0

func (a *TheAuth) SetMustChangePassword(ctx context.Context, userID ULID, required bool) error

SetMustChangePassword flags or unflags userID for a forced password change. Setting the flag also revokes the user's sessions, so the change is felt at once; the user then gets CodePasswordChangeRequired at sign-in until a password reset completes. It needs Config.AccountState.

func (*TheAuth) SetupToken ¶

func (a *TheAuth) SetupToken() string

SetupToken returns the pending first-run setup token, or "" when Config.Bootstrap is unset or the first user already exists.

func (*TheAuth) SharedSignalsHandler ¶ added in v2.10.0

func (a *TheAuth) SharedSignalsHandler() http.Handler

SharedSignalsHandler returns the SSF transmitter routes (/.well-known/ssf-configuration and /ssf/*), or nil when Config.SharedSignals is unset. Mount it at the issuer origin root.

func (*TheAuth) SharedSignalsReceiverHandler ¶ added in v2.10.0

func (a *TheAuth) SharedSignalsReceiverHandler() http.Handler

SharedSignalsReceiverHandler returns the RFC 8935 push endpoint of the receiver, or nil when no receiver is configured.

func (*TheAuth) SharedSignalsTransmitter ¶ added in v2.10.0

func (a *TheAuth) SharedSignalsTransmitter() *signals.Transmitter

SharedSignalsTransmitter exposes the transmitter for host code that wants to emit custom events (device-compliance-change, assurance-level-change, credential-compromise, token-claims-change) with Emit. Nil when off.

func (*TheAuth) Start ¶

func (a *TheAuth) Start() error

Start spawns the audit writer goroutine when Config.Audit is non-nil and the writer is not already running. Idempotent; safe to call multiple times. New calls Start automatically so existing callers that never invoked Start keep working.

PR D architecture reorg (2026-06-20): forwards to the extracted audit service. WebAuthn / TOTP / SAML GC loops are spawned directly in New via their per-service Start methods; Close handles their lifecycle.

func (*TheAuth) StartAuthorize ¶

func (a *TheAuth) StartAuthorize(ctx context.Context, req AuthorizeRequest, user *User) (AuthorizeResult, error)

StartAuthorize validates the request and, when the supplied user is non-nil, immediately mints an authorization code bound to the request and returns a redirect URL with code + state. When user is nil the caller should redirect to LoginURL so the user can sign in. Forwards to as.StartAuthorize.

func (*TheAuth) StartDeviceAuth ¶

func (a *TheAuth) StartDeviceAuth(ctx context.Context, in StartDeviceAuthInput) (DeviceAuthStart, error)

StartDeviceAuth opens a device authorization request.

func (*TheAuth) Stats ¶

func (a *TheAuth) Stats() Stats

Stats returns a snapshot of runtime counters.

func (*TheAuth) StepUp ¶

func (a *TheAuth) StepUp(ctx context.Context, sess *Session, in StepUpInput) (time.Time, error)

StepUp verifies a second proof of identity for the session's user and elevates the session for Config.StepUpTTL, returning the elevation expiry.

func (*TheAuth) SubscribeRevocations ¶

func (a *TheAuth) SubscribeRevocations(fn func(RevocationEvent)) (func(), error)

SubscribeRevocations registers fn for every revocation event.

func (*TheAuth) SuspendAgent ¶

func (a *TheAuth) SuspendAgent(ctx context.Context, agentID ULID, reason string) error

SuspendAgent flips status to suspended. Cascades to every issued token mentioning this agent on the next introspection refresh.

func (*TheAuth) TOTPStatus ¶

func (a *TheAuth) TOTPStatus(ctx context.Context, userID ULID) (TOTPStatus, error)

TOTPStatus returns the user's TOTP enrollment state.

func (*TheAuth) UnlinkOAuthProvider ¶

func (a *TheAuth) UnlinkOAuthProvider(ctx context.Context, sessionToken, provider string) error

UnlinkOAuthProvider removes the named OAuth provider from the current user's linked accounts. Returns ErrLastAuthMethod when the provider is the only sign-in method. Used by the /api/v1/me/connections DELETE handler in glinr-v2.

func (*TheAuth) UnlockUser ¶

func (a *TheAuth) UnlockUser(ctx context.Context, emailAddr string) error

UnlockUser clears the login lockout and MFA lockout for the user with the given email so they can try again immediately.

func (*TheAuth) UpdateRole ¶

func (a *TheAuth) UpdateRole(ctx context.Context, roleID ULID, name, description string, perms []string) (Role, error)

UpdateRole rewrites name / description / permissions on an existing role. nil-valued fields are not touched (caller passes the current value). Emits "role.updated". Forwards to rbacSvc.UpdateRole.

func (*TheAuth) UpdateSAMLConnection ¶

func (a *TheAuth) UpdateSAMLConnection(ctx context.Context, id ULID, in SAMLConnectionInput) (SAMLConnection, error)

UpdateSAMLConnection rewrites an existing connection in place.

func (*TheAuth) UserByID ¶

func (a *TheAuth) UserByID(ctx context.Context, id ULID) (*User, error)

UserByID looks up a user by ID. Returns (nil, ErrNotFound) when the row does not exist. Added in v2.5 to unblock consumer code that previously had no public accessor and had to reach into storage directly (consumer feedback 2026-06-22).

func (*TheAuth) UserCount ¶

func (a *TheAuth) UserCount(ctx context.Context) (int, error)

UserCount returns the number of user records. It needs a storage that implements UserCountStorage.

func (*TheAuth) VerifyTOTP ¶

func (a *TheAuth) VerifyTOTP(ctx context.Context, pendingSessionToken, code string) (string, Session, error)

VerifyTOTP consumes a 6-digit code against the user's confirmed secret, upgrades their pending session to full, and returns the (same) token with the upgraded session row. Forwards to totpSvc.Verify, then fires OnSignin: this is the moment a password sign-in that was held at pending_2fa becomes a full session.

func (*TheAuth) WatchRevocation ¶

func (a *TheAuth) WatchRevocation(ctx context.Context, target RevocationTarget, opts WatchOptions) (context.Context, context.CancelCauseFunc)

WatchRevocation returns a context cancelled, with an error wrapping ErrCredentialRevoked as its cause, as soon as an event matches target or a poll finds the credential invalid. Call the cancel func when the stream ends.

func (*TheAuth) WatchRevocationMiddleware ¶

func (a *TheAuth) WatchRevocationMiddleware(opts WatchOptions) func(http.Handler) http.Handler

WatchRevocationMiddleware cancels the request context when the presented credential is revoked, so SSE, MCP and other long-lived handlers drop within seconds. Place it after RequireAbility, which supplies the Principal; a session cookie is used when no bearer token was presented.

func (*TheAuth) WatchSession ¶

func (a *TheAuth) WatchSession(ctx context.Context, sessionToken string, interval time.Duration) (context.Context, context.CancelCauseFunc)

WatchSession re-validates sessionToken every interval and cancels the returned context, with the reason as its cause, once it stops validating. It fails closed on any error. Checks do not count as user activity. Call the cancel func when the stream ends.

func (*TheAuth) WatchSessionMiddleware ¶

func (a *TheAuth) WatchSessionMiddleware(interval time.Duration) func(http.Handler) http.Handler

WatchSessionMiddleware wraps a streaming handler so the request context is cancelled when the caller's session stops validating (see WatchSession). Place it after Authn or RequireAuth.

type TheAuthError ¶

type TheAuthError = models.TheAuthError

TheAuthError is the structured error type returned by v0.2+ service methods. Callers can errors.As-extract it and switch on Code for stable handling, or errors.Is-check against a value of the same Code for shorter paths.

PR B architecture reorg (2026-06-20): the struct + methods now live in internal/models so subpackages can construct it without taking an import cycle on the root package. The type alias below preserves the v0.2+ public name and method set; existing callers compile unchanged.

func NewError ¶

func NewError(code, message string, inner error) *TheAuthError

NewError constructs a TheAuthError with the supplied code, message, and optional wrapped cause. Re-exported from internal/models for the same reason as the type alias above.

type TokenExchangeRequest ¶

type TokenExchangeRequest = internalas.TokenExchangeRequest

TokenExchangeRequest is the parsed form-encoded body of a token-exchange call. Field names map 1:1 onto the RFC 8693 wire form.

type TokenPolicyConfig ¶ added in v2.8.0

type TokenPolicyConfig = internalas.TokenPolicyConfig

TokenPolicyConfig is the root alias for the per-client token policy.

type TokenRequest ¶

type TokenRequest = internalas.TokenRequest

TokenRequest is the parsed form-encoded body of a POST /oauth/token call, plus the authenticated client extracted from the request line / headers.

type TokenResponse ¶

type TokenResponse = internalas.TokenResponse

TokenResponse is the JSON body emitted by /oauth/token on success.

type Tracer ¶

type Tracer = observability.Tracer

Tracer is the span starter adapters implement. See internal/observability.Tracer for the full contract.

type TrustedDevice ¶ added in v2.10.0

type TrustedDevice = models.TrustedDevice

TrustedDevice is a remember-this-device record. Only the hash of its cookie token is stored.

type TrustedDeviceInfo ¶ added in v2.10.0

type TrustedDeviceInfo struct {
	ID          ULID      `json:"id"`
	DeviceLabel string    `json:"deviceLabel"`
	IPPrefix    string    `json:"ipPrefix,omitempty"`
	CreatedAt   time.Time `json:"createdAt"`
	LastUsedAt  time.Time `json:"lastUsedAt"`
	ExpiresAt   time.Time `json:"expiresAt"`
}

TrustedDeviceInfo is the end-user view of one trusted device.

type TrustedDeviceStorage ¶ added in v2.10.0

type TrustedDeviceStorage interface {
	InsertTrustedDevice(ctx context.Context, d TrustedDevice) error
	// TrustedDeviceByTokenHash returns the record for userID and hash,
	// revoked or expired rows included; callers check RevokedAt and ExpiresAt.
	TrustedDeviceByTokenHash(ctx context.Context, userID ULID, hash []byte) (*TrustedDevice, error)
	// ListTrustedDevices returns the user's unrevoked, unexpired devices,
	// newest first.
	ListTrustedDevices(ctx context.Context, userID ULID) ([]TrustedDevice, error)
	// TouchTrustedDevice sets LastUsedAt.
	TouchTrustedDevice(ctx context.Context, id ULID, at time.Time) error
	// RevokeTrustedDevice revokes one device owned by userID. It returns
	// ErrStorageNotFound when no such live device exists.
	RevokeTrustedDevice(ctx context.Context, userID, id ULID) error
	// RevokeUserTrustedDevices revokes every live device of userID and
	// returns how many it revoked.
	RevokeUserTrustedDevices(ctx context.Context, userID ULID) (int, error)
}

TrustedDeviceStorage is the optional capability behind Config.TrustedDevices. Lookups return ErrStorageNotFound on a miss.

type TrustedDevicesConfig ¶ added in v2.10.0

type TrustedDevicesConfig struct {
	// TTL is the trust window. Default 30 days.
	TTL time.Duration
	// CookieName defaults to "theauth_trusted_device".
	CookieName string
}

TrustedDevicesConfig enables remember-this-device for TOTP. After a successful TOTP or recovery-code step the client may send {"rememberDevice": true}; the library then sets a signed cookie and stores only its hash. Later password sign-ins from that device skip the TOTP prompt until the window ends. Trust is revoked on password change, when TOTP is removed, and through the trusted-device list. It needs Config.TOTP and a storage implementing TrustedDeviceStorage.

type TrustedJWTIssuer ¶

type TrustedJWTIssuer struct {
	// Issuer is the value the trusted issuer places in the iss claim of
	// its JWTs. Must be an exact string match.
	Issuer string

	// JWKSURL is the URL of the issuer's JSON Web Key Set document.
	// Fetched and cached by the AS; rotated on 401 or periodic refresh.
	JWKSURL string

	// AllowedAlgorithms is the set of JWS algorithms the AS will accept
	// for this issuer. Defaults to ES256, RS256, EdDSA.
	AllowedAlgorithms []string

	// SubjectMapper resolves the "sub" claim (and any other claims) of
	// the external JWT to a local user ULID. When nil the built-in
	// SubMapper is used: the sub claim is parsed directly as a ULID.
	// Use EmailMapper to resolve the email claim to a local user.Email
	// row instead.
	SubjectMapper SubjectMapper
}

TrustedJWTIssuer is one entry in JWTBearerConfig.TrustedJWTIssuers.

type ULID ¶

type ULID = models.ULID

ULID is the canonical ID type, generated in app, stored as uuid in Postgres.

type User ¶

type User = models.User

func ImportUserTo ¶

func ImportUserTo(ctx context.Context, store ImportUserStorage, in ImportedUser) (User, error)

ImportUserTo inserts an existing user and its password hash into store, with no TheAuth instance.

func UserFromContext ¶

func UserFromContext(ctx context.Context) (*User, bool)

UserFromContext returns the authenticated User attached by Authn middleware, if any. Returns false when the request is anonymous.

type UserCountStorage ¶

type UserCountStorage interface {
	// CountUsers returns the total number of user records.
	CountUsers(ctx context.Context) (int, error)
}

UserCountStorage is an optional capability required by Config.Bootstrap to detect whether the first administrator has been created yet.

type UserRole ¶

type UserRole = models.UserRole

type UserStorage ¶

type UserStorage interface {
	CreateUser(ctx context.Context, u User) (User, error)
	UserByEmail(ctx context.Context, email string) (*User, error)
	UserByID(ctx context.Context, id ULID) (*User, error)
	MarkEmailVerified(ctx context.Context, userID ULID) error
}

UserStorage covers user records and email verification.

type WatchOptions ¶

type WatchOptions = revocation.WatchOptions

WatchOptions tunes WatchRevocation.

type WebAuthnConfig ¶

type WebAuthnConfig struct {
	// RPID is the Relying Party Server ID. e.g. "glinr.com" (eTLD+1 of the
	// origin, no scheme, no port). Required.
	RPID string
	// RPDisplayName is shown by browsers and authenticators. Required.
	RPDisplayName string
	// RPOrigins is the fully qualified origins permitted to invoke the
	// API, e.g. ["https://glinr.com"]. At least one required.
	RPOrigins []string
	// ChallengeTTL caps how long the in-memory challenge session is valid.
	// Defaults to 5 minutes; challenges are single-use regardless.
	ChallengeTTL time.Duration
	// RequireUserVerification makes registration and login demand user
	// verification (PIN or biometric), so a passkey is never a bare
	// possession factor. Defaults to false (v2 behavior: UV "preferred").
	RequireUserVerification bool
	// CloneWarning selects what happens when an assertion's sign count
	// fails to advance, the signal of a cloned authenticator. The default,
	// CloneWarningReject, refuses the login; CloneWarningFlag lets it
	// through and emits a passkey.clone_warning audit event.
	CloneWarning CloneWarningPolicy
	// UserHandleResolver lets passkeys imported from another system sign in
	// when their authenticator holds a user handle that is not a theauth
	// handle. It receives the credential id and the handle and must return
	// the user that handle denotes. The credential's stored owner stays
	// authoritative: login is refused unless the resolver returns that same
	// user. Nil (the default) accepts only theauth user handles.
	UserHandleResolver func(ctx context.Context, credentialID, userHandle []byte) (ULID, error)

	// AttestationPreference is the attestation conveyance requested from
	// authenticators: "none" (default), "indirect", "direct" or
	// "enterprise". The upstream library verifies the statement formats it
	// supports; trust anchors (FIDO MDS) are not configured here.
	AttestationPreference string

	// RequireAttestationStatement rejects registrations whose attestation
	// format is "none". Pair with AttestationPreference "direct".
	RequireAttestationStatement bool

	// AAGUIDAllowlist, when non-empty, accepts only these authenticator
	// models (UUID strings). Registration of anything else fails.
	AAGUIDAllowlist []string

	// AAGUIDDenylist rejects these authenticator models. It wins over the
	// allowlist.
	AAGUIDDenylist []string

	// AuthenticatorNames maps an AAGUID to a display name for UIs.
	AuthenticatorNames map[string]string

	// AuthenticatorName is an optional lookup consulted before
	// AuthenticatorNames, receiving a lowercase hyphenated AAGUID.
	AuthenticatorName func(aaguid string) string
}

WebAuthnConfig wires the Relying Party identity. Field names mirror the upstream go-webauthn/webauthn.Config so consumers reading either set of docs see the same vocabulary.

type WebAuthnCredential ¶

type WebAuthnCredential = models.WebAuthnCredential

func ImportWebAuthnCredentialTo ¶

func ImportWebAuthnCredentialTo(ctx context.Context, store WebAuthnStorage, in ImportedWebAuthnCredential) (WebAuthnCredential, error)

ImportWebAuthnCredentialTo inserts an existing credential into store, with no TheAuth instance.

type WebAuthnRenameStorage ¶

type WebAuthnRenameStorage interface {
	// RenameWebAuthnCredential sets the display name of the credential
	// identified by id when it belongs to userID. Returns ErrStorageNotFound
	// when no such row exists.
	RenameWebAuthnCredential(ctx context.Context, id, userID ULID, name string) error
}

WebAuthnRenameStorage is the optional capability behind passkey rename (PATCH /auth/webauthn/credentials/{id}). Adapters that do not implement it answer 501 on that route; everything else keeps working.

type WebAuthnStorage ¶

type WebAuthnStorage interface {
	// MoveWebAuthnCredentials reassigns every WebAuthn credential row owned
	// by secondaryID to primaryID.
	MoveWebAuthnCredentials(ctx context.Context, primaryID, secondaryID ULID) error
	InsertWebAuthnCredential(ctx context.Context, c WebAuthnCredential) (WebAuthnCredential, error)
	WebAuthnCredentialsByUserID(ctx context.Context, userID ULID) ([]WebAuthnCredential, error)
	// WebAuthnCredentialByCredentialID returns the row keyed by the raw
	// authenticator credential ID, or ErrStorageNotFound when missing.
	WebAuthnCredentialByCredentialID(ctx context.Context, credentialID []byte) (*WebAuthnCredential, error)
	// UpdateWebAuthnSignCount atomically writes a strictly greater sign
	// count and bumps last_used_at. Returns ErrReplayDetected when the
	// new count is not strictly greater than the stored value (the
	// canonical replay signal per WebAuthn L2 / L3). Returns
	// ErrStorageNotFound when the credential does not exist.
	UpdateWebAuthnSignCount(ctx context.Context, credentialID []byte, newCount uint32, usedAt time.Time) error
	// UpdateWebAuthnBackupFlags records the WebAuthn backup-eligible / backup
	// -state flags for a credential that had none stored (a row written before
	// the backup_eligible / backup_state columns existed). It is the
	// trust-on-first-use reconciliation write for legacy synced passkeys and
	// is idempotent. Implementations should return nil when the credential is
	// missing rather than error; the caller treats any failure as non-fatal
	// (a failed reconciliation must never fail an already-verified login).
	UpdateWebAuthnBackupFlags(ctx context.Context, credentialID []byte, backupEligible, backupState bool) error
	// DeleteWebAuthnCredential removes a credential by ID, scoped to the
	// owning user. Returns ErrStorageNotFound when the row does not exist
	// or does not belong to the caller (no leak on cross-user lookup).
	DeleteWebAuthnCredential(ctx context.Context, id ULID, userID ULID) error
}

WebAuthnStorage covers WebAuthn passkey credentials.

Directories ¶

Path Synopsis
Package admin holds shared helpers for the /admin/v1 HTTP surface: RFC 7807 problem+json marshalling and keyset cursor encoding.
Package admin holds shared helpers for the /admin/v1 HTTP surface: RFC 7807 problem+json marshalling and keyset cursor encoding.
audit
sinks/splunkhec
Package splunkhec provides an AuditSink that forwards batches of audit events to a Splunk HTTP Event Collector (HEC) endpoint.
Package splunkhec provides an AuditSink that forwards batches of audit events to a Splunk HTTP Event Collector (HEC) endpoint.
sinks/webhook
Package webhook provides an AuditSink that POSTs audit events as CloudEvents 1.0 envelopes to a configurable HTTP endpoint.
Package webhook provides an AuditSink that POSTs audit events as CloudEvents 1.0 envelopes to a configurable HTTP endpoint.
Package clientauth lets any Go CLI authenticate against a theauth-go server with the RFC 8628 device grant, keep the resulting API token in a local store, and call the server with it.
Package clientauth lets any Go CLI authenticate against a theauth-go server with the RFC 8628 device grant, keep the resulting API token in a local store, and call the server with it.
cmd
theauth-doctor command
Command theauth-doctor fetches the security report of a running theauth-go server and prints it.
Command theauth-doctor fetches the security report of a running theauth-go server and prints it.
theauth-go command
Command theauth-go is a small developer CLI for theauth-go projects.
Command theauth-go is a small developer CLI for theauth-go projects.
theauth-loadtest command
Command theauth-loadtest measures theauth-go against a real Postgres under concurrent HTTP load.
Command theauth-loadtest measures theauth-go against a real Postgres under concurrent HTTP load.
theauth-migrate command
theauth-migrate is a CLI tool that converts AWS Cognito and Auth0 user exports to theauth-go storage rows.
theauth-migrate is a CLI tool that converts AWS Cognito and Auth0 user exports to theauth-go storage rows.
theauth-migrate/auth0
Package auth0 reads Auth0 user-pool exports and converts them to the migration Bundle format.
Package auth0 reads Auth0 user-pool exports and converts them to the migration Bundle format.
theauth-migrate/cognito
Package cognito reads AWS Cognito user-pool exports and converts them to the migration Bundle format.
Package cognito reads AWS Cognito user-pool exports and converts them to the migration Bundle format.
theauth-migrate/internal
Package internal defines the shared migration bundle format, applier, and validator used by both the cognito and auth0 sub-commands.
Package internal defines the shared migration bundle format, applier, and validator used by both the cognito and auth0 sub-commands.
theauth-migrate/keycloak
Package keycloak reads a Keycloak realm export and converts it to the migration Bundle format.
Package keycloak reads a Keycloak realm export and converts it to the migration Bundle format.
Package crypto contains the primitives theauth-go uses for password hashing (Argon2id), opaque session and reset tokens (crypto/rand plus SHA-256), AES-256-GCM symmetric encryption for OAuth tokens at rest, PKCE code verifier and S256 challenge generation, and salted SHA-256 recovery-code hashing.
Package crypto contains the primitives theauth-go uses for password hashing (Argon2id), opaque session and reset tokens (crypto/rand plus SHA-256), AES-256-GCM symmetric encryption for OAuth tokens at rest, PKCE code verifier and S256 challenge generation, and salted SHA-256 recovery-code hashing.
Package email defines the Sender interface theauth-go uses to deliver magic-link and password-reset messages, plus a Noop implementation suitable for local development and tests.
Package email defines the Sender interface theauth-go uses to deliver magic-link and password-reset messages, plus a Noop implementation suitable for local development and tests.
examples
cli-device-login command
Command cli-device-login signs a command-line tool in with the OAuth 2.0 device authorization grant (RFC 8628).
Command cli-device-login signs a command-line tool in with the OAuth 2.0 device authorization grant (RFC 8628).
cli-device-login/server command
Command server is a self-contained demo authorization server for the cli-device-login example: in-memory storage, the RFC 8628 device grant enabled, and a bare sign-in page so the verification flow works end to end in a browser.
Command server is a self-contained demo authorization server for the cli-device-login example: in-memory storage, the RFC 8628 device grant enabled, and a bare sign-in page so the verification flow works end to end in a browser.
cli-login command
Command cli-login shows a host CLI authenticating against a theauth-go server.
Command cli-login shows a host CLI authenticating against a theauth-go server.
doctor-admin command
doctor-admin serves /healthz publicly and a root-only /admin/security page that renders the theauth-go security report next to it.
doctor-admin serves /healthz publicly and a root-only /admin/security page that renders the theauth-go security report next to it.
hooks command
hooks is a runnable demo of Config.LifecycleHooks.
hooks is a runnable demo of Config.LifecycleHooks.
totp-stepup command
totp-stepup is a runnable demo of the v0.5 password + TOTP step-up flow.
totp-stepup is a runnable demo of the v0.5 password + TOTP step-up flow.
webauthn-passkey command
webauthn-passkey is a runnable demo of v0.5 passkey registration + login.
webauthn-passkey is a runnable demo of v0.5 passkey registration + login.
integration
internal/testutil
Package testutil adapts the root test hooks to typed helpers for the black-box integration tests.
Package testutil adapts the root test hooks to typed helpers for the black-box integration tests.
internal
account
Package account exposes the /account/* end-user self-service endpoints (agents the user owns and delegation grants the user has issued).
Package account exposes the /account/* end-user self-service endpoints (agents the user owns and delegation grants the user has issued).
admin
Package admin exposes the /admin/v1 organization-scoped admin API: user / session / role / audit / oauth-account management.
Package admin exposes the /admin/v1 organization-scoped admin API: user / session / role / audit / oauth-account management.
agent
Package agent owns the v2.0 agent identity lifecycle: CreateAgent, MintAgentCredential, RotateAgentSecret, ListAgentsByOwner, GetAgent, SuspendAgent, ResumeAgent, RevokeAgent, and the agentBySubjectClaim resolver consulted by internal/as.
Package agent owns the v2.0 agent identity lifecycle: CreateAgent, MintAgentCredential, RotateAgentSecret, ListAgentsByOwner, GetAgent, SuspendAgent, ResumeAgent, RevokeAgent, and the agentBySubjectClaim resolver consulted by internal/as.
agent/handlers
Package handlers exposes the organization-scoped agent + delegation administration endpoints mounted under /admin/v1/organizations/{orgID}/agents and .../delegations.
Package handlers exposes the organization-scoped agent + delegation administration endpoints mounted under /admin/v1/organizations/{orgID}/agents and .../delegations.
apitokens
Package apitokens implements scoped API tokens, the RFC 8628 device grant, agent tokens and the HTTP routes and middleware around them.
Package apitokens implements scoped API tokens, the RFC 8628 device grant, agent tokens and the HTTP routes and middleware around them.
as
Package as owns the OAuth 2.1 + MCP authorization server runtime: the JWKS state machine and key rotation goroutine, the /oauth/authorize + /oauth/token + /oauth/revoke + /oauth/introspect service code, dynamic client registration (RFC 7591), AS metadata documents (RFC 8414 + RFC 9728), and the RFC 8693 token-exchange grant.
Package as owns the OAuth 2.1 + MCP authorization server runtime: the JWKS state machine and key rotation goroutine, the /oauth/authorize + /oauth/token + /oauth/revoke + /oauth/introspect service code, dynamic client registration (RFC 7591), AS metadata documents (RFC 8414 + RFC 9728), and the RFC 8693 token-exchange grant.
as/handlers
Package handlers exposes the OAuth 2.1 + MCP authorization server HTTP endpoints.
Package handlers exposes the OAuth 2.1 + MCP authorization server HTTP endpoints.
audit
Package audit defines the audit-emission interface that internal service packages depend on.
Package audit defines the audit-emission interface that internal service packages depend on.
authevents
Package authevents defines the PII-minimal authentication event stream.
Package authevents defines the PII-minimal authentication event stream.
bootstrap
Package bootstrap gates creation of the first user behind a one-time setup token.
Package bootstrap gates creation of the first user behind a one-time setup token.
chain
Package chain provides pure helpers for RFC 8693 actor chain validation: depth counting, scope subset checking, duration narrowing, and act-claim construction.
Package chain provides pure helpers for RFC 8693 actor chain validation: depth counting, scope subset checking, duration narrowing, and act-claim construction.
cimd
Package cimd implements RFC draft 'Client ID Metadata Documents' (CIMD) per the MCP Authorization specification 2025-11-25.
Package cimd implements RFC draft 'Client ID Metadata Documents' (CIMD) per the MCP Authorization specification 2025-11-25.
clientauthcache
Package clientauthcache caches the result of an OAuth client_secret verification (Argon2id PHC compare) so that hot endpoints (introspect, token, revoke) do not pay the ~27ms Argon2 cost on every request.
Package clientauthcache caches the result of an OAuth client_secret verification (Argon2id PHC compare) so that hot endpoints (introspect, token, revoke) do not pay the ~27ms Argon2 cost on every request.
delegation
Package delegation owns the v2.0 delegation_grants lifecycle: GrantDelegation, ListDelegationsForUser, ListDelegationsForAgent, RevokeDelegation, and the canonical Active + NarrowScope helpers consulted by the AS token-exchange and introspection paths.
Package delegation owns the v2.0 delegation_grants lifecycle: GrantDelegation, ListDelegationsForUser, ListDelegationsForAgent, RevokeDelegation, and the canonical Active + NarrowScope helpers consulted by the AS token-exchange and introspection paths.
doctor
Package doctor evaluates security-posture checks over a plain input struct.
Package doctor evaluates security-posture checks over a plain input struct.
dpop
Package dpop implements RFC 9449 Demonstrating Proof-of-Possession (DPoP) for OAuth 2.0 / OAuth 2.1 sender-constrained access tokens.
Package dpop implements RFC 9449 Demonstrating Proof-of-Possession (DPoP) for OAuth 2.0 / OAuth 2.1 sender-constrained access tokens.
emailnorm
Package emailnorm canonicalizes email addresses so uniqueness checks and lookups agree regardless of case, surrounding whitespace, or Unicode compatibility forms.
Package emailnorm canonicalizes email addresses so uniqueness checks and lookups agree regardless of case, surrounding whitespace, or Unicode compatibility forms.
httpsec
Package httpsec holds the Secure cookie rewriting and the Origin allowlist check.
Package httpsec holds the Secure cookie rewriting and the Origin allowlist check.
httpx
Package httpx hosts shared HTTP helpers used by extracted handler packages: the canonical sentinel-error to status mapping, the {code,message} JSON error body, the URL-param ULID parser, and the no-trust client IP shim.
Package httpx hosts shared HTTP helpers used by extracted handler packages: the canonical sentinel-error to status mapping, the {code,message} JSON error body, the URL-param ULID parser, and the no-trust client IP shim.
identitylink
Package identitylink owns the three identity-linking service methods (v2.3): LinkOAuthToCurrentUser, LinkPasswordToCurrentUser, MergeAccounts.
Package identitylink owns the three identity-linking service methods (v2.3): LinkOAuthToCurrentUser, LinkPasswordToCurrentUser, MergeAccounts.
importer
Package importer inserts accounts, TOTP secrets and passkeys migrated from another system.
Package importer inserts accounts, TOTP secrets and passkeys migrated from another system.
jwt
Package jwt implements the minimum JWT surface required by the v2.0 authorization server: Ed25519 (EdDSA) sign and verify for access tokens shaped per RFC 9068 (typ = "at+jwt").
Package jwt implements the minimum JWT surface required by the v2.0 authorization server: Ed25519 (EdDSA) sign and verify for access tokens shaped per RFC 9068 (typ = "at+jwt").
magiclink
Package magiclink owns the request / consume flow for email-delivered magic-link sign-in tokens.
Package magiclink owns the request / consume flow for email-delivered magic-link sign-in tokens.
models
Package models is the internal home for the theauth-go data layer: persisted entity structs (User, Session, OAuthClient, Agent, ...), the canonical Permission name catalog, and the sentinel errors that storage adapters and service code share.
Package models is the internal home for the theauth-go data layer: persisted entity structs (User, Session, OAuthClient, Agent, ...), the canonical Permission name catalog, and the sentinel errors that storage adapters and service code share.
oauth
Package oauth owns the user-facing OAuth 2.0 login state machine: PKCE state generation at /start and code exchange at /callback.
Package oauth owns the user-facing OAuth 2.0 login state machine: PKCE state generation at /start and code exchange at /callback.
oauth/handlers
Package handlers exposes the /auth/providers/{name}/start and /auth/providers/{name}/callback endpoints for user-facing OAuth login (Google, GitHub, Discord, Microsoft).
Package handlers exposes the /auth/providers/{name}/start and /auth/providers/{name}/callback endpoints for user-facing OAuth login (Google, GitHub, Discord, Microsoft).
observability
Package observability is the pluggable tracing + metrics adapter surface the theauth-go library uses to expose spans and counters without pulling in OpenTelemetry, Prometheus, or any other vendor as a hard dependency.
Package observability is the pluggable tracing + metrics adapter surface the theauth-go library uses to expose spans and counters without pulling in OpenTelemetry, Prometheus, or any other vendor as a hard dependency.
organizations
Package organizations owns the create / read / member-management surface for multi-tenant organizations.
Package organizations owns the create / read / member-management surface for multi-tenant organizations.
organizations/handlers
Package handlers exposes the /auth/orgs/* HTTP endpoints for multi-tenant organization create / read / membership management.
Package handlers exposes the /auth/orgs/* HTTP endpoints for multi-tenant organization create / read / membership management.
password
Package password owns the email + password signup / signin / reset flow, including the Argon2id hash + verify cost (paid even on user-not-found to equalise signin timing per security audit M6), the magic-link-backed reset, and the TOTP-step-up gate that mints a pending_2fa session when the user has a confirmed second factor.
Package password owns the email + password signup / signin / reset flow, including the Argon2id hash + verify cost (paid even on user-not-found to equalise signin timing per security audit M6), the magic-link-backed reset, and the TOTP-step-up gate that mints a pending_2fa session when the user has a confirmed second factor.
password/handlers
Package handlers exposes the /auth/email-password/* HTTP endpoints for password signup, signin, forgot, and reset.
Package handlers exposes the /auth/email-password/* HTTP endpoints for password signup, signin, forgot, and reset.
pathprefix
Package pathprefix holds the route prefix default and validation shared by the root package and the internal service packages.
Package pathprefix holds the route prefix default and validation shared by the root package and the internal service packages.
rar
Package rar implements the data model for OAuth 2.0 Rich Authorization Requests (RFC 9396): parsing the authorization_details parameter, serialising it for storage and token claims, and the narrowing rules used when a client asks for less than it was granted.
Package rar implements the data model for OAuth 2.0 Rich Authorization Requests (RFC 9396): parsing the authorization_details parameter, serialising it for storage and token claims, and the narrowing rules used when a client asks for less than it was granted.
ratelimit
Package ratelimit holds the per-key request limiter and the trusted-proxy aware client IP helpers.
Package ratelimit holds the per-key request limiter and the trusted-proxy aware client IP helpers.
rbac
Package rbac owns the v1.0 role + permission management surface: permission seeding, organization-scoped role CRUD, grant / revoke, and the HasPermission / PermissionsForUser checks consumed by middleware.
Package rbac owns the v1.0 role + permission management surface: permission seeding, organization-scoped role CRUD, grant / revoke, and the HasPermission / PermissionsForUser checks consumed by middleware.
revocation
Package revocation carries credential revocation events, the bus that fans them out, and the watcher that cancels a context when one matches.
Package revocation carries credential revocation events, the bus that fans them out, and the watcher that cancels a context when one matches.
safehttp
Package safehttp builds outbound HTTP clients that refuse to connect to non-public addresses.
Package safehttp builds outbound HTTP clients that refuse to connect to non-public addresses.
saml
Package saml's Service owns the v0.7 SAML SP surface: connection CRUD, SP-initiated login (BeginLogin), the ACS endpoint backend (FinishLogin), the per-connection SP metadata serializer (MetadataXML), the in-memory AuthnRequest tracker for replay protection, and the GC goroutine that sweeps expired AuthnRequest IDs.
Package saml's Service owns the v0.7 SAML SP surface: connection CRUD, SP-initiated login (BeginLogin), the ACS endpoint backend (FinishLogin), the per-connection SP metadata serializer (MetadataXML), the in-memory AuthnRequest tracker for replay protection, and the GC goroutine that sweeps expired AuthnRequest IDs.
saml/handlers
Package handlers exposes the SAML SP-flow endpoints (/auth/saml/{connectionId}/login, /acs, /metadata).
Package handlers exposes the SAML SP-flow endpoints (/auth/saml/{connectionId}/login, /acs, /metadata).
samltest
Package samltest provides an in-process SAML IdP for end-to-end testing of the SP integration.
Package samltest provides an in-process SAML IdP for end-to-end testing of the SP integration.
scim
Package scim holds the small SCIM parsing helpers that the root theauth package uses internally but does not export.
Package scim holds the small SCIM parsing helpers that the root theauth package uses internally but does not export.
scim/handlers
Package handlers exposes the /scim/v2/* SCIM 2.0 resource and discovery endpoints, plus the per-organization SCIM token CRUD endpoints mounted under /auth/orgs/{orgId}/scim/tokens.
Package handlers exposes the /scim/v2/* SCIM 2.0 resource and discovery endpoints, plus the per-organization SCIM token CRUD endpoints mounted under /auth/orgs/{orgId}/scim/tokens.
session
Package session owns the Issue / Validate primitives for opaque session tokens.
Package session owns the Issue / Validate primitives for opaque session tokens.
storagestub
Package storagestub holds capability stubs that report ErrStorageMissingCapability.
Package storagestub holds capability stubs that report ErrStorageMissingCapability.
testhooks
Package testhooks lets black-box tests reach unexported root behavior without widening the public API.
Package testhooks lets black-box tests reach unexported root behavior without widening the public API.
theauthtest
Package theauthtest provides shared test helpers for building TheAuth instances and creating users in tests across internal packages.
Package theauthtest provides shared test helpers for building TheAuth instances and creating users in tests across internal packages.
throttle
Package throttle implements login and MFA attempt limiting: per (IP, identifier) exponential backoff after a grace period, plus per-key lockout with automatic expiry.
Package throttle implements login and MFA attempt limiting: per (IP, identifier) exponential backoff after a grace period, plus per-key lockout with automatic expiry.
totp
Package totp owns the v0.5 second-factor TOTP surface: enrollment (BeginEnrollment + FinishEnrollment), verification (Verify), and the recovery-code path (ConsumeRecoveryCode).
Package totp owns the v0.5 second-factor TOTP surface: enrollment (BeginEnrollment + FinishEnrollment), verification (Verify), and the recovery-code path (ConsumeRecoveryCode).
totp/handlers
Package handlers exposes the /auth/totp/* HTTP endpoints for TOTP 2FA enrollment, verification, recovery, and removal.
Package handlers exposes the /auth/totp/* HTTP endpoints for TOTP 2FA enrollment, verification, recovery, and removal.
trusteddevice
Package trusteddevice implements remember-this-device records that let a password sign-in skip the TOTP prompt for a configurable window.
Package trusteddevice implements remember-this-device records that let a password sign-in skip the TOTP prompt for a configurable window.
wavt
Package wavt is the WebAuthn virtual test helper used to drive the v0.5 passkey ceremony tests.
Package wavt is the WebAuthn virtual test helper used to drive the v0.5 passkey ceremony tests.
webauthn
Package webauthn owns the v0.5 passkey (FIDO2/WebAuthn L3) surface: registration ceremonies (BeginRegistration + FinishRegistration), login ceremonies (BeginLogin + FinishLogin), the in-memory sync.Map for in-flight challenges, and the GC goroutine that sweeps expired challenges.
Package webauthn owns the v0.5 passkey (FIDO2/WebAuthn L3) surface: registration ceremonies (BeginRegistration + FinishRegistration), login ceremonies (BeginLogin + FinishLogin), the in-memory sync.Map for in-flight challenges, and the GC goroutine that sweeps expired challenges.
webauthn/handlers
Package handlers exposes the /auth/webauthn/* HTTP endpoints for passkey registration, authentication, and credential management.
Package handlers exposes the /auth/webauthn/* HTTP endpoints for passkey registration, authentication, and credential management.
kv
Package kv defines the small interfaces theauth uses for state that must be shared between replicas: rate-limit counters, replay caches (DPoP jti) and short-lived caches (Client ID Metadata Documents).
Package kv defines the small interfaces theauth uses for state that must be shared between replicas: rate-limit counters, replay caches (DPoP jti) and short-lived caches (Client ID Metadata Documents).
kvtest
Package kvtest is the contract suite for kv.Cache implementations.
Package kvtest is the contract suite for kv.Cache implementations.
redis
Package redis implements kv.Cache on Redis without importing a Redis driver.
Package redis implements kv.Cache on Redis without importing a Redis driver.
sqlkv
Package sqlkv implements kv.Cache on a single table of the SQL database you already run for theauth storage.
Package sqlkv implements kv.Cache on a single table of the SQL database you already run for theauth storage.
Package openapi derives an OpenAPI 3.1 document from a mounted chi router.
Package openapi derives an OpenAPI 3.1 document from a mounted chi router.
Package otp issues and verifies one-time numeric codes delivered over a pluggable channel (email, SMS, or anything else a Sender can reach).
Package otp issues and verifies one-time numeric codes delivered over a pluggable channel (email, SMS, or anything else a Sender can reach).
Package policy is a small, dependency-free authorization engine: JSON policy documents of allow and deny statements over action and resource globs, evaluated with explicit-deny-wins and default-deny semantics.
Package policy is a small, dependency-free authorization engine: JSON policy documents of allow and deny statements over action and resource globs, evaluated with explicit-deny-wins and default-deny semantics.
Package provider is the namespace root for theauth-go's OAuth 2.0 implementations.
Package provider is the namespace root for theauth-go's OAuth 2.0 implementations.
apple
Package apple implements theauth.Provider against Sign In with Apple.
Package apple implements theauth.Provider against Sign In with Apple.
bitbucket
Package bitbucket implements theauth.Provider against Bitbucket Cloud's OAuth 2.0 endpoints.
Package bitbucket implements theauth.Provider against Bitbucket Cloud's OAuth 2.0 endpoints.
discord
Package discord implements theauth.Provider against Discord's OAuth 2.0 endpoints.
Package discord implements theauth.Provider against Discord's OAuth 2.0 endpoints.
facebook
Package facebook implements theauth.Provider against Meta's OAuth 2.0 endpoints.
Package facebook implements theauth.Provider against Meta's OAuth 2.0 endpoints.
generic
Package generic builds theauth.Provider values from a declarative Spec.
Package generic builds theauth.Provider values from a declarative Spec.
github
Package github implements theauth.Provider against GitHub's OAuth 2.0 endpoints.
Package github implements theauth.Provider against GitHub's OAuth 2.0 endpoints.
gitlab
Package gitlab implements theauth.Provider against GitLab's OpenID Connect endpoints.
Package gitlab implements theauth.Provider against GitLab's OpenID Connect endpoints.
google
Package google implements theauth.Provider against Google's OAuth 2.0 and OpenID Connect endpoints.
Package google implements theauth.Provider against Google's OAuth 2.0 and OpenID Connect endpoints.
internal/oauthtest
Package oauthtest provides shared httptest scaffolding for the OAuth provider packages under provider/.
Package oauthtest provides shared httptest scaffolding for the OAuth provider packages under provider/.
internal/refresh
Package refresh implements the RFC 6749 section 6 refresh_token grant shared by the in-tree providers.
Package refresh implements the RFC 6749 section 6 refresh_token grant shared by the in-tree providers.
linkedin
Package linkedin implements theauth.Provider against LinkedIn's OAuth 2.0 and OpenID Connect endpoints.
Package linkedin implements theauth.Provider against LinkedIn's OAuth 2.0 and OpenID Connect endpoints.
microsoft
Package microsoft implements theauth.Provider against Microsoft Entra ID (Azure AD) OAuth 2.0 endpoints.
Package microsoft implements theauth.Provider against Microsoft Entra ID (Azure AD) OAuth 2.0 endpoints.
oidc
Package oidc implements theauth.Provider (and theauth.NonceProvider) for any OpenID Connect issuer using discovery.
Package oidc implements theauth.Provider (and theauth.NonceProvider) for any OpenID Connect issuer using discovery.
slack
Package slack implements theauth.Provider against Slack's OpenID Connect endpoints (Sign in with Slack).
Package slack implements theauth.Provider against Slack's OpenID Connect endpoints (Sign in with Slack).
twitch
Package twitch implements theauth.Provider against Twitch's OpenID Connect endpoints.
Package twitch implements theauth.Provider against Twitch's OpenID Connect endpoints.
x
Package x implements theauth.Provider against X's (formerly Twitter) OAuth 2.0 with PKCE endpoints.
Package x implements theauth.Provider against X's (formerly Twitter) OAuth 2.0 with PKCE endpoints.
Package signals implements the OpenID Shared Signals Framework 1.0 (SSF), with the CAEP and RISC event vocabularies, on top of Security Event Tokens (RFC 8417).
Package signals implements the OpenID Shared Signals Framework 1.0 (SSF), with the CAEP and RISC event vocabularies, on top of Security Event Tokens (RFC 8417).
storetest
Package storetest is the contract suite for signals.Store implementations.
Package storetest is the contract suite for signals.Store implementations.
Package storage re-exports the theauth.Storage interface and the canonical ErrNotFound sentinel that adapters return on lookup misses.
Package storage re-exports the theauth.Storage interface and the canonical ErrNotFound sentinel that adapters return on lookup misses.
memory
Package memory provides an in-process implementation of theauth.Storage backed by Go maps protected by a sync.RWMutex.
Package memory provides an in-process implementation of theauth.Storage backed by Go maps protected by a sync.RWMutex.
mysql
Package mysql provides a MySQL 8.x-backed storage.Storage implementation using database/sql and github.com/go-sql-driver/mysql.
Package mysql provides a MySQL 8.x-backed storage.Storage implementation using database/sql and github.com/go-sql-driver/mysql.
postgres
Package postgres provides a production-grade implementation of theauth.Storage backed by PostgreSQL through pgx and sqlc-generated query bindings.
Package postgres provides a production-grade implementation of theauth.Storage backed by PostgreSQL through pgx and sqlc-generated query bindings.
Package storagetest provides a public contract test suite for theauth.Storage implementations.
Package storagetest provides a public contract test suite for theauth.Storage implementations.

Jump to

Keyboard shortcuts

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