auth

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0 Imports: 31 Imported by: ? modules, 0 packages

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

README

tensile-auth

CI Go Reference npm OpenSSF Best Practices OpenSSF Scorecard License

Like Better Auth, but built for agents. Open source, for Go and TypeScript.

A person signs in with a passkey. Each agent they hand work to gets its own narrower, shorter-lived session. When an agent tries something risky, the person approves that exact action with one tap, and the agent runs it once.

Read the docs, start with the quickstart, or point your coding agent at llms.txt.

The idea in code

svc, _ := auth.New(memstore.New())

// After your app has signed alice in:
_, alice, _ := svc.StartSession(ctx, "alice", auth.StartOptions{Scopes: []string{"repo:read", "repo:write"}})

// alice registers an agent and hands it a narrower, shorter-lived session.
agent, _ := svc.CreateAgent(ctx, alice, auth.AgentSpec{Name: "Claude Code", Scopes: []string{"repo:read"}})
tok, _, _ := svc.Delegate(ctx, alice, auth.DelegateSpec{Agent: agent.ID, Scopes: []string{"repo:read"}})

p, _ := svc.Authenticate(ctx, tok.Reveal()) // p.User == "alice", p.IsAgent() == true
_ = svc.Revoke(ctx, alice.Session)          // the agent's session ends too, immediately

Every principal names the human it acts for. A delegated session gets a subset of its parent's scopes, never outlives its parent, and ends when its parent ends.

Agents ask, people approve

Wrap a risky route with authhttp.Approvable:

mux.Handle("DELETE /repos/{id}", authhttp.Public, authhttp.Approvable(auth.Need{Action: "repo.delete", Human: true}, func(r *http.Request) auth.Action {
	return auth.Action{Kind: "repo.delete", Resource: r.PathValue("id"), Summary: "Delete the repository " + r.PathValue("id")}
})(http.HandlerFunc(deleteRepo)))
  1. The agent asks. An agent that calls the route gets a link instead of a yes.
  2. The person taps. They open the link and approve with a passkey, which signs that exact action.
  3. It runs once. The agent's retry waits for the decision, runs the route once, and leaves a signed receipt in the audit log.

The approvals guide covers waiting, notifications, and serverless apps.

Quickstart

go get tensile.tools/auth@latest

The service, every sign-in route, and one element make a complete passkey sign-in. Error handling is left out here:

store := memstore.New()
limiter, _ := ratelimit.New(ratelimit.NewMemory(), ratelimit.DefaultRules())
svc, _ := auth.New(store, auth.WithLimiter(limiter))
go svc.Run(ctx) // seals the audit log
pk, _ := passkey.New(svc, store, passkey.Config{RPID: "localhost", Origins: []string{"http://localhost:8080"}})
mux := authhttp.NewMux(svc, authhttp.WithClientIP(), authhttp.WithOrigins("http://localhost:8080"))
authroutes.Mount(mux, authroutes.Config{Passkeys: pk, PasskeyOnly: true})
<tensile-sign-in redirect="/"></tensile-sign-in>
<script type="module" src="/auth/client/elements/index.js"></script>

To see it working, run go run ./examples/quickstart and open http://localhost:8080. examples/quickstart is the same code with its errors handled. For a complete app with agents, approvals, a CLI, and an MCP server, run go run ./examples/agents and follow its tour.

Presets

A preset is a complete configuration in one line. Its name is versioned, so standard@1 means the same settings forever, and it states the OWASP ASVS 5.0 level it reaches.

p := preset.MustGet(preset.Standard)
// auditKey is at least 32 random bytes that you keep for the life of the
// audit log, for example from a secret manager.
svc, err := auth.New(store, p.ServiceOptions(auth.WithLimiter(limiter), auth.WithAuditKey(auditKey))...)

A preset with passwords needs an audit key: password.New refuses to start without one.

Preset For Passwords Second factor ASVS 5.0
consumer@1 Consumer apps 8 characters, breached-password check required Optional Level 1, and Level 2 except 6.3.3
standard@1 Most apps, and the default 15 characters; no account until the address is confirmed A passkey offered after the first sign-in Level 1, and Level 2 except 6.2.12 and 6.3.3
strict@1 Admin and finance apps 15 characters Required, with a recovery path, before a full session Level 2
passkey-only@1 Apps with no passwords None The passkey, with confirmed recovery codes Level 2

To see every setting a preset expands to, run go run ./cmd/tensile-auth-preset standard@1.

No paid tier

Passkeys, two-step sign-in, recovery codes, sign-in with Google, GitHub, or any OpenID Connect provider, the OAuth provider, MCP authorization, and the audit log are all in this library, under Apache-2.0. Security features never move behind a paid tier.

How it compares

tensile-auth is an embedded framework: it runs inside your Go binary and stores users in your database. Each row was checked against the project's own repository, docs, or pricing page on 23 November 2026 and again on 3 December 2026; the full comparison explains each one.

Project Runs as Licence Passkeys Choose it when
tensile-auth A library in your binary Apache-2.0 Yes People and their agents both call your Go app
go-webauthn A library in your binary BSD-3-Clause Yes You add passkeys to your own user system
goth A library in your binary MIT No You need sign-in with many OAuth providers
authboss A library in your binary MIT No You want password accounts and TOTP in your binary
Ory Kratos A server you operate Apache-2.0 Yes You want identity flows as an API, with your own screens
Zitadel A server you operate AGPL-3.0 Yes You need multi-tenant B2B identity, SAML, and SCIM
Keycloak A server you operate Apache-2.0 Yes You need SAML, LDAP, and enterprise single sign-on
Auth0, Clerk, WorkOS A hosted service Proprietary Yes; on Clerk's paid plans, and in WorkOS's hosted sign-in You'd rather pay than operate identity

Better Auth (MIT) runs inside your own TypeScript server and has no Go SDK. It adds agents with its Agent Auth plugin, which its docs call not yet stable, and keeps its stored audit log in its paid hosted service. Choose it when your whole app is TypeScript, or you need organizations, SAML, or SCIM today. These facts were checked on 5 December 2026; the Better Auth comparison explains each one.

tensile-auth has no SAML, no SCIM, no organizations, and no external security audit, and it is pre-1.0.

Apps in other languages

tensile-auth-server runs the library as one binary, and @tensile-tools/auth, the TypeScript SDK, connects a Node, Bun, or Deno app to it, with adapters for Next.js, Express, and Hono. Start with the Node integration guide and the operator guide.

npm install @tensile-tools/auth @tensile-tools/auth-client

Everything it does

  • Human and agent sessions. Agents can delegate to sub-agents, and every principal still names the responsible human.
  • Delegation only narrows: a child gets a subset of its parent's scopes, never outlives its parent, and depth is capped.
  • Human login with passkeys, or an email and a password. passkey handles discoverable passkeys with user verification and step-up, password handles email and password sign-in held to OWASP ASVS 5.0 Level 2, recovery issues one-time recovery codes, and totp adds TOTP as a second factor. Adding or removing a factor needs a session that authenticated within 10 minutes, and Principal.MultiFactor reports how strongly a session signed in.
  • Passwords that can't weaken an account. Argon2id hashes, a 15-character minimum, a list of 10,000 common passwords, and an optional breached-password check (password/pwned). A password alone is single-factor, and it never stands in for a passkey or TOTP the account has: such an account's password session is never fresh. Sign-up, sign-in, and forgot-password answer the same for every address, nothing locks an account, and a code sent by email never signs anyone in. An account with an unconfirmed address can't use agents.
  • Agents that sign themselves up. With auth.WithSignup, an agent registers itself, gets a sandboxed token and a single-use claim code, and waits for a fresh, multi-factor human to claim it. Unclaimed agents are deleted at their claim deadline.
  • Personal access tokens and OAuth. Scoped, expiring personal access tokens (tsp_…), and an OAuth 2 and OpenID Connect provider with the device flow, the code flow with PKCE, rotating refresh tokens, and token exchange onto delegation. gh auth login --hostname works against it.
  • MCP authorization. The provider is an MCP authorization server: resource indicators (RFC 8707) bind each token to one MCP server, every authorization response carries iss (RFC 9207), and clients such as Claude Code and ChatGPT connect with their client ID metadata documents, fetched with SSRF protection, or, behind a flag, with dynamic registration. mcpauth makes a server built on the official Go MCP SDK a resource server, with per-tool scopes, and each connected client is a connection you list, audit tool by tool, and revoke on its own.
  • Social login that can't take over accounts. federation signs people in with Google, GitHub, or any OpenID Connect provider. Identities are keyed by the provider's subject, never by email address; linking needs a signed-in, recently verified human; and your sign-up hook alone decides who gets an account.
  • Opaque, checksummed tokens (tss_…, tsa_…, tsp_…, tso_…, tsr_…) that secret scanners can detect, and leakscan, which revokes a token when a scanner reports it. Only their SHA-256 is stored, and the Token type redacts itself everywhere.
  • Agent tokens bound to keys. With DPoP (RFC 9449), an agent's token works only with a fresh proof signed by the agent's private key, so a leaked token alone gets nowhere. auth.RequireAgentKeys refuses to create unbound agent sessions.
  • Quotas. auth.WithQuota checks a hook before agent creation, signup, claims, delegation, and personal access token creation. The built-in auth.Caps caps enabled agents per human and live sessions per agent, and a quota that fails refuses the action.
  • Rotation with a 10-second grace window. Reusing a rotated-out token revokes the whole session tree.
  • net/http middleware that accepts Bearer, DPoP, gh's token scheme, git's Basic auth, and cookies, with CSRF protection built in.
  • A built-in audit log. Every session start, delegation, rotation, revocation, agent change, and detected token reuse is recorded in the same transaction as the change. Failed sign-ins, throttled attempts, rejected tokens, and denied requests are recorded too, with the client, and bounded so attackers can't flood the table. Read it with svc.Events. Events are sealed into a hash chain, so svc.VerifyAudit detects edits and deletions, and signed checkpoints catch a rebuilt chain.
  • Rate limiting built in. ratelimit throttles sign-in attempts per client and per identified user, with counters in memory, Redis or Valkey, or PostgreSQL, so every server shares them. Attackers can slow themselves down but can't lock anyone else out.
  • Fast checks across servers. cachestore caches token lookups, and pgstore.Watch clears every server's cache through Postgres LISTEN/NOTIFY when any server revokes or rotates a token. If the watcher loses its connection, the cache switches itself off.
  • An admin API. authadmin serves versioned JSON routes that your administrators, human or agent, use to inspect users, sessions, delegation trees, and agents, revoke them, page through the audit log, and see alerts. You mount it behind your own admin check, and an OpenAPI 3.1 document describes it.
  • Leave in one command. tensile-auth-server export writes every person's address, password hash, passkeys, TOTP secret, recovery codes, and identities to one age-encrypted file, and import signs them all in elsewhere as the same user. It also imports from Auth0, Clerk, and Supabase. See the leaving guide.
  • A Store interface with in-memory, SQLite, and PostgreSQL stores, and a conformance suite that every store must pass.

Protect an MCP server with the sign-in you already have

You don't need the library's provider to use mcpauth. If your authorization server, such as Auth0, Okta, Keycloak, or Clerk, issues JWT access tokens, verify them with mcpauth.JWT:

v, err := mcpauth.JWT(mcpauth.JWTConfig{
	Issuer:   "https://example.us.auth0.com/", // exactly as the tokens' iss holds it
	Audience: "https://notes.example.com/mcp", // configure your server to put this in aud
})
p, err := mcpauth.New(mcpauth.Options{
	Resource:             "https://notes.example.com/mcp",
	AuthorizationServers: []string{"https://example.us.auth0.com/"},
	Verifier:             v,
	Scopes:               []string{"notes:read"},
	ToolScopes:           map[string][]string{"notes_list": nil, "notes_add": {"notes:write"}},
})
p.Register(mux, "/mcp", server, &mcp.StreamableHTTPOptions{Stateless: true})

The verifier finds the keys through the issuer's metadata, accepts only asymmetric signatures, and requires the issuer, an expiry, and your MCP server as audience. A JWT can't be revoked before it expires, so keep tokens short or set MaxAge.

If your application has its own login but no OAuth server, authhttp.Bridge puts that login in front of the library's provider and consent page. See examples/mcpserver with -own-login, and the design.

Learn more

Packages

Package Purpose
auth Sessions, delegation, tokens, agent signup, personal access tokens, OAuth grants, quotas, the audit log and its hash chain, and errors. Standard library only
authhttp Middleware (Bearer, DPoP, token, Basic, and cookies), Require, RequireScope, RequireFresh, and cookie helpers
authadmin Admin API: users, sessions, agents, revocation, the audit log, and alerts, with an OpenAPI document
memstore In-memory Store for tests and examples
sqlitestore SQLite Store for local and small installs (cgo-free)
pgstore PostgreSQL Store (pgx v5) for servers, Watch to keep caches fresh across servers, NewRateLimits for rate-limit counters, and NewProofReplays for DPoP proof IDs
passkey Passkey registration, sign-in, and step-up (go-webauthn)
password Email and password sign-up, confirmation, sign-in, step-up, change, reset, and address change, with Argon2id (x/crypto)
password/pwned An opt-in breached-password check against the Have I Been Pwned range API
preset Versioned presets: a complete configuration in one line, with its ASVS level
recovery One-time recovery codes
totp TOTP as a second factor, with sealed secrets
federation Sign-in with Google, GitHub, and other OpenID Connect providers, with safe account linking (zitadel/oidc, x/oauth2)
ratelimit A ready-made limiter for sign-in attempts, with an in-memory backend
ratelimit/redislimit Rate-limit counters in Redis or Valkey (go-redis/redis_rate)
ratelimit/limittest Conformance suite for rate-limit backends
dpop DPoP proofs of possession for agent tokens: verification, signing for clients, and an in-memory replay cache (go-jose)
dpop/redisreplay DPoP replay cache in Redis or Valkey
dpop/replaytest Conformance suite for replay caches
leakscan Handler for secret-scanning alerts that revokes leaked tokens (GitHub's format)
oauth OAuth 2 and OpenID Connect provider: device flow, code flow, refresh, token exchange, resource indicators, client ID metadata documents, and dynamic registration (zitadel/oidc)
mcpauth Protects an MCP server built on the official Go SDK: Protected Resource Metadata, audience checks, per-tool scopes, audited tool calls, and verifiers for this library's tokens, introspection, and JWT access tokens from another authorization server (modelcontextprotocol/go-sdk)
authexport Export every sign-in record to one age-encrypted file, and import it into another store as the same users (filippo.io/age)
cachestore Short-lived cache of token lookups that wraps any Store
server The tensile-auth server: the library as one binary for apps in any language, with its configuration, startup checks, and health endpoints. cmd/tensile-auth-server runs it; the operator guide covers installing, configuring, and running it
sdk @tensile-tools/auth, the TypeScript backend SDK for the server, with Next.js, Express, and Hono adapters. A Node, Bun, or Deno app uses it to proxy /auth/ and check each request; the Node integration guide walks through it
storetest Conformance suites for stores: storetest.Run(t, newStore), and RunFactors, RunSignup, RunSignupSettings, RunDevices, RunIdentities, RunEmails, and RunTransfer for the optional store interfaces

To see passkey sign-up, sign-in, step-up, and recovery codes in a browser, run go run ./examples/passkeyapp and open http://localhost:8080. To sign the gh CLI in to a server built on the library, see examples/ghserver. To connect Claude Code to an MCP server protected by the library, see examples/mcpserver. The security self-assessment maps the library to OWASP ASVS 5.0.

Repository layout

The Go files in the root folder are package auth; its documentation is in doc.go. Each package in the table above has its own folder, and every folder has a README.md that lists what's in it. The other folders:

Folder What it holds
docs/ The integration guide, the server's operator guide, the error catalog, the design and security invariants, the release process, and the designs behind each feature
examples/ Runnable applications built on the library
client/ The browser client, in TypeScript, and its compiled build that authroutes serves
skills/ The agent skill and the test that keeps its recipe compiling
cmd/ tensile-auth-server, the server; tensile-auth-preset, which prints a preset; and the FIDO conformance server
internal/ Packages the library shares but applications can't import
tools/ The development tools, in their own module, and the common-password generator
bench/ The coding-agent benchmark
conformance/ The OpenID conformance run against examples/ghserver
.github/workflows/ The CI, fuzzing, workflow audit, and conformance workflows
.githooks/ The pre-commit hook that just hooks installs

Development

Needs Go 1.26+, just and golangci-lint v2.

just hooks   # once: run fmt-check and lint before every commit
just ci      # everything CI runs: actions-check, fmt-check, lint, tidy-check, test (race), vuln
just fuzz    # every fuzz target, FUZZTIME=10s each by default
just fuzz-changed  # only the targets your changes since origin/main can affect
just cover   # coverage report
just test-pg # Postgres store tests in a throwaway Postgres 18 container (needs Docker)
just test-redis # Redis limiter and DPoP replay cache tests in a throwaway Valkey 8 container (needs Docker)
just test-gh # the real gh CLI against examples/ghserver on port 443 (Linux, needs gh)
just api-check # API compatibility with the latest release tag (gorelease)

Licence: Apache-2.0. Security reports: see SECURITY.md. The project doesn't accept pull requests yet; CONTRIBUTING.md explains how to help.

Documentation

Overview

Package auth authenticates the humans who use an application and the AI agents acting for them.

A human signs in with a passkey (package passkey), a recovery code (package recovery), TOTP as a second factor (package totp), or an external identity provider (package federation). Factors return proofs, and Service.BeginSignIn and Service.CompleteSignIn turn them into a session, asking for a second factor when the account needs one. From a session, the human delegates narrower, shorter-lived sessions to agents with Service.Delegate, and agents delegate further to sub-agents. Every Principal names the responsible human, however deep the delegation goes.

Operations declare what they need with a Need: a minimum Assurance, how recent the human's proof must be, whether only a human may act, and scopes. Service.Require enforces it, records every refusal, and returns a Refusal that says how to satisfy it. Describe turns every error the library returns into one RFC 9457 Problem. An agent refused a human-only action can ask its human with Service.RequestApproval, who approves that exact action with one passkey tap.

Delegation only ever narrows: a child session gets a subset of its parent's scopes, never outlives its parent, and the chain is capped at Policy.MaxDepth. Revoking a session revokes everything delegated from it before Service.Revoke returns.

Tokens are opaque, prefixed, and checksummed, for example "tss_…" for a human session and "tsa_…" for an agent session, so secret scanners can find leaked ones. Only their SHA-256 digest is stored, and the Token type redacts itself when printed, logged, or marshaled.

Every change is recorded in an audit log in the same transaction as the change. Read it with Service.Events.

Storage is pluggable through Store and FactorStore: memstore for tests, sqlitestore, and pgstore, each checked by the storetest conformance suite. Package authhttp connects the service to net/http, and the browser client lives in client/. Start with docs/guide.md.

Example

A human signs in, registers an agent, and hands it a narrower session. Revoking the human's session revokes the agent's too.

package main

import (
	"context"
	"fmt"

	auth "tensile.tools/auth"
	"tensile.tools/auth/memstore"
)

func main() {
	ctx := context.Background()
	svc, err := auth.New(memstore.New())
	if err != nil {
		panic(err)
	}

	// After your app has authenticated the human (passkey, SSO, ...):
	_, human, err := svc.StartSession(ctx, "alice", auth.StartOptions{Scopes: []string{"repo:read", "repo:write"}})
	if err != nil {
		panic(err)
	}

	agent, err := svc.CreateAgent(ctx, human, auth.AgentSpec{Name: "Claude Code", Scopes: []string{"repo:read", "repo:write"}})
	if err != nil {
		panic(err)
	}
	agentTok, _, err := svc.Delegate(ctx, human, auth.DelegateSpec{Agent: agent.ID, Scopes: []string{"repo:read"}})
	if err != nil {
		panic(err)
	}

	p, err := svc.Authenticate(ctx, agentTok.Reveal())
	if err != nil {
		panic(err)
	}
	fmt.Println(p.User, p.IsAgent(), p.Has("repo:read"), p.Has("repo:write"))
	fmt.Println(agentTok) // tokens redact themselves when printed

	if err = svc.Revoke(ctx, human.Session); err != nil {
		panic(err)
	}
	_, err = svc.Authenticate(ctx, agentTok.Reveal())
	fmt.Println(err)
}
Output:
alice true true false
tsa_REDACTED
auth: unauthenticated

Index

Examples

Constants

View Source
const (
	MinApprovalTTL = time.Minute
	MaxApprovalTTL = 24 * time.Hour
)

Limits of Need.ApprovalTTL.

View Source
const (
	// MaxApprovalNotifications is how many notifications run at once. A
	// new approval while that many run is logged and not notified.
	MaxApprovalNotifications = 32
	// ApprovalNotifyTimeout is how long one notification may run before
	// its context ends.
	ApprovalNotifyTimeout = 30 * time.Second
)

Limits of an ApprovalNotifier.

View Source
const (
	// MaxApprovalWaitsPerAgent is the most waits one agent holds.
	MaxApprovalWaitsPerAgent = 4
	// MaxApprovalWaits is the most waits one Service holds.
	MaxApprovalWaits = 1024
)

Limits on the waits that Service.RedeemApprovalWait holds open at once. A wait over either limit returns ErrApprovalPending at once, as a redeem without a wait does.

View Source
const (
	// ActionGrant is [Service.Grant].
	ActionGrant = "oauth.grant"
	// ActionSignupOverride is [Service.SetSignupOverride].
	ActionSignupOverride = "signup.override"
)

Actions of the library's own needs, in access_denied events.

View Source
const (
	// ActionCreateAgent is [Service.CreateAgent].
	ActionCreateAgent = "create_agent"
	// ActionRegisterAgent is [Service.RegisterAgent]. The request has no
	// User, because a self-signed-up agent has no human yet.
	ActionRegisterAgent = actionRegister
	// ActionClaimAgent is [Service.ClaimAgent]: the claimer gains an agent
	// and the agent gains a session. The request names the claimer but no
	// Agent, because the store finds the agent by its claim code.
	ActionClaimAgent = actionClaim
	// ActionDelegate is [Service.Delegate], and token exchange through it.
	ActionDelegate = "delegate"
	// ActionCreatePAT is [Service.CreatePAT].
	ActionCreatePAT = "create_pat"
)

Actions that a Quota checks, in QuotaRequest.Action. They are also the Action of the access_denied events that a refusal records.

View Source
const (
	// ConflictUser means the user ID has a sign-in record already.
	ConflictUser = "user"
	// ConflictEmail means another user holds the address.
	ConflictEmail = "email"
	// ConflictHandle means another user holds the passkey user handle.
	ConflictHandle = "handle"
	// ConflictCredential means the passkey credential ID is registered.
	ConflictCredential = "credential"
	// ConflictRecoveryCode means another user holds a code with the same
	// hash.
	ConflictRecoveryCode = "recovery_code"
	// ConflictIdentity means the issuer and subject are linked already.
	ConflictIdentity = "identity"
	// ConflictAgent means the agent ID exists.
	ConflictAgent = "agent"
	// ConflictOwner means the agent's owner isn't a user that this import
	// stores: the owner is missing from the import, existed before it, or
	// was skipped. An import never attaches an agent to a user that existed
	// before it.
	ConflictOwner = "owner"
)

What an ImportConflict collided with.

View Source
const ActionPeekClaim = "agent.peek_claim"

ActionPeekClaim is the limiter action for Service.PeekClaim.

View Source
const ApprovalTTL = 5 * time.Minute

ApprovalTTL is how long an approval request waits for its human, and how long an approval waits to be redeemed, unless Need.ApprovalTTL sets another time.

View Source
const ClaimFreshFor = 10 * time.Minute

ClaimFreshFor is how recently the claimer must have authenticated.

View Source
const DefaultAccessTTL = time.Hour

DefaultAccessTTL is the lifetime of an OAuth access token issued with a refresh token, when GrantSpec.AccessTTL is zero.

View Source
const DefaultDeviceBoundLifetime = 10 * time.Minute

DefaultDeviceBoundLifetime is how long a device-bound session's token works before the browser must prove its key again.

View Source
const DefaultRecoveryHold = time.Hour

DefaultRecoveryHold is how long, after a recovery code is used, needs with HoldAfterRecovery stay refused. See WithRecoveryHold.

View Source
const GrantFreshFor = 30 * time.Minute

GrantFreshFor is how recently the human must have authenticated for Service.Grant. It covers an approval within PATFreshFor followed by a device's wait of up to 15 minutes for its token; the oauth package checks PATFreshFor when the human approves.

View Source
const MaxApprovalWait = 60 * time.Second

MaxApprovalWait is the longest Service.RedeemApprovalWait waits.

View Source
const MaxCollectWait = 60 * time.Second

MaxCollectWait is the longest Service.CollectClaimWait waits.

View Source
const MaxElevation = time.Hour

MaxElevation is the longest an elevation from Service.Elevate is kept. A need's Within decides how long it counts, up to this.

View Source
const MaxProofAge = 5 * time.Minute

MaxProofAge is how old a proof can be when it is used.

View Source
const MinAuditKeySize = 32

MinAuditKeySize is the smallest key, in bytes, that WithAuditKey accepts.

View Source
const PATFreshFor = 10 * time.Minute

PATFreshFor is how recently the human must have authenticated to create a personal access token.

View Source
const PasswordInvalid = "!"

PasswordInvalid is the hash that marks a password an administrator invalidated. It matches no password.

View Source
const PendingTTL = 5 * time.Minute

PendingTTL is how long a pending sign-in waits for its remaining factors. A recovery code it reserved stays unspent if it expires.

View Source
const ProblemTypePrefix = "urn:tensile:auth:problem:"

ProblemTypePrefix starts every Problem Type. The URN names the problem without depending on a domain.

View Source
const (

	// SignupOverrideFreshFor is how recently the human changing the
	// override must have authenticated.
	SignupOverrideFreshFor = 10 * time.Minute
)
View Source
const UndoWindow = 72 * time.Hour

UndoWindow is how long after a recovery sign-in another device can undo it with Service.UndoRecovery.

Variables

View Source
var (
	// ErrApprovalPending means the human hasn't decided yet: retry later.
	ErrApprovalPending = NewError("auth: approval pending", Problem{
		Status: 409, Code: "approval_pending", Title: "Waiting for approval", RetryAfter: 5,
		Fix: "Wait for the person to approve, then try again. To wait in one request, retry with the header Prefer: wait=60.",
	})
	// ErrApprovalDenied means the human denied the request.
	ErrApprovalDenied = NewError("auth: approval denied", Problem{
		Status: 403, Code: "approval_denied", Title: "Request denied",
		Fix: "The person denied this request. Ask them before trying again.",
	})
	// ErrApprovalInvalid means the approval is unknown, expired, already
	// used, from another agent, or for a different action. It is spent
	// either way.
	ErrApprovalInvalid = NewError("auth: approval invalid", Problem{
		Status: 403, Code: "approval_invalid", Title: "That approval can't be used",
		Fix: "The approval expired, was used, or was for a different action. Ask again.",
	})
)

Errors that approvals return.

View Source
var (
	ErrScopeExceeded  = errors.New("auth: requested scope exceeds what the parent holds")
	ErrExpiryExceeded = errors.New("auth: requested lifetime exceeds what the parent allows")
	ErrDepthExceeded  = errors.New("auth: delegation chain too deep")
	ErrParentInactive = errors.New("auth: parent session is revoked or expired")
	ErrAgentInactive  = errors.New("auth: agent is disabled")
	ErrNotAgentOwner  = errors.New("auth: agent belongs to a different user")
	ErrInvalidInput   = errors.New("auth: invalid input")
)

Errors returned when a request to start or delegate a session is invalid.

View Source
var (
	// ErrNotFound means a session or agent does not exist. Management calls
	// only; Authenticate never returns it.
	ErrNotFound = errors.New("auth: not found")
	// ErrNotRotatable means the token belongs to an agent session. Agent
	// sessions are short-lived and are re-delegated instead of rotated.
	ErrNotRotatable = errors.New("auth: agent sessions cannot be rotated")
	// ErrRotateConflict means another request rotated the same token first.
	// Keep using the old token: it stays valid for Policy.RotateGrace.
	ErrRotateConflict = errors.New("auth: token was rotated concurrently")
	// ErrResourceMismatch means a refresh named a resource other than the
	// one its grant was issued for. A grant's resource never changes.
	ErrResourceMismatch = errors.New("auth: the grant is for a different resource")
)

Errors returned by session management calls.

View Source
var (
	// ErrFactorExists means the credential is already registered, or the
	// user already has a factor where only a first one is allowed.
	ErrFactorExists = errors.New("auth: factor already exists")
	// ErrConflict means a compare-and-swap lost to a concurrent update.
	ErrConflict = errors.New("auth: concurrent update")
	// ErrStepUpRequired means the operation needs a human session that
	// authenticated recently. Send the user through step-up and retry.
	ErrStepUpRequired = errors.New("auth: a recently authenticated human session is required")
	// ErrStrongerFactorRequired means the session is recent, but a
	// recovery code is its only factor: see [Principal.RecoveryOnly].
	// Stepping up with another recovery code doesn't help. Send the user
	// to add a passkey, or to step up with a passkey or TOTP, and retry. It
	// also matches [ErrStepUpRequired], so callers that only check that
	// error keep working.
	ErrStrongerFactorRequired error = strongerFactorError{}
)

Errors returned by factor stores and factor packages.

View Source
var (
	// NeedRevokeOwn is checked by [Service.RevokeOwn] and
	// [Service.RevokeOwnAgent]. Ending your own session or agent is safe
	// from any human session, including one in recovery mode.
	NeedRevokeOwn = Need{Action: "session.revoke_own", Assurance: AssuranceRecovering, Human: true}
	// NeedRevokeOthers is checked by [Service.RevokeOthers]. It refuses
	// recovery mode, so a stolen recovery code can't sign the person out
	// of the devices that could undo the recovery.
	NeedRevokeOthers = Need{Action: "session.revoke_others", Assurance: AssuranceSingle, Within: 10 * time.Minute, Human: true}
)

Needs that the ownership-checked management calls check. WithNeeds tightens them.

View Source
var (
	// NeedCreatePAT is checked by [Service.CreatePAT].
	NeedCreatePAT = Need{Action: ActionCreatePAT, Assurance: AssuranceSingle, Within: PATFreshFor, Human: true, HoldAfterRecovery: true}
	// NeedGrant is checked by [Service.Grant].
	// A session from the application's own login can meet it.
	NeedGrant = Need{Action: ActionGrant, Assurance: AssuranceSingle, Within: GrantFreshFor, Human: true, HoldAfterRecovery: true, Bridged: true}
	// NeedClaimAgent is checked by [Service.ClaimAgent].
	NeedClaimAgent = Need{Action: ActionClaimAgent, Assurance: AssuranceMulti, Within: ClaimFreshFor, Human: true, HoldAfterRecovery: true}
	// NeedSignupOverride is checked when a human changes the signup
	// overrides.
	NeedSignupOverride = Need{Action: ActionSignupOverride, Assurance: AssuranceMulti, Within: SignupOverrideFreshFor, Human: true}
)

The library's own needs. WithNeeds tightens them by Action.

View Source
var (
	// ErrQuotaExceeded means a [Quota], the store's agent cap, or
	// [SignupPolicy].MaxUnclaimed refused the action. [SignupStore] and
	// [Store.InsertAgent] return it too.
	ErrQuotaExceeded = errors.New("auth: quota exceeded")
	// ErrQuotaUnavailable means a [Quota] returned an error other than
	// [ErrQuotaExceeded], so the library refused the action. Treat it as a
	// server error. The quota's error is wrapped.
	ErrQuotaUnavailable = errors.New("auth: quota unavailable")
)

Errors returned when a quota refuses an action.

View Source
var (
	// ErrSignupRejected means signup is off, or the policy, a hook, or a
	// quota rejected the request. Use [ReasonOf] for logs. A refusal by a
	// quota also matches [ErrQuotaExceeded].
	ErrSignupRejected = errors.New("auth: agent signup rejected")
	// ErrClaimInvalid means the claim code is unknown, already used, or
	// past its deadline.
	ErrClaimInvalid = errors.New("auth: claim code is unknown, used, or expired")
	// ErrNotClaimed means no human has claimed the agent yet. Ask again
	// later.
	ErrNotClaimed = errors.New("auth: agent is not claimed yet")
)

Errors returned by agent signup.

View Source
var (
	// ErrOverridesOff means the service doesn't use signup overrides, or
	// signup is off in code.
	ErrOverridesOff = errors.New("auth: signup overrides are off")
	// ErrWidens means a SignupOverride would widen the code policy.
	ErrWidens = errors.New("auth: a signup override can only narrow the code policy")
)

Errors for signup overrides.

View Source
var (
	// ErrTargetNotEmpty means the store has sign-in records and the
	// import didn't set Merge.
	ErrTargetNotEmpty = errors.New("auth: the store has sign-in records; import into an empty store, or merge")
	// ErrImportConflict means a record in the import conflicts with a
	// stored one or with another in the import, and the import didn't
	// set Merge.
	ErrImportConflict = errors.New("auth: the import conflicts with stored records")
)

Errors of TransferStore.ImportUsers.

View Source
var ErrAuditTampered = errors.New("auth: audit log has been tampered with")

ErrAuditTampered means a sealed event or a checkpoint doesn't match the chain. The error names the first position that fails.

View Source
var ErrDevToolsOff = errors.New("auth: dev tools are off")

ErrDevToolsOff means a development-only call ran without WithDevTools.

View Source
var ErrDeviceProof = NewError("auth: device proof rejected", Problem{
	Status: 401, Code: "device_proof_rejected", Title: "Sign in again",
	Fix: "This device couldn't prove it holds the session's key. Sign in again.",
})

ErrDeviceProof means a DBSC proof didn't verify: a malformed token, a bad signature, an unknown or used challenge, or an unknown binding. The browser ends the device-bound session; the person signs in again.

View Source
var ErrEmailUnverified = errors.New("auth: a confirmed email address is required")

ErrEmailUnverified means the account has an email address that isn't confirmed. A *Refusal with CodeEmailUnverified matches it.

View Source
var ErrFactorRejected = errors.New("auth: factor rejected")

ErrFactorRejected is returned when a factor doesn't verify: an unknown or wrong credential, a bad or reused code, or an expired or reused ceremony. Every cause returns the same error, so responses can't reveal whether an account exists. Use ReasonOf only for logs and metrics.

View Source
var ErrKeyRequired = errors.New("auth: agent sessions must be bound to a key")

ErrKeyRequired is returned when a service created with RequireAgentKeys is asked to create an agent session that isn't bound to a key.

View Source
var ErrProofReplayed = errors.New("auth: proof of possession was already used")

ErrProofReplayed is the error that KeyProof.Spend returns for a proof that was already used.

View Source
var ErrScopeMissing = errors.New("auth: a required scope is missing")

ErrScopeMissing means the principal lacks a scope that an operation's Need lists.

View Source
var ErrSignInIncomplete = NewError("auth: pending sign-in can't complete", Problem{
	Status: 401, Code: "sign_in_incomplete", Title: "Start signing in again",
	Fix: "Your sign-in expired or is missing a step. Sign in again.",
})

ErrSignInIncomplete means Service.CompleteSignIn got a pending token that is unknown, expired, or already used, or proofs that don't cover what the pending sign-in needs. The pending sign-in is spent either way: start signing in again.

View Source
var ErrThrottled = errors.New("auth: too many attempts")

ErrThrottled means the limiter asked the caller to wait. Use RetryAfter to read how long.

View Source
var ErrTokenReused = errors.New("auth: token reused")

ErrTokenReused means a rotated-out token was presented after its grace window. The whole session tree has been revoked. An error matching ErrTokenReused also matches ErrUnauthenticated.

View Source
var ErrUnauthenticated = errors.New("auth: unauthenticated")

ErrUnauthenticated is returned for every token that cannot be used: malformed, unknown, expired, idle, revoked or reused. Callers must treat all of these the same way in responses. Use ReasonOf only for logs and metrics.

View Source
var ErrUndoNotAllowed = NewError("auth: undo needs a session from before the recovery", Problem{
	Status: 403, Code: "undo_not_allowed", Title: "Use another device",
	Fix: "Undo the recovery from a device that was signed in before it.",
})

ErrUndoNotAllowed means Service.UndoRecovery came from a session that started at or after the recovery, or that used a recovery code itself: either could be the attacker's.

View Source
var NeedApprove = Need{Action: "approval.decide", Assurance: AssuranceRecovering, Human: true}

NeedApprove is the need Service.Approve and Service.Deny check.

View Source
var NeedPeekClaim = Need{Action: "agent.peek_claim", Assurance: AssuranceRecovering, Human: true}

NeedPeekClaim is the need Service.PeekClaim checks.

View Source
var NeedUndoRecovery = Need{Action: "recovery.undo", Assurance: AssuranceSingle, Within: 10 * time.Minute, Human: true}

NeedUndoRecovery is the need Service.UndoRecovery checks. WithNeeds tightens it.

Functions

func ApprovalChallenge

func ApprovalChallenge(id string, digest [32]byte) []byte

ApprovalChallenge is the WebAuthn challenge for approving approval id with digest. A passkey that signs it signs the action itself.

func CheckImportedAgent

func CheckImportedAgent(a *Agent) error

CheckImportedAgent applies the rules that Service.CreateAgent applies to an agent's name and scopes: a name of 1 to 100 printable bytes, and valid scopes, sorted and without duplicates, as the service stores them. An import calls it before storing an agent.

It doesn't cap the scopes by the owner's: the library stores no scopes for a user, only for the sessions that Service.CreateAgent checks against. An imported agent gains nothing from wide scopes, because Service.Delegate grants a session only scopes that both the owner's session and the agent hold.

func ClientFrom

func ClientFrom(ctx context.Context) string

ClientFrom returns the key set by WithClient, or "".

func HintFactor

func HintFactor(r Reason, hint Problem) error

HintFactor returns an error like RejectFactor that also tells the person what to do, through Describe. Use it only after the person is identified, for example for a second factor or a step-up, never before sign-in, where every failure must look the same.

func NewError

func NewError(msg string, p Problem) error

NewError returns an error with message msg that Describe turns into p. Packages built on this library use it for their sentinel errors, so their failures reach clients in the same shape.

func PairingWords

func PairingWords(code string) [4]string

PairingWords returns four words derived from a claim code, for an agent to print next to its claim link and for Service.PeekClaim to show the person. Matching words prove the person is claiming the agent in front of them. The words carry 32 bits of the code's hash, too few to help guess the code.

func RejectFactor

func RejectFactor(r Reason) error

RejectFactor returns an error that matches ErrFactorRejected and carries r for ReasonOf. Factor packages use it.

func RetryAfter

func RetryAfter(err error) time.Duration

RetryAfter returns how long a throttled caller should wait, or zero if err is not ErrThrottled.

func TokenHash

func TokenHash(raw string) string

TokenHash returns the ath claim value for a token: its base64url SHA-256 hash without padding (RFC 9449, section 4.2).

func WithActor

func WithActor(ctx context.Context, p Principal) context.Context

WithActor returns a copy of ctx that names p as the actor of every change made with it, such as an administrator revoking someone else's session. The service and the factor packages copy the actor into every event they record, in the same transaction as the change.

func WithClient

func WithClient(ctx context.Context, key string) context.Context

WithClient returns a copy of ctx that names the client making the request, for the limiter and the audit log. Use a key that an attacker can't rotate freely, such as the client IP address. The key is cut to 128 bytes of valid UTF-8 without control characters.

func WithKeyProof

func WithKeyProof(ctx context.Context, p KeyProof) context.Context

WithKeyProof returns a copy of ctx carrying p, for Service.Authenticate and the other calls that accept a token. Only code that checked the proof, such as package dpop, should call it.

func WithPrincipal

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

WithPrincipal returns a copy of ctx carrying p.

Types

type Action

type Action struct {
	// Kind names the operation, for example "repo.delete".
	Kind string `json:"kind"`
	// Resource names what it acts on, for example "acme/api".
	Resource string `json:"resource,omitempty"`
	// Params holds the parameters that matter, for example the branch.
	Params map[string]string `json:"params,omitempty"`
	// Summary is what the person reads before approving, for example
	// "Delete the repository acme/api". It is part of the digest, so the
	// text the person approved is the text that was signed.
	Summary string `json:"summary"`
}

Action describes one exact operation an agent asks its human to approve, for Service.RequestApproval. The approval is bound to the action's Action.Digest, so it can't be redeemed for anything else.

func (Action) Digest

func (a Action) Digest() [32]byte

Digest returns the SHA-256 of the action's canonical JSON: its fields in a fixed order and its Params sorted by key.

type Actor

type Actor struct {
	User    UserID
	Agent   AgentID
	Session SessionID
}

Actor is who made a change on someone else's behalf, for example an administrator who revoked a user's session. Events record it in Event.Actor. It's empty when the user, or the library, made the change.

func ActorFrom

func ActorFrom(ctx context.Context) Actor

ActorFrom returns the actor set by WithActor, or the zero Actor.

func (Actor) IsZero

func (a Actor) IsZero() bool

IsZero reports whether a is empty.

type Agent

type Agent struct {
	ID AgentID
	// Owner is the responsible human. It is empty while the agent is
	// unclaimed.
	Owner      UserID
	Name       string
	Scopes     []string // the most any session of this agent may hold
	CreatedAt  time.Time
	DisabledAt time.Time // zero while enabled
	// ClaimedType is the agent type reported at signup, for example
	// "claude-code". It is a self-reported label: don't trust it unless
	// TypeVerified is true.
	ClaimedType string
	// TypeVerified is true only when the [TypeVerifier] accepted an
	// attestation for ClaimedType.
	TypeVerified bool
	// ClaimBy is the claim deadline of an unclaimed agent, after which it
	// is deleted. It is zero for agents created by [Service.CreateAgent].
	ClaimBy time.Time
	// ClaimedAt is when a human claimed the agent, or zero.
	ClaimedAt time.Time
}

Agent is a delegated identity owned by a human. Sessions for it are created with Service.Delegate.

An agent that signed itself up with Service.RegisterAgent has no owner until a human claims it with Service.ClaimAgent.

func (Agent) Unclaimed

func (a Agent) Unclaimed() bool

Unclaimed reports whether the agent signed itself up and no human has claimed it yet.

type AgentFilter

type AgentFilter struct {
	// Owner limits the result to agents this user owns. Empty means every
	// owner.
	Owner UserID
	// Unclaimed limits the result to agents that signed themselves up and
	// that no human has claimed. Don't set it together with Owner.
	Unclaimed bool
	// Disabled limits the result to disabled agents, claimed or not.
	Disabled bool
	// After returns only agents with a greater ID, for paging.
	After AgentID
	// Limit is the most agents to return. Stores may assume 1 to 1,000.
	Limit int
}

AgentFilter selects agents for Store.ListAgents and Service.Agents.

type AgentID

type AgentID string

AgentID identifies an agent registered with Service.CreateAgent.

type AgentSpec

type AgentSpec struct {
	// Name is shown to humans, for example "Claude Code on laptop".
	Name string
	// Scopes is the most any session of this agent may ever hold.
	Scopes []string
}

AgentSpec describes an agent to create.

type Approval

type Approval struct {
	// ID identifies the approval, for example "apr_…". It isn't a secret:
	// only the agent that asked can redeem it, and only for its action.
	ID string
	// User is the human who must approve.
	User UserID
	// Agent and Session are the agent session that asked.
	Agent   AgentID
	Session SessionID
	// Action is what the agent wants to do, and Digest its digest.
	Action Action
	Digest [32]byte
	// State is pending, approved, or denied.
	State ApprovalState
	// ExpiresAt is when the request, or the approval, expires.
	ExpiresAt time.Time
	// Need is what the action requires of a person; the approving human
	// must meet it, with the passkey tap counting as a fresh multi-factor
	// proof.
	Need Need
	// URL is the absolute address of the page where the person reviews
	// the approval, from [WithApprovalURL], or empty without it.
	URL string
}

Approval is a request from an agent for its human to approve one action.

type ApprovalNotifier

type ApprovalNotifier func(ctx context.Context, a Approval, url string) error

ApprovalNotifier tells a person that their agent asked for an approval, for example by email or in a chat channel. a is the new approval and url its page from WithApprovalURL, or empty without it. Send the person the summary and the link; never send anything that grants the approval by itself.

type ApprovalState

type ApprovalState string

ApprovalState says where an approval is.

const (
	ApprovalPending  ApprovalState = "pending"
	ApprovalApproved ApprovalState = "approved"
	ApprovalDenied   ApprovalState = "denied"
)

Approval states.

type Assurance

type Assurance uint8

Assurance says how strongly the human behind a session proved who they are. Levels are ordered: a higher level satisfies every need for a lower one.

const (
	// AssuranceNone is an agent session, a personal access token, or an
	// OAuth token: none of them carries a human proof of its own.
	AssuranceNone Assurance = iota
	// AssuranceRecovering is a human session whose only factor is a
	// recovery code, alone or with a federated sign-in. See
	// [Principal.RecoveryOnly].
	AssuranceRecovering
	// AssuranceSingle is a human session with one factor, such as a
	// federated sign-in, or a session the application started without
	// proofs.
	AssuranceSingle
	// AssuranceMulti is a human session with a passkey, which verifies the
	// user itself, or with TOTP and another factor.
	AssuranceMulti
)

Assurance levels, weakest first.

func (Assurance) MarshalText

func (a Assurance) MarshalText() ([]byte, error)

MarshalText encodes the level as its name.

func (Assurance) String

func (a Assurance) String() string

String returns the level's name: none, recovering, single, or multi.

func (*Assurance) UnmarshalText

func (a *Assurance) UnmarshalText(b []byte) error

UnmarshalText decodes a level from its name.

type Attempt

type Attempt struct {
	// Action names the operation, for example "passkey.finish_login".
	Action string
	// Client is the key the application put in the context with
	// [WithClient], such as an IP address or device ID.
	Client string
	// User is set only once the user is identified, for example for a
	// second factor or a step-up. Attempts before sign-in leave it empty,
	// so throttling can't reveal whether an account exists.
	User UserID
	// Target names what an attempt before sign-in aims at, as an opaque key
	// that doesn't say whether an account exists: for example, a hash of a
	// normalized email address. It is empty for most attempts. An attempt
	// with a Target comes from [Runtime.AllowTarget], after the same
	// attempt passed [Runtime.Allow] for its client, so a limiter should
	// count it against the target only.
	Target string
}

Attempt describes one sign-in or enrolment attempt.

type Caps

type Caps struct {
	// AgentsPerUser caps the enabled agents one human owns, counted on
	// CreateAgent and ClaimAgent. Disabled agents don't count.
	AgentsPerUser int
	// SessionsPerAgent caps the live sessions one agent holds, counted on
	// Delegate.
	SessionsPerAgent int
}

Caps is a ready Quota with two caps. A zero field means no cap.

AgentsPerUser holds under concurrency: when you pass Caps or *Caps itself to WithQuota, the store also counts the owner's agents in the transaction that creates or claims one. SessionsPerAgent is counted before the insert, so concurrent delegations to one agent can pass it together: an agent ends with at most SessionsPerAgent plus the number of concurrent delegations to it, minus one. Caps wrapped in another Quota keeps its checks but loses the transactional count.

func (Caps) Check

func (c Caps) Check(ctx context.Context, r QuotaRequest) error

Check implements Quota.

type Ceremony

type Ceremony struct {
	// ID is the SHA-256 of the ceremony's challenge, so the finish step can
	// find it from the client's response alone.
	ID   [32]byte
	Kind string
	// User is set for ceremonies that start from a known user, such as a
	// registration or a step-up.
	User UserID
	// Binding ties a ceremony to the browser that began it, for example a
	// session ID or an application nonce.
	Binding   string
	Data      []byte
	ExpiresAt time.Time
}

Ceremony is the server-side state of a sign-in or enrolment ceremony between its begin and finish steps.

type ChainHead

type ChainHead struct {
	Pos  int64
	Hash [32]byte
}

ChainHead is the last sealed event: its position and hash. The zero ChainHead is the empty chain.

type ChainLink struct {
	Seq  int64
	Pos  int64
	Hash [32]byte
}

ChainLink seals one event: the event's Seq, and the position and hash it gets.

type Challenge

type Challenge struct {
	// Action names the operation.
	Action string `json:"action"`
	// Assurance is the minimum level the operation needs.
	Assurance Assurance `json:"assurance"`
	// WithinSeconds is how recent the human's proof must be, or 0 for any
	// age.
	WithinSeconds int `json:"within_seconds,omitempty"`
	// Human is true when agents and tokens can't do the operation.
	Human bool `json:"human,omitempty"`
	// Scopes lists the scopes that were missing.
	Scopes []string `json:"scopes,omitempty"`
	// SatisfyWith lists the factors the account has that would meet the
	// need, strongest first. It is empty when none would.
	SatisfyWith []Method `json:"satisfy_with"`
	// Begin is where to start the step-up, when the application set one.
	Begin string `json:"begin,omitempty"`
	// Approval is set when an agent was refused a need its human can meet:
	// the human approves at URL, and the agent retries with the approval's
	// ID in the Tensile-Approval header.
	Approval *ChallengeApproval `json:"approval,omitempty"`
	// Purpose is set when only an elevation for this purpose satisfies the
	// need: step up with [Service.Elevate], not a plain step-up.
	Purpose *Purpose `json:"purpose,omitempty"`
}

Challenge says what would turn a refused request into a success: the need that failed, and the factors this account has that would meet it.

type ChallengeApproval

type ChallengeApproval struct {
	ID string `json:"id"`
	// URL is the page where the person approves: absolute when the
	// application configured one.
	URL              string `json:"url,omitempty"`
	Summary          string `json:"summary"`
	ExpiresInSeconds int    `json:"expires_in"`
	// WaitHint is the Prefer header value (RFC 7240) to send with the
	// retry so the server holds it until the person decides, for example
	// "wait=60".
	WaitHint string `json:"wait_hint,omitempty"`
}

ChallengeApproval is the approval an agent can wait for instead of stopping at a refusal.

type Checkpoint

type Checkpoint struct {
	Head      ChainHead
	At        time.Time
	Signature []byte
}

Checkpoint is a signed chain head.

func (*Checkpoint) Verify

func (cp *Checkpoint) Verify(pub ed25519.PublicKey) bool

Verify reports whether cp was signed by the holder of pub.

type Claim

type Claim struct {
	Owner  UserID
	Scopes []string
	At     time.Time
	// MaxOwned, when positive, caps the enabled agents Owner may own after
	// the claim, as maxOwned does for [Store.InsertAgent].
	MaxOwned int
}

Claim describes a claim for SignupStore.ClaimAgent.

type ClaimPreview

type ClaimPreview struct {
	// Agent is the unclaimed agent: its name, the type it reports, whether
	// that type was verified, when it signed up, and its claim deadline.
	Agent Agent
	// Words are four pairing words derived from the claim code. The agent
	// prints the same words with [PairingWords]; the person checks that
	// they match before claiming, so a claim code phished from someone
	// else's terminal shows different words.
	Words [4]string
}

ClaimPreview is what a person sees before claiming an agent, from Service.PeekClaim.

type ClaimSpec

type ClaimSpec struct {
	// Scopes becomes the agent's scopes and its new session's scopes. The
	// claimer must hold all of them.
	Scopes []string
	// TTL is the new session's lifetime, as in [DelegateSpec].
	TTL time.Duration
	// KeyThumbprint binds the new session to the agent's public key, as in
	// [DelegateSpec]. Empty means an unbound session: the claimer's own
	// binding is never passed on, because the claimer doesn't hold the
	// agent's key. It is required under [RequireAgentKeys]. The agent can
	// report it with its claim code.
	KeyThumbprint string
}

ClaimSpec says what a claimed agent may do.

type ClientRegistration

type ClientRegistration struct {
	Client          string
	Name            string
	ApplicationType string
	RedirectURIs    []string
}

ClientRegistration describes a client that registered itself.

type Connection

type Connection struct {
	// ID is the grant's root session: its refresh token's session, or
	// the access token's for a client without refresh tokens. Revoke the
	// connection with [Service.RevokeConnection].
	ID SessionID
	// Client is the OAuth client ID.
	Client string
	// Resource is what the tokens are for.
	Resource string
	// Scopes the grant holds.
	Scopes []string
	// CreatedAt is when the human approved it.
	CreatedAt time.Time
	// LastUsedAt is the latest use of any token in the grant.
	LastUsedAt time.Time
	// ExpiresAt is when the grant ends at the latest.
	ExpiresAt time.Time
}

Connection is an OAuth grant for a resource, such as one MCP client connected to one MCP server for one user. Each grant is its own connection, even when many share a client ID, as every install of a client with a metadata document does.

type Consent struct {
	// Client is the OAuth client ID. Required.
	Client string
	// ClientKind says where the client came from, for example
	// "metadata_document".
	ClientKind string
	// RedirectURI is where the approval goes.
	RedirectURI string
	// Resource is the resource (RFC 8707) the tokens are for, or empty.
	Resource string
	// Scopes the approval grants.
	Scopes []string
}

Consent is what a human approved on an OAuth consent page.

type Counts

type Counts struct {
	// Users who have a stored session or own an agent.
	Users int
	// LiveSessions aren't revoked and haven't reached their ExpiresAt.
	LiveSessions int
	// ActiveAgents are claimed or created by a user, and not disabled.
	ActiveAgents int
	// UnclaimedAgents signed themselves up, aren't claimed, and aren't
	// disabled.
	UnclaimedAgents int
	// DisabledAgents are disabled, claimed or not.
	DisabledAgents int
	// EventsSince is the number of audit events since the time passed.
	EventsSince int
}

Counts are totals for an admin overview, from Store.Counts.

type CredentialRecord

type CredentialRecord struct {
	ID             []byte
	User           UserID
	Name           string
	SignCount      uint32
	BackupEligible bool
	BackupState    bool
	PRF            bool
	CreatedAt      time.Time
	LastUsedAt     time.Time
	CloneWarnedAt  time.Time // zero unless a sign-count regression was seen
	Data           []byte
}

CredentialRecord is the stored form of a passkey credential. Only the fields the library queries are columns; Data holds the rest as the passkey package encodes it.

type DelegateSpec

type DelegateSpec struct {
	// Name labels the token for people, for example "Claude Code, task
	// 14", at most 128 bytes. It appears as SessionInfo.Name on the
	// session tree. Empty means no label.
	Name string
	// Agent the new session belongs to. Required when the parent is a human
	// session, and must be owned by the parent's user. When the parent is an
	// agent session it must be empty or the parent's own agent: an agent can
	// delegate to sub-sessions of itself, never to a different agent.
	Agent AgentID
	// Scopes for the new session. They must be held by both the parent and
	// the agent.
	Scopes []string
	// TTL is the requested lifetime. Zero means Policy.AgentMax, cut short
	// to the parent's expiry. A non-zero TTL that exceeds either fails with
	// ErrExpiryExceeded.
	TTL time.Duration
	// KeyThumbprint binds the new session to the agent's public key: its
	// RFC 7638 JWK SHA-256 thumbprint, base64url-encoded without padding
	// (43 characters), as the jkt confirmation of RFC 9449. A bound token
	// works only with a proof of possession of the key. See [KeyProof].
	//
	// Empty means the parent's binding: a session delegated from a bound
	// session is always bound, to the parent's key or to its own. An
	// unbound parent produces an unbound session, unless the service was
	// created with [RequireAgentKeys], which refuses it.
	KeyThumbprint string
}

DelegateSpec describes a session to delegate.

type DeviceBinding

type DeviceBinding struct {
	// ID is the DBSC session identifier the browser sends back on refresh.
	// It isn't a secret: refreshing needs the key.
	ID string
	// Session is the bound session.
	Session SessionID
	// User is its user.
	User UserID
}

DeviceBinding is a session bound to a browser's key.

type DeviceCode

type DeviceCode struct {
	DeviceHash [32]byte
	UserHash   [32]byte
	// Client is the OAuth client that asked.
	Client string
	// Scopes the client asked for.
	Scopes []string
	// Requester is the client key of the device that asked, set with
	// [WithClient], to show on the approval page.
	Requester    string
	CreatedAt    time.Time
	ExpiresAt    time.Time
	Interval     time.Duration
	LastPolledAt time.Time // zero before the first poll
	State        DeviceState

	// The decision, set once State isn't DevicePending.
	DecidedAt time.Time
	// User and Session are the human and the session that decided.
	User    UserID
	Session SessionID
	// Granted, AuthenticatedAt, and Methods are the approving session's,
	// for the tokens issued when the device next polls.
	Granted         []string
	AuthenticatedAt time.Time
	Methods         []Method
}

DeviceCode is the stored form of an OAuth device authorization request. Only hashes of the device code and the user code are stored.

type DeviceDecision

type DeviceDecision struct {
	State           DeviceState // DeviceApproved or DeviceDenied
	At              time.Time
	User            UserID
	Session         SessionID
	Granted         []string
	AuthenticatedAt time.Time
	Methods         []Method
}

DeviceDecision is a human's decision on a device code, for DeviceStore.DecideDeviceCode.

type DeviceState

type DeviceState uint8

DeviceState is the state of a device code.

const (
	DevicePending DeviceState = iota + 1
	DeviceApproved
	DeviceDenied
)

Device code states.

type DeviceStore

type DeviceStore interface {
	// InsertDeviceCode stores a new, pending device code.
	InsertDeviceCode(ctx context.Context, d DeviceCode) error

	// DeviceByUserCode returns the device code whose user code hashes to
	// userHash, or ErrNotFound when there is none or it expired at now.
	DeviceByUserCode(ctx context.Context, userHash [32]byte, now time.Time) (DeviceCode, error)

	// DecideDeviceCode records the human's decision on a pending device
	// code that hasn't expired at d.At, and appends ev in the same
	// transaction. It returns ErrNotFound when the code is missing or
	// expired, and ErrConflict when it was already decided.
	DecideDeviceCode(ctx context.Context, userHash [32]byte, d DeviceDecision, ev Event) error

	// PollDeviceCode records a poll from the device at now and returns the
	// code, with LastPolledAt set to the previous poll. When the code is
	// approved or denied, the same operation deletes it, so the decision
	// is returned to at most one poll. It returns ErrNotFound when the
	// code is missing or expired at now, and deletes an expired code.
	PollDeviceCode(ctx context.Context, deviceHash [32]byte, now time.Time) (DeviceCode, error)

	// DeleteExpiredDeviceCodes deletes codes that expired before the given
	// time and returns how many were deleted.
	DeleteExpiredDeviceCodes(ctx context.Context, before time.Time) (int, error)
}

DeviceStore persists OAuth device codes (RFC 8628) between the request on the device and the human's decision in a browser. The oauth package uses it. Implementations must make each method atomic, and must pass storetest.RunDevices.

type EmailClaim

type EmailClaim struct {
	Record EmailRecord
	// Hash, when not empty, becomes Record.User's password.
	Hash string
	// At is the ChangedAt of that password.
	At time.Time
	// First makes the claim fail when the user has any sign-in method.
	First bool
	// Replace lets the claim replace the user's other address.
	Replace bool
	// Events are appended when the claim succeeds.
	Events []Event
	// Released is appended, with User set to the evicted user, when the
	// claim evicts an unverified holder.
	Released Event
}

EmailClaim is the input to EmailStore.ClaimEmail.

type EmailRecord

type EmailRecord struct {
	// Key is the normalized address, unique across users.
	Key string
	// Address is the address as the person entered it, for delivery.
	Address string
	// User holds the address. A user has at most one address.
	User      UserID
	CreatedAt time.Time
	// VerifiedAt is when the holder proved control of the mailbox, or zero.
	VerifiedAt time.Time
}

EmailRecord is the stored form of a user's email address.

func (EmailRecord) Verified

func (r EmailRecord) Verified() bool

Verified reports whether the address is confirmed.

type EmailStore

type EmailStore interface {
	// ClaimEmail gives c.Record.Key to c.Record.User. The checks run in
	// this order.
	//
	//  1. First: when c.First is set, it fails with ErrFactorExists if the
	//     user has an address, a password, an identity, a passkey
	//     credential, a recovery code, or a TOTP factor.
	//  2. Holder: when another user holds the key verified, it fails with
	//     ErrFactorExists. When another user holds it unverified, it fails
	//     with ErrFactorExists if c.Record.VerifiedAt is zero; otherwise it
	//     deletes that user's address and password and appends c.Released
	//     with User set to that user. When c.Record.User holds the key
	//     already, it updates Address, and sets VerifiedAt if
	//     c.Record.VerifiedAt is set and the stored one is zero.
	//  3. Own address: when c.Record.User holds another address, it
	//     deletes it if c.Replace is set, and fails with ErrFactorExists
	//     otherwise. The password stays.
	//  4. Write: it inserts the row; when c.Hash isn't empty, it sets the
	//     password to c.Hash with Version one more than before, or 1, and
	//     ChangedAt set to c.At; then it appends c.Events.
	ClaimEmail(ctx context.Context, c EmailClaim) error

	// EmailByUser returns u's address, or ErrNotFound.
	EmailByUser(ctx context.Context, u UserID) (EmailRecord, error)

	// PasswordByEmail returns the address with the given key and its
	// user's password, in one statement. It returns ErrNotFound when no
	// user holds the key, and a zero PasswordRecord when the user has no
	// password.
	PasswordByEmail(ctx context.Context, key string) (EmailRecord, PasswordRecord, error)

	// Password returns u's password record, or ErrNotFound.
	Password(ctx context.Context, u UserID) (PasswordRecord, error)

	// VerifyEmail sets VerifiedAt to at and appends ev, only when u holds
	// key unverified. It returns nil without an event when the address is
	// verified already, and ErrNotFound when u doesn't hold key. No method
	// clears VerifiedAt.
	VerifyEmail(ctx context.Context, u UserID, key string, at time.Time, ev Event) error

	// SetPassword sets set.User's password by compare-and-set on Version.
	// When set.Want is 0, the user must have no password, and the password
	// gets Version 1. Otherwise the stored Version must equal set.Want,
	// and becomes set.Want+1. A mismatch returns ErrConflict. When the user
	// has no address, or set.Key is set and the user doesn't hold it with
	// VerifiedAt set, it returns ErrNotFound.
	SetPassword(ctx context.Context, set PasswordSet, ev Event) error

	// RehashPassword replaces u's hash only when the stored hash equals
	// old; otherwise it returns ErrConflict, or ErrNotFound when u has no
	// password. Version and ChangedAt don't change. It isn't audited: the
	// password didn't change.
	RehashPassword(ctx context.Context, u UserID, old, hash string) error

	// DeletePassword deletes u's password and keeps the address. It
	// returns ErrNotFound when there is none.
	DeletePassword(ctx context.Context, u UserID, ev Event) error

	// DeleteEmail deletes u's address and password. It returns
	// ErrNotFound when u has no address.
	DeleteEmail(ctx context.Context, u UserID, ev Event) error
}

EmailStore persists the email address each user signs in with, and the user's password hash. The password package uses it. The library still owns no users: it stores only which address signs in as which user. An address belongs to at most one user, a user has at most one address, and a password exists only for a user with an address.

Implementations must make each method one atomic statement or transaction, append its events in the same transaction, append nothing when it fails, and pass storetest.RunEmails.

type Event

type Event struct {
	// Seq orders events in the audit log. The store assigns it, so it is
	// set only on events read back with [Service.Events]. On Postgres,
	// concurrent transactions can commit out of Seq order, so a reader that
	// pages with EventFilter.AfterSeq can miss an event that commits late:
	// use Seq for display and paging, not for exactly-once processing.
	Seq     int64
	Kind    EventKind
	At      time.Time
	User    UserID
	Agent   AgentID
	Session SessionID
	Parent  SessionID
	// Count is the number of sessions affected, for revocations. For a
	// failure event, it's the number of attempts the event stands for: 1,
	// or more for a summary.
	Count int
	// Factor identifies the credential or factor involved, if any.
	Factor string
	// Methods lists the methods a session was started or stepped up with.
	Methods []Method
	// Action names the attempted operation for failure events, for example
	// "passkey.finish_login" or "GET /repos".
	Action string
	// Reason says why an attempt failed. It's empty for changes.
	Reason Reason
	// Client is the key the application set with [WithClient], such as an
	// IP address, or empty.
	Client string
	// Source is where a leaked token was found, for token_leaked events:
	// the URL the secret scanner reported, or the kind of place when it
	// gave none. It's cut to 512 bytes of valid UTF-8 without control
	// characters. Display it as text, never as a link that you follow
	// automatically.
	Source string
	// Until is set only on summaries of failed attempts: the time of the
	// last attempt counted. At is the first.
	Until time.Time
	// Detail carries structured data for some kinds, as JSON: for
	// signup_settings_changed, the new override. It's empty for most.
	Detail string
	// Pos is the event's position in the audit hash chain, or 0 until it
	// is sealed. See [Service.SealAudit].
	Pos int64
	// Hash is the event's chain hash, set once it is sealed.
	Hash [32]byte
	// Actor is who made the change on someone else's behalf, set with
	// [WithActor], or empty.
	Actor Actor
}

Event describes a completed change. It never contains a token.

type EventFilter

type EventFilter struct {
	// User limits the result to events about this user. Empty means every
	// user.
	User UserID
	// AfterSeq returns only events with a larger Seq, for paging.
	AfterSeq int64
	// Kinds limits the result to these kinds. Empty means every kind.
	Kinds []EventKind
	// Agent limits the result to events about this agent. Empty means
	// every agent.
	Agent AgentID
	// Actor limits the result to events whose Actor.User is this user.
	// Empty means every event, with or without an actor.
	Actor UserID
	// BeforeSeq, when positive, returns only events with a smaller Seq,
	// for paging with Descending.
	BeforeSeq int64
	// Descending returns the newest events first.
	Descending bool
	// Limit is the most events to return. Stores may assume 1 to 1,000.
	Limit int
}

EventFilter selects audit events for Store.ListEvents and Service.Events.

type EventKind

type EventKind string

EventKind names something that happened to a session or agent.

const (
	EventApprovalRequested EventKind = "approval_requested"
	// EventApprovalGranted's Detail holds the [Receipt] as JSON.
	EventApprovalGranted  EventKind = "approval_granted"
	EventApprovalDenied   EventKind = "approval_denied"
	EventApprovalRedeemed EventKind = "approval_redeemed"
)

Audit event kinds for approvals. Every one carries the agent, its session, the approval's ID as Factor, and the action's summary as Detail.

const (
	EventDeviceApproved EventKind = "device_approved"
	EventDeviceDenied   EventKind = "device_denied"
)

Audit event kinds for device codes. Session is the human session that decided, and Factor the OAuth client.

const (
	EventDeviceBound     EventKind = "device_bound"
	EventDeviceRefreshed EventKind = "device_refreshed"
	EventDeviceUnbound   EventKind = "device_unbound"
)

EventDeviceBound records a session bound to a browser key, EventDeviceRefreshed a token reissued after a proof of that key, and EventDeviceUnbound a binding ended after a proof of that key, when DBSC was turned off.

const (
	// EventEmailAdded is an address a user didn't have before.
	EventEmailAdded EventKind = "email_added"
	// EventEmailVerified is an address confirmed by its mailbox.
	EventEmailVerified EventKind = "email_verified"
	// EventEmailChanged is an address that replaced the user's old one.
	EventEmailChanged EventKind = "email_changed"
	// EventEmailReleased is an unverified address taken from its holder by
	// a verified claim. User is the evicted user.
	EventEmailReleased EventKind = "email_released"
	// EventEmailRemoved is an address deleted with its password.
	EventEmailRemoved EventKind = "email_removed"
	// EventPasswordSet is a user's first password.
	EventPasswordSet EventKind = "password_set"
	// EventPasswordChanged is a password changed by its user.
	EventPasswordChanged EventKind = "password_changed"
	// EventPasswordReset is a password set with a reset code.
	EventPasswordReset EventKind = "password_reset"
	// EventPasswordInvalidated is a password an administrator invalidated.
	EventPasswordInvalidated EventKind = "password_invalidated"
	// EventPasswordRemoved is a password deleted, by its user or by
	// [Service.UndoRecovery].
	EventPasswordRemoved EventKind = "password_removed"
	// EventPasswordResetRequested is a reset code sent to a known account.
	// It describes no change, so it is recorded with [Store.RecordEvent].
	EventPasswordResetRequested EventKind = "password_reset_requested"
	// EventEmailChangeRequested is a confirmation code sent to a new
	// address. It describes no change.
	EventEmailChangeRequested EventKind = "email_change_requested"
)

Audit event kinds for addresses and passwords. Stores append them in the same transaction as the change. Factor holds an address label from Service.EmailLabel, or "password"; no event holds an address, a password, a hash, or a code.

const (
	EventSessionStarted   EventKind = "session_started"
	EventSessionDelegated EventKind = "session_delegated"
	EventSessionRotated   EventKind = "session_rotated"
	EventSessionRevoked   EventKind = "session_revoked"
	EventUserRevoked      EventKind = "user_revoked"
	EventAgentCreated     EventKind = "agent_created"
	EventAgentRevoked     EventKind = "agent_revoked"
	EventTokenReused      EventKind = "token_reused"
	EventSessionSteppedUp EventKind = "session_stepped_up"
	// EventAgentRegistered is an agent that signed itself up.
	EventAgentRegistered EventKind = "agent_registered"
	// EventAgentClaimed is a human claiming an agent. Count is the number
	// of sandbox sessions revoked.
	EventAgentClaimed EventKind = "agent_claimed"
	// EventAgentExpired is an unclaimed agent deleted at its claim
	// deadline. Count is the number of sessions deleted with it.
	EventAgentExpired EventKind = "agent_expired"
	// EventTokenLeaked is a token that a secret scanner found in public.
	// The service revoked the token's session and every session delegated
	// from it; Count is how many were newly revoked, and Source says where
	// the token was found.
	EventTokenLeaked EventKind = "token_leaked"
)

Event kinds passed to the observer.

const (
	// EventFactorRejected is a passkey, recovery code, TOTP code, or
	// registration that didn't verify, or a signed request, such as a
	// secret-scanning alert, whose signature didn't. Reason says why.
	EventFactorRejected EventKind = "factor_rejected"
	// EventAttemptThrottled is an attempt the limiter delayed.
	EventAttemptThrottled EventKind = "attempt_throttled"
	// EventTokenRejected is a request with a session token that didn't
	// authenticate. Reason says why.
	EventTokenRejected EventKind = "token_rejected"
	// EventAccessDenied is an authenticated request or delegation that
	// lacked a permission. Reason says which.
	EventAccessDenied EventKind = "access_denied"
	// EventFailuresSkipped is a summary of failed attempts of mixed kinds:
	// those against one user, when more keys skipped attempts than
	// FailureLimits.Summaries, or those of anyone, beyond that or once
	// FailureLimits.Keys is reached. Reason is [ReasonMerged] when a store
	// outage forced summaries together.
	EventFailuresSkipped EventKind = "failures_skipped"
)

Event kinds for failed attempts. They describe no change, so the service records them with Store.RecordEvent, and passes every attempt to the observer. To bound what an attacker can write to the store, it writes events only within FailureLimits and counts the other attempts in summaries: events with Until set that stand for Count attempts between At and Until. Action and Client are cut to 128 bytes.

const (
	EventPasskeyAdded          EventKind = "passkey_added"
	EventPasskeyRenamed        EventKind = "passkey_renamed"
	EventPasskeyRemoved        EventKind = "passkey_removed"
	EventPasskeyCloneSuspected EventKind = "passkey_clone_suspected" //nolint:gosec // G101: an event name, not a credential
	EventPasskeyBackupChanged  EventKind = "passkey_backup_changed"
	EventFactorsDeleted        EventKind = "factors_deleted"
	EventRecoveryCodesCreated  EventKind = "recovery_codes_generated"
	EventRecoveryCodeUsed      EventKind = "recovery_code_used"
	EventTOTPEnrolled          EventKind = "totp_enrolled"
	EventTOTPRemoved           EventKind = "totp_removed"
	EventTOTPLocked            EventKind = "totp_locked"
)

Audit event kinds for factors.

const (
	// EventOAuthGranted records a new OAuth grant: a refresh token, or a
	// lone access token for a client that gets no refresh token. Parent is
	// the human session that approved it.
	EventOAuthGranted EventKind = "oauth_granted"
	// EventOAuthTokenIssued records an access token issued under a
	// refresh token. Parent is the refresh token's session.
	EventOAuthTokenIssued EventKind = "oauth_token_issued" //nolint:gosec // G101: an event name, not a credential
)

Audit event kinds for OAuth grants. Each names the OAuth client in Factor.

const (
	// EventIdentityLinked is an external identity linked to a user, by a
	// signed-in user or by an application's sign-up hook.
	EventIdentityLinked EventKind = "identity_linked"
	// EventIdentityUnlinked is an external identity removed from a user.
	EventIdentityUnlinked EventKind = "identity_unlinked"
)

Audit event kinds for external identities. Factor names the identity without its subject; see the federation package.

const (
	EventExportStarted EventKind = "export_started"
	EventUsersExported EventKind = "users_exported"
	EventUsersImported EventKind = "users_imported"
)

Audit event kinds for export and import. An export records EventExportStarted before it writes the first byte and EventUsersExported after the last; an import records EventUsersImported in the same transaction as the rows. Count is the number of users.

const EventOAuthClientRegistered EventKind = "oauth_client_registered"

EventOAuthClientRegistered records a dynamic client registration (RFC 7591). Factor names the new client; Detail holds its name, application type, and redirect URIs as JSON.

const EventOAuthConsented EventKind = "oauth_consented"

EventOAuthConsented records that a human approved an OAuth client's authorization request on the consent page. Factor names the client; Detail holds the client kind, redirect URI, resource, and granted scopes as JSON.

const EventPATCreated EventKind = "pat_created"

EventPATCreated records a new personal access token. Parent is the session that created it.

const EventRecoveryCodesConfirmed EventKind = "recovery_codes_confirmed"

EventRecoveryCodesConfirmed records that a person typed back one of their unused recovery codes, which proves they saved the set. A later EventRecoveryCodesCreated voids it.

const EventRecoveryUndone EventKind = "recovery_undone"

EventRecoveryUndone records Service.UndoRecovery. Session is the recovered session, and Detail holds the UndoResult as JSON. The account's remaining recovery codes are deleted in the same transaction.

const EventSessionElevated EventKind = "session_elevated"

EventSessionElevated records Service.Elevate. Detail holds the purpose as JSON.

const EventSignupSettingsChanged EventKind = "signup_settings_changed"

EventSignupSettingsChanged is an admin changing the signup override. Count is the new version, Detail the override as JSON, and Actor who changed it.

const EventToolCalled EventKind = "tool_called"

EventToolCalled records one call of an MCP tool, allowed or refused. Session is the access token's session, Parent the grant, Factor the client, Action the tool, and Reason scope_missing for a refusal; Detail holds the resource, the decision, and the SHA-256 of the arguments as JSON.

type FactorStore

type FactorStore interface {
	// PutCeremony stores the state of a ceremony that has begun. It returns
	// ErrConflict, and changes nothing, when a ceremony with c.ID exists,
	// even an expired one that hasn't been deleted yet: callers rely on it
	// as an atomic insert-if-absent.
	PutCeremony(ctx context.Context, c Ceremony) error

	// ConsumeCeremony deletes the ceremony with the given ID and one of
	// kinds, and returns it, in one operation, so a ceremony can be
	// finished at most once. It returns ErrNotFound when the ceremony is
	// missing, of another kind, or expired at now; an expired ceremony of
	// the right kind is deleted too, and a ceremony of another kind is
	// never touched, so a lookup in one flow can't destroy another's state.
	// kinds must not be empty.
	ConsumeCeremony(ctx context.Context, id [32]byte, now time.Time, kinds ...string) (Ceremony, error)

	// CeremonyByID returns the ceremony with id without consuming it, or
	// [ErrNotFound] when there is none or it expired at or before now.
	CeremonyByID(ctx context.Context, id [32]byte, now time.Time) (Ceremony, error)

	// UserHandle returns u's passkey user handle, storing fresh as the
	// handle when u has none yet. When fresh is nil, it only reads: it
	// returns ErrNotFound when u has no handle and stores nothing.
	UserHandle(ctx context.Context, u UserID, fresh []byte) ([]byte, error)

	// UserByHandle returns the user with handle h, or ErrNotFound.
	UserByHandle(ctx context.Context, h []byte) (UserID, error)

	// InsertCredential stores a new passkey credential. It fails with
	// ErrFactorExists when the credential ID is already registered, or,
	// when first is true, when the user already has a passkey, recovery
	// codes, or a TOTP factor; that check is atomic with the insert. A
	// linked external identity, an address, and a password don't count, so
	// an account that signs in only through a provider or with a password
	// can add its first passkey.
	InsertCredential(ctx context.Context, c CredentialRecord, first bool, ev Event) error

	// CredentialByID returns the credential with the given ID, or
	// ErrNotFound.
	CredentialByID(ctx context.Context, id []byte) (CredentialRecord, error)

	// ListCredentials returns u's credentials, oldest first.
	ListCredentials(ctx context.Context, u UserID) ([]CredentialRecord, error)

	// UpdateCredentialUse replaces the credential's sign count, backup
	// state, last use, clone warning, and data with those of c, but only
	// if its sign count still equals prevCount (compare-and-swap);
	// otherwise it returns ErrConflict. It records ev when ev is non-nil.
	UpdateCredentialUse(ctx context.Context, id []byte, prevCount uint32, c CredentialRecord, ev *Event) error

	// DeleteCredential deletes u's credential with the given ID, or
	// returns ErrNotFound.
	DeleteCredential(ctx context.Context, u UserID, id []byte, ev Event) error

	// RenameCredential sets the name of u's credential id and appends ev
	// in the same transaction, or returns ErrNotFound when u has no such
	// credential.
	RenameCredential(ctx context.Context, u UserID, id []byte, name string, ev Event) error

	// ReplaceRecoveryCodes replaces u's recovery codes with the given
	// hashes, deleting the old set in the same transaction.
	ReplaceRecoveryCodes(ctx context.Context, u UserID, hashes [][32]byte, ev Event) error

	// ConsumeRecoveryCode deletes the recovery code with hash h in one
	// operation, so a code works at most once, and returns its user and how
	// many codes the user has left. It returns ErrNotFound for an unknown
	// or used code. The stored event gets User set to the code's user.
	ConsumeRecoveryCode(ctx context.Context, h [32]byte, ev Event) (UserID, int, error)

	// RecoveryCodeOwner returns the user whose unused recovery code has
	// hash h, without spending it, or [ErrNotFound].
	RecoveryCodeOwner(ctx context.Context, h [32]byte) (UserID, error)

	// CountRecoveryCodes returns how many unused recovery codes u has.
	CountRecoveryCodes(ctx context.Context, u UserID) (int, error)

	// PutTOTP stores u's TOTP factor, replacing an existing one only if it
	// is unconfirmed or locked; otherwise it returns ErrFactorExists.
	PutTOTP(ctx context.Context, f TOTPRecord) error

	// TOTP returns u's TOTP factor, or ErrNotFound.
	TOTP(ctx context.Context, u UserID) (TOTPRecord, error)

	// AdvanceTOTP records that a code for step was accepted: it sets
	// LastStep to step, resets Failures, sets ConfirmedAt to at if unset,
	// and replaces Sealed when sealed is non-nil. It does so only if step is
	// greater than LastStep and the factor isn't locked (compare-and-set);
	// otherwise it returns ErrConflict, or ErrNotFound when there is no
	// factor. It records ev when ev is non-nil.
	AdvanceTOTP(ctx context.Context, u UserID, step int64, at time.Time, sealed []byte, ev *Event) error

	// FailTOTP counts a failed code and locks the factor at the given time
	// once Failures reaches limit, in one operation. It records lockEv only
	// when this call locks the factor, and returns the new failure count
	// and whether the factor is locked.
	FailTOTP(ctx context.Context, u UserID, limit int, at time.Time, lockEv Event) (failures int, locked bool, err error)

	// DeleteTOTP deletes u's TOTP factor, or returns ErrNotFound.
	DeleteTOTP(ctx context.Context, u UserID, ev Event) error

	// DeleteUserFactors deletes every factor of u and its user handle, for
	// account erasure, u's external identities when the store is also an
	// [IdentityStore], and u's address and password when the store is also
	// an [EmailStore]. Audit events are kept.
	DeleteUserFactors(ctx context.Context, u UserID, ev Event) error

	// DeleteExpiredCeremonies deletes ceremonies that expired before the
	// given time and returns how many were deleted.
	DeleteExpiredCeremonies(ctx context.Context, before time.Time) (int, error)
}

FactorStore persists sign-in factors: ceremony state, passkey user handles and credentials, recovery codes, and TOTP factors. Factor packages use it; services that only check tokens don't need it. Implementations must make each method atomic, and must pass storetest.RunFactors.

Methods that take an Event append it to the audit log in the same transaction, as Store methods do.

type FailureLimits

type FailureLimits struct {
	// Window is the period the limits apply to.
	Window time.Duration
	// PerKey is how many events one kind of failure with one reason, from
	// one client, against one user, writes in a window.
	PerKey int
	// Total is how many events each budget writes in a window.
	Total int
	// Keys caps the keys each budget tracks in a window, so a client that
	// rotates its key can't grow memory without bound. Attempts with a new
	// key beyond it are counted in a failures_skipped event.
	Keys int
	// Summaries caps the summaries of each kind written when a window
	// ends: per-key summaries for both budgets, then per-user summaries for
	// the remaining attributed keys. Attempts beyond them are counted in a
	// failures_skipped event.
	Summaries int
	// UnlimitedPerUser removes PerKey for failures tied to a user or
	// session, so each one writes its own event until Total is reached.
	// An attacker who can fail as a known user, for example with a stolen
	// expired token, can then use the whole attributed budget alone.
	UnlimitedPerUser bool
}

FailureLimits bounds the failure events a Service writes to the store. Failed attempts come from anyone, including clients that never signed in, so one row per attempt would let an attacker write to the database as fast as they can send requests.

Within the limits, every attempt is its own event. Beyond them, attempts are counted in summary events, so the store still has how many, from where, against whom, and when. The observer always receives every attempt.

Failures tied to a user or session, and anonymous ones, have separate budgets, so a flood of anonymous attempts can't hide failures against a known account.

func DefaultFailureLimits

func DefaultFailureLimits() FailureLimits

DefaultFailureLimits returns the defaults: 10 events per key and 1,000 per budget each minute, 10,000 keys, and 1,000 summaries of each kind.

type Grant

type Grant struct {
	// Access authenticates requests. It is a SessionOAuth token.
	Access Token
	// Refresh obtains new access tokens. It is zero unless a refresh token
	// was issued.
	Refresh Token
	// Principal is the access token's principal.
	Principal Principal
}

Grant holds the tokens issued to an OAuth client.

type GrantSpec

type GrantSpec struct {
	// Client is the OAuth client ID. Required.
	Client string
	// Scopes the tokens hold. They must be a subset of the owner's, or of
	// the refresh token's on refresh. Empty on refresh means all of the
	// refresh token's scopes.
	Scopes []string
	// AccessTTL is the access token's lifetime. Zero means
	// [DefaultAccessTTL] with a refresh token and Policy.OAuthMax without
	// one. It can't exceed Policy.OAuthMax.
	AccessTTL time.Duration
	// Refresh also issues a refresh token, which [Service.RefreshGrant]
	// exchanges for new access tokens. Ignored on refresh.
	Refresh bool
	// Resource is the resource (RFC 8707) the tokens are for, such as an
	// MCP server's canonical URI, at most 512 bytes. Every token of the
	// grant carries it as Principal.Resource, for its whole life. Empty
	// means a token without an audience. On refresh, empty keeps the
	// grant's resource, and any other value must equal it.
	Resource string
}

GrantSpec describes the tokens to issue to an OAuth client.

type HashMatch

type HashMatch uint8

HashMatch says which of a session's token hashes matched a lookup.

const (
	MatchCurrent HashMatch = iota + 1
	MatchPrevious
	MatchRetired
)

Hash match results.

type IdentityRecord

type IdentityRecord struct {
	// Issuer identifies the identity provider, for example
	// "https://accounts.google.com" or "https://github.com".
	Issuer string
	// Subject is the provider's stable identifier for the account, unique
	// within the issuer.
	Subject    string
	User       UserID
	CreatedAt  time.Time
	LastUsedAt time.Time
}

IdentityRecord is the stored form of an external identity linked to a user. It holds no email address, name, or token from the provider.

type IdentityStore

type IdentityStore interface {
	// InsertIdentity links the identity r to r.User and appends ev in the
	// same transaction. It fails with ErrFactorExists when an identity with
	// the same issuer and subject is linked to any user, or, when first is
	// true, when r.User already has an identity, a passkey credential, a
	// recovery code, a TOTP factor, or an email address; that check is
	// atomic with the insert. So a sign-up hook can never attach an
	// identity to an account found by its email address.
	InsertIdentity(ctx context.Context, r IdentityRecord, first bool, ev Event) error

	// IdentityByKey returns the identity with the given issuer and subject,
	// or ErrNotFound.
	IdentityByKey(ctx context.Context, issuer, subject string) (IdentityRecord, error)

	// ListIdentities returns u's identities, oldest first.
	ListIdentities(ctx context.Context, u UserID) ([]IdentityRecord, error)

	// TouchIdentity records that the identity was used to sign in at at. It
	// never moves LastUsedAt backwards, and returns ErrNotFound for an
	// unknown identity. It is not audited: the session it starts is.
	TouchIdentity(ctx context.Context, issuer, subject string, at time.Time) error

	// DeleteIdentity unlinks u's identity with the given issuer and subject
	// and appends ev in the same transaction. It returns ErrNotFound when
	// the identity doesn't exist or belongs to another user.
	DeleteIdentity(ctx context.Context, u UserID, issuer, subject string, ev Event) error
}

IdentityStore persists external identities: accounts at identity providers, such as Google or GitHub, linked to users. The federation package uses it. Implementations must make each method atomic, record events in the same transaction as the change, and pass storetest.RunIdentities.

An identity is keyed by its issuer and subject, never by an email address, and belongs to at most one user.

type Import

type Import struct {
	Users  []UserExport
	Agents []Agent
	// Merge skips conflicting records instead of refusing the import, and
	// allows a store that isn't empty.
	Merge bool
}

Import is what TransferStore.ImportUsers stores. Every record's User must equal its UserExport's User, and every agent's Owner must be set.

type ImportConflict

type ImportConflict struct {
	// User is the user skipped, or empty for an agent.
	User UserID
	// Agent is the agent skipped, or empty for a user.
	Agent AgentID
	// Record names what exists already: one of the Conflict constants.
	Record string
}

ImportConflict is a record that TransferStore.ImportUsers didn't store because one with the same key exists.

type ImportResult

type ImportResult struct {
	// Users and Agents count what was stored.
	Users, Agents int
	// Skipped lists each conflict, in the order of the import: with Merge,
	// the records skipped; without it, the conflicts that refused the
	// import.
	Skipped []ImportConflict
}

ImportResult says what TransferStore.ImportUsers stored and skipped.

type KeyProof

type KeyProof struct {
	// Thumbprint is the RFC 7638 JWK SHA-256 thumbprint, base64url
	// without padding, of the key that signed the proof.
	Thumbprint string
	// TokenHash is the proof's ath claim: the base64url SHA-256 hash of
	// the token, without padding.
	TokenHash string
	// Failure, when set, says why the proof failed its checks. Every
	// token presented with a failed proof is rejected for that reason.
	Failure Reason
	// AllowUnbound accepts a token that isn't bound to a key, for a proof
	// that binds a token being issued, as at a token endpoint. TokenHash
	// is then ignored for an unbound token.
	AllowUnbound bool
	// Spend records the proof's ID and returns [ErrProofReplayed] when it
	// was already recorded. The service calls it once, after the token
	// authenticates and agrees with the proof, so only callers holding a
	// live token can record IDs. Any other error is a server
	// error, not a rejection. A KeyProof without Spend is rejected.
	Spend func(ctx context.Context) error
}

KeyProof is a checked proof of possession of a private key, such as a DPoP proof (RFC 9449), that comes with a token. Package dpop builds it; pass it in the context with WithKeyProof.

A token bound to a key authenticates only with a KeyProof whose Thumbprint is the session's KeyThumbprint, whose TokenHash covers the token, and whose Spend reports it fresh. A token that isn't bound to a key is rejected with a KeyProof, unless AllowUnbound is set.

func KeyProofFrom

func KeyProofFrom(ctx context.Context) (KeyProof, bool)

KeyProofFrom returns the proof stored by WithKeyProof, if any.

type Limiter

type Limiter interface {
	// Allow returns how long to wait before the attempt may proceed. Zero
	// means proceed. An error means the limiter couldn't decide; the
	// library then fails closed with a server error.
	Allow(ctx context.Context, a Attempt) (retryAfter time.Duration, err error)
	// Report records whether the attempt succeeded.
	Report(ctx context.Context, a Attempt, ok bool)
}

Limiter throttles sign-in and enrolment attempts. The library calls Allow before it verifies anything or writes to the store, and Report after. It never locks an account on attempts made before sign-in: the limiter can only delay them, so it can't be used to lock someone out.

The library ships no implementation, because the right one depends on the deployment: a token bucket per client in memory, Valkey, or the database.

type Method

type Method string

Method names a way a human proved who they are.

const (
	MethodPasskey  Method = "passkey"
	MethodTOTP     Method = "totp"
	MethodRecovery Method = "recovery"
	MethodExternal Method = "external"
	// MethodFederated is a sign-in through an external identity provider,
	// such as Google, GitHub, or another OpenID Connect issuer, from the
	// federation package. It is a single factor that the library can't
	// inspect: a session whose only method is MethodFederated is never
	// [Principal.Fresh] and never [Principal.MultiFactor], and
	// [Service.StepUp] rejects it.
	MethodFederated Method = "federated"
	// MethodPassword is a password, from the password package. It is a
	// single factor, and it counts as fresh only while it is the strongest
	// factor the account has: on an account with a passkey or a confirmed
	// TOTP factor, a session whose strongest method is a password is never
	// fresh, and [Service.StepUp] and [Service.Elevate] refuse a password
	// proof.
	MethodPassword Method = "password"
	// MethodBridged is a sign-in that the application performed with its
	// own login, which authhttp.Bridge turned into a session with
	// [StartOptions.Bridged]. The library can't inspect it. A session
	// whose methods are only MethodBridged, or MethodBridged and
	// [MethodFederated], is [Principal.BridgedOnly]: it keeps the
	// application's sign-in time, meets only needs that set
	// [Need.Bridged], and can't delegate or create agents. No proof
	// carries it: StartSession, StepUp, and Elevate refuse such a proof.
	MethodBridged Method = "bridged"
)

Methods that factor packages produce. MethodExternal is for factors the application verifies itself, such as a hardware token checked by another service. Don't use it for email links or SMS codes: they prove access to a mailbox or phone number, not who the person is, and OWASP ASVS 5.0 requirement 6.3.6 forbids them as a factor.

type Need

type Need struct {
	// Action names the operation in the audit log and in [WithNeeds], for
	// example "create_pat", "repo.delete", or a route pattern such as
	// "DELETE /repos/{id}". It is 1 to 128 bytes without control
	// characters.
	Action string
	// Assurance is the minimum level.
	Assurance Assurance
	// Within is how recent the human's proof must be. Zero means any age.
	// A need with Within set refuses agents and tokens, which are never
	// fresh.
	Within time.Duration
	// Human refuses agents, personal access tokens, and OAuth tokens.
	Human bool
	// Scopes lists scopes the principal must all hold.
	Scopes []string
	// HoldAfterRecovery refuses the operation for a while after a recovery
	// code is used on the account, from any of its sessions: see
	// [WithRecoveryHold]. The library sets it for operations that create
	// credentials that outlive a session.
	HoldAfterRecovery bool
	// Purpose, when set, makes the need pass only through an elevation for
	// this purpose from [Service.Elevate]: plain step-up doesn't count.
	// Within then defaults to 10 minutes.
	Purpose Purpose
	// Bridged lets a session from the application's own login
	// ([Principal.BridgedOnly]) meet the need. Without it, every need at
	// AssuranceRecovering or above refuses such a session with
	// [ErrStrongerFactorRequired]. The library sets it only for approving
	// an OAuth grant. A need from [WithNeeds] keeps it only when both set
	// it.
	Bridged bool
	// ApprovalTTL is how long an approval for this need waits for its
	// person, and then how long the granted approval waits for the agent
	// to redeem it: from [MinApprovalTTL] to [MaxApprovalTTL], or zero for
	// [ApprovalTTL], 5 minutes. Raise it for an agent that runs in the
	// background and checks back later. A need from [WithNeeds] keeps the
	// shorter of the two.
	ApprovalTTL time.Duration
}

Need declares what an operation requires of its caller. The library's own sensitive operations each check one, and applications declare their own and check them with Service.Require. WithNeeds tightens any of them by Action.

func AgentPart

func AgentPart(n Need) Need

AgentPart returns the parts of n an agent must meet itself before it can ask for an approval: its scopes and the recovery hold, without the parts only a person can meet. To check it, use Service.RequireAgentPart, which applies WithNeeds before it strips these parts. Service.Require applies WithNeeds after, so it puts a Human floor back and refuses every agent.

type Observer

type Observer func(context.Context, Event)

Observer receives events after the change has been stored. It runs synchronously on the calling goroutine and cannot fail the operation: a panic is recovered and logged. Keep it fast, or hand events to a queue.

The observer is for metrics, notifications and best-effort audit logs. A durable audit trail belongs in the store, written in the same transaction as the change.

type Option

type Option func(*Service)

Option configures a Service.

func RequireAgentKeys

func RequireAgentKeys() Option

RequireAgentKeys refuses to create agent sessions that aren't bound to a key: Service.Delegate, Service.ClaimAgent, and Service.RegisterAgent fail with ErrKeyRequired unless the request or its parent names a key. Unbound agent sessions created before keep working until they end.

func WithApprovalNotifier

func WithApprovalNotifier(n ApprovalNotifier) Option

WithApprovalNotifier calls n once for each new approval, after it is stored and recorded: never for a request that Service.RequestApproval answered with an approval that was already pending, and never for a refused request. n runs in its own goroutine under a context that the request's end doesn't cancel and that ends after ApprovalNotifyTimeout, so it never delays or fails the agent's request. An error or a panic from n is logged to WithLogger's logger.

func WithApprovalURL

func WithApprovalURL(base string) Option

WithApprovalURL sets the page where a person reviews an approval, as an absolute URL to which the approval's ID is appended: for example "https://app.example/approve/" gives "https://app.example/approve/apr_…". Approval.URL holds the result, and authhttp.Approvable puts it in the challenge an agent gets. It must use https, or http on a loopback host such as localhost, and have no fragment. The URL comes only from this setting, never from a request, so an agent can't point a person at another host.

func WithAuditKey added in v0.4.0

func WithAuditKey(key []byte) Option

WithAuditKey sets the secret key that turns personal data into pseudonyms: the address labels and the federated identity labels in the audit log, and the rate-limit keys for an address. Each pseudonym is an HMAC-SHA256 of the value under key, so anyone without key, including someone who holds a copy of the audit log and a list of candidate addresses or provider user IDs, can't tell which person a label names.

key must be at least MinAuditKeySize bytes from a cryptographically secure source, kept secret, and kept for the life of the audit log: a new key gives every address and identity a new label, so events from before and after the change can't be linked. New refuses a key that is too short, or whose bytes all have the same value, such as an all-zero key. The password package requires it.

func WithClock

func WithClock(now func() time.Time) Option

WithClock sets the time source, for tests. The default is time.Now.

func WithDevTools

func WithDevTools() Option

WithDevTools turns on the development-only calls: Service.DevAge and Service.DevRecoverySession, which authhttp.DevTools serves to the browser client's developer panel. Never use it in production: authhttp.Mux.Check refuses to start with it unless every origin is localhost.

func WithFailureLimits

func WithFailureLimits(l FailureLimits) Option

WithFailureLimits replaces DefaultFailureLimits.

func WithLimiter

func WithLimiter(l Limiter) Option

WithLimiter sets the limiter for sign-in and enrolment attempts. Without one, New logs a warning, because nothing slows down guessing.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger for internal warnings, such as a detected token reuse or a panicking observer. The default discards logs.

func WithNeeds

func WithNeeds(needs ...Need) Option

WithNeeds tightens needs by their Action: the library's own, such as NeedCreatePAT, and an application's. Each field becomes the stricter of the two, so a need can be raised but never lowered. For example, WithNeeds(auth.Need{Action: auth.ActionCreatePAT, Assurance: auth.AssuranceMulti}) requires a passkey or two factors to create a personal access token. New rejects a need without an Action.

func WithObserver

func WithObserver(o Observer) Option

WithObserver sets the function that receives events. See Observer.

func WithPolicy

func WithPolicy(p Policy) Option

WithPolicy replaces DefaultPolicy.

func WithQuota

func WithQuota(qs ...Quota) Option

WithQuota adds quotas, checked in order; the first refusal wins. Pass Caps or *Caps itself, not wrapped, for its agent cap to hold under concurrency. WithQuota reads AgentsPerUser for the store when it runs, so changing a *Caps afterwards doesn't change the store's cap. Without a quota, nothing is capped except the unclaimed agents of SignupPolicy.MaxUnclaimed.

func WithRecoveryGate

func WithRecoveryGate(g RecoveryGate) Option

WithRecoveryGate refuses every need at AssuranceMulti for a human principal whose account doesn't have both a second factor (a passkey, or a confirmed TOTP factor that isn't locked) and a confirmed recovery path: unused recovery codes that the person typed back after they were generated, or, unless g.RequireCodes, two second factors. Forcing a second factor before a recovery path is in place locks people out, so the gate holds the full session, not the sign-in: a session can still enroll factors and generate recovery codes, which need less. The refusal has CodeSetupIncomplete. The preset package sets it for strict@1 and passkey-only@1.

func WithRecoveryHold

func WithRecoveryHold(d time.Duration) Option

WithRecoveryHold sets how long, after a recovery code is used on an account, the account can't do what needs with HoldAfterRecovery guard: create a personal access token, approve an OAuth grant, or claim an agent. The hold covers every session of the account, including one that later added a passkey, so a stolen recovery code buys an attacker nothing durable before the person notices. Zero turns the hold off, for example on a self-hosted server with one administrator; the maximum is 7 days. The default is DefaultRecoveryHold. Undoing the recovery with Service.UndoRecovery lifts the hold.

func WithSignup

func WithSignup(p SignupPolicy) Option

WithSignup turns on agent self-signup with policy p. Signup is off without it. The store must implement SignupStore.

With signup on, Principal.User is empty for unclaimed agents. Check Principal.Unclaimed before you use User as a key.

func WithSignupOverrides

func WithSignupOverrides() Option

WithSignupOverrides makes the service read a SignupOverride from the store, which must implement SignupSettingsStore, and apply it on top of the code policy. Every server reloads it at most 5 seconds after use finds it stale, and at once after a change made through it. A server that hasn't loaded it yet refuses new signups and holds unclaimed agents to an empty sandbox, so a pause can never be missed.

func WithTokenBrand

func WithTokenBrand(brand string) Option

WithTokenBrand sets the token prefix brand, 2 to 6 lowercase letters. The default "ts" produces tokens like "tss_…" and "tsa_…". Changing it invalidates every existing token.

type PATSpec

type PATSpec struct {
	// Name is shown to the human, for example "CI deploys". It is 1 to 100
	// bytes.
	Name string
	// Scopes the token holds. They must be a subset of the owner's.
	Scopes []string
	// TTL is the token's lifetime. Zero means Policy.PATDefault; it can't
	// exceed Policy.PATMax.
	TTL time.Duration
}

PATSpec describes a personal access token to create.

type PasswordRecord

type PasswordRecord struct {
	User UserID
	// Hash is a PHC string, opaque to the store. The library never stores
	// a password.
	Hash string
	// Version is 1 for the first password; each SetPassword adds 1.
	Version   int64
	ChangedAt time.Time
}

PasswordRecord is the stored form of a user's password.

type PasswordSet

type PasswordSet struct {
	User UserID
	Hash string
	// Want is the Version the stored password must have; 0 means none.
	Want int64
	// Key, when set, must be User's address, verified.
	Key string
	At  time.Time
}

PasswordSet is the input to EmailStore.SetPassword.

type Pending

type Pending struct {
	// Token identifies the pending sign-in, for example "tsi_…": a
	// checksummed token of its own kind, so secret scanners recognize it
	// and it never authenticates a request. It is a secret: keep it in an
	// HttpOnly cookie or the server-side form state, never in a URL. It
	// works with CompleteSignIn once.
	Token string
	// User is the account signing in.
	User UserID
	// Needs lists the methods still required, for example [totp]. When it
	// is empty, call CompleteSignIn at once.
	Needs []Method
	// First is the proof the sign-in started with. Pass it to factors that
	// need a first factor, such as totp.TOTP.Verify.
	First Proof
	// Until is when the pending sign-in expires.
	Until time.Time
}

Pending is a sign-in that has its first proof and waits for the factors in Needs. Pass Token to Service.CompleteSignIn with a proof for each.

type Policy

type Policy struct {
	// HumanIdle ends a human session after this long without use.
	HumanIdle time.Duration
	// HumanMax ends a human session this long after it starts, no matter how
	// often it is used.
	HumanMax time.Duration
	// AgentIdle ends an agent session after this long without use.
	AgentIdle time.Duration
	// AgentMax is the longest an agent session can live. A delegated session
	// also never outlives its parent.
	AgentMax time.Duration
	// MaxDepth caps the delegation chain. A human session has depth 0, an
	// agent it delegates to has depth 1, and so on.
	MaxDepth int
	// RotateGrace is how long a rotated-out token keeps working, to cover
	// requests already in flight. Presenting it after the window counts as
	// reuse and revokes the whole session tree.
	RotateGrace time.Duration

	// PATDefault is the lifetime of a personal access token created with a
	// zero TTL. Zero means 30 days.
	PATDefault time.Duration
	// PATMax is the longest a personal access token can live. Zero means
	// 366 days.
	PATMax time.Duration
	// PATIdle ends a personal access token after this long without use.
	// Zero means 90 days.
	PATIdle time.Duration
	// OAuthMax is the longest an OAuth grant can live: its refresh token,
	// or its access token when the client gets no refresh token. Zero
	// means 366 days.
	OAuthMax time.Duration
	// OAuthIdle ends an OAuth grant after this long without use or
	// refresh. Zero means 90 days.
	OAuthIdle time.Duration
}

Policy sets session lifetimes and delegation limits. Every session has both an idle timeout and an absolute maximum; there is no mode that turns either off.

func DefaultPolicy

func DefaultPolicy() Policy

DefaultPolicy returns the defaults: human sessions idle out after 14 days and end after 90, agent sessions idle out after 15 minutes and end after 8 hours, delegation is capped at depth 4, and rotation grace is 10 seconds.

The human defaults suit a developer tool on personal devices, and they are longer than the NIST SP 800-63B-4 reauthentication limits for AAL2 (24 hours, and 1 hour idle). Sensitive actions don't depend on session age: they need proofs at most 5 minutes old or a session that authenticated within 10 minutes. To meet AAL2 reauthentication, set HumanIdle to 1 hour and HumanMax to 24 hours. See docs/security/asvs-5.0.md.

Personal access tokens default to 30 days, live at most 366 days, and end after 90 days without use. OAuth grants live at most 366 days and end after 90 days without use.

type Principal

type Principal struct {
	// User is the responsible human. It is never empty, including for agents
	// several delegation levels deep, except for an agent that signed itself
	// up and isn't claimed yet: see [Principal.Unclaimed].
	User UserID
	// Kind says what kind of session or token authenticated the request.
	// It is zero only in a Principal built by hand.
	Kind SessionKind
	// Agent is empty for human sessions.
	Agent AgentID
	// Client is the OAuth client an OAuth token was issued to, or empty.
	Client string
	// Session is the session this principal was authenticated from.
	Session SessionID
	// Parent is the session this one was delegated from, or empty for a
	// session started by a human login.
	Parent SessionID
	// Depth is 0 for a human session, 1 for an agent delegated by a human, 2
	// for a sub-agent, and so on.
	Depth int
	// Scopes is sorted and deduplicated. The library enforces that delegation
	// narrows scopes but does not interpret them.
	Scopes []string
	// AuthenticatedAt is when the human last proved who they are, inherited
	// by delegated sessions. Don't compare it yourself for step-up checks:
	// use [Principal.Fresh], which is always false for agents.
	AuthenticatedAt time.Time
	// Methods lists how the human proved who they are, sorted. It is empty
	// when the application started the session without proofs.
	Methods []Method
	// ExpiresAt is the absolute expiry of the session.
	ExpiresAt time.Time
	// KeyThumbprint is the thumbprint of the key an agent session is bound
	// to, or empty for an unbound session. A bound principal was
	// authenticated with a proof of possession of that key. See
	// [DelegateSpec] and [KeyProof].
	KeyThumbprint string
	// IssuedAt is when the presented token was issued: the session's
	// start, or its last rotation or step-up. It is zero for sessions
	// stored before it was recorded. authhttp.WithRotation uses it.
	IssuedAt time.Time
	// Resource is the resource (RFC 8707) an OAuth token was issued for,
	// its audience, or empty for a token without one. A token with a
	// resource is meant only for that resource: verifiers that serve
	// something else must refuse it. authhttp.Middleware does, unless
	// configured with authhttp.WithResource.
	Resource string
}

Principal is the authenticated caller of a request.

func FromContext

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

FromContext returns the principal stored by WithPrincipal, if any.

func (Principal) Assurance

func (p Principal) Assurance() Assurance

Assurance returns how strongly the human behind p proved who they are in this session. Agents, personal access tokens, and OAuth tokens are always AssuranceNone, even though they inherit their human's methods.

func (Principal) BridgedOnly

func (p Principal) BridgedOnly() bool

BridgedOnly reports whether the session's only sign-in is the application's own login, bridged with StartOptions.Bridged, alone or with a federated sign-in. Such a session is exactly as strong as the application says: Service.Require refuses it for every need at AssuranceRecovering or above that doesn't set Need.Bridged, so it can approve an OAuth grant but can't create a personal access token, claim an agent, or make admin changes. Tokens and agent sessions inherit their human's methods, so it holds for them too. Stepping up with another factor lifts the restriction.

func (Principal) CheckStrong

func (p Principal) CheckStrong(now time.Time, maxAge time.Duration) error

CheckStrong returns nil when p is a human session that authenticated within maxAge of now with a factor stronger than a recovery code. It returns ErrStepUpRequired when p isn't fresh, and ErrStrongerFactorRequired when p is fresh but Principal.RecoveryOnly. Operations that create long-lived credentials or change factors use it.

func (Principal) Fresh

func (p Principal) Fresh(now time.Time, maxAge time.Duration) bool

Fresh reports whether a human authenticated within maxAge of now. It is always false for agents, personal access tokens, and OAuth tokens, so only a human session can pass a step-up check, even though the others inherit AuthenticatedAt. It is also false for a session whose only method is MethodFederated: a sign-in through an external identity provider never counts as a recent check of who the person is, so such a session has to step up with another factor first.

func (Principal) Has

func (p Principal) Has(scope string) bool

Has reports whether the principal holds scope.

func (Principal) IsAgent

func (p Principal) IsAgent() bool

IsAgent reports whether the principal is an agent session.

func (Principal) MultiFactor

func (p Principal) MultiFactor() bool

MultiFactor reports whether the session was started or stepped up with more than one factor. A passkey counts on its own, because the passkey package requires user verification; TOTP counts together with any other method, including MethodFederated. A recovery code alone does not, and neither does a federated sign-in alone.

func (Principal) RecoveryOnly

func (p Principal) RecoveryOnly() bool

RecoveryOnly reports whether a recovery code is the only factor the human used in this session, alone or with a federated or bridged sign-in. Such a session is how a person who lost their passkey gets back in: it can add a passkey and generate new recovery codes, but operations that create long-lived credentials or change other factors refuse it with ErrStrongerFactorRequired. Adding a passkey and stepping up with it lifts the restriction.

func (Principal) Unclaimed

func (p Principal) Unclaimed() bool

Unclaimed reports whether the principal is a session of an agent that signed itself up and that no human has claimed. Its User is empty, and its Scopes are within the signup sandbox. Check it before you use User as a key: for example, an EventFilter with an empty User matches every user.

type Problem

type Problem struct {
	// Type is ProblemTypePrefix followed by Code.
	Type string `json:"type"`
	// Title is a short summary for people, in sentence case.
	Title string `json:"title"`
	// Status is the HTTP status code.
	Status int `json:"status"`
	// Code is the stable name to branch on.
	Code ProblemCode `json:"code"`
	// Detail explains this occurrence for people.
	Detail string `json:"detail,omitempty"`
	// Fix tells the person what to do next.
	Fix string `json:"fix,omitempty"`
	// RetryAfter is how many seconds to wait before retrying, for
	// CodeThrottled.
	RetryAfter int `json:"retry_after,omitempty"`
	// Challenge says how to satisfy a refused need, for the codes that
	// [Refusal] uses.
	Challenge *Challenge `json:"challenge,omitempty"`
}

Problem describes a failure for a client, in the shape of RFC 9457 problem details: application/problem+json with the extension members code, fix, retry_after, and challenge. Describe builds one for every error the library returns. Before a person is identified, problems are generic, so they never reveal whether an account, passkey, or token exists.

func Describe

func Describe(err error) Problem

Describe returns the Problem for err. Every error the library returns maps to a specific problem; any other error becomes a 500 with CodeInternal and no detail, so internal messages never reach a client. It returns the zero Problem for a nil error.

Describe is for errors from serving a request, which go to the client. Setup errors, from building the service and its parts at start, aren't for clients: for example passkey.ErrConfig, password.ErrConfig, federation.ErrConfig, an error from New, and the error from authhttp's Mux.Check. Their messages name the field and the fix. Log them as they are and stop the server. Never pass them to Describe: it has no problems for them, so most become a bare internal problem that hides the cause.

type ProblemCode

type ProblemCode string

ProblemCode is a stable, machine-readable name for a kind of failure. Clients branch on it; its text never changes meaning.

const (
	CodeCodeReused   ProblemCode = "code_reused"
	CodeFactorLocked ProblemCode = "factor_locked"
)

Hints that factor packages attach after identification.

const (
	// CodeStepUpRequired means the session is strong enough but not
	// recent: step up with any factor in the challenge and retry.
	CodeStepUpRequired ProblemCode = "step_up_required"
	// CodeStrongerFactorRequired means the session's factors are weaker
	// than the need, however recent: step up with a factor in the
	// challenge, or add one first.
	CodeStrongerFactorRequired ProblemCode = "stronger_factor_required"
	// CodeHumanRequired means an agent, a personal access token, or an
	// OAuth token tried an operation only a human session may do.
	CodeHumanRequired ProblemCode = "human_required"
	// CodeScopeMissing means the principal lacks a scope the need lists.
	CodeScopeMissing ProblemCode = "scope_missing"
)

Problem codes for refusals that Service.Require returns.

const (
	CodeUnauthenticated ProblemCode = "unauthenticated"
	CodeFactorRejected  ProblemCode = "factor_rejected"
	CodeThrottled       ProblemCode = "throttled"
	CodeInvalidRequest  ProblemCode = "invalid_request"
	CodeNotFound        ProblemCode = "not_found"
	CodeConflict        ProblemCode = "conflict"
	CodeFactorExists    ProblemCode = "factor_exists"
	CodeScopeExceeded   ProblemCode = "scope_exceeded"
	CodeExpiryExceeded  ProblemCode = "expiry_exceeded"
	CodeDepthExceeded   ProblemCode = "depth_exceeded"
	CodeParentInactive  ProblemCode = "parent_inactive"
	CodeAgentInactive   ProblemCode = "agent_inactive"
	CodeNotAgentOwner   ProblemCode = "not_agent_owner"
	CodeNotRotatable    ProblemCode = "not_rotatable"
	CodeKeyRequired     ProblemCode = "key_required"
	CodeQuotaExceeded   ProblemCode = "quota_exceeded"
	CodeSignupRejected  ProblemCode = "signup_rejected"
	CodeClaimInvalid    ProblemCode = "claim_invalid"
	CodeNotClaimed      ProblemCode = "not_claimed"
	CodeUnavailable     ProblemCode = "unavailable"
	CodeInternal        ProblemCode = "internal"
)

Problem codes for errors that aren't refusals. See also the codes that Refusal uses.

const CodeEmailUnverified ProblemCode = "email_unverified"

CodeEmailUnverified means the account's email address isn't confirmed, so it can't create, claim, or delegate to agents yet.

const CodeRecoveryHold ProblemCode = "recovery_hold"

CodeRecoveryHold means a need with HoldAfterRecovery was refused because a recovery code was used on the account recently.

const CodeSetupIncomplete ProblemCode = "setup_incomplete"

CodeSetupIncomplete means a need at AssuranceMulti was refused under a RecoveryGate, because the account has no second factor or no confirmed recovery path yet.

type Proof

type Proof struct {
	User UserID
	// Method is how the user proved who they are.
	Method Method
	// Factor identifies the credential or factor used, for the audit log.
	Factor string
	// At is when the factor was verified.
	At time.Time
	// UserVerified is true when the factor itself checked the user, as a
	// passkey with user verification does.
	UserVerified bool
	// Reserved is the hash of a recovery code that this proof checked but
	// didn't spend: see recovery.Codes.Check. [Service.StartSession],
	// [Service.StepUp], and [Service.CompleteSignIn] spend it when they use
	// the proof, so a code is spent only when a session actually starts.
	// Zero for every other proof.
	Reserved [32]byte
	// Receipt is set by passkey.Passkeys.FinishApproval: the assertion
	// that approved one action, for [Service.Approve].
	Receipt *Receipt
}

Proof records that a human just passed one factor. Factor packages such as passkey, recovery, and totp return proofs; the application passes them to Service.StartSession or Service.StepUp, so the session records how the user signed in.

A proof is a record, not a capability: an application can always start a session itself. Proofs exist so sessions carry their methods and so step-up works the same way for every factor.

type Purpose

type Purpose struct {
	Name     string `json:"name"`
	Resource string `json:"resource,omitempty"`
}

Purpose names what a purpose-scoped step-up allows: an operation and the resource it acts on, for example For("secrets.edit", "repo:acme/api:prod").

func For

func For(name, resource string) Purpose

For returns the purpose name on resource.

func (Purpose) IsZero

func (p Purpose) IsZero() bool

IsZero reports whether p names no purpose.

type Quota

type Quota interface {
	// Check returns nil to let r proceed, or an error matching
	// [ErrQuotaExceeded] to refuse it. Any other error means the quota
	// couldn't decide, and the library refuses the action.
	Check(ctx context.Context, r QuotaRequest) error
}

Quota decides whether a principal may create one more agent, agent session, or personal access token. The library calls Check after it has validated a request and checked its permissions, and before it writes to the store. See docs/design/quotas.md.

Quotas fail closed: an error matching ErrQuotaExceeded refuses the action, and any other error refuses it too, as a server error matching ErrQuotaUnavailable. Either way the library records an access_denied event with the reason.

The library ships one implementation, Caps. Pass yours, or several, with WithQuota.

type QuotaRequest

type QuotaRequest struct {
	// Action is one of ActionCreateAgent, ActionRegisterAgent,
	// ActionClaimAgent, ActionDelegate, or ActionCreatePAT.
	Action string
	// Client is the key the application set with [WithClient].
	Client string
	// User is the responsible human. It is empty for ActionRegisterAgent,
	// and for ActionDelegate from an unclaimed agent's session.
	User UserID
	// Agent is the agent that receives a session, for ActionDelegate.
	// It is empty otherwise.
	Agent AgentID
	// contains filtered or unexported fields
}

QuotaRequest describes an action for Quota.Check.

func (QuotaRequest) Agents

func (r QuotaRequest) Agents(ctx context.Context) (int, error)

Agents returns how many enabled agents r.User owns, counted through the service's store. It returns zero when r.User is empty.

func (QuotaRequest) Sessions

func (r QuotaRequest) Sessions(ctx context.Context) (int, error)

Sessions returns how many live sessions r.Agent holds, counted through the service's store. A session is live until it is revoked or reaches its absolute expiry; an idle session counts until then. It returns zero when r.Agent is empty.

type Reason

type Reason string

Reason explains why authentication failed. It is for logs and metrics only and must never be sent to a client.

const (
	ReasonNone         Reason = ""
	ReasonMalformed    Reason = "malformed"
	ReasonUnknown      Reason = "unknown"
	ReasonKindMismatch Reason = "kind_mismatch"
	ReasonExpired      Reason = "expired"
	ReasonIdle         Reason = "idle"
	ReasonRevoked      Reason = "revoked"
	ReasonAgentRevoked Reason = "agent_revoked"
	ReasonReused       Reason = "reused"
	// ReasonClientMismatch means an OAuth token was presented by a client
	// other than the one it was issued to.
	ReasonClientMismatch Reason = "client_mismatch"
	// ReasonAudienceMismatch means a token bound to a resource was
	// presented somewhere else, or a refresh named another resource.
	ReasonAudienceMismatch Reason = "audience_mismatch"
)

Reasons reported by ReasonOf.

const (
	ReasonScopeMissing Reason = "scope_missing"
	ReasonNotFresh     Reason = "not_fresh"
	// ReasonRecoveryOnly means the session was fresh, but a recovery code
	// was its only factor: see [Principal.RecoveryOnly].
	ReasonRecoveryOnly  Reason = "recovery_only"
	ReasonCrossOrigin   Reason = "cross_origin"
	ReasonScopeExceeded Reason = "scope_exceeded"
	ReasonNotAgentOwner Reason = "not_agent_owner"
	// ReasonMerged marks a failures_skipped event that holds summaries
	// merged because the store was unavailable for longer than the queue
	// of unwritten events can cover. Their counts survive; who and where
	// don't.
	ReasonMerged Reason = "merged"
)

Reasons recorded with EventAccessDenied, and ReasonMerged.

const (
	// ReasonKeyRequired means a token bound to a key arrived without a
	// proof of possession, for example as a Bearer token.
	ReasonKeyRequired Reason = "key_required"
	// ReasonKeyMismatch means the proof was signed by a key other than
	// the one the token is bound to.
	ReasonKeyMismatch Reason = "key_mismatch"
	// ReasonProofTokenMismatch means the proof's access token hash (ath)
	// doesn't match the token it came with.
	ReasonProofTokenMismatch Reason = "proof_token_mismatch"
	// ReasonNotKeyBound means a proof of possession came with a token that
	// isn't bound to a key.
	ReasonNotKeyBound Reason = "not_key_bound"
	// ReasonProofReplayed means the proof was already used.
	ReasonProofReplayed Reason = "proof_replayed"
)

Reasons for rejecting a token because of its key binding.

const (
	ReasonFactorUnknown   Reason = "factor_unknown"
	ReasonFactorInvalid   Reason = "factor_invalid"
	ReasonCeremonyInvalid Reason = "ceremony_invalid"
	ReasonCodeReused      Reason = "code_reused"
	ReasonCloneSuspected  Reason = "clone_suspected"
	ReasonFactorLocked    Reason = "factor_locked"
)

Reasons a factor was rejected, reported by ReasonOf.

const (
	// ReasonNotHuman means an agent or token tried a human-only operation.
	ReasonNotHuman Reason = "not_human"
	// ReasonWeakFactor means the session's factors were below the need's
	// assurance, other than [ReasonRecoveryOnly].
	ReasonWeakFactor Reason = "weak_factor"
	// ReasonBridged means a session from the application's own login
	// ([Principal.BridgedOnly]) tried an operation whose need doesn't set
	// [Need.Bridged].
	ReasonBridged Reason = "bridged"
)

Reasons recorded with EventAccessDenied for refusals.

const (
	ReasonSignupDisabled Reason = "signup_disabled"
	ReasonTypeDenied     Reason = "type_denied"
	ReasonTypeUnverified Reason = "type_unverified"
	ReasonWorkRejected   Reason = "work_rejected"
	ReasonNotAdmitted    Reason = "not_admitted"
	ReasonQuotaExceeded  Reason = "quota_exceeded"
	ReasonClaimInvalid   Reason = "claim_invalid"
)

Reasons for rejected signups and claims, reported by ReasonOf and recorded with EventAccessDenied and EventTokenRejected.

const ReasonApprovalMismatch Reason = "approval_mismatch"

ReasonApprovalMismatch is recorded when an approval is redeemed by another agent or for another action.

const ReasonEmailUnverified Reason = "email_unverified"

ReasonEmailUnverified is recorded with EventAccessDenied when an account with an unconfirmed address tries to use agents.

const ReasonQuotaUnavailable Reason = "quota_unavailable"

ReasonQuotaUnavailable is the reason recorded when a Quota fails.

const ReasonRecoveryHold Reason = "recovery_hold"

ReasonRecoveryHold is recorded with EventAccessDenied for refusals with CodeRecoveryHold.

const ReasonSetupIncomplete Reason = "setup_incomplete"

ReasonSetupIncomplete is recorded with EventAccessDenied for refusals with CodeSetupIncomplete.

const ReasonSignupPaused Reason = "signup_paused"

ReasonSignupPaused is recorded when a signup is refused because an override paused signup, or because the service hasn't loaded the override yet.

const ReasonWrongAccount Reason = "wrong_account"

ReasonWrongAccount means a step-up used a credential of another account.

func DenyReason

func DenyReason(err error) Reason

DenyReason returns the EventAccessDenied reason for an error from Principal.CheckStrong.

func ReasonOf

func ReasonOf(err error) Reason

ReasonOf returns the reason behind an authentication failure, or ReasonNone if err is not one.

type Receipt

type Receipt struct {
	Approval          string   `json:"approval"`
	Digest            [32]byte `json:"digest"`
	Credential        []byte   `json:"credential"`
	AuthenticatorData []byte   `json:"authenticator_data"`
	ClientDataJSON    []byte   `json:"client_data_json"`
	Signature         []byte   `json:"signature"`
}

Receipt is the proof that a person approved one exact action: a passkey assertion over ApprovalChallenge. The audit log keeps it in the approval_granted event, and passkey.Passkeys.VerifyReceipt checks it against the credential's stored public key.

type RecoveryGate

type RecoveryGate struct {
	// RequireCodes counts only confirmed recovery codes as a recovery
	// path. Otherwise two second factors count too, for example two
	// passkeys, or a passkey and TOTP.
	RequireCodes bool
}

RecoveryGate holds full sessions until an account can recover. See WithRecoveryGate.

func (RecoveryGate) Complete

func (g RecoveryGate) Complete(s Setup) bool

Complete reports whether s meets g.

type RecoverySignIn

type RecoverySignIn struct {
	// Session is the session the recovery code started.
	Session SessionID
	// At is when it started.
	At time.Time
	// Client is the client key the application set, such as an IP prefix.
	Client string
	// UndoBy is when [Service.UndoRecovery] stops accepting it.
	UndoBy time.Time
}

RecoverySignIn is a session started with a recovery code that can still be undone.

type Refusal

type Refusal struct {
	// Code says which part of the need failed.
	Code ProblemCode
	// Need is the need after [WithNeeds] tightened it.
	Need Need
	// SatisfyWith lists the factors this account has that would meet the
	// need with a step-up, strongest first: passkey, totp, password,
	// recovery. It is empty when none would, for example for an agent, or
	// for a recovering account with no passkey yet.
	SatisfyWith []Method
	// Missing lists the scopes the principal lacks, for CodeScopeMissing.
	Missing []string
	// Until is when a [CodeRecoveryHold] refusal ends, and RetryAfter how
	// long that is from the refusal.
	Until      time.Time
	RetryAfter time.Duration
}

Refusal is the error Service.Require returns when a principal falls short of a need. It says what would turn the refusal into a success: Describe turns it into a Problem with a Challenge. A refusal with CodeStepUpRequired, CodeStrongerFactorRequired, or CodeHumanRequired matches ErrStepUpRequired; CodeStrongerFactorRequired also matches ErrStrongerFactorRequired; CodeScopeMissing matches ErrScopeMissing; CodeEmailUnverified matches ErrEmailUnverified.

func (*Refusal) Error

func (r *Refusal) Error() string

func (*Refusal) Is

func (r *Refusal) Is(target error) bool

Is reports whether target is one of the sentinels that r matches.

func (*Refusal) Problem

func (r *Refusal) Problem() Problem

Problem describes the refusal for a client.

type Registration

type Registration struct {
	// Agent is the new, unclaimed agent.
	Agent Agent
	// Token is the agent's tsa_ token for its signup session, which ends at
	// Agent.ClaimBy.
	Token Token
	// ClaimCode is the single-use code a human passes to
	// [Service.ClaimAgent]. Give it to the agent to show its human.
	ClaimCode Token
	// Principal is the signup session.
	Principal Principal
}

Registration is the result of Service.RegisterAgent.

type Runtime

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

Runtime gives factor packages the parts of a Service they share: the clock, the limiter, the observer, and the logger. Applications don't need it.

func (Runtime) Allow

func (r Runtime) Allow(ctx context.Context, action string, user UserID) error

Allow asks the limiter whether an attempt may proceed. It returns nil, an error matching ErrThrottled, or a server error if the limiter failed. With no limiter, every attempt proceeds.

func (Runtime) AllowTarget

func (r Runtime) AllowTarget(ctx context.Context, action, target string) error

AllowTarget asks the limiter whether an attempt before sign-in may proceed against target, an opaque key that doesn't reveal whether an account exists. Call it after Runtime.Allow for the client. It returns nil, an error matching ErrThrottled, or a server error if the limiter failed, and records throttled attempts as Allow does.

func (Runtime) ApprovalURL

func (r Runtime) ApprovalURL() string

ApprovalURL returns the approval page's URL from WithApprovalURL, or "" without it. authhttp reads it to know which page is the approval page.

func (Runtime) Brand

func (r Runtime) Brand() string

Brand returns the brand of the service's tokens, for packages that issue tokens of their own kinds in the same format.

func (Runtime) DevTools

func (r Runtime) DevTools() bool

DevTools reports whether WithDevTools is on.

func (Runtime) HasLimiter

func (r Runtime) HasLimiter() bool

HasLimiter reports whether the service has a limiter, so authhttp.Mux.Check can refuse to start without one.

func (Runtime) Logger

func (r Runtime) Logger() *slog.Logger

Logger returns the service's logger.

func (Runtime) Now

func (r Runtime) Now() time.Time

Now returns the service's current time.

func (Runtime) Observe

func (r Runtime) Observe(ctx context.Context, ev Event)

Observe passes ev to the observer only, without writing it to the store. Factor packages call it after the store has recorded the event in the same transaction as the change.

func (Runtime) Report

func (r Runtime) Report(ctx context.Context, action string, user UserID, err error)

Report tells the limiter how an attempt ended, and records a factor_rejected event when err matches ErrFactorRejected. Other errors are server errors, not failed attempts, and aren't recorded.

func (Runtime) Require

func (r Runtime) Require(ctx context.Context, p Principal, n Need) error

Require checks p against n with Service.Require.

type Service

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

Service creates, authenticates, rotates and revokes sessions. It is safe for concurrent use.

func New

func New(store Store, opts ...Option) (*Service, error)

New returns a Service backed by store.

func (*Service) Agent

func (s *Service) Agent(ctx context.Context, id AgentID) (Agent, error)

Agent returns the agent with the given ID, or ErrNotFound.

func (*Service) Agents

func (s *Service) Agents(ctx context.Context, f AgentFilter) ([]Agent, error)

Agents returns agents ordered by ID, owned by f.Owner when it's set, or only unclaimed ones when f.Unclaimed is set. A zero Limit means 100; the maximum is 1,000. To page, pass the last agent's ID as f.After.

func (*Service) Approval

func (s *Service) Approval(ctx context.Context, viewer Principal, id string) (Approval, error)

Approval returns approval id for its human to review: what the agent wants to do, and which agent and session asked. viewer must be a human session of the approval's user; anyone else gets ErrNotFound.

func (*Service) Approve

func (s *Service) Approve(ctx context.Context, human Principal, id string, proof Proof) error

Approve approves approval id with proof, a passkey proof from passkey.Passkeys.FinishApproval whose assertion signed ApprovalChallenge for this approval. It records approval_granted with the Receipt in the audit log. human must be a session of the approval's user that meets NeedApprove. It returns ErrNotFound for an approval that isn't pending, and ErrFactorRejected for a proof that isn't bound to this approval.

func (*Service) Authenticate

func (s *Service) Authenticate(ctx context.Context, raw string) (Principal, error)

Authenticate returns the principal for a raw token. Every failure matches ErrUnauthenticated; a store failure returns a different error, which callers should treat as a server error, not a rejected token.

Authenticate always reads the store, so revocation is immediate.

A token bound to a key authenticates only when ctx carries a KeyProof from that key for this token; see WithKeyProof.

func (*Service) BeginSignIn

func (s *Service) BeginSignIn(ctx context.Context, first Proof, o StartOptions) (Pending, error)

BeginSignIn starts a sign-in with a first proof and returns what else the account needs. A passkey needs nothing more. Any other first proof, such as a recovery code or a federated sign-in, needs TOTP when the account has confirmed TOTP, even while it is locked, so locking TOTP can't remove the second factor. o.Scopes apply to the session that Service.CompleteSignIn starts; o.Proofs and o.AuthenticatedAt must be empty. A recovery code that [recovery.Codes.Check] reserved stays unspent until the sign-in completes.

func (*Service) BindDevice

func (s *Service) BindDevice(ctx context.Context, p Principal, proof string) (DeviceBinding, Token, error)

BindDevice binds the human session behind p to the key in proof, the registration JWT the browser sent in Secure-Session-Response, which must carry a challenge from Service.RegistrationChallenge for p's session. It rotates the session's token, so a cookie copied before the binding stops working, and returns the binding and the new token.

func (*Service) Checkpoint

func (s *Service) Checkpoint(ctx context.Context, key ed25519.PrivateKey, trusted ...Checkpoint) (Checkpoint, error)

Checkpoint seals pending events and signs the chain head with key. Store the result where the database's administrators can't change it.

Pass the earlier checkpoints you trust, at least the latest one, read from that storage. Checkpoint checks their signatures against key's public key and verifies the chain against them before it signs, so a chain rebuilt since then is reported as ErrAuditTampered instead of being signed. With no earlier checkpoints, it trusts the chain as it is: do that only for the first checkpoint.

func (*Service) ClaimAgent

func (s *Service) ClaimAgent(ctx context.Context, claimer Principal, code string, spec ClaimSpec) (Agent, error)

ClaimAgent makes claimer's user the owner of the unclaimed agent whose claim code is code, with the scopes in spec. claimer must be a human session that authenticated within ClaimFreshFor with more than one factor (Principal.MultiFactor); otherwise ClaimAgent returns ErrStepUpRequired. The scopes must be a subset of claimer's.

In one store transaction, the claim consumes the code, revokes every sandbox session of the agent, and creates the agent's new session, delegated from claimer as Service.Delegate would. The agent collects its token for that session with Service.CollectClaim within Policy.AgentIdle. A code that is unknown, used, or past its deadline returns ErrClaimInvalid. The email address rule of Service.CreateAgent applies.

func (*Service) CollectClaim

func (s *Service) CollectClaim(ctx context.Context, signupToken string) (Token, Principal, error)

CollectClaim exchanges a claimed agent's signup token for the token of the session that Service.ClaimAgent created. It works once: a second call counts as token reuse and revokes the collected session and every session delegated from it, so a thief who collects first is cut off when the agent tries.

When the signup session is bound to a key, CollectClaim needs a KeyProof from that key that covers signupToken, even when the claimed session isn't bound; otherwise it checks the claimed session's binding.

Before the agent is claimed, CollectClaim returns ErrNotClaimed for a valid signup token, so the agent can poll it. Every other failure matches ErrUnauthenticated.

func (*Service) CollectClaimWait

func (s *Service) CollectClaimWait(ctx context.Context, signupToken string, wait time.Duration) (Token, Principal, error)

CollectClaimWait is Service.CollectClaim that waits up to wait, at most MaxCollectWait, for a person to claim the agent, so an agent can hold one request open instead of polling. It returns as soon as the claim happens, when ctx ends, or with ErrNotClaimed when wait runs out.

func (*Service) CompleteSignIn

func (s *Service) CompleteSignIn(ctx context.Context, pending string, proofs ...Proof) (Token, Principal, error)

CompleteSignIn finishes a pending sign-in with a proof for each method it needs, spends any recovery code it reserved, and starts the session. The pending token works once, even when CompleteSignIn fails; on failure it returns ErrSignInIncomplete, or ErrFactorRejected when the reserved recovery code was spent elsewhere in the meantime.

func (*Service) Connections

func (s *Service) Connections(ctx context.Context, u UserID) ([]Connection, error)

Connections returns the live connections of u, oldest first: the OAuth grants that carry a resource.

func (*Service) Counts

func (s *Service) Counts(ctx context.Context, window time.Duration) (Counts, error)

Counts returns totals for an admin overview, with EventsSince counting the audit events of the last window. window must be positive.

func (*Service) CreateAgent

func (s *Service) CreateAgent(ctx context.Context, owner Principal, spec AgentSpec) (Agent, error)

CreateAgent registers an agent owned by the human behind owner. The agent's scopes must be a subset of owner's. Agents cannot create agents. A quota set with WithQuota can refuse it with ErrQuotaExceeded. When the store is an EmailStore and the account's address isn't confirmed, it returns a *Refusal with CodeEmailUnverified; an account without an address is unaffected. An owner that is Principal.BridgedOnly gets ErrStrongerFactorRequired.

func (*Service) CreatePAT

func (s *Service) CreatePAT(ctx context.Context, owner Principal, spec PATSpec) (Token, SessionInfo, error)

CreatePAT creates a personal access token for the human behind owner. A token that isn't used for Policy.PATIdle stops working.

owner must be a human session that authenticated within PATFreshFor, so a stolen session, token, or agent can't mint a long-lived credential; otherwise CreatePAT returns ErrStepUpRequired. A session whose only factor is a recovery code gets ErrStrongerFactorRequired. The token never rotates and is never fresh. It isn't tied to owner's session: it ends when it expires, or with Service.Revoke or Service.RevokeUser. A quota set with WithQuota can refuse it with ErrQuotaExceeded.

func (*Service) Delegate

func (s *Service) Delegate(ctx context.Context, parent Principal, spec DelegateSpec) (Token, Principal, error)

Delegate creates an agent session from parent. The new session's user, and the human's authentication time, are inherited from parent and cannot be set by the caller. A quota set with WithQuota can refuse it with ErrQuotaExceeded. From a parent that isn't an agent's session, the email address rule of Service.CreateAgent applies too. A parent that is Principal.BridgedOnly, including a token a bridged session approved, gets ErrStrongerFactorRequired.

func (*Service) Deny

func (s *Service) Deny(ctx context.Context, human Principal, id string) error

Deny denies approval id. human must be a session of the approval's user that meets NeedApprove. The agent's next Service.RedeemApproval returns ErrApprovalDenied.

func (*Service) DevAge

func (s *Service) DevAge(ctx context.Context, raw string, d time.Duration) (Token, Principal, error)

DevAge rotates the human session behind raw and moves when it authenticated back by d, so the session looks d older without waiting: for example, past the step-up window. It returns the new token.

func (*Service) DevRecoverySession

func (s *Service) DevRecoverySession(ctx context.Context, u UserID) (Token, Principal, error)

DevRecoverySession starts a session for u as if they had signed in with a recovery code alone, to try recovery mode and its hold.

func (*Service) DeviceBound

func (s *Service) DeviceBound(ctx context.Context, session SessionID) (bool, error)

DeviceBound reports whether session is bound to a browser key. On a store error it returns the error, and callers must not treat the session as unbound.

func (*Service) Elevate

func (s *Service) Elevate(ctx context.Context, p Principal, purpose Purpose, proofs ...Proof) (time.Time, error)

Elevate steps the session behind p up for one purpose only, with fresh proofs. Unlike Service.StepUp, it doesn't rotate the token or make the session generally fresh: only needs with the same Purpose count it. So confirming once to edit one repository's production secrets doesn't also allow deleting the organization from a tab left open. It returns when the elevation was proved; Service.Elevation reports it later. Like Service.StepUp, it refuses password proofs on an account with a passkey or a confirmed TOTP factor.

func (*Service) Elevation

func (s *Service) Elevation(ctx context.Context, p Principal, purpose Purpose) (time.Time, error)

Elevation returns when p's session was elevated for purpose, or the zero time when it wasn't, or its elevation is older than MaxElevation. Use it to show a labeled timer, such as "Editing acme/api prod secrets: 8 min".

func (*Service) EmailLabel added in v0.4.0

func (s *Service) EmailLabel(key string) string

EmailLabel names an address in the audit log without revealing it: "email:" followed by its Service.Pseudonym, keyed by WithAuditKey. key is the normalized address. Without an audit key it returns "email", which names no address at all.

func (*Service) Events

func (s *Service) Events(ctx context.Context, f EventFilter) ([]Event, error)

Events returns audit events matching f, oldest first, or newest first when f.Descending is set. A zero Limit means 100; the maximum is 1,000. To page, pass the last event's Seq as f.AfterSeq, or as f.BeforeSeq when f.Descending is set.

func (*Service) ExpireUnclaimed

func (s *Service) ExpireUnclaimed(ctx context.Context) (int, error)

ExpireUnclaimed deletes every unclaimed agent past its claim deadline, with every session it holds, and records an agent_expired event for each. It returns how many agents it deleted. Service.Run calls it once per minute; call it yourself if you don't run Run. It does nothing when the store isn't a SignupStore.

func (*Service) FlushFailures

func (s *Service) FlushFailures(ctx context.Context)

FlushFailures ends the current window and writes every queued failure event. Call it when the process shuts down; Service.Run does.

func (*Service) Grant

func (s *Service) Grant(ctx context.Context, owner Principal, spec GrantSpec) (Grant, error)

Grant issues OAuth tokens to a client on behalf of the human behind owner, after the human approved the request. owner must be a human session that authenticated within GrantFreshFor, because the grant can outlive it by up to a year; otherwise Grant returns ErrStepUpRequired, or ErrStrongerFactorRequired when a recovery code is its only factor. owner's session must still be live when the grant is issued, so revoking the session that approved a pending request cancels it; otherwise Grant returns ErrParentInactive. The oauth package calls it; applications rarely need to.

The grant isn't tied to owner's session: it ends when it expires, after Policy.OAuthIdle without use, or with Service.Revoke on its refresh token's or access token's session, or Service.RevokeUser. Revoking a refresh token revokes every access token issued under it.

func (*Service) HasAuditKey added in v0.4.0

func (s *Service) HasAuditKey() bool

HasAuditKey reports whether the Service has a key from WithAuditKey.

func (*Service) Inspect

func (s *Service) Inspect(ctx context.Context, raw string) (Principal, error)

Inspect returns the principal of any token that authenticates, refresh tokens included, for OAuth introspection and revocation. Every failure matches ErrUnauthenticated, as with Service.Authenticate. Don't use it to authenticate requests: a refresh token's principal must never be accepted as a caller. Inspect doesn't need a KeyProof for a token bound to a key, and reports the binding in Principal.KeyThumbprint.

func (*Service) ListSessions

func (s *Service) ListSessions(ctx context.Context, u UserID, f SessionFilter) ([]SessionInfo, error)

ListSessions lists u's sessions that match f, oldest first.

func (*Service) Meets

func (s *Service) Meets(ctx context.Context, p Principal, n Need) bool

Meets reports whether p meets n after WithNeeds tightened it, without recording anything. Use it to decide what to show, for example whether to offer a step-up before an action; enforce with Service.Require. A store error counts as not meeting the need.

func (*Service) Need

func (s *Service) Need(base Need) Need

Need returns the need the service checks for action, starting from base: base tightened by WithNeeds. Factor packages call it to report their effective needs.

func (*Service) PeekClaim

func (s *Service) PeekClaim(ctx context.Context, viewer Principal, code string) (ClaimPreview, error)

PeekClaim shows the unclaimed agent behind a claim code without spending the code, so the person can check its name, type, and pairing words before granting it scopes with Service.ClaimAgent. It is rate-limited per person, and every failure returns ErrClaimInvalid, whether the code is malformed, unknown, used, or past its deadline.

func (*Service) PendingApprovals

func (s *Service) PendingApprovals(ctx context.Context, viewer Principal) ([]Approval, error)

PendingApprovals returns the approvals that wait for viewer's decision, newest first, at most 50: the person's inbox of agent requests. viewer must be a human session; any other principal gets none. Each approval is one that Service.Approval would show viewer, still pending and unexpired. It reads the approval_requested events of the last MaxApprovalTTL.

func (*Service) PendingSignIn

func (s *Service) PendingSignIn(ctx context.Context, pending string) (Pending, error)

PendingSignIn returns the pending sign-in behind pending without using it up: who is signing in, what they still need, and the first proof, for factors that need one, such as totp.TOTP.Verify. Token is empty. It returns ErrSignInIncomplete for an unknown, used, or expired token.

func (*Service) Prune

func (s *Service) Prune(ctx context.Context) (int, error)

Prune deletes sessions past their absolute expiry, expired ceremonies when the store is also a FactorStore, and expired device codes when it is a DeviceStore. It returns how many sessions were deleted. Run it periodically.

func (*Service) Pseudonym added in v0.4.0

func (s *Service) Pseudonym(purpose string, parts ...[]byte) string

Pseudonym returns 32 hexadecimal digits, the first 16 bytes of an HMAC-SHA256 under the key from WithAuditKey of purpose and parts. The same purpose and parts always give the same pseudonym, and different purposes never collide. It returns "" when the Service has no audit key.

func (*Service) RecordAccessDenied

func (s *Service) RecordAccessDenied(ctx context.Context, p Principal, action string, reason Reason)

RecordAccessDenied records that p was refused action, for example a request without the scope it needs or an application permission check that failed. authhttp calls it for the requests it rejects with 403.

func (*Service) RecordClientRegistration

func (s *Service) RecordClientRegistration(ctx context.Context, r ClientRegistration) error

RecordClientRegistration records a dynamic client registration as an oauth_client_registered event. The oauth package calls it.

func (*Service) RecordConsent

func (s *Service) RecordConsent(ctx context.Context, who Principal, c Consent) error

RecordConsent records that the human behind who approved an OAuth client's request, as an oauth_consented event in the audit log. The oauth package calls it before it issues the authorization code, and fails the approval when it returns an error. A consent is a record only: the provider never skips a consent page because of an earlier one.

func (*Service) RecordToolCall

func (s *Service) RecordToolCall(ctx context.Context, c ToolCall) error

RecordToolCall records a tool call as a tool_called event in the audit log, which the hash chain covers. mcpauth.AuditTo calls it.

func (*Service) RecoverySignIns

func (s *Service) RecoverySignIns(ctx context.Context, u UserID) ([]RecoverySignIn, error)

RecoverySignIns lists u's sign-ins with a recovery code from the last UndoWindow that haven't been undone, newest first. Show them to u's other signed-in devices with a "That wasn't me" action that calls Service.UndoRecovery.

func (*Service) RedeemApproval

func (s *Service) RedeemApproval(ctx context.Context, agent Principal, id string, act Action, need Need) error

RedeemApproval spends approval id for agent and act, so the agent can do act once. The approval must be approved, unexpired, unused, asked for by agent's agent, and for an action with the same digest. It returns ErrApprovalPending while the human hasn't decided, ErrApprovalDenied when they denied it, and ErrApprovalInvalid for anything else. A redeem by another agent, or for another action, leaves the approval in place, so nobody can burn an approval they don't own.

need is the need of the operation the agent is about to do. It must have the same action, after WithNeeds, as the need the approval was asked for, so an approval for one route's need can't open another route that describes the same action. The agent must still meet AgentPart of it.

func (*Service) RedeemApprovalWait

func (s *Service) RedeemApprovalWait(ctx context.Context, raw, id string, act Action, need Need, wait time.Duration) (Principal, error)

RedeemApprovalWait is Service.RedeemApproval that waits up to wait, at most MaxApprovalWait, while the approval is pending, so an agent can hold one request open until its human decides instead of polling. raw is the agent's token, which the request already authenticated. It returns as soon as the person approves (and spends the approval, as RedeemApproval does), denies, or the approval expires, when ctx ends, for example because the client disconnected, or with ErrApprovalPending when wait runs out.

Before each attempt to redeem, the first and every one after a wake-up, it authenticates raw again through the store, so a token, agent, or session tree revoked during the wait gets ErrUnauthenticated and the approval stays unspent. A token bound to a key isn't asked for a second proof: the request proved the key when it first authenticated. On success it returns the agent's principal from that last check; run the operation as that principal.

A decision made through this Service wakes the wait at once; a decision made by another process that shares the store, a revocation, and an expiry are found within 2 seconds. An agent holds at most MaxApprovalWaitsPerAgent waits and the Service at most MaxApprovalWaits; a wait over either limit returns ErrApprovalPending without waiting.

func (*Service) RefreshChallenge

func (s *Service) RefreshChallenge(ctx context.Context, bindingID string) (string, error)

RefreshChallenge returns a fresh challenge for refreshing bindingID, which the refresh proof must carry. It returns ErrDeviceProof for a binding that doesn't exist or is no longer its session's binding.

func (*Service) RefreshDevice

func (s *Service) RefreshDevice(ctx context.Context, bindingID, proof string) (Token, Principal, error)

RefreshDevice checks proof, the refresh JWT signed by the key bound to binding and carrying a challenge from Service.RefreshChallenge for it, and reissues the bound session's token. It returns ErrDeviceProof for any failure, and ErrUnauthenticated when the session has ended.

func (*Service) RefreshGrant

func (s *Service) RefreshGrant(ctx context.Context, raw string, spec GrantSpec) (Grant, error)

RefreshGrant exchanges a refresh token for a new access token and a new refresh token. The old refresh token keeps working for Policy.RotateGrace, so that a retry after a lost response succeeds only as a conflict; presenting it after that revokes the grant and every access token issued under it.

spec.Client must be the client the refresh token was issued to, and spec.Scopes must be a subset of its scopes. Every failure matches ErrUnauthenticated except a concurrent refresh, which returns ErrRotateConflict, a scope or lifetime the grant doesn't allow, and store failures.

func (*Service) RegisterAgent

func (s *Service) RegisterAgent(ctx context.Context, r SignupRequest) (Registration, error)

RegisterAgent signs up an agent with no human. It returns the agent's token for a signup session held to the sandbox, and a single-use claim code for the human who will claim it with Service.ClaimAgent. The agent is deleted at Agent.ClaimBy unless it is claimed first.

It asks the limiter first, as "agent.register" keyed on the client only, then runs, in order, CheckWork, the type rules, Admit, the quotas set with WithQuota, and MaxUnclaimed. Every rejection returns an error matching ErrSignupRejected and records an access_denied event; a quota refusal also matches ErrQuotaExceeded.

func (*Service) RegistrationChallenge

func (s *Service) RegistrationChallenge(ctx context.Context, p Principal) (string, error)

RegistrationChallenge returns a fresh challenge for binding the session behind p, which the registration proof must carry. It refuses a session that is already bound, so a stolen cookie can't move the session to another key. The challenge works once and expires after 5 minutes.

func (*Service) RequestApproval

func (s *Service) RequestApproval(ctx context.Context, agent Principal, act Action, need Need) (Approval, error)

RequestApproval records a request from agent for its human to approve act, for example after the agent got a human_required refusal. Show the person the approval with Service.Approval, let them approve with a passkey through passkey.Passkeys.BeginApproval, and have the agent retry with Service.RedeemApproval. An unclaimed agent can't ask.

need is what the action requires. The agent must meet every part of it that doesn't need a person (its scopes and the recovery hold), and the approving human must meet all of it.

While the agent has a pending, unexpired approval for an action with the same digest under a need with the same action, RequestApproval returns that approval instead of a new one, and records nothing: an agent that asks again doesn't ask its person again.

func (*Service) Require

func (s *Service) Require(ctx context.Context, p Principal, n Need) error

Require checks p against n after WithNeeds tightened it, and returns nil or a *Refusal. Every refusal is recorded as an EventAccessDenied with n.Action as its action. The checks run in order: Human, then Scopes, then Assurance, then Within, and the first that fails names the refusal, so the remedy it offers is the one that can work.

func (*Service) RequireAgentPart

func (s *Service) RequireAgentPart(ctx context.Context, p Principal, n Need) error

RequireAgentPart checks p against AgentPart of n after WithNeeds tightened n, and returns nil or a *Refusal as Service.Require does. It tightens n first and strips the parts only a person can meet second, so the agent meets the scopes and the recovery hold of the floor, but a floor that marks the action Human doesn't refuse it. Use it before you ask for or redeem an approval yourself. Don't pass AgentPart(n) to Service.Require: Require tightens again and puts the Human floor back.

func (*Service) Revoke

func (s *Service) Revoke(ctx context.Context, id SessionID) error

Revoke revokes a session and every session delegated from it. There is no way to revoke a session without its descendants.

func (*Service) RevokeAgent

func (s *Service) RevokeAgent(ctx context.Context, id AgentID) error

RevokeAgent disables the agent, so no new sessions can be delegated to it, and revokes all of its sessions, in one transaction.

func (*Service) RevokeConnection

func (s *Service) RevokeConnection(ctx context.Context, who Principal, id SessionID) error

RevokeConnection revokes one connection of the human behind who, and every token issued under it, at once. The user's other connections stay, those of the same client included. who must be a human session; it needn't be fresh, because revoking only takes access away. An ID that isn't one of who's live connections returns ErrNotFound.

func (*Service) RevokeLeaked

func (s *Service) RevokeLeaked(ctx context.Context, raw, source string) (bool, error)

RevokeLeaked handles a token that a secret scanner found in public, for example in a commit. When raw is a token this service issued, it revokes the token's session and every session delegated from it, records a token_leaked event with source, and returns true. It does so whether the token is current, rotated out, expired, or already revoked: a rotated-out token in public means the session's tokens are exposed, and an expired parent can still have live delegated sessions.

A leaked agent claim code (KindClaimCode) lets anyone who finds it claim the agent. RevokeLeaked deletes the unclaimed agent that holds it, with every session of the agent, records token_leaked with the agent and source, and returns true. The agent has to sign up again. A code that was already used, or whose agent expired, matches nothing.

For anything else, such as a malformed token, a token of another brand, or a well-formed token that no session holds, RevokeLeaked returns false and records nothing, because nothing changed. A store failure returns an error and no result.

Only call it with reports whose origin you verified, for example with package leakscan. A leak report isn't a use of the token: it doesn't update the session's last use and isn't rate limited.

func (*Service) RevokeOthers

func (s *Service) RevokeOthers(ctx context.Context, by Principal) (int, error)

RevokeOthers revokes every human session, personal access token, and OAuth grant of by's account except by's own session and what is delegated from it, after checking NeedRevokeOthers. Agents keep working through sessions delegated from by's session. It returns how many sessions it revoked.

func (*Service) RevokeOwn

func (s *Service) RevokeOwn(ctx context.Context, by Principal, id SessionID) error

RevokeOwn revokes one of by's own sessions, and everything delegated from it, after checking NeedRevokeOwn. It returns ErrNotFound for a session that doesn't exist or isn't by's, so it never confirms another account's session. The bare Service.Revoke is for administrators.

A session in recovery mode may revoke only itself and what is delegated from it. For any other session it checks NeedRevokeOthers, which refuses recovery mode, so a stolen recovery code can't sign the person out of the devices that could undo the recovery.

func (*Service) RevokeOwnAgent

func (s *Service) RevokeOwnAgent(ctx context.Context, by Principal, id AgentID) error

RevokeOwnAgent disables one of by's agents and revokes its sessions, after checking NeedRevokeOwn. It returns ErrNotFound for an agent that doesn't exist or belongs to someone else. The bare Service.RevokeAgent is for administrators.

func (*Service) RevokeUser

func (s *Service) RevokeUser(ctx context.Context, u UserID) error

RevokeUser revokes every session of u, human and agent.

func (*Service) Rotate

func (s *Service) Rotate(ctx context.Context, raw string) (Token, error)

Rotate replaces a human session's token and returns the new one. The old token keeps working for Policy.RotateGrace; after that, presenting it revokes the whole session tree. Call it on scope changes and periodically for browser sessions. Service.StepUp rotates too.

func (*Service) Run

func (s *Service) Run(ctx context.Context)

Run does the service's background work once per FailureLimits window until ctx ends: it writes queued failure events, so summaries and retries don't wait for the next failure, seals new audit events into the hash chain (Service.SealAudit), and, when the store is a SignupStore, deletes unclaimed agents past their deadline (Service.ExpireUnclaimed). When ctx ends, it flushes failures, seals once more, and returns.

Start it in its own goroutine for the life of the service, on every server, for example go svc.Run(ctx). Without it, a crash can lose up to one window of over-limit counts, unclaimed agents are never deleted, and audit events stay unsealed until something calls SealAudit. Service.VerifyAudit can't detect a change to, or the deletion of, an unsealed event; Service.UnsealedAudit reports how many there are.

func (*Service) Runtime

func (s *Service) Runtime() Runtime

Runtime returns the service's Runtime.

func (*Service) SealAudit

func (s *Service) SealAudit(ctx context.Context) (int, error)

SealAudit seals every committed event that isn't sealed yet into the hash chain, and returns how many it sealed. It is safe to call from several servers at once: the store serializes sealers. Service.Run calls it once a minute.

func (*Service) SessionTree

func (s *Service) SessionTree(ctx context.Context, u UserID) ([]SessionNode, error)

SessionTree returns u's live sessions as a tree for a "where you're signed in" page: each root is a device's human session, a personal access token, or an OAuth grant, and its children are the agent sessions delegated from it, at any depth. Roots are newest first; children are oldest first. Revoking a root with Service.RevokeOwn revokes its whole branch.

func (*Service) Sessions

func (s *Service) Sessions(ctx context.Context, u UserID) ([]SessionInfo, error)

Sessions lists every session of u, including revoked and expired ones that have not been pruned.

func (*Service) SetSignupOverride

func (s *Service) SetSignupOverride(ctx context.Context, who Principal, o SignupOverride, version int64) (int64, error)

SetSignupOverride replaces the override with o, if the stored version is still version, and returns the new version. who must be a human who authenticated within SignupOverrideFreshFor with more than one factor. It returns ErrWidens when o would widen the code policy, ErrConflict when someone changed the override since version, and ErrStepUpRequired when who isn't fresh and multi-factor.

func (*Service) Setup

func (s *Service) Setup(ctx context.Context, u UserID) (Setup, error)

Setup reads what u's account has toward a full session. A store that isn't a FactorStore holds no factors.

func (*Service) SignupCodeSettings

func (s *Service) SignupCodeSettings() SignupSettings

SignupCodeSettings returns the signup policy as set in code, before any override: the most an override can allow.

func (*Service) SignupOverrideNow

func (s *Service) SignupOverrideNow(ctx context.Context) (SignupOverride, int64, error)

SignupOverrideNow returns the stored override and its version, read from the store.

func (*Service) SignupOverridesOn

func (s *Service) SignupOverridesOn() bool

SignupOverridesOn reports whether the service applies a stored SignupOverride.

func (*Service) SignupSettings

func (s *Service) SignupSettings(ctx context.Context) SignupSettings

SignupSettings returns the signup policy in effect, with defaults filled in and any SignupOverride applied. Admin tools show it; it never contains secrets.

func (*Service) StartSession

func (s *Service) StartSession(ctx context.Context, u UserID, o StartOptions) (Token, Principal, error)

StartSession creates a human session for u. Call it after the application has authenticated the human.

func (*Service) StepUp

func (s *Service) StepUp(ctx context.Context, raw string, proofs ...Proof) (Token, Principal, error)

StepUp records that the human behind a session just proved who they are again, for example before a sensitive action. It checks the proofs, rotates the token, sets the session's AuthenticatedAt to the latest proof, and adds the proofs' methods, all in one store operation. It returns the new token, which the client must use from now on.

Only the new token is elevated: the rotated-out token keeps its old AuthenticatedAt during its grace window, and agent sessions delegated earlier are unchanged. StepUp rejects agent sessions with ErrNotRotatable, and a token that is already rotated out with ErrRotateConflict. It rejects a MethodFederated proof with ErrInvalidInput, because a sign-in through an external identity provider never makes a session fresh. It refuses proofs that are all MethodPassword with a *Refusal that has CodeStrongerFactorRequired when the account has a passkey or a confirmed TOTP factor, because a password never stands in for a stronger factor.

func (*Service) UnbindDevice

func (s *Service) UnbindDevice(ctx context.Context, bindingID, proof string) (Token, Principal, error)

UnbindDevice ends a binding when DBSC is turned off. It checks proof like Service.RefreshDevice, deletes the binding, and reissues the session's token, which from then on works for the session's whole lifetime. Without a valid proof nothing changes: the binding ID isn't a secret, and a stolen short-lived cookie must not become a long-lived one. It returns ErrUnauthenticated when the session has ended.

The session can't be bound again: it keeps its record of the one binding offer it got.

func (*Service) UndoRecovery

func (s *Service) UndoRecovery(ctx context.Context, by Principal, recovered SessionID) (UndoResult, error)

UndoRecovery reverses a recovery sign-in that the person behind by says wasn't them. by must meet NeedUndoRecovery and come from a session that started before the recovery and never used a recovery code. In one call it:

  • revokes the recovered session and every session, personal access token, and OAuth grant of the account created since, except by's own session
  • disables every agent created or claimed since
  • removes every passkey and TOTP factor added since
  • deletes a password set or changed since, and an address added or changed since, when the store is an EmailStore
  • deletes the account's remaining recovery codes, which may have leaked together; generate a new set from by's session next

It lifts the recovery hold, unless another recovery inside the hold remains. It returns ErrNotFound when recovered isn't one of Service.RecoverySignIns, and ErrUndoNotAllowed when by's session is too new.

func (*Service) UnsealedAudit

func (s *Service) UnsealedAudit(ctx context.Context) (int, time.Time, error)

UnsealedAudit returns how many committed events aren't sealed into the hash chain yet, and when the oldest of them was recorded, or the zero time when every event is sealed. Service.VerifyAudit can't detect a change to these events. A count that keeps growing, or an oldest time more than a few windows old, means nothing runs Service.Run or Service.SealAudit. Like VerifyAudit, it reads every event.

func (*Service) User

func (s *Service) User(ctx context.Context, u UserID) (UserSummary, error)

User returns the summary of one user, or ErrNotFound when the user has no stored session and owns no agent.

func (*Service) Users

func (s *Service) Users(ctx context.Context, f UserFilter) ([]UserSummary, error)

Users returns a summary of every user who has a stored session or owns an agent, ordered by ID. A zero Limit means 100; the maximum is 1,000. To page, pass the last user's ID as f.After.

The library knows users only through their sessions and agents, so a user whose sessions were all pruned and who owns no agent is absent. The application's own user directory is the source of truth for accounts.

func (*Service) VerifyAudit

func (s *Service) VerifyAudit(ctx context.Context, checkpoints ...ChainHead) (ChainHead, error)

VerifyAudit recomputes the hash chain from the start and returns its head. Each checkpoint must match the chain at its position, so a chain rebuilt by someone without the checkpoint key fails. It returns an error matching ErrAuditTampered at the first mismatch.

VerifyAudit covers only sealed events. An event is sealed when Service.SealAudit runs, which Service.Run does once per window, so keep Run running. Until then, a change to the event, or its deletion, is undetectable, and VerifyAudit still succeeds. VerifyAudit doesn't seal: sealing would add events it can't vouch for to the chain. To see what it doesn't cover, call Service.UnsealedAudit.

type SessionFilter

type SessionFilter struct {
	// Kinds keeps only these kinds. Empty keeps every kind.
	Kinds []SessionKind
	// Live keeps only sessions that aren't revoked or past their absolute
	// expiry.
	Live bool
	// Agent keeps only sessions of this agent.
	Agent AgentID
}

SessionFilter narrows Service.ListSessions.

type SessionID

type SessionID string

SessionID identifies a session. It is not a secret.

type SessionInfo

type SessionInfo struct {
	ID         SessionID
	Kind       SessionKind
	Agent      AgentID
	Parent     SessionID
	Name       string // personal access tokens only
	Client     string // OAuth tokens only
	Depth      int
	Scopes     []string
	CreatedAt  time.Time
	LastSeenAt time.Time
	ExpiresAt  time.Time
	RevokedAt  time.Time
	// AuthenticatedAt is when the human last proved who they are,
	// inherited by delegated sessions.
	AuthenticatedAt time.Time
	// Methods lists how the human proved who they are, sorted.
	Methods []Method
	// IdleTimeout is how long the session may go unused before it stops
	// working.
	IdleTimeout time.Duration
	// KeyThumbprint is the thumbprint of the key the session is bound to,
	// or empty. See [DelegateSpec].
	KeyThumbprint string
	// Device and UserAgent describe where a human session signed in, from
	// [StartOptions].
	Device    string
	UserAgent string
	// RotatedAt is when the current token was issued.
	RotatedAt time.Time
	// Resource is the resource an OAuth token is for, or empty.
	Resource string
}

SessionInfo describes a session for display, for example on a "your sessions" page. It contains no secrets.

func (*SessionInfo) State

func (i *SessionInfo) State(now time.Time) SessionState

State reports whether the session is revoked, past its absolute expiry, idle for longer than its IdleTimeout, or live, at now. It matches the checks of Service.Authenticate.

type SessionKind

type SessionKind uint8

SessionKind says what a session is: a human's sign-in, an agent's delegated session, or a token issued to a script or an OAuth client.

const (
	SessionHuman SessionKind = iota + 1
	SessionAgent
	// SessionPAT is a personal access token, created with
	// [Service.CreatePAT].
	SessionPAT
	// SessionOAuth is an OAuth access token, created with [Service.Grant]
	// or [Service.RefreshGrant].
	SessionOAuth
	// SessionRefresh is an OAuth refresh token. It never authenticates a
	// request; it only obtains new access tokens.
	SessionRefresh
)

Session kinds. Only SessionHuman sessions rotate, step up, or count as fresh.

type SessionNode

type SessionNode struct {
	Session  SessionInfo
	Children []SessionNode
}

SessionNode is a live session and the live sessions delegated from it.

type SessionRecord

type SessionRecord struct {
	ID     SessionID
	Kind   SessionKind
	User   UserID
	Agent  AgentID
	Parent SessionID
	// Name is the name of a personal access token, or empty.
	Name string
	// Client is the OAuth client of an OAuth token, or empty.
	Client          string
	Depth           int
	Scopes          []string
	CreatedAt       time.Time
	AuthenticatedAt time.Time
	Methods         []Method
	LastSeenAt      time.Time
	IdleTimeout     time.Duration
	ExpiresAt       time.Time
	RevokedAt       time.Time // zero while live

	CurrentHash        [32]byte
	PreviousHash       [32]byte // zero when there is none
	PreviousValidUntil time.Time
	// PreviousAuthenticatedAt is the AuthenticatedAt that the previous token
	// carries during its grace window, so stepping up elevates only the new
	// token.
	PreviousAuthenticatedAt time.Time
	// PreviousMethods is the Methods that the previous token carries during
	// its grace window.
	PreviousMethods []Method
	// KeyThumbprint is the RFC 7638 JWK SHA-256 thumbprint, base64url
	// without padding, of the key an agent session is bound to, or empty
	// for an unbound session. See [DelegateSpec].
	KeyThumbprint string
	// Device labels the device the session signed in from, for example
	// "Chrome on macOS", and UserAgent is the user agent it came from, at
	// most 256 bytes. Both are empty for sessions that didn't record them.
	Device    string
	UserAgent string
	// RotatedAt is when the current token was issued: the session's start,
	// or its last rotation or step-up.
	RotatedAt time.Time
	// Resource is the resource (RFC 8707) an OAuth grant and its tokens
	// are for, such as an MCP server's URI, or empty. See
	// [GrantSpec.Resource].
	Resource string
}

SessionRecord is the stored form of a session. Only Store implementations should handle it directly; applications use Principal and SessionInfo.

type SessionState

type SessionState string

SessionState says whether a session can still be used.

const (
	SessionRevoked SessionState = "revoked"
	SessionExpired SessionState = "expired"
	SessionIdle    SessionState = "idle"
	SessionLive    SessionState = "live"
)

Session states, in the order SessionInfo.State checks them.

type Setup

type Setup struct {
	// Passkeys is how many passkeys the account has.
	Passkeys int `json:"passkeys"`
	// TOTP is true for a confirmed TOTP factor that isn't locked.
	TOTP bool `json:"totp"`
	// RecoveryCodes is how many unused recovery codes the account has.
	RecoveryCodes int `json:"recovery_codes"`
	// RecoveryConfirmed is true when the person typed back one of the
	// current set's codes.
	RecoveryConfirmed bool `json:"recovery_confirmed"`
}

Setup is what an account has toward a full session under a RecoveryGate, and toward the offers of a preset.

func (Setup) RecoveryPath

func (s Setup) RecoveryPath(requireCodes bool) bool

RecoveryPath reports whether the account can recover: confirmed unused recovery codes, or, unless requireCodes, two second factors.

func (Setup) SecondFactor

func (s Setup) SecondFactor() bool

SecondFactor reports whether the account has a passkey or a usable TOTP factor.

type SignupClaim

type SignupClaim struct {
	// CodeHash is the SHA-256 of the claim code.
	CodeHash [32]byte
	// PickupHash becomes the token hash of the session that ClaimAgent
	// inserts, until the agent collects its new token.
	PickupHash [32]byte
}

SignupClaim is the stored claim state of an unclaimed agent.

type SignupOverride

type SignupOverride struct {
	// Paused stops new signups. Agents already signed up keep working.
	Paused bool `json:"paused,omitempty"`
	// MaxUnclaimed lowers the quota. Zero keeps the code value.
	MaxUnclaimed int `json:"max_unclaimed,omitempty"`
	// ClaimWindow shortens how long new unclaimed agents live. Zero keeps
	// the code value.
	ClaimWindow time.Duration `json:"claim_window,omitempty"`
	// Scopes, when not nil, replaces the sandbox with these scopes, which
	// must be in the code sandbox. An empty, non-nil list empties it.
	Scopes []string `json:"scopes"`
	// DenyTypes adds agent types to the code deny list.
	DenyTypes []string `json:"deny_types,omitempty"`
	// RequireVerifiedType, when true, requires verified agent types even if
	// the code policy doesn't.
	RequireVerifiedType bool `json:"require_verified_type,omitempty"`
}

SignupOverride narrows the signup policy set in code, at runtime, from the store. It can only narrow: it can pause signup, lower the quota, shorten the claim window, take scopes out of the sandbox, deny more agent types, and require verified types. It can't turn signup on, widen anything, or change the hooks, which are code. A compromised admin can therefore stop signups but never open them up.

The zero SignupOverride changes nothing. Turn overrides on with WithSignupOverrides.

type SignupPolicy

type SignupPolicy struct {
	// Scopes is the sandbox: the most any session of an unclaimed agent
	// can hold, for example only the agent's own private repositories. The
	// library checks it on every Authenticate, so narrowing it takes effect
	// at once. It can be empty: the agent then holds no scopes until it is
	// claimed.
	Scopes []string
	// ClaimWindow is how long an unclaimed agent lives. After it, the agent
	// and every session it holds are deleted. Zero means 7 days; the
	// maximum is 30 days.
	ClaimWindow time.Duration
	// SessionIdle ends an unclaimed agent's signup session after this long
	// without use. Zero means 24 hours, or ClaimWindow when that is
	// shorter. It can't exceed ClaimWindow.
	SessionIdle time.Duration
	// MaxUnclaimed caps how many unclaimed agents the store holds. Zero
	// means 10,000.
	MaxUnclaimed int
	// DenyTypes rejects agents that report one of these types.
	DenyTypes []string
	// AllowTypes, when not empty, admits only agents that report one of
	// these types. A reported type is an unverified label, so an allow or
	// deny list is only as strong as the proof behind it: set Verifier and
	// RequireVerifiedType to make it a security control.
	AllowTypes []string
	// RequireVerifiedType rejects agents whose type the Verifier didn't
	// verify.
	RequireVerifiedType bool
	// Verifier checks vendor attestations of an agent's type. Without one,
	// no type is ever verified.
	Verifier TypeVerifier
	// CheckWork, when set, verifies a proof of work in the request before
	// the other policy checks. A non-nil error rejects the request.
	CheckWork func(ctx context.Context, r SignupRequest) error
	// Admit, when set, makes the final decision on each request, for
	// example by agent type. A non-nil error rejects the request.
	Admit func(ctx context.Context, r SignupRequest) error
}

SignupPolicy turns on agent self-signup and sets its rules. See WithSignup and docs/design/agent-signup.md.

type SignupRequest

type SignupRequest struct {
	// Name is shown to humans, for example on the claim page.
	Name string
	// Type is the agent type the agent reports, for example "claude-code".
	// It is lowercased and must be up to 64 characters of a-z, 0-9, '.',
	// '_', and '-'. Empty means "unknown".
	Type string
	// Attestation is optional vendor proof of Type, passed to the
	// TypeVerifier.
	Attestation []byte
	// Work is an optional proof of work, passed to CheckWork.
	Work string
	// Scopes narrows the sandbox for this agent. Empty means the whole
	// sandbox.
	Scopes []string
	// KeyThumbprint binds the signup session to the agent's public key, as
	// in [DelegateSpec]. It is required under [RequireAgentKeys].
	KeyThumbprint string
}

SignupRequest is an agent's request to sign itself up.

type SignupSettings

type SignupSettings struct {
	// Enabled is false when the service has no signup policy.
	Enabled bool
	// Paused is true when an override stopped new signups, or the service
	// hasn't loaded the override yet.
	Paused              bool
	Scopes              []string
	ClaimWindow         time.Duration
	SessionIdle         time.Duration
	MaxUnclaimed        int
	AllowTypes          []string
	DenyTypes           []string
	RequireVerifiedType bool
	HasVerifier         bool
	HasWorkCheck        bool
	HasAdmit            bool
}

SignupSettings describes the signup policy in effect, as data. It leaves out the hooks, which are code, and says only whether each is set.

type SignupSettingsStore

type SignupSettingsStore interface {
	// SignupOverride returns the stored override and its version, or the
	// zero override and version 0 when none is stored.
	SignupOverride(ctx context.Context) (SignupOverride, int64, error)
	// PutSignupOverride stores o as version+1, but only if the stored
	// version is version; otherwise it returns ErrConflict. It records ev,
	// with Count set to the new version, in the same transaction, and
	// returns the new version.
	PutSignupOverride(ctx context.Context, o SignupOverride, version int64, ev Event) (int64, error)
}

SignupSettingsStore is implemented by stores that keep a SignupOverride. memstore, sqlitestore, and pgstore implement it.

type SignupStore

type SignupStore interface {
	// InsertSignup stores the unclaimed agent a, its claim state c, and its
	// signup session rec, together with ev, but only while the store holds
	// fewer than maxUnclaimed unclaimed agents, checked atomically with the
	// insert; otherwise it returns [ErrQuotaExceeded].
	InsertSignup(ctx context.Context, a Agent, c SignupClaim, rec SessionRecord, maxUnclaimed int, ev Event) error

	// ClaimAgent finds the enabled, unclaimed agent whose claim code hash is
	// code and whose ClaimBy is after c.At, and in one transaction: sets its
	// Owner, Scopes, and ClaimedAt from c; deletes its claim state, so the
	// code works once; revokes every session of the agent, and every
	// session delegated from one of them, at c.At; and inserts rec, with
	// rec.Agent set to the agent and rec.CurrentHash set to its pickup hash.
	// It checks rec.Parent as InsertSession does. It returns ErrNotFound
	// when no agent matches, and [ErrQuotaExceeded], changing nothing, when
	// c.MaxOwned is positive and Owner already owns that many enabled
	// agents, counted atomically with the claim. The stored event gets Agent set to the agent
	// and Count set to the number of sessions revoked; the returned int is
	// that number.
	ClaimAgent(ctx context.Context, code [32]byte, c Claim, rec SessionRecord, ev Event) (Agent, int, error)

	// ExpireUnclaimed deletes up to limit unclaimed agents whose ClaimBy is
	// at or before now, oldest deadline first. Each agent is deleted with
	// its claim state and every session of it, in one transaction, with an
	// event built from ev with Agent set to the agent and Count to the
	// number of sessions deleted. It returns the events it stored.
	ExpireUnclaimed(ctx context.Context, now time.Time, limit int, ev Event) ([]Event, error)

	// DeleteSignup finds the unclaimed agent whose claim code hash is code,
	// whatever its deadline or state, and deletes it with its claim state
	// and every session of it, in one transaction, with ev stored with
	// Agent set to the agent and Count to the number of sessions deleted.
	// It returns the deleted agent and that number, or ErrNotFound when no
	// unclaimed agent holds the code.
	DeleteSignup(ctx context.Context, code [32]byte, ev Event) (Agent, int, error)

	// AgentByClaimCode returns the unclaimed agent whose claim code has
	// hash code, without changing anything, or [ErrNotFound].
	AgentByClaimCode(ctx context.Context, code [32]byte) (Agent, error)
}

SignupStore persists self-signed-up agents. Implementations must make each method atomic, record events in the same transaction as the change, and pass storetest.RunSignup.

type StartOptions

type StartOptions struct {
	// Scopes the session holds. Delegated sessions can only narrow them.
	Scopes []string
	// AuthenticatedAt is when the human proved who they are. Zero means now.
	// Don't set it together with Proofs.
	AuthenticatedAt time.Time
	// Proofs record how the human signed in, as returned by factor packages.
	// Each must be for the same user and at most MaxProofAge old. The
	// session's Methods and AuthenticatedAt come from them.
	Proofs []Proof
	// Device labels the device, for example "Chrome on macOS", at most 128
	// bytes, and UserAgent is the request's user agent, cut to 256 bytes.
	// People see them on their list of sessions. authhttp.SignIn sets both
	// from the request.
	Device    string
	UserAgent string
	// Bridged starts a session for a sign-in that the application
	// performed with its own login, as authhttp.Bridge does. The
	// session's Methods hold [MethodBridged] next to the methods of
	// Proofs, which makes it [Principal.BridgedOnly] unless a proof is a
	// stronger factor. Without Proofs, AuthenticatedAt is required: the
	// session is never fresher than the application's sign-in.
	Bridged bool
	// MaxAge, when positive, ends the session MaxAge after it starts,
	// before the policy's HumanMax.
	MaxAge time.Duration
}

StartOptions configures Service.StartSession.

type Store

type Store interface {
	// InsertSession stores a new session. If r.Parent is set, the insert
	// must fail with ErrParentInactive when the parent is missing or
	// revoked, checked atomically with the insert. If r.Agent is set, it
	// must fail with ErrAgentInactive when the agent is missing or disabled,
	// also atomically.
	InsertSession(ctx context.Context, r SessionRecord, ev Event) error

	// SessionByHash finds the session whose current, previous, or retired
	// token hash is h, and says which one matched. It returns ErrNotFound
	// when nothing matches.
	SessionByHash(ctx context.Context, h [32]byte) (SessionRecord, HashMatch, error)

	// Touch records that the session was used at seen. It never moves
	// LastSeenAt backwards. It returns ErrNotFound for an unknown session.
	// Touch is not audited.
	Touch(ctx context.Context, id SessionID, seen time.Time) error

	// SwapToken replaces the current hash with swap.Next, but only if it
	// still equals swap.Old (compare-and-swap); otherwise it returns
	// ErrRotateConflict. On success the old hash becomes the previous hash,
	// valid until swap.GraceUntil, and any earlier previous hash is retired.
	// The session's AuthenticatedAt and Methods move to
	// PreviousAuthenticatedAt and PreviousMethods; AuthenticatedAt is then
	// replaced by swap.AuthenticatedAt when that is set, and Methods by
	// swap.Methods when that is non-nil.
	SwapToken(ctx context.Context, id SessionID, swap Swap, ev Event) error

	// RevokeTree revokes the session and every session delegated from it,
	// at any depth, at ev.At, and returns how many were newly revoked. It
	// returns ErrNotFound when the root does not exist. The stored event
	// gets Count set to the result, and User set to the root's user when
	// ev.User is empty.
	RevokeTree(ctx context.Context, root SessionID, ev Event) (int, error)

	// RevokeUser revokes every live session of u, and every session
	// delegated from one of them, at ev.At, and returns how many were newly
	// revoked. The stored event gets Count set to the result.
	RevokeUser(ctx context.Context, u UserID, ev Event) (int, error)

	// RevokeAgent disables the agent, so InsertSession rejects new sessions
	// for it, and revokes every live session of the agent and every session
	// delegated from one of them, all at ev.At and in one transaction. It
	// returns how many sessions were newly revoked, or ErrNotFound for an
	// unknown agent. The stored event gets Count set to the result, and User
	// set to the agent's owner when ev.User is empty.
	RevokeAgent(ctx context.Context, id AgentID, ev Event) (int, error)

	// InsertAgent stores a new agent. When maxOwned is positive, it stores
	// the agent only while a.Owner owns fewer than maxOwned enabled agents,
	// counted atomically with the insert, so concurrent inserts can't pass
	// the cap together; otherwise it returns [ErrQuotaExceeded].
	InsertAgent(ctx context.Context, a Agent, maxOwned int, ev Event) error

	// Agent returns the agent with the given ID, or ErrNotFound.
	Agent(ctx context.Context, id AgentID) (Agent, error)

	// ListSessions returns every session, live or not, whose User is u.
	ListSessions(ctx context.Context, u UserID) ([]SessionRecord, error)

	// DeleteExpired deletes sessions whose ExpiresAt is before the given
	// time, and returns how many were deleted. It doesn't delete audit
	// events.
	DeleteExpired(ctx context.Context, before time.Time) (int, error)

	// ListEvents returns audit events matching f in ascending Seq order,
	// or descending when f.Descending is set.
	ListEvents(ctx context.Context, f EventFilter) ([]Event, error)

	// RecordEvent appends an event that describes no change, such as a
	// failed attempt.
	RecordEvent(ctx context.Context, ev Event) error

	// SealEvents adds unsealed events to the audit hash chain. In one
	// transaction, serialized against every other SealEvents call, it reads
	// the chain head and up to limit unsealed events in Seq order, calls
	// seal with them, and stores the links seal returns. It returns how
	// many events it sealed. Events read back must have the same field
	// values that ListEvents returns, because the chain hashes them.
	SealEvents(ctx context.Context, limit int, seal func(head ChainHead, evs []Event) ([]ChainLink, error)) (int, error)

	// ChainEvents returns up to limit sealed events with Pos greater than
	// after, in Pos order.
	ChainEvents(ctx context.Context, after int64, limit int) ([]Event, error)

	// ListUsers returns a summary of every user who has a stored session
	// or owns an agent, ordered by UserID, with IDs greater than f.After,
	// at most f.Limit. A session counts as live when it isn't revoked and
	// now is before its ExpiresAt.
	ListUsers(ctx context.Context, f UserFilter, now time.Time) ([]UserSummary, error)

	// ListAgents returns agents ordered by ID, with IDs greater than
	// f.After, at most f.Limit, owned by f.Owner when it's set, only
	// unclaimed ones when f.Unclaimed is set, and only disabled ones when
	// f.Disabled is set. It also returns unclaimed
	// agents' fields, such as ClaimBy.
	ListAgents(ctx context.Context, f AgentFilter) ([]Agent, error)

	// Counts returns totals for an admin overview. A session is live as
	// for ListUsers. EventsSince counts events with At at or after since.
	Counts(ctx context.Context, now, since time.Time) (Counts, error)
}

Store persists sessions, agents, and the audit log. Implementations must make each method atomic. Package storetest checks the contract; every implementation must pass storetest.Run.

Hashes are SHA-256 digests of tokens. A Store never sees a raw token.

Every method that changes sessions or agents takes the Event that describes the change, and must append it to the audit log in the same transaction as the change, so the log never records a change that didn't happen or misses one that did. A method that fails appends nothing.

type Swap

type Swap struct {
	Old, Next  [32]byte
	GraceUntil time.Time
	// At is when the new token is issued; the store records it as the
	// session's RotatedAt.
	At time.Time
	// AuthenticatedAt, when set, replaces the session's AuthenticatedAt.
	AuthenticatedAt time.Time
	// Methods, when non-nil, replaces the session's Methods.
	Methods []Method
}

Swap describes a token rotation for Store.SwapToken.

type TOTPRecord

type TOTPRecord struct {
	User        UserID
	Sealed      []byte
	LastStep    int64
	Failures    int
	CreatedAt   time.Time
	ConfirmedAt time.Time // zero until the first correct code
	DisabledAt  time.Time // zero unless locked after too many failures
}

TOTPRecord is the stored form of a TOTP factor. Sealed is the encrypted secret; the library never stores it in plain text.

type Token

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

Token is a bearer secret returned when a session is created or rotated.

A Token redacts itself everywhere it might leak by accident: fmt verbs, slog, and JSON or text marshaling all print only its prefix. Call Token.Reveal when you deliberately send it to the client.

func (Token) GoString

func (t Token) GoString() string

GoString implements fmt.GoStringer so %#v redacts too.

func (Token) IsZero

func (t Token) IsZero() bool

IsZero reports whether t is the zero Token.

func (Token) LogValue

func (t Token) LogValue() slog.Value

LogValue implements slog.LogValuer.

func (Token) MarshalJSON

func (t Token) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler with the redacted form.

func (Token) MarshalText

func (t Token) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler with the redacted form.

func (Token) Reveal

func (t Token) Reveal() string

Reveal returns the secret. It is the only way to read it.

func (Token) String

func (t Token) String() string

String returns the token prefix followed by "REDACTED".

type ToolCall

type ToolCall struct {
	User     UserID
	Session  SessionID
	Grant    SessionID
	Client   string
	Resource string
	// Tool is the tool's name. It is cut to 128 bytes.
	Tool string
	// Allowed is false for a call refused for missing scopes.
	Allowed bool
	// ArgsSHA256 is the hex SHA-256 of the raw arguments; the arguments
	// themselves are never stored.
	ArgsSHA256 string
}

ToolCall describes one call of an MCP tool, for Service.RecordToolCall.

type TransferStore

type TransferStore interface {
	// ExportUsers calls fn once for each user who has an address, a
	// password, a passkey user handle or credential, a TOTP factor, a
	// recovery code, or an identity, in ascending byte order of the user
	// ID, inside one read-only snapshot, so records written while it runs
	// are either all seen or not seen. It stops at the first error from
	// fn and returns it.
	ExportUsers(ctx context.Context, fn func(UserExport) error) error
	// ExportAgents calls fn for each claimed agent, that is, each agent
	// with an owner, in ascending byte order of the agent ID, inside the
	// same kind of snapshot. Unclaimed agents are left out: they expire on
	// their own.
	ExportAgents(ctx context.Context, fn func(Agent) error) error
	// ImportUsers stores the users and agents of the import in one
	// transaction, and appends ev with Count set to the users stored.
	//
	// Without in.Merge, it returns [ErrTargetNotEmpty] and stores nothing
	// when the store has any address, password, passkey user handle or
	// credential, TOTP factor, recovery code, or identity, and returns
	// [ErrImportConflict] with the conflicts and stores nothing when any
	// record conflicts, for example two users of the import with the
	// same address.
	//
	// An agent is stored only when its owner is a user that this import
	// stores; any other agent is a conflict, [ConflictOwner].
	//
	// With in.Merge, it skips each user with a record that conflicts, and
	// each agent whose ID exists or whose owner it didn't store, and
	// reports them in
	// ImportResult.Skipped. A skipped user's records are all skipped: a
	// record is never overwritten or attached to another user.
	ImportUsers(ctx context.Context, in Import, ev Event) (ImportResult, error)
}

TransferStore reads and writes every sign-in record, for export and import. See the export design in docs/design/export.md. Implementations must pass storetest.RunTransfer.

The records hold credentials: password hashes, sealed TOTP secrets, and recovery code hashes. Only code that writes an encrypted export, or reads one, should call these methods; no HTTP route should.

type TypeVerifier

type TypeVerifier interface {
	// VerifyType reports whether attestation proves agentType. An error is
	// a server error, not a rejection.
	VerifyType(ctx context.Context, agentType string, attestation []byte) (bool, error)
}

TypeVerifier verifies that an agent is the type it says it is, from an attestation signed by its vendor. The library ships no verifier.

type UndoResult

type UndoResult struct {
	// Sessions is how many sessions, tokens, and grants were revoked.
	Sessions int `json:"sessions"`
	// Agents is how many agents were disabled.
	Agents int `json:"agents"`
	// Passkeys is how many passkeys were removed.
	Passkeys int `json:"passkeys"`
	// TOTP is true when a TOTP factor was removed.
	TOTP bool `json:"totp"`
	// Password is true when a password set or changed since was deleted.
	Password bool `json:"password"`
	// Email is true when an address set or changed since was deleted.
	Email bool `json:"email"`
}

UndoResult says what Service.UndoRecovery reversed.

type UserExport

type UserExport struct {
	User     UserID
	Email    *EmailRecord
	Password *PasswordRecord
	// Handle is the passkey user handle, or nil.
	Handle []byte
	// Credentials are ordered by ID, in ascending byte order.
	Credentials []CredentialRecord
	// TOTP holds the sealed secret, as the store holds it.
	TOTP *TOTPRecord
	// RecoveryCodes are the hashes of the unused codes, in ascending byte
	// order.
	RecoveryCodes [][32]byte
	// Identities are ordered by issuer, then subject, in ascending byte
	// order.
	Identities []IdentityRecord
}

UserExport is every sign-in record of one user, for TransferStore. Slices are empty, and pointers nil, for records the user doesn't have.

func (*UserExport) HasSignInRecord

func (u *UserExport) HasSignInRecord() bool

HasSignInRecord reports whether u has any record that TransferStore.ExportUsers exports.

type UserFilter

type UserFilter struct {
	// After returns only users with a greater ID, for paging.
	After UserID
	// Limit is the most users to return. Stores may assume 1 to 1,000.
	Limit int
}

UserFilter selects users for Store.ListUsers and Service.Users.

type UserID

type UserID string

UserID identifies the human responsible for a session. The application chooses its format; the library treats it as opaque.

type UserSummary

type UserSummary struct {
	User UserID
	// LiveSessions counts the user's sessions, human and agent, that
	// aren't revoked or past their absolute expiry. Sessions that are idle
	// count until they're used.
	LiveSessions int
	// Agents counts the enabled agents the user owns.
	Agents int
	// LastSeenAt is the latest LastSeenAt of the user's stored sessions,
	// or zero when there are none.
	LastSeenAt time.Time
}

UserSummary describes a user the library knows about through their sessions and agents. The application owns the user's account.

Directories

Path Synopsis
Package authadmin is an HTTP API for an application's administrators, human or agent.
Package authadmin is an HTTP API for an application's administrators, human or agent.
Package authexport writes and reads the export format: every sign-in record of an install in one age-encrypted JSON Lines file, so people can leave for another install or another product, or move between store kinds, and sign in there as the same user.
Package authexport writes and reads the export format: every sign-in record of an install in one age-encrypted JSON Lines file, so people can leave for another install or another product, or move between store kinds, and sign in there as the same user.
Package authhttp connects an auth.Service to net/http.
Package authhttp connects an auth.Service to net/http.
Package authroutes serves every route the browser client calls, so an app gets passkey and email and password sign-up, sign-in, step-up, TOTP, recovery codes, and sign-out from one call:
Package authroutes serves every route the browser client calls, so an app gets passkey and email and password sign-up, sign-in, step-up, TOTP, recovery codes, and sign-out from one call:
Package authtest checks that an application's routes refuse the principals their needs exclude.
Package authtest checks that an application's routes refuse the principals their needs exclude.
bench
agentbench command
Command agentbench measures how fast coding agents add passkey sign-in to a Go app with this library, and whether what they build works.
Command agentbench measures how fast coding agents add passkey sign-in to a Go app with this library, and whether what they build works.
Package cachestore wraps an auth.Store with a short-lived, in-memory cache of token lookups, so most calls to Authenticate don't reach the database.
Package cachestore wraps an auth.Store with a short-lived, in-memory cache of token lookups, so most calls to Authenticate don't reach the database.
Package client embeds the compiled browser client, so a Go server can serve it without Node: authroutes.Mount serves it under /auth/client/, and a page imports it with
Package client embeds the compiled browser client, so a Go server can serve it without Node: authroutes.Mount serves it under /auth/client/, and a page imports it with
cmd
fidoconformance command
Command fidoconformance serves the passkey package through the REST API that the FIDO Alliance conformance tool's server tests call, so a person can run those tests by hand before a release.
Command fidoconformance serves the passkey package through the REST API that the FIDO Alliance conformance tool's server tests call, so a person can run those tests by hand before a release.
tensile-auth-preset command
Command tensile-auth-preset prints what a preset expands to: every setting, the ASVS level it reaches, what it misses, and its deviations.
Command tensile-auth-preset prints what a preset expands to: every setting, the ASVS level it reaches, what it misses, and its deviations.
tensile-auth-server command
Command tensile-auth-server is the tensile-auth server: the library as one binary that apps in any language use over HTTP.
Command tensile-auth-server is the tensile-auth server: the library as one binary that apps in any language use over HTTP.
Package dpop checks DPoP proofs (RFC 9449), which prove that the caller holds the private key an agent session is bound to.
Package dpop checks DPoP proofs (RFC 9449), which prove that the caller holds the private key an agent session is bound to.
redisreplay
Package redisreplay keeps DPoP proof IDs in Redis or Valkey, so every server that shares the database accepts a proof once.
Package redisreplay keeps DPoP proof IDs in Redis or Valkey, so every server that shares the database accepts a proof once.
replaytest
Package replaytest is a conformance suite for dpop.ReplayCache implementations.
Package replaytest is a conformance suite for dpop.ReplayCache implementations.
examples
agents command
Command agents runs Errands, a web app where households share chores, bills, and errands, and where each person can hand a household to an AI agent.
Command agents runs Errands, a web app where households share chores, bills, and errands, and where each person can hand a household to an AI agent.
agents/cmd/errands command
Command errands is the CLI for the Errands example.
Command errands is the CLI for the Errands example.
ghserver command
Command ghserver is a minimal GitHub-compatible server that the gh CLI can sign in to with "gh auth login --hostname".
Command ghserver is a minimal GitHub-compatible server that the gh CLI can sign in to with "gh auth login --hostname".
mcpserver command
Command mcpserver is an MCP server protected by mcpauth, with the tensile-auth OAuth provider that issues its tokens in the same binary.
Command mcpserver is an MCP server protected by mcpauth, with the tensile-auth OAuth provider that issues its tokens in the same binary.
passkeyapp command
Command passkeyapp is a minimal web application that uses the library for passkey sign-up, sign-in, step-up, and recovery codes.
Command passkeyapp is a minimal web application that uses the library for passkey sign-up, sign-in, step-up, and recovery codes.
quickstart command
Command quickstart is passkey sign-in in one file: run it, open http://localhost:8080, and press Continue.
Command quickstart is passkey sign-in in one file: run it, open http://localhost:8080, and press Continue.
Package federation signs humans in through external identity providers: Google and any other OpenID Connect issuer, with zitadel/oidc, and GitHub, with golang.org/x/oauth2 and GitHub's REST API.
Package federation signs humans in through external identity providers: Google and any other OpenID Connect issuer, with zitadel/oidc, and GitHub, with golang.org/x/oauth2 and GitHub's REST API.
internal
emailcode
Package emailcode issues and redeems single-use codes that an application sends by email, for example to confirm an address or reset a password.
Package emailcode issues and redeems single-use codes that an application sends by email, for example to confirm an address or reset a password.
migrate
Package migrate reads numbered SQL migration files for the store packages.
Package migrate reads numbered SQL migration files for the store packages.
resourceuri
Package resourceuri puts resource indicators (RFC 8707), such as an MCP server's URI, in one canonical form, so that the authorization server and the resource server compare them the same way.
Package resourceuri puts resource indicators (RFC 8707), such as an MCP server's URI, in one canonical form, so that the authorization server and the resource server compare them the same way.
safefetch
Package safefetch fetches small documents from URLs that an attacker may choose, such as OAuth client ID metadata documents, without letting the request reach anything but the public internet.
Package safefetch fetches small documents from URLs that an attacker may choose, such as OAuth client ID metadata documents, without letting the request reach anything but the public internet.
seal
Package seal encrypts small secrets at rest with AES-256-GCM, under a key ring that supports rotation.
Package seal encrypts small secrets at rest with AES-256-GCM, under a key ring that supports rotation.
token
Package token generates, parses and hashes opaque bearer tokens.
Package token generates, parses and hashes opaque bearer tokens.
Package leakscan revokes session tokens that a secret scanner finds in public, such as in a commit, a package, or a log.
Package leakscan revokes session tokens that a secret scanner finds in public, such as in a commit, a package, or a log.
Package mcpauth makes an MCP server built on the official Go SDK (github.com/modelcontextprotocol/go-sdk) a correct OAuth resource server under the MCP authorization specification (revision 2026-07-28).
Package mcpauth makes an MCP server built on the official Go SDK (github.com/modelcontextprotocol/go-sdk) a correct OAuth resource server under the MCP authorization specification (revision 2026-07-28).
Package memstore is an in-memory auth.Store for tests, examples and single-process tools.
Package memstore is an in-memory auth.Store for tests, examples and single-process tools.
Package oauth is an OAuth 2 and OpenID Connect provider for an auth.Service.
Package oauth is an OAuth 2 and OpenID Connect provider for an auth.Service.
Package passkey signs humans in with passkeys (WebAuthn), using go-webauthn.
Package passkey signs humans in with passkeys (WebAuthn), using go-webauthn.
Package password signs humans in with an email address and a password, held to OWASP ASVS 5.0.0: Level 2 in full, and Level 3 where the library can own the requirement.
Package password signs humans in with an email address and a password, held to OWASP ASVS 5.0.0: Level 2 in full, and Level 3 where the library can own the requirement.
pwned
Package pwned checks passwords against the Have I Been Pwned range API, for password.Config.Breached.
Package pwned checks passwords against the Have I Been Pwned range API, for password.Config.Breached.
Package pgstore is an auth.Store backed by PostgreSQL, using pgx v5.
Package pgstore is an auth.Store backed by PostgreSQL, using pgx v5.
Package preset gives a complete, explicit configuration in one line.
Package preset gives a complete, explicit configuration in one line.
Package ratelimit is a ready-made auth.Limiter.
Package ratelimit is a ready-made auth.Limiter.
limittest
Package limittest is a conformance suite for ratelimit.Backend implementations.
Package limittest is a conformance suite for ratelimit.Backend implementations.
redislimit
Package redislimit keeps ratelimit counters in Redis or Valkey, using go-redis/redis_rate.
Package redislimit keeps ratelimit counters in Redis or Valkey, using go-redis/redis_rate.
Package recovery issues and redeems recovery codes: one-time codes a human keeps offline to sign in when they lose their passkeys.
Package recovery issues and redeems recovery codes: one-time codes a human keeps offline to sign in when they lose their passkeys.
Package server is the tensile-auth server: the library packaged as one binary, so apps in any language can use it over HTTP.
Package server is the tensile-auth server: the library packaged as one binary, so apps in any language can use it over HTTP.
Package sqlitestore is an auth.Store backed by SQLite, for local and small installs.
Package sqlitestore is an auth.Store backed by SQLite, for local and small installs.
Package storetest is the conformance suite for auth.Store implementations.
Package storetest is the conformance suite for auth.Store implementations.
Package totp adds time-based one-time passwords (RFC 6238) as a second factor.
Package totp adds time-based one-time passwords (RFC 6238) as a second factor.

Jump to

Keyboard shortcuts

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