theauth

package module
v2.14.0 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: MIT Imports: 93 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 for Go (this repository) theAuth for TypeScript

theauth-go: Go authentication library

One self-hosted Go library for sign-in, passkeys, SSO, SCIM, an OAuth 2.1 and OpenID Connect server, and MCP authorization. It mounts into your net/http app and keeps users and tokens in your database.

CI Release Go Reference OpenSSF Scorecard GitHub stars

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

Quickstart · Security · Stability · Compare · Docs

Useful to you? Star the repo so other Go developers can find it.

Quickstart

Sign-up, sign-in, magic links, sessions and a protected route, stored in one SQLite file. Needs Go 1.26. The SQLite module is experimental; Postgres, MySQL and memory storage are also available. Keep the pinned versions: storage/sqlite v0.3.0 does not compile with v2.13.0.

go get github.com/glincker/theauth-go/v2@v2.13.0 github.com/glincker/theauth-go/storage/sqlite@v0.2.0
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))
}

a.Handler() is a plain http.Handler, so no http.StripPrefix is needed. With chi, call a.Mount(r). More setups are in examples, and install options in docs/INSTALL.md.

What it solves

Your problem What theauth-go does
Adding login to a Go app means stitching several packages together Passwords, magic links, social login, passkeys, TOTP and sessions come from one module
MCP clients expect OAuth 2.1 with discovery and PKCE Runs the authorization server in your process and guards tools with the mcpresource module
A business customer asks for SSO and user provisioning SAML 2.0 service provider, SCIM 2.0, organizations and RBAC (beta)
A hosted identity vendor would own your user table Users, sessions and tokens stay in SQLite, Postgres or MySQL that you run
AI agents need their own credentials and narrower rights Agent identities, delegation and token exchange (experimental)

Features

Area What you get
Sign-in Email and password (Argon2id), magic links, email and SMS codes, 12 social login providers, 16 presets and generic OIDC
Passkeys and MFA WebAuthn passkeys with discoverable login, TOTP with recovery codes, step-up checks
OAuth 2.1 and OIDC server Authorization code with PKCE, refresh rotation, client credentials, token exchange, dynamic registration. OpenID Provider features (ID tokens, userinfo, logout), device grant, PAR, JAR, DPoP and CIBA are experimental
MCP and agents Protected resource metadata (RFC 9728), scope guards for tools. Client ID metadata documents and agent delegation are experimental
SSO and provisioning SAML 2.0 service provider, SCIM 2.0, organizations, RBAC (beta)
APIs and CLIs Scoped API tokens, device login for Go CLIs (RFC 8628, experimental)
Storage Memory, SQLite, Postgres, MySQL, or your own backend checked by a contract suite
Operations Audit log with webhook, Splunk and OTLP sinks, OpenTelemetry, Prometheus, rate limits, a security doctor

Adapters exist for Gin, Echo and Fiber (experimental). Details and guides: docs/FEATURES.md.

Checked against a real MCP client

The official modelcontextprotocol/go-sdk client (v1.8.0) completes discovery, dynamic client registration, PKCE, token exchange and an authenticated tool call in integration/mcp-interop. Login and consent are simulated, so this proves the protocol path, not a production deployment.

Run it with cd integration/mcp-interop && GOWORK=off go run ./cmd/demo.

How it compares

theauth-go Keycloak fosite zitadel/oidc goth authboss
Runs as Library Separate server Library Library Library Library
Password login Yes Yes Yes
Social login Yes Yes Yes, longer list Yes
Passkeys Yes Yes
TOTP Yes Yes Yes
OAuth 2.0 or OIDC server Yes Yes Yes Yes
Device grant Experimental Yes Yes
Token exchange Yes Partial Yes
PAR Experimental Yes Yes
DPoP Experimental Yes
Client ID metadata documents Experimental Experimental
SAML SP only, beta Yes
SCIM Beta Tech preview
Admin console No Yes
OpenID certified No Yes Relying party
License MIT Apache-2.0 Apache-2.0 Apache-2.0 MIT MIT

A blank cell means we did not verify it, not that it is missing. Sources, retrieval date and the cases where each of them beats theauth-go are in docs/COMPARISON.md. Also read when not to use it.

Status

Stable means SemVer applies. Beta means the API is covered by SemVer but there are known behavior or interoperability gaps. Experimental means it may change in a minor release, or the stability policy does not cover it yet.

Area Status Basis
Sign-in, sessions, social login, passkeys, TOTP Stable Root package, listed stable
Authorization server core: code with PKCE, refresh, client credentials, token exchange, discovery, dynamic registration Stable v2.0 commitment in the policy
MCP resource server (mcpresource) and RFC 9728 metadata Stable Listed stable package
OpenID Provider features, device grant, DPoP, CIMD, PAR, JAR, CIBA, RAR, ID-JAG Experimental Not covered by the policy, or listed experimental
Agent identity and delegation Experimental Listed experimental
Persistent sessions Experimental New, ships in the next release (guide)
iot/*, tokenvault, approvals, signals (SSF and CAEP), kv, otp, visitorsignal, agentpolicy, audit/checkpoint Experimental Not in the policy yet
SAML SSO, SCIM, organizations, RBAC Beta API listed stable; no published IdP interop matrix
Memory storage, audit sinks Stable Listed stable
Postgres and MySQL storage Beta The full contract suite runs in CI on Postgres 16 and MySQL 8.4 (storage)
SQLite storage, clientauth, policy, Gin, Echo and Fiber adapters Experimental First three listed experimental; adapters not in the policy

Trust and security

Check it yourself Where
Private vulnerability reporting, or support@glinr.com Security policy
What the authorization server defends against, and its limits Threat model
Tests with the race detector, CodeQL, govulncheck, dependency review, Scorecard Workflows
453 test files and 27 fuzz targets (counted 2026-12-03); line coverage is about 46 percent Proof page, Codecov
Cosign signatures, SBOM and build provenance on v2.8.0 and v2.9.0. v2.10.0 to v2.13.0 have no signed assets because the release workflow failed Verify releases
MIT license, governance and maintainers License, Governance, Maintainers

Know before you adopt: the first commit is dated 2026-06-20, the team is small, and there is no independent security audit or OpenID certification. Levelrail, a product from the same maintainer, imports the library. More in docs/ABOUT.md.

Docs

Start Documentation site · Install · Examples · API reference
Build Features · Agent quickstart · Storage · All repo docs
Move FAQ and migration guides · Changelog
Get help Support · Discussions

Contribute and support the project

Made by

Built by GLINCKER, a GLINR STUDIOS company. More from the team:

GLINR Studios
Open source from the team behind theAuth

Levelrail

Self-hosted deployment platform. Git push, HTTPS, logs, rollback.

theSVG

Open SVG brand library with logos, icons and flags.

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.

Example (ConnectedApps) ¶

Connected apps: users list the OAuth clients they authorized and revoke them, over GET and DELETE /auth/account/connected-apps or from Go.

package main

import (
	"context"
	"fmt"
	"log"

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

func main() {
	store := memory.New()
	a, err := theauth.New(theauth.Config{
		Storage: store,
		BaseURL: "https://app.example.com",
		// Example only: production reads a random 32 byte key from the environment.
		EncryptionKey: []byte("example-encryption-key-32-bytes!"),
		AuthorizationServer: &theauth.AuthorizationServerConfig{
			Issuer: "https://app.example.com",
			Resources: []theauth.ProtectedResource{
				{Identifier: "https://app.example.com/mcp", Scopes: []string{"files.read"}},
			},
			// Lets revocation recall access tokens from resource servers that introspect.
			AccessTokenRevocation: true,
			// Without a consent handler a revoked app reconnects silently.
			ConsentHandler: func(_ context.Context, _ theauth.ConsentRequest) (theauth.ConsentDecision, error) {
				return theauth.ConsentDecision{Action: theauth.ConsentInteract, RedirectToConsentURL: "/consent"}, nil
			},
		},
		ConnectedApps: &theauth.ConnectedAppsConfig{
			OnRevoked: func(_ context.Context, ev theauth.ConnectedAppRevoked) {
				// Forget any consent decision you stored for ev.UserID and ev.ClientID.
				_ = ev
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer a.Close()

	r := chi.NewRouter()
	a.Mount(r)

	ctx := context.Background()
	user, err := store.CreateUser(ctx, theauth.User{ID: theauth.ULID{1}, Email: "a@example.com"})
	if err != nil {
		log.Fatal(err)
	}
	list, err := a.ListConnectedApps(ctx, user.ID)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(len(list.Apps), list.Truncated)
	_, err = a.RevokeConnectedApp(ctx, user.ID, "client-unknown")
	fmt.Println(err)
}
Output:
0 false
theauth: connected app not found
Example (DataExport) ¶

Data export: users download what is stored about them, with the application's own data added.

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/glincker/theauth-go/v2"
	"github.com/glincker/theauth-go/v2/internal/ulid"
	"github.com/glincker/theauth-go/v2/storage/memory"
	"github.com/go-chi/chi/v5"
)

func main() {
	store := memory.New()
	a, err := theauth.New(theauth.Config{
		Storage: store,
		BaseURL: "https://app.example.com",
		DataExport: &theauth.DataExportConfig{
			Extra: func(context.Context, theauth.ULID) (map[string]any, error) {
				return map[string]any{"plan": "pro"}, nil
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer a.Close()

	r := chi.NewRouter()
	a.Mount(r) // adds GET /auth/me/export

	ctx := context.Background()
	u, err := store.CreateUser(ctx, theauth.User{ID: ulid.New(), Email: "ada@example.com", CreatedAt: time.Now()})
	if err != nil {
		log.Fatal(err)
	}
	out, err := a.ExportUserData(ctx, u.ID) // check who is asking before you call this
	if err != nil {
		log.Fatal(err)
	}
	profile := out.Sections[theauth.DataExportSectionProfile].(theauth.DataExportProfile)
	fmt.Println(out.Version, profile.Email, out.Sections[theauth.DataExportSectionExtra])
}
Output:
1 ada@example.com map[plan:pro]
Example (EmailChange) ¶

Email change: users move their account to a new address after confirming it from that mailbox, and the previous address can take it back for a while.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"

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

func main() {
	a, err := theauth.New(theauth.Config{
		Storage:      memory.New(),
		BaseURL:      "https://app.example.com",
		AccountState: true, // an undo then forces a password reset
		EmailChange: &theauth.EmailChangeConfig{
			Allow: func(_ context.Context, u *theauth.User) error {
				if u.EmailVerifiedAt == nil {
					return errors.New("verify your current address first")
				}
				return nil
			},
		},
		// Set EmailSender: the default sender only logs, links included.
	})
	if err != nil {
		log.Fatal(err)
	}
	defer a.Close()

	r := chi.NewRouter()
	a.Mount(r) // adds POST /auth/email/change and the confirm and undo pages

	_, err = a.ConfirmEmailChange(context.Background(), "not-a-live-token")
	var te *theauth.TheAuthError
	fmt.Println(errors.As(err, &te) && te.Code == theauth.CodeEmailChangeInvalid)
}
Output:
true
Example (PasskeySignals) ¶

Passkey signals: what a page hands to the WebAuthn Signal API so a password manager drops deleted passkeys and shows the current name.

package main

import (
	"context"
	"fmt"
	"log"

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

func main() {
	store := memory.New()
	a, err := theauth.New(theauth.Config{
		Storage: store,
		BaseURL: "https://example.com",
		WebAuthn: &theauth.WebAuthnConfig{
			RPID: "example.com", RPDisplayName: "Example", RPOrigins: []string{"https://example.com"},
			// Accept automatic passkey upgrades shortly after a password sign-in.
			AllowConditionalCreate: true,
			// Answer passkey delete and rename with the signal object.
			SignalsInResponses: true,
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer a.Close()

	ctx := context.Background()
	user, err := a.CreateUser(ctx, theauth.CreateUserInput{Email: "ada@example.com", Name: "Ada"})
	if err != nil {
		log.Fatal(err)
	}
	s, err := a.PasskeySignals(ctx, user.ID)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(s.RPID, s.DisplayName, len(s.AllAcceptedCredentialIDs))
}
Output:
example.com Ada 0
Example (PersistentSessions) ¶

Persistent sessions: sign-ins that send "remember": true get a remember cookie, and POST /auth/session/refresh trades it for a new session when the short session ends.

package main

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

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

func main() {
	secret := []byte(os.Getenv("THEAUTH_REMEMBER_SECRET"))
	if len(secret) < 32 {
		// Example only: production reads a shared 32+ byte secret from the environment.
		secret = []byte("example-remember-secret-32-bytes!")
	}
	a, err := theauth.New(theauth.Config{
		Storage:    memory.New(),
		BaseURL:    "https://app.example.com",
		SessionTTL: time.Hour,
		PersistentSessions: &theauth.PersistentSessionsConfig{
			Secret:           secret,
			IdleTimeout:      14 * 24 * time.Hour,
			AbsoluteLifetime: 60 * 24 * time.Hour,
			// Limits can only shorten: here social sign-ins are remembered for one day.
			Limits: func(_ context.Context, in theauth.RememberLimitsInput) theauth.RememberLimits {
				if in.Method == "oauth" {
					return theauth.RememberLimits{AbsoluteLifetime: 24 * time.Hour}
				}
				return theauth.RememberLimits{}
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer a.Close()

	r := chi.NewRouter()
	a.Mount(r)
	// A server-rendered page gate refreshes from the remember cookie when the session is gone.
	r.Get("/app", func(w http.ResponseWriter, req *http.Request) {
		if _, _, err := a.RefreshFromRequest(w, req); err != nil {
			http.Redirect(w, req, "/login", http.StatusSeeOther)
			return
		}
		_, _ = w.Write([]byte("signed in"))
	})
	fmt.Println("mounted")
}
Output:
mounted
Example (SigninNotices) ¶

Sign-in notices: a sign-in from a new browser and security changes reach the user, and the "this was not me" link in a sign-in notice signs every session out.

package main

import (
	"context"
	"fmt"
	"log"

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

func main() {
	a, err := theauth.New(theauth.Config{
		Storage:       memory.New(),
		BaseURL:       "https://app.example.com",
		EncryptionKey: []byte("example-encryption-key-32-bytes!"), // read it from a secret store
		SigninNotices: &theauth.SigninNoticesConfig{
			// Without Notify a plain text mail goes through Config.EmailSender.
			Notify: func(_ context.Context, n theauth.SigninNotice) error {
				// Look the user up by n.UserID and send n.Kind with n.ReportURL. Do not log the URL.
				return nil
			},
		},
		LifecycleHooks: &theauth.LifecycleHooks{
			OnReportedNotMe: func(_ context.Context, u *theauth.User, r theauth.SigninReport) error {
				// Force a password change here, or alert your security team.
				return nil
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer a.Close()

	r := chi.NewRouter()
	a.Mount(r) // adds GET and POST /auth/signin-notices/report
	fmt.Println("mounted")
}
Output:
mounted
Example (SsoDomains) ¶

SSO domains: a SAML connection claims an email domain, proves it with a DNS TXT record, and addresses at that domain are then routed to it.

package main

import (
	"context"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"fmt"
	"log"
	"math/big"
	"time"

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

// exampleDNS stands in for the real zone: the record the domain owner would publish.
type exampleDNS map[string][]string

func (d exampleDNS) LookupTXT(_ context.Context, name string) ([]string, error) { return d[name], nil }

// exampleKeypair makes a throwaway certificate. Use your own SP keypair and the IdP's certificate.
func exampleKeypair() (certPEM, keyPEM []byte) {
	k, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		log.Fatal(err)
	}
	tpl := &x509.Certificate{
		SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "example"},
		NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour),
	}
	der, err := x509.CreateCertificate(rand.Reader, tpl, tpl, &k.PublicKey, k)
	if err != nil {
		log.Fatal(err)
	}
	return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}),
		pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)})
}

// SSO domains: a SAML connection claims an email domain, proves it with a DNS TXT record, and
// addresses at that domain are then routed to it.
func main() {
	ctx := context.Background()
	cert, key := exampleKeypair()
	dns, store := exampleDNS{}, memory.New()
	a, err := theauth.New(theauth.Config{
		Storage:       store,
		BaseURL:       "https://app.example.com",
		Organizations: &theauth.OrganizationsConfig{},
		SAML:          &theauth.SAMLConfig{SPCertificatePEM: cert, SPPrivateKeyPEM: key},
		SSODomains: &theauth.SSODomainsConfig{
			RequireVerified: true,
			Resolver:        dns, // omit to use the system resolver
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer a.Close()

	owner, err := store.CreateUser(ctx, theauth.User{ID: theauth.ULID{1}, Email: "owner@acme.example"})
	if err != nil {
		log.Fatal(err)
	}
	org, err := a.CreateOrganization(ctx, "Acme", "acme", owner.ID)
	if err != nil {
		log.Fatal(err)
	}
	conn, err := a.CreateSAMLConnection(ctx, theauth.SAMLConnectionInput{
		OrganizationID: org.ID, IdPEntityID: "https://idp.example.com", IdPSSOURL: "https://idp.example.com/sso",
		IdPX509Cert: string(cert), SPEntityID: "https://app.example.com/saml",
		SPACSURL: "https://app.example.com/auth/saml/acs", AttributeMap: theauth.DefaultSAMLAttributeMap(),
	})
	if err != nil {
		log.Fatal(err)
	}

	d, err := a.AddSSODomain(ctx, conn.ID, "Acme.example")
	if err != nil {
		log.Fatal(err)
	}
	_, found, _ := a.SSOConnectionForEmail(ctx, "jane@acme.example")
	fmt.Println(d.RecordName, found)

	dns[d.RecordName] = []string{d.RecordValue}
	if _, err := a.VerifySSODomain(ctx, d.ID); err != nil {
		log.Fatal(err)
	}
	got, found, _ := a.SSOConnectionForEmail(ctx, "jane@acme.example")
	fmt.Println(found, got.ID == conn.ID)
}
Output:
_theauth-challenge.acme.example false
true true

Index ¶

Examples ¶

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 (
	// CaptchaSignUp is POST {PathPrefix}/email-password/signup.
	CaptchaSignUp = "sign-up"
	// CaptchaSignIn is POST {PathPrefix}/email-password/signin.
	CaptchaSignIn = "sign-in"
	// CaptchaMagicLink is POST {PathPrefix}/magic-link.
	CaptchaMagicLink = "magic-link"
	// CaptchaPasswordReset is POST {PathPrefix}/email-password/forgot, the reset request.
	CaptchaPasswordReset = "reset-password"
)

Endpoint names for CaptchaConfig.Endpoints.

View Source
const (
	CaptchaBodyField            = captcha.BodyField
	DefaultCaptchaTokenHeader   = captcha.DefaultTokenHeader
	DefaultCaptchaTimeout       = captcha.DefaultTimeout
	DefaultCaptchaMaxTokenBytes = captcha.DefaultMaxTokenBytes
	DefaultCaptchaMaxBodyBytes  = captcha.DefaultMaxBodyBytes
	DefaultRecaptchaMinScore    = captcha.DefaultRecaptchaMinScore
)

Captcha wire names and the defaults of CaptchaConfig.

View Source
const (
	CodeCaptchaRequired = "captcha_required"
	CodeCaptchaFailed   = "captcha_failed"
)

Captcha error codes, both sent with status 400.

View Source
const (
	ConsentApprove          = internalas.ConsentApprove
	ConsentDeny             = internalas.ConsentDeny
	ConsentInteract         = internalas.ConsentInteract
	ConsentSourceRegistered = internalas.ConsentSourceRegistered
	ConsentSourceCIMD       = internalas.ConsentSourceCIMD
)
View Source
const (
	DeviceJoinTokenSingle = internalas.JoinTokenKindSingle
	DeviceJoinTokenClaim  = internalas.JoinTokenKindClaim
	DeviceJoinTokenBulk   = internalas.JoinTokenKindBulk
)

Kinds of device enrollment token for CreateDeviceJoinTokenInput.Kind.

View Source
const (
	ConnectedAppSourceRegistered      = models.ConnectedAppSourceRegistered
	ConnectedAppSourceDCR             = models.ConnectedAppSourceDCR
	ConnectedAppSourceCIMD            = models.ConnectedAppSourceCIMD
	ConnectedAppSourceUnknown         = models.ConnectedAppSourceUnknown
	ConnectedAppAccessRevoked         = models.ConnectedAppAccessRevoked
	ConnectedAppAccessExpireNaturally = models.ConnectedAppAccessExpireNaturally
)

Values of ConnectedApp.Source and ConnectedAppRevokeResult.AccessTokens.

View Source
const (
	CodeConnectedAppNotFound     = "connected_app_not_found"
	CodeConnectedAppsUnavailable = "connected_apps_unavailable"
	CodeSessionRequired          = "session_required"
)

Error codes of the connected apps routes. They appear only when Config.ConnectedApps is set.

View Source
const (
	DataExportSectionProfile            = "profile"
	DataExportSectionIdentities         = "identities"
	DataExportSectionSessions           = "sessions"
	DataExportSectionRememberedDevices  = "rememberedDevices"
	DataExportSectionPasskeys           = "passkeys"
	DataExportSectionTOTP               = "totp"
	DataExportSectionTrustedDevices     = "trustedDevices"
	DataExportSectionAPIKeys            = "apiKeys"
	DataExportSectionOrganizations      = "organizations"
	DataExportSectionRoles              = "roles"
	DataExportSectionConnectedApps      = "connectedApps"
	DataExportSectionKnownDevices       = "knownDevices"
	DataExportSectionSigninReports      = "signinReports"
	DataExportSectionPendingEmailChange = "pendingEmailChange"
	DataExportSectionAgents             = "agents"
	DataExportSectionDelegations        = "delegations"
	DataExportSectionAuditLogs          = "auditLogs"
	DataExportSectionExtra              = "extra"
)

Names of the sections of a data export.

View Source
const (
	// CodeEmailChangeInvalid is returned, with status 410, for a link that is unknown, used,
	// expired or can no longer be applied.
	CodeEmailChangeInvalid = "email_change_invalid"
	// CodeEmailChangeNotAllowed is returned, with status 403, when the account may not change its address.
	CodeEmailChangeNotAllowed = "email_change_not_allowed"
	// CodeInvalidEmail is returned, with status 400, for a malformed address.
	CodeInvalidEmail = "invalid_email"
	// CodeEmailUnchanged is returned, with status 400, when the new address is the current one.
	CodeEmailUnchanged = "email_unchanged"
)

Error codes of email change. They appear only when Config.EmailChange is set.

View Source
const (
	DoctorEmailChangeNoDelivery    = doctor.DoctorEmailChangeNoDelivery
	DoctorEmailChangeNoForcedReset = doctor.DoctorEmailChangeNoForcedReset
)

Email change doctor finding IDs.

View Source
const (
	EmailChangeKindConfirm = models.EmailChangeKindConfirm
	EmailChangeKindUndo    = models.EmailChangeKindUndo
)

The kinds of an EmailChangeRecord.

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
	DeviceStatusSuspended = models.DeviceStatusSuspended
	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
	// DoctorWebAuthnUnknownSignalShared reports passkey_unknown on an RP ID other hosts can share.
	DoctorWebAuthnUnknownSignalShared = doctor.DoctorWebAuthnUnknownSignalShared
	DoctorRedirectAllowList           = doctor.DoctorRedirectAllowList
	DoctorCookieDomain                = doctor.DoctorCookieDomain
	DoctorCookieNoneOpen              = doctor.DoctorCookieNoneOpen
	DoctorSecurityHeadersOff          = doctor.DoctorSecurityHeadersOff
	DoctorConnectedNoConsent          = doctor.DoctorConnectedNoConsent
	DoctorConnectedNoDenylist         = doctor.DoctorConnectedNoDenylist
	DoctorConnectedNoSkew             = doctor.DoctorConnectedNoSkew
)
View Source
const (
	CodePasskeyUnknown              = models.CodePasskeyUnknown
	CodeConditionalCreateDisabled   = models.CodeConditionalCreateDisabled
	CodeConditionalCreateNotAllowed = models.CodeConditionalCreateNotAllowed
)

Error codes of the passkey lifecycle responses.

View Source
const (
	CodeSessionExpired     = "session_expired"
	CodeRememberInvalid    = "remember_invalid"
	CodeRememberExpired    = "remember_expired"
	CodeRememberReused     = "remember_reused"
	CodeRefreshDenied      = "refresh_denied"
	CodeRefreshUnavailable = "refresh_unavailable"
)

Error codes of persistent sessions. They appear only when Config.PersistentSessions is set.

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 AuditCaptchaFailed = "captcha.failed"

AuditCaptchaFailed is the audit action of a refused captcha check.

View Source
const AuditConnectedAppRevoked = "oauth.connected_app.revoked"

AuditConnectedAppRevoked is the audit action of a successful revocation.

View Source
const AuditDataExported = "user.data_exported"

AuditDataExported is the audit action of a successful export.

View Source
const BackchannelStatusConsumed = "consumed"

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

View Source
const CodeReportLinkInvalid = "report_link_invalid"

CodeReportLinkInvalid is returned, with status 410, for a report link that is unknown, used or expired.

View Source
const CodeSSOConnectionNotFound = "sso_connection_not_found"

CodeSSOConnectionNotFound is returned, with status 404, by POST /sso/discover for every address that routes nowhere.

View Source
const DataExportVersion = 1

DataExportVersion is the value of UserDataExport.Version. It changes when a section changes incompatibly.

View Source
const DeviceAttestationJoinToken = models.DeviceAttestationJoinToken

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

View Source
const DoctorAuthZENNoAuthorize = doctor.DoctorAuthZENNoAuthorize

DoctorAuthZENNoAuthorize reports an AuthZEN decision point mounted without an Authorize hook.

View Source
const DoctorAuthZENNoRateLimit = doctor.DoctorAuthZENNoRateLimit

DoctorAuthZENNoRateLimit reports an AuthZEN decision point mounted without a rate limit.

View Source
const DoctorCaptchaFailOpen = doctor.DoctorCaptchaFailOpen

DoctorCaptchaFailOpen reports Config.Captcha with FailOpen set.

View Source
const DoctorCaptchaNoHostname = doctor.DoctorCaptchaNoHostname

DoctorCaptchaNoHostname reports Config.Captcha without CaptchaConfig.Hostname.

View Source
const DoctorSSODomainsUnverifiedRouting = doctor.DoctorSSODomainsUnverifiedRouting

DoctorSSODomainsUnverifiedRouting is the SSO domains doctor finding ID.

View Source
const DoctorSigninNoticesNoDelivery = doctor.DoctorSigninNoticesNoDelivery

DoctorSigninNoticesNoDelivery reports sign-in notices that have no way to reach the user.

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 (
	ErrConnectedAppNotFound  = models.ErrConnectedAppNotFound
	ErrConnectedAppsDisabled = errors.New("theauth: connected apps are not enabled")
)

Connected apps errors. Match them with errors.Is.

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

	// ErrAuditProvenanceUnsupported is returned by QueryAudit when the query has a Provenance filter
	// and the storage backend does not declare AuditProvenanceSupported() true.
	ErrAuditProvenanceUnsupported = models.ErrAuditProvenanceUnsupported

	// ErrBadProvenanceFilter is returned for a provenance filter with an unknown kind or a bad hash.
	ErrBadProvenanceFilter = models.ErrBadProvenanceFilter

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

	// ErrDeviceAttestationRequired is returned by enrollment when attestation evidence is required
	// (DeviceAttestationConfig.Required) and missing.
	ErrDeviceAttestationRequired = models.ErrDeviceAttestationRequired

	// ErrDeviceAttestationFailed is returned by enrollment when the attestation verifier refused
	// the evidence. Use errors.As with *DeviceAttestationError for the reason.
	ErrDeviceAttestationFailed = models.ErrDeviceAttestationFailed

	ErrDeviceConflict = models.ErrDeviceConflict

	// ErrDeviceRevoked is returned when a revoked device is suspended or resumed.
	ErrDeviceRevoked = models.ErrDeviceRevoked

	// 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 (
	// ErrPasskeyUnknown is wrapped by a login whose credential id is not stored.
	ErrPasskeyUnknown              = models.ErrPasskeyUnknown
	ErrConditionalCreateDisabled   = models.ErrConditionalCreateDisabled
	ErrConditionalCreateNotAllowed = models.ErrConditionalCreateNotAllowed
)

Passkey lifecycle errors. Match them with errors.Is.

View Source
var (
	ErrRememberInvalid            = persist.ErrInvalid
	ErrRememberExpired            = persist.ErrExpired
	ErrRememberReused             = persist.ErrReused
	ErrRefreshDenied              = persist.ErrDenied
	ErrRefreshUnavailable         = persist.ErrUnavailable
	ErrPersistentSessionsDisabled = errors.New("theauth: persistent sessions are not enabled")
)

Refresh errors. Match them with errors.Is.

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 (
	// ErrSSODomainsDisabled is returned by the domain methods when Config.SSODomains is nil.
	ErrSSODomainsDisabled = errors.New("theauth: sso domains are not enabled")
	// ErrSSODomainInvalid refuses a name that cannot be claimed.
	ErrSSODomainInvalid = ssodomain.ErrInvalidDomain
	// ErrSSODomainNotFound is returned for an unknown domain id.
	ErrSSODomainNotFound = ssodomain.ErrNotFound
	// ErrSSODomainUnproven means the TXT record is missing or holds another value.
	ErrSSODomainUnproven = ssodomain.ErrUnproven
	// ErrSSODomainLookupFailed means DNS gave no usable answer.
	ErrSSODomainLookupFailed = ssodomain.ErrLookupFailed
	// ErrSSODomainLimit refuses a claim beyond MaxDomainsPerConnection.
	ErrSSODomainLimit = ssodomain.ErrLimit
	// ErrSSODomainTaken means another connection holds the verified claim.
	ErrSSODomainTaken = models.ErrSSODomainTaken
	// ErrSSODomainUnverified is returned by FinishSAMLLogin under RequireVerified.
	ErrSSODomainUnverified = models.ErrSSODomainUnverified
)

Errors of SSO domain verification.

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 ErrCaptchaUnavailable = captcha.ErrUnavailable

ErrCaptchaUnavailable is what a CaptchaVerifier wraps when the check could not be made. Only such errors, and running past CaptchaConfig.Timeout, are let through by FailOpen.

View Source
var ErrDataExportDisabled = errors.New("theauth: data export is not enabled")

ErrDataExportDisabled is returned by ExportUserData when Config.DataExport is nil.

View Source
var ErrDeviceAppAssertion = internalas.ErrDeviceAppAssertion

ErrDeviceAppAssertion matches every *DeviceAppAssertionError with errors.Is.

View Source
var ErrEmailChangeAddressTaken = models.ErrEmailChangeAddressTaken

ErrEmailChangeAddressTaken is returned by EmailChangeStorage when the unique email constraint refuses the target address.

View Source
var ErrEmailChangeDisabled = errors.New("theauth: email change is not enabled")

ErrEmailChangeDisabled is returned by the email change methods when Config.EmailChange is nil.

View Source
var ErrEmailChangeUndoCancelDisabled = errors.New("theauth: cancelling email change undo is not enabled")

ErrEmailChangeUndoCancelDisabled is returned by CancelEmailChangeUndo unless EmailChangeConfig.AllowUndoCancel is set.

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 ErrSSODomainExists = models.ErrSSODomainExists

ErrSSODomainExists is returned by SSODomainStorage when the connection already lists the domain.

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 DeviceAttestationFacts ¶ added in v2.14.0

func DeviceAttestationFacts(d Device) (device.AttestationFacts, bool)

DeviceAttestationFacts projects the verified attestation claims stored on a device (Device.AttestationClaims) into the facts policy reads: securityLevel (software, hardware or strongbox), bootState and the attested app ids. Put the result in device.Claims.Attestation before signing an offline bundle (device.Signer.SignBundle), and permissions with an attestation constraint are then decided against it offline, exactly as the TypeScript SDK decides them. The second result is false for a device without hardware evidence and for claims of a format this SDK does not know (a custom verifier's): such a device satisfies no attestation constraint.

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 RememberFromContext ¶ added in v2.14.0

func RememberFromContext(ctx context.Context) (token string, expires time.Time, ok bool)

RememberFromContext returns the remember token minted under a WithRemember context, if any. Send it with SetRememberCookie.

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.

func WithRemember ¶ added in v2.14.0

func WithRemember(ctx context.Context, remember bool) context.Context

WithRemember marks ctx so the next full session issued under it is remembered (or not). Use it around a custom sign-in, then read the token with RememberFromContext.

func WithRememberMethod ¶ added in v2.14.0

func WithRememberMethod(ctx context.Context, remember bool, method string) context.Context

WithRememberMethod is WithRemember that also records the sign-in method shown in the device list, for custom flows such as an email code.

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

	// InputHashKey keys the hashes of input content declared with audit.WithInputs (HMAC-SHA256 under
	// a subkey derived from this key). Without it the hash is plain SHA-256, which anyone can compute
	// for a guessable input such as a one word message. At least 16 bytes. Keep it apart from other
	// secrets, and keep it stable: changing it changes the hash of the same content, so older rows
	// no longer match a filter built with the new key.
	InputHashKey []byte

	// PseudonymRotation turns on rotating pseudonyms for the personal ids in the audit chain. The
	// storage backend must implement AuditPseudonymRotator (memory, sqlite, postgres and mysql do),
	// otherwise New fails. Rows written before it was turned on keep their stable pseudonym and still
	// verify.
	PseudonymRotation *PseudonymRotation
}

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 AuditProvenanceFilter ¶ added in v2.14.0

type AuditProvenanceFilter = models.ProvenanceFilter

AuditProvenanceFilter is AuditQuery.Provenance.

type AuditPseudonymRotator ¶ added in v2.14.0

type AuditPseudonymRotator interface {
	// SetAuditPseudonymRotation turns rotation on with r.
	SetAuditPseudonymRotation(r PseudonymRotation) error
	// ShredAuditPseudonyms deletes the period secrets outside the retention window now and returns
	// the periods shredded. After it nobody can link those periods to any other.
	ShredAuditPseudonyms(ctx context.Context) ([]int64, error)
}

AuditPseudonymRotator is implemented by storage backends that can rotate audit pseudonyms.

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

	// ReauthTTL is how long a prompt=login or max_age=0 demand stays open for the user to sign in
	// again (default 10 minutes).
	ReauthTTL 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
	// IntrospectionCacheMaxEntries bounds the cached active introspection answers, least recently
	// used first out. Zero means 10000, negative disables the cache.
	IntrospectionCacheMaxEntries int

	// 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 CaptchaConfig ¶ added in v2.14.0

type CaptchaConfig struct {
	// Verifier checks tokens, see NewTurnstileVerifier, NewHCaptchaVerifier and
	// NewRecaptchaVerifier.
	Verifier CaptchaVerifier
	// Endpoints names the guarded routes (default all of CaptchaSignUp, CaptchaSignIn,
	// CaptchaMagicLink and CaptchaPasswordReset).
	Endpoints []string
	// FailOpen lets a request with a token through when the check cannot be made, logging each one
	// at error level. The default refuses it. A missing or rejected token, and a provider answering
	// 429, are always refused.
	FailOpen bool
	// Timeout bounds one verification (default DefaultCaptchaTimeout).
	Timeout time.Duration
	// TokenHeader carries the token (default DefaultCaptchaTokenHeader).
	TokenHeader string
	// Hostname, when set, is the hostname the challenge must have been solved on.
	Hostname string
	// Actions overrides the expected action per endpoint name. The default is the endpoint name
	// with "_" for "-", for example "sign_in". An empty value skips the check for that endpoint.
	Actions map[string]string
	// MaxTokenBytes caps a token (default DefaultCaptchaMaxTokenBytes).
	MaxTokenBytes int
	// MaxBodyBytes caps the body buffered to find the token (default DefaultCaptchaMaxBodyBytes).
	// The guarded handlers read at most 16 KiB.
	MaxBodyBytes int64
}

CaptchaConfig requires a solved captcha on selected public endpoints. Only Verifier is required. The token is read from TokenHeader, or from the "captchaToken" member of a JSON body.

Example ¶
package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

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

// demoCaptcha accepts one fixed token. Use NewTurnstileVerifier, NewHCaptchaVerifier or
// NewRecaptchaVerifier with your provider secret.
type demoCaptcha struct{}

func (demoCaptcha) Verify(_ context.Context, in theauth.CaptchaInput) error {
	if in.Token != "solved" {
		return errors.New("not solved")
	}
	return nil
}

func main() {
	a, err := theauth.New(theauth.Config{
		Storage: memory.New(),
		BaseURL: "http://localhost",
		Captcha: &theauth.CaptchaConfig{Verifier: demoCaptcha{}},
	})
	if err != nil {
		panic(err)
	}
	defer a.Close()
	r := chi.NewRouter()
	a.Mount(r)

	for _, body := range []string{
		`{"email":"ada@example.com"}`,
		`{"email":"ada@example.com","captchaToken":"guess"}`,
		`{"email":"ada@example.com","captchaToken":"solved"}`,
	} {
		req := httptest.NewRequest(http.MethodPost, "/auth/magic-link", strings.NewReader(body))
		req.Header.Set("Content-Type", "application/json")
		w := httptest.NewRecorder()
		r.ServeHTTP(w, req)
		fmt.Println(w.Code, strings.TrimSpace(w.Body.String()))
	}
}
Output:
400 {"code":"captcha_required","message":"captcha token required"}
400 {"code":"captcha_failed","message":"captcha verification failed"}
200 {"sent":true}

type CaptchaInput ¶ added in v2.14.0

type CaptchaInput = captcha.Input

CaptchaInput is one token to verify.

type CaptchaVerifier ¶ added in v2.14.0

type CaptchaVerifier = captcha.Verifier

CaptchaVerifier checks a token. Nil accepts it. An error wrapping ErrCaptchaUnavailable means the check could not be made; any other error rejects the token. It must honor the context.

func NewHCaptchaVerifier ¶ added in v2.14.0

func NewHCaptchaVerifier(secret string, client *http.Client) (CaptchaVerifier, error)

NewHCaptchaVerifier verifies hCaptcha tokens. A nil client uses the default transport.

func NewRecaptchaVerifier ¶ added in v2.14.0

func NewRecaptchaVerifier(secret string, minScore float64, client *http.Client) (CaptchaVerifier, error)

NewRecaptchaVerifier verifies reCAPTCHA v3 tokens scoring at least minScore (zero means DefaultRecaptchaMinScore). A nil client uses the default transport.

func NewTurnstileVerifier ¶ added in v2.14.0

func NewTurnstileVerifier(secret string, client *http.Client) (CaptchaVerifier, error)

NewTurnstileVerifier verifies Cloudflare Turnstile tokens. A nil client uses the default transport.

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
	// PersistentSessions enables "keep me signed in" with rotating remember tokens when non-nil.
	// Needs PersistentSessionStorage. See PersistentSessionsConfig.
	//
	// Experimental: may change in a minor release. See docs/STABILITY-AND-SECURITY.md.
	PersistentSessions *PersistentSessionsConfig
	// ConnectedApps lets a user list and revoke the OAuth clients they authorized when non-nil.
	// Needs AuthorizationServer and ConnectedAppStorage. See ConnectedAppsConfig.
	ConnectedApps *ConnectedAppsConfig
	// DataExport lets a user download everything stored about them when non-nil.
	// See DataExportConfig.
	DataExport *DataExportConfig
	// EmailChange lets a signed in user change their sign-in address when non-nil. Needs
	// EmailChangeStorage. See EmailChangeConfig.
	EmailChange *EmailChangeConfig
	// SSODomains adds DNS ownership proof for SAML connection domains and home realm discovery when
	// non-nil. Needs SAML and SSODomainStorage. See SSODomainsConfig.
	SSODomains   *SSODomainsConfig
	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

	// SigninNotices sends new device sign-in and security change notices with a "this was not me"
	// link when non-nil. Needs KnownDeviceStorage. See docs/signin-notices.md.
	SigninNotices *SigninNoticesConfig
	// Captcha requires a solved captcha on public sign-up, sign-in and mail sending endpoints when
	// non-nil. See docs/captcha.md.
	Captcha *CaptchaConfig
	// 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 ConnectedApp ¶ added in v2.14.0

type ConnectedApp = models.ConnectedApp

ConnectedApp, ConnectedAppList and ConnectedAppRevokeResult are the connected apps results.

type ConnectedAppList ¶ added in v2.14.0

type ConnectedAppList = models.ConnectedAppList

ConnectedApp, ConnectedAppList and ConnectedAppRevokeResult are the connected apps results.

type ConnectedAppRevokeResult ¶ added in v2.14.0

type ConnectedAppRevokeResult = models.ConnectedAppRevokeResult

ConnectedApp, ConnectedAppList and ConnectedAppRevokeResult are the connected apps results.

type ConnectedAppRevoked ¶ added in v2.14.0

type ConnectedAppRevoked struct {
	UserID    ULID
	ClientID  string
	RevokedAt time.Time
	// AccessTokens is ConnectedAppAccessRevoked or ConnectedAppAccessExpireNaturally.
	AccessTokens string
}

ConnectedAppRevoked describes one revocation handed to ConnectedAppsConfig.OnRevoked.

type ConnectedAppStorage ¶ added in v2.14.0

type ConnectedAppStorage = internalas.ConnectedAppStorage

ConnectedAppStorage is the optional capability behind Config.ConnectedApps. It is detected by type assertion and is not part of Storage. storagetest.RunConnectedApps checks the contract.

type ConnectedAppsConfig ¶ added in v2.14.0

type ConnectedAppsConfig struct {
	// ClockSkew widens a revocation: evidence issued up to this long after it is refused too, which
	// covers clock differences between instances. Default 2s; negative means none.
	ClockSkew time.Duration
	// OnRevoked runs after a successful revocation, for example to drop a stored consent decision.
	OnRevoked func(ctx context.Context, ev ConnectedAppRevoked)
	// MaxApps caps a listing; the result reports Truncated beyond it. Default 200.
	MaxApps int
	// MaxClientIDLength is the longest client id, in bytes, the authorization server accepts while
	// connected apps are on, which bounds what a revocation can store. Default 1024, at most 2048.
	MaxClientIDLength int
	// MetadataTimeout is the total time one listing may spend fetching client metadata documents.
	// Default 5s.
	MetadataTimeout time.Duration
	// MetadataLookupTimeout bounds each metadata document fetch of a listing. Default 2s.
	MetadataLookupTimeout time.Duration
	// MetadataConcurrency is how many metadata documents one listing fetches at once. Default 8.
	MetadataConcurrency int
	// ListRateLimitPerIP is the per-IP per-minute budget of the listing route. Default 60.
	ListRateLimitPerIP int
	// RevokeRateLimitPerIP is the per-IP per-minute budget of the revoke route. Default 30.
	RevokeRateLimitPerIP int
	// RevokeRateLimitPerUser is the per-user per-minute budget of the revoke route. Default 30.
	RevokeRateLimitPerUser int
}

ConnectedAppsConfig turns on connected apps: a user can list the OAuth clients of this authorization server that hold a live refresh token for them, and revoke one. Nil (the default) mounts no routes and changes nothing. Requires Config.AuthorizationServer and storage implementing ConnectedAppStorage. See docs/connected-apps.md.

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 DataExportAPIKey ¶ added in v2.14.0

type DataExportAPIKey struct {
	ID         ULID       `json:"id"`
	Name       string     `json:"name"`
	Kind       string     `json:"kind,omitempty"`
	AgentName  string     `json:"agentName,omitempty"`
	AgentID    *ULID      `json:"agentId,omitempty"`
	Abilities  []string   `json:"abilities"`
	CreatedAt  time.Time  `json:"createdAt"`
	ExpiresAt  *time.Time `json:"expiresAt,omitempty"`
	LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`
	RevokedAt  *time.Time `json:"revokedAt,omitempty"`
}

DataExportAPIKey is the metadata of one API token, an entry of the "apiKeys" section.

type DataExportAgent ¶ added in v2.14.0

type DataExportAgent struct {
	ID             ULID       `json:"id"`
	Name           string     `json:"name"`
	Description    string     `json:"description,omitempty"`
	Status         string     `json:"status"`
	ClientID       string     `json:"clientId"`
	Scope          []string   `json:"scope,omitempty"`
	OrganizationID *ULID      `json:"organizationId,omitempty"`
	CreatedAt      time.Time  `json:"createdAt"`
	LastActiveAt   *time.Time `json:"lastActiveAt,omitempty"`
	ExpiresAt      *time.Time `json:"expiresAt,omitempty"`
}

DataExportAgent is one agent the user owns, an entry of the "agents" section.

type DataExportAuditEvent ¶ added in v2.14.0

type DataExportAuditEvent struct {
	ID        ULID      `json:"id"`
	Action    string    `json:"action"`
	Event     string    `json:"event,omitempty"`
	CreatedAt time.Time `json:"createdAt"`
	// ActorUserID is the user's id, "other" for anyone else, or empty when none was recorded.
	ActorUserID string `json:"actorUserId,omitempty"`
	TargetType  string `json:"targetType,omitempty"`
	// TargetID is "other" for another user.
	TargetID       string `json:"targetId,omitempty"`
	OrganizationID *ULID  `json:"organizationId,omitempty"`
	// IPPrefix and UserAgent are set only on events the user performed with no other accountability actor.
	IPPrefix  string `json:"ipPrefix,omitempty"`
	UserAgent string `json:"userAgent,omitempty"`
}

DataExportAuditEvent is one audit event without its metadata.

type DataExportAuditLog ¶ added in v2.14.0

type DataExportAuditLog struct {
	// Events are those the user performed or that target the user, last recorded first.
	Events []DataExportAuditEvent `json:"events"`
	// Truncated is true when older events were left out by DataExportConfig.AuditLimit.
	Truncated bool `json:"truncated"`
}

DataExportAuditLog is the "auditLogs" section.

type DataExportConfig ¶ added in v2.14.0

type DataExportConfig struct {
	// RecentAuth is the maximum age of the session's authentication for the route (default 10
	// minutes).
	RecentAuth time.Duration
	// AuditLimit caps the audit events of one export, last recorded kept (default 500).
	AuditLimit int
	// RateLimitPerUser is how many exports one user may download per hour (default 3).
	RateLimitPerUser int
	// Extra adds application data under the "extra" section. An error fails the export. What it
	// returns is sent to the user as is, so leave out secrets and other users' data.
	Extra func(ctx context.Context, userID ULID) (map[string]any, error)
	// Sections limits the export to the named sections (DataExportSection constants). Empty means all.
	Sections []string
}

DataExportConfig turns on user data export: ExportUserData and GET {PathPrefix}/me/export. Nil (the default) mounts no route and changes nothing. See docs/data-export.md.

type DataExportDelegation ¶ added in v2.14.0

type DataExportDelegation struct {
	ID                 ULID       `json:"id"`
	AgentID            ULID       `json:"agentId"`
	OrganizationID     *ULID      `json:"organizationId,omitempty"`
	Scope              []string   `json:"scope"`
	Resource           string     `json:"resource"`
	MaxDurationSeconds int        `json:"maxDurationSeconds"`
	CreatedAt          time.Time  `json:"createdAt"`
	ExpiresAt          *time.Time `json:"expiresAt,omitempty"`
	RevokedAt          *time.Time `json:"revokedAt,omitempty"`
}

DataExportDelegation is one grant the user issued, an entry of the "delegations" section.

type DataExportEmailChange ¶ added in v2.14.0

type DataExportEmailChange struct {
	NewEmail    string    `json:"newEmail"`
	RequestedAt time.Time `json:"requestedAt"`
	ExpiresAt   time.Time `json:"expiresAt"`
}

DataExportEmailChange is one entry of the "pendingEmailChange" section.

type DataExportIdentities ¶ added in v2.14.0

type DataExportIdentities struct {
	OAuth any `json:"oauth"`
	SAML  any `json:"saml"`
}

DataExportIdentities is the "identities" section. Each field is a []DataExportIdentity or a DataExportUnavailable.

type DataExportIdentity ¶ added in v2.14.0

type DataExportIdentity struct {
	// Provider is the OAuth provider name, or "saml".
	Provider     string     `json:"provider"`
	Subject      string     `json:"subject"`
	ConnectionID *ULID      `json:"connectionId,omitempty"`
	LinkedAt     time.Time  `json:"linkedAt"`
	LastLoginAt  *time.Time `json:"lastLoginAt,omitempty"`
}

DataExportIdentity is one linked sign-in identity.

type DataExportKnownDevice ¶ added in v2.14.0

type DataExportKnownDevice struct {
	FirstSeenAt time.Time `json:"firstSeenAt"`
	LastSeenAt  time.Time `json:"lastSeenAt"`
}

DataExportKnownDevice is one entry of the "knownDevices" section.

type DataExportOrganization ¶ added in v2.14.0

type DataExportOrganization struct {
	ID   ULID   `json:"id"`
	Name string `json:"name"`
	Slug string `json:"slug"`
	Role string `json:"role"`
	// Roles are the RBAC roles held in the organization, absent without RBACStorage.
	Roles []string `json:"roles,omitempty"`
}

DataExportOrganization is one membership, an entry of the "organizations" section.

type DataExportPasskey ¶ added in v2.14.0

type DataExportPasskey struct {
	// CredentialID is unpadded base64url.
	CredentialID   string     `json:"credentialId"`
	Name           string     `json:"name"`
	AAGUID         string     `json:"aaguid,omitempty"`
	BackupEligible *bool      `json:"backupEligible,omitempty"`
	BackupState    *bool      `json:"backupState,omitempty"`
	CreatedAt      time.Time  `json:"createdAt"`
	LastUsedAt     *time.Time `json:"lastUsedAt,omitempty"`
}

DataExportPasskey is one entry of the "passkeys" section.

type DataExportProfile ¶ added in v2.14.0

type DataExportProfile struct {
	ID              ULID       `json:"id"`
	Email           string     `json:"email"`
	EmailVerifiedAt *time.Time `json:"emailVerifiedAt,omitempty"`
	Name            string     `json:"name"`
	AvatarURL       string     `json:"avatarUrl,omitempty"`
	CreatedAt       time.Time  `json:"createdAt"`
	UpdatedAt       time.Time  `json:"updatedAt"`
	// The SCIM directory fields.
	ExternalID  string `json:"externalId,omitempty"`
	GivenName   string `json:"givenName,omitempty"`
	FamilyName  string `json:"familyName,omitempty"`
	DisplayName string `json:"displayName,omitempty"`
}

DataExportProfile is the "profile" section.

type DataExportRememberedDevice ¶ added in v2.14.0

type DataExportRememberedDevice struct {
	ID          ULID       `json:"id"`
	Label       string     `json:"label,omitempty"`
	DeviceLabel string     `json:"deviceLabel"`
	UserAgent   string     `json:"userAgent,omitempty"`
	IPPrefix    string     `json:"ipPrefix,omitempty"`
	Method      string     `json:"method,omitempty"`
	AuthMethods []string   `json:"authMethods,omitempty"`
	CreatedAt   time.Time  `json:"createdAt"`
	LastUsedAt  time.Time  `json:"lastUsedAt"`
	ExpiresAt   time.Time  `json:"expiresAt"`
	ForgottenAt *time.Time `json:"forgottenAt,omitempty"`
}

DataExportRememberedDevice is one entry of the "rememberedDevices" section.

type DataExportRole ¶ added in v2.14.0

type DataExportRole struct {
	ID   ULID   `json:"id"`
	Name string `json:"name"`
}

DataExportRole is one role held outside any organization, an entry of the "roles" section.

type DataExportSession ¶ added in v2.14.0

type DataExportSession struct {
	ID                   ULID       `json:"id"`
	DeviceLabel          string     `json:"deviceLabel"`
	UserAgent            string     `json:"userAgent,omitempty"`
	IPPrefix             string     `json:"ipPrefix,omitempty"`
	AuthLevel            string     `json:"authLevel,omitempty"`
	AuthMethods          []string   `json:"authMethods,omitempty"`
	AuthTime             *time.Time `json:"authTime,omitempty"`
	CreatedAt            time.Time  `json:"createdAt"`
	LastSeenAt           *time.Time `json:"lastSeenAt,omitempty"`
	ExpiresAt            time.Time  `json:"expiresAt"`
	ActiveOrganizationID *ULID      `json:"activeOrganizationId,omitempty"`
}

DataExportSession is one entry of the "sessions" section.

type DataExportSigninReport ¶ added in v2.14.0

type DataExportSigninReport struct {
	ID        ULID       `json:"id"`
	UserAgent string     `json:"userAgent,omitempty"`
	IPPrefix  string     `json:"ipPrefix,omitempty"`
	SigninAt  time.Time  `json:"signinAt"`
	ExpiresAt time.Time  `json:"expiresAt"`
	UsedAt    *time.Time `json:"usedAt,omitempty"`
}

DataExportSigninReport is one "this was not me" link, an entry of the "signinReports" section.

type DataExportTOTP ¶ added in v2.14.0

type DataExportTOTP struct {
	Enabled   bool       `json:"enabled"`
	EnabledAt *time.Time `json:"enabledAt,omitempty"`
}

DataExportTOTP is the "totp" section.

type DataExportUnavailable ¶ added in v2.14.0

type DataExportUnavailable struct {
	Unavailable bool `json:"unavailable"`
}

DataExportUnavailable stands in for a section the storage cannot list.

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 DeviceAppAssertionError ¶ added in v2.14.0

type DeviceAppAssertionError = internalas.DeviceAppAssertionError

DeviceAppAssertionError is the refusal of an App Attest assertion (see its Code).

type DeviceAppAssertionRequest ¶ added in v2.14.0

type DeviceAppAssertionRequest = internalas.DeviceAppAssertionRequest

DeviceAppAssertionRequest is one Apple App Attest assertion from a device.

type DeviceAppAttestStorage ¶ added in v2.14.0

type DeviceAppAttestStorage interface {
	AdvanceAppAttestCounter(ctx context.Context, id ULID, counter uint32) (bool, error)
}

DeviceAppAttestStorage is the optional counter store for Apple App Attest assertions. The built in stores implement it. AdvanceAppAttestCounter raises the device counter to counter only while it is lower, in one statement, and reports whether it did.

type DeviceAttestationConfig ¶ added in v2.14.0

type DeviceAttestationConfig = internalas.DeviceAttestationConfig

DeviceAttestationConfig is the root alias for the enrollment attestation hook.

type DeviceAttestationError ¶ added in v2.14.0

type DeviceAttestationError = internalas.DeviceAttestationError

DeviceAttestationError is the enrollment refusal for evidence the verifier rejected. It matches ErrDeviceAttestationFailed with errors.Is.

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 DeviceCertTokenRequest ¶ added in v2.14.0

type DeviceCertTokenRequest = internalas.DeviceCertTokenRequest

DeviceCertTokenRequest asks for an RFC 8705 certificate bound token for a device.

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
	// SuspendDevice moves an active device to suspended and reports whether it changed. A revoked
	// or already suspended device is left alone (false). ResumeDevice is the reverse and never
	// revives a revoked device. Both are conditional updates, so concurrent callers cannot both win.
	SuspendDevice(ctx context.Context, id ULID) (bool, error)
	ResumeDevice(ctx context.Context, id ULID) (bool, error)
	// DeviceBySPIFFEID and DeviceByKeyThumbprint are indexed lookups, ErrStorageNotFound on a miss.
	// The thumbprint is the RFC 7638 value in Device.KeyThumbprint. Two devices can share a key,
	// so the newest one is returned.
	DeviceBySPIFFEID(ctx context.Context, spiffeID string) (*Device, error)
	DeviceByKeyThumbprint(ctx context.Context, thumbprint string) (*Device, 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 device enrollment token, single use unless MaxUses is above one.

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 EmailChangeConfig ¶ added in v2.14.0

type EmailChangeConfig struct {
	// TokenTTL is how long the confirm link sent to the new address works (default 1 hour).
	TokenTTL time.Duration
	// UndoTTL is how long the undo link sent to the previous address works (default 72 hours).
	// Until then the previous address cannot be used to create another account, and whoever reads
	// that mailbox can take the account back (see AllowUndoCancel).
	UndoTTL time.Duration
	// RecentAuth is the maximum age of the session's authentication for a request (default 10
	// minutes).
	RecentAuth time.Duration
	// DisableOldAddressNotice stops all mail to the previous address. It also removes undo, since
	// the undo link is only ever sent there. An unverified previous address never gets either.
	DisableOldAddressNotice bool
	// Allow vetoes a change by returning an error. It runs at request and at confirm time, after
	// the managed identity check.
	Allow func(ctx context.Context, u *User) error
	// AllowManagedUsers lets users whose address belongs to a SAML or SCIM directory change it.
	// By default they are refused.
	AllowManagedUsers bool
	// RequestRateLimitPerUser is how many requests one user may make per RequestRateWindow
	// (default 5).
	RequestRateLimitPerUser int
	// RequestRateWindow is the window of RequestRateLimitPerUser (default 1 hour).
	RequestRateWindow time.Duration
	// ConfirmRateLimitPerIP is the per-IP per-minute budget of the confirm and undo routes
	// (default 10).
	ConfirmRateLimitPerIP int
	// SendTimeout bounds one background delivery (default 10s).
	SendTimeout time.Duration
	// AllowUndoCancel lets a recently authenticated session withdraw undo links, through
	// CancelEmailChangeUndo and its route. Off by default, because someone who moved the account to
	// their own mailbox can authenticate again and remove the owner's way back.
	AllowUndoCancel bool
}

EmailChangeConfig turns on self serve email change: a signed in user asks for a new address, confirms it from that mailbox, and the previous address gets an undo link. Nil (the default) mounts no routes and changes nothing. Storage must implement EmailChangeStorage, and Config.EmailSender delivers the links. See docs/email-change.md.

type EmailChangeListStorage ¶ added in v2.14.0

type EmailChangeListStorage interface {
	// ListPendingEmailChanges returns the user's unused confirm records that expire after at, newest
	// first. TokenHash may be left empty.
	ListPendingEmailChanges(ctx context.Context, userID ULID, at time.Time) ([]EmailChangeRecord, error)
}

EmailChangeListStorage lists the pending email changes of a user.

type EmailChangeRecord ¶ added in v2.14.0

type EmailChangeRecord = models.EmailChange

EmailChangeRecord is the stored state behind one confirm or undo link. Storage adapters read and write it.

type EmailChangeResult ¶ added in v2.14.0

type EmailChangeResult struct {
	UserID    ULID
	OldEmail  string
	NewEmail  string
	ChangedAt time.Time
	// UndoExpiresAt is zero when no undo link was issued.
	UndoExpiresAt time.Time
}

EmailChangeResult describes a confirmed change.

type EmailChangeStorage ¶ added in v2.14.0

type EmailChangeStorage interface {
	// CreateEmailChange stores a pending confirm record and removes the user's other confirm records.
	CreateEmailChange(ctx context.Context, r EmailChangeRecord) error
	// DeletePendingEmailChanges removes the user's confirm records and returns how many there were.
	// Account recovery calls it.
	DeletePendingEmailChanges(ctx context.Context, userID ULID) (int64, error)
	// CancelEmailChangeUndos removes, atomically, the user's unused undo records that expire after at
	// and whose NewEmail is newEmail (compared case insensitively), and returns the removed records.
	CancelEmailChangeUndos(ctx context.Context, userID ULID, newEmail string, at time.Time) ([]EmailChangeRecord, error)
	// EmailChangeByTokenHash returns the record in any state, or ErrStorageNotFound.
	EmailChangeByTokenHash(ctx context.Context, tokenHash []byte) (*EmailChangeRecord, error)
	// ApplyEmailChange spends an unused confirm record that expires after at, moves the user from
	// OldEmail to NewEmail marked verified at at, stores undo when non nil, and deletes the user's
	// password reset tokens and the magic links of both addresses. It returns ErrStorageNotFound when
	// the record cannot be spent or the user no longer has OldEmail, and ErrEmailChangeAddressTaken
	// when another account holds NewEmail. A failure changes nothing.
	ApplyEmailChange(ctx context.Context, tokenHash []byte, at time.Time, undo *EmailChangeRecord) (*EmailChangeRecord, error)
	// RevertEmailChange spends an unused undo record that expires after at, restores OldEmail with the
	// record's OldEmailVerifiedAt (never marking it verified on its own), deletes the user's confirm records, the undo records created at or after this
	// one, the user's password reset tokens and the magic links of the involved addresses. It returns
	// the record and the address the user had just before. Errors are as for ApplyEmailChange.
	RevertEmailChange(ctx context.Context, tokenHash []byte, at time.Time) (r *EmailChangeRecord, previousEmail string, err error)
	// EmailReservedForUndo reports whether an unused undo record that expires after at holds email
	// (compared case insensitively) for a user other than except.
	EmailReservedForUndo(ctx context.Context, email string, except ULID, at time.Time) (bool, error)
	// EmailChangeIdentityManaged reports whether an external directory owns the user's address: the
	// user has a SAML identity or a SCIM external id, or belongs to an organization with a live SCIM
	// token.
	EmailChangeIdentityManaged(ctx context.Context, userID ULID) (bool, error)
	// DeleteExpiredEmailChanges removes records that expired at or before the given time.
	DeleteExpiredEmailChanges(ctx context.Context, before time.Time) (int64, error)
}

EmailChangeStorage is the optional capability behind Config.EmailChange. It is detected by type assertion and is not part of Storage. Only token hashes are stored. ApplyEmailChange and RevertEmailChange must each be one transaction; storagetest.RunEmailChange checks the contract.

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 KnownDeviceListStorage ¶ added in v2.14.0

type KnownDeviceListStorage interface {
	// ListKnownDevices returns the user's known devices, oldest first.
	ListKnownDevices(ctx context.Context, userID ULID) ([]KnownDeviceRecord, error)
	// ListSigninReports returns the user's stored report links in any state, oldest first. TokenHash
	// and DeviceHash may be left empty.
	ListSigninReports(ctx context.Context, userID ULID) ([]SigninReportRecord, error)
}

KnownDeviceListStorage lists what sign-in notices keep about a user.

type KnownDeviceRecord ¶ added in v2.14.0

type KnownDeviceRecord = models.KnownDevice

KnownDeviceRecord is one recognized device of a user, without its hash.

type KnownDeviceStorage ¶ added in v2.14.0

type KnownDeviceStorage interface {
	// TouchKnownDevice reports whether the device is known for the user and, if so, moves its last
	// seen time to at.
	TouchKnownDevice(ctx context.Context, userID ULID, deviceHash []byte, at time.Time) (bool, error)
	// RecordKnownDevice stores the device for the user; recording it again only moves its last seen time.
	RecordKnownDevice(ctx context.Context, userID ULID, deviceHash []byte, at time.Time) error
	// ForgetKnownDevice removes one device of the user. A missing device is not an error.
	ForgetKnownDevice(ctx context.Context, userID ULID, deviceHash []byte) error
	// DeleteStaleKnownDevices removes devices of every user last seen before the given time.
	DeleteStaleKnownDevices(ctx context.Context, lastSeenBefore time.Time) (int64, error)
	CreateSigninReport(ctx context.Context, r SigninReportRecord) error
	// SigninReportByTokenHash returns the report in any state, or ErrStorageNotFound.
	SigninReportByTokenHash(ctx context.Context, tokenHash []byte) (*SigninReportRecord, error)
	// ConsumeSigninReport sets UsedAt to at in one conditional write, only while the report is unused
	// and expires after at, and returns the row. Otherwise it returns ErrStorageNotFound.
	ConsumeSigninReport(ctx context.Context, tokenHash []byte, at time.Time) (*SigninReportRecord, error)
	// DeleteExpiredSigninReports removes reports that expired at or before the given time.
	DeleteExpiredSigninReports(ctx context.Context, before time.Time) (int64, error)
}

KnownDeviceStorage is the optional capability behind Config.SigninNotices. It is detected by type assertion and is not part of Storage. Only hashes of device ids and link tokens are stored; storagetest.RunKnownDevices checks the contract.

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
	// OnReportedNotMe runs after a user used a "this was not me" link and was signed out everywhere
	// (Config.SigninNotices). Use it to force a password change or alert staff. Observe-only.
	OnReportedNotMe func(ctx context.Context, user *User, report SigninReport) 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, OnOrgSwitch and OnReportedNotMe 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 MemberAttachRequest ¶ added in v2.14.0

type MemberAttachRequest struct {
	OrganizationID ULID
	ActorID        ULID
	UserID         ULID
	Role           string
}

MemberAttachRequest describes an HTTP request to attach an existing account to an organization.

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 OAuthGrantEvidence ¶ added in v2.14.0

type OAuthGrantEvidence = models.OAuthGrantEvidence

OAuthGrantRow, OAuthGrantRevocation, OAuthGrantEvidence and OAuthTokenRef are the records of ConnectedAppStorage.

type OAuthGrantRevocation ¶ added in v2.14.0

type OAuthGrantRevocation = models.OAuthGrantRevocation

OAuthGrantRow, OAuthGrantRevocation, OAuthGrantEvidence and OAuthTokenRef are the records of ConnectedAppStorage.

type OAuthGrantRow ¶ added in v2.14.0

type OAuthGrantRow = models.OAuthGrantRow

OAuthGrantRow, OAuthGrantRevocation, OAuthGrantEvidence and OAuthTokenRef are the records of ConnectedAppStorage.

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 OAuthTokenRef ¶ added in v2.14.0

type OAuthTokenRef = models.OAuthTokenRef

OAuthGrantRow, OAuthGrantRevocation, OAuthGrantEvidence and OAuthTokenRef are the records of ConnectedAppStorage.

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 {
	// AuthorizeMemberAttach approves an HTTP request that attaches an existing account to an
	// organization. Nil refuses, since membership lets the organization's SAML and SCIM manage the
	// account. Return true only with proof that the account holder agreed. Go calls are not gated.
	AuthorizeMemberAttach func(ctx context.Context, req MemberAttachRequest) (bool, error)
}

OrganizationsConfig turns multi-tenancy on when non-nil. The zero value is safe.

type PARConfig ¶

type PARConfig = internalas.PARConfig

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

type PasskeySignals ¶ added in v2.14.0

type PasskeySignals = models.PasskeySignals

PasskeySignals is what a page passes to PublicKeyCredential.signalAllAcceptedCredentials and signalCurrentUserDetails. Byte values are unpadded base64url. See docs/passkey-signals.md.

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 PersistentSessionStorage ¶ added in v2.14.0

type PersistentSessionStorage interface {
	// CreateSessionFamily stores a new family and its first token history row.
	CreateSessionFamily(ctx context.Context, f SessionFamilyRecord) error
	SessionFamilyByID(ctx context.Context, id ULID) (*SessionFamilyRecord, error)
	// SessionFamilyBySessionID returns the family whose current session is sessionID, or else the
	// family whose session before its last advance or rebind was sessionID.
	SessionFamilyBySessionID(ctx context.Context, sessionID ULID) (*SessionFamilyRecord, error)
	// SessionFamilyTokenGeneration returns the generation of a hash in the family's history.
	SessionFamilyTokenGeneration(ctx context.Context, familyID ULID, verifierHash []byte) (int64, error)
	// AddSessionFamilyToken inserts a history row; an identical existing row is not an error.
	AddSessionFamilyToken(ctx context.Context, t SessionFamilyToken) error
	// AdvanceSessionFamily applies the rotation only while the family is at in.FromGeneration, is
	// neither revoked nor forgotten, and (when in.Rerotate) RerotatedFrom differs from
	// in.ParentGeneration. It sets UsedAt to nil and reports whether it applied.
	AdvanceSessionFamily(ctx context.Context, in SessionFamilyAdvance) (bool, error)
	// MarkSessionFamilyUsed sets UsedAt and LastUsedAt to at on the unrevoked family whose current
	// session is sessionID, when UsedAt is nil.
	MarkSessionFamilyUsed(ctx context.Context, sessionID ULID, at time.Time) error
	// RebindSessionFamily moves an unrevoked family from session from to session to.
	RebindSessionFamily(ctx context.Context, familyID, from, to ULID) (bool, error)
	// RevokeSessionFamily sets RevokedAt and RevokeReason unless already revoked, and returns the row.
	RevokeSessionFamily(ctx context.Context, id ULID, reason string, at time.Time) (*SessionFamilyRecord, error)
	// RevokeUserSessionFamilies revokes the user's unrevoked families except the one whose current
	// session is keepSession (zero for none) and returns the rows it revoked.
	RevokeUserSessionFamilies(ctx context.Context, userID, keepSession ULID, reason string, at time.Time) ([]SessionFamilyRecord, error)
	// ForgetSessionFamily sets ForgottenAt on an unrevoked family.
	ForgetSessionFamily(ctx context.Context, id ULID, at time.Time) (bool, error)
	RenameSessionFamily(ctx context.Context, id ULID, label string) error
	// ListUserSessionFamilies returns the user's unrevoked families, forgotten ones included.
	ListUserSessionFamilies(ctx context.Context, userID ULID) ([]SessionFamilyRecord, error)
}

PersistentSessionStorage is the optional capability behind Config.PersistentSessions. It is detected by type assertion and is not part of Storage. Only hashes of remember tokens are stored. AdvanceSessionFamily must be one conditional write so that several instances agree on a single rotation; storagetest.RunPersistentSessions checks the contract.

Experimental: may change in a minor release. See docs/STABILITY-AND-SECURITY.md.

type PersistentSessionsConfig ¶ added in v2.14.0

type PersistentSessionsConfig struct {
	// Secret derives rotated tokens so parallel refreshes get identical cookies. At least 32 bytes,
	// shared by every instance. Required.
	Secret []byte
	// PreviousSecrets are still accepted for tokens rotated before a secret change.
	PreviousSecrets [][]byte
	// IdleTimeout ends a device unused for this long (default 30 days). It must exceed SessionTTL,
	// because only a refresh extends it.
	IdleTimeout time.Duration
	// AbsoluteLifetime ends a device this long after its original sign-in (default 90 days).
	AbsoluteLifetime time.Duration
	// Grace is how long the previous token still returns the same successor (default 30s, at most 5m).
	Grace time.Duration
	// CookieName is the remember cookie (default "theauth_remember").
	CookieName string
	// RefreshRateLimitPerIP is the per-IP per-minute budget of the refresh endpoint (default 60). It
	// is separate from RateLimitPerIP because every open tab may refresh when a session ends.
	RefreshRateLimitPerIP int
	// AllowSAML lets SAML sign-ins be remembered. Off by default: the identity provider owns the
	// lifetime of an SSO session.
	AllowSAML bool
	// Eligible can refuse remember for a session, for example demo, kiosk or SSO accounts.
	Eligible func(ctx context.Context, in RememberEligibility) bool
	// Limits can shorten IdleTimeout and AbsoluteLifetime per user or organization; longer values
	// are ignored. It runs at sign-in and on every refresh.
	Limits func(ctx context.Context, in RememberLimitsInput) RememberLimits
	// Check runs on every refresh after the built-in user checks. An error denies the refresh
	// without revoking anything.
	Check func(ctx context.Context, in RefreshCheckInput) (RefreshDecision, error)
	// OnReuse is called after a reused token revoked its family, for example to notify the user.
	OnReuse func(ctx context.Context, fam SessionFamily)
}

PersistentSessionsConfig turns on persistent sessions ("keep me signed in"): a sign-in that asks for it gets a long-lived remember cookie next to the normal session cookie. When the session dies, POST {PathPrefix}/session/refresh trades the remember cookie for a new session and a rotated remember cookie. Nil (the default) leaves every existing behaviour unchanged.

Experimental: may change in a minor release. See docs/STABILITY-AND-SECURITY.md.

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 PseudonymRotation ¶ added in v2.14.0

type PseudonymRotation = internalaudit.Rotation

PseudonymRotation is the rotation policy for audit pseudonyms. PeriodDays is the length of one period in days (at least 1). RetainPeriods is how many older periods keep their secret: 0 means the default of 1, a negative value keeps only the current period.

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 RefreshCheckInput ¶ added in v2.14.0

type RefreshCheckInput struct {
	User   User
	Family SessionFamily
}

RefreshCheckInput is what the refresh veto hook sees.

type RefreshDecision ¶ added in v2.14.0

type RefreshDecision int

RefreshDecision is the result of PersistentSessionsConfig.Check.

const (
	// RefreshAllow lets the refresh proceed.
	RefreshAllow RefreshDecision = iota
	// RefreshDeny refuses this refresh and keeps the device.
	RefreshDeny
	// RefreshRevoke refuses and ends the device and its session.
	RefreshRevoke
)

type RefreshInput ¶ added in v2.14.0

type RefreshInput struct {
	RememberToken string
	// SessionToken is the current session cookie, if any. A live session of the same device makes
	// the refresh a no-op.
	SessionToken string
	UserAgent    string
	IP           string
}

RefreshInput is a refresh request.

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 RefreshResult ¶ added in v2.14.0

type RefreshResult struct {
	Rotated           bool
	SessionToken      string
	Session           Session
	RememberToken     string
	RememberExpiresAt time.Time
	Family            SessionFamily
}

RefreshResult is a successful refresh. When Rotated is false the caller already holds a live session and keeps its cookies; the token fields are empty.

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 RememberEligibility ¶ added in v2.14.0

type RememberEligibility struct {
	UserID  ULID
	Session Session
	// Method is the sign-in method: password, mfa, passkey, magic_link, oauth, saml, signup or
	// programmatic.
	Method string
}

RememberEligibility describes a session about to be remembered.

type RememberLimits ¶ added in v2.14.0

type RememberLimits struct {
	IdleTimeout      time.Duration
	AbsoluteLifetime time.Duration
}

RememberLimits are per-user limits. Zero keeps the configured value.

type RememberLimitsInput ¶ added in v2.14.0

type RememberLimitsInput struct {
	UserID ULID
	Method string
}

RememberLimitsInput identifies whose limits PersistentSessionsConfig.Limits returns.

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 SAMLIdentityListStorage ¶ added in v2.14.0

type SAMLIdentityListStorage interface {
	// SAMLIdentitiesByUserID returns the user's SAML identities, oldest first.
	SAMLIdentitiesByUserID(ctx context.Context, userID ULID) ([]SAMLIdentity, error)
}

SAMLIdentityListStorage lists the SAML identities linked to a user.

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 SSODomain ¶ added in v2.14.0

type SSODomain = models.SSODomain

SSODomain is one email domain claimed by a SAML connection, with the TXT record that proves it.

type SSODomainResolver ¶ added in v2.14.0

type SSODomainResolver = ssodomain.Resolver

SSODomainResolver looks up TXT records. LookupTXT must honor the context deadline.

type SSODomainStorage ¶ added in v2.14.0

type SSODomainStorage interface {
	// CreateSSODomain stores a claim, or returns ErrSSODomainExists for the same connection and domain.
	CreateSSODomain(ctx context.Context, d SSODomain) error
	SSODomainByID(ctx context.Context, id ULID) (*SSODomain, error)
	// SSODomainsByConnection returns the connection's claims ordered by domain.
	SSODomainsByConnection(ctx context.Context, connectionID ULID) ([]SSODomain, error)
	// SSODomainsByName returns every claim on a domain, the verified one first, then oldest first.
	SSODomainsByName(ctx context.Context, domain string) ([]SSODomain, error)
	// MarkSSODomainVerified sets VerifiedAt (keeping an earlier value) and LastCheckedAt and clears
	// FailedChecks. It returns ErrSSODomainTaken when another row holds the verified claim.
	MarkSSODomainVerified(ctx context.Context, id ULID, at time.Time) (SSODomain, error)
	// SSODomainsDueForRecheck returns the verified rows last checked at or before checkedBefore.
	SSODomainsDueForRecheck(ctx context.Context, checkedBefore time.Time) ([]SSODomain, error)
	// ClaimSSODomainRecheck sets LastCheckedAt to at in one conditional write if the row is still due,
	// and reports whether it did.
	ClaimSSODomainRecheck(ctx context.Context, id ULID, checkedBefore, at time.Time) (bool, error)
	// RecordSSODomainFailure atomically adds one failed check to a verified row and clears VerifiedAt
	// when the count reaches grace; the bool reports that this call cleared it. An unverified row is
	// returned unchanged.
	RecordSSODomainFailure(ctx context.Context, id ULID, grace int) (SSODomain, bool, error)
	DeleteSSODomain(ctx context.Context, id ULID) error
}

SSODomainStorage is the optional capability behind Config.SSODomains. It is detected by type assertion and is not part of Storage. Rows go away with their connection. At most one row per domain may be verified, enforced by the database; storagetest.RunSSODomains checks the contract.

type SSODomainsConfig ¶ added in v2.14.0

type SSODomainsConfig struct {
	// TXTPrefix is put in front of the domain to form the record name (default "_theauth-challenge").
	TXTPrefix string
	// Resolver looks up TXT records (default the system resolver through net.Resolver).
	Resolver SSODomainResolver
	// LookupTimeout bounds one lookup (default 5s).
	LookupTimeout time.Duration
	// RecheckInterval is how old a verified domain's last check must be before RecheckSSODomains
	// looks it up again. Zero (the default) never rechecks. Nothing rechecks on its own.
	RecheckInterval time.Duration
	// GraceFailures is how many consecutive rechecks finding no matching record remove verification
	// (default 3). Failed lookups do not count.
	GraceFailures int
	// MaxDomainsPerConnection caps the claims, verified or not, one connection may hold (default 50).
	MaxDomainsPerConnection int
	// RequireVerified refuses any SAML sign-in whose email domain is not verified for that
	// connection. Off by default so existing connections keep working; verify their domains before
	// turning it on. Discovery routes by verified domains whatever this says.
	RequireVerified bool
	// DiscoveryRateLimitPerIP is the per-IP per-minute budget of POST /sso/discover (default 10).
	DiscoveryRateLimitPerIP int
}

SSODomainsConfig turns on domain ownership proof for SAML connections and home realm discovery. Nil (the default) mounts no routes and changes nothing. It needs Config.SAML, and storage must implement SSODomainStorage. See docs/sso-domains.md.

type SSORecheckResult ¶ added in v2.14.0

type SSORecheckResult = ssodomain.RecheckResult

SSORecheckResult counts one RecheckSSODomains pass.

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 SessionFamily ¶ added in v2.14.0

type SessionFamily struct {
	ID ULID `json:"id"`
	// SessionID is the session of the current generation; it may have expired.
	SessionID ULID `json:"sessionId"`
	// Live reports whether that session can still authenticate requests.
	Live bool `json:"live"`
	// Persistent is false once remember was turned off for the device.
	Persistent  bool   `json:"persistent"`
	Current     bool   `json:"current"`
	Method      string `json:"method"`
	Label       string `json:"label,omitempty"`
	DeviceLabel string `json:"deviceLabel"`
	UserAgent   string `json:"userAgent"`
	IP          string `json:"-"`
	IPPrefix    string `json:"ipPrefix,omitempty"`
	// SignedInAt is the original sign-in; refreshes never move it.
	SignedInAt       time.Time `json:"signedInAt"`
	LastUsedAt       time.Time `json:"lastUsedAt"`
	IdleDeadline     time.Time `json:"idleDeadline"`
	AbsoluteDeadline time.Time `json:"absoluteDeadline"`
}

SessionFamily is one remembered device sign-in.

type SessionFamilyAdvance ¶ added in v2.14.0

type SessionFamilyAdvance = models.SessionFamilyAdvance

SessionFamilyAdvance is a conditional rotation of a session family.

type SessionFamilyRecord ¶ added in v2.14.0

type SessionFamilyRecord = models.SessionFamily

SessionFamilyRecord is the stored state of one remembered device sign-in. Storage adapters read and write it; applications use SessionFamily.

type SessionFamilyToken ¶ added in v2.14.0

type SessionFamilyToken = models.SessionFamilyToken

SessionFamilyToken is one row of a family's remember token hash history.

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 SigninNotice ¶ added in v2.14.0

type SigninNotice struct {
	ID     ULID             `json:"id"`
	UserID ULID             `json:"userId"`
	Kind   SigninNoticeKind `json:"kind"`
	At     time.Time        `json:"at"`
	// UserAgent is the caller supplied header; treat it as untrusted text.
	UserAgent string `json:"userAgent,omitempty"`
	// IPPrefix is the client address masked to /24 (IPv4) or /48 (IPv6).
	IPPrefix string `json:"ipPrefix,omitempty"`
	Location string `json:"location,omitempty"`
	// ReportURL is the "this was not me" link, set on new device sign-ins only. It is a bearer
	// credential that signs the user out everywhere: deliver it to the user and do not log it.
	ReportURL string            `json:"reportUrl,omitempty"`
	Details   map[string]string `json:"details,omitempty"`
}

SigninNotice is one notice to deliver to a user.

type SigninNoticeKind ¶ added in v2.14.0

type SigninNoticeKind string

SigninNoticeKind names what a notice is about. Hosts may pass their own kinds to NotifySecurityEvent.

const (
	NoticeNewDeviceSignin SigninNoticeKind = "new_device_signin"
	NoticePasswordChanged SigninNoticeKind = "password_changed"
	NoticeMFAEnabled      SigninNoticeKind = "mfa_enabled"
	NoticeMFADisabled     SigninNoticeKind = "mfa_disabled"
	NoticePasskeyAdded    SigninNoticeKind = "passkey_added"
	NoticePasskeyRemoved  SigninNoticeKind = "passkey_removed"
	NoticeEmailChanged    SigninNoticeKind = "email_changed"
)

The notice kinds. The strings are stable.

type SigninNoticesConfig ¶ added in v2.14.0

type SigninNoticesConfig struct {
	// Notify delivers a notice. When nil a plain text mail goes to the user through
	// Config.EmailSender. It must honor ctx; delivery is given up after SendTimeout.
	Notify func(ctx context.Context, n SigninNotice) error
	// Events limits which kinds are sent. Empty sends every kind.
	Events []SigninNoticeKind
	// ReportLinkTTL is how long a "this was not me" link works (default 7 days).
	ReportLinkTTL time.Duration
	// Secret signs report links, at least 32 bytes and shared by every instance. When empty a key
	// is derived from Config.EncryptionKey; one of the two is required.
	Secret []byte
	// DeviceCookieName is the cookie that recognizes a browser (default "theauth_device_id").
	DeviceCookieName string
	// DeviceCookieTTL is how long an unused device stays recognized (default 400 days).
	DeviceCookieTTL time.Duration
	// DeviceIDsPerCookie is how many accounts one browser stays recognized for (default 5, at most 10).
	DeviceIDsPerCookie int
	// Location optionally describes a client address for the notice. It runs off the request path
	// and receives the full address; only its answer and the address prefix go into the notice.
	Location func(ctx context.Context, ip string) string
	// NotifyWithoutDevice treats a sign-in made through the Go API, with no request and so no
	// device cookie, as coming from a new device. Default false.
	NotifyWithoutDevice bool
	// SendTimeout bounds one delivery, and the device lookup on the sign-in path (default 10s).
	SendTimeout time.Duration
	// CloseTimeout bounds how long Close waits for sends still running, for example through a Notify
	// that ignores ctx (default 30s).
	CloseTimeout time.Duration
	// ReportRateLimitPerIP is the per-IP per-minute budget of the report endpoint (default 10).
	ReportRateLimitPerIP int
	// ReportRevokesAPITokens makes a report also revoke the user's API tokens, so a token minted
	// through the reported sign-in stops working. Needs Config.APITokens. Default false.
	ReportRevokesAPITokens bool
	// ReportRevokesConnectedApps makes a report also run RevokeAllConnectedApps for the user. Needs
	// Config.ConnectedApps. Default false.
	ReportRevokesConnectedApps bool
}

SigninNoticesConfig turns on sign-in and security notices. A completed sign-in from a device the user has not used before sends a notice with a "this was not me" link, and security changes (password, second factor, passkeys) send a notice. Nil (the default) changes nothing. Storage must implement KnownDeviceStorage. See docs/signin-notices.md.

type SigninReport ¶ added in v2.14.0

type SigninReport struct {
	NoticeID   ULID
	UserID     ULID
	SignedInAt time.Time
	ReportedAt time.Time
	UserAgent  string
	IPPrefix   string
	// APITokensRevoked counts the API tokens this report revoked (ReportRevokesAPITokens).
	APITokensRevoked int
	// ConnectedAppsRevoked lists the client ids this report revoked (ReportRevokesConnectedApps).
	ConnectedAppsRevoked []string
}

SigninReport describes a sign-in the user reported as not theirs.

type SigninReportRecord ¶ added in v2.14.0

type SigninReportRecord = models.SigninReport

SigninReportRecord is the stored state behind one "this was not me" link. Storage adapters read and write it; applications see SigninReport.

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) AddSSODomain ¶ added in v2.14.0

func (a *TheAuth) AddSSODomain(ctx context.Context, connectionID ULID, domain string) (SSODomain, error)

AddSSODomain claims an email domain for a SAML connection and returns the TXT record to publish (RecordName and RecordValue). Adding it again returns the same token. A new claim beyond MaxDomainsPerConnection returns ErrSSODomainLimit. The caller authorizes.

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) AuditInputHash ¶ added in v2.14.0

func (a *TheAuth) AuditInputHash(content string) string

AuditInputHash returns the hash the audit log records for input content, using Config.Audit.InputHashKey when set. Use it to build an AuditQuery.Provenance filter for a message or document you still hold:

q := theauth.AuditQuery{Provenance: &theauth.AuditProvenanceFilter{
	Kind: audit.InputRetrievedDocument, Hash: a.AuditInputHash(doc)}}

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) BeginConditionalPasskeyRegistration ¶ added in v2.14.0

func (a *TheAuth) BeginConditionalPasskeyRegistration(ctx context.Context, sess *Session) (*protocol.CredentialCreation, string, error)

BeginConditionalPasskeyRegistration starts a conditional create (automatic passkey upgrade) for a session the caller has already validated. It needs WebAuthnConfig.AllowConditionalCreate and a password sign-in in that session within ConditionalCreateWindow.

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) CancelEmailChangeUndo ¶ added in v2.14.0

func (a *TheAuth) CancelEmailChangeUndo(ctx context.Context, sess Session) (int, error)

CancelEmailChangeUndo withdraws the outstanding undo links of the changes that led to the session user's current address, and the reservation of the addresses they would restore. The session must have authenticated within EmailChangeConfig.RecentAuth. It returns how many links it cancelled, and mails each address that held one. It needs EmailChangeConfig.AllowUndoCancel.

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) ConfirmEmailChange ¶ added in v2.14.0

func (a *TheAuth) ConfirmEmailChange(ctx context.Context, token string) (EmailChangeResult, error)

ConfirmEmailChange spends a confirm link: the user's address becomes the new one, marked verified, and every session, remembered device, trusted device, pending magic link and password reset token of the user ends. No session is issued, since the confirming browser may belong to another device. A previous address that was verified gets an undo link. The link is refused once the session that requested the change is revoked, expired or idle. A link that cannot be applied, including because the address was taken meanwhile, fails with CodeEmailChangeInvalid. If an error comes with a non zero result, the address did change but the final revocation pass failed.

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 an enrollment token: a single use join token, a claim code or a bulk token (see CreateDeviceJoinTokenInput.Kind). 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. With Config.EmailChange, an address held for a pending undo is an ErrUserEmailConflict.

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) ExportUserData ¶ added in v2.14.0

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

ExportUserData builds a UserDataExport and audits AuditDataExported when it succeeds. It does no authorization and no rate limiting: callers must make sure the result only reaches that user or someone entitled to it. A section whose storage capability is missing is DataExportUnavailable; any storage or Extra error fails the whole export. An unknown user is ErrStorageNotFound.

func (*TheAuth) FinishConditionalPasskeyRegistration ¶ added in v2.14.0

func (a *TheAuth) FinishConditionalPasskeyRegistration(ctx context.Context, sess *Session, challengeToken, name string, body io.Reader) (WebAuthnCredential, error)

FinishConditionalPasskeyRegistration completes a ceremony begun with BeginConditionalPasskeyRegistration, from the same session. FinishPasskeyRegistration does too when ctx carries the session, as it does behind RequireAuth.

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) ForgetSessionFamily ¶ added in v2.14.0

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

ForgetSessionFamily turns remember off for one device: its current session keeps working until it ends, then the device must sign in again.

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) IssueDeviceCertToken ¶ added in v2.14.0

func (a *TheAuth) IssueDeviceCertToken(ctx context.Context, req DeviceCertTokenRequest) (TokenResponse, error)

IssueDeviceCertToken mints a short lived access token for a device that the caller already authenticated with an X.509-SVID (iot/spiffe Bridge.IssueToken is the usual caller). The token carries cnf x5t#S256, so mcpresource accepts it only on a connection that presents that certificate. It needs Config.AuthorizationServer.DeviceTokens and issues no refresh token.

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) ListConnectedApps ¶ added in v2.14.0

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

ListConnectedApps returns the OAuth clients holding a live refresh token for the user, most recently used first. It never fails because a client's metadata cannot be resolved.

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) ListSSODomains ¶ added in v2.14.0

func (a *TheAuth) ListSSODomains(ctx context.Context, connectionID ULID) ([]SSODomain, error)

ListSSODomains returns the connection's domains.

func (*TheAuth) ListSessionFamilies ¶ added in v2.14.0

func (a *TheAuth) ListSessionFamilies(ctx context.Context, userID, currentSessionID ULID) ([]SessionFamily, error)

ListSessionFamilies returns the user's remembered devices, newest first, including dormant ones whose session has ended. currentSessionID marks the caller's own device.

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) NotifySecurityEvent ¶ added in v2.14.0

func (a *TheAuth) NotifySecurityEvent(ctx context.Context, userID ULID, kind SigninNoticeKind, details map[string]string) error

NotifySecurityEvent sends a security notice to a user through the SigninNotices channel, for changes the host makes itself such as NoticeEmailChanged. Request facts come from the context audit metadata and are included only when the signed in user in ctx or AuditMetadata.ActorUserID is that user, neither names anyone else and details["by"] is not "admin". The default mail goes to the address stored when this is called. Delivery runs in the background and its failures are audited, not returned. It does nothing when notices are off or the kind is filtered out, and returns ErrStorageNotFound for an unknown user.

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) PasskeySignals ¶ added in v2.14.0

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

PasskeySignals returns the signal data of a user. Send it only to that user, signed in. It fails rather than return a partial list, which would make a provider hide valid passkeys.

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) RecheckSSODomains ¶ added in v2.14.0

func (a *TheAuth) RecheckSSODomains(ctx context.Context) (SSORecheckResult, error)

RecheckSSODomains looks up the verified domains due under RecheckInterval. A domain whose record is definitely missing or wrong GraceFailures checks in a row loses verification; failed lookups do not count. Call it on a schedule.

func (*TheAuth) RecordAuthZENMount ¶ added in v2.14.0

func (a *TheAuth) RecordAuthZENMount(rateLimited bool)

RecordAuthZENMount is called by authzen.Mount so Doctor can report a decision point mounted on this instance without a rate limit. Hosts do not need to call it.

func (*TheAuth) RecordAuthZENNoAuthorize ¶ added in v2.14.0

func (a *TheAuth) RecordAuthZENNoAuthorize()

RecordAuthZENNoAuthorize is called by authzen.Mount when it mounts without Config.Authorize, so Doctor can report it. Hosts do not need to call it.

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) RefreshFromRequest ¶ added in v2.14.0

func (a *TheAuth) RefreshFromRequest(w http.ResponseWriter, r *http.Request) (*Session, *User, error)

RefreshFromRequest is the server-side refresh for a page gate: it returns the request's live session, or refreshes it from the remember cookie and writes the new cookies to w. Unsafe methods must pass the strict origin check. It never runs from API middleware on its own.

func (*TheAuth) RefreshSession ¶ added in v2.14.0

func (a *TheAuth) RefreshSession(ctx context.Context, in RefreshInput) (RefreshResult, error)

RefreshSession trades a remember token for a session. It rechecks the user and the Check hook, rotates the token and detects reuse. Prefer the POST {PathPrefix}/session/refresh route or RefreshFromRequest, which also set the cookies.

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) RemoveSSODomain ¶ added in v2.14.0

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

RemoveSSODomain deletes a domain claim.

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) RenameSessionFamily ¶ added in v2.14.0

func (a *TheAuth) RenameSessionFamily(ctx context.Context, userID, familyID ULID, label string) error

RenameSessionFamily sets the label of one of the user's devices. Another user's id returns ErrStorageNotFound.

func (*TheAuth) RequestEmailChange ¶ added in v2.14.0

func (a *TheAuth) RequestEmailChange(ctx context.Context, sess Session, newEmail string) error

RequestEmailChange starts a change of the session user's address. The session must have authenticated within EmailChangeConfig.RecentAuth. A confirm link goes to newEmail and, unless disabled, a notice without a link to the current address. A new request replaces the pending one. The answer is the same whether or not another account holds newEmail; in that case nothing is sent to it. Mail is delivered in the background.

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) ResumeDevice ¶ added in v2.14.0

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

ResumeDevice lifts a suspension. A revoked device stays revoked and returns ErrDeviceRevoked.

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) RevokeAllConnectedApps ¶ added in v2.14.0

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

RevokeAllConnectedApps ends everything the user granted to any OAuth client, for account recovery. A user wide watermark refuses all evidence issued so far, access tokens and assertions with no stored row included, and every client with stored evidence is revoked like RevokeConnectedApp does. It returns the ids revoked, also beside an error; call it again then.

func (*TheAuth) RevokeConnectedApp ¶ added in v2.14.0

func (a *TheAuth) RevokeConnectedApp(ctx context.Context, userID ULID, clientID string) (ConnectedAppRevokeResult, error)

RevokeConnectedApp ends the user's grant to clientID: pending codes, refresh tokens and, when AuthorizationServer.AccessTokenRevocation is on, live access tokens. Older codes, device and CIBA approvals and subject tokens are refused from then on. It returns ErrConnectedAppNotFound, after refusing earlier evidence all the same, when storage held nothing for the client. Any other error means a step failed; call it again. The client, delegations, agents, vault consents and sessions are left in place.

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) RevokeOtherSessionFamilies ¶ added in v2.14.0

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

RevokeOtherSessionFamilies ends every device of the user except the one holding keepSessionID.

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) RevokeSessionFamily ¶ added in v2.14.0

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

RevokeSessionFamily ends one of the user's devices and its session. Another user's id returns ErrStorageNotFound.

func (*TheAuth) RevokeSessionFamilyBySession ¶ added in v2.14.0

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

RevokeSessionFamilyBySession ends the device whose current session is sessionID, if any.

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) SSOConnectionForEmail ¶ added in v2.14.0

func (a *TheAuth) SSOConnectionForEmail(ctx context.Context, email string) (SAMLConnection, bool, error)

SSOConnectionForEmail is home realm discovery: it returns the SAML connection for the address's domain. Only the verified holder routes; unverified claims never do. Subdomains do not match.

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) SetPersistentSessionLimits ¶ added in v2.14.0

func (a *TheAuth) SetPersistentSessionLimits(idle, absolute time.Duration) error

SetPersistentSessionLimits changes the default idle timeout and absolute lifetime at runtime. Existing devices keep shorter limits they already have.

func (*TheAuth) SetRememberCookie ¶ added in v2.14.0

func (a *TheAuth) SetRememberCookie(w http.ResponseWriter, token string, expires time.Time)

SetRememberCookie writes the remember cookie for a token from RememberFromContext or RefreshSession. It is a no-op when persistent sessions are off.

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) ShredAuditPseudonyms ¶ added in v2.14.0

func (a *TheAuth) ShredAuditPseudonyms(ctx context.Context) ([]int64, error)

ShredAuditPseudonyms deletes the audit pseudonym period secrets that fell out of the retention window and returns the periods removed. Rotation does this by itself on the first write of each new period; call it to do so on demand. It needs Config.Audit.PseudonymRotation, otherwise it returns an error.

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) SuspendDevice ¶ added in v2.14.0

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

SuspendDevice puts an active device on hold: it gets no tokens until ResumeDevice. A revoked device returns ErrDeviceRevoked. Suspending twice succeeds.

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) UndoEmailChange ¶ added in v2.14.0

func (a *TheAuth) UndoEmailChange(ctx context.Context, token string) error

UndoEmailChange spends an undo link: the previous address comes back, even after further changes, later undo links and the pending change are cancelled, every session and device ends again, and credentials added since the change was requested are removed (see docs/email-change.md). With Config.AccountState the account must also reset its password before the next sign-in. It fails with CodeEmailChangeInvalid when another account now holds the address.

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) VerifyDeviceAppAssertion ¶ added in v2.14.0

func (a *TheAuth) VerifyDeviceAppAssertion(ctx context.Context, deviceID ULID, req DeviceAppAssertionRequest) (Device, error)

VerifyDeviceAppAssertion checks an Apple App Attest assertion from an enrolled device against the key attested at enrollment (the attestedPublicKey claim) and advances the device's replay counter with one conditional update, so the same assertion works once. It needs a store that implements DeviceAppAttestStorage (the built in stores do). Put a server challenge into ClientData and check it yourself, the counter is the only replay protection kept here.

func (*TheAuth) VerifySSODomain ¶ added in v2.14.0

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

VerifySSODomain looks up the TXT record and marks the domain verified on an exact value match. It returns ErrSSODomainUnproven, ErrSSODomainLookupFailed or ErrSSODomainTaken otherwise. When another connection holds the domain, the holder's record is looked up again and a holder that no longer publishes it is released.

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
	// ArgumentsHash binds the request to the arguments the approver saw: a hex SHA-256 of the
	// canonical JSON of action, resource and arguments (toolguard.HashApprovalAction). It is never
	// edited after the request is opened. Empty means the request is not argument bound (a row
	// opened before the column existed), which any presented arguments satisfy.
	ArgumentsHash string
	// RequiredApprovals is how many distinct approvers the request needs before ApprovedAt is
	// set. 0 and 1 both mean one approver, the ordinary flow. Above 1 only VoteToolApproval can
	// approve the request: ApproveToolApproval refuses it, so the quorum cannot be skipped.
	RequiredApprovals int
	// Approvers lists the approvers counted so far, oldest first. Only the stores fill it, and
	// only for a request with RequiredApprovals above 1.
	Approvers  []string
	CreatedAt  time.Time
	ExpiresAt  time.Time
	ApprovedAt time.Time
	ConsumedAt time.Time
	DeniedAt   time.Time
	// ExpiredAt is set once by ExpireToolApproval, the first time an overdue undecided request
	// is noticed. Expiry is also derived from ExpiresAt, so a request past ExpiresAt is expired
	// whether or not this is set.
	ExpiredAt 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). Every built in store implements it. 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 ToolApprovalExpiryStorage ¶ added in v2.14.0

type ToolApprovalExpiryStorage interface {
	// ExpireToolApproval flips id to expired when it is undecided, unspent, not yet marked and past
	// its ExpiresAt. Exactly one concurrent caller sees true.
	ExpireToolApproval(ctx context.Context, id string, now time.Time) (bool, error)
	// ListOverdueToolApprovals returns undecided, unmarked requests past ExpiresAt, oldest first,
	// at most limit (0 means 100).
	ListOverdueToolApprovals(ctx context.Context, now time.Time, limit int) ([]ToolApproval, error)
}

ToolApprovalExpiryStorage is the optional capability that marks overdue requests expired, so the expiry is recorded once (one audit row, one event). Every built in store implements it.

type ToolApprovalQuorumStorage ¶ added in v2.14.0

type ToolApprovalQuorumStorage interface {
	VoteToolApproval(ctx context.Context, id, approver string, now time.Time) (ToolApprovalVote, error)
}

ToolApprovalQuorumStorage is the optional capability behind quorum (two person) approvals. Every built in store implements it. VoteToolApproval counts approver's approval toward a request with RequiredApprovals above 1 and approves it when the last one lands. It must be atomic: each approver counts once even under concurrent calls (a primary key on (approval_id, approver)), a vote is accepted only while the request is undecided, unspent and unexpired (so expiry covers the whole quorum), the requester (OpenedBy, when set) never counts, and exactly one concurrent caller completes the quorum.

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 ToolApprovalVote ¶ added in v2.14.0

type ToolApprovalVote struct {
	Outcome   ToolApprovalVoteOutcome
	Approvers []string
}

ToolApprovalVote is the result of VoteToolApproval. Approvers lists every approver counted after the call, oldest first.

type ToolApprovalVoteOutcome ¶ added in v2.14.0

type ToolApprovalVoteOutcome string

ToolApprovalVoteOutcome is what VoteToolApproval did with one approver's approval.

const (
	// VoteCounted means the approval was recorded and the quorum is not complete yet.
	VoteCounted ToolApprovalVoteOutcome = "counted"
	// VoteCompleted means the approval was recorded and the request is now approved.
	VoteCompleted ToolApprovalVoteOutcome = "completed"
	// VoteDuplicate means this approver already approved the request. Nothing was recorded.
	VoteDuplicate ToolApprovalVoteOutcome = "duplicate"
	// VoteRequester means the approver opened the request. Nothing was recorded.
	VoteRequester ToolApprovalVoteOutcome = "requester"
	// VoteNotPending means the request is unknown, decided, spent, expired, or needs only one
	// approver (use ApproveToolApproval for those). Nothing was recorded.
	VoteNotPending ToolApprovalVoteOutcome = "not_pending"
)

Vote outcomes.

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 UserDataExport ¶ added in v2.14.0

type UserDataExport struct {
	Version     int       `json:"version"`
	GeneratedAt time.Time `json:"generatedAt"`
	// Sections is keyed by the DataExportSection constants. A value is the section's type (see
	// docs/data-export.md) or DataExportUnavailable. Sections of features that are off are absent.
	Sections map[string]any `json:"sections"`
}

UserDataExport is the data of one user that the export covers, without secrets, hashes or key material. It is not every record: SCIM group membership, audit events naming the user only as the accountability subject, account state and more are left out (docs/data-export.md, Not included).

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

	// AllowConditionalCreate lets a conditional create (automatic passkey upgrade, begun with
	// mediation "conditional") register without user presence, shortly after a password sign-in in
	// the same session. Every other ceremony still requires it. Default false. It cannot be combined
	// with RequireUserVerification. See docs/passkey-signals.md.
	AllowConditionalCreate bool

	// ConditionalCreateWindow is how long after the password sign-in a conditional create is
	// accepted (default 5 minutes).
	ConditionalCreateWindow time.Duration

	// SignalsInResponses makes deleting and renaming a passkey answer 200 with {"signals": ...}
	// (see PasskeySignals) instead of 204 with no body. Default false.
	SignalsInResponses bool

	// SignalUnknownCredentials answers a passkey login with a credential id the server does not
	// store with passkey_unknown, so the page can have the provider delete it. Turn it on only when
	// this server holds every passkey of RPID: another deployment sharing the RP ID may rely on one
	// it does not know. Default false.
	SignalUnknownCredentials bool
}

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 authzen is a policy decision point for the OpenID Authorization API 1.0 (https://openid.net/specs/authorization-api-1_0.html).
Package authzen is a policy decision point for the OpenID Authorization API 1.0 (https://openid.net/specs/authorization-api-1_0.html).
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.
conformance
oidf/provider command
Command provider is a throwaway OpenID Provider for self-run OpenID Foundation conformance tests.
Command provider is a throwaway OpenID Provider for self-run OpenID Foundation conformance tests.
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.
keycloak
Package keycloak holds interop tests against a real Keycloak.
Package keycloak holds interop tests against a real Keycloak.
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.
captcha
Package captcha checks bot challenge tokens: it reads the token from a request, asks a verifier and classifies the outcome.
Package captcha checks bot challenge tokens: it reads the token from a request, asks a verifier and classifies the outcome.
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.
emailchange
Package emailchange holds the address rules, mail text and confirm pages of self serve email change.
Package emailchange holds the address rules, mail text and confirm pages of self serve email change.
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.
epoch
Package epoch guards read-through caches against a store that races an invalidation.
Package epoch guards read-through caches against a store that races an invalidation.
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.
persist
Package persist implements persistent sessions: a long-lived remember credential per device that mints a new short session when the old one dies.
Package persist implements persistent sessions: a long-lived remember credential per device that mints a new short session when the old one dies.
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.
signinnotice
Package signinnotice holds the parts of sign-in notices that need no server state: device recognition, report link tokens, the default mail text and the report pages.
Package signinnotice holds the parts of sign-in notices that need no server state: device recognition, report link tokens, the default mail text and the report pages.
ssodomain
Package ssodomain owns SSO domain ownership proof by DNS TXT and home realm discovery.
Package ssodomain owns SSO domain ownership proof by DNS TXT and home realm discovery.
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.
iot
attest
Package attest verifies device hardware attestation evidence from Android, Apple and TPM 2.0.
Package attest verifies device hardware attestation evidence from Android, Apple and TPM 2.0.
device
Package device is the device side of theAuth IoT identity: sign short lived device assertions, verify signed offline policy bundles, and decide offline with Evaluate.
Package device is the device side of theAuth IoT identity: sign short lived device assertions, verify signed offline policy bundles, and decide offline with Evaluate.
device/internal/tinygocheck command
Command tinygocheck is the smoke test for building iot/device with TinyGo.
Command tinygocheck is the smoke test for building iot/device with TinyGo.
fleet
Package fleet is the Go twin of the TypeScript device conformance kit (@glinr/theauth/testing/devices).
Package fleet is the Go twin of the TypeScript device conformance kit (@glinr/theauth/testing/devices).
fleet/cmd/fleetbench command
Command fleetbench runs the device conformance kit at scale and prints latency percentiles and memory.
Command fleetbench runs the device conformance kit at scale and prints latency percentiles and memory.
mqttauth
Package mqttauth answers the authentication and authorization questions an MQTT broker asks over HTTP: may this client connect, and may it publish to or subscribe to this topic.
Package mqttauth answers the authentication and authorization questions an MQTT broker asks over HTTP: may this client connect, and may it publish to or subscribe to this topic.
mqttauth/redispurge
Package redispurge is a mqttauth.PurgeBroadcaster over Redis PUBLISH and SUBSCRIBE, for deployments of the MQTT broker auth service that already run Redis.
Package redispurge is a mqttauth.PurgeBroadcaster over Redis PUBLISH and SUBSCRIBE, for deployments of the MQTT broker auth service that already run Redis.
mqttauth/revocationmqtt
Package revocationmqtt delivers the signed device revocation snapshot over MQTT as a retained message, and lets a device or gateway receive and verify it.
Package revocationmqtt delivers the signed device revocation snapshot over MQTT as a retained message, and lets a device or gateway receive and verify it.
spiffe
Package spiffe is the SPIFFE workload identity bridge: a workload presents an X.509-SVID or a JWT-SVID, the package verifies it against a trust bundle you configure, and maps the SPIFFE ID to an existing theAuth device through Storage.DeviceBySPIFFEID.
Package spiffe is the SPIFFE workload identity bridge: a workload presents an X.509-SVID or a JWT-SVID, the package verifies it against a trust bundle you configure, and maps the SPIFFE ID to an existing theAuth device through Storage.DeviceBySPIFFEID.
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.
pathmatch
Package pathmatch is resource pattern matching in two modes, the Go twin of the TypeScript core matcher (packages/core/src/policy/resource-match.ts).
Package pathmatch is resource pattern matching in two modes, the Go twin of the TypeScript core matcher (packages/core/src/policy/resource-match.ts).
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