theauth

package module
v2.13.0 Latest Latest
Warning

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

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

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

README ¶

theAuth

theauth-go

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

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

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


What it is

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

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

Contents

Install

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

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

Verify releases

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

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

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

Packages

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

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

Modules on pkg.go.dev

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

The TypeScript packages are listed in the theAuth README.

Quick start: net/http and SQLite

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

package main

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

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

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

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

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

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

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

Quick start: agent identity and delegation

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

package main

import (
	"context"
	"log"

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

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

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

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

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

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

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

What you can build

Add sign-in to a Go web app

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

Run an OAuth 2.1 authorization server in Go

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

Secure an MCP server

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

Passkeys and WebAuthn

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

Device login for Go CLIs

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

SAML SSO and SCIM provisioning

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

Create a user for an existing identity

CreateUser adds a user row without sending email or creating a credential or session. It is idempotent on the normalized email, so calling it on every login of an external identity provider is safe, even concurrently. Typed errors match ErrUserInvalidInput, ErrUserEmailConflict and ErrUserIDConflict with errors.Is. Details: docs/create-user.md.

u, err := a.CreateUser(ctx, theauth.CreateUserInput{Email: "ada@example.com", Name: "Ada"})

Agent identity and delegation

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

Features

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

Running more than one replica

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

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

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

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

Choosing between a library and a hosted service

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

Storage backends

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

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

Postgres and MySQL implement the newer token, device, session and throttle capabilities and pass the new storagetest suites against live PostgreSQL 16 and MySQL 8. The full shared contract passes on Postgres when you opt in with THEAUTH_PG_CONTRACT=1 and a DSN in THEAUTH_TEST_PG_DSN (verified on PostgreSQL 14), but that gate is not enabled in CI yet. The MySQL gate is still off, so treat MySQL support for the newer features as newly added. You can write your own backend and verify it with the public storagetest suite.

Stability

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

Security

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

Migrating

FAQ

Does theauth-go work without Postgres? Yes. Use storage/sqlite for a single static binary with one database file, storage/memory for tests, or MySQL. SQLite supports organizations, SAML, SCIM and RBAC, and runs the OAuth 2.1 authorization server, agents and CIBA (migrations 0020 to 0034); see docs/storage-capabilities.md.

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

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

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

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

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

Examples

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

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

Made by GLINCKER, a GLINR STUDIOS company

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

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

Documentation ¶

Overview ¶

Package theauth is auth for AI agents and humans in Go. It embeds into a net/http or chi server and keeps all data in your own database (memory, SQLite, Postgres or MySQL). It provides an OAuth 2.1 authorization server with agent identities and delegation, and human login with passwords, passkeys, TOTP, OAuth, SAML, SCIM and RBAC.

Quick start:

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

See docs/AGENTS.md or https://docs.theauth.dev/go for the full feature list.

Index ¶

Constants ¶

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

Error codes the TypeScript library and client SDKs key on (IsCSRFRejected, IsRateLimited).

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
)
View Source
const (
	PrincipalSession = apitokens.PrincipalSession
	PrincipalToken   = apitokens.PrincipalToken
	ActorKindUser    = apitokens.ActorKindUser
	ActorKindAgent   = apitokens.ActorKindAgent
)
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
	// RevocationOrgMember means a user lost access to one organization (for example an org-scoped SCIM
	// deactivation); only credentials scoped to that organization are void.
	RevocationOrgMember = revocation.OrgMember
)
View Source
const (
	ConsentApprove          = internalas.ConsentApprove
	ConsentDeny             = internalas.ConsentDeny
	ConsentInteract         = internalas.ConsentInteract
	ConsentSourceRegistered = internalas.ConsentSourceRegistered
	ConsentSourceCIMD       = internalas.ConsentSourceCIMD
)
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

	// agents:admin and delegations:admin grant agent and delegation CRUD under /admin/v1 (seeded into
	// owner and admin roles).
	PermissionAgentsAdmin      = models.PermissionAgentsAdmin
	PermissionDelegationsAdmin = models.PermissionDelegationsAdmin

	// PermissionAccountLink and its siblings are user-scoped; admin overrides go through /admin/v1.
	PermissionAccountLink  = models.PermissionAccountLink
	PermissionAccountMerge = models.PermissionAccountMerge
)

The seeded permission catalog. Consumers extend it and never shrink it. New fails if a custom permission duplicates a seeded name with a different description. The list is intentionally finite; wildcards and ABAC are not supported.

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

	CodeTOTPRequired    = models.CodeTOTPRequired
	CodeInvalidTOTP     = models.CodeInvalidTOTP
	CodeAlreadyEnrolled = models.CodeAlreadyEnrolled
	CodeWebAuthn        = models.CodeWebAuthn

	CodeIdentityConflict = models.CodeIdentityConflict
	CodeStepUpRequired   = models.CodeStepUpRequired
	CodeLastAuthMethod   = models.CodeLastAuthMethod
)

Stable error codes callers can switch on. New endpoints return TheAuthError; older ones keep returning the sentinels.

View Source
const (
	// CodePasswordChangeRequired is returned at sign-in when the account must change its password.
	CodePasswordChangeRequired = models.CodePasswordChangeRequired
	// CodeAccountDisabled is returned at sign-in for a disabled account.
	CodeAccountDisabled = models.CodeAccountDisabled
	// CodeReauthRequired means the session needs a recent authentication.
	CodeReauthRequired = models.CodeReauthRequired
	// CodeSessionLimit means the concurrent session cap rejected the sign-in.
	CodeSessionLimit = models.CodeSessionLimit
	// CodeProviderGrantRevoked means the upstream provider rejected the refresh token.
	CodeProviderGrantRevoked = models.CodeProviderGrantRevoked
	// CodeProviderNoRefresh means the stored provider grant cannot be refreshed.
	CodeProviderNoRefresh = models.CodeProviderNoRefresh
)
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"
)
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
)
View Source
const (
	SigninStepFull         = password.SigninStepFull
	SigninStepTOTPRequired = password.SigninStepTOTPRequired
)
View Source
const (
	// GitHubActionsIssuerURL is the iss value of GitHub Actions OIDC tokens.
	GitHubActionsIssuerURL = "https://token.actions.githubusercontent.com"
	// GitHubActionsJWKSURL is the jwks_uri from GitHub's OIDC discovery document.
	GitHubActionsJWKSURL = GitHubActionsIssuerURL + "/.well-known/jwks"
)
View Source
const (
	AuthLevelFull       = models.AuthLevelFull
	AuthLevelPending2FA = models.AuthLevelPending2FA
)
View Source
const (
	AMRPassword     = models.AMRPassword
	AMROTP          = models.AMROTP
	AMRHardwareKey  = models.AMRHardwareKey
	AMRSoftwareKey  = models.AMRSoftwareKey
	AMRUserVerified = models.AMRUserVerified
	AMRMFA          = models.AMRMFA
	AMREmail        = models.AMREmail
	AMRFederated    = models.AMRFederated
	AMRSSO          = models.AMRSSO
)
View Source
const (
	OrgRoleOwner  = models.OrgRoleOwner
	OrgRoleAdmin  = models.OrgRoleAdmin
	OrgRoleMember = models.OrgRoleMember
)
View Source
const (
	AuditOrderAsc  = models.AuditOrderAsc
	AuditOrderDesc = models.AuditOrderDesc
)

Audit read orders for AuditQuery.Order.

View Source
const (
	JWKSStateNext     = models.JWKSStateNext
	JWKSStateCurrent  = models.JWKSStateCurrent
	JWKSStatePrevious = models.JWKSStatePrevious
	JWKSStateRetired  = models.JWKSStateRetired
)
View Source
const (
	ClientOwnerKindUser         = models.ClientOwnerKindUser
	ClientOwnerKindOrganization = models.ClientOwnerKindOrganization
	ClientOwnerKindAgent        = models.ClientOwnerKindAgent
	ClientOwnerKindAnonymous    = models.ClientOwnerKindAnonymous
)
View Source
const (
	ClientAuthSecretBasic = models.ClientAuthSecretBasic
	ClientAuthSecretPost  = models.ClientAuthSecretPost
	ClientAuthNone        = models.ClientAuthNone
)
View Source
const (
	GrantTypeAuthorizationCode = models.GrantTypeAuthorizationCode
	GrantTypeRefreshToken      = models.GrantTypeRefreshToken
	GrantTypeClientCredentials = models.GrantTypeClientCredentials
	GrantTypeTokenExchange     = models.GrantTypeTokenExchange
)
View Source
const (
	AgentStatusActive    = models.AgentStatusActive
	AgentStatusSuspended = models.AgentStatusSuspended
	AgentStatusRevoked   = models.AgentStatusRevoked
)
View Source
const (
	AgentCredentialKindSecret = models.AgentCredentialKindSecret
	AgentCredentialKindX509   = models.AgentCredentialKindX509
	AgentCredentialKindJWK    = models.AgentCredentialKindJWK
)
View Source
const (
	BackchannelStatusPending  = models.BackchannelStatusPending
	BackchannelStatusApproved = models.BackchannelStatusApproved
	BackchannelStatusDenied   = models.BackchannelStatusDenied
)
View Source
const (
	AccessTokenFormatJWT    = models.AccessTokenFormatJWT
	AccessTokenFormatOpaque = models.AccessTokenFormatOpaque
)
View Source
const (
	SubjectTypePublic   = models.SubjectTypePublic
	SubjectTypePairwise = models.SubjectTypePairwise
)
View Source
const (
	DeviceAuthPending  = models.DeviceAuthPending
	DeviceAuthApproved = models.DeviceAuthApproved
	DeviceAuthDenied   = models.DeviceAuthDenied
	DeviceAuthConsumed = models.DeviceAuthConsumed
)
View Source
const (
	DeviceStatusActive  = models.DeviceStatusActive
	DeviceStatusRevoked = models.DeviceStatusRevoked
)
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
	MetricAgentPolicyResolverErrors    = observability.MetricAgentPolicyResolverErrors
	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
)
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
)
View Source
const (
	SeverityCritical = doctor.SeverityCritical
	SeverityHigh     = doctor.SeverityHigh
	SeverityMedium   = doctor.SeverityMedium
	SeverityLow      = doctor.SeverityLow
	SeverityInfo     = doctor.SeverityInfo
)
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
	DoctorCookieDomain       = doctor.DoctorCookieDomain
	DoctorCookieNoneOpen     = doctor.DoctorCookieNoneOpen
	DoctorSecurityHeadersOff = doctor.DoctorSecurityHeadersOff
)
View Source
const (
	StepUpMethodPassword = "password"
	StepUpMethodTOTP     = "totp"
	StepUpMethodPasskey  = "passkey"
)
View Source
const (
	// VaultStatusActive means the credential can be used and refreshed.
	VaultStatusActive = "active"
	// VaultStatusNeedsReauth means the provider rejected the refresh token; the user must connect again.
	VaultStatusNeedsReauth = "needs_reauth"
)
View Source
const AgentSubjectPrefix = models.AgentSubjectPrefix

AgentSubjectPrefix is prepended to an agent ID in JWT sub and act.sub claims, so resource servers can tell agents from users without consulting storage.

View Source
const BackchannelStatusConsumed = "consumed"

BackchannelStatusConsumed marks an approved CIBA request whose tokens were already delivered.

View Source
const DeviceAttestationJoinToken = models.DeviceAttestationJoinToken

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

View Source
const GrantTypeCIBA = models.GrantTypeCIBA

GrantTypeCIBA is the CIBA grant type URN per RFC 9509.

View Source
const GrantTypeDeviceCode = models.GrantTypeDeviceCode

GrantTypeDeviceCode is the RFC 8628 grant type URN.

View Source
const MinPasswordLength = password.MinPasswordLength

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

View Source
const PasswordResetTTL = password.PasswordResetTTL

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

View Source
const (
	ResponseTypeCode = models.ResponseTypeCode
)
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
)
View Source
const TokenTypeIDJAG = models.TokenTypeIDJAG

TokenTypeIDJAG is the token type URN of an Identity Assertion JWT Authorization 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
)
View Source
var (
	ErrConsentTicketInvalid   = internalas.ErrConsentTicketInvalid
	ErrConsentDecisionInvalid = internalas.ErrConsentDecisionInvalid
)
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 keyset pagination cursor fails to decode.
	ErrBadCursor = models.ErrBadCursor

	// ErrBadAuditOrder is returned when AuditQuery.Order is neither "", "asc" nor "desc".
	ErrBadAuditOrder = models.ErrBadAuditOrder

	// ErrAuditOrderUnsupported is returned by QueryAudit when the query uses Order "asc", an Event
	// filter or a "c1." cursor and the storage backend does not declare AuditOrderSupported() true.
	ErrAuditOrderUnsupported = models.ErrAuditOrderUnsupported

	// ErrReplayDetected is returned by storage when a WebAuthn sign count does not strictly increase.
	// The library treats it as a clone attempt and refuses the login. Authenticators that never count
	// stay at zero and are handled by the caller.
	ErrReplayDetected = internalwebauthn.ErrReplayDetected

	// ErrAlreadyEnrolled is returned when TOTP enrollment finishes for a user who already has a
	// confirmed secret. The user must delete TOTP first to re-enroll.
	ErrAlreadyEnrolled = internaltotp.ErrAlreadyEnrolled

	// ErrSCIMRequiresOrganizations is returned by New when SCIM is set without Organizations, since
	// every SCIM token is bound to one organization.
	ErrSCIMRequiresOrganizations = errors.New("theauth: SCIM requires Organizations to be enabled")
	// ErrSAMLRequiresOrganizations is returned by New when SAML is set without Organizations; routing
	// keys off organization ownership.
	ErrSAMLRequiresOrganizations = errors.New("theauth: SAML requires Organizations to be enabled")
	// ErrSAMLUnsignedAssertion is returned by FinishSAMLLogin when the assertion parses but is not signed.
	ErrSAMLUnsignedAssertion = internalsaml.ErrSAMLUnsignedAssertion
	// ErrSAMLMissingEmail is returned by FinishSAMLLogin when the mapped email attribute is empty.
	ErrSAMLMissingEmail = internalsaml.ErrSAMLMissingEmail
	// ErrSAMLInvalidAssertion wraps the underlying crewjam/saml error for failed signature, condition
	// or replay checks.
	ErrSAMLInvalidAssertion = internalsaml.ErrSAMLInvalidAssertion
	// ErrLastOwner is returned when a member removal would leave the organization with zero owners.
	ErrLastOwner = models.ErrLastOwner
	// ErrUnsupportedFilter is returned by the SCIM filter parser for any shape outside the eq-only whitelist.
	ErrUnsupportedFilter = errors.New("theauth: scim filter not supported")
	// ErrSlugTaken is returned when the organization slug already exists.
	ErrSlugTaken = models.ErrSlugTaken

	// ErrAdminRequiresRBAC is returned by New when Admin is set without RBAC.
	ErrAdminRequiresRBAC = errors.New("theauth: Admin requires RBAC to be enabled")
	// ErrForbidden means the caller lacks a required permission. Handlers map it to 403 "rbac.forbidden".
	ErrForbidden = models.ErrForbidden
	// ErrUnknownPermission means the permission name is not in the catalog. Mapped to 400
	// "rbac.unknown_permission".
	ErrUnknownPermission = models.ErrUnknownPermission
	// ErrRoleInUse means a role delete would leave no user holding "users:admin". Mapped to 409
	// "rbac.role_in_use".
	ErrRoleInUse = models.ErrRoleInUse
	// ErrNoActiveOrg means the session has no active organization. Mapped to 403 "rbac.no_active_org".
	ErrNoActiveOrg = errors.New("theauth: session has no active organization")
	// ErrOrgMismatch means the session's active organization differs from the resource's. Mapped to
	// 403 "rbac.org_mismatch".
	ErrOrgMismatch = errors.New("theauth: session active organization does not match resource")
	// ErrRBACDisabled is returned by RBAC service methods when Config.RBAC is nil.
	ErrRBACDisabled = models.ErrRBACDisabled
)

Sentinel errors kept for v0.1 callers that errors.Is-check against them. New code should prefer TheAuthError and the Code* constants. Model-layer sentinels are defined in internal/models and re-exported here.

View Source
var (
	// ErrASRequiresEncryptionKey is returned by New when AuthorizationServer is set without a 32-byte
	// EncryptionKey. The key protects JWKS private keys at rest.
	ErrASRequiresEncryptionKey = models.ErrASRequiresEncryptionKey

	// ErrASIssuerRequired is returned by New when AuthorizationServer is set without an Issuer (RFC 8414).
	ErrASIssuerRequired = models.ErrASIssuerRequired

	// ErrASUnsupportedAlg is returned by New for any signing algorithm other than EdDSA.
	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 "invalid_grant": expired or replayed authorization codes and refresh tokens.
	ErrOAuthInvalidGrant = models.ErrOAuthInvalidGrant

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

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

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

	ErrOAuthInvalidAuthorizationDetails = models.ErrOAuthInvalidAuthorizationDetails

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

	// ErrOAuthRegistrationDenied is returned when DCR has no valid initial access token and
	// AllowAnonymousRegistration is false.
	ErrOAuthRegistrationDenied = models.ErrOAuthRegistrationDenied

	// ErrOAuthRedirectURIMismatch is returned when the token request's redirect_uri differs from the
	// one bound to the code.
	ErrOAuthRedirectURIMismatch = models.ErrOAuthRedirectURIMismatch

	// ErrOAuthPKCEMismatch is returned when code_verifier does not match the stored S256 challenge.
	ErrOAuthPKCEMismatch = models.ErrOAuthPKCEMismatch

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

	// ErrNotImplemented is returned by paths reserved for a later phase, such as agent credentials of
	// kind x509 or 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 that is suspended or revoked.
	ErrAgentInactive = models.ErrAgentInactive

	// ErrAgentExpired is returned when the agent is past its ExpiresAt. It matches ErrAgentInactive
	// under errors.Is; the wire code is agent_expired.
	ErrAgentExpired = models.ErrAgentExpired

	// ErrAgentExpiryInvalid is returned when a requested agent expiry is in the past or too far ahead.
	ErrAgentExpiryInvalid = models.ErrAgentExpiryInvalid

	// ErrDelegationNotFound is returned when no delegation grant matches the user, agent and resource.
	// Token exchange surfaces it as access_denied.
	ErrDelegationNotFound = models.ErrDelegationNotFound

	// ErrDelegationRevoked is returned when a delegation grant exists but is revoked. Introspection
	// reports active=false.
	ErrDelegationRevoked = models.ErrDelegationRevoked

	// ErrChainDepthExceeded is returned by token exchange when the actor chain would exceed
	// AgentConfig.MaxChainDepth.
	ErrChainDepthExceeded = models.ErrChainDepthExceeded

	ErrSubjectTokenInvalid = models.ErrSubjectTokenInvalid

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

	// ErrAgentRequiresAS is returned by New when AgentIdentity is set without AuthorizationServer.
	ErrAgentRequiresAS = models.ErrAgentRequiresAS

	ErrAgentChainDepthTooHigh = models.ErrAgentChainDepthTooHigh

	// ErrAccountUXRequiresAgents is returned by New when AccountUX is set without AgentIdentity.
	ErrAccountUXRequiresAgents = models.ErrAccountUXRequiresAgents

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

	// ErrStepUpRequired is returned by identity-linking methods when the session's AuthLevel is not
	// AuthLevelFull.
	ErrStepUpRequired = models.ErrStepUpRequired

	ErrLastAuthMethod = models.ErrLastAuthMethod

	// ErrCIBAAuthorizationPending is returned by PollBackchannelToken until the user approves or denies.
	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 = models.ErrCIBAInvalidRequest

	// ErrCIBADisabled is returned when CIBA is not enabled (no CIBA config, or storage lacks CIBAStorage).
	ErrCIBADisabled = models.ErrCIBADisabled

	ErrCIBAUserMismatch = models.ErrCIBAUserMismatch

	ErrDeviceAuthUserCodeTaken = models.ErrDeviceAuthUserCodeTaken

	ErrDeviceUserCodeInvalid = models.ErrDeviceUserCodeInvalid

	ErrDeviceTooManyAttempts = models.ErrDeviceTooManyAttempts

	ErrRegistrationTokenInvalid = models.ErrRegistrationTokenInvalid

	ErrRegistrationTokensDisabled = models.ErrRegistrationTokensDisabled

	ErrDeviceEnrollmentInvalid = models.ErrDeviceEnrollmentInvalid

	ErrDeviceConflict = models.ErrDeviceConflict

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

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

	ErrSessionLinkInvalid = models.ErrSessionLinkInvalid
)
View Source
var (
	// ErrUserInvalidInput means the email or another CreateUser field failed validation.
	ErrUserInvalidInput = &UserError{Code: "USER_INVALID_INPUT", Message: "invalid user input"}
	// ErrUserEmailConflict means the email is registered under a different user ID than requested.
	ErrUserEmailConflict = &UserError{Code: "USER_EMAIL_CONFLICT", Message: "email is registered under a different user id"}
	// ErrUserIDConflict means the requested user ID is already used by another email.
	ErrUserIDConflict = &UserError{Code: "USER_ID_CONFLICT", Message: "user id is already in use by another email"}
)
View Source
var (
	// ErrProviderGrantRevoked means the provider no longer honors the stored refresh token. The stored
	// tokens are cleared.
	ErrProviderGrantRevoked = models.ErrProviderGrantRevoked
	// ErrProviderRefreshUnsupported means the provider cannot refresh, or no refresh token is stored.
	ErrProviderRefreshUnsupported = models.ErrProviderRefreshUnsupported
	// ErrProviderNotLinked means the user has no linked account for the provider.
	ErrProviderNotLinked = models.ErrProviderNotLinked
)
View Source
var DefaultSAMLAttributeMap = models.DefaultSAMLAttributeMap

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

View Source
var ErrAccountStateDisabled = models.ErrAccountStateDisabled

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

View Source
var ErrAgentPolicyDenied = models.ErrAgentPolicyDenied

ErrAgentPolicyDenied is wrapped by every refusal caused by agent policy.

View Source
var ErrAgentRateLimit = errors.New("theauth: invalid AgentConfig.RateLimit")

ErrAgentRateLimit is the sentinel for an invalid AgentConfig.RateLimit.

View Source
var ErrAuditChainUnsupported = models.ErrAuditChainUnsupported

ErrAuditChainUnsupported is returned by VerifyAuditChain when the storage backend keeps no hash chain.

View Source
var ErrAuditUnavailable = audit.ErrAuditUnavailable

ErrAuditUnavailable is returned by EmitDecision in fail-closed mode when a decision event cannot be queued.

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.

View Source
var ErrGitHubActionsUnrestricted = errors.New("theauth: GitHubActionsIssuer needs Repository or RepositoryOwner: an unrestricted GitHub issuer lets any GitHub repository mint tokens")

ErrGitHubActionsUnrestricted is returned by GitHubActionsIssuer when neither Repository nor RepositoryOwner is set.

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 ErrInvalidClaimMatcher = internalas.ErrInvalidClaimMatcher

ErrInvalidClaimMatcher is returned by New (wrapped) for a misconfigured ClaimMatcher.

View Source
var ErrStorageMissingCapability = models.ErrStorageMissingCapability

ErrStorageMissingCapability is returned by New when an enabled feature needs a capability the storage lacks.

View Source
var ErrStorageMissingOAuthMethods = models.ErrStorageMissingOAuthMethods

ErrStorageMissingOAuthMethods is returned by New when Config.AuthorizationServer is set but Config.Storage does not satisfy OAuthServerStorage.

LatencyBuckets is the shared histogram layout for every _latency_seconds metric. Consumers pre-registering histograms must use this exact slice so bucket boundaries line up.

Functions ¶

func DefaultRedactor ¶

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

DefaultRedactor masks values for password, secret, token, code, refresh_token and access_token keys at any 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 the hex sha256 of the lowercased email.

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 an authorize error means an authenticated user is needed. Both packages share the sentinel, so existing errors.Is checks keep working.

func IsReauthRequired ¶ added in v2.10.0

func IsReauthRequired(err error) bool

IsReauthRequired reports whether a StartAuthorize error means the user must authenticate again (max_age or acr).

func MergeAuthMethods ¶ added in v2.11.0

func MergeAuthMethods(existing []string, add ...string) []string

MergeAuthMethods appends the methods in add that existing lacks (lowercased, order kept).

func NewMemoryOAuthStateStore ¶

func NewMemoryOAuthStateStore() *internaloauth.MemoryStateStore

NewMemoryOAuthStateStore returns the default in-process OAuthStateStore. Call Close when done.

func SeededSecretKeys ¶

func SeededSecretKeys() []string

SeededSecretKeys returns a copy of the key blocklist the default redactor applies.

func WithAuditMetadata ¶

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

WithAuditMetadata attaches an AuditMetadata to ctx; EmitAudit reads it.

func WithAuthContext ¶ added in v2.10.0

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

WithAuthContext returns a context carrying ac for StartAuthorize.

Types ¶

type APIToken ¶

type APIToken = apitokens.APIToken

func ImportAPITokenTo ¶

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

ImportAPITokenTo inserts an existing token by hash into store without a TheAuth instance. Abilities are checked for syntax only, since there is no configured allowlist.

type APITokenAgentStorage ¶ added in v2.11.0

type APITokenAgentStorage = apitokens.APITokenAgentStorage

type APITokenStorage ¶

type APITokenStorage = apitokens.APITokenStorage

type APITokensConfig ¶

type APITokensConfig = apitokens.Config

type ASMetadata ¶

type ASMetadata = internalas.ASMetadata

ASMetadata is the RFC 8414 document served at /.well-known/oauth-authorization-server.

type ASRateLimits ¶ added in v2.8.0

type ASRateLimits = internalas.RateLimits

ASRateLimits is the root alias for the AS endpoint limits.

type AccountDeleteStorage ¶ added in v2.10.0

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

AccountDeleteStorage is the optional capability behind account deletion. DeleteUserCascade removes the user and every row that belongs to it, so nothing is left behind.

type AccountDeletionConfig ¶ added in v2.10.0

type AccountDeletionConfig struct {
	RecentAuthMaxAge time.Duration
}

AccountDeletionConfig mounts DELETE /account for self-service deletion. Needs AccountDeleteStorage.

type AccountState ¶ added in v2.10.0

type AccountState = models.AccountState

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

type AccountStateStorage ¶ added in v2.10.0

type AccountStateStorage interface {
	AccountStateByUserID(ctx context.Context, userID ULID) (AccountState, error)
	SetMustChangePassword(ctx context.Context, userID ULID, required bool) error
	SetUserDisabledAt(ctx context.Context, userID ULID, at *time.Time) error
}

AccountStateStorage is the optional capability behind forced password change and account disable. Without it those features return ErrStorageMissingCapability and sign-in is unchanged.

type Actor ¶

type Actor = apitokens.Actor

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/* on the router passed to Mount when non-nil.

type AdmissionLimit ¶ added in v2.10.0

type AdmissionLimit struct {
	Max    int
	Window time.Duration
}

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

type AdmissionLimits ¶ added in v2.10.0

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

AdmissionLimits are the per-tier budgets: 30, 120 and 300 requests per 60 seconds by default.

type AdmissionOptions ¶ added in v2.10.0

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

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

type Agent ¶

type Agent = models.Agent

type AgentConfig ¶

type AgentConfig struct {
	// MaxChainDepth caps the actor chain length (default 3: root subject plus two agents). Operators may
	// lower it to 2 to disable sub-delegation, but New rejects values above 3 in v2.0.
	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 exp window for token-exchange tokens when the requester does not
	// narrow it (default 15 minutes).
	DefaultDelegatedTokenTTL time.Duration

	// AgentSecretLength is the entropy in bytes of generated agent secrets (default 32, 256 bits). Secrets
	// are stored hashed (Argon2id) and shown once, at creation or rotation.
	AgentSecretLength int

	// PolicyEngine, when set, evaluates the agent's IAM policies on every agent token mint. An explicit Deny
	// fails the mint with access_denied, scopes no Allow covers are narrowed away, and the policy ids and
	// hash go into the agent_policy claim and audit event. Build one with the agentpolicy package.
	PolicyEngine AgentPolicyEngine

	// RateLimit bounds how often each agent (keyed by agent id) may mint tokens or call AuthorizeAgent.
	// Over the limit the mint gets HTTP 429 with Retry-After. The zero value disables it.
	RateLimit AgentRateLimit

	// BeforeAuthorize, when set, runs an external guard or in process hook on every AuthorizeAgent
	// call the policy engine and rate limit allowed. A deny refuses the call with decision code
	// hook_denied, an escalate with approval_required, and a timeout (default 2s) or failure with
	// hook_timeout or hook_error: it fails closed. Nil, the default, changes nothing. See docs/hooks.md.
	BeforeAuthorize *AgentHookRunner
}

AgentConfig wires the agent-identity policy. Set it on Config.AgentIdentity to enable agents, delegations and token exchange. The zero value is valid and means accept-all defaults at New.

type AgentCredential ¶

type AgentCredential = models.AgentCredential

type AgentHookRunner ¶ added in v2.12.0

type AgentHookRunner = hook.Runner

AgentHookRunner runs AgentConfig.BeforeAuthorize: a before authorize hook or external guard with a timeout, panic recovery and fail closed. Build it with the policy/hook package, for example &hook.Runner{Hook: guard, Timeout: 1500 * time.Millisecond}.

type AgentOwner ¶

type AgentOwner = models.AgentOwner

type AgentPolicyDeniedError ¶ added in v2.11.0

type AgentPolicyDeniedError = models.AgentPolicyDeniedError

AgentPolicyDeniedError is returned when an agent's policy refuses an action. errors.Is(err, ErrAgentPolicyDenied) matches it.

type AgentPolicyEngine ¶ added in v2.11.0

type AgentPolicyEngine = agent.PolicyEngine

AgentPolicyEngine resolves and evaluates the policies attached to an agent. Hosts normally use the agentpolicy package rather than implementing it.

type AgentRateLimit ¶ added in v2.11.0

type AgentRateLimit struct {
	Requests int
	Per      time.Duration
	Burst    int
}

AgentRateLimit bounds how often one agent may mint tokens or call Authorize: Requests per Per, with Burst as the bucket size (default Requests). The zero value disables the limit.

func (AgentRateLimit) Normalize ¶ added in v2.11.0

func (r AgentRateLimit) Normalize() (AgentRateLimit, error)

Normalize applies defaults (Per one minute, Burst equal to Requests) and rejects negative values and a non-positive Requests. The zero value is invalid: use a nil pointer for "no override".

type AgentRateLimitedError ¶ added in v2.11.0

type AgentRateLimitedError = models.AgentRateLimitedError

AgentRateLimitedError is returned when an agent used up its budget.

type AgentRegistration ¶

type AgentRegistration = agent.Registration

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 AuditChainBreak ¶ added in v2.11.0

type AuditChainBreak = models.AuditChainBreak

AuditChainBreak locates the first row at which an audit chain fails to verify.

type AuditChainResult ¶ added in v2.11.0

type AuditChainResult = models.AuditChainResult

AuditChainResult is the outcome of VerifyAuditChain.

type AuditConfig ¶

type AuditConfig struct {
	// BufferSize is the channel buffer between EmitAudit and the writer goroutine (default 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 (default 1 second).
	FlushInterval time.Duration

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

	// DrainTimeout caps how long Close waits for the writer goroutine to drain (default 5 seconds).
	DrainTimeout time.Duration

	// Sinks are optional SIEM streaming destinations, fanned out after each successful storage write. A
	// failing sink is logged at Warn, counted in Stats.AuditSinkFailed and dropped, so sink failures never
	// block storage writes. Built-in sinks live in audit/sinks/.
	Sinks []AuditSink

	// FailClosed makes decision-class audit events fail closed: when one cannot be queued, EmitDecision
	// returns an error so the caller can deny the action. Off by default so audit pressure never blocks
	// request paths.
	FailClosed bool

	// DecisionActionPrefixes overrides the audit action prefixes treated as decision-class for FailClosed.
	DecisionActionPrefixes []string
}

AuditConfig configures the async audit writer. The zero value is valid.

type AuditEvent ¶

type AuditEvent = models.AuditEvent

type AuditMetadata ¶

type AuditMetadata = audit.AuditMetadata

AuditMetadata is an optional bundle attached to a context to override the auto-derived actor, org, IP and UA.

type AuditQuery ¶

type AuditQuery = models.AuditQuery

type AuditSink ¶

type AuditSink interface {
	Stream(ctx context.Context, batch []AuditEvent) error

	Name() string
}

AuditSink streams audit events to an external system. Sinks are best effort: a failed Stream never blocks canonical writes and is counted in Stats.AuditSinkFailed. Built-in sinks live under audit/sinks/ (otlp, splunkhec, webhook).

type AuditStorage ¶

type AuditStorage interface {
	// InsertAuditEvents writes a batch in one round trip. The log is append-only: adapters must not
	// expose UPDATE or DELETE for audit rows. On failure the writer logs and increments
	// Stats.AuditFailed without retrying (a documented tradeoff).
	InsertAuditEvents(ctx context.Context, events []AuditEvent) error
	QueryAuditEvents(ctx context.Context, q AuditQuery) (events []AuditEvent, nextCursor string, err error)
}

AuditStorage covers the append-only audit log.

type AuthContext ¶ added in v2.10.0

type AuthContext = internalas.AuthContext

AuthContext describes how the user authenticated (auth_time, amr). StartAuthorize callers that bypass the handler attach it with WithAuthContext so tokens carry auth_time, acr and amr.

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. Implementations must return quickly; panics are recovered.

func AuthEventChannelSink ¶

func AuthEventChannelSink(ch chan<- AuthEvent) AuthEventSink

AuthEventChannelSink returns an AuthEventSink that forwards to ch and drops events when ch is full (never blocks).

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 bridges the AS to a push delivery mechanism (FCM, APNs, SMS). See internal/as.AuthenticationDevice.

type AuthorizationCode ¶

type AuthorizationCode = models.AuthorizationCode

type AuthorizationServerConfig ¶

type AuthorizationServerConfig struct {
	// Issuer is the canonical https URL that becomes the iss claim on every JWT (no query or fragment).
	Issuer string

	// Resources lists the protected resources this AS advertises. Every authorize and token request must carry
	// a resource parameter matching one of them (RFC 8707, RFC 9068).
	Resources []ProtectedResource

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

	// KeyRotationPeriod is how often the JWKS rotation goroutine promotes keys (default 30 days).
	KeyRotationPeriod time.Duration

	// KeyRetention caps how long a retired key stays in /oauth/jwks (default 90 days).
	KeyRetention time.Duration

	// AccessTokenTTL caps the lifetime of access tokens (default 1 hour).
	AccessTokenTTL time.Duration

	// RefreshTokenTTL caps refresh token lifetime (default 30 days). Refresh tokens rotate on use; reuse of an
	// old one revokes the family (RFC 9700 section 4.14).
	RefreshTokenTTL time.Duration

	// AuthorizationCodeTTL caps authorization code lifetime (default 60 seconds, per OAuth 2.1).
	AuthorizationCodeTTL time.Duration

	// RegistrationAccessTokenTTL caps registration access tokens minted by POST /oauth/register
	// (default 365 days).
	RegistrationAccessTokenTTL time.Duration

	// AllowAnonymousRegistration permits POST /oauth/register without an initial access token. Off by
	// default; when on, the endpoint is pinned to 1 request per minute per IP and clients are stamped
	// AnonymousRegistered.
	AllowAnonymousRegistration bool

	// RegistrationTokens is the operator-supplied set of bearer initial access tokens accepted by POST
	// /oauth/register while DCR is bearer-gated (the default). Tokens are SHA-256 hashed at New and compared in
	// constant time. With no tokens and AllowAnonymousRegistration false, every registration gets 401
	// (security audit H1).
	RegistrationTokens []string

	// RegistrationRateLimitPerMinute caps POST /oauth/register per source IP. Defaults to 1 with
	// AllowAnonymousRegistration and 5 otherwise; negative disables the cap, which is not advised on a
	// public bind (security audit H2).
	RegistrationRateLimitPerMinute int

	// IntrospectionCacheTTL is the Cache-Control max-age emitted by the introspection endpoint
	// (default 60 seconds).
	IntrospectionCacheTTL time.Duration

	// SubjectActiveCacheTTL bounds how long a positive subject-active lookup (agent status, user disabled state)
	// is reused during introspection. Revocation events drop the entry at once; default 1 second, capped at 2,
	// negative disables.
	SubjectActiveCacheTTL time.Duration

	// Clock overrides the time source; see the Clock type.
	Clock Clock

	// LoginURL is where unauthenticated authorize requests redirect, with a next parameter (default
	// "/auth/login").
	LoginURL string

	// DisableRotation skips the background JWKS rotation goroutine. Tests use it to pin key state;
	// production must leave it false.
	DisableRotation bool

	// CIMD wires Client ID Metadata Documents. When non-nil, client_ids that parse as https URLs are
	// resolved by fetching their metadata instead of consulting storage. Nil falls back to RFC 7591
	// DCR. The default policy is DenyAll; operators opt in to AllowAnyHTTPS or AllowHTTPSHosts.
	CIMD *CIMDConfig

	// DPoP, when non-nil, enables RFC 9449 sender-constrained tokens: the token endpoint binds cnf.jkt
	// and resource servers re-verify the proof on every call, so a stolen token cannot be replayed
	// without the proof key.
	DPoP *DPoPConfig

	// RequireState makes /oauth/authorize reject requests without a non-empty state parameter
	// (invalid_request). Default false for compatibility; browser clients should enable it for CSRF
	// protection (security re-audit L5).
	RequireState bool

	// AccessTokenRevocation enables the store-backed access-token jti denylist (opt-in). Revocation,
	// code replay and token exchange honor it, and introspection reports revoked tokens inactive.
	// Local JWT verifiers never consult it and must introspect. Default false keeps access tokens
	// stateless.
	AccessTokenRevocation bool

	// ClientCompat relaxes strictness checks so real-world MCP clients (Claude Desktop, Cursor,
	// ChatGPT) interoperate. Every switch defaults to strict; LoopbackAnyPort and DropUnknownScopes
	// carry real tradeoffs (see docs/client-compat.md).
	ClientCompat ClientCompatConfig

	// ACRValues maps a sorted, "+"-joined amr method set (for example "pwd" or "otp+pwd") to the acr
	// claim (RFC 9470 step-up). Missing entries use urn:theauth:acr:1fa for one method and
	// urn:theauth:acr:mfa otherwise.
	ACRValues map[string]string

	// SessionAMR overrides the RFC 8176 methods used for the amr and acr claims. By default it is
	// Session.AuthMethods (sessions with no record assume ["pwd"]). A non-empty result wins; called on
	// /oauth/authorize only.
	SessionAMR func(ctx context.Context, sess *Session) []string

	// CORS opts the discovery and OAuth endpoints in to browser cross-origin access (allow list,
	// exact origin match). The zero value sends no CORS headers. See docs/oauth-cors.md.
	CORS CORSConfig

	// PAR wires RFC 9126 pushed authorization requests. When non-nil and the storage implements PARStorage,
	// POST /oauth/par is mounted and authorize accepts request_uri. Nil disables PAR.
	PAR *PARConfig

	// JAR wires RFC 9101 signed request objects on /oauth/authorize and /oauth/par. Nil disables JAR.
	JAR *JARConfig

	// JWTBearer enables RFC 7523 features: private_key_jwt and client_secret_jwt client authentication
	// at the token endpoint (section 2.2), and the jwt-bearer grant that exchanges JWTs from trusted
	// external issuers (section 2.1). Nil disables both.
	JWTBearer *JWTBearerConfig

	// CIBA enables RFC 9509 backchannel authentication when non-nil. Endpoints mount only if storage
	// implements CIBAStorage.
	CIBA *CIBAConfig

	// DeviceAuthorization enables the RFC 8628 device grant when non-nil. Storage must implement
	// DeviceAuthorizationStorage (memory, SQLite, Postgres and MySQL do); clients opt in by
	// registering the device_code grant.
	DeviceAuthorization *DeviceAuthorizationConfig

	// TokenPolicy enables per-client extra signing algorithms (ES256, RS256) and opaque reference
	// tokens. Nil keeps every client on EdDSA JWTs. Opaque tokens need OpaqueTokenStorage.
	TokenPolicy *TokenPolicyConfig

	// RAR enables RFC 9396 authorization_details on authorize, PAR, JAR and the token endpoint. Nil
	// rejects the parameter.
	RAR *RARConfig

	// IDJAG enables Identity Assertion JWT Authorization Grants through token exchange and their
	// redemption at the jwt-bearer grant (which also needs JWTBearer). Nil disables both.
	IDJAG *IDJAGConfig

	// RateLimits tunes the per-IP and per-client limits on the AS endpoints and the cap on concurrent Argon2id
	// client-secret verifications. Nil applies the defaults; set a field negative to turn it off.
	RateLimits *ASRateLimits

	// RegistrationTokenTTL is the default lifetime of an initial access token (default 24h).
	RegistrationTokenTTL time.Duration

	// DeviceTokens enables constrained device identity when non-nil: join tokens, enrollment at
	// /oauth/devices/enroll, and the jwt-bearer grant for registered devices (short-lived tokens, no
	// refresh). Storage must implement DeviceIdentityStorage.
	DeviceTokens *DeviceTokensConfig

	// OIDC turns the server into an OpenID Provider when non-nil. See docs/oidc-provider.md.
	OIDC *OIDCConfig

	// ConsentHandler hands the consent decision to the host app, after authentication and request
	// validation. It returns Approve (optionally with narrowed scopes and a grant expiry), Deny, or
	// Interact (render the host's consent page, then resume with TheAuth.CompleteConsent). Nil keeps
	// auto-approve. See docs/oauth-consent.md.
	ConsentHandler ConsentHandler

	// ConsentMaxGrantTTL caps the lifetime of a grant approved through ConsentHandler. Zero means no extra cap.
	ConsentMaxGrantTTL time.Duration

	// ConsentTicketTTL is the validity of a consent_ticket (default 10m).
	ConsentTicketTTL time.Duration
}

AuthorizationServerConfig wires the OAuth 2.1 and MCP authorization server. Set it on Config.AuthorizationServer to mount /.well-known/ and /oauth/ routes; nil keeps v1.0 behavior.

type AuthorizeRequest ¶

type AuthorizeRequest = internalas.AuthorizeRequest

AuthorizeRequest is the parsed GET /oauth/authorize query. PKCE is required; response_type must be "code" and code_challenge_method must be "S256" (OAuth 2.1 forbids the implicit and password flows).

type AuthorizeResult ¶

type AuthorizeResult = internalas.AuthorizeResult

AuthorizeResult is the redirect URL to send the user agent to after a successful authorize call.

type BackchannelRedeemer ¶ added in v2.11.0

type BackchannelRedeemer interface {
	RedeemBackchannelRequest(ctx context.Context, authReqID string, now time.Time) (BackchannelRequest, bool, error)
}

BackchannelRedeemer is an optional CIBAStorage capability that makes token delivery single use. RedeemBackchannelRequest atomically moves an approved, unexpired request to consumed and returns its tokens. Exactly one concurrent caller gets ok == true. Without it the AS uses an in-process lock, correct only on one node; multi-node needs this capability.

type BackchannelRequest ¶

type BackchannelRequest = models.BackchannelRequest

BackchannelRequest is the persistent record for one CIBA flow.

type BootstrapConfig ¶

type BootstrapConfig = bootstrap.Config

BootstrapConfig gates creation of the first user behind a one-time setup token (the storage must implement UserCountStorage). While no user exists, password signup needs the token in the X-Setup-Token header or a "setupToken" body field. Afterwards signup is refused with CodeSignupClosed unless OpenSignupAfterFirstUser is set. Magic-link signup cannot present a token, so the first admin signs up with a password.

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

	DefaultExpiry time.Duration

	DefaultInterval time.Duration

	MaxRequestedExpiry time.Duration

	MinPollInterval time.Duration
}

CIBAConfig wires CIBA on the authorization server. Leave nil (the default) to disable it.

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(ctx context.Context, req BackchannelRequest) error

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

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

	DeleteBackchannelRequest(ctx context.Context, authReqID string) error

	TouchBackchannelPoll(ctx context.Context, authReqID string, now time.Time, newInterval int) (BackchannelRequest, error)
}

CIBAStorage is the optional persistence for CIBA. Without it /oauth/bc-authorize is not mounted. Memory and Postgres implement it; custom adapters must add these methods before enabling Config.AuthorizationServer.CIBA.

type CIMDConfig ¶

type CIMDConfig = cimd.Config

CIMDConfig wires the CIMD service onto the AS. The default trust policy is DenyAll (fail-closed).

type CIMDTrustPolicy ¶

type CIMDTrustPolicy = cimd.TrustPolicy

CIMDTrustPolicy decides which https client_id URLs the AS may fetch as CIMD documents.

func AllowAnyHTTPS ¶

func AllowAnyHTTPS() CIMDTrustPolicy

AllowAnyHTTPS permits every absolute https URL. Use it only when federating with the open MCP ecosystem; known clients should prefer AllowHTTPSHost.

func AllowHTTPSHost ¶

func AllowHTTPSHost(host string) CIMDTrustPolicy

AllowHTTPSHost permits one host (case-insensitive, exact match).

func AllowHTTPSHosts ¶

func AllowHTTPSHosts(hosts ...string) CIMDTrustPolicy

AllowHTTPSHosts permits any of the hosts (case-insensitive, exact match). An empty list denies everything, so a typo cannot silently allow every host.

func DenyAll ¶

func DenyAll() CIMDTrustPolicy

DenyAll returns a CIMDTrustPolicy that rejects every URL. It is the fail-closed default: trust must be explicit.

type CORSConfig ¶ added in v2.12.0

type CORSConfig = internalas.CORSConfig

CORSConfig is the root alias for as.CORSConfig. The zero value sends no CORS headers.

type ClaimMatcher ¶ added in v2.11.0

type ClaimMatcher = internalas.ClaimMatcher

ClaimMatcher requires one claim of a verified jwt-bearer assertion to satisfy exactly one operator (Equals, OneOf, Pattern or Present).

type ClientCompatConfig ¶ added in v2.10.0

type ClientCompatConfig = internalas.ClientCompat

ClientCompatConfig is the root alias for as.ClientCompat. The zero value is fully strict.

type ClientOwner ¶

type ClientOwner = models.ClientOwner

type ClientRegistrationRequest ¶

type ClientRegistrationRequest = internalas.ClientRegistrationRequest

ClientRegistrationRequest is the parsed JSON body of POST /oauth/register (RFC 7591 field names).

type Clock ¶

type Clock interface {
	Now() time.Time
}

Clock is the time source for the introspection cache and chain-cache TTL. Tests inject a fake clock to assert revocation deterministically.

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
	// enabled features need. New returns ErrStorageMissingCapability when a feature needs more.
	CoreStorage CoreStorage

	EmailSender email.Sender
	BaseURL     string
	// PathPrefix is the route prefix Mount and Handler serve under (default "/auth"). It must start
	// with "/" and not end with one.
	PathPrefix string
	SigningKey ed25519.PrivateKey
	SessionTTL time.Duration
	// SessionIdleTimeout expires a session unused for this long; zero disables it. Needs
	// SessionManagementStorage.
	SessionIdleTimeout time.Duration
	// SessionTouchInterval throttles last-seen writes (default 1m; negative disables). Must be shorter
	// than SessionIdleTimeout.
	SessionTouchInterval time.Duration
	StepUpTTL            time.Duration
	// SessionLinks enables programmatic session links when non-nil. Needs SessionLinkStorage and
	// SessionManagementStorage.
	SessionLinks *SessionLinksConfig
	MagicLinkTTL time.Duration
	CookieName   string
	// SecureCookie forces the Secure attribute on session cookies. It defaults to true when BaseURL is
	// https; otherwise Secure is still set per request when the connection is TLS or a trusted proxy
	// sent X-Forwarded-Proto: https.
	SecureCookie bool
	// SuppressSecureCookieWarning silences the startup WARN logged when SecureCookie is false. Use it
	// only for local dev without TLS.
	SuppressSecureCookieWarning bool
	// Cookies tunes the attributes of every cookie the library writes (session, trusted device, OAuth
	// state, WebAuthn challenge). The zero value keeps the historic behavior. See CookiesConfig.
	Cookies CookiesConfig
	// SecurityHeaders adds Strict-Transport-Security (https requests only), X-Content-Type-Options,
	// Referrer-Policy and X-Frame-Options to every response served through Mount or Handler. It is off
	// by default so an embedding application keeps control of its own headers.
	SecurityHeaders bool
	// RateLimitPerIP is the per-IP per-minute budget for credential endpoints (default 5).
	RateLimitPerIP int
	// RateLimitPerEmail is the per-email per-minute budget for signin and forgot (default 3).
	RateLimitPerEmail int

	// TrustedProxies lists reverse-proxy networks whose X-Forwarded-For is trusted by the rate limiter
	// and the audit IP capture. Default empty (no XFF trust); deployments that depend on XFF must list
	// their proxy CIDRs (security audit H4). For a single-host load balancer pass a /32 (or /128)
	// prefix.
	TrustedProxies []netip.Prefix

	// Stores plugs in shared state backends: the rate limiters, the DPoP replay cache and the CIMD
	// cache. Nil fields keep per-replica in-process defaults. Behind several replicas, use a shared
	// adapter (see the kv package).
	Stores kv.Stores

	// TrustedOrigins lists extra origins (scheme://host[:port]) allowed to send cookie-authenticated
	// state-changing requests. The BaseURL origin is always trusted.
	TrustedOrigins []string

	// DisableCSRFProtection turns off the Origin/Referer check on cookie-authenticated unsafe methods.
	// Leave false unless a fronting layer enforces it.
	DisableCSRFProtection bool

	// Admission, when set, runs the Admission middleware ahead of every route Mount and Handler
	// register. It stacks with the per-route credential limits.
	Admission *AdmissionOptions

	// ErrorResponder, when set, writes every error response the root middleware produces, so an app
	// can emit its own envelope. status is the HTTP status, code the stable machine code and message
	// the text. The WWW-Authenticate header is already set on a 401. Nil keeps the built-in RFC 7807
	// bodies.
	ErrorResponder func(w http.ResponseWriter, r *http.Request, status int, code, message string)

	// SuppressTrustedProxiesWarning silences the startup WARN logged when TrustedProxies is empty.
	SuppressTrustedProxiesWarning bool

	// Providers is the list of OAuth providers exposed under /auth/providers/{name}/start and
	// /callback. Nil disables OAuth. Each Name() must be unique.
	Providers []Provider

	// ProviderResolver supplies OAuth/OIDC providers 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 with it.
	ProviderResolver      ProviderResolver
	ProviderResolverFirst bool
	// ProviderResolverTTL caches resolver answers, including "not found". Zero disables caching; use
	// InvalidateProvider to drop an entry early.
	ProviderResolverTTL time.Duration

	// EncryptionKey is the 32-byte AES-256 key that encrypts provider tokens before storage. Required
	// when Providers is non-empty. Source it from a secrets manager; never commit it.
	EncryptionKey []byte

	// PostLoginRedirect is where the OAuth callback redirects after sign-in (default "/"). Set a path
	// on your own origin.
	PostLoginRedirect string

	// APITokens enables scoped API tokens, RequireAbility and, via its Device field, the device grant.
	APITokens *APITokensConfig

	// WebAuthn enables passkey registration and discoverable login when non-nil.
	WebAuthn *WebAuthnConfig

	OAuth *OAuthConfig

	// AuthEventSink, when set, receives every security-relevant authentication event as a PII-minimal AuthEvent.
	// It is independent of Config.Audit.
	AuthEventSink AuthEventSink

	// SharedSignals enables the OpenID Shared Signals Framework 1.0 transmitter and optional receiver. Requires
	// AuthorizationServer. See docs/shared-signals.md.
	SharedSignals *SharedSignalsConfig

	// TOTP enables time-based second-factor enrollment. Requires EncryptionKey so the secret is
	// encrypted at rest.
	TOTP *TOTPConfig

	// Organizations enables multi-tenancy when non-nil. Organization-scoped routes are not mounted otherwise.
	Organizations *OrganizationsConfig

	// SAML enables the per-connection Service Provider routes when non-nil. The SP keypair lives here
	// so it can rotate centrally. Requires Organizations.
	SAML *SAMLConfig

	// SCIM enables the /scim/v2 endpoints when non-nil. Requires Organizations.
	SCIM *SCIMConfig

	// RBAC enables organization-scoped role and permission management when non-nil. Consumers extend,
	// never shrink, the seeded lists. New fails if Admin is set without RBAC, since admin endpoints
	// are permission-gated.
	RBAC *RBACConfig

	// Audit enables the async batched audit writer when non-nil. When nil, EmitAudit is a silent no-op.
	Audit *AuditConfig

	// Admin mounts /admin/v1/* when non-nil. Requires RBAC.
	Admin *AdminConfig

	// AuthorizationServer enables the OAuth 2.1 and MCP authorization server, mounting the
	// /.well-known and /oauth routes. Requires EncryptionKey (32 bytes) and a Storage implementing
	// OAuthServerStorage.
	AuthorizationServer *AuthorizationServerConfig

	// AgentIdentity enables the agent identity service, the client_credentials grant, delegation
	// grants and RFC 8693 token exchange on /oauth/token. Requires AuthorizationServer. Defaults are
	// applied at New.
	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 mounts /account/agents and /account/delegations. Requires AgentIdentity. Routes use
	// session auth only and manage the user's own agents and delegations.
	AccountUX bool

	// Observability optionally wires consumer-supplied Tracer and Metrics adapters. Nil uses no-op
	// adapters, which keeps OpenTelemetry and other vendor SDKs out of this module. See
	// examples/observability-otel and observability-prom.
	Observability *Hooks

	// PasswordPolicy controls optional extensions to password verification. The zero value disables them all.
	PasswordPolicy PasswordPolicyConfig

	// LifecycleHooks lets consumers react to authentication lifecycle events without forking handlers.
	// Nil is a no-op. See the LifecycleHooks type for semantics.
	LifecycleHooks *LifecycleHooks

	// Tenancy opts into tenant provisioning. When Tenancy.AutoCreatePersonalOrg is true and
	// Organizations is set, each signup creates a personal organization owned by the user and makes it
	// active.
	Tenancy *TenancyConfig

	// LoginThrottle tunes password-login backoff, per-user lockout and the TOTP attempt limit. Nil
	// selects safe defaults.
	LoginThrottle *LoginThrottleConfig

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

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

	// AccountState enforces per-user lifecycle flags (forced password change, disabled users) at every
	// sign-in. Needs AccountStateStorage.
	AccountState bool

	// AccountDeletion mounts DELETE /account when non-nil. The session must have authenticated recently.
	AccountDeletion *AccountDeletionConfig

	SessionPolicy *SessionPolicy

	TrustedDevices *TrustedDevicesConfig
	// contains filtered or unexported fields
}

Config holds the wiring for a TheAuth instance. BaseURL and exactly one of Storage or CoreStorage are required; New applies the other defaults. SigningKey is reserved for future JWT signing (v0.1 uses opaque tokens).

type ConsentAction ¶ added in v2.11.0

type ConsentAction = internalas.ConsentAction

ConsentHandler, ConsentRequest, ConsentDecision and friends are the root aliases for the host-owned consent API.

type ConsentClient ¶ added in v2.11.0

type ConsentClient = internalas.ConsentClient

ConsentHandler, ConsentRequest, ConsentDecision and friends are the root aliases for the host-owned consent API.

type ConsentDecision ¶ added in v2.11.0

type ConsentDecision = internalas.ConsentDecision

ConsentHandler, ConsentRequest, ConsentDecision and friends are the root aliases for the host-owned consent API.

type ConsentHandler ¶ added in v2.11.0

type ConsentHandler = internalas.ConsentHandler

ConsentHandler, ConsentRequest, ConsentDecision and friends are the root aliases for the host-owned consent API.

type ConsentRequest ¶ added in v2.11.0

type ConsentRequest = internalas.ConsentRequest

ConsentHandler, ConsentRequest, ConsentDecision and friends are the root aliases for the host-owned consent API.

type CookiesConfig ¶ added in v2.12.0

type CookiesConfig struct {
	// Domain shares the cookies with every subdomain of the given host (for example "example.com").
	// Empty keeps them host-only. A Domain cookie can be overwritten by any sibling subdomain, so
	// prefer leaving it empty. It cannot be combined with Prefix "host".
	Domain string
	// SameSite is "lax" (default), "strict" or "none". "none" requires Secure. "strict" is applied
	// to the session, device and WebAuthn cookies; the OAuth state cookie stays Lax because the
	// provider callback is a cross-site navigation that Strict would not carry the cookie on.
	SameSite string
	// Partitioned adds the CHIPS Partitioned attribute (cookies keyed to the top-level site). It
	// requires Secure and is meant for SameSite "none" in embedded third-party contexts.
	Partitioned bool
	// Prefix adds a browser-enforced name prefix to the session cookie: "secure" gives __Secure-,
	// "host" gives __Host- (Secure, Path=/, no Domain). Empty adds none. A CookieName that already
	// starts with the prefix is left alone, and the prefix rules are enforced either way. Both
	// modes require Secure (Config.SecureCookie or an https BaseURL).
	Prefix string
}

CookiesConfig tunes the attributes of every cookie the library writes. HttpOnly and Path are not configurable, and Secure follows Config.SecureCookie and BaseURL. The zero value keeps the historic behavior: host-only, SameSite=Lax, not Partitioned, no name prefix. New rejects an invalid combination at startup.

type CoreStorage ¶

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

type Counter ¶

type Counter = observability.Counter

Counter is a monotonic counter.

type CreateAgentInput ¶

type CreateAgentInput = models.CreateAgentInput

type CreateDeviceJoinTokenInput ¶ added in v2.10.0

type CreateDeviceJoinTokenInput = internalas.CreateDeviceJoinTokenInput

CreateDeviceJoinTokenInput describes a device join token to mint.

type CreateRegistrationTokenInput ¶ added in v2.8.0

type CreateRegistrationTokenInput = internalas.CreateRegistrationTokenInput

CreateRegistrationTokenInput describes an initial access token to mint.

type CreateUserInput ¶ added in v2.12.0

type CreateUserInput struct {
	// Email is required. It is validated and stored in the canonical form of NormalizeEmail.
	Email string
	// Name is an optional display name, at most 256 bytes after trimming.
	Name string
	// ID optionally fixes the user ID, for example to match your own identity provider. The zero
	// value means generate one.
	ID ULID
}

CreateUserInput is the input to TheAuth.CreateUser.

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; other errors fail 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 client IDs that must present a DPoP proof on every token request
	// (400 otherwise).
	RequireDPoPForClients []string

	// AllowedSignAlgs whitelists proof signing algorithms (default ES256, ES384, RS256, PS256, EdDSA).
	// HMAC and "none" are always rejected per RFC 9449 section 4.2.
	AllowedSignAlgs []string

	// ProofMaxAge bounds how far from now a proof's iat may be (default 60 seconds; much above 5
	// minutes weakens protection).
	ProofMaxAge time.Duration

	// NonceTTL bounds how long an issued DPoP-Nonce stays acceptable (default 10 minutes).
	NonceTTL time.Duration

	// RequireNonceForTokens makes the token endpoint demand a nonce on every proof (400 use_dpop_nonce
	// on the first call). Off by default; enable it for an AS exposed to untrusted clients to bound
	// proof replay.
	RequireNonceForTokens bool

	// NonceSecret is the HMAC-SHA256 key that mints and verifies DPoP-Nonce values. Empty generates a
	// random key at startup; set a stable value when several AS instances sit behind a load balancer.
	NonceSecret []byte

	// JTIReplayWindow caps the in-memory jti LRU used to reject replayed proofs within ProofMaxAge
	// (default 4096; 0 means default).
	JTIReplayWindow int
}

DPoPConfig configures the RFC 9449 DPoP verifier shared by the authorization server and mcpresource. Fields are optional and defaulted by New; the shape matches the internal dpop.Config.

type DelegationGrant ¶

type DelegationGrant = models.DelegationGrant

type Device ¶ added in v2.10.0

type Device = models.Device

Device is a registered constrained device (see DeviceTokensConfig).

type DeviceAuthStart ¶

type DeviceAuthStart = apitokens.DeviceAuthStart

type DeviceAuthorization ¶ added in v2.8.0

type DeviceAuthorization = models.DeviceAuthorization

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

type DeviceAuthorizationConfig ¶ added in v2.8.0

type DeviceAuthorizationConfig = internalas.DeviceConfig

DeviceAuthorizationConfig is the root alias for the RFC 8628 settings.

type DeviceAuthorizationStorage ¶ added in v2.8.0

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

DeviceAuthorizationStorage is the optional persistence for the RFC 8628 device grant. Decide and Consume are conditional updates that report whether they applied.

type DeviceCode ¶

type DeviceCode = apitokens.DeviceCode

type DeviceCodeLister ¶

type DeviceCodeLister = apitokens.DeviceCodeLister

type DeviceCodeStorage ¶

type DeviceCodeStorage = apitokens.DeviceCodeStorage

type DeviceConfig ¶

type DeviceConfig = apitokens.DeviceConfig

type DeviceDecision ¶

type DeviceDecision = apitokens.DeviceDecision

type DeviceIdentityStorage ¶ added in v2.10.0

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

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

DeviceIdentityStorage is the optional persistence for constrained devices and their join tokens.

type DeviceJoinToken ¶ added in v2.10.0

type DeviceJoinToken = models.DeviceJoinToken

DeviceJoinToken is a single-use device enrollment token.

type DevicePage ¶ added in v2.8.0

type DevicePage = internalas.DevicePage

DevicePage is the view model handed to DeviceAuthorizationConfig.Page.

type DevicePendingFilter ¶

type DevicePendingFilter = apitokens.DevicePendingFilter

type DeviceRequestInfo ¶

type DeviceRequestInfo = apitokens.DeviceRequestInfo

type DeviceRequestSummary ¶

type DeviceRequestSummary = apitokens.DeviceRequestSummary

type DeviceToken ¶

type DeviceToken = apitokens.DeviceToken

type DeviceTokensConfig ¶ added in v2.10.0

type DeviceTokensConfig = internalas.DeviceTokensConfig

DeviceTokensConfig is the root alias for the device identity settings.

type DoctorAdminLister ¶

type DoctorAdminLister interface {
	ListAdminUserIDs(ctx context.Context) ([]ULID, error)
}

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

type DoctorSessionCounter ¶

type DoctorSessionCounter interface {
	CountExpiredSessions(ctx context.Context, before time.Time) (int, error)
}

DoctorSessionCounter is the optional storage capability that counts expired but unpruned sessions.

type EmailMapper ¶

type EmailMapper struct {
	// Lookup finds a user by 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. Lookup must be set; the AS wires Storage.UserByEmail. Returns ErrStorageNotFound when no such user exists.

func (EmailMapper) Resolve ¶

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

Resolve returns the local user ULID for the supplied claim map, or ErrStorageNotFound when no mapping exists.

type EnrollTOTPResult ¶

type EnrollTOTPResult = totp.EnrollResult

EnrollTOTPResult is returned by BeginTOTPEnrollment for the caller to render.

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 GitHubActionsOptions ¶ added in v2.11.0

type GitHubActionsOptions struct {
	Repository      string
	RepositoryOwner string
	Refs            []string
	Environment     string
	Audience        string
	SubjectMapper   SubjectMapper
}

GitHubActionsOptions configures GitHubActionsIssuer.

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 observability adapters attached to Config.Observability. Either field may be nil; the library falls back to no-op adapters per field.

type IDJAGConfig ¶ added in v2.8.0

type IDJAGConfig = internalas.IDJAGConfig

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

type IdentityConflictError ¶

type IdentityConflictError = models.IdentityConflictError

IdentityConflictError is wrapped inside ErrIdentityConflict when the OAuth account is bound to a different user. errors.As it to read ConflictingUserID.

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

type ImportedUser ¶

type ImportedUser = importer.ImportedUser

ImportedUser is an existing account to insert.

type ImportedWebAuthnCredential ¶

type ImportedWebAuthnCredential = importer.ImportedWebAuthnCredential

ImportedWebAuthnCredential is an existing passkey or security key.

type IntrospectionResponse ¶

type IntrospectionResponse = internalas.IntrospectionResponse

IntrospectionResponse is the RFC 7662 section 2.2 response, plus the act chain and delegation_grant_id fields.

type JARConfig ¶

type JARConfig = internalas.JARConfig

JARConfig is the root alias for as.JARConfig. Set Config.AuthorizationServer.JAR to enable RFC 9101.

type JWKSKey ¶

type JWKSKey = models.JWKSKey

type JWTBearerConfig ¶

type JWTBearerConfig struct {
	// TrustedJWTIssuers lists external issuers whose JWTs may be exchanged for AS tokens (RFC 7523 section 2.1).
	// Each entry needs Issuer and JWKSURL; AllowedAlgorithms defaults to ES256, RS256 and EdDSA.
	TrustedJWTIssuers []TrustedJWTIssuer

	// ClientAssertionMaxAge bounds how far in the past a client assertion's iat may be (default 60 seconds).
	ClientAssertionMaxAge time.Duration

	// AssertionMaxAge bounds how far in the past a bearer grant assertion's iat may be (default 300 seconds).
	AssertionMaxAge time.Duration

	// ReplayCacheTTL is how long JTIs stay in the replay cache (default 600 seconds, covering the
	// maximum assertion lifetime). Backends without JWTBearerStorage fall back to an in-process map
	// and lose replay protection on restart.
	ReplayCacheTTL time.Duration

	// MaxActorChainDepth caps on-behalf-of actor chains in the RFC 8693 token-exchange grant (default 5).
	MaxActorChainDepth int

	// JWKSCacheTTL is how long a fetched JWKS is reused, so key rotation is picked up (default 5
	// minutes). Failed fetches are never cached.
	JWKSCacheTTL time.Duration

	// JWKSCacheMaxEntries bounds how many distinct JWKS URLs are cached (default 256).
	JWKSCacheMaxEntries int

	// JWKSFetchTimeout is the total time allowed for one JWKS fetch (default 5 seconds).
	JWKSFetchTimeout time.Duration

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

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

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

type JWTBearerStorage ¶

type JWTBearerStorage interface {
	// InsertJTI records a new jti. It returns ErrStorageNotFound when the jti already exists in the
	// replay window (the generic duplicate signal, so implement it with a unique constraint on jti).
	// expiresAt is when the jti may be pruned.
	InsertJTI(ctx context.Context, jti string, expiresAt time.Time) error
	// SweepExpiredJTIs removes jti rows expiring before the given time.
	SweepExpiredJTIs(ctx context.Context, before time.Time) error
}

JWTBearerStorage is an optional extension giving durable JTI replay prevention for RFC 7523 assertions. Without it the AS falls back to an in-process map, which loses replay protection on restart.

type Labels ¶

type Labels = observability.Labels

Labels is the name-to-value label set for one metric instance. Never put high-cardinality identifiers in it.

type LifecycleHooks ¶

type LifecycleHooks struct {
	OnSignup         func(ctx context.Context, user *User, method SignupMethod) error
	OnSignin         func(ctx context.Context, user *User, sess *Session) error
	OnPasswordChange func(ctx context.Context, user *User) error
	OnMFAEnabled     func(ctx context.Context, user *User, kind MFAKind) error
	OnTokenIssued    func(ctx context.Context, claims map[string]any) (map[string]any, error)
	OnOrgSwitch      func(ctx context.Context, user *User, orgID string) error
	// OnAccountDeleted runs after the delete committed; user is the snapshot taken just before it. It is
	// observe-only, so errors and panics are only logged.
	OnAccountDeleted func(ctx context.Context, user *User) error
	// OnOAuthConflict fires when a sign-in email matches a user registered via another provider. It must return
	// a redirect URL for a short-lived verification challenge; nil silently links the providers.
	OnOAuthConflict func(ctx context.Context, p OAuthConflictPayload) (redirectURL string, err error)

	// OnHookError, when set, receives the hook name and error whenever an observe-only hook fails or panics. It
	// runs in addition to the slog line, must stay fast, and cannot change request outcomes.
	OnHookError func(ctx context.Context, hook string, err error)
}

LifecycleHooks lets consumers react to authentication lifecycle events without forking handlers. All fields are optional and run after the underlying operation succeeds, before the response is written. OnSignup, OnSignin, OnPasswordChange, OnMFAEnabled and OnOrgSwitch are observe-only: errors and panics are logged (and reported to OnHookError) but never fail the request. Gate a signup at the route instead. OnTokenIssued is the only hook that may mutate state: it returns the claims to sign, and an error fails issuance.

type LoggingAuthenticationDevice ¶

type LoggingAuthenticationDevice struct{}

LoggingAuthenticationDevice logs notifications at INFO. Suitable for staging.

func (LoggingAuthenticationDevice) Notify ¶

type LoginThrottleCASStore ¶

type LoginThrottleCASStore = throttle.CASStore

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

type LoginThrottleConfig ¶

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

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

type LoginThrottleEntry ¶

type LoginThrottleEntry = throttle.Entry

LoginThrottleEntry is one record held by a LoginThrottleStore.

type LoginThrottleEntryDeleter ¶ added in v2.7.0

type LoginThrottleEntryDeleter = throttle.LoginEntryDeleter

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

type LoginThrottleStore ¶

type LoginThrottleStore = throttle.Store

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

func NewMemoryLoginThrottleStore ¶

func NewMemoryLoginThrottleStore(maxEntries int) LoginThrottleStore

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

type MFAKind ¶

type MFAKind string

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

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

type MagicLinkStorage ¶

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

MagicLinkStorage covers single-use magic-link tokens.

type MemoryRevocationBus ¶

type MemoryRevocationBus = revocation.MemoryBus

MemoryRevocationBus is the in-process RevocationBus.

func NewMemoryRevocationBus ¶

func NewMemoryRevocationBus() *MemoryRevocationBus

NewMemoryRevocationBus returns an empty in-process bus.

type Metrics ¶

type Metrics = observability.Metrics

Metrics is the instrument factory that adapters implement.

type MintAPITokenInput ¶

type MintAPITokenInput = apitokens.MintAPITokenInput

type MintAgentTokenInput ¶

type MintAgentTokenInput = apitokens.MintAgentTokenInput

type MintSessionLinkInput ¶

type MintSessionLinkInput struct {
	UserID ULID
	// CredentialID binds the session to an upstream credential that is re-checked on every use. Empty
	// mints an unbound link.
	CredentialID string
	TTL          time.Duration
	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.

type NoopAuthenticationDevice ¶

type NoopAuthenticationDevice struct{}

NoopAuthenticationDevice discards every notification. Suitable for tests and out-of-band notification setups.

func (NoopAuthenticationDevice) Notify ¶

type OAuthAccount ¶

type OAuthAccount = models.OAuthAccount

type OAuthAccountStorage ¶

type OAuthAccountStorage interface {
	// UpsertOAuthAccount inserts or updates the row keyed by (provider, provider_user_id).
	// Implementations must encrypt token bytes before they reach storage.
	UpsertOAuthAccount(ctx context.Context, a OAuthAccount) (OAuthAccount, error)
	OAuthAccountByProviderUserID(ctx context.Context, provider, providerUserID string) (*OAuthAccount, error)

	OAuthAccountsByUserID(ctx context.Context, userID ULID) ([]OAuthAccount, error)

	MoveOAuthAccount(ctx context.Context, provider, providerUserID string, newUserID ULID) error

	DeleteOAuthAccountByProvider(ctx context.Context, userID ULID, provider string) error
}

OAuthAccountStorage covers linked third-party OAuth accounts.

type OAuthCallbackResult ¶ added in v2.7.0

type OAuthCallbackResult = internaloauth.CallbackResult

OAuthCallbackResult is what OAuthCallback returns on success.

type OAuthClient ¶

type OAuthClient = models.OAuthClient

type OAuthConfig ¶

type OAuthConfig struct {
	StateStore OAuthStateStore
	StateTTL   time.Duration
	// AllowedReturnTo lists post-login destinations a caller may request with ?return_to= (exact URLs,
	// or "/" paths matched exactly or by a "*" prefix). Anything else falls back to
	// Config.PostLoginRedirect.
	AllowedReturnTo     []string
	Signup              OAuthSignupPolicy
	AllowedEmailDomains []string
	// InviteCheck is required for OAuthSignupInvite. It receives the verified, lower-cased email.
	InviteCheck func(ctx context.Context, email string) (bool, error)
	// RedirectURI, when set, builds the redirect_uri sent to the provider instead of BaseURL + prefix
	// + callback, so callback URLs already registered at the provider keep working. It must be an
	// absolute https URL (http only for loopback or with AllowInsecureRedirectURI) with no fragment or
	// userinfo. Never derive it from an unvalidated Host header.
	RedirectURI func(r *http.Request, provider string) (string, error)
	// RedirectURIAllowedHosts, when non-empty, restricts the host (or
	// host:port) RedirectURI may return; anything else fails closed.
	// Experimental.
	RedirectURIAllowedHosts []string
	// AllowInsecureRedirectURI permits an http:// RedirectURI result on a
	// non-loopback host. For development only. Experimental.
	AllowInsecureRedirectURI bool
}

OAuthConfig tunes OAuth login hardening. The zero value keeps v2 behavior: in-memory state, 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
}

type OAuthServerStorage ¶

type OAuthServerStorage interface {
	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

	InsertAuthorizationCode(ctx context.Context, c AuthorizationCode) error
	// ConsumeAuthorizationCode atomically loads and deletes a code row. It returns ErrStorageNotFound
	// when absent or already used.
	ConsumeAuthorizationCode(ctx context.Context, code string) (*AuthorizationCode, error)

	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

	// InsertJWKSKey stores a key whose private bytes arrive already encrypted.
	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. Status transitions go through UpdateAgentStatus; last_active_at is touched by
	// introspection and token paths.
	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
	// UpdateAgentExpiry sets or clears (nil) the agent expiry. A missing agent is ErrNotFound.
	UpdateAgentExpiry(ctx context.Context, id ULID, expiresAt *time.Time) error

	// Agent credentials. Rotation inserts a fresh row before revoking the old one; callers filter on
	// RevokedAt themselves.
	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. Uniqueness on (user_id, agent_id, resource) is enforced by the database.
	// Revocations reach resource servers within 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 persistence needed by the OAuth 2.1 authorization server, the JWKS rotation goroutine and dynamic client registration.

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 (the default).
	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 verified email domain is in AllowedEmailDomains.
	OAuthSignupAllowedDomains OAuthSignupPolicy = "allowed_domains"
	// OAuthSignupInvite creates users only when OAuthConfig.InviteCheck approves the verified email.
	OAuthSignupInvite OAuthSignupPolicy = "invite"
)

type OAuthStartResult ¶ added in v2.7.0

type OAuthStartResult = internaloauth.StartResult

OAuthStartResult is the provider authorization URL and the Binding secret, which goes in an HttpOnly cookie.

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; the default in-memory store is single-process.

type OIDCConfig ¶ added in v2.10.0

type OIDCConfig = internalas.OIDCConfig

OIDCConfig is the root alias for the OpenID Provider settings.

type OpaqueAccessToken ¶ added in v2.8.0

type OpaqueAccessToken = models.OpaqueAccessToken

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

type OpaqueTokenStorage ¶ added in v2.8.0

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

OpaqueTokenStorage is the optional persistence behind opaque (reference) access tokens, enabled per client through TokenPolicy. Only token hashes are stored.

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 empty for now; a non-nil value turns multi-tenancy on. Future tunables land here without breaking zero-value wiring.

type PARConfig ¶

type PARConfig = internalas.PARConfig

PARConfig is the root alias for as.PARConfig. Set Config.AuthorizationServer.PAR to enable RFC 9126.

type PasswordPolicyConfig ¶

type PasswordPolicyConfig struct {
	// AllowLegacyBcrypt enables the legacy-hash fallback for migrated users: bcrypt ($2a$, $2b$, $2x$)
	// and PBKDF2 hashes are verified and transparently re-hashed to Argon2id on success. With false a
	// bcrypt hash fails. Leave false outside migrations.
	AllowLegacyBcrypt bool

	// ShareDummyHash makes every engine in the process reuse one timing-equalization hash, so a test
	// binary that builds many engines pays the 64 MiB Argon2id cost once. Leave false in production.
	ShareDummyHash bool

	// HashConcurrency bounds concurrent Argon2id hashes process-wide (default NumCPU/4, at least 1) so
	// sign-ins queue instead of each allocating 64 MiB. The last New call wins.
	HashConcurrency int

	// MinLength is the minimum password length in bytes (default 12).
	MinLength int

	// MaxBytes is the maximum password length in bytes, rejected with CodeWeakPassword (default 72,
	// the bcrypt limit).
	MaxBytes int

	// BreachChecker, when set, rejects passwords found in a breach corpus on signup and change. Lookup
	// errors fail open.
	BreachChecker BreachChecker

	// OnLegacyHashAccepted is called from a separate goroutine after a legacy-hash user's password is
	// re-hashed to Argon2id, with (userID, newHash), so hosts that mirror hashes can update their
	// copy. Panics are recovered; it never fails a login.
	OnLegacyHashAccepted func(userID string, newArgon2idHash string)
}

PasswordPolicyConfig holds optional password-verification extensions, meant for migration windows. Disable them once users are 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 with their stored PHC hash. The hash is "" when the
	// account has no password (for example magic-link-only signup), which must surface as
	// 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(ctx context.Context, userID ULID) (string, error)

	// MovePasswordHash copies the Argon2id hash from secondaryID to primaryID (overwriting it) and
	// clears secondaryID's.
	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 canonical permission catalog by value, so callers cannot mutate library state.

type Principal ¶

type Principal = apitokens.Principal

func PrincipalFromContext ¶

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

PrincipalFromContext returns the Principal attached by RequireAbility.

type PrincipalKind ¶

type PrincipalKind = apitokens.PrincipalKind

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 and OIDC provider implements. Each provider lives in its own sub-package under provider/<name>/ so consumers import only what they use.

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 providers at request time. Resolve returns (nil, false, nil) for an unknown name and an error when the lookup itself failed.

type ProviderToken ¶

type ProviderToken = internaloauth.ProviderToken

ProviderToken is the normalized shape of an OAuth token exchange response. Providers vary in which fields they fill (GitHub often omits RefreshToken and ExpiresAt). Storage encrypts the tokens at rest.

type ProviderUser ¶

type ProviderUser = internaloauth.ProviderUser

ProviderUser is the normalized shape of a provider's userinfo response. ID is the provider-stable identifier stored as oauth_accounts.provider_user_id. EmailVerified is true only when the provider attests to it.

type RARConfig ¶ added in v2.8.0

type RARConfig = internalas.RARConfig

RARConfig is the root alias for the RFC 9396 settings.

type RBACConfig ¶

type RBACConfig struct {
	// Permissions extends the seeded catalog, deduped by case-sensitive name. New rejects names containing
	// whitespace or non-ASCII, since permission names are program identifiers.
	Permissions []Permission

	// DefaultRoles seeds every new organization; empty uses owner, admin and member. Reserved names must
	// stay present when overridden, or New returns an error.
	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. Insert is idempotent on name, so seeding at app start is 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(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(ctx context.Context, userID ULID) (int, error)
	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.

type RefreshProvider ¶ added in v2.10.0

type RefreshProvider = internaloauth.RefreshProvider

RefreshProvider is the optional Provider capability behind GetProviderToken. It must return an error wrapping ErrProviderGrantRevoked when the provider rejects the refresh token. Providers without it still sign users in; GetProviderToken answers ErrProviderRefreshUnsupported once their token expires.

type RefreshToken ¶

type RefreshToken = models.RefreshToken

type RegisterAgentInput ¶

type RegisterAgentInput = agent.RegisterInput

type RegisteredClient ¶

type RegisteredClient = models.RegisteredClient

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

type RegistrationToken ¶ added in v2.8.0

type RegistrationToken = models.RegistrationToken

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

type RegistrationTokenStorage ¶ added in v2.8.0

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

RegistrationTokenStorage is the optional persistence for initial access tokens.

type Report ¶

type Report = doctor.Report

Report is the result of TheAuth.Doctor.

type ResetPasswordOption ¶ added in v2.10.0

type ResetPasswordOption func(*resetPasswordOptions)

ResetPasswordOption customizes ResetPasswordAdmin.

func RequirePasswordChange ¶ added in v2.10.0

func RequirePasswordChange() ResetPasswordOption

RequirePasswordChange makes ResetPasswordAdmin force a new password before the next sign-in completes. Needs Config.AccountState.

type RevocationBus ¶

type RevocationBus = revocation.Bus

RevocationBus fans revocation events out to subscribers.

type RevocationEvent ¶

type RevocationEvent = revocation.Event

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

type RevocationKind ¶

type RevocationKind = revocation.Kind

RevocationKind says what was revoked.

type RevocationTarget ¶

type RevocationTarget = revocation.Target

RevocationTarget names the credential a stream was opened with.

func TargetForPrincipal ¶

func TargetForPrincipal(p *Principal) RevocationTarget

TargetForPrincipal builds the watch target for an authenticated principal.

type Role ¶

type Role = models.Role

type RoleSeed ¶

type RoleSeed = rbac.RoleSeed

RoleSeed describes one organization-scoped role created at SeedOrganizationRoles time. Unknown permission names make New fail so typos surface at startup.

func DefaultRoleSeeds ¶

func DefaultRoleSeeds() []RoleSeed

DefaultRoleSeeds returns the three default organization roles seeded into every new organization. The reserved names "owner", "admin" and "member" must stay present when Config.RBAC.DefaultRoles overrides them.

type SAMLAttributeMap ¶

type SAMLAttributeMap = models.SAMLAttributeMap

type SAMLConfig ¶

type SAMLConfig struct {
	// SPCertificatePEM and SPPrivateKeyPEM sign every outbound AuthnRequest; New fails if either is unparseable.
	SPCertificatePEM []byte
	SPPrivateKeyPEM  []byte

	// AuthnRequestTTL caps how long an SP-initiated AuthnRequest ID is tracked for replay protection
	// (default 10 minutes).
	AuthnRequestTTL time.Duration

	// ClockSkew tolerated on Conditions.NotBefore and NotOnOrAfter (default 30 seconds; some IdPs need 60).
	ClockSkew time.Duration

	// AllowedRelayStates lists extra post-login destinations accepted as RelayState (exact URLs or "/" prefixes
	// ending in "*"); any other value 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 and update; it mirrors internal/saml field for field.

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 returned by AuthenticateSCIMToken. Bundling OrgID and TokenID avoids a second storage lookup.

type SCIMConfig ¶

type SCIMConfig struct {
	// RequireHTTPS rejects requests without TLS whose X-Forwarded-Proto is not "https" (default true). Set false
	// only behind a TLS-terminating proxy that strips the header.
	RequireHTTPS bool

	// MaxPageSize caps the count parameter on list endpoints (default 200; RFC 7644 section 3.4.2).
	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

	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

	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, or false for anonymous requests.

type SessionAuthStorage ¶ added in v2.11.0

type SessionAuthStorage interface {
	// AppendSessionAuthMethods adds missing methods (order kept, no duplicates) and advances AuthTime
	// to at when later.
	AppendSessionAuthMethods(ctx context.Context, id ULID, methods []string, at time.Time) ([]string, time.Time, error)
}

SessionAuthStorage is the optional capability that atomically records a second factor or step-up in a session's auth methods. Built-in backends persist AuthMethods and AuthTime on CreateSession already; without this interface sessions simply carry no appended record.

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(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 time.Duration
	// CredentialChecker is consulted when a link is minted, when it is exchanged, 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(ctx context.Context, userID ULID) ([]Session, error)
	TouchSession(ctx context.Context, id ULID, at time.Time) error
	RevokeOtherUserSessions(ctx context.Context, userID, keep ULID) (int, error)
	RevokeSessionsByCredential(ctx context.Context, credentialID string) (int, error)
	SetSessionElevatedUntil(ctx context.Context, id ULID, until *time.Time) error
}

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

type SessionOverflow ¶ added in v2.10.0

type SessionOverflow string

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

const (
	SessionEvictOldest SessionOverflow = "evict_oldest"
	// SessionReject refuses the new sign-in with CodeSessionLimit.
	SessionReject SessionOverflow = "reject"
)

type SessionPolicy ¶ added in v2.10.0

type SessionPolicy struct {
	MaxConcurrentSessions int
	Overflow              SessionOverflow
}

SessionPolicy caps how many full sessions one user may hold. Pending 2FA sessions do not count. The check is best effort under concurrency. It needs SessionManagementStorage.

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 at the supplied auth level (typically
	// AuthLevelPending2FA). CreateSession keeps defaulting to AuthLevelFull.
	CreateSessionWithAuthLevel(ctx context.Context, s Session) (Session, error)
	// UpdateSessionAuthLevel rewrites a session's auth level. TOTP verification uses it to promote a
	// pending session.
	UpdateSessionAuthLevel(ctx context.Context, id ULID, level string) error
}

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

type Severity ¶

type Severity = doctor.Severity

Severity ranks a doctor finding.

type SharedSignalsConfig ¶ added in v2.10.0

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

	// Issuer is the SET issuer (default AuthorizationServer.Issuer). SETs are signed with the AS keys.
	Issuer string
	// BaseURL is the public URL the handler is mounted at, used in the metadata document (default Issuer).
	BaseURL string
	// Store holds streams and the delivery queue. The default is in memory and loses queued events on
	// restart; use the sqlite or postgres SignalsStore in production.
	Store signals.Store

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

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

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

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

type SharedSignalsReceiverConfig ¶ added in v2.10.0

type SharedSignalsReceiverConfig struct {
	Audience     string
	Issuers      map[string]string
	Authenticate func(r *http.Request) bool
	// ResolveUser maps a subject to a local user id for the default revocation handler. Only email
	// subjects are resolved by default.
	ResolveUser func(ctx context.Context, sub signals.Subject) (userID ULID, ok bool, err error)
	Handlers    []signals.Handler
	// DisableDefaultRevocation turns off the default revocation handler.
	DisableDefaultRevocation bool

	AllowPrivateNetworks bool
	AllowInsecureHTTP    bool
}

SharedSignalsReceiverConfig configures the receiver half.

type SigninStep ¶

type SigninStep = password.SigninStep

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

type SignupMethod ¶

type SignupMethod string

SignupMethod identifies which credential path created a user. LifecycleHooks.OnSignup receives it so consumers can branch on the path.

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

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, TOTP Code, or a passkey Challenge and Assertion.

type Storage ¶

Storage is the full persistence contract, embedding every capability interface in this file. Adapters live in sub-packages (storage/memory, storage/postgres); it is defined here to avoid an import cycle.

type SubMapper ¶

type SubMapper struct{}

SubMapper is the built-in SubjectMapper that parses the "sub" claim as a ULID (for example for internal workload tokens).

func (SubMapper) Resolve ¶

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

Resolve returns the local user ULID for the supplied claim map, or ErrStorageNotFound when no mapping exists.

type SubjectMapper ¶

type SubjectMapper interface {
	// Resolve returns the local user ULID for the claims, or ErrStorageNotFound when no mapping
	// exists. Other errors are treated as transient 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. The built-ins are SubMapper (the sub claim is a ULID) and EmailMapper (the email claim names a user). Custom implementations see the full payload.

type TOTPConfig ¶

type TOTPConfig struct {
	// Issuer is shown in the authenticator app, e.g. "GLINR Quarter".
	Issuer string
	// RecoveryCodeCount is the number of recovery codes (default 10); each carries 40 bits from crypto/rand.
	RecoveryCodeCount int
}

TOTPConfig wires second-factor TOTP. Algorithm is fixed at SHA-1, 30s and 6 digits for compatibility with mainstream authenticator apps; skew is one period either side.

type TOTPReplayStorage ¶

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

TOTPReplayStorage is an optional capability making TOTP replay protection durable across processes. Without it the last used step is tracked 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 secondaryID's TOTP secret to primaryID. An existing confirmed primary
	// secret wins and the secondary is dropped, preserving the active factor.
	MoveTOTPSecret(ctx context.Context, primaryID, secondaryID ULID) error
	// UpsertPendingTOTPSecret writes an encrypted, unconfirmed secret. It preserves a confirmed secret
	// untouched; re-enrollment requires DeleteTOTPSecret first.
	UpsertPendingTOTPSecret(ctx context.Context, s TOTPSecret) error
	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 marks the matching unused code used, atomically. It returns
	// ErrStorageNotFound for a wrong, reused or cross-user code.
	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 creates a personal organization (user as owner, set active) on every wired signup
	// path. Default false; wire custom provisioning via LifecycleHooks.OnSignup instead.
	AutoCreatePersonalOrg bool

	// PersonalOrgNameFn returns the display name of a personal organization (default: the user's email).
	PersonalOrgNameFn func(*User) string

	// PersonalOrgSlugFn returns a URL-safe slug (default "personal-" plus the lowercased ULID, unique without a
	// conflict-retry loop).
	PersonalOrgSlugFn func(*User) string
}

TenancyConfig (v2.5) opts into tenant provisioning so consumers need not seed organization rows on signup. It takes effect only when Config.Organizations is set.

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 wiring are delegated to 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, so caching is trivial.

func (*TheAuth) AddOrganizationMember ¶

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

AddOrganizationMember adds a user to an organization or updates their role ("owner", "admin" or "member"). It refuses to demote the last owner (ErrLastOwner).

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

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

Admission returns net/http middleware that runs before authentication and refuses anonymous floods. It applies tiered per-client rate limits (429 with Retry-After) and a cross-site check for cookie-authenticated unsafe methods (403). Counters use Config.Stores.RateLimiter when set so replicas share budgets; a store failure lets the request through.

func (*TheAuth) AgentHookSubject ¶ added in v2.12.0

func (a *TheAuth) AgentHookSubject(ctx context.Context, agentID string) (hook.AgentInfo, hook.Delegation, error)

AgentHookSubject returns the agent and delegation fields of a hook input for agentID. The delegation path is the agent alone; Inbound lists the agent's active delegation grants. A Go grant runs from a user to an agent, so FromAgent holds "user:<id>". It fits toolguard.Guard.HookSubject. An unknown agent wraps ErrAgentNotFound and a suspended or revoked one ErrAgentInactive.

func (*TheAuth) ApproveBackchannelAuth ¶

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

ApproveBackchannelAuth marks the pending CIBA request approved and provisions the tokens the next poll returns. userID must be the authenticating user; a request already bound to another user returns ErrCIBAUserMismatch.

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 on failure. Needs Config.APITokens.

func (*TheAuth) AuthenticateSCIMToken ¶

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

AuthenticateSCIMToken is the entry point of the SCIM bearer middleware, run on every request. It resolves the org and token in one storage round trip and touches last_used_at asynchronously.

func (*TheAuth) Authn ¶

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

Authn reads the session cookie, validates it and adds the user and session to the request context. It does not reject anonymous requests; pair it with RequireAuth or RequirePendingOrFull.

func (*TheAuth) AuthorizeAgent ¶ added in v2.11.0

func (a *TheAuth) AuthorizeAgent(ctx context.Context, agentID, action, resource string) error

AuthorizeAgent checks whether the agent may perform action on resource under its attached policies, spending one unit of its rate budget. It returns nil when allowed, *AgentPolicyDeniedError on refusal, *AgentRateLimitedError (with RetryAfter) when the budget is spent, and an error for an unresolvable policy. Without PolicyEngine, RateLimit and BeforeAuthorize it returns nil.

With AgentConfig.BeforeAuthorize set, the hook runs after the policy and rate limit allowed the call. A refusal from it wraps ErrAgentPolicyDenied and a *hook.BlockedError carrying the decision code (hook_denied, hook_timeout, hook_error or approval_required), and emits an agent.authorize_denied audit event with decision_code.

func (*TheAuth) BeginPasskeyLogin ¶

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

BeginPasskeyLogin starts a WebAuthn assertion ceremony.

func (*TheAuth) BeginPasskeyRegistration ¶

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

BeginPasskeyRegistration starts a WebAuthn credential creation ceremony. The returned challenge token goes in a short-lived cookie.

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 returns a fresh shared secret and otpauth URL. The secret is shown exactly once.

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 sessions and returns a fresh token.

func (*TheAuth) CheckAgentRate ¶ added in v2.11.0

func (a *TheAuth) CheckAgentRate(ctx context.Context, agentID string) error

CheckAgentRate spends one unit of the agent's rate budget without evaluating policy; it suits toolguard.Guard.Limit.

func (*TheAuth) ClientCredentialsToken ¶

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

ClientCredentialsToken mints a self-token for an authenticated agent client (sub "agent:<id>"). The aud is bound to the resource parameter (RFC 8707) and scope is intersected with the agent's registered scopes. Suspended or revoked agents fail with ErrAgentInactive (access_denied on the wire).

func (*TheAuth) Close ¶

func (a *TheAuth) Close()

Close releases background resources: the OAuth state, WebAuthn, TOTP and SAML GC loops and the audit writer. Audit drain waits up to Config.Audit.DrainTimeout. Safe to call multiple times.

func (*TheAuth) CompleteConsent ¶ added in v2.11.0

func (a *TheAuth) CompleteConsent(ctx context.Context, ticket string, dec ConsentDecision, user *User) (AuthorizeResult, error)

CompleteConsent resumes an authorization that ConsentHandler answered with ConsentInteract. The user must be the signed-in user the ticket was issued to. Protect the calling endpoint against CSRF. See docs/oauth-consent.md.

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. OnSignin fires as for VerifyTOTP.

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

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

func (*TheAuth) CreateAgent ¶

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

CreateAgent persists an agent owned by a user or organization with a backing OAuth client, and returns the agent and its one-shot secret.

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

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

CreateDeviceJoinToken mints a single-use join token for one constrained device. The plaintext is shown once; the token fixes the device's name, SPIFFE ID and scopes.

func (*TheAuth) CreateOrganization ¶

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

CreateOrganization writes a new org and makes the user its owner. The slug is lowercased and validated; storage enforces uniqueness.

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

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

CreateRegistrationToken mints an initial access token for POST /oauth/register. The plaintext is returned once; only a SHA-256 digest is stored. Needs a storage implementing RegistrationTokenStorage.

func (*TheAuth) CreateRole ¶

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

CreateRole adds a role with the listed permissions. Names are unique per organization and emit role.created.

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 256-bit token and returns the plaintext once. Only its sha256 hash is stored.

func (*TheAuth) CreateUser ¶ added in v2.12.0

func (a *TheAuth) CreateUser(ctx context.Context, in CreateUserInput) (User, error)

CreateUser creates a user, or returns the existing one when the normalized email is already registered and in.ID is zero or equal to the stored ID. An existing user is never modified. It sends no email and creates no credential or session. A new user emits a "user.created" audit event. Errors match ErrUserInvalidInput, ErrUserEmailConflict and ErrUserIDConflict via errors.Is; the loser of a concurrent call with the same email gets the winner's user, not an error.

func (*TheAuth) DCRRegister ¶

DCRRegister is RegisterClient for Go callers: the same operation as POST /oauth/register.

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 now, for resource servers that authenticate agents another way (for example an OAuth access token). Needs Config.APITokens.

func (*TheAuth) DeleteRole ¶

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

DeleteRole removes a role. It returns ErrRoleInUse when the role is the sole grantor of users:admin in its organization.

func (*TheAuth) DeleteSAMLConnection ¶

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

DeleteSAMLConnection removes the connection and cascades its identities.

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

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

DeleteUser permanently deletes userID and everything owned by them, keeping audit rows with the actor cleared. It returns ErrLastOwner when the user is the sole owner of an organization. OnAccountDeleted fires after the delete commits.

func (*TheAuth) DenyBackchannelAuth ¶

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

DenyBackchannelAuth marks the pending CIBA request denied; the next poll returns access_denied.

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

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

DisableUser blocks sign-in and revokes the user's sessions and API tokens. Needs Config.AccountState. EnableUser lifts the block but not the revocations.

func (*TheAuth) Doctor ¶

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

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

func (*TheAuth) EmitAudit ¶

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

EmitAudit enqueues an audit event for batched async write. It never blocks: when the writer channel is full the event is dropped and Stats.AuditDropped increments. The metadata map is mutated by the redactor, so callers must not reuse it. It is a no-op when Config.Audit is nil or after Close.

func (*TheAuth) EmitDecision ¶ added in v2.11.0

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

EmitDecision is EmitAudit for decision-class events (authorization, policy, approval, delegation). With Config.Audit.FailClosed set it returns ErrAuditUnavailable when the event cannot be queued, so the caller can deny the action. Otherwise it behaves like EmitAudit and returns nil.

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

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

EnableUser lifts a DisableUser block.

func (*TheAuth) ExchangeAuthorizationCode ¶

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

ExchangeAuthorizationCode redeems a one-time code for an access and refresh token pair. It enforces PKCE S256, redirect_uri equality, audience binding (RFC 8707) and client authentication.

func (*TheAuth) ExchangeToken ¶

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

ExchangeToken implements RFC 8693 token exchange.

func (*TheAuth) FinishPasskeyLogin ¶

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

FinishPasskeyLogin verifies the assertion, advances the sign counter and issues a session. OnSignin fires for it.

func (*TheAuth) FinishPasskeyRegistration ¶

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

FinishPasskeyRegistration stores the new credential. OnSignup fires with SignupMethodPasskey when it is the user's first credential; registration needs an authenticated user, so the first passkey is the closest equivalent of an account-creation moment.

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 and runs find-or-create. OnSignup fires with SignupMethodSAML when the user row was created here; OnSignin fires for the session just issued.

func (*TheAuth) FinishTOTPEnrollment ¶

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

FinishTOTPEnrollment confirms the pending secret with one code and returns the recovery codes. OnMFAEnabled fires on success.

func (*TheAuth) GetAgent ¶

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

GetAgent returns the agent record by ID.

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

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

GetProviderToken returns a usable upstream access token for the user's linked provider account. An expired token is refreshed and the rotated tokens persisted; concurrent calls for one user and provider share one upstream refresh. It needs at least one configured provider and Config.EncryptionKey.

func (*TheAuth) GrantDelegation ¶

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

GrantDelegation persists a delegation grant. Scope must be a subset of the resource's scopes, resource must be a known ProtectedResource, and max_duration_seconds must be within AgentConfig.MaxDelegationDuration.

func (*TheAuth) GrantRole ¶

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

GrantRole assigns roleID to target. The actor must already be allowed to grant; run RequirePermission upstream. It is idempotent and emits role.granted.

func (*TheAuth) Handler ¶

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

Handler returns a stdlib http.Handler serving every route Mount registers, for net/http users without chi. Paths keep their configured prefixes, so http.StripPrefix is unnecessary 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 reports whether the user holds perm in orgID, or is a super_admin (which bypasses every check).

func (*TheAuth) ImportAPIToken ¶

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

ImportAPIToken inserts an existing token by its SHA-256 hash, which must cover the full raw secret as clients present it. 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 a token and returns the introspection response. JWTs are recognised by their three segments; anything else is looked up as a refresh token by hash. A non-empty expectedAud makes mismatched audiences return active=false.

func (*TheAuth) InvalidateProvider ¶

func (a *TheAuth) InvalidateProvider(name string)

InvalidateProvider drops the cached ProviderResolver answer for name so an edited provider takes effect 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 at AuthLevelPending2FA.

func (*TheAuth) IssueSessionByUserID ¶

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

IssueSessionByUserID mints a full session for a user without an existing session token (used after OTP verification in the account-linking flow).

func (*TheAuth) JWTBearerGrant ¶

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

JWTBearerGrant implements RFC 7523 section 2.1: an external JWT from a configured TrustedJWTIssuer is exchanged for an AS-issued access token. It needs Config.AuthorizationServer.JWTBearer; otherwise ErrOAuthUnsupportedGrantType.

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 to the user behind sessionToken, for the post-OTP account-linking flow.

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

func (*TheAuth) ListDelegationsForUser ¶

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

ListDelegationsForUser returns every grant the user issued, including revoked ones.

func (*TheAuth) ListDeviceRequests ¶

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

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

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

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

ListDevices lists registered devices, newest first.

func (*TheAuth) ListOrganizationMembers ¶

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

ListOrganizationMembers returns every member of the organization.

func (*TheAuth) ListProviders ¶

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

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

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

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

ListRegistrationTokens lists tokens newest first; a nil orgID lists all. Hashes are on the model, so do not expose them.

func (*TheAuth) ListSAMLConnections ¶

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

ListSAMLConnections returns every connection for one organization.

func (*TheAuth) ListSCIMTokens ¶

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

ListSCIMTokens returns every token for the org, revoked or not.

func (*TheAuth) ListSessions ¶

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

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

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

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

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

func (*TheAuth) ListUserOrganizations ¶

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

ListUserOrganizations returns every organization the user belongs to.

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 credential of the requested kind on an existing agent. Only the secret kind is implemented; X.509 and JWK 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. Only its hash is stored.

func (*TheAuth) Mount ¶

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

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

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

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

func (*TheAuth) NormalizeEmail ¶

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

NormalizeEmail returns the canonical form used for every email lookup (trimmed, lowercased, NFKC when Config.EmailNFKC is set).

func (*TheAuth) NotifyOwnerDisabled ¶

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

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

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

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

OAuthCallback completes the login flow for an app hosting its own callback route. It fires the same hooks as the built-in callback; the caller sets the session cookie from SessionToken and clears the binding cookie.

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

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

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

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

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

OIDCLogout sends back-channel logout tokens to every OpenID client that took part in sessionID, for logouts that skip end_session (admin revocation, account deletion). It does not revoke the session.

func (*TheAuth) ObservabilityHooks ¶

func (a *TheAuth) ObservabilityHooks() *Hooks

ObservabilityHooks returns the bundle in use, never nil, so custom services can share the same adapters.

func (*TheAuth) OrganizationByID ¶

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

OrganizationByID looks up an organization by ULID.

func (*TheAuth) OrganizationBySlug ¶

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

OrganizationBySlug looks up an organization by URL-safe slug.

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

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

PasskeyAuthenticatorName returns the configured display name for a credential's AAGUID, or "" when unknown.

func (*TheAuth) PermissionsForUser ¶

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

PermissionsForUser returns the user's permissions in orgID, sorted. A nil orgID returns system-role permissions only.

func (*TheAuth) ProtectedResourceMetadataDoc ¶

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

ProtectedResourceMetadataDoc builds the RFC 9728 document for a configured resource identifier.

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 and a cursor for the next page. It performs no authorization; callers check. q.Order is "desc" (default) or "asc" and q.Event filters by shared event name; both, and "c1." cursors, need a backend that declares AuditOrderSupported() true, otherwise it returns ErrAuditOrderUnsupported. An unknown order returns ErrBadAuditOrder and a cursor that does not decode for the order returns ErrBadCursor.

func (*TheAuth) RateLimitByEmail ¶

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

RateLimitByEmail limits requests per "email" field of the JSON body (read up to 16 KiB, then restored for the handler). Requests without a parseable email pass through; the handler rejects them.

func (*TheAuth) RateLimitByIP ¶

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

RateLimitByIP limits requests per source IP to perMinute. Wire it once per route group at startup. X-Forwarded-For is honored only from Config.TrustedProxies; the empty default trusts no proxy (security audit H4).

func (*TheAuth) RecordSessionAuth ¶ added in v2.11.0

func (a *TheAuth) RecordSessionAuth(ctx context.Context, sess *Session, methods ...string) error

RecordSessionAuth appends authentication methods (RFC 8176 values) to the session's record and advances AuthTime to now, atomically. Use it from a host-owned second factor. It returns ErrStorageMissingCapability without SessionAuthStorage.

func (*TheAuth) RecordTokenMinted ¶

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

RecordTokenMinted reports a token mint from an issuer (API tokens, device codes). kind is a short label such as "api"; it must never 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. Presenting an already-rotated token revokes the whole family (RFC 9700 section 4.14).

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.

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 and mints a client_id (plus a secret for confidential clients). The plaintext secret is in the return value only; surface it once and never log it.

func (*TheAuth) RemoveOrganizationMember ¶

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

RemoveOrganizationMember removes a user. It refuses to remove the last owner (ErrLastOwner).

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 without a full session. Pending 2FA sessions are refused; only the TOTP verify routes opt in to RequirePendingOrFull. Errors are RFC 7807 problem+json with a WWW-Authenticate header. The codes are auth.unauthenticated and auth.step_up_required (a pending 2FA session that must complete the second factor).

func (*TheAuth) RequirePendingOrFull ¶

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

RequirePendingOrFull accepts pending_2fa and full sessions. Only the TOTP verify and recovery routes use it.

func (*TheAuth) RequirePermission ¶

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

RequirePermission enforces that the caller holds every named permission in session.active_organization_id. A session with no active organization gets 403 rbac.no_active_org, and the system super_admin bypasses the check. With Config.RBAC nil it returns 500, since wiring the middleware without RBAC is a programming error.

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.

func (*TheAuth) ResetPasswordAdmin ¶

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

ResetPasswordAdmin sets a password without a reset token, revokes sessions and clears lockouts. It enforces the password policy and is meant for a recover-admin command. RequirePasswordChange forces the user to choose their own.

func (*TheAuth) ResumeAgent ¶

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

ResumeAgent sets a suspended agent back to active; a revoked agent cannot be resumed.

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 is terminal: a revoked agent cannot be resumed.

func (*TheAuth) RevokeDelegation ¶

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

RevokeDelegation marks a grant revoked. Tokens minted under it become invalid at the next introspection refresh (worst case IntrospectionCacheTTL).

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

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

RevokeDevice refuses the device's assertions from then on and reports its tokens inactive. Revoking twice succeeds.

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

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

RevokeDeviceJoinToken revokes an unspent device join token.

func (*TheAuth) RevokeOtherSessions ¶

func (a *TheAuth) RevokeOtherSessions(ctx context.Context, userID, keep ULID) (int, error)

RevokeOtherSessions revokes every live session of userID except keep, and returns how many it revoked.

func (*TheAuth) RevokeOwnedSession ¶

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

RevokeOwnedSession revokes one session after confirming it belongs to userID. Another user's session returns ErrStorageNotFound, so ids cannot be probed.

func (*TheAuth) RevokeOwnerAPITokens ¶

func (a *TheAuth) RevokeOwnerAPITokens(ctx context.Context, ownerID ULID) (int, error)

RevokeOwnerAPITokens revokes every live token of an owner. Call it when a user is deleted or a service account is retired.

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

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

RevokeRegistrationToken revokes a token. Revoking twice succeeds.

func (*TheAuth) RevokeRole ¶

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

RevokeRole removes roleID from target and emits role.revoked.

func (*TheAuth) RevokeSCIMToken ¶

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

RevokeSCIMToken marks the token revoked. Revoked tokens still resolve by hash, but the middleware refuses them.

func (*TheAuth) RevokeSession ¶

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

RevokeSession revokes one session by id. It does no ownership check; callers must authorize first.

func (*TheAuth) RevokeSessionsByCredential ¶

func (a *TheAuth) RevokeSessionsByCredential(ctx context.Context, credentialID string) (int, error)

RevokeSessionsByCredential revokes every live session tied to credentialID, for cutting sessions when an upstream credential is revoked. Sessions are also re-checked lazily on use.

func (*TheAuth) RevokeToken ¶

func (a *TheAuth) RevokeToken(ctx context.Context, token, tokenTypeHint, clientID, clientSecret string) error

RevokeToken invalidates a refresh token. Access tokens are stateless JWTs bounded by exp, and codes are single-use.

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

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

RevokeTrustedDevice revokes one of the user's trusted devices. Unknown, foreign or already revoked devices return ErrStorageNotFound.

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

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

RevokeTrustedDevices revokes every trusted device of the user and returns how many it revoked.

func (*TheAuth) RevokeUserSessions ¶

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

RevokeUserSessions revokes every session of userID, unconditionally. To keep one session, re-issue or exclude it yourself.

func (*TheAuth) RotateAgentSecret ¶

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

RotateAgentSecret mints a fresh secret and revokes every prior credential. Use it on suspected compromise; use MintAgentCredential when overlapping credentials are wanted.

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 the old one. Use it after a privilege change.

func (*TheAuth) RotateSigningKey ¶

func (a *TheAuth) RotateSigningKey(ctx context.Context) error

RotateSigningKey advances the JWKS state machine one step. Each call mints a fresh next key, so concurrent calls are safe.

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 default roles for one organization. It is idempotent on (organization_id, name) and reconciles existing roles' permissions against the seed.

func (*TheAuth) SeedPermissions ¶

func (a *TheAuth) SeedPermissions(ctx context.Context) ([]Permission, error)

SeedPermissions ensures every seeded and consumer-extended permission row exists. It is idempotent and runs lazily on the first role seeding, so apps may call it eagerly at startup.

func (*TheAuth) SessionByID ¶

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

SessionByID returns a session's current state (RevokedAt, ExpiresAt) by id. It lets callers resolve a session id from another source, such as an audit actor_session_id, without a token hash.

func (*TheAuth) SetActiveOrganization ¶

func (a *TheAuth) SetActiveOrganization(ctx context.Context, sessionID ULID, orgID *ULID) error

SetActiveOrganization sets (or with a nil orgID clears) the session's active organization. The caller must verify membership first. OnOrgSwitch fires on success in both directions, with an empty string when clearing.

func (*TheAuth) SetAgentExpiry ¶ added in v2.12.0

func (a *TheAuth) SetAgentExpiry(ctx context.Context, agentID ULID, expiresAt *time.Time) error

SetAgentExpiry sets the agent's expiry, or clears it with nil. A non-nil value must be in the future and no more than 10 years ahead (ErrAgentExpiryInvalid otherwise). Past the expiry the agent is denied with ErrAgentExpired, which matches ErrAgentInactive.

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

func (a *TheAuth) SetMustChangePassword(ctx context.Context, userID ULID, required bool) error

SetMustChangePassword flags or unflags userID for a forced password change. Setting it also revokes the user's sessions. Needs Config.AccountState.

func (*TheAuth) SetupToken ¶

func (a *TheAuth) SetupToken() string

SetupToken returns the pending first-run setup token, or "" when Config.Bootstrap is unset or a user exists.

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

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

SharedSignalsHandler returns the transmitter routes (/.well-known/ssf-configuration and /ssf/*), or nil when unset. Mount it at the issuer origin root.

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

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

SharedSignalsReceiverHandler returns the RFC 8935 push endpoint, or nil when no receiver is configured.

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

func (a *TheAuth) SharedSignalsTransmitter() *signals.Transmitter

SharedSignalsTransmitter returns the transmitter, so host code can emit custom events with Emit. Nil when off.

func (*TheAuth) Start ¶

func (a *TheAuth) Start() error

Start spawns the audit writer goroutine when Config.Audit is set. It is idempotent. New calls it automatically.

func (*TheAuth) StartAuthorize ¶

func (a *TheAuth) StartAuthorize(ctx context.Context, req AuthorizeRequest, user *User) (AuthorizeResult, error)

StartAuthorize validates the request. With a non-nil user it mints a code and returns the redirect URL; with nil the caller should redirect to LoginURL.

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.

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 sets status to suspended. Issued tokens mentioning the agent fail on the next introspection refresh.

func (*TheAuth) TOTPStatus ¶

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

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

func (*TheAuth) UnlinkOAuthProvider ¶

func (a *TheAuth) UnlinkOAuthProvider(ctx context.Context, sessionToken, provider string) error

UnlinkOAuthProvider removes a provider from the current user's linked accounts. It returns ErrLastAuthMethod when that provider is the only sign-in method.

func (*TheAuth) UnlockUser ¶

func (a *TheAuth) UnlockUser(ctx context.Context, emailAddr string) error

UnlockUser clears the login and MFA lockouts for an email so the user can retry immediately.

func (*TheAuth) UpdateRole ¶

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

UpdateRole rewrites a role's name, description and permissions. Emits role.updated.

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 returns (nil, ErrNotFound) when the user does not exist. It spares consumers from reaching into storage.

func (*TheAuth) UserCount ¶

func (a *TheAuth) UserCount(ctx context.Context) (int, error)

UserCount returns the number of user records (needs a storage implementing UserCountStorage).

func (*TheAuth) VerifyAuditChain ¶ added in v2.11.0

func (a *TheAuth) VerifyAuditChain(ctx context.Context) (AuditChainResult, error)

VerifyAuditChain verifies the tamper-evident hash chain. Only the sqlite backend keeps a chain; elsewhere it returns Supported and OK both false with ErrAuditChainUnsupported, so an unchecked log is never reported as verified.

func (*TheAuth) VerifyTOTP ¶

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

VerifyTOTP upgrades the pending session to a full one. OnSignin fires here: this is the moment a password sign-in held at pending_2fa becomes a full session.

func (*TheAuth) WarmDummyHash ¶ added in v2.13.0

func (a *TheAuth) WarmDummyHash()

WarmDummyHash computes the timing-equalization hash used for unknown-user sign-ins now, instead of on the first such sign-in. It exists to remove the one-time slower first unknown-user sign-in and is optional. Safe to call more than once and concurrently; it does nothing when password auth is disabled or the hash is already computed.

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 when 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 cause, once it stops validating. It fails closed on errors. Checks do not count as user activity.

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

type TheAuthError ¶

type TheAuthError = models.TheAuthError

TheAuthError is the structured error type returned by service methods. Callers can errors.As it and switch on Code.

func NewError ¶

func NewError(code, message string, inner error) *TheAuthError

NewError constructs a TheAuthError with a code, message and optional wrapped cause.

type TokenExchangeRequest ¶

type TokenExchangeRequest = internalas.TokenExchangeRequest

TokenExchangeRequest is the parsed form body of an RFC 8693 token-exchange call.

type TokenPolicyConfig ¶ added in v2.8.0

type TokenPolicyConfig = internalas.TokenPolicyConfig

TokenPolicyConfig is the root alias for the per-client token policy.

type TokenRequest ¶

type TokenRequest = internalas.TokenRequest

TokenRequest is the parsed form body of POST /oauth/token plus the authenticated client.

type TokenResponse ¶

type TokenResponse = internalas.TokenResponse

TokenResponse is the JSON body emitted by /oauth/token on success.

type TokenVaultStorage ¶ added in v2.11.0

type TokenVaultStorage interface {
	// PutVaultCredential inserts or replaces the credential for (UserID, Provider). Replacement keeps
	// the ID and CreatedAt and bumps Version.
	PutVaultCredential(ctx context.Context, c VaultCredential) (VaultCredential, error)
	VaultCredentialByUserProvider(ctx context.Context, userID, provider string) (*VaultCredential, error)
	// SwapVaultCredential replaces the row only when its stored Version equals expectedVersion. It
	// must be one atomic conditional write and reports false on a version mismatch or a missing row.
	SwapVaultCredential(ctx context.Context, c VaultCredential, expectedVersion int64) (bool, error)
	ListVaultCredentials(ctx context.Context, userID string) ([]VaultCredential, error)
	// ScanVaultCredentials pages through credentials in ID order, for key rotation sweeps.
	ScanVaultCredentials(ctx context.Context, afterID string, limit int) ([]VaultCredential, error)
	DeleteVaultCredential(ctx context.Context, userID, provider string) error
}

TokenVaultStorage is the optional storage capability behind the tokenvault package. Implementations copy slices on the way in and out, and report a missing row as storage.ErrNotFound. There is one credential per (UserID, Provider).

type ToolApproval ¶ added in v2.11.0

type ToolApproval struct {
	ID          string
	AgentID     string
	Action      string
	Resource    string
	Requirement string
	Tier        string
	Reason      string
	Approver    string
	// OpenedBy is the human or service that opened the request, used for the four-eyes check in
	// the approvals package. Empty means unknown, so no self-approval check applies.
	OpenedBy   string
	DeniedBy   string
	CreatedAt  time.Time
	ExpiresAt  time.Time
	ApprovedAt time.Time
	ConsumedAt time.Time
	DeniedAt   time.Time
}

ToolApproval is one approval request for a guarded agent tool call, bound to the agent, action and resource it was opened for.

type ToolApprovalAdminStorage ¶ added in v2.11.0

type ToolApprovalAdminStorage interface {
	ToolApprovalStorage
	GetToolApproval(ctx context.Context, id string) (ToolApproval, bool, error)
	// ListToolApprovals returns requests created newest first, at most limit (0 means 100).
	ListToolApprovals(ctx context.Context, limit int) ([]ToolApproval, error)
	// DenyToolApproval denies id when it is still undecided, unspent and unexpired.
	DenyToolApproval(ctx context.Context, id, denier string, now time.Time) (bool, error)
}

ToolApprovalAdminStorage is the optional capability behind the approvals inbox (the approvals package). Only the memory store implements it today; SQL backends do not. A store that implements it must make ApproveToolApproval fail for a denied request, and DenyToolApproval must be one atomic conditional write deciding the winner by rows affected.

type ToolApprovalStorage ¶ added in v2.11.0

type ToolApprovalStorage interface {
	OpenToolApproval(ctx context.Context, a ToolApproval) error
	ApproveToolApproval(ctx context.Context, id, approver string, now time.Time) (bool, error)
	// ConsumeToolApproval spends id when it is approved, unexpired, unspent and opened for the same
	// agent, action and resource.
	ConsumeToolApproval(ctx context.Context, id, agentID, action, resource string, now time.Time) (bool, error)
}

ToolApprovalStorage is the optional storage capability behind single-use approvals for agent tool calls. The consume step must be one atomic conditional write (for example UPDATE ... WHERE consumed_at IS NULL, deciding the winner by rows affected), so an approval is spent exactly once across the deployment.

type Tracer ¶

type Tracer = observability.Tracer

Tracer starts spans. Adapters implement it; see internal/observability.Tracer for the contract.

type TrustedDevice ¶ added in v2.10.0

type TrustedDevice = models.TrustedDevice

TrustedDevice is a remember-this-device record.

type TrustedDeviceInfo ¶ added in v2.10.0

type TrustedDeviceInfo struct {
	ID          ULID      `json:"id"`
	DeviceLabel string    `json:"deviceLabel"`
	IPPrefix    string    `json:"ipPrefix,omitempty"`
	CreatedAt   time.Time `json:"createdAt"`
	LastUsedAt  time.Time `json:"lastUsedAt"`
	ExpiresAt   time.Time `json:"expiresAt"`
}

TrustedDeviceInfo is the end-user view of one trusted device.

type TrustedDeviceStorage ¶ added in v2.10.0

type TrustedDeviceStorage interface {
	InsertTrustedDevice(ctx context.Context, d TrustedDevice) error
	TrustedDeviceByTokenHash(ctx context.Context, userID ULID, hash []byte) (*TrustedDevice, error)
	// ListTrustedDevices returns the user's unrevoked, unexpired devices, newest first.
	ListTrustedDevices(ctx context.Context, userID ULID) ([]TrustedDevice, error)
	TouchTrustedDevice(ctx context.Context, id ULID, at time.Time) error
	RevokeTrustedDevice(ctx context.Context, userID, id ULID) error
	RevokeUserTrustedDevices(ctx context.Context, userID ULID) (int, error)
}

TrustedDeviceStorage is the optional capability behind Config.TrustedDevices.

type TrustedDevicesConfig ¶ added in v2.10.0

type TrustedDevicesConfig struct {
	TTL        time.Duration
	CookieName string
}

TrustedDevicesConfig enables remember-this-device for TOTP. After a successful second factor the client may send {"rememberDevice": true}; the library sets a signed cookie and stores only its hash. Trust is revoked on password change, TOTP removal, or through the trusted-device list. Needs Config.TOTP and TrustedDeviceStorage.

type TrustedJWTIssuer ¶

type TrustedJWTIssuer struct {
	// Issuer is the exact iss value this trusted issuer places in its JWTs.
	Issuer string

	// JWKSURL is the URL of the issuer's JSON Web Key Set, fetched and cached by the AS.
	JWKSURL string

	// AllowedAlgorithms is the set of JWS algorithms accepted for this issuer (default ES256, RS256, EdDSA).
	AllowedAlgorithms []string

	// SubjectMapper resolves the external JWT's claims to a local user ULID. When nil the built-in
	// SubMapper is used. Use EmailMapper to resolve the email claim to a local user instead.
	SubjectMapper SubjectMapper

	// RequiredClaims are matchers every verified assertion from this issuer must satisfy before it is
	// exchanged. A missing claim fails closed and matching is case sensitive. With none configured
	// every validly signed assertion is accepted, which is unsafe for multi-tenant issuers such as
	// GitHub Actions: see GitHubActionsIssuer.
	RequiredClaims []ClaimMatcher

	// Audience, when non-empty, is the aud value assertions from this issuer must carry instead of the
	// AS issuer URL.
	Audience string
}

TrustedJWTIssuer is one entry in JWTBearerConfig.TrustedJWTIssuers.

func GitHubActionsIssuer ¶ added in v2.11.0

func GitHubActionsIssuer(opts GitHubActionsOptions) (TrustedJWTIssuer, error)

GitHubActionsIssuer returns a TrustedJWTIssuer for GitHub Actions OIDC tokens, with claim matchers built from opts. It returns ErrGitHubActionsUnrestricted unless Repository or RepositoryOwner is set, because GitHub signs tokens for every repository with one key. Append further matchers such as job_workflow_ref to RequiredClaims.

type ULID ¶

type ULID = models.ULID

ULID is the canonical ID type, generated in the app and 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 user attached by Authn middleware, or false for anonymous requests.

type UserCountStorage ¶

type UserCountStorage interface {
	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 UserError ¶ added in v2.12.0

type UserError struct {
	// Code is "USER_INVALID_INPUT", "USER_EMAIL_CONFLICT" or "USER_ID_CONFLICT".
	Code string
	// Message is a human readable detail. It never includes the stored user's data.
	Message string
}

UserError is the typed error returned by CreateUser. Compare with errors.Is against ErrUserInvalidInput, ErrUserEmailConflict or ErrUserIDConflict. Code uses the same names as the TypeScript SDK.

func (*UserError) Error ¶ added in v2.12.0

func (e *UserError) Error() string

func (*UserError) Is ¶ added in v2.12.0

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

Is reports whether target is a *UserError with the same Code, so the Err* sentinels match any message.

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 VaultCredential ¶ added in v2.11.0

type VaultCredential struct {
	ID              string
	UserID          string
	Provider        string
	AccountID       string
	Scopes          []string
	AccessCT        []byte
	RefreshCT       []byte
	AccessExpiresAt time.Time
	Status          string
	// Version is maintained by the store: 1 on first insert, then incremented on each write. It backs
	// compare and swap.
	Version   int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

VaultCredential is one stored third party OAuth credential, keyed by (UserID, Provider). AccessCT and RefreshCT are sealed by the tokenvault package; a store never sees a plaintext token.

type WatchOptions ¶

type WatchOptions = revocation.WatchOptions

WatchOptions tunes WatchRevocation.

type WebAuthnConfig ¶

type WebAuthnConfig struct {
	// RPID is the Relying Party ID, the eTLD+1 of the origin (for example "glinr.com"). Required.
	RPID string
	// RPDisplayName is shown by browsers and authenticators. Required.
	RPDisplayName string
	// RPOrigins lists the origins allowed to call the WebAuthn API, for example ["https://glinr.com"].
	RPOrigins []string
	// ChallengeTTL caps how long a challenge is valid (default 5 minutes; challenges are single-use).
	ChallengeTTL time.Duration
	// RequireUserVerification makes registration and login demand PIN or biometric verification, so a passkey
	// is never a bare possession factor. Default false (UV "preferred").
	RequireUserVerification bool
	// CloneWarning picks what happens when an assertion's sign count fails to advance (a cloned authenticator).
	// The default rejects the login; CloneWarningFlag allows it and emits passkey.clone_warning.
	CloneWarning CloneWarningPolicy
	// UserHandleResolver lets passkeys imported from another system sign in when their user handle is not a
	// theauth handle. It must return the user the handle denotes; login is refused unless that matches the
	// credential's stored owner. Nil accepts only theauth handles.
	UserHandleResolver func(ctx context.Context, credentialID, userHandle []byte) (ULID, error)

	// AttestationPreference is the attestation conveyance requested: "none" (default), "indirect", "direct" or
	// "enterprise". Trust anchors (FIDO MDS) are not configured here.
	AttestationPreference string

	// RequireAttestationStatement rejects registrations with attestation format "none"; pair with "direct".
	RequireAttestationStatement bool

	// AAGUIDAllowlist, when non-empty, accepts only these authenticator models (UUID strings).
	AAGUIDAllowlist []string

	// AAGUIDDenylist rejects these authenticator models and wins over the allowlist.
	AAGUIDDenylist []string

	// AuthenticatorNames maps an AAGUID to a display name for UIs.
	AuthenticatorNames map[string]string

	// AuthenticatorName is an optional lookup consulted before
	// AuthenticatorNames, receiving a lowercase hyphenated AAGUID.
	AuthenticatorName func(aaguid string) string
}

WebAuthnConfig wires the Relying Party identity. Field names mirror go-webauthn/webauthn.Config.

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(ctx context.Context, id, userID ULID, name string) error
}

WebAuthnRenameStorage is the optional capability behind passkey rename (PATCH /auth/webauthn/credentials/{id}).

type WebAuthnStorage ¶

type WebAuthnStorage interface {
	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(ctx context.Context, credentialID []byte) (*WebAuthnCredential, error)
	// UpdateWebAuthnSignCount atomically writes a strictly greater sign count. It returns
	// ErrReplayDetected when the new count is not greater (the WebAuthn replay signal) and
	// ErrStorageNotFound for an unknown credential.
	UpdateWebAuthnSignCount(ctx context.Context, credentialID []byte, newCount uint32, usedAt time.Time) error
	// UpdateWebAuthnBackupFlags is an idempotent trust-on-first-use write of the backup flags for
	// legacy passkeys. Return nil when the credential is missing: a failed reconciliation must never
	// fail an already-verified login.
	UpdateWebAuthnBackupFlags(ctx context.Context, credentialID []byte, backupEligible, backupState bool) error
	// DeleteWebAuthnCredential removes a credential scoped to its owner. It returns ErrStorageNotFound
	// for another user's credential, so cross-user lookups leak nothing.
	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.
Package agentpolicy attaches IAM policy documents to agents, so the library decides what an agent may do.
Package agentpolicy attaches IAM policy documents to agents, so the library decides what an agent may do.
Package approvals is a small HTTP inbox for agent tool approvals: list pending requests, approve or deny them, with a four-eyes rule and an audit row per decision.
Package approvals is a small HTTP inbox for agent tool approvals: list pending requests, approve or deny them, with a four-eyes rule and an audit row per decision.
Package audit exposes the audit event vocabulary, the write-order cursor and the write-order stamp so storage backends in other modules (storage/sqlite) and custom backends share one implementation with the built-in stores.
Package audit exposes the audit event vocabulary, the write-order cursor and the write-order stamp so storage backends in other modules (storage/sqlite) and custom backends share one implementation with the built-in stores.
checkpoint
Package checkpoint implements signed audit checkpoints, Merkle inclusion and consistency proofs, and portable receipts, wire compatible with the TypeScript SDK.
Package checkpoint implements signed audit checkpoints, Merkle inclusion and consistency proofs, and portable receipts, wire compatible with the TypeScript SDK.
sinks/splunkhec
Package splunkhec provides an AuditSink that forwards audit event batches to a Splunk HTTP Event Collector (HEC) endpoint.
Package splunkhec provides an AuditSink that forwards audit event batches to a Splunk HTTP Event Collector (HEC) endpoint.
sinks/webhook
Package webhook provides an AuditSink that POSTs audit events as CloudEvents 1.0 envelopes, HMAC-SHA256 signed.
Package webhook provides an AuditSink that POSTs audit events as CloudEvents 1.0 envelopes, HMAC-SHA256 signed.
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-dev command
Command theauth-dev starts a local in-memory TheAuth server and walks the agent flow end to end: a seeded user and agent, a delegation, allowed and denied guarded tool calls, and a verified audit chain.
Command theauth-dev starts a local in-memory TheAuth server and walks the agent flow end to end: a seeded user and agent, a delegation, allowed and denied guarded tool calls, and a verified audit chain.
theauth-doctor command
Command theauth-doctor prints the security report of a running theauth-go server.
Command theauth-doctor prints the security report of a running theauth-go server.
theauth-go command
Command theauth-go is a small developer CLI for theauth-go projects: secret generation, OpenAPI export, policy tests, database migrations and project scaffolding.
Command theauth-go is a small developer CLI for theauth-go projects: secret generation, OpenAPI export, policy tests, database migrations and project scaffolding.
theauth-loadtest command
Command theauth-loadtest measures theauth-go against a real Postgres under concurrent HTTP load.
Command theauth-loadtest measures theauth-go against a real Postgres under concurrent HTTP load.
theauth-migrate command
Command theauth-migrate converts AWS Cognito, Auth0 and Keycloak user exports into theauth-go storage rows.
Command theauth-migrate converts AWS Cognito, Auth0 and Keycloak user exports into theauth-go storage rows.
theauth-migrate/auth0
Package auth0 reads Auth0 user exports into the migration Bundle.
Package auth0 reads Auth0 user exports into the migration Bundle.
theauth-migrate/cognito
Package cognito reads AWS Cognito user exports and converts them to the migration Bundle.
Package cognito reads AWS Cognito user exports and converts them to the migration Bundle.
theauth-migrate/internal
Package internal defines the shared migration bundle format, applier, and validator used by both the cognito and auth0 sub-commands.
Package internal defines the shared migration bundle format, applier, and validator used by both the cognito and auth0 sub-commands.
theauth-migrate/keycloak
Package keycloak reads a Keycloak realm export into the migration Bundle.
Package keycloak reads a Keycloak realm export into the migration Bundle.
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
agent-policy command
Command agent-policy shows an autonomy denylist enforced as an IAM Deny on an agent.
Command agent-policy shows an autonomy denylist enforced as an IAM Deny on an agent.
agent-tool-guard command
Command agent-tool-guard shows the framework-agnostic tool guard: a refund tool that runs freely for small amounts and needs a human approval above a threshold.
Command agent-tool-guard shows the framework-agnostic tool guard: a refund tool that runs freely for small amounts and needs a human approval above a threshold.
cli-device-login command
Command cli-device-login signs a CLI in with the RFC 8628 device grant.
Command cli-device-login signs a CLI in with the RFC 8628 device grant.
cli-device-login/server command
Command server is a self-contained demo authorization server for cli-device-login: in-memory storage, the device grant and a bare sign-in page.
Command server is a self-contained demo authorization server for cli-device-login: in-memory storage, the device grant and a bare sign-in page.
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.
github-actions-oidc command
GitHub Actions OIDC login, end to end and offline.
GitHub Actions OIDC login, end to end and offline.
hooks command
Command hooks demos Config.LifecycleHooks: /auth/* routes with TOTP enabled and every observe-only hook logging a structured line.
Command hooks demos Config.LifecycleHooks: /auth/* routes with TOTP enabled and every observe-only hook logging a structured line.
oauth-consent command
Host-owned OAuth consent demo.
Host-owned OAuth consent demo.
policy-shrink command
Policy shrink demo.
Policy shrink demo.
taint-guard-go command
Command taint-guard-go shows the taint aware tool guard.
Command taint-guard-go shows the taint aware tool guard.
token-vault command
Command token-vault shows an agent obtaining a short lived access token for a connected provider on behalf of a user, without ever holding the refresh token.
Command token-vault shows an agent obtaining a short lived access token for a connected provider on behalf of a user, without ever holding the refresh token.
token-vault-smoke command
Command token-vault-smoke checks a token vault provider preset against the REAL provider, using your own test credentials.
Command token-vault-smoke checks a token vault provider preset against the REAL provider, using your own test credentials.
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
Command webauthn-passkey is a runnable demo of passkey registration and login on the /auth/* routes with WebAuthn enabled.
Command webauthn-passkey is a runnable demo of passkey registration and login on the /auth/* routes with WebAuthn enabled.
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 serves the /account/* self-service endpoints: the agents and delegation grants a user owns.
Package account serves the /account/* self-service endpoints: the agents and delegation grants a user owns.
admin
Package admin serves the /admin/v1 organization-scoped API: user, session, role, audit and OAuth account management.
Package admin serves the /admin/v1 organization-scoped API: user, session, role, audit and OAuth account management.
agent
Package agent owns the agent identity lifecycle.
Package agent owns the agent identity lifecycle.
agent/handlers
Package handlers serves the organization-scoped agent and delegation admin endpoints under /admin/v1/organizations/{orgID}.
Package handlers serves the organization-scoped agent and delegation admin endpoints under /admin/v1/organizations/{orgID}.
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 implements the OAuth 2.1 and MCP authorization server runtime: JWKS and key rotation, the authorize, token, revoke and introspect services, dynamic client registration, RFC 8414 and RFC 9728 metadata, and RFC 8693 token exchange.
Package as implements the OAuth 2.1 and MCP authorization server runtime: JWKS and key rotation, the authorize, token, revoke and introspect services, dynamic client registration, RFC 8414 and RFC 9728 metadata, and RFC 8693 token exchange.
as/handlers
Package handlers serves the OAuth 2.1 and MCP authorization server HTTP endpoints: metadata, JWKS, authorize, token, revoke, introspect and register.
Package handlers serves the OAuth 2.1 and MCP authorization server HTTP endpoints: metadata, JWKS, authorize, token, revoke, introspect and register.
audit
Package audit defines the Emitter seam that internal service packages depend on.
Package audit defines the Emitter seam 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 chains: depth, scope subset, duration narrowing and act-claim construction.
Package chain provides pure helpers for RFC 8693 actor chains: depth, scope subset, duration narrowing and act-claim construction.
cimd
Package cimd implements Client ID Metadata Documents per the MCP Authorization specification 2025-11-25.
Package cimd implements Client ID Metadata Documents per the MCP Authorization specification 2025-11-25.
clientauthcache
Package clientauthcache caches successful client_secret verifications (Argon2id), so hot endpoints do not pay the Argon2 cost on every request.
Package clientauthcache caches successful client_secret verifications (Argon2id), so hot endpoints do not pay the Argon2 cost on every request.
delegation
Package delegation owns the delegation grant lifecycle: grant, list, revoke, and the Active and NarrowScope helpers the AS uses for token exchange and introspection, so those helpers live in one place.
Package delegation owns the delegation grant lifecycle: grant, list, revoke, and the Active and NarrowScope helpers the AS uses for token exchange and introspection, so those helpers live in one place.
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 DPoP for sender-constrained tokens.
Package dpop implements RFC 9449 DPoP for sender-constrained tokens.
emailnorm
Package emailnorm canonicalizes email addresses, so uniqueness checks and lookups agree on case, whitespace and Unicode forms.
Package emailnorm canonicalizes email addresses, so uniqueness checks and lookups agree on case, whitespace and Unicode 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 holds shared HTTP helpers for the extracted handler packages: the error to status mapping, the {code,message} body, the ULID path parser and the client IP shim.
Package httpx holds shared HTTP helpers for the extracted handler packages: the error to status mapping, the {code,message} body, the ULID path parser and the client IP shim.
identitylink
Package identitylink owns the identity-linking methods: link an OAuth account, link a password, merge accounts and unlink a provider.
Package identitylink owns the identity-linking methods: link an OAuth account, link a password, merge accounts and unlink a provider.
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 JWT surface the authorization server needs: Ed25519 (EdDSA) signing and verification of RFC 9068 access tokens (typ "at+jwt"), plus the RFC 7519 registered claims.
Package jwt implements the JWT surface the authorization server needs: Ed25519 (EdDSA) signing and verification of RFC 9068 access tokens (typ "at+jwt"), plus the RFC 7519 registered claims.
magiclink
Package magiclink owns the request and consume flow for emailed magic-link sign-in tokens.
Package magiclink owns the request and consume flow for emailed magic-link sign-in tokens.
models
Package models is the internal home for the persisted entities (User, Session, OAuthClient, Agent and others), the Permission catalog, and the sentinel errors shared by storage adapters and services.
Package models is the internal home for the persisted entities (User, Session, OAuthClient, Agent and others), the Permission catalog, and the sentinel errors shared by storage adapters and services.
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 /callback endpoints for user-facing OAuth login (Google, GitHub, Discord, Microsoft).
Package handlers exposes the /auth/providers/{name}/start and /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 create, read and member management for multi-tenant organizations.
Package organizations owns create, read and member management 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 and password signup, signin and reset flow.
Package password owns the email and password signup, signin and reset flow.
password/handlers
Package handlers exposes the /auth/email-password/* endpoints for signup, signin, forgot and reset.
Package handlers exposes the /auth/email-password/* endpoints for signup, signin, forgot and reset.
pathprefix
Package pathprefix holds the route prefix default and validation shared by the root package and the internal service packages.
Package pathprefix holds the route prefix default and validation shared by the root package and the internal service packages.
rar
Package rar implements the data model for OAuth 2.0 Rich Authorization Requests (RFC 9396): parsing the authorization_details parameter, serialising it for storage and token claims, and the narrowing rules used when a client asks for less than it was granted.
Package rar implements the data model for OAuth 2.0 Rich Authorization Requests (RFC 9396): parsing the authorization_details parameter, serialising it for storage and token claims, and the narrowing rules used when a client asks for less than it was granted.
ratelimit
Package ratelimit holds the per-key request limiter and the trusted-proxy aware client IP helpers.
Package ratelimit holds the per-key request limiter and the trusted-proxy aware client IP helpers.
rbac
Package rbac owns role and permission management: permission seeding, organization-scoped role CRUD, grant and revoke, and the HasPermission and PermissionsForUser checks used by middleware.
Package rbac owns role and permission management: permission seeding, organization-scoped role CRUD, grant and revoke, and the HasPermission and PermissionsForUser checks used by middleware.
revocation
Package revocation carries credential revocation events, the bus that fans them out, and the watcher that cancels a context when one matches.
Package revocation carries credential revocation events, the bus that fans them out, and the watcher that cancels a context when one matches.
safehttp
Package safehttp builds outbound HTTP clients that refuse to connect to non-public addresses.
Package safehttp builds outbound HTTP clients that refuse to connect to non-public addresses.
saml
Package saml owns the SAML service provider surface: connection CRUD, SP-initiated login, the ACS backend, per-connection SP metadata, and the AuthnRequest tracker that blocks replay.
Package saml owns the SAML service provider surface: connection CRUD, SP-initiated login, the ACS backend, per-connection SP metadata, and the AuthnRequest tracker that blocks replay.
saml/handlers
Package handlers exposes the SAML SP-flow endpoints (/auth/saml/{connectionId}/login, /acs and /metadata).
Package handlers exposes the SAML SP-flow endpoints (/auth/saml/{connectionId}/login, /acs and /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 SCIM parsing helpers the root package uses internally.
Package scim holds the SCIM parsing helpers the root package uses internally.
scim/handlers
Package handlers exposes the /scim/v2/* SCIM 2.0 resource and discovery endpoints, plus the per-organization SCIM token CRUD endpoints 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 under /auth/orgs/{orgId}/scim/tokens.
session
Package session owns the Issue and Validate primitives for opaque session tokens.
Package session owns the Issue and 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 second-factor TOTP: enrollment, verification, recovery codes, and the pending_2fa session minted at sign-in.
Package totp owns second-factor TOTP: enrollment, verification, recovery codes, and the pending_2fa session minted at sign-in.
totp/handlers
Package handlers exposes the /auth/totp/* endpoints for TOTP enrollment, verification, recovery and removal.
Package handlers exposes the /auth/totp/* endpoints for TOTP enrollment, verification, recovery and removal.
trusteddevice
Package trusteddevice implements remember-this-device records that let a password sign-in skip the TOTP prompt for a configurable window.
Package trusteddevice implements remember-this-device records that let a password sign-in skip the TOTP prompt for a configurable window.
wavt
Package wavt is the WebAuthn virtual test helper used to drive the v0.5 passkey ceremony tests.
Package wavt is the WebAuthn virtual test helper used to drive the v0.5 passkey ceremony tests.
webauthn
Package webauthn owns passkey (FIDO2 WebAuthn L3) registration and login ceremonies and the in-memory store of in-flight challenges.
Package webauthn owns passkey (FIDO2 WebAuthn L3) registration and login ceremonies and the in-memory store of in-flight challenges.
webauthn/handlers
Package handlers exposes the /auth/webauthn/* endpoints for passkey registration, login and credential management.
Package handlers exposes the /auth/webauthn/* endpoints for passkey registration, login and credential management.
kv
Package kv defines the small interfaces theauth uses for state that must be shared between replicas: rate-limit counters, replay caches (DPoP jti) and short-lived caches (Client ID Metadata Documents).
Package kv defines the small interfaces theauth uses for state that must be shared between replicas: rate-limit counters, replay caches (DPoP jti) and short-lived caches (Client ID Metadata Documents).
kvtest
Package kvtest is the contract suite for kv.Cache implementations.
Package kvtest is the contract suite for kv.Cache implementations.
redis
Package redis implements kv.Cache on Redis without importing a Redis driver.
Package redis implements kv.Cache on Redis without importing a Redis driver.
sqlkv
Package sqlkv implements kv.Cache on a single table of the SQL database you already run for theauth storage.
Package sqlkv implements kv.Cache on a single table of the SQL database you already run for theauth storage.
Package openapi derives an OpenAPI 3.1 document from a mounted chi router.
Package openapi derives an OpenAPI 3.1 document from a mounted chi router.
Package otp issues and verifies one-time numeric codes delivered over a pluggable channel (email, SMS, or anything else a Sender can reach).
Package otp issues and verifies one-time numeric codes delivered over a pluggable channel (email, SMS, or anything else a Sender can reach).
Package policy is a small, dependency-free authorization engine: JSON policy documents of allow and deny statements over action and resource globs, evaluated with explicit-deny-wins and default-deny semantics.
Package policy is a small, dependency-free authorization engine: JSON policy documents of allow and deny statements over action and resource globs, evaluated with explicit-deny-wins and default-deny semantics.
hook
Package hook runs before authorize hooks: code that sees an agent call after the agent is resolved and may deny it, send it to approval, or let it continue to the normal policy checks.
Package hook runs before authorize hooks: code that sees an agent call after the agent is resolved and may deny it, send it to approval, or let it continue to the normal policy checks.
policytest
Package policytest is a small declarative test kit for policy documents.
Package policytest is a small declarative test kit for policy documents.
shrink
Package shrink applies least privilege to agent authorization.
Package shrink applies least privilege to agent authorization.
toolguard
Package toolguard puts the policy engine in front of an agent tool call.
Package toolguard puts the policy engine in front of an agent tool call.
Package provider is the namespace root for theauth-go's OAuth 2.0 implementations.
Package provider is the namespace root for theauth-go's OAuth 2.0 implementations.
apple
Package apple implements theauth.Provider against Sign In with Apple.
Package apple implements theauth.Provider against Sign In with Apple.
bitbucket
Package bitbucket implements theauth.Provider against Bitbucket Cloud's OAuth 2.0 endpoints.
Package bitbucket implements theauth.Provider against Bitbucket Cloud's OAuth 2.0 endpoints.
discord
Package discord implements theauth.Provider against Discord's OAuth 2.0 endpoints.
Package discord implements theauth.Provider against Discord's OAuth 2.0 endpoints.
facebook
Package facebook implements theauth.Provider against Meta's OAuth 2.0 endpoints.
Package facebook implements theauth.Provider against Meta's OAuth 2.0 endpoints.
generic
Package generic builds theauth.Provider values from a declarative Spec.
Package generic builds theauth.Provider values from a declarative Spec.
github
Package github implements theauth.Provider against GitHub's OAuth 2.0 endpoints.
Package github implements theauth.Provider against GitHub's OAuth 2.0 endpoints.
gitlab
Package gitlab implements theauth.Provider against GitLab's OpenID Connect endpoints.
Package gitlab implements theauth.Provider against GitLab's OpenID Connect endpoints.
google
Package google implements theauth.Provider against Google's OAuth 2.0 and OpenID Connect endpoints.
Package google implements theauth.Provider against Google's OAuth 2.0 and OpenID Connect endpoints.
internal/oauthtest
Package oauthtest provides shared httptest scaffolding for the OAuth provider packages under provider/.
Package oauthtest provides shared httptest scaffolding for the OAuth provider packages under provider/.
internal/refresh
Package refresh implements the RFC 6749 section 6 refresh_token grant shared by the in-tree providers.
Package refresh implements the RFC 6749 section 6 refresh_token grant shared by the in-tree providers.
linkedin
Package linkedin implements theauth.Provider against LinkedIn's OAuth 2.0 and OpenID Connect endpoints.
Package linkedin implements theauth.Provider against LinkedIn's OAuth 2.0 and OpenID Connect endpoints.
microsoft
Package microsoft implements theauth.Provider against Microsoft Entra ID (Azure AD) OAuth 2.0 endpoints.
Package microsoft implements theauth.Provider against Microsoft Entra ID (Azure AD) OAuth 2.0 endpoints.
oidc
Package oidc implements theauth.Provider (and theauth.NonceProvider) for any OpenID Connect issuer using discovery.
Package oidc implements theauth.Provider (and theauth.NonceProvider) for any OpenID Connect issuer using discovery.
slack
Package slack implements theauth.Provider against Slack's OpenID Connect endpoints (Sign in with Slack).
Package slack implements theauth.Provider against Slack's OpenID Connect endpoints (Sign in with Slack).
twitch
Package twitch implements theauth.Provider against Twitch's OpenID Connect endpoints.
Package twitch implements theauth.Provider against Twitch's OpenID Connect endpoints.
x
Package x implements theauth.Provider against X's (formerly Twitter) OAuth 2.0 with PKCE endpoints.
Package x implements theauth.Provider against X's (formerly Twitter) OAuth 2.0 with PKCE endpoints.
Package signals implements the OpenID Shared Signals Framework 1.0 (SSF), with the CAEP and RISC event vocabularies, on top of Security Event Tokens (RFC 8417).
Package signals implements the OpenID Shared Signals Framework 1.0 (SSF), with the CAEP and RISC event vocabularies, on top of Security Event Tokens (RFC 8417).
storetest
Package storetest is the contract suite for signals.Store implementations.
Package storetest is the contract suite for signals.Store implementations.
Package storage re-exports the theauth.Storage interface and the canonical ErrNotFound sentinel that adapters return on lookup misses.
Package storage re-exports the theauth.Storage interface and the canonical ErrNotFound sentinel that adapters return on lookup misses.
memory
Package memory provides an in-process implementation of theauth.Storage backed by Go maps protected by a sync.RWMutex.
Package memory provides an in-process implementation of theauth.Storage backed by Go maps protected by a sync.RWMutex.
mysql
Package mysql provides a MySQL 8.x storage.Storage implementation using database/sql and go-sql-driver/mysql.
Package mysql provides a MySQL 8.x storage.Storage implementation using database/sql and 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 contract test suite for theauth.Storage implementations.
Package storagetest provides a contract test suite for theauth.Storage implementations.
Package tokenvault stores third party OAuth credentials (access and refresh tokens) encrypted at rest and lets an agent obtain a short lived access token for a connected provider on behalf of a user, without the agent ever holding the refresh token.
Package tokenvault stores third party OAuth credentials (access and refresh tokens) encrypted at rest and lets an agent obtain a short lived access token for a connected provider on behalf of a user, without the agent ever holding the refresh token.

Jump to

Keyboard shortcuts

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