authkit

package module
v0.97.1 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 7 Imported by: 0

README

AuthKit

Embedded auth library for Go applications. (Standalone server coming later.)

Migrations

Apply AuthKit's Postgres schema before constructing the client, from your app's migrate command (same shape as rivermigrate):

import "github.com/open-rails/authkit/authkitmigrate"

migrator := authkitmigrate.New(pool, nil) // &authkitmigrate.Config{Schema: "..."} for a non-default schema
res, err := migrator.Migrate(ctx)         // idempotent; res.Applied lists what ran

migrator.Validate(ctx) reports pending migrations without applying.

Construction

(Basic embedded setup)

package main

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

	"github.com/gin-gonic/gin"
	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/redis/go-redis/v9"

	"github.com/open-rails/authkit"
	authkitgin "github.com/open-rails/authkit/adapters/gin"
	"github.com/open-rails/authkit/embedded"
	"github.com/open-rails/authkit/authhttp"
	"github.com/open-rails/authkit/verify"
)

func setupAuth() (*gin.Engine, *authhttp.Service, authkit.Client, error) {
	ctx := context.Background()

	pg, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
	if err != nil {
		return nil, nil, nil, err
	}
	rdb := redis.NewClient(&redis.Options{Addr: os.Getenv("REDIS_ADDR")})
	var mailer embedded.EmailSender // host-provided implementation

	cfg := embedded.Config{
		Token: embedded.TokenConfig{
			Issuer:               "https://app.example.com",
			IssuedAudiences:      []string{"myapp"},
			ExpectedAudiences:    []string{"myapp"},
			AccessTokenDuration:  15 * time.Minute,
			RefreshTokenDuration: 30 * 24 * time.Hour,
			SessionMaxPerUser:    3,
		},
		Frontend: embedded.FrontendConfig{
			BaseURL:           "https://app.example.com",
			OIDCReturnPath:    "/login/callback",
			VerifyPath:        "/verify",
			PasswordResetPath: "/reset",
			PasswordlessPath:  "/passwordless",
			InvitePath:        "/accept-invite",
		},
		Registration: embedded.RegistrationConfig{
			Verification:                 authkit.RegistrationVerificationRequired,
			NativeUserMode:               authkit.RegistrationModeOpen,
			PasswordlessLogin:            true,
			PasswordlessAutoRegistration: false,
		},
		Keys: embedded.KeysConfig{
			// Vault-mounted key directory. AuthKit reads the JWT signing keys from
			// <Path>/keys.json and the TOTP secret-encryption key (#148) from
			// <Path>/totp.key — a base64/hex-encoded 16/24/32-byte AES key, perms
			// 0600/0400. Hosts never load these secrets manually.
			Path: "/vault/auth",
		},
		Identity: embedded.IdentityConfig{},
		APIKeys: embedded.APIKeysConfig{
			Prefix: "myapp",
			MaxTTL: 90 * 24 * time.Hour,
		},
		TwoFactor: embedded.TwoFactorConfig{
			// Mode: Disabled | Optional | Required. Required gates the SESSION —
			// existing un-enrolled users are challenged on their next request.
			Mode:    authkit.TwoFactorOptional,
			Methods: []authkit.TwoFactorMethod{authkit.TwoFactorEmail, authkit.TwoFactorTOTP},
			// TOTPSecretKey is an override for tests; the normal path loads
			// <Keys.Path>/totp.key (see Keys above).
		},
		Passkeys: embedded.PasskeyConfig{
			RPID:             "app.example.com",
			RPDisplayName:    "My App",
			Origins:          []string{"https://app.example.com"},
			UserVerification: "preferred",
		},
		RBAC: []authkit.PersonaDef{
			{
				Name: authkit.RootPersona,
				Roles: []authkit.RoleDef{
					{
						Name: "support",
						Permissions: []string{
							"root:users:ban",
							"root:users:recover",
						},
					},
				},
				// Optional. Root capabilities are off unless the host enables them.
				Capabilities: authkit.PersonaCapabilities{CustomRoles: true},
				Catalog: []string{
					"root:users:ban",
					"root:users:recover",
				},
			},
			{
				Name:   "org",
				Parent: authkit.RootPersona,
				Roles: []authkit.RoleDef{
					{
						Name: "admin",
						Permissions: []string{
							"org:members:read",
							"org:members:invite",
						},
					},
				},
			},
			{
				Name:   "repo",
				Parent: "org",
				Capabilities: authkit.PersonaCapabilities{
					APIKeys:            true,
					RemoteApplications: true,
				},
				Roles: []authkit.RoleDef{
					{
						Name: "developer",
						Permissions: []string{
							"repo:models:read",
							"repo:models:deploy",
						},
					},
				},
			},
		},
		Environment:   "production",
		Schema:        "profiles",
		SolanaNetwork: "mainnet",
	}

	// One call builds the embedded engine AND the HTTP transport over it.
	// Engine dependencies (Redis, senders, entitlements, …) ride in via WithEngine.
	srv, client, err := authhttp.New(cfg, pg,
		authhttp.WithEngine(embedded.WithRedis(rdb), embedded.WithEmailSender(mailer)),
		// Trust only infrastructure that overwrites/appends forwarded headers.
		authhttp.WithTrustedProxies("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"),
		authhttp.WithLanguageConfig(authhttp.LanguageConfig{
			Supported: []string{"en", "es"},
			Default:   "en",
		}),
	)
	if err != nil {
		return nil, nil, nil, err
	}

	router := gin.New()
	// The whole AuthKit surface — JWKS at /.well-known/jwks.json, browser OIDC
	// under /oidc, JSON API under /api/v1 — is ONE framework-neutral handler,
	// mounted once as the router's fallback. Host routes always win; excluded
	// routes are the host-shadowing seam.
	mount, err := authhttp.MountHandler(srv, authhttp.MountOptions{})
	if err != nil {
		return nil, nil, nil, err
	}
	router.NoRoute(authkitgin.Fallback(mount))

	// Host route middleware definitions, in the same order as the examples below.
	optionalAuth := authkitgin.Use(verify.Optional(srv.Verifier()))
	requireAuth := authkitgin.Use(verify.Required(srv.Verifier()))
	optionalUser := authkitgin.Use(verify.OptionalUser(srv.Verifier()))
	requireUser := authkitgin.Use(verify.RequiredUser(srv.Verifier()))
	requirePremium := authkitgin.Use(verify.RequireEntitlement("premium"))
	requirePaidPlan := authkitgin.Use(verify.RequireAnyEntitlement("premium", "pro"))
	rootScope := func(*http.Request) verify.PermissionScope {
		return verify.PermissionScope{Persona: authkit.RootPersona}
	}
	requireBanUsersPermission := authkitgin.Use(verify.RequirePermission(client, "root:users:ban", rootScope))
	repoScope := func(c *gin.Context) verify.PermissionScope {
		return verify.PermissionScope{Persona: "repo", Instance: c.Param("repo")}
	}
	requireDeployPermission := authkitgin.RequirePermission(client, "repo:models:deploy", repoScope)
	sensitive := authkitgin.Use(verify.Sensitive())
	requireDeletePermission := authkitgin.RequirePermission(client, "repo:models:delete", repoScope)

	// ====== Public routes ======
	// Public host route: no AuthKit authentication required.
	router.GET("/api/v1/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, map[string]any{
			"ok":      true,
			"service": "doujins",
		})
	})

	// ====== Optional and required user routes ======
	// Optional-user host route: public when anonymous, enriched when a user token is present.
	router.GET("/api/v1/session/optional", optionalUser, func(c *gin.Context) {
		userClaims, ok := authkitgin.UserClaims(c)
		resp := map[string]any{"authenticated": ok}
		if ok {
			resp["user_id"] = userClaims.UserID
		}
		c.JSON(http.StatusOK, resp)
	})

	// Authenticated user host route: reads token claims and loads profile data only when needed.
	router.GET("/api/v1/account/debug", requireUser, func(c *gin.Context) {
		userClaims, _ := authkitgin.UserClaims(c)
		users, err := client.UsersByIDs(c.Request.Context(), []string{userClaims.UserID})
		if err != nil || len(users) == 0 {
			c.JSON(http.StatusInternalServerError, map[string]any{"error": "user_lookup_failed"})
			return
		}

		c.JSON(http.StatusOK, map[string]any{
			"user_id":        userClaims.UserID,
			"email":          users[0].Email,
			"token_email":    userClaims.Email,
			"email_verified": userClaims.EmailVerified,
			"session_id":     userClaims.SessionID,
		})
	})

	// ====== User account routes ======
	// Sensitive account route: requires recent step-up before changing email.
	router.POST("/api/v1/account/email", requireUser, sensitive, func(c *gin.Context) {
		userClaims, _ := authkitgin.UserClaims(c)
		c.JSON(http.StatusOK, map[string]any{
			"user_id":    userClaims.UserID,
			"session_id": userClaims.SessionID,
			"accepted":   true,
		})
	})

	// ====== Optional and required auth routes ======
	// Optional-auth host route: public when anonymous, enriched by any valid principal.
	router.GET("/api/v1/principal/optional", optionalAuth, func(c *gin.Context) {
		principal, ok := authkitgin.Principal(c)
		resp := map[string]any{"authenticated": ok}
		if ok {
			resp["principal_kind"] = principal.Kind
			resp["issuer"] = principal.Issuer
			resp["subject"] = principal.Subject
		}
		c.JSON(http.StatusOK, resp)
	})

	// Required-auth host route: accepts users, API keys, remote apps, or delegated tokens.
	router.GET("/api/v1/principal/current", requireAuth, func(c *gin.Context) {
		principal, _ := authkitgin.Principal(c)
		c.JSON(http.StatusOK, map[string]any{
			"principal_kind": principal.Kind,
			"issuer":         principal.Issuer,
			"subject":        principal.Subject,
		})
	})

	// Permission-gated host route: accepts any principal with repo:models:deploy.
	router.POST("/api/v1/repos/:repo/models/deploy", requireAuth, requireDeployPermission, func(c *gin.Context) {
		principal, _ := authkitgin.Principal(c)
		c.JSON(http.StatusOK, map[string]any{
			"principal_kind": principal.Kind,
			"issuer":         principal.Issuer,
			"subject":        principal.Subject,
			"repo":           c.Param("repo"),
			"permission":     "repo:models:deploy",
		})
	})

	// ====== Entitlement routes ======
	// Entitlement-gated host route: requires the premium entitlement on the user.
	router.GET("/api/v1/premium/download", requireUser, requirePremium, func(c *gin.Context) {
		userClaims, _ := authkitgin.UserClaims(c)
		c.JSON(http.StatusOK, map[string]any{
			"user_id":      userClaims.UserID,
			"entitlements": userClaims.Entitlements,
			"download_url": "/downloads/premium.zip",
		})
	})

	// Any-entitlement host route: requires at least one accepted entitlement.
	router.GET("/api/v1/account/export", requireUser, requirePaidPlan, func(c *gin.Context) {
		userClaims, _ := authkitgin.UserClaims(c)
		c.JSON(http.StatusOK, map[string]any{
			"user_id":      userClaims.UserID,
			"entitlements": userClaims.Entitlements,
			"export_id":    "exp_123",
		})
	})

	// ====== Permission routes ======
	// Root-admin host route: requires root:users:ban on the singleton root persona.
	router.POST("/api/v1/admin/users/:id/ban", requireUser, requireBanUsersPermission, func(c *gin.Context) {
		userClaims, _ := authkitgin.UserClaims(c)
		c.JSON(http.StatusOK, map[string]any{
			"admin_user_id":  userClaims.UserID,
			"banned_user_id": c.Param("id"),
		})
	})

	// Sensitive permission-gated host route: requires permission plus recent step-up.
	router.DELETE("/api/v1/repos/:repo/models/:id", requireUser, sensitive, requireDeletePermission, func(c *gin.Context) {
		userClaims, _ := authkitgin.UserClaims(c)
		c.JSON(http.StatusOK, map[string]any{
			"user_id":  userClaims.UserID,
			"repo":     c.Param("repo"),
			"model_id": c.Param("id"),
			"deleted":  true,
		})
	})

	return router, srv, client, nil
}

This exposes AuthKit routes such as /api/v1/token, /api/v1/me, and /.well-known/jwks.json.

Redis is passed once, on the engine (embedded.WithRedis); the HTTP layer adopts it automatically (#210) — authhttp.WithRedis is only an override.

Two-step construction: hosts that need to hold or decorate the engine separately build it first, then wrap it:

client, err := embedded.New(cfg, pg, embedded.WithRedis(rdb), embedded.WithEmailSender(mailer))
srv, err := authhttp.NewServer(client, authhttp.WithTrustedProxies("10.0.0.0/8"))

The returned client is the host's authkit.Client for in-process operations. The future standalone server will use remote.New for the same contract.

authhttp.MountHandler returns the whole surface as one http.Handler: every enabled JSON API route under APIPrefix (default /api/v1), browser OIDC redirects under OIDCPath (default /oidc), and JWKS at /.well-known/jwks.json. Options: Groups selects surfaces (auth, registration, account, admin, permission_groups, browser_oidc); ExcludeRoutes drops routes the host shadows with its own handlers; MountPrefix shifts everything under a host path (boundary-checked, for non-stripping proxies); Wrap decorates every mounted route. gin hosts mount it once via router.NoRoute(authkitgin.Fallback(mount)) (or gin.WrapH on an explicit wildcard); any other router mounts it like any http.Handler.

Browser OIDC result contract

The three routes under OIDCPath ({provider}/login, {provider}/callback, {provider}/step-up/callback) are browser navigations, so both outcomes are delivered to the SPA, never left as a raw response body on the backend URL:

  • Success: 302 to Frontend.BaseURL + OIDCReturnPath with #access_token=…&refresh_token=…&expires_in=…&provider=…[&return_to=…] (no refresh_token under MountOptions.RefreshCookie — see below).
  • Error: 302 to the same route with #error=<code>&flow=login|link&provider=…[&return_to=…]. Codes are the stable wire codes (access_denied, invalid_state, account_exists_link_required, …); an unparseable IdP ?error= collapses to provider_error. When the outcome is 2fa_enrollment_required the fragment also carries enrollment_token, enrollment_expires_in and allowed_methods (deliberately NOT access_token: an enrollment-scoped token must not be storable as a session by a fragment parser that only looks for access_token).
  • Popup flows (?ui=popup&popup_nonce=… on login): the popup document posts {type: "AUTHKIT_OIDC_RESULT", access_token, …, nonce} to the opener on success and {type: "AUTHKIT_OIDC_ERROR", error, flow, provider, nonce} on failure — distinct types, so an opener that only understands the success shape can never misread an error as a login.
  • Step-up flows: failures redirect to the flow's return_to with ?step_up=failed (matching the existing success/failure redirects).
  • format=json or Accept: application/json keeps the legacy JSON error envelope on every stage. Rate-limit rejections (429) always stay JSON.
  • Browser results (fragment redirects and popup documents) are emitted with Cache-Control: no-store (RFC 6749 §5.1) — they carry tokens.
  • The raw IdP ?error=/error_description values are logged server-side ([authkit/oidc], quoted and truncated) for diagnostics; only the sanitized code is ever reflected to the client.

MountOptions{RefreshCookie: true} moves the rotating refresh token out of every response body into an HttpOnly + Secure + SameSite=Lax cookie named authkit_rt. Off by default — a host that does not set it sees byte-identical behaviour.

h, err := authhttp.MountHandler(srv, authhttp.MountOptions{RefreshCookie: true})
Aspect Behaviour
Issue All ten session-establishing responses (password / passwordless / passkeys / SIWS / 2FA verify / email+phone verify / registration auto-login / refresh rotation / OIDC popup / OIDC fragment) set the cookie and omit refresh_token from the body, the fragment and the postMessage payload.
Consume POST /token and POST /sessions/current take the body's refresh_token when present, the cookie otherwise. A cookie-only client sends an empty refresh_token and gets a rotation, not a 400.
Clear DELETE /logout, and a refresh that fails with user_banned. Never on the unknown-token 401 — staleness and death are indistinguishable there, and clearing would destroy a still-live jar value over a transient failure.
Path The mount's API anchor (MountPrefix + APIPrefix, e.g. /api/v1) — the narrowest prefix covering both consuming routes. Keeps the cookie off the SPA document and its assets.
SameSite Lax, never Strict. The OIDC tail is a cross-site top-level GET from the IdP, and emailed verification links land the same way; Strict withholds the cookie there and the first refresh fails. Lax still blocks the cross-site POST a CSRF would need.
Secure Derived like the OAuth state cookie: HTTPS Frontend.BaseURL, or the request's own TLS. Plain-http local dev gets a non-Secure cookie so the flow still works.

Two gates apply to a cookie-sourced credential only (a body token is not CSRF-relevant): a present-but-mismatched Origin is refused, and duplicate authkit_rt cookies fail closed — a sibling host that can set Domain=<parent> would otherwise plant a value that sorts ahead of the host-only one and silently swap the session. Both refusals leave the session alive and the cookie untouched.

Requirement: the SPA and this mount must share an origin, or the cookie never reaches the refresh call. Not fixed: script running in a live tab can still call the refresh route. This removes theft-and-replay from elsewhere, not abuse from inside the victim's own tab.

RBAC config and durability

Config.RBAC is a single []authkit.PersonaDef slice. Each persona is a permission namespace and declares roles with persona:resource:action grants. root is configured with the same shape as any other persona: Parent is empty, capabilities default off, and any host root entry is merged with AuthKit's intrinsic root owner and built-in root: permissions.

Role definitions and per-persona Catalog entries are in-memory config. Editing a role's grants changes what every holder of that role can do after the new schema is loaded. The containment shape and runtime rows are durable: group_persona_parents is reconciled from config, while group_user_roles, group_custom_roles, and api_keys keep name references to personas and roles.

Treat persona names and role names as durable identifiers. Do not rename in place; create a new name, migrate assignments, then retire the old one. Removing a role, catalog grant, or persona fails closed: unresolved names grant nothing, but AuthKit does not auto-delete those rows because a typo in config must not erase operator intent. Review and clean up drifted rows deliberately, and do not reuse a retired name for a different meaning until old assignments are cleared.

Instance creation (CreatePermissionGroup, including its unchecked OwnerSubjectID owner-seeding) has no actor-aware *As variant: authorizing who may create a group instance is deliberately the HOST's job in the embedded trust model — the host already decided to call it, which is the authority. Runtime mutations to an EXISTING instance (assign/unassign a role, define/delete a custom role, mint an invite or API key) all go through actor-aware *As paths that re-derive authority from the caller's own grants (#136/#247 no-escalation). *As variants for group creation itself are deferred to the Phase-2 remote transport (#138), where host-trust no longer holds and every actor must be independently authorized.


Advanced Host Flows

Session history (sign-ins, revocations, password changes) is built in: events are recorded best-effort in Postgres (session_events) and served by GET /admin/users/{id}/signins in every deployment. Retention defaults to 365 days (IP + user-agent are personal data — the ceiling is deliberate); tune it with Config.SessionEventRetention (negative = keep forever). Pruning runs inside Client.CleanupExpiredAuthState — schedule it daily-ish (the standalone server ticks it itself).

func mountAdvancedAuthExamples(
	router *gin.Engine,
	client authkit.Client,
	requireAuth gin.HandlerFunc,
	requireUser gin.HandlerFunc,
) {
	type Caller struct {
		Invoker string
		Payer   string
	}
	resolveCaller := func(_ context.Context, principal authkit.Principal) (Caller, error) {
		return Caller{
			Invoker: principal.Subject,
			Payer:   principal.Subject,
		}, nil
	}

	rootScope := func(*http.Request) verify.PermissionScope {
		return verify.PermissionScope{Persona: authkit.RootPersona}
	}
	requireRootRead := authkitgin.Use(verify.RequirePermission(client, "root:resources:read", rootScope))
	requireRootCredentialsManage := authkitgin.Use(verify.RequirePermission(client, "root:credentials:manage", rootScope))
	requireRootUsersInvite := authkitgin.Use(verify.RequirePermission(client, "root:users:invite", rootScope))

	// Operator route: list users for an admin screen.
	router.GET("/api/v1/operator/users", requireUser, requireRootRead, func(c *gin.Context) {
		users, err := client.AdminListUsers(c.Request.Context(), authkit.AdminUserListOptions{
			Page:     1,
			PageSize: 50,
			Status:   authkit.AdminUserStatusActive,
			Sort:     authkit.AdminUserSortCreatedAt,
			Desc:     true,
		})
		if err != nil {
			c.JSON(http.StatusInternalServerError, map[string]any{"error": "user_list_failed"})
			return
		}
		c.JSON(http.StatusOK, users)
	})

	// Operator route: create a user directly.
	router.POST("/api/v1/operator/users", requireUser, requireRootUsersInvite, func(c *gin.Context) {
		var req struct {
			Email    string `json:"email"`
			Username string `json:"username"`
		}
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, map[string]any{"error": "invalid_request"})
			return
		}
		user, err := client.CreateUser(c.Request.Context(), req.Email, req.Username)
		if err != nil {
			c.JSON(http.StatusBadRequest, map[string]any{"error": "user_create_failed"})
			return
		}
		c.JSON(http.StatusOK, user)
	})

	// Operator route: register a trusted remote application issuer.
	router.POST("/api/v1/operator/remote-applications", requireUser, requireRootCredentialsManage, func(c *gin.Context) {
		var req struct {
			Slug              string `json:"slug"`
			PermissionGroupID string `json:"permission_group_id"`
			Issuer            string `json:"issuer"`
			JWKSURI           string `json:"jwks_uri"`
		}
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, map[string]any{"error": "invalid_request"})
			return
		}
		app, err := client.UpsertRemoteApplication(c.Request.Context(), authkit.RemoteApplication{
			Slug:              req.Slug,
			PermissionGroupID: req.PermissionGroupID,
			Issuer:            req.Issuer,
			JWKSURI:           req.JWKSURI,
			Mode:              authkit.RemoteAppModeJWKS,
			Enabled:           true,
		})
		if err != nil {
			c.JSON(http.StatusBadRequest, map[string]any{"error": "remote_application_register_failed"})
			return
		}
		c.JSON(http.StatusOK, app)
	})

	// Platform route: mint a delegated token for another AuthKit-protected API.
	router.POST("/api/v1/platform/delegated-token", requireAuth, func(c *gin.Context) {
		var req struct {
			Subject string `json:"subject"`
			Tier    string `json:"tier"`
		}
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, map[string]any{"error": "invalid_request"})
			return
		}
		token, err := client.MintDelegatedAccessToken(c.Request.Context(), authkit.DelegatedAccessParams{
			Audiences:        []string{"tensorhub"},
			DelegatedSubject: req.Subject,
			Permissions:      []string{"repo:models:deploy"},
			Attributes:       map[string]any{"tier": req.Tier},
			TTL:              15 * time.Minute,
		})
		if err != nil {
			c.JSON(http.StatusBadRequest, map[string]any{"error": "delegated_token_failed"})
			return
		}
		c.JSON(http.StatusOK, map[string]any{"access_token": token})
	})

	// Resource route: resolve AuthKit's raw principal into the app's caller model.
	router.POST("/api/v1/resources/invoke", requireAuth, func(c *gin.Context) {
		principal, _ := authkitgin.Principal(c)
		caller, err := resolveCaller(c.Request.Context(), principal)
		if err != nil {
			c.JSON(http.StatusUnauthorized, map[string]any{"error": "unauthorized"})
			return
		}
		c.JSON(http.StatusOK, map[string]any{
			"invoker": caller.Invoker,
			"payer":   caller.Payer,
		})
	})
}
Signed documents and delegated references

AuthKit's documents package signs and verifies immutable, content-addressed JSON envelopes. The signed iss, aud, versioned type (for example example.entitlements/v1), and opaque payload are transport/trust metadata; only the receiving application owns payload schema, normalization, authorization semantics, and side effects.

(*embedded.Client).SignDocument signs with the service's live AuthKit key. documents.NewPublisher serves the retained compact JWS at /.well-known/authkit/documents/{digest}, and documents.NewResolver performs an authenticated issuer-relative fetch before verify.Verifier checks the exact digest, issuer, audience, type, key, and signature. Publisher and resolver authorization callbacks should use the host's existing AuthKit machine credentials; nil authorization denies access. The digest identifies immutable signed payload bytes, while the compact JWS can change when those bytes are re-signed during key rotation, so publisher responses use a representation ETag and require cache revalidation.

Delegated tokens pin documents with the top-level documents claim:

{"documents":{"example.entitlements/v1":"sha256:<64 lowercase hex>"}}

Pre-launch consumers hard-cut from any application-specific attributes.policy_digest convention to documents[type]. AuthKit intentionally provides no compatibility alias and never interprets an application payload.

Owned document publishing and the delegated mint route (#260/#261)

documents.NewService runs the whole publish lifecycle over an AuthKit-owned Postgres table (migration 0005_signed_documents): sign → verify → persist → re-read → re-verify at boot, digest-stable re-signature on key rotation, and ErrDigestCollision on any payload/type change under an existing digest. The host supplies only its compiled payload:

docSvc, err := documents.NewService(ctx, documents.ServiceConfig{
    Type: "example.entitlements/v1", Payload: payload,
    Issuer: cfg.Token.Issuer, Audiences: cfg.Delegated.Audiences,
    Signer: client, Postgres: pool, Schema: client.Schema(),
})
srv, err := authhttp.NewServer(client, authhttp.WithDocuments(docSvc))

MountHandler then serves GET|HEAD /.well-known/authkit/documents/{digest} (root-anchored, RouteDocuments). Reader authorization is config — Config.Documents.ReaderSlugs names the remote applications allowed to fetch; publication is never public and a providers/readers mismatch refuses at boot.

POST /delegated/token (RouteDelegated, mounted when Config.Delegated.Audiences is set) mints delegated tokens for the authenticated user: audience-subset clamp, request TTL clamped into the boot-validated TTLFloor <= TTLDefault <= TTLCeiling triple (an inconsistent triple never boots), document digests stamped from every WithDocuments provider, and post-mint signing-KID reconciliation so a stamped document always verifies against the token's key. Every delegated token carries a fresh uuidv7 jti (ak#270), so a receiving service can revoke one token by id rather than the whole session; DelegatedAccessParams.JTI still lets a caller pin its own. Host semantics enter through ONE seam:

embedded.WithDelegatedAttributes(func(ctx context.Context, userID string) (map[string]any, map[string]string, error) {
    tier := billing.ResolveEffectiveTier(ctx, userID) // host-owned meaning
    return map[string]any{"entitlement": tier}, nil, nil
})
Application self-registration (#264)

Enable with Config.Applications = ApplicationsConfig{SelfRegistration: true, OrgPersona: "org"} (OrgPersona: a declared non-root persona parented by root). Routes mount only when enabled (RouteApplications group):

POST /api/v1/applications/register          {"domain": "cozy.art"}
POST /api/v1/applications/{slug}/rotate     {"jws": "<compact JWS>"}
POST /api/v1/applications/{slug}/repoint    {"jws": "<compact JWS>"}
POST /api/v1/admin/applications/{slug}/tier {"tier": "approved"}   (root:credentials:manage)

Registration. The server fetches https://<domain>/.well-known/authkit/application.json — that fetch IS the domain-control proof (https-only, redirect-refusing, SSRF-guarded outside dev-like environments; dev accepts an http://127.0.0.1:<port> base URL, and the manual/bootstrap path remains the loopback escape hatch). SLUGS AND DOMAINS ARE SEPARATE: the domain is the trust root and the re-registration key; the document's slug field is a REQUESTED handle (defaulting to the hostname) claimed through the same availability + anti-squat gates as any org slug — cozy.art can claim cozy-creator. The document also declares issuer (host must equal the proven domain outside dev), exactly one of jwks_uri/public_keys, and optional display_name / document_endpoint. Result: a remote_applications row (uuidv7 identity, tier registered, trust root domain) plus a SERVICE-OWNED org — an OrgPersona group whose instance slug is the claimed slug, owned by the application principal itself. Re-registering the same domain is idempotent: it re-proves the root and refreshes issuer/keys/config from the re-fetched document (the boot-time self-heal); the slug is never changed by a refresh. Per-IP and per-domain rate limits apply (application_register bucket); embedded.WithApplicationAdmission injects a host admission predicate — cost gates (allowances, card-on-file) are the host's, anti-spam velocity caps are authkit's.

Rotation doctrine. The trust root — domain control, or the owning user account — rotates keys; the keypair alone NEVER does. If every old key is gone, re-registration adopts whatever the document declares now. The signed paths are conveniences: rotate (replace the trust source) and repoint (move the trust root to a new domain, proven by fetching the new domain's document; uuid, slug, and org are all stable) accept an ACME-style compact JWS signed by a currently-trusted key — JOSE typ authkit-application-request+jws, payload {"op","slug","aud","iat",...} with aud = this platform's issuer and iat within ±5 minutes (anti-replay; both operations are idempotent within the window). A disabled application's keys are not trusted — recovery is always the trust root.

Tiers. registered buys existence only: authenticate + serve/fetch documents. approved is an admin act (SetApplicationTier). Re-verification cadence and dormancy are HOST policy: sweepers read RootVerifiedAt and call SetApplicationEnabled; authkit ships no clocks or background jobs.

Naming doctrine. uuidv7 is the only join key; slugs are meaningful unique handles claimed like usernames (GitHub model); display_name is free-form non-unique metadata on both applications and permission groups. PATCH /api/v1/<persona>/{slug} (gated <persona>:settings:manage; owners hold it via the wildcard) renames a group slug or updates its display name. A renamed-away slug is TOMBSTONED: permanently reserved to the same group and forwarding through slug resolution, so published references keep working and nobody can ever re-claim it (the group may reclaim its own tombstone by renaming back). DeletePermissionGroup tombstones the slug by default; DeletePermissionGroupOptions{ReleaseSlug: true} frees it — safe only for names nothing ever referenced, and that judgment is the host's. Slug renames are velocity-capped per user + per IP (group_settings bucket) — a rename is a claim.

Liveness-aware verification (#267)

VerifyRequest / Required are STATELESS by design (#215): a banned or deleted user keeps a valid access token until it expires (≤1 access TTL). For a privileged surface that cannot accept that window, wire a liveness source once and mount the live gate instead:

verifier.WithLiveness(client) // any authkit.Client — embedded or remote

admin := router.Group("/api/v1/admin", authkitgin.RequiredLive(verifier))
  • verify.RequiredLive / RequiredLiveUser (and the authkitgin twins) — 401 on a banned, deleted, reserved or unknown account, on the user's NEXT request.
  • Claims handed downstream carry Username, Email and EmailVerified FRESH as of that lookup. Do not call the admin directory per request to refresh display fields; roles and entitlements have their own live reads (RoleSlugsByUsers, Allow, ListEntitlements).
  • verifier.AllowLive(ctx, client, claims, perm, scope) is verify.Allow with the liveness precondition — "live AND permitted" in one call, so a banned user who still holds a permission assignment is denied. verifier.IsLive is the bare predicate.
  • Fail-closed, no cache. A lookup error denies. Exactly one UserLivenessByIDs call per gated request, no memoization — any cache reintroduces the staleness window the gate exists to close. Mounting RequiredLive without WithLiveness PANICS at mount rather than silently degrading to the weaker gate.
Public-safe user projections (#268)

Two batch projections, one query each, differing only in who may see the result:

method type use
UsersByIDs UserRef{ID, Username, Email} PRIVILEGED — admin surfaces, the account's own views
PublicUsersByIDs PublicUserRef{ID, Username, AvatarURL, Biography, CreatedAt, Deleted} rendering users to other users

PublicUserRef has no email field at all, so a resolved author nests straight into a response body. Soft-deleted users come back as TOMBSTONES (Deleted set, display fields blank); banned users come back normally (a ban is an access decision, not a visibility one); unknown ids are absent. ref.DisplayName() / authkit.PublicDisplayName(refs, id) render user-<id8> for tombstoned and unresolved ids, so the call site needs no fallback branch. Derived assets (thumbnail sizes, CDN rewrites) stay host-owned — authkit stores one avatar string.

Frontend code calls the AuthKit routes mounted by MountHandler:

POST /api/v1/password/login
POST /api/v1/token
GET  /api/v1/me
POST /api/v1/passwordless/start
POST /api/v1/passwordless/confirm
POST /api/v1/register
GET  /api/v1/capabilities
POST /api/v1/oidc/{provider}/link/start

Documentation

Overview

Package authkit holds authentication primitives shared between authkit's issuing core and its verification layer: plain data types, opaque-credential parsing, and sentinel errors that carry NO dependency on Postgres or the rest of core (stdlib only). It exists so the verification path — and, later, a standalone verify module (agents #110/#107) — can depend on these without pulling in the storage layer. The core package re-exports every symbol here as an alias, so existing callers using core.X are unaffected.

Index

Constants

View Source
const (
	ImportStatusInserted               ImportUserStatus                 = "inserted"
	ImportStatusSkipped                ImportUserStatus                 = "skipped"
	ImportStatusRejected               ImportUserStatus                 = "rejected"
	ImportUnverifiedSolanaLinkInserted ImportUnverifiedSolanaLinkStatus = "inserted"
	ImportUnverifiedSolanaLinkSkipped  ImportUnverifiedSolanaLinkStatus = "skipped"
	ImportUnverifiedSolanaLinkRejected ImportUnverifiedSolanaLinkStatus = "rejected"
	AdminUserStatusActive              AdminUserStatus                  = "active"     // not deleted, not banned
	AdminUserStatusBanned              AdminUserStatus                  = "banned"     // not deleted, currently banned
	AdminUserStatusDeleted             AdminUserStatus                  = "deleted"    // soft-deleted
	AdminUserStatusAny                 AdminUserStatus                  = "any"        // no deleted/banned predicate
	AdminUserSortCreatedAt             AdminUserSort                    = "created_at" // default
	AdminUserSortLastLogin             AdminUserSort                    = "last_login"
	AdminUserSortUsername              AdminUserSort                    = "username"
	AdminUserSortEmail                 AdminUserSort                    = "email"
)
View Source
const (
	ErrorTypeInvalidRequest = "invalid_request_error"
	ErrorTypeAuthentication = "authentication_error"
	ErrorTypeAuthorization  = "authorization_error"
	ErrorTypeRateLimit      = "rate_limit_error"
	ErrorTypeAPI            = "api_error"
)

Error type categories, aligned with openrails' / Stripe's taxonomy strings.

View Source
const (
	RemoteAppModeJWKS   = "jwks"
	RemoteAppModeStatic = "static"
)

Remote-application trust modes (#74). A remote_application is a federation PRINCIPAL whose credential is a key, with exactly one trust source:

jwks   — keys fetched + refreshed from JWKSURI; rotation is publishing a new
         kid at the same URL.
static — authorized_keys-style human-managed PEM list for principals without
         a JWKS endpoint; manual rotation by design.
View Source
const (
	ApplicationTierRegistered = "registered"
	ApplicationTierApproved   = "approved"
)

Application capability tiers (#264).

View Source
const (
	ApplicationTrustRootManual = "manual"
	ApplicationTrustRootDomain = "domain"
	ApplicationTrustRootUser   = "user"
)

Application trust roots (#264): the authority that rotates keys.

View Source
const (
	// ServiceJWTTokenUse is the required `token_use` claim for service JWTs.
	ServiceJWTTokenUse = "service"
	// DefaultServiceJWTLifetime is the recommended lifetime for first-party
	// machine-to-machine service JWTs.
	DefaultServiceJWTLifetime = 15 * time.Minute
)
View Source
const ApplicationWellKnownPath = "/.well-known/authkit/application.json"

ApplicationWellKnownPath is where a domain-registered application serves its ApplicationDocument. Fetching it over HTTPS IS the domain-control proof.

View Source
const PermWildcard = "*"

PermWildcard is the wildcard CHARACTER used inside namespace-anchored globs (`org:*`, `org:members:*`, `org:*:read`, `root:*`). A bare standalone `*` is NOT a valid grant — it is rejected everywhere.

Variables

View Source
var (
	// ErrInvalidAccessToken indicates an API key that does not exist, has a bad
	// secret, or whose owning permission group is gone. Deliberately indistinguishable from
	// a malformed token so callers learn nothing from the error.
	ErrInvalidAccessToken = errors.New("invalid_token")
	// ErrAccessTokenRevoked indicates the API key was explicitly revoked.
	ErrAccessTokenRevoked = errors.New("token_revoked")
	// ErrAccessTokenExpired indicates the API key is past its expires_at.
	ErrAccessTokenExpired = errors.New("token_expired")
)
View Source
var (
	ErrApplicationDocumentFetchFailed  = errors.New("application_document_fetch_failed")
	ErrApplicationDocumentInvalid      = errors.New("application_document_invalid")
	ErrApplicationDomainConflict       = errors.New("application_domain_conflict")
	ErrApplicationDomainInvalid        = errors.New("application_domain_invalid")
	ErrApplicationIssuerConflict       = errors.New("application_issuer_conflict")
	ErrApplicationNotDomainRooted      = errors.New("application_not_domain_rooted")
	ErrApplicationRegistrationDisabled = errors.New("application_registration_disabled")
	ErrApplicationSignatureInvalid     = errors.New("application_signature_invalid")
	ErrApplicationSignatureStale       = errors.New("application_signature_stale")
	ErrApplicationSlugConflict         = errors.New("application_slug_conflict")
	ErrApplicationTierInvalid          = errors.New("application_tier_invalid")
	ErrBootstrapDatabaseNotEmpty       = errors.New("bootstrap_database_not_empty")
	ErrGroupSlugApplicationManaged     = errors.New("group_slug_application_managed")
	ErrGroupSlugTaken                  = errors.New("group_slug_taken")
	// #263 generated persona-instance creation.
	ErrGroupSlugReserved    = errors.New("group_slug_reserved")
	ErrGroupSlugInvalid     = errors.New("group_slug_invalid")
	ErrGroupCreationRefused = errors.New("group_creation_refused")
	// #262 first-class avatar URL field.
	ErrAvatarURLInvalid                  = errors.New("avatar_url_invalid")
	ErrCannotRemoveLastAdminRole         = errors.New("cannot_remove_last_admin_role")
	ErrAccountRegistrationInviteConsumed = errors.New("account_registration_invite_consumed")
	ErrAccountRegistrationInviteExpired  = errors.New("account_registration_invite_expired")
	ErrAccountRegistrationInviteNotFound = errors.New("account_registration_invite_not_found")
	ErrAccountRegistrationInviteRevoked  = errors.New("account_registration_invite_revoked")
	ErrCustomClaimsReserved              = errors.New("custom_jwt_reserved_claim")
	ErrCustomJWTReservedType             = errors.New("custom_jwt_reserved_type")
	ErrCustomRoleGrantCrossPersona       = errors.New("custom_role_grant_cross_persona")
	ErrCustomRoleGrantOutsideCatalog     = errors.New("custom_role_grant_outside_catalog")
	ErrCustomRoleIsCatalogRole           = errors.New("custom_role_is_catalog_role")
	ErrCustomRoleNameInvalid             = errors.New("custom_role_name_invalid")
	ErrCustomRolesNotSupported           = errors.New("custom_roles_not_supported")
	ErrEmailAlreadyVerified              = errors.New("email_already_verified")
	ErrEmailDeliveryFailed               = errors.New("email_delivery_failed")
	ErrEmailInUse                        = errors.New("email_in_use")
	ErrEmailSenderUnavailable            = errors.New("email_sender_unavailable")
	ErrEmptyCustomClaims                 = errors.New("custom_jwt_empty_claims")
	ErrEntitlementFilterUnavailable      = errors.New("entitlement_filter_unavailable")
	ErrExternalInvitesDisabled           = errors.New("external_invites_disabled")
	ErrGroupNotFound                     = errors.New("permission_group_not_found")
	ErrInsufficientRoleAuthority         = errors.New("insufficient_role_authority")
	ErrInvalidAttributeDef               = errors.New("invalid_attribute_def")
	ErrInvalidBootstrapManifest          = errors.New("invalid_bootstrap_manifest")
	ErrInvalidExpiry                     = errors.New("invalid_expiry")
	ErrInvalidInvite                     = errors.New("invalid_invite")
	ErrInvalidRole                       = errors.New("invalid_role")
	ErrInvalidUntil                      = errors.New("invalid_until")
	ErrInviteLinkExpired                 = errors.New("group_invite_link_expired")
	ErrInviteLinkNotFound                = errors.New("group_invite_link_not_found")
	ErrInviteLinkRevoked                 = errors.New("group_invite_link_revoked")
	ErrMissingName                       = errors.New("missing_name")
	ErrMissingSigner                     = errors.New("missing_signer")
	ErrNotGroupMember                    = errors.New("not_group_member")
	ErrOwnerSlugTaken                    = errors.New("owner_slug_taken")
	ErrPasskeyCloneDetected              = errors.New("passkey_clone_detected")
	ErrPasskeyNotFound                   = errors.New("passkey_not_found")
	ErrPasskeyUserVerificationRequired   = errors.New("passkey_user_verification_required")
	ErrPasswordlessDisabled              = errors.New("passwordless_disabled")
	ErrPasswordResetRequired             = errors.New("password_reset_required")
	ErrPendingRegistrationNotFound       = errors.New("pending_registration_not_found")
	ErrPhoneAlreadyVerified              = errors.New("phone_already_verified")
	ErrPhoneInUse                        = errors.New("phone_in_use")
	ErrRegistrationDisabled              = errors.New("registration_disabled")
	ErrRemoteApplicationNotFound         = errors.New("remote_application_not_found")
	ErrRenameRateLimited                 = errors.New("rename_rate_limited")
	ErrReservedIssuer                    = errors.New("reserved_issuer")
	ErrRoleAssignmentEscalation          = errors.New("role_assignment_escalation")
	ErrRoleNotAssignable                 = errors.New("role_not_assignable")
	ErrSMSDeliveryFailed                 = errors.New("sms_delivery_failed")
	ErrSMSSenderUnavailable              = errors.New("sms_unavailable")
	ErrStepUpRequired                    = errors.New("step_up_required")
	ErrTooManyCustomClaims               = errors.New("custom_jwt_too_many_claims")
	ErrTwoFAEnrollmentRequired           = errors.New("2fa_enrollment_required")
	ErrUnknownGroupPersona               = errors.New("unknown_group_persona")
	ErrUnknownRole                       = errors.New("unknown_role")
	ErrUserBanned                        = errors.New("user_banned")
	ErrUserNotFound                      = errors.New("user_not_found")
	ErrUserRoleNotFound                  = errors.New("user_role_not_found")
	ErrVerificationLinkExpired           = errors.New("verification_link_expired")
	ErrSIWSAddressMismatch               = errors.New("siws_address_mismatch")
	ErrSIWSChallengeExpired              = errors.New("siws_challenge_expired")
	ErrSIWSChallengeMismatch             = errors.New("siws_challenge_mismatch")
	ErrSIWSChallengeNotFound             = errors.New("siws_challenge_not_found")
	ErrSIWSDomainInvalid                 = errors.New("siws_domain_invalid")
	ErrSIWSSignatureInvalid              = errors.New("siws_signature_invalid")
	ErrSIWSTimestampInvalid              = errors.New("siws_timestamp_invalid")
	ErrWalletAlreadyLinked               = errors.New("wallet_already_linked")
	ErrProviderAlreadyLinked             = errors.New("provider_already_linked")
)

Sentinel errors — the wire-contract error identities shared by the embedded engine and (Phase 2) the remote SDK so errors.Is works across transports (#138 contract inversion). internal/authcore aliases these.

View Source
var ErrAttributeDefNotFound = errors.New("attribute_def_not_found")

ErrAttributeDefNotFound indicates no registered remote-application attribute definition matched.

View Source
var ErrInvalidRemoteApplication = errors.New("invalid_remote_application")

ErrInvalidRemoteApplication indicates a malformed remote_application registration payload.

View Source
var ErrInvalidServiceJWT = errors.New("invalid_service_jwt")

ErrInvalidServiceJWT indicates a presented service JWT failed verification.

Functions

func APIKeyMarker

func APIKeyMarker(prefix string) string

APIKeyMarker returns the leading marker that identifies an API key for the given application prefix: "<prefix>_st_" when prefix is non-empty, else "st_".

func CodeForError added in v0.76.0

func CodeForError(err error) string

CodeForError resolves an error to its wire code by walking the error chain: it returns the first sentinel's .Error() for which errors.Is(err, sentinel) holds, or "" if none match. Unlike keying off err.Error() directly, this handles WRAPPED sentinels (e.g. fmt.Errorf("%w: %w", ErrEmailDeliveryFailed, cause)) — the server emits that code so the remote client re-derives errors.Is(err, ErrX) identity and the status classification stays correct across the wire (#197).

func ErrorCodes added in v0.80.0

func ErrorCodes() []string

ErrorCodes returns every registered wire code (each sentinel's Error() string), for parity guards between this registry and transport code tables.

func ErrorForCode added in v0.68.0

func ErrorForCode(code string) error

ErrorForCode maps a wire error code (a sentinel's Error() string) back to the sentinel, so a remote client re-derives errors.Is(err, authkit.ErrX) identity across the network. Unknown/empty codes return nil — the caller supplies its own fallback. The server emits err.Error() as the code; remote/ resolves it here, so the wire-error contract has ONE source of truth (#142).

func ErrorMessage

func ErrorMessage(code string) string

ErrorMessage returns a human-readable English message for a wire error code: a curated message for common codes, otherwise a humanized form of the code so the message is never empty. Localized catalogs are a future extension.

func ErrorTypeForStatus

func ErrorTypeForStatus(status int) string

ErrorTypeForStatus maps an HTTP status to its error-type category (the same inference openrails performs).

func FormatAPIKey

func FormatAPIKey(prefix, keyID, secret string) string

FormatAPIKey assembles the full presented token: <marker><key_id>_<secret>.

func HTTPStatus added in v0.80.0

func HTTPStatus(err error) (int, string)

HTTPStatus maps an error to its HTTP status and wire code (#213): the ONE chain-aware mapper for consumers calling Client methods directly and for the management transport, so hosts stop re-implementing the errors.Is chains authkit already encodes. Non-sentinel errors return (500, "internal_error"); sentinels without an explicit status entry return 422 with their code. (The authhttp handlers keep their own chains where they deliberately emit context-specific wire codes — e.g. last-admin-role maps to a different code on the group routes than the sentinel's own.)

func HasAPIKeyPrefix

func HasAPIKeyPrefix(prefix, token string) bool

HasAPIKeyPrefix reports whether token carries the API-key marker for prefix. Used by middleware to route to the API-key path before attempting JWT verification.

func ParseAPIKey

func ParseAPIKey(prefix, token string) (keyID, secret string, ok bool)

ParseAPIKey splits a presented token into its key_id and secret. key_id and secret are base62 (no underscores), so the first "_" after the marker is the unambiguous delimiter. ok is false if the token lacks the marker or either part is empty.

func PermMatches

func PermMatches(grant, concrete string) bool

PermMatches reports whether a GRANT token authorizes a CONCRETE permission. The grant may be a literal (`org:members:read`) or a namespace-anchored glob where `*` wildcards a whole segment (`org:members:*`, `org:*:read`, `org:*`). The namespace (segment 0) must be a literal — a bare `*` (or a `*` namespace) never matches. A two-segment glob `ns:*` matches every concrete `ns:…` perm.

This is the shared, authz-critical matcher used by both core's RBAC checks and the verification layer's permission-coverage checks.

func PublicDisplayName added in v0.92.0

func PublicDisplayName(refs map[string]PublicUserRef, id string) string

PublicDisplayName renders id's display name against a PublicUsersByIDs result, including for ids the batch did not resolve at all (never-existed accounts, which are absent from the map rather than tombstoned). It is the whole author-name branch a caller would otherwise write around every lookup.

Types

type APIKey

type APIKey struct {
	ID          string
	KeyID       string
	Name        string
	Role        string
	Permissions []string
	CreatedBy   string
	CreatedAt   time.Time
	LastUsedAt  *time.Time
	ExpiresAt   *time.Time
	RevokedAt   *time.Time
}

type APIKeyMintOptions

type APIKeyMintOptions struct {
	Name      string
	Role      string
	CreatedBy string
	ExpiresAt *time.Time
}

type APIKeys added in v0.72.0

type APIKeys interface {
	MintAPIKey(ctx context.Context, persona, instanceSlug, name, role, createdBy string, expiresAt *time.Time) (APIKey, string, error)
	MintAPIKeyWithOptions(ctx context.Context, persona, instanceSlug string, opts APIKeyMintOptions) (APIKey, string, error)
	ListAPIKeys(ctx context.Context, persona, instanceSlug string) ([]APIKey, error)
	RevokeAPIKey(ctx context.Context, persona, instanceSlug, tokenID string) (bool, error)
	ResolveAPIKey(ctx context.Context, keyID, secret string) (string, []string, error)
	ResolveAPIKeyDetailed(ctx context.Context, keyID, secret string) (ResolvedAPIKey, error)
}

APIKeys mints, lists, revokes, and resolves opaque API keys.

type AccountRegistrationInvite added in v0.72.0

type AccountRegistrationInvite struct {
	ID         string
	Email      string
	InvitedBy  string
	ExpiresAt  time.Time
	RevokedAt  *time.Time
	ConsumedAt *time.Time
	ConsumedBy *string
	// Persona/InstanceSlug/Role describe an OPTIONAL group role the code also grants
	// on consume (#147 register+join). Empty for a plain registration invite.
	Persona      string
	InstanceSlug string
	Role         string
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

type AccountRegistrationInviteCreated added in v0.72.0

type AccountRegistrationInviteCreated struct {
	ID        string
	Code      string
	URL       string
	Email     string
	ExpiresAt time.Time
	// Persona/InstanceSlug/Role echo the optional group grant carried by the code.
	Persona      string
	InstanceSlug string
	Role         string
}

type Admin added in v0.72.0

type Admin interface {
	AdminCountUsers(ctx context.Context, opts AdminUserListOptions) (int64, error)
	AdminGetUser(ctx context.Context, id string) (*AdminUser, error)
	AdminListUserSessions(ctx context.Context, userID string) ([]Session, error)
	AdminListUsers(ctx context.Context, opts AdminUserListOptions) (*AdminListUsersResult, error)
	AdminRevokeUserSessions(ctx context.Context, userID string) error
	AdminSetPassword(ctx context.Context, userID, new string) error
	BanUser(ctx context.Context, userID string, reason *string, until *time.Time, bannedBy string) error
	UnbanUser(ctx context.Context, userID string) error
}

Admin is the intrinsic admin view of the user directory: list, inspect, ban, and admin-side session/password control.

type AdminListUsersResult

type AdminListUsersResult struct {
	Users  []AdminUser `json:"users"`
	Total  int64       `json:"total"`
	Limit  int         `json:"limit"`
	Offset int         `json:"offset"`
}

type AdminUser

type AdminUser struct {
	ID              string     `json:"id"`
	Email           *string    `json:"email"` // Nullable for phone-only users
	PhoneNumber     *string    `json:"phone_number"`
	Username        *string    `json:"username"`
	DiscordUsername *string    `json:"discord_username"`
	EmailVerified   bool       `json:"email_verified"`
	PhoneVerified   bool       `json:"phone_verified"`
	BannedAt        *time.Time `json:"banned_at,omitempty"`
	BannedUntil     *time.Time `json:"banned_until,omitempty"`
	BanReason       *string    `json:"ban_reason,omitempty"`
	BannedBy        *string    `json:"banned_by,omitempty"`
	DeletedAt       *time.Time `json:"deleted_at"`
	Biography       *string    `json:"biography"`
	CreatedAt       time.Time  `json:"created_at"`
	UpdatedAt       time.Time  `json:"updated_at"`
	LastLogin       *time.Time `json:"last_login"`
	Roles           []string   `json:"roles"`
	RemovedRoles    []string   `json:"removed_roles,omitempty"`
	Entitlements    []string   `json:"entitlements"`
	// PreferredLanguage carries the user's stored language preference through from
	// the loaded user row, so callers (e.g. GET /me) need not issue a separate
	// language read (#228). Omitted from JSON when unset.
	PreferredLanguage *string `json:"preferred_language,omitempty"`
	// AvatarURL is the host-supplied avatar URL/key string (#262).
	AvatarURL *string `json:"avatar_url,omitempty"`
}

type AdminUserListOptions

type AdminUserListOptions struct {
	Page        int
	PageSize    int
	Search      string          // ILIKE over username/email/phone_number
	Role        string          // root_role slug (e.g. "admin"); empty = no role filter
	Status      AdminUserStatus // empty = non-deleted (historical default)
	Sort        AdminUserSort   // empty = created_at
	Desc        bool            // true = descending
	Entitlement string          // empty = no entitlement filter; else provider-backed
}

type AdminUserSort

type AdminUserSort string

type AdminUserStatus

type AdminUserStatus string

type ApplicationDocument added in v0.88.0

type ApplicationDocument struct {
	// Slug is the REQUESTED handle — a free claim through the same
	// availability + anti-squat gates as any org (slugs and domains are
	// separate). Empty defaults to the serving domain's hostname.
	Slug string `json:"slug"`
	// DisplayName is free-form, non-unique metadata.
	DisplayName string `json:"display_name,omitempty"`
	// Issuer is the application's token `iss`; its host must be the serving
	// domain outside dev-like environments.
	Issuer string `json:"issuer"`
	// JWKSURI XOR PublicKeys: exactly one trust source.
	JWKSURI    string         `json:"jwks_uri,omitempty"`
	PublicKeys []RemoteAppKey `json:"public_keys,omitempty"`
	// DocumentEndpoint is the optional signed-document base URL.
	DocumentEndpoint string `json:"document_endpoint,omitempty"`
}

ApplicationDocument is the well-known application.json a self-registering application serves at https://<domain>/.well-known/authkit/application.json. Unknown fields are ignored (forward-compatible).

type Authorizer added in v0.67.0

type Authorizer interface {
	Can(ctx context.Context, subjectID, subjectKind, persona, instanceSlug, perm string) (bool, error)
	ListEffectivePermissions(ctx context.Context, subjectID, subjectKind, persona, instanceSlug string) ([]string, error)
	IsUserAllowed(ctx context.Context, userID string) (bool, error)
	RoleSlugsByUsers(ctx context.Context, userIDs []string) (map[string][]string, error)
}

Authorizer is a cross-cutting authorization view (#143): the "can this subject do X here" methods. Unlike the per-topic interfaces in client.go, it spans three of them (Groups for permission checks, Users for the live-user/ban gate, Roles for role resolution), so it is defined here as its own narrow view rather than mapping to one. *embedded.Client (and the full authkit.Client) satisfies it, so a host whose authorization layer wants just these four methods can depend on this slice instead of the whole surface.

Add a cross-cutting slice like this only when a real consumer signature needs one; the per-topic interfaces (Users, Tokens, Groups, ...) cover the rest.

type Bootstrap added in v0.72.0

type Bootstrap interface {
	// ApplyBootstrapManifest applies a parsed manifest. There is deliberately no
	// ApplyBootstrapManifestFile on the contract: a file path is the SERVER's
	// filesystem, meaningless over a remote transport (#142). Hosts with a file
	// load it themselves (e.g. embedded.LoadBootstrapManifestFile) then call this.
	ApplyBootstrapManifest(ctx context.Context, manifest BootstrapManifest, opts BootstrapReconcileOptions) (BootstrapManifestResult, error)
}

Bootstrap applies a parsed bootstrap manifest (operator/deploy seeding).

type BootstrapManifest

type BootstrapManifest struct {
	Users              []BootstrapManifestUser              `json:"users" yaml:"users"`
	RemoteApplications []BootstrapManifestRemoteApplication `json:"remote_applications" yaml:"remote_applications"`
	// Dev carries dev-only runtime fixtures (#266). NOT part of the apply-once
	// reconcile: hosts read it at every boot and honor it only in a dev
	// environment (fail-closed).
	Dev BootstrapManifestDev `json:"dev,omitempty" yaml:"dev,omitempty"`
}

type BootstrapManifestDev added in v0.89.0

type BootstrapManifestDev struct {
	// StaticEntitlements are entitlement names seeded into every access token
	// via a static EntitlementsProvider — billing/entitlement E2E fixtures as
	// reviewable YAML (formerly the AUTHKIT_STATIC_ENTITLEMENTS env CSV, #266).
	StaticEntitlements []string `json:"static_entitlements,omitempty" yaml:"static_entitlements,omitempty"`
}

BootstrapManifestDev is the dev-only fixture section of a bootstrap manifest.

type BootstrapManifestRemoteApplication

type BootstrapManifestRemoteApplication struct {
	Slug       string         `json:"slug" yaml:"slug"`
	Issuer     string         `json:"issuer" yaml:"issuer"`
	JWKSURI    string         `json:"jwks_uri" yaml:"jwks_uri"`
	PublicKeys []RemoteAppKey `json:"public_keys" yaml:"public_keys"`
	Enabled    *bool          `json:"enabled" yaml:"enabled"`
	RootRole   string         `json:"root_role" yaml:"root_role"`
}

type BootstrapManifestResult

type BootstrapManifestResult struct {
	DryRun              bool `json:"dry_run"`
	AlreadyApplied      bool `json:"already_applied"`
	UsersCreated        int  `json:"users_created"`
	UsersUpdated        int  `json:"users_updated"`
	PasswordsSet        int  `json:"passwords_set"`
	PasswordsKept       int  `json:"passwords_kept"`
	RootRoleAssignments int  `json:"root_role_assignments"`
	RemoteApplications  int  `json:"remote_applications"`
	RemoteAppRootRoles  int  `json:"remote_application_root_roles"`
}

type BootstrapManifestUser

type BootstrapManifestUser struct {
	Email         string                 `json:"email" yaml:"email"`
	PhoneNumber   string                 `json:"phone_number" yaml:"phone_number"`
	Username      string                 `json:"username" yaml:"username"`
	EmailVerified bool                   `json:"email_verified" yaml:"email_verified"`
	PhoneVerified bool                   `json:"phone_verified" yaml:"phone_verified"`
	Banned        bool                   `json:"banned" yaml:"banned"`
	BannedAt      *time.Time             `json:"banned_at" yaml:"banned_at"`
	BannedUntil   *time.Time             `json:"banned_until" yaml:"banned_until"`
	BanReason     *string                `json:"ban_reason" yaml:"ban_reason"`
	BannedBy      *string                `json:"banned_by" yaml:"banned_by"`
	Metadata      map[string]any         `json:"metadata" yaml:"metadata"`
	Password      *BootstrapUserPassword `json:"password" yaml:"password"`
	// RootRole assigns one root permission-group role to this user by name.
	// "owner" (the built-in apex, root:*) is seeded SEED-IF-ABSENT; any other
	// name is assigned as a same-named catalog role of the root persona.
	RootRole string `json:"root_role" yaml:"root_role"`
}

type BootstrapReconcileOptions

type BootstrapReconcileOptions struct {
	DryRun bool
	// StartupOnly applies the manifest at most once, using Name as the marker.
	// Leave false for ordinary operator/CLI applies.
	StartupOnly bool
	// Name scopes the startup apply-once marker. Empty means "default".
	Name string
}

type BootstrapUserPassword

type BootstrapUserPassword struct {
	Plaintext     string         `json:"plaintext" yaml:"plaintext"`
	Hash          string         `json:"hash" yaml:"hash"`
	HashAlgo      string         `json:"hash_algo" yaml:"hash_algo"`
	HashParams    map[string]any `json:"hash_params" yaml:"hash_params"`
	ResetRequired bool           `json:"reset_required" yaml:"reset_required"`
	// Enforce makes the password DESIRED-STATE (#89): re-asserted on every
	// reconcile. Default false = SEED-ONCE — the password is applied only when
	// the user is first created, so a password rotated out of band (via the
	// admin API) is never reverted to the manifest value on a later reconcile.
	// Must not be combined with ResetRequired (forcing a reset every run is
	// nonsensical).
	Enforce bool `json:"enforce" yaml:"enforce"`
}

type Client

Client is the portable AuthKit contract: the full set of operations meaningful across both the in-process (embedded) and the Phase-2 remote transports (issue #138), composed from the topic interfaces above. Infra accessors (Postgres, Keyfunc, JWKS, raw Options/Schema) are deliberately OFF this interface; they stay on the concrete *embedded.Client. Code against authkit.Client (or one of the topic interfaces) so swapping backends is construction-only:

c, err := embedded.New(cfg, pg) // today (in-process)
var _ authkit.Client = c
// c, err := remote.New(url, creds) // Phase 2 (standalone)

type CreateAccountRegistrationInviteRequest added in v0.72.0

type CreateAccountRegistrationInviteRequest struct {
	Email     string
	InvitedBy string
	ExpiresIn time.Duration
	// Persona/InstanceSlug/Role, when all set, make this a register+join invite: the
	// minted code ALSO grants the given role in that permission group on consume
	// (#147). The minting actor must hold that group's members:manage (no-escalation);
	// a role-carrying invite does NOT require general root:users:invite. Leave empty
	// for a plain registration invite (root:users:invite gated).
	Persona      string
	InstanceSlug string
	Role         string
}

type CreateGroupInviteLinkRequest

type CreateGroupInviteLinkRequest struct {
	Persona      string
	InstanceSlug string
	Role         string
	ExpiresIn    time.Duration
	InvitedBy    string
}

type CreatePermissionGroupRequest

type CreatePermissionGroupRequest struct {
	Persona            string
	InstanceSlug       string
	ParentPersona      string
	ParentInstanceSlug string
	OwnerSubjectID     string
	// OwnerSubjectKind selects the owner principal kind: "user" (default) or
	// "remote_application" (#264 service-owned orgs — an application principal
	// owning its own permission group).
	OwnerSubjectKind string
	// DisplayName is free-form, non-unique group metadata (#264 naming
	// doctrine: vanity naming lives here, never on the slug).
	DisplayName string
}

type CustomJWTMintOptions

type CustomJWTMintOptions struct {
	// Claims is the host's claim set, e.g. {"cap_kind": "...", "grants": [...],
	// "release_id": "..."}. Required and non-empty. It may carry `sub`/`aud`
	// (unless overridden by the Subject/Audiences options) but may NOT carry the
	// AuthKit-owned registered claims `iss`/`iat`/`exp`.
	Claims map[string]any
	// TTL is the token lifetime. Required (must be > 0); capped at
	// MaxCustomJWTLifetime.
	TTL time.Duration
	// Type is the JOSE `typ` header (e.g. "worker-capability+jwt"). When empty the
	// header is left unset — unlike the opinionated minters, MintCustomJWT does
	// not impose a default `typ`; the host owns the token shape. It may NOT be one
	// of AuthKit's own first-party classes (access / delegated-access /
	// remote-application-access / service `+jwt`) — doing so returns
	// ErrCustomJWTReservedType (AK2-AUTH-02).
	Type string
	// Subject, when set, becomes the `sub` claim and wins over any `sub` in Claims.
	Subject string
	// Audiences, when set, becomes the `aud` claim and wins over any `aud` in Claims.
	Audiences []string
	// Issuer, when set, becomes the `iss` claim; otherwise `iss` defaults to the
	// Service's configured Issuer. This is the ONLY way to override `iss`.
	Issuer string
}

type DelegatedAccessParams

type DelegatedAccessParams struct {
	// Issuer becomes the `iss` claim: the AuthKit issuer that signed the token.
	// Must match a remote_application registered with the validating resource server.
	// Required when minting via the free function; the *Service mint method
	// defaults it to the Service's configured Issuer when empty.
	Issuer string
	// Audiences becomes the `aud` claim: the target resource API(s), e.g.
	// "openrails", "tensorhub", or "gen-orchestrator".
	Audiences []string
	// DelegatedSubject becomes `delegated_sub`: the issuer-side subject id.
	// Required. No local account is implied in the receiving service.
	DelegatedSubject string
	// Permissions becomes the `permissions` claim: an array of resource-defined
	// permission strings (NOT OAuth's space-delimited `scope`). Receiving
	// services validate these against their own permission set.
	Permissions []string
	// Documents becomes the top-level `documents` claim: versioned document
	// type -> canonical sha256 digest. AuthKit transports and validates these
	// references but does not resolve or interpret their payload schemas.
	Documents map[string]string
	// Attributes becomes the `attributes` claim: the canonical app-specific
	// ESCAPE HATCH (#75). An object of issuer-asserted, NAMESPACED, OPAQUE
	// key/values that AuthKit transports + optionally shape-validates but NEVER
	// interprets — the semantics belong to the consuming app (tensorhub etc.).
	// Each value is set in ONE of two modes, per key:
	//   INLINE    — the value carries the full definition, e.g.
	//               {"tier":{"endpoints":[...],"caps":[...]}}. No lookup.
	//   REFERENCE — the value is a short string key, e.g. {"tier":"tier-1"},
	//               resolved by the consumer against a definition the
	//               remote_application registered ahead of time (see the
	//               attribute-def registry: Service.RegisterRemoteAppAttributeDef
	//               / ResolveRemoteAppAttributeDef). Keeps tokens small.
	// Reserved well-known keys: `tier` (opaque entitlement-tier string), `roles`
	// (a uuid array; prefer the typed Roles field below), and `documents` (use the
	// top-level Documents field above). Everything else is free-form per consuming
	// app. Values are arbitrary JSON.
	Attributes map[string]any
	// Roles is a convenience for emitting the delegated subject's role UUIDs into
	// `attributes.roles` (a JSON array of UUID strings). Equivalent to setting
	// Attributes["roles"] yourself; when both are set this typed field wins.
	Roles []string
	// TTL is the token lifetime. Defaults to 15m when zero.
	TTL time.Duration
	// JTI becomes the `jti` claim (token identifier). Optional to SET, but
	// always PRESENT on the minted token: when empty the minter generates a
	// fresh uuidv7, so a receiving service can revoke any delegated token by
	// id without a per-issuer "does this one have a jti" carve-out.
	JTI string
	// NotBefore, when set, becomes the `nbf` claim. Optional.
	NotBefore time.Time
}

type DeletePermissionGroupOptions added in v0.88.0

type DeletePermissionGroupOptions struct {
	ReleaseSlug bool
}

DeletePermissionGroupOptions controls the delete-time naming rule (#264): by DEFAULT a deleted group's slug is TOMBSTONED to its uuid forever (fail-safe — published references can never be re-claimed by someone else). ReleaseSlug frees the name (and drops the group's own tombstones) instead; that is safe ONLY for names nothing ever referenced, and the judgment is the host's. authkit never deletes a group on its own.

type DocumentEnvelope added in v0.86.0

type DocumentEnvelope = documents.Envelope

type DocumentReference added in v0.86.0

type DocumentReference = documents.Reference

type Documents added in v0.86.0

type Documents interface {
	SignDocument(ctx context.Context, envelope DocumentEnvelope) (SignedDocument, error)
}

Documents signs immutable opaque JSON envelopes with the service's current AuthKit key. Verification and resolution live in documents + verify.

type Entitlements added in v0.72.0

type Entitlements interface {
	ListEntitlements(ctx context.Context, userID string) []string
}

Entitlements reads a user's active entitlement names from the host-provided EntitlementsProvider.

type ErrorEnvelope

type ErrorEnvelope struct {
	Error ErrorObject `json:"error"`
}

ErrorEnvelope is the top-level error response: {"error": {...}}.

func NewErrorEnvelope

func NewErrorEnvelope(status int, code string, param *string, metadata map[string]any) ErrorEnvelope

NewErrorEnvelope builds the canonical nested error envelope for an HTTP status + machine code: the type is derived from the status and the message from the code catalog. param and metadata are optional (omitted when nil/empty).

type ErrorObject

type ErrorObject struct {
	Type     string         `json:"type"`
	Code     string         `json:"code"`
	Message  string         `json:"message"`
	Param    *string        `json:"param,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

ErrorObject is the nested error detail carried under the top-level "error" key.

type GroupInstance added in v0.93.0

type GroupInstance struct {
	ID           string
	Persona      string
	InstanceSlug string
	DisplayName  string
}

GroupInstance is one persona instance's own identity (#269): the addressing pair a caller already holds, plus the uuid a HOST needs to own rows about the group in its own (or a sibling service's) ledger — openrails' `customer_id` being the case that forced it. Group ids never appear in a PATH; this type is how a caller who already has authority over an instance LEARNS its id.

type GroupInviteLink struct {
	ID                string
	PermissionGroupID string
	Role              string
	InvitedBy         string
	// RedeemedAt is non-nil once the single-use link has been redeemed (#235;
	// replaces the former Uses 0/1 counter).
	RedeemedAt *time.Time
	ExpiresAt  *time.Time
	RevokedAt  *time.Time
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

type GroupInviteLinkCreated

type GroupInviteLinkCreated struct {
	ID   string
	Code string
	URL  string
}

type GroupMember

type GroupMember struct {
	SubjectID   string
	SubjectKind string
	Role        string
}

type Groups added in v0.72.0

type Groups interface {
	CreatePermissionGroup(ctx context.Context, req CreatePermissionGroupRequest) (string, error)
	EnsureRootGroup(ctx context.Context) (string, error)
	SeedPermissionGroupContainment(ctx context.Context) error
	ResolveGroupIDForSlug(ctx context.Context, persona, instanceSlug string) (string, error)
	GroupInstanceForSlug(ctx context.Context, persona, instanceSlug string) (GroupInstance, error)
	CreateAccountRegistrationInvite(ctx context.Context, req CreateAccountRegistrationInviteRequest) (AccountRegistrationInviteCreated, error)
	RevokeAccountRegistrationInvite(ctx context.Context, inviteID, actorUserID string) error
	AssignGroupRoleAs(ctx context.Context, actorUserID, persona, instanceSlug, subjectID, subjectKind, role string) error
	UnassignGroupRoleAs(ctx context.Context, actorUserID, persona, instanceSlug, subjectID, subjectKind, role string) error
	RemoveGroupSubjectAs(ctx context.Context, actorUserID, persona, instanceSlug, subjectID, subjectKind string) error
	LeaveGroup(ctx context.Context, userID, persona, instanceSlug string) error
	ListGroupMembers(ctx context.Context, persona, instanceSlug string) ([]GroupMember, error)
	ListSubjectGroups(ctx context.Context, subjectID, subjectKind string) ([]SubjectGroupMembership, error)
	Can(ctx context.Context, subjectID, subjectKind, persona, instanceSlug, perm string) (bool, error)
	ListEffectivePermissions(ctx context.Context, subjectID, subjectKind, persona, instanceSlug string) ([]string, error)
	CreateGroupInviteLink(ctx context.Context, req CreateGroupInviteLinkRequest) (GroupInviteLinkCreated, error)
	ListGroupInviteLinks(ctx context.Context, persona, instanceSlug string) ([]GroupInviteLink, error)
	RevokeGroupInviteLink(ctx context.Context, persona, instanceSlug, linkID string) error
	RedeemGroupInviteLink(ctx context.Context, code, redeemerUserID string) (RedeemGroupInviteLinkResult, error)
	ExternalInvitesEnabled() bool
}

Groups is the permission-group surface: lifecycle, membership, role assignment, authorization checks, and invite links. Role/subject mutation here is actor-checked (no-escalation) only; the unchecked bootstrap/genesis equivalent (AssignGroupRole) lives on embedded.Client.Genesis() (#241), not on this interface.

type ImportUnverifiedSolanaLinkInput added in v0.97.1

type ImportUnverifiedSolanaLinkInput struct {
	UserID          string
	Address         string
	Source          string
	SourceID        string
	SourceCreatedAt *time.Time
}

ImportUnverifiedSolanaLinkInput is a migration-only Solana identity claim. Importing reserves the address but does not make it a login method; the user must prove ownership through the normal SIWS flow before AuthKit trusts it.

type ImportUnverifiedSolanaLinkResult added in v0.97.1

type ImportUnverifiedSolanaLinkResult struct {
	Index   int
	UserID  string
	Address string
	Status  ImportUnverifiedSolanaLinkStatus
	Reason  string
}

ImportUnverifiedSolanaLinkResult is the outcome for one input row.

type ImportUnverifiedSolanaLinkStatus added in v0.97.1

type ImportUnverifiedSolanaLinkStatus string

ImportUnverifiedSolanaLinkStatus is the per-row outcome of a legacy Solana identity import.

type ImportUnverifiedSolanaLinksResult added in v0.97.1

type ImportUnverifiedSolanaLinksResult struct {
	Results  []ImportUnverifiedSolanaLinkResult
	Inserted int
	Skipped  int
	Rejected int
}

ImportUnverifiedSolanaLinksResult aggregates per-row wallet import outcomes.

type ImportUserInput

type ImportUserInput struct {
	Email         string
	PhoneNumber   string
	Username      string
	EmailVerified bool
	PhoneVerified bool
	BannedAt      *time.Time
	BannedUntil   *time.Time
	BanReason     *string
	BannedBy      *string
	Metadata      map[string]any
	CreatedAt     *time.Time
	UpdatedAt     *time.Time

	// Optional pre-hashed credential to import alongside the user (bulk legacy
	// migration). When PasswordHash is non-empty and the user row is inserted,
	// ImportUsers stores it verbatim. The verify-time whitelist (argon2id/bcrypt,
	// else legacy-reset-required) still governs login; bulk import does not
	// re-validate the hash, matching single-row UpsertPasswordHash.
	PasswordHash string
	HashAlgo     string
	HashParams   []byte
}

type ImportUserResult

type ImportUserResult struct {
	Index  int
	UserID string // set when Status == inserted
	Status ImportUserStatus
	Reason string // set for skipped/rejected (machine-ish: "duplicate_in_batch", "already_exists", or a validation code)
}

type ImportUserStatus

type ImportUserStatus string

type ImportUsersResult

type ImportUsersResult struct {
	Results  []ImportUserResult
	Inserted int
	Skipped  int
	Rejected int
}

type InstanceCreationDef added in v0.90.0

type InstanceCreationDef struct {
	// Enabled mounts POST /<persona>. Off by default.
	Enabled bool
	// SlugPattern further restricts creatable slugs beyond the built-in
	// instance-slug rule: an unanchored regexp source, anchored (^...$) at
	// schema build. Empty = built-in rule only.
	SlugPattern string
	// ReservedSlugs are exact lowercase slugs creatable only by callers holding
	// ReservedEscalationRole in the root group (a list is config, a route is not).
	ReservedSlugs []string
	// ReservedEscalationRole is the root-group role that may create reserved
	// slugs. Empty = reserved slugs are not creatable through this route at all.
	ReservedEscalationRole string
}

InstanceCreationDef opts a persona into the generated creation route (#263): POST /<persona> creates an instance with the authenticated user seeded as its owner. Only root-parented personas may enable it. AuthKit owns the anti-squat velocity limits (per-IP + per-user); host COST gates plug in through WithInstanceAdmission. Zero value = no creation route (existing behavior).

type MFAStatus

type MFAStatus struct {
	Enabled        bool
	Satisfied      bool
	AllowedMethods []string
}

type Maintenance added in v0.72.0

type Maintenance interface {
	CleanupExpiredAuthState(ctx context.Context) error
	ValidateVerificationConfiguration() error
}

Maintenance is operational upkeep run outside a request: expire stale auth state, validate the verification configuration.

type OpResult added in v0.80.0

type OpResult struct {
	ID  string
	Err error
}

OpResult is the per-item outcome of a batch mutation (#219/#222): batch writes return one OpResult per requested ID so partial failure is expressible — a bare single error on a bulk write would hide which item failed. Err == nil means the item succeeded.

Over the remote transport Err marshals as its sentinel wire code (#197), so errors.Is against authkit sentinels survives the round-trip; a non-sentinel error degrades to an opaque code string.

func (OpResult) MarshalJSON added in v0.80.0

func (r OpResult) MarshalJSON() ([]byte, error)

func (*OpResult) UnmarshalJSON added in v0.80.0

func (r *OpResult) UnmarshalJSON(b []byte) error

type PasswordlessConfirmResult

type PasswordlessConfirmResult struct {
	UserID   string
	Method   string
	ReturnTo string
}

type PasswordlessStartRequest

type PasswordlessStartRequest struct {
	Identifier         string
	Mode               string
	ReturnTo           string
	PreferredLanguage  string
	AccountInviteToken string
}

type PasswordlessStartResult

type PasswordlessStartResult struct {
	Sent    bool
	Channel string
	Code    string
	LinkURL string
}

type Passwords added in v0.72.0

type Passwords interface {
	ChangePassword(ctx context.Context, userID, current, new string, keepSessionID *string) error
	UpsertPasswordHash(ctx context.Context, userID, hash, algo string, params []byte) error
	VerifyUserPassword(ctx context.Context, userID, pass string) bool
}

Passwords is the password credential surface: change, import, verify.

type PersonaCapabilities added in v0.72.0

type PersonaCapabilities struct {
	APIKeys            bool
	RemoteApplications bool
	CustomRoles        bool
}

PersonaCapabilities are opt-in generated management capabilities for a persona.

type PreferredLanguage

type PreferredLanguage struct {
	Language string
}

type Principal added in v0.72.0

type Principal struct {
	Kind    PrincipalKind `json:"kind"`
	Issuer  string        `json:"issuer,omitempty"`
	Subject string        `json:"subject,omitempty"`
}

Principal is the small generic-auth shape host adapters expose.

type PrincipalKind added in v0.72.0

type PrincipalKind string

PrincipalKind is the broad AuthKit credential class for a verified request.

const (
	PrincipalKindUser              PrincipalKind = "user"
	PrincipalKindAPIKey            PrincipalKind = "api_key"
	PrincipalKindRemoteApplication PrincipalKind = "remote_application"
	PrincipalKindDelegated         PrincipalKind = "delegated"
	PrincipalKindService           PrincipalKind = "service"
)

type Providers added in v0.72.0

type Providers interface {
	// ImportUnverifiedSolanaLinks imports legacy wallet claims without trusting
	// them as login credentials. Only a later successful SIWS proof promotes an
	// imported claim to verified state.
	ImportUnverifiedSolanaLinks(ctx context.Context, inputs []ImportUnverifiedSolanaLinkInput) (ImportUnverifiedSolanaLinksResult, error)
	LinkProvider(ctx context.Context, userID, provider, subject string, email *string) error
	LinkProviderByIssuer(ctx context.Context, userID, issuer, providerSlug, subject string, email *string) error
	UnlinkProvider(ctx context.Context, userID, provider string) error
	// ProviderUsernames returns each user's stored username for the given
	// provider in ONE call (#219/#220; replaces the single GetProviderUsername).
	// Map keyed by user id; users without a stored username are absent.
	ProviderUsernames(ctx context.Context, userIDs []string, provider string) (map[string]string, error)
}

Providers links and unlinks external identity providers on an account.

type PublicUserRef added in v0.92.0

type PublicUserRef struct {
	ID string
	// Username is "" when unset OR when the user is a tombstone — see Deleted.
	// Prefer DisplayName over reading this directly.
	Username  string
	AvatarURL string // "" if unset or tombstoned
	Biography string // "" if unset or tombstoned
	CreatedAt time.Time
	// Deleted marks a TOMBSTONE: the id resolved to a soft-deleted account, so
	// the reference is not dangling — but every other field is zero, including
	// CreatedAt. Nothing about a deleted account is published. Callers render
	// DisplayName and show nothing else.
	Deleted bool
}

PublicUserRef is the PUBLIC-SAFE batch user projection (#268): the display identity of a user as other users may see it. It deliberately has NO email field — the type, not an `omitempty` tag or a caller's discipline, is what makes it safe to nest inside a response body.

Every field here is public by nature: a username, an avatar, a biography and a join date are what a profile page shows. Derived assets (thumbnail sizes, CDN rewrites) stay host-owned — authkit stores one avatar string (#262) and does not know a host's image pipeline.

func (PublicUserRef) DisplayName added in v0.92.0

func (r PublicUserRef) DisplayName() string

DisplayName is the name to render for a user, with the fallback both consumer hosts had independently hand-rolled: the username when there is one, else a stable, non-identifying `user-<first 8 of id>`. Tombstoned and unnamed users take the fallback.

type RedeemGroupInviteLinkResult

type RedeemGroupInviteLinkResult struct {
	Persona      string
	InstanceSlug string
	Role         string
}

type RegisteredApplication added in v0.88.0

type RegisteredApplication struct {
	Application     RemoteApplication
	OrgPersona      string
	OrgInstanceSlug string
	// Created is false for an idempotent re-registration (the boot-time
	// self-heal / rotation-from-root path).
	Created bool
}

RegisteredApplication is the result of a (re-)registration: the application row plus its service-owned org (the permission group the application principal owns).

type RegistrationMode added in v0.72.0

type RegistrationMode string

RegistrationMode is the public native-user self-registration policy (#147). It governs ONLY public self-registration; operators can always create users through privileged APIs, bootstrap, or manual DB operations regardless of mode.

Open       — anyone may self-register.
InviteOnly — self-registration requires a valid unbound account-registration
             invite code.
Closed      — no public self-registration at all.

The former AdminOnly / AdminBootstrapOnly / ManifestOnly modes were removed (#147): they described operator-side creation, not a public self-registration policy, and are subsumed by "use the privileged APIs" under any mode.

const (
	RegistrationModeOpen       RegistrationMode = "open"
	RegistrationModeInviteOnly RegistrationMode = "invite_only"
	RegistrationModeClosed     RegistrationMode = "closed"
)

type RegistrationVerificationPolicy added in v0.72.0

type RegistrationVerificationPolicy string

RegistrationVerificationPolicy controls whether a newly-registered contact must be verified.

const (
	RegistrationVerificationNone     RegistrationVerificationPolicy = "none"
	RegistrationVerificationOptional RegistrationVerificationPolicy = "optional"
	RegistrationVerificationRequired RegistrationVerificationPolicy = "required"
)

type RemoteAppAttributeDef

type RemoteAppAttributeDef struct {
	RemoteApplicationID string
	Key                 string
	Version             int32
	Definition          json.RawMessage
}

RemoteAppAttributeDef is a remote_application's registered attribute definition: the full inline value a REFERENCE-mode delegated-token attribute resolves to (#75). Definition is opaque JSON the consuming app interprets.

type RemoteAppKey

type RemoteAppKey struct {
	KID          string `json:"kid,omitempty" yaml:"kid,omitempty"`
	PublicKeyPEM string `json:"public_key_pem" yaml:"public_key_pem"`
}

RemoteAppKey is one entry of a static-mode principal's human-managed key list (stored as jsonb; edited like an authorized_keys file).

type RemoteApplication

type RemoteApplication struct {
	ID                string
	Slug              string
	PermissionGroupID string // controlling permission-group id
	Issuer            string // OIDC iss
	JWKSURI           string // OIDC jwks_uri (jwks mode only)
	// Mode is the trust source: RemoteAppModeJWKS (fetch from JWKSURI) XOR
	// RemoteAppModeStatic (human-managed PublicKeys list). Never both.
	Mode string
	// PublicKeys is the static-mode key list (empty in jwks mode).
	PublicKeys []RemoteAppKey
	Enabled    bool
	// DisplayName is free-form, non-unique vanity metadata (#264). The slug is
	// the public handle; the uuid is the internal join key.
	DisplayName string
	// Tier is the application's capability tier: ApplicationTierRegistered
	// (self-registered; zero default capability — authenticate + documents
	// only) or ApplicationTierApproved (an admin act on the host).
	Tier string
	// TrustRoot is what can rotate this application's keys (#264):
	// ApplicationTrustRootManual (admin/bootstrap-managed),
	// ApplicationTrustRootDomain (re-fetching Domain's application.json
	// re-proves control and adopts current keys), or
	// ApplicationTrustRootUser (the owning user's authenticated session).
	// Never the keypair alone.
	TrustRoot string
	// Domain is the trust-root location for domain-rooted applications (the
	// canonical registration input; empty otherwise). Domains and slugs are
	// SEPARATE: the domain proves identity, the slug is a claimed handle.
	Domain string
	// DocumentEndpoint is the application's optional signed-document base URL
	// declared in its application.json.
	DocumentEndpoint string
	// RootVerifiedAt is the last successful trust-root proof (zero when the
	// root was never proven, e.g. manual registrations).
	RootVerifiedAt time.Time
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

RemoteApplication is a registered federation principal: an external issuer authkit trusts to mint delegated/remote-application tokens. It is a plain data view; persistence and lifecycle live in core.

type RemoteApplicationAccessParams

type RemoteApplicationAccessParams struct {
	// Issuer becomes the `iss` claim: the remote_application's OIDC issuer,
	// registered with the validating resource server. Required when minting via
	// the free function; the *Service mint method defaults it to the Service's
	// configured Issuer when empty.
	Issuer string
	// Audiences becomes the `aud` claim: the target resource API(s).
	Audiences []string
	// TTL is the token lifetime. Defaults to 15m when zero.
	TTL time.Duration
	// JTI, when set, becomes the `jti` claim. Optional.
	JTI string
	// NotBefore, when set, becomes the `nbf` claim. Optional.
	NotBefore time.Time
	// Permissions, when non-nil, becomes the `permissions` claim: a DOWN-SCOPING
	// request for least-privilege (#76 amendment). The stored grant is the
	// ceiling; effective = this claim, but EVERY claimed perm must be within the
	// stored grant — an out-of-grant claimed perm REJECTS the token at verify (a
	// remote application access token can never widen). nil/absent => no claim
	// => full stored ceiling (backward-compatible with v0.28.0 tokens).
	Permissions []string
}

type RemoteApplicationAuthority added in v0.83.0

type RemoteApplicationAuthority struct {
	Permissions  []string
	Persona      string
	InstanceSlug string
}

RemoteApplicationAuthority is a remote_application's STORED authority: its role-resolved effective permissions plus the owning permission-group INSTANCE they are bound to (#248). InstanceSlug is "" for singleton personas (root). Exact-instance binding only; descendant/walk-down authority is deliberately deferred.

type RemoteApps added in v0.72.0

type RemoteApps interface {
	UpsertRemoteApplication(ctx context.Context, in RemoteApplication) (*RemoteApplication, error)
	GetRemoteApplication(ctx context.Context, issuer string) (*RemoteApplication, error)
	DeleteRemoteApplication(ctx context.Context, issuer string) error
	ListRemoteApplications(ctx context.Context, activeOnly bool) ([]RemoteApplication, error)
	ResolveRemoteApplicationAuthority(ctx context.Context, appID string) (RemoteApplicationAuthority, error)
	ResolveRemoteAppAttributeDef(ctx context.Context, appID, key string, version int32) (*RemoteAppAttributeDef, error)
}

RemoteApps manages trusted remote applications (federation issuers) and resolves their stored authority.

type ResolvedAPIKey

type ResolvedAPIKey struct {
	APIKeyID string
	KeyID    string
	// PermissionGroupID is the controlling permission-group id.
	PermissionGroupID string
	// Persona / InstanceSlug identify the owning permission-group INSTANCE the
	// key was minted on (#248). InstanceSlug is "" for singleton personas (root).
	// The verify layer binds the key's token-carried permissions to this exact
	// instance; descendant/walk-down authority is deliberately deferred.
	Persona      string
	InstanceSlug string
	Role         string
	Permissions  []string
}

ResolvedAPIKey is the API-key resolution result. Permissions is the key's role resolved to its effective permission set AT VERIFY TIME (so a role edit is reflected immediately — perms are never frozen into the key).

type Roles added in v0.72.0

type Roles interface {
	// Assign/RemoveRolesBySlugAs are batch-native (#219/#222): the actor-checked
	// no-escalation authority check (#136) runs PER ITEM inside the batch — an
	// actor may hold authority over some targets and not others, and each item's
	// OpResult carries its own ErrInsufficientRoleAuthority/ErrRoleAssignmentEscalation.
	// Per-item best-effort; single-item = one-element slice.
	AssignRolesBySlugAs(ctx context.Context, actorUserID string, userIDs []string, slug string) ([]OpResult, error)
	RemoveRolesBySlugAs(ctx context.Context, actorUserID string, userIDs []string, slug string) ([]OpResult, error)
	UpsertRoleBySlug(ctx context.Context, name, slug string, description *string) error
	// RoleSlugsByUsers returns each user's LIVE configured root permission-group
	// role slugs in ONE call — batch-native per the operation-shape rule (#219,
	// #220; replaces ListRoleSlugsByUser + ListRoleSlugsByUserErr). The map is
	// keyed by user id; users with no roles are absent. Errors PROPAGATE so authz
	// callers fail closed (#136) instead of reading an outage as "no roles".
	// Single-user = one-element slice + m[id].
	RoleSlugsByUsers(ctx context.Context, userIDs []string) (map[string][]string, error)
}

Roles is global root-role assignment, actor-checked (no-escalation) only. The unchecked bootstrap/genesis equivalents (AssignRoleBySlug, RemoveRoleBySlug) are NOT part of this in-process/RPC-swappable interface (#241) — they live on embedded.Client.Genesis(), an explicitly-dangerous seam reached only by the concrete embedded client, never through authkit.Client or the remote transport.

type Senders added in v0.72.0

type Senders interface {
	HasEmailSender() bool
	HasSMSSender() bool
	SMSAvailable() bool
	CheckSMSHealth(ctx context.Context) error
}

Senders reports whether the configured message senders are available and healthy.

type ServiceJWTClaims

type ServiceJWTClaims struct {
	Issuer      string
	Subject     string
	Audiences   []string
	IssuedAt    time.Time
	NotBefore   time.Time
	ExpiresAt   time.Time
	JTI         string
	TokenUse    string
	Permissions []string
	Scope       []string
}

ServiceJWTClaims is the canonical AuthKit claim shape for caller-minted machine-to-machine JWTs. Permissions are requested capabilities; receiving services must still intersect them with server-side grants.

type ServiceJWTMintOptions

type ServiceJWTMintOptions struct {
	Subject     string
	Audiences   []string
	Permissions []string
	Lifetime    time.Duration
	NotBefore   time.Time
	IssuedAt    time.Time
	JTI         string
}

type Session

type Session struct {
	ID                  string
	FamilyID            string
	CreatedAt           time.Time
	LastAuthenticatedAt *time.Time
	LastUsedAt          time.Time
	ExpiresAt           *time.Time
	RevokedAt           *time.Time
	UserAgent           *string
	IPAddr              *string
}

Session is a sanitized session view (no tokens). Part of the wire contract.

type Sessions added in v0.72.0

type Sessions interface {
	ListUserSessions(ctx context.Context, userID string) ([]Session, error)
	RevokeAllSessions(ctx context.Context, userID string, keepSessionID *string) error
}

Sessions is the backend session surface: list and revoke-all. Refresh-token EXCHANGE is deliberately NOT here — it is a browser/end-user request flow served by the /token endpoint, so it lives on the HTTP layer only (layer test, SEMVER §4.2). The engine impl stays on *authcore.Service; authkit's own /token handler calls it there via embedded.Unwrap.

type SignedDocument added in v0.86.0

type SignedDocument = documents.SignedDocument

type SubjectGroupMembership

type SubjectGroupMembership struct {
	// GroupID is the instance's internal uuid (#269). It is a JOIN KEY, not an
	// address — every route stays slug-addressed — and it is reported only for
	// the caller's OWN memberships.
	GroupID      string
	Persona      string
	InstanceSlug string
	DisplayName  string
	Role         string
}

type Tokens added in v0.72.0

type Tokens interface {
	// MintAccessToken signs a user access JWT (#214: Mint* = signing a JWT;
	// session creation — IssueRefreshSession* on the engine — is not a Mint).
	MintAccessToken(ctx context.Context, userID string, extra map[string]any) (string, time.Time, error)
	MintCustomJWT(ctx context.Context, opts CustomJWTMintOptions) (string, error)
	MintDelegatedAccessToken(ctx context.Context, p DelegatedAccessParams) (string, error)
	MintRemoteApplicationAccessToken(ctx context.Context, p RemoteApplicationAccessParams) (string, error)
	MintServiceJWT(ctx context.Context, opts ServiceJWTMintOptions) (string, ServiceJWTClaims, error)
}

Tokens issues the app's JWTs: access, service, delegated, remote-application, and custom.

type TwoFactorMethod added in v0.72.0

type TwoFactorMethod string

TwoFactorMethod is one second-factor channel a host enables.

const (
	TwoFactorEmail TwoFactorMethod = "email"
	TwoFactorSMS   TwoFactorMethod = "sms"
	TwoFactorTOTP  TwoFactorMethod = "totp"
)

type TwoFactorMode added in v0.72.0

type TwoFactorMode string

TwoFactorMode is the host's account-wide 2FA enrollment policy.

const (
	// TwoFactorDisabled turns 2FA off entirely: no user enrollment/challenge/
	// verify routes are usable.
	TwoFactorDisabled TwoFactorMode = "disabled"
	// TwoFactorOptional lets users enroll a second factor if they choose; an
	// un-enrolled user is not blocked from normal session use.
	TwoFactorOptional TwoFactorMode = "optional"
	// TwoFactorRequired forces every user to enroll a second factor before normal
	// session use. Existing un-enrolled users are challenged on their next
	// authenticated request (the session, not just signup, is gated).
	TwoFactorRequired TwoFactorMode = "required"
)

type User

type User struct {
	ID              string
	Email           *string // Nullable - phone-only users have NULL email
	PhoneNumber     *string
	Username        *string
	DiscordUsername *string
	EmailVerified   bool
	PhoneVerified   bool
	BannedAt        *time.Time
	BannedUntil     *time.Time
	BanReason       *string
	BannedBy        *string
	DeletedAt       *time.Time
	Biography       *string
	CreatedAt       time.Time
	UpdatedAt       time.Time
	LastLogin       *time.Time
	// PreferredLanguage is populated by the by-ID lookup (UserByID) only; other
	// lookups leave it nil. Nullable — NULL/unset when the user has no stored
	// language preference.
	PreferredLanguage *string
	// AvatarURL is the host-supplied avatar URL/key string (#262). Blob storage
	// stays host-owned; authkit stores only this string. Populated by the by-ID
	// lookup (UserByID) only, like PreferredLanguage.
	AvatarURL *string
}

User is the public user view returned by AuthKit lookups. Plain data — part of the wire contract shared by the embedded engine and (Phase 2) the remote SDK. See #138 (contract inversion): definitions live here in the lean, pgx-free contract package; internal/authcore aliases back to these.

type UserLiveness added in v0.92.0

type UserLiveness struct {
	ID string
	// Allowed is the same account gate that guards token mint at login and
	// refresh: false for deleted, banned and reserved accounts. An expired
	// temporary ban is allowed (and cleared, exactly as the single-user gate
	// clears it).
	Allowed       bool
	Username      string // "" if unset
	Email         string // "" if unset (phone-only accounts have none)
	EmailVerified bool
	AvatarURL     string // "" if unset
}

UserLiveness is the per-request account-liveness verdict for one user, plus the identity fields that are fresh AS OF that same lookup (#267). It is what verify's liveness gate consumes, and what lets a host stop reaching for an admin-privileged read just to refresh a username or email onto a request.

The verdict is deliberately BOOLEAN: it does not report whether a denial was a ban, a deletion or a reservation. That distinction is an account-status question for an authenticated, entitled surface — not something an authentication gate should hand back to whoever presented the token.

type UserRef added in v0.66.0

type UserRef struct {
	ID       string
	Username string // "" if unset
	Email    string // "" if unset
}

UserRef is a slim user projection (id + display fields) returned by batch lookups like Client.UsersByIDs — resolving many user IDs to display data in one query, without N+1 single fetches. Part of the wire contract.

It carries Email, so it is the PRIVILEGED batch projection: use it only where the caller is entitled to see addresses (admin surfaces, the account's own views). For anything rendered to other users — comment authors, gallery owners, public profiles — use PublicUserRef / Client.PublicUsersByIDs (#268), which has no email field at all.

type Users added in v0.72.0

type Users interface {
	CreateUser(ctx context.Context, email, username string) (*User, error)
	GetUserByEmail(ctx context.Context, email string) (*User, error)
	GetUserByPhone(ctx context.Context, phone string) (*User, error)
	GetUserBySolanaAddress(ctx context.Context, address string) (*User, error)
	GetUserByUsername(ctx context.Context, username string) (*User, error)
	GetUserMetadata(ctx context.Context, userID string) (map[string]any, error)
	PatchUserMetadata(ctx context.Context, userID string, patch map[string]any) error
	// {Hard,Soft}DeleteUsers / RestoreUsers are batch-native admin bulk mutations
	// (#219/#222): per-item BEST-EFFORT — deleting 99 of 100 succeeds item-by-item
	// and the returned OpResults pinpoint the failures. Single-item = one-element
	// slice. The outer error is a whole-call failure only (e.g. no store).
	// SetEmailVerified / UpdateEmail / UpdateUsername stay single by decision:
	// they are per-subject correctness flows, not bulk admin operations.
	HardDeleteUsers(ctx context.Context, userIDs []string) ([]OpResult, error)
	SoftDeleteUsers(ctx context.Context, userIDs []string) ([]OpResult, error)
	RestoreUsers(ctx context.Context, userIDs []string) ([]OpResult, error)
	SetEmailVerified(ctx context.Context, id string, v bool) error
	UpdateBiography(ctx context.Context, id string, bio *string) error
	// UpdateAvatarURL sets (or clears, with nil) the user's avatar URL/key
	// string (#262). Blob storage/validation is the host's job — authkit stores
	// the string and serves it on GET /me.
	UpdateAvatarURL(ctx context.Context, id string, avatarURL *string) error
	UpdateEmail(ctx context.Context, id, email string) error
	UpdateUsername(ctx context.Context, id, username string) error
	UpdateImportedUser(ctx context.Context, userID string, input ImportUserInput) (*User, error)
	ImportUsers(ctx context.Context, inputs []ImportUserInput) (ImportUsersResult, error)
	ListUsersDeletedBefore(ctx context.Context, cutoff time.Time, limit int) ([]string, error)
	TimeUntilUsernameRenameAvailable(ctx context.Context, userID string, now time.Time) (int64, error)
	IsUserAllowed(ctx context.Context, userID string) (bool, error)
	// UsersByIDs resolves many user IDs to slim display projections (id +
	// username/email) in ONE query: the batch read for "render N authors"
	// without N+1. Missing IDs are simply absent from the result. (Replaces the
	// removed authkit/identity store; writes go through UpdateUsername/UpdateEmail,
	// which enforce the rename cooldown + validation raw table writes skip.)
	// Returns map[id]UserRef (#219/#220): O(1) single-item access, missing IDs absent.
	//
	// PRIVILEGED — the projection carries Email. Render other users with
	// PublicUsersByIDs.
	UsersByIDs(ctx context.Context, ids []string) (map[string]UserRef, error)
	// PublicUsersByIDs is the PUBLIC-SAFE twin of UsersByIDs (#268): the same
	// one-query batch shape, projected to PublicUserRef — which has NO email
	// field — so a resolved author can be nested straight into a response body.
	// Soft-deleted users come back as tombstones (display fields blanked,
	// Deleted set); banned users come back normally, because a ban is an access
	// decision, not a visibility one; unknown ids are absent, and
	// PublicDisplayName covers them.
	PublicUsersByIDs(ctx context.Context, ids []string) (map[string]PublicUserRef, error)
	// UserLivenessByIDs is the batch account-liveness read behind verify's
	// per-request liveness gate (#267): the same ban/deleted/reserved verdict
	// that guards token mint, plus the identity fields (username, email,
	// email_verified, avatar) fresh as of that lookup — so a host has no reason
	// to call the admin directory to refresh display claims on a hot path.
	// Errors PROPAGATE so authorization callers fail closed; unknown ids are
	// absent from the map and a gate must treat that as a denial.
	UserLivenessByIDs(ctx context.Context, ids []string) (map[string]UserLiveness, error)
}

Users is account create/read/update/delete, identity lookups, metadata, and bulk import/read.

Directories

Path Synopsis
adapters
gin
Package authkitgin bridges AuthKit's net/http middleware to gin.
Package authkitgin bridges AuthKit's net/http middleware to gin.
twilio/internal/twiliocommon
Package twiliocommon holds the small helpers shared by AuthKit's Twilio email and SMS sender adapters (which are separate packages): request-language resolution, the app display label, and the default outbound HTTP client.
Package twiliocommon holds the small helpers shared by AuthKit's Twilio email and SMS sender adapters (which are separate packages): request-language resolution, the app display label, and the default outbound HTTP client.
Package authkitmigrate applies AuthKit's embedded Postgres migrations from host code, mirroring rivermigrate's shape:
Package authkitmigrate applies AuthKit's embedded Postgres migrations from host code, mirroring rivermigrate's shape:
Package testing provides utilities for testing applications that use authkit.
Package testing provides utilities for testing applications that use authkit.
cmd
authkit-server command
Command authkit-server is the standalone, self-hostable AuthKit server (#142).
Command authkit-server is the standalone, self-hostable AuthKit server (#142).
Package documents defines AuthKit's generic immutable signed-document wire contract.
Package documents defines AuthKit's generic immutable signed-document wire contract.
Re-exports of the public types, constants, sentinel errors, and helper functions implemented in internal/authcore.
Re-exports of the public types, constants, sentinel errors, and helper functions implemented in internal/authcore.
internal
db
Schema indirection (authkit issue 69).
Schema indirection (authkit issue 69).
genremote command
Command genremote generates the AuthKit remote SDK (authkit/remote) and the management-API method registry (authkit/server) from the authkit.Client interface in client.go — ONE source of truth for both transports (#142).
Command genremote generates the AuthKit remote SDK (authkit/remote) and the management-API method registry (authkit/server) from the authkit.Client interface in client.go — ONE source of truth for both transports (#142).
siws
Package siws implements Sign In With Solana (SIWS) authentication.
Package siws implements Sign In With Solana (SIWS) authentication.
testdb
Package testdb owns AuthKit's Postgres integration-test harness.
Package testdb owns AuthKit's Postgres integration-test harness.
migrations
postgres
Package migrations embeds AuthKit's Postgres schema migrations.
Package migrations embeds AuthKit's Postgres schema migrations.
Experimental: NOT covered by the v1 semver contract (#202) — the standalone/ remote transport has no production consumer yet; its surface (generated from authkit.Client) may change in MINOR releases until proven and promoted.
Experimental: NOT covered by the v1 semver contract (#202) — the standalone/ remote transport has no production consumer yet; its surface (generated from authkit.Client) may change in MINOR releases until proven and promoted.
Experimental: NOT covered by the v1 semver contract (#202) — the standalone/ remote transport has no production consumer yet; the wire contract may change in MINOR releases until proven and promoted.
Experimental: NOT covered by the v1 semver contract (#202) — the standalone/ remote transport has no production consumer yet; the wire contract may change in MINOR releases until proven and promoted.

Jump to

Keyboard shortcuts

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