theauth

package module
v2.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 70 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

████████╗██╗  ██╗███████╗ █████╗ ██╗   ██╗████████╗██╗  ██╗     ██████╗  ██████╗
╚══██╔══╝██║  ██║██╔════╝██╔══██╗██║   ██║╚══██╔══╝██║  ██║    ██╔════╝ ██╔═══██╗
   ██║   ███████║█████╗  ███████║██║   ██║   ██║   ███████║    ██║  ███╗██║   ██║
   ██║   ██╔══██║██╔══╝  ██╔══██║██║   ██║   ██║   ██╔══██║    ██║   ██║██║   ██║
   ██║   ██║  ██║███████╗██║  ██║╚██████╔╝   ██║   ██║  ██║    ╚██████╔╝╚██████╔╝
   ╚═╝   ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝ ╚═════╝    ╚═╝   ╚═╝  ╚═╝     ╚═════╝  ╚═════╝

OAuth 2.1 + MCP authorization for Go. Type-safe, dependency-light, FAPI-adjacent.

Go Reference Go Report Card Release CI codecov Go Postgres SLSA 3 SBOM Discord

go get github.com/glincker/theauth-go/v2

theauth-go is a Go library, not a hosted service. You mount it into your own net/http or chi server and it handles sign-in, sessions, API tokens, CLI login and an OAuth 2.1 / MCP authorization server, with your data in your own database. It runs as a single static binary with embedded SQLite, or against Postgres or MySQL.

30 second quickstart: net/http and SQLite

Needs Go 1.26 for storage/sqlite (its pure Go driver declares 1.26). The root module builds on Go 1.25.

go get github.com/glincker/theauth-go/v2 github.com/glincker/theauth-go/storage/sqlite
db, _ := sql.Open("sqlite", "file:app.db?_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_txlock=immediate")
_ = sqlitestore.Migrate(ctx, db)
store, _ := sqlitestore.New(db)

a, _ := theauth.New(theauth.Config{CoreStorage: store, BaseURL: "http://localhost:8080"})
defer a.Close()

mux := http.NewServeMux()
mux.Handle("/auth/", a.Handler()) // signup, signin, magic link, sessions; passkeys and TOTP when configured
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))
})))
http.ListenAndServe(":8080", mux)

Import sqlitestore "github.com/glincker/theauth-go/storage/sqlite" and _ "modernc.org/sqlite". Check errors in real code. For Postgres or chi, see Quick start.

What it does

  • Email and password (Argon2id), magic links, 12 OAuth login providers, WebAuthn passkeys, TOTP with recovery codes.
  • Opaque server-side sessions with step-up (RequireRecentAuth), session list and revoke, idle timeout.
  • Scoped API tokens with RequireAbility, and RFC 8628 device login for CLIs via the clientauth package (DeviceLogin, Whoami, Logout).
  • Agent tokens (MintAgentToken) and a revocation bus that long-lived connections can watch.
  • First-run bootstrap: a setup token gates creation of the first admin.
  • OAuth 2.1 authorization server, MCP authorization, agent identities with delegation, SAML, SCIM, RBAC, audit log.
  • Storage: memory, SQLite, Postgres, MySQL. Not every backend implements every capability, see the matrix.

Contents


Why theauth-go

theauth-go Auth0 better-auth Goth Hydra
License MIT Proprietary MIT MIT Apache 2.0
Self-hosted Yes No Yes Yes Yes
MCP authorization Yes No No No No
FAPI 2.0 adjacent (PAR+JAR+DPoP) Yes Partial No No Partial
DPoP-bound tokens Yes No No No No
SBOM + Sigstore signed Yes No No No No
Pluggable storage Yes No Partial No Yes
Go-native, single import Yes No No Yes No

theauth-go is the first Go auth library where OAuth 2.1, MCP authorization, agent identities, and revocable delegation chains ship in a single go get. It drops into a chi or net/http server in under twenty lines.


Features at a glance

Expand full feature list

OAuth 2.1 grants

  • Authorization code + PKCE S256 (mandatory)
  • Refresh token with rotation + family revocation on replay
  • client_credentials for service accounts and agents
  • RFC 8693 token exchange: scope narrowing, duration tightening, actor chain capped at 3
  • JWT bearer (RFC 7523)
  • CIBA: RFC 9509 backchannel authentication (Poll + Ping modes)
  • DPoP-bound access tokens (RFC 9449)
  • PAR: Pushed Authorization Requests (RFC 9126)
  • JAR: JWT-Secured Authorization Requests (RFC 9101)

MCP authorization

  • CIMD per MCP spec 2025-11-25
  • /.well-known/oauth-protected-resource (RFC 9728)
  • mcpresource SDK: zero-dependency module for MCP resource servers
  • Actor-chain walking via AS introspection
  • 401 with WWW-Authenticate: Bearer per RFC 6750 on failure

Authentication

  • Magic link sign-in
  • Email + password with Argon2id (OWASP 2026 defaults, 12-char minimum)
  • 12 OAuth providers: GitHub, Google, Microsoft, Discord, Facebook, Slack, GitLab, Bitbucket, Twitch, LinkedIn, X/Twitter, Apple
  • WebAuthn passkeys: discoverable login, sign-count replay protection, NIST SP 800-63B single-factor-strong
  • TOTP second factor with 10 single-use recovery codes and pending_2fa step-up state machine
  • SAML 2.0 Service Provider (per-organization IdP binding, signed assertions only)

Enterprise

  • SCIM 2.0: Users and Groups CRUD, RFC 7644 PATCH, per-org isolation
  • RBAC with closed permission catalog, seeded roles, RequirePermission middleware
  • Organization multi-tenancy with active_organization_id session scope
  • Audit logging: append-only, async, keyset pagination, pluggable SIEM sinks

Storage

Observability

  • 10 OpenTelemetry spans across hot paths
  • 10 Prometheus metrics (requests, errors, token issuances, latency histograms)
  • Pluggable adapters: bring your own OTel exporter or Prometheus registry

Security profile

  • FAPI 2.0-adjacent: PAR + JAR + JWT-Bearer + DPoP
  • Ed25519 JWT signing with 30-day JWKS rotation
  • RFC 8707 audience binding (mandatory)
  • RFC 9700 refresh-token rotation with replay detection
  • RFC 7591 dynamic client registration with bearer-gated initial access tokens
  • Per-IP and per-email rate limiting on every credential endpoint
  • HttpOnly, Secure, SameSite=Lax cookies; only SHA-256 hash persisted

Supply chain

  • SBOM generated on every release
  • Sigstore keyless signing via cosign
  • SLSA-3 provenance attestation
  • Verify with: cosign verify-blob --certificate-identity-regexp=".*" --certificate-oidc-issuer="https://token.actions.githubusercontent.com" <artifact>

Quick start

Requirements: Go 1.25+

go get github.com/glincker/theauth-go/v2

Step 1 -- Create an auth instance with in-memory storage:

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

a, err := theauth.New(theauth.Config{
    Storage: memory.New(),
    BaseURL: "http://localhost:8080", // used in magic-link emails
})

Step 2 -- Mount routes and protect your API:

import "github.com/go-chi/chi/v5"

r := chi.NewRouter()
a.Mount(r) // wires /auth/* (magic-link, email-password, OAuth, passkeys, TOTP, SAML, MCP)

r.With(a.RequireAuth()).Get("/dashboard", func(w http.ResponseWriter, r *http.Request) {
    user, _ := theauth.UserFromContext(r.Context())
    fmt.Fprintf(w, "Welcome %s", user.Email)
})

Step 3 -- Switch to Postgres for production:

import (
    "github.com/jackc/pgx/v5/pgxpool"
    "github.com/glincker/theauth-go/v2/storage/postgres"
)

pool, _ := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
a, _ := theauth.New(theauth.Config{
    Storage: postgres.New(pool), // automatic schema migration on first run
    BaseURL: "https://myapp.com",
})

Full runnable example: examples/chi-app/


MCP resource server

The mcpresource module is a zero-dependency Go module for MCP resource servers. It does not pull in theauth core or any storage adapter.

go get github.com/glincker/theauth-go/mcpresource
v := mcpresource.New(
    "https://mcp.example.com",
    mcpresource.WithJWKS("https://as.example.com/oauth/jwks"),
    mcpresource.WithIntrospection(
        "https://as.example.com/oauth/introspect",
        "mcp-client-id", "mcp-client-secret",
    ),
)

r := chi.NewRouter()
r.Use(v.Middleware) // JWT validation, audience check, actor-chain walk, revocation
r.Get("/tools/run", func(w http.ResponseWriter, r *http.Request) {
    p, _ := v.Principal(r.Context())
    // p.Subject (user), p.Actor (final agent), p.ActorChain (delegation path)
})

Full runnable example: examples/mcp-server/


Documentation

Getting Started Installation, quick start, choosing a storage backend
Concepts OAuth 2.1, MCP, PAR/JAR, JWT-Bearer, CIBA, DPoP
Guides Add an OAuth provider, enable passkeys, OTel tracing, SIEM audit streaming
Reference Config, Storage, Errors, Metrics, Spans
Security Threat model, SOC 2 mapping, GDPR data handling
Migrations Version upgrade guides
Releases and verification cosign verify-blob command for SBOM and signed artifacts

In-repo references:

Document Description
AGENTS.md Concise reference for AI coding assistants: patterns, anti-patterns, file map
STABILITY.md Public API surface, SemVer rules, Storage interface special rules
CHANGELOG.md Per-release notable changes following Keep a Changelog
ROADMAP.md In-flight work and known gaps
SECURITY.md Vulnerability disclosure policy and contact
CONTRIBUTING.md Dev setup, test commands, commit convention, PR process
MIGRATION.md Step-by-step upgrade guides between major versions

Examples

Example What it shows
examples/chi-app/ Magic links and email/password with chi
examples/echo-app/ Drop-in with Echo
examples/gin-app/ Drop-in with Gin
examples/stdlib-app/ Pure net/http, no framework
examples/single-binary-sqlite/ One static binary, SQLite, setup token, API tokens, device-login CLI (Go 1.26)
examples/mcp-server/ MCP resource server using mcpresource middleware
examples/oauth-multi-provider/ GitHub + Google + Microsoft + Discord in one app
examples/observability-otel/ OTel tracing and span export
examples/observability-prom/ Prometheus metrics scrape
examples/webauthn-passkey/ Passkey register and discoverable login
examples/totp-stepup/ Password + TOTP step-up flow
examples/oauth-apple/ Sign in with Apple (JWT client secret)
examples/oauth-gitlab/ Sign in with GitLab (self-hosted or gitlab.com)

Each example includes a README, main.go, go.mod, docker-compose.yml, .env.example, and Makefile.


Storage backends

Backend Path Use case
Memory storage/memory Development, unit tests, zero deps
SQLite storage/sqlite Single binary and single host, pure Go, own module (Go 1.26), no organizations, SAML, SCIM, RBAC or OAuth server
Postgres storage/postgres Production default, pgx/v5 + sqlc
MySQL storage/mysql MySQL 8.x alternative
Contract suite storagetest Verify your own custom backend

Bring your own storage backend by implementing the Storage interface and running the storagetest contract suite against it.


Security

Please do not open a public GitHub issue for security vulnerabilities.

Report to security@glincker.com or use GitHub Security Advisories.

See SECURITY.md for supported versions, disclosure policy, scope, and SLA targets.

Password policy

  • Minimum length: 12 characters, enforced at the library level (internal/password.MinPasswordLength, NIST 2024 baseline). Signup and password-change requests below this length return weak_password.
  • Hashing: Argon2id, using the parameter defaults from golang.org/x/crypto/argon2.
  • Anti-enumeration: a fixed-cost dummy Argon2id verify runs on user-not-found, so login timing doesn't reveal whether an email is registered.
  • The 12-character minimum is currently fixed at the package level; there is no Config field to override it yet.

FAQ

Is this production ready? Yes for v1.0+ surfaces (session auth, OAuth providers, RBAC, audit log), covered by STABILITY.md's SemVer contract. v2.0's OAuth 2.1 authorization server and agent-identity primitives are feature complete as of v2.0.0. Check CHANGELOG.md for the current release.

How does it compare to Auth0, better-auth, or Ory Hydra? See the comparison table above. The short version: theauth-go is self-hosted like better-auth/Hydra but also ships MCP authorization and FAPI 2.0-adjacent features (PAR+JAR+DPoP) that none of the alternatives have.

Does it support AI agent / MCP use cases specifically? Yes, this is one of the two things that differentiate it from every other Go auth library. See the MCP resource server section, and the agent-identity and delegation-chain docs.

What databases are supported? Postgres and MySQL, plus an in-memory backend for tests. The Storage interface is public, so custom backends are possible.

Is it free and open source? Yes, MIT licensed, no paid tier gating any feature in this repository.


Community

Join the GLINR Discord and talk to us in the #theauth forum channel.

Join the GLINR Discord


Contributing

See CONTRIBUTING.md for dev setup, test commands, commit convention, and PR process.

Short version:

git clone https://github.com/glincker/theauth-go.git
cd theauth-go
go test -race ./...
go vet ./...

Open an issue first for anything beyond a typo or one-file fix.


License

MIT


Built by the founder of theSVG.org.

A Product of GLINR STUDIOS

Documentation

Overview

Package theauth provides OAuth 2.1 and MCP authorization for Go applications, alongside magic-link, email/password, WebAuthn passkey, TOTP, SAML, and SCIM authentication.

TheAuth ships 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), RFC 9728 MCP resource server metadata, agent identities with revocable delegation chains, organization-scoped RBAC, and an async audit log. Storage backends include in-memory, Postgres (pgx), and MySQL. See docs/AGENTS.md or https://theauth.dev for the full feature list and quick start.

Index

Constants

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 (
	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 (
	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 GrantTypeCIBA = models.GrantTypeCIBA

GrantTypeCIBA is the CIBA grant type URN per RFC 9509.

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.

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

	// 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
)
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 DefaultSAMLAttributeMap = models.DefaultSAMLAttributeMap

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

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

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

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

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

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

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

	// 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
	// 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 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 DeviceAuthStart

type DeviceAuthStart = apitokens.DeviceAuthStart

Token, device and principal types.

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

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

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

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 or wrapping every endpoint at the HTTP boundary. All fields are optional; nil hooks are silent no-ops. Hooks run synchronously on the request goroutine after the underlying operation succeeds and before the HTTP response is written.

A non-nil error returned from a hook is logged at Warn level via slog and does NOT fail the request: the request that triggered the hook has already succeeded, and rolling back is not possible without coordinated storage transactions. Use hooks for fire-and-observe behavior (provisioning, analytics, notifications). For request-failing side effects, wrap at the handler boundary.

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

OnTokenIssued is the only hook permitted to mutate state: it receives the claims map about to be signed into a JWT access token and returns the updated map. Returning a non-nil error from OnTokenIssued does fail token issuance because the token has not yet been minted.

Wiring status (v2.5): every hook below is wired. OnSignup fires from password, magic-link, OAuth callback, SAML, and a user's first-ever WebAuthn credential (passkey registration has no true account-creation moment, so the first credential is the closest equivalent). OnSignin fires from password, magic-link, and OAuth callback. OnTokenIssued fires from every OAuth access-token grant. OnOrgSwitch fires only from the explicit SetActiveOrganization call, not from auto-provisioned personal orgs. OAuthConflictPayload is passed to LifecycleHooks.OnOAuthConflict when a sign-in OAuth email matches an existing user who registered via a different provider. The consumer creates a verification challenge and returns the URL the browser should be redirected to.

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 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 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 bcrypt fallback in VerifyPassword. When
	// true, hashes starting with "$2a$", "$2b$", or "$2x$" are verified with
	// golang.org/x/crypto/bcrypt. On a successful match the password is
	// transparently re-hashed with Argon2id; callers receive the new hash via
	// the OnLegacyHashAccepted callback so they can update storage
	// asynchronously. With false, a bcrypt hash fails as invalid credentials. Set to false (default) in all non-migration deployments.
	AllowLegacyBcrypt bool

	// 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 called (in the background) whenever a bcrypt
	// hash is successfully verified and the password has been re-hashed. The
	// caller receives (userID string, newArgon2idHash string). Persist the new
	// hash to storage to complete the upgrade. If nil, upgrades are silently
	// discarded (not recommended for production migration windows).
	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 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 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 Report

type Report = doctor.Report

Report is the result of TheAuth.Doctor.

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

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

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. (OnSignin is intentionally not fired here: per docs/ROADMAP.md it ships only for password, magic-link, and OAuth callback paths so far.)

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

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 (most attack-surface). All limits are in-memory + per-process; replace at the LB layer for multi-instance deploys.

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

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

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

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-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.
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-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.
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.
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.
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 serialiser (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 serialiser (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.
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.
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.
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/.
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 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