diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,16 @@
 [PVP](https://pvp.haskell.org/) and is versioned independently of the other
 Shōmei packages.
 
+## 0.4.0.0 — 2026-11-25
+
+- **Breaking:** require the Shōmei 0.4 API series.
+
+- Add users reset-mfa with explicit operator, case, owner-verification and target-confirmation flags; share the audited workflow and configured bounded notification delivery. Support secret-free second-factor reset notices in every built-in transport.
+
+- Body/rate rejections in OAuth namespaces return 413 invalid_request / 429 temporarily_unavailable as non-cacheable OAuth JSON; application routes retain problem documents. Add hostMiddlewareWithOAuthMounts and authContextWithOAuthMounts for embedding parity. Packaged-executable Hurl acceptance runs through just test-oauth-contract and CI.
+
+- Fix admin redirect requirements, audit type validation, lifetime-independent revocation guidance, keyless no-op TOTP conversion, and concise redacted configuration errors. Add Prometheus HELP metadata and decimal bucket labels. Exact finite `le` label spellings change and may create new Prometheus series; update dashboards that match their old text.
+
 ## 0.3.0.1 — 2026-11-17
 
 - Admit `base64` 2.0 and 2.1 (`>=1.0 && <2.2`). No source or API change.
diff --git a/app/Admin.hs b/app/Admin.hs
--- a/app/Admin.hs
+++ b/app/Admin.hs
@@ -19,9 +19,10 @@
 import Shomei.Admin.Roles (RolesCommand, rolesParser, runRoles)
 import Shomei.Admin.ServiceAccounts (ServiceAccountsCommand, runServiceAccounts, serviceAccountsParser)
 import Shomei.Admin.Sweep (SweepOptions, runSweep, sweepParser)
-import Shomei.Admin.Users (createUserAction)
+import Shomei.Admin.Users (ResetMfaOptions, createUserAction, resetMfaAction, resetMfaParser, validateResetMfaOptions)
 import Shomei.Mfa.Totp.Postgres (checkTotpEnvelopeVersions, migrateTotpEnvelopeBatch, totpEncryptionKeyFromBase64)
 import Shomei.Migrations (applyShomeiMigrations)
+import Shomei.Server.ConfigurationError (reportConfigurationError)
 import Shomei.Server.Keys (loadKekFromEnv, loadNamedKekFromEnv)
 import Shomei.SigningKey.Domain (SigningAlgorithm (ES256), signingAlgorithmFromText)
 import System.Environment (lookupEnv)
@@ -49,12 +50,14 @@
   | KeysList
   | KeysRewrap
 
-data UsersCommand = UsersCreate
-  { email :: Text,
-    passwordFile :: Maybe FilePath,
-    displayName :: Maybe Text,
-    emailVerified :: Bool
-  }
+data UsersCommand
+  = UsersCreate
+      { email :: Text,
+        passwordFile :: Maybe FilePath,
+        displayName :: Maybe Text,
+        emailVerified :: Bool
+      }
+  | UsersResetMfa ResetMfaOptions
 
 commandParser :: Parser Command
 commandParser =
@@ -106,7 +109,9 @@
 usersParser :: Parser UsersCommand
 usersParser =
   hsubparser
-    (command "create" (info createOpts (progDesc "Create a user account")))
+    ( command "create" (info createOpts (progDesc "Create a user account"))
+        <> command "reset-mfa" (info (UsersResetMfa <$> resetMfaParser) (progDesc "Recover independently verified owners after loss of every second factor"))
+    )
   where
     createOpts =
       UsersCreate
@@ -128,7 +133,7 @@
 run :: Command -> IO ()
 run = \case
   Migrate -> do
-    env <- loadAdminEnv
+    env <- reportConfigurationError "shomei-admin" loadAdminEnv
     applyShomeiMigrations env.connStr >>= \case
       Left migrationError -> do
         hPutStrLn stderr ("shomei-admin: schema migration failed: " <> show migrationError)
@@ -144,7 +149,7 @@
               <> "); run `shomei-migrate status` for per-migration detail"
           )
   Keys kc -> do
-    env <- loadAdminEnv
+    env <- reportConfigurationError "shomei-admin" loadAdminEnv
     case kc of
       KeysGenerate alg -> do
         kek <- loadKekFromEnv
@@ -159,25 +164,31 @@
         keysRewrap oldKek newKek env.pool
   Users (UsersCreate {email, passwordFile, displayName, emailVerified}) -> do
     password <- readPasswordSecret passwordFile
-    env <- loadAdminEnv
+    env <- reportConfigurationError "shomei-admin" loadAdminEnv
     createUserAction env email password displayName emailVerified
+  Users (UsersResetMfa recoveryOptions) -> do
+    case validateResetMfaOptions recoveryOptions of
+      Left message -> hPutStrLn stderr (Text.unpack message) >> exitFailure
+      Right () -> pure ()
+    env <- reportConfigurationError "shomei-admin" loadAdminEnv
+    resetMfaAction env recoveryOptions
   Roles rc -> do
-    env <- loadAdminEnv
+    env <- reportConfigurationError "shomei-admin" loadAdminEnv
     runRoles env rc
   ServiceAccounts sc -> do
-    env <- loadAdminEnv
+    env <- reportConfigurationError "shomei-admin" loadAdminEnv
     runServiceAccounts env sc
   OAuthClients oc -> do
-    env <- loadAdminEnv
+    env <- reportConfigurationError "shomei-admin" loadAdminEnv
     runOAuthClients env oc
   Audit ac -> do
-    env <- loadAdminEnv
+    env <- reportConfigurationError "shomei-admin" loadAdminEnv
     runAudit env ac
   Sweep opts -> do
-    env <- loadAdminEnv
+    env <- reportConfigurationError "shomei-admin" loadAdminEnv
     runSweep env opts
   TotpMigrateEnvelopes check offline -> do
-    env <- loadAdminEnv
+    env <- reportConfigurationError "shomei-admin" loadAdminEnv
     let die message = hPutStrLn stderr message >> exitFailure
         counts = checkTotpEnvelopeVersions env.pool >>= either (const (die "shomei-admin: TOTP version/schema check failed")) pure
     (legacy, invalid) <- counts
@@ -187,25 +198,28 @@
       else do
         if not offline then die "shomei-admin: stop all Shomei writers, retain database/key backup, then pass --offline" else pure ()
         if invalid /= 0 then die "shomei-admin: unknown TOTP envelope version; conversion refused" else pure ()
-        raw <- lookupEnv "SHOMEI_TOTP_ENCRYPTION_KEY"
-        key <-
-          either
-            (const (die "shomei-admin: valid SHOMEI_TOTP_ENCRYPTION_KEY required"))
-            pure
-            (maybe (Left "missing") (totpEncryptionKeyFromBase64 . Text.pack) raw)
-        let loop total conflicts = do
-              (remaining, unknown) <- counts
-              if unknown /= 0
-                then die "shomei-admin: unknown TOTP envelope version"
-                else
-                  if remaining == 0
-                    then putStrLn ("converted=" <> show total)
-                    else do
-                      converted <- migrateTotpEnvelopeBatch key env.pool >>= either (const (die "shomei-admin: TOTP batch failed; restore key/snapshot and retry; no unreadable row overwritten")) pure
-                      if converted == 0 && conflicts >= (2 :: Int)
-                        then die "shomei-admin: repeated conversion conflicts; verify all writers are stopped"
-                        else loop (total + converted) (if converted == 0 then conflicts + 1 else 0)
-        loop (0 :: Int) 0
+        if legacy == 0
+          then putStrLn "converted=0"
+          else do
+            raw <- lookupEnv "SHOMEI_TOTP_ENCRYPTION_KEY"
+            key <-
+              either
+                (const (die "shomei-admin: valid SHOMEI_TOTP_ENCRYPTION_KEY required"))
+                pure
+                (maybe (Left "missing") (totpEncryptionKeyFromBase64 . Text.pack) raw)
+            let loop total conflicts = do
+                  (remaining, unknown) <- counts
+                  if unknown /= 0
+                    then die "shomei-admin: unknown TOTP envelope version"
+                    else
+                      if remaining == 0
+                        then putStrLn ("converted=" <> show total)
+                        else do
+                          converted <- migrateTotpEnvelopeBatch key env.pool >>= either (const (die "shomei-admin: TOTP batch failed; restore key/snapshot and retry; no unreadable row overwritten")) pure
+                          if converted == 0 && conflicts >= (2 :: Int)
+                            then die "shomei-admin: repeated conversion conflicts; verify all writers are stopped"
+                            else loop (total + converted) (if converted == 0 then conflicts + 1 else 0)
+            loop (0 :: Int) 0
 
 -- | Read a secret without placing it in argv. A terminal gets a no-echo prompt; redirected
 -- stdin and files are consumed in full. Remove exactly one conventional line ending so
diff --git a/app/Shomei/Admin/Audit.hs b/app/Shomei/Admin/Audit.hs
--- a/app/Shomei/Admin/Audit.hs
+++ b/app/Shomei/Admin/Audit.hs
@@ -38,6 +38,7 @@
 import Effectful.Error.Static (Error, runErrorNoCallStack)
 import Options.Applicative
 import Shomei.Admin.Env (AdminEnv (..))
+import Shomei.Audit.Event.Codec (knownAuthEventTypes)
 import Shomei.Audit.Reader.Postgres (runAuthEventReaderPostgres)
 import Shomei.Audit.Reader.Store
   ( AuditEventQuery (..),
@@ -89,7 +90,7 @@
   AuditFilters
     <$> optional (txt (long "user" <> metavar "USER_ID" <> help "Canonical user TypeID or legacy UUID"))
     <*> optional (txt (long "session" <> metavar "SESSION_ID" <> help "Canonical session TypeID or legacy UUID"))
-    <*> many (txt (long "type" <> metavar "EVENT_TYPE" <> help "Filter by event type (repeatable)"))
+    <*> many (option (eitherReader (validateEventType . Text.pack)) (long "type" <> metavar "EVENT_TYPE" <> help "Filter by event type known to this binary (repeatable)"))
     <*> optional (txt (long "since" <> metavar "ISO8601" <> help "Only events at or after this time (inclusive)"))
     <*> optional (txt (long "until" <> metavar "ISO8601" <> help "Only events strictly before this time"))
     <*> option auto (long "limit" <> metavar "N" <> value 50 <> showDefault <> help "Max rows (clamped to 1000)")
@@ -146,6 +147,7 @@
 -- | Validate the textual filters into an 'AuditEventQuery' (a bad typed ID/UUID/timestamp aborts).
 toQuery :: AuditFilters -> IO AuditEventQuery
 toQuery f = do
+  forM_ f.fTypes (either die (const (pure ())) . validateEventType)
   user <- parseIdentityOpt (fmap userIdToUUID . parseId) "--user" f.fUser
   session <- parseIdentityOpt (fmap sessionIdToUUID . parseId) "--session" f.fSession
   since <- parseTimeOpt "--since" f.fSince
@@ -190,3 +192,8 @@
 
 die :: String -> IO a
 die msg = hPutStrLn stderr ("shomei-admin: " <> msg) >> exitFailure
+
+validateEventType :: Text -> Either String Text
+validateEventType ty
+  | ty `elem` knownAuthEventTypes = Right ty
+  | otherwise = Left ("--type: unknown event type; accepted: " <> Text.unpack (Text.intercalate ", " knownAuthEventTypes))
diff --git a/app/Shomei/Admin/Env.hs b/app/Shomei/Admin/Env.hs
--- a/app/Shomei/Admin/Env.hs
+++ b/app/Shomei/Admin/Env.hs
@@ -18,6 +18,7 @@
 import Shomei.Config (ShomeiConfig)
 import Shomei.Persistence.Pool.Postgres (Pool, acquirePool)
 import Shomei.Server.Config (defaultDbStatementTimeoutMs, loadCoreConfig)
+import Shomei.Server.ConfigurationError (configurationError)
 import System.Environment (lookupEnv)
 import Text.Read (readMaybe)
 
@@ -46,13 +47,12 @@
   lanes <- intEnvOr "SHOMEI_ARGON2_PARALLELISM" defaultArgon2Params.parallelism
   let params = Argon2Params {memoryKiB = mem, iterations = iters, parallelism = lanes}
   for_ (argon2HardFloor params) \why ->
-    ioError
-      ( userError
-          ( "SHOMEI_ARGON2_MEMORY_KIB/SHOMEI_ARGON2_ITERATIONS/SHOMEI_ARGON2_PARALLELISM "
-              <> "are rejected by the Argon2 implementation: "
-              <> Text.unpack why
-          )
+    configurationError
+      ( "SHOMEI_ARGON2_MEMORY_KIB/SHOMEI_ARGON2_ITERATIONS/SHOMEI_ARGON2_PARALLELISM "
+          <> "are rejected by the Argon2 implementation: "
+          <> Text.unpack why
       )
+
   pure params
 
 intEnvOr :: Text -> Int -> IO Int
@@ -61,7 +61,7 @@
   case m of
     Just v | not (null v) -> case readMaybe v of
       Just n | n > 0 -> pure n
-      _ -> ioError (userError (Text.unpack name <> " must be a positive integer"))
+      _ -> configurationError (Text.unpack name <> " must be a positive integer")
     _ -> pure def
 
 requireEnv :: Text -> IO Text
@@ -70,4 +70,4 @@
   case m of
     Just v
       | let stripped = Text.strip (Text.pack v), not (Text.null stripped) -> pure stripped
-    _ -> ioError (userError (Text.unpack name <> " is not set"))
+    _ -> configurationError (Text.unpack name <> " is not set")
diff --git a/app/Shomei/Admin/OAuthClients.hs b/app/Shomei/Admin/OAuthClients.hs
--- a/app/Shomei/Admin/OAuthClients.hs
+++ b/app/Shomei/Admin/OAuthClients.hs
@@ -111,7 +111,7 @@
               <> metavar "confidential|public"
               <> help "confidential: can keep a secret. public: cannot (SPA, native app); PKCE is then mandatory"
           )
-        <*> many (Text.pack <$> strOption (long "redirect-uri" <> metavar "URI" <> help "An exact redirect target; repeatable. Matched by exact string equality"))
+        <*> some (Text.pack <$> strOption (long "redirect-uri" <> metavar "URI" <> help "An exact redirect target; repeatable. Matched by exact string equality"))
         <*> many (Text.pack <$> strOption (long "scope" <> metavar "SCOPE" <> help "A scope this client may request; repeatable"))
     clientIdArg = Text.pack <$> argument str (metavar "CLIENT_ID")
 
diff --git a/app/Shomei/Admin/ServiceAccounts.hs b/app/Shomei/Admin/ServiceAccounts.hs
--- a/app/Shomei/Admin/ServiceAccounts.hs
+++ b/app/Shomei/Admin/ServiceAccounts.hs
@@ -243,7 +243,7 @@
     account <- revokeAction env cid
     putStrLn ("revoked " <> Text.unpack (saClientId account))
     -- Access tokens are stateless JWTs: one minted a moment ago stays valid until it expires.
-    putStrLn "note: tokens already issued to this account remain valid until they expire (default 5 minutes)"
+    putStrLn "note: tokens already issued to this account remain valid until they expire"
   ServiceAccountsList -> do
     accounts <- listAction env
     forM_ accounts \a ->
diff --git a/app/Shomei/Admin/Users.hs b/app/Shomei/Admin/Users.hs
--- a/app/Shomei/Admin/Users.hs
+++ b/app/Shomei/Admin/Users.hs
@@ -3,22 +3,34 @@
 -- (with a trivial 'TokenSigner' fake — the CLI does not need a real access token).
 module Shomei.Admin.Users
   ( createUserAction,
+    ResetMfaOptions (..),
+    resetMfaParser,
+    validateResetMfaOptions,
+    resetMfaAction,
+    runRecovery,
   )
 where
 
-import Control.Monad (when)
+import Control.Monad (forM_, when)
+import Data.Aeson (encode, object, (.=))
+import Data.ByteString.Lazy.Char8 qualified as LBS
+import Data.IORef (modifyIORef', newIORef, readIORef)
 import Data.Set qualified as Set
 import Data.Text (Text)
 import Data.Text qualified as Text
-import Effectful (Eff, IOE, runEff)
+import Effectful (Eff, IOE, liftIO, runEff)
 import Effectful.Dispatch.Dynamic (interpret_)
 import Effectful.Error.Static (Error, runErrorNoCallStack)
 import Network.HTTP.Client (Manager)
 import Network.HTTP.Client.TLS (newTlsManager)
+import Options.Applicative
+import Shomei.Account.Admin.Recovery
 import Shomei.Account.Credential.Postgres (runCredentialStorePostgres)
 import Shomei.Account.Credential.Store (CredentialStore)
 import Shomei.Account.Email.Domain (mkEmail)
 import Shomei.Account.LoginId.Domain (loginIdText, mkLoginId)
+import Shomei.Account.Notification.Domain (Notification)
+import Shomei.Account.Notification.Store (Notifier (..))
 import Shomei.Account.Password.Breach.Store (PasswordBreachChecker)
 import Shomei.Account.Password.Domain (PasswordPolicy (..), PlainPassword (..))
 import Shomei.Account.Password.Hash.Postgres (Argon2Params, HashingLimiter, newHashingLimiter, runPasswordHasherCrypto, runTokenGenCrypto)
@@ -36,11 +48,13 @@
 import Shomei.Authorization.Role.Workflow (undefinedDefaultRoles)
 import Shomei.Config (ShomeiConfig (..))
 import Shomei.Error (AuthError)
-import Shomei.Id (UserId)
+import Shomei.Id (UserId, idText, parseId)
+import Shomei.Notify (deliverNotification)
 import Shomei.OAuth.IdToken.Domain (IdToken (..))
 import Shomei.Persistence.Database.Postgres (Database, runDatabasePool)
 import Shomei.Persistence.Pool.Postgres (Pool)
 import Shomei.Server.BreachChecker (runPasswordBreachCheckerHibp)
+import Shomei.Server.Config (loadNotifierSecretsFromEnv)
 import Shomei.Session.Authentication.Workflow (signup)
 import Shomei.Session.Command (SignupCommand (..))
 import Shomei.Session.Token.Domain (AccessToken (..))
@@ -52,6 +66,7 @@
 import Shomei.Time.Store (Clock, now)
 import System.Exit (exitFailure)
 import System.IO (hPutStrLn, stderr)
+import System.Timeout (timeout)
 
 createUserAction :: AdminEnv -> Text -> PlainPassword -> Maybe Text -> Bool -> IO ()
 createUserAction env emailArg password mDisplay verified = do
@@ -182,3 +197,72 @@
 
 die :: String -> IO a
 die msg = hPutStrLn stderr ("shomei-admin: " <> msg) >> exitFailure
+
+data ResetMfaOptions = ResetMfaOptions
+  { targetUser :: !UserId,
+    operatorLabel :: !Text,
+    caseReference :: !Text,
+    identityVerified :: !Bool,
+    confirmUser :: !UserId
+  }
+  deriving stock (Eq, Show)
+
+resetMfaParser :: Parser ResetMfaOptions
+resetMfaParser =
+  ResetMfaOptions
+    <$> userOption "user" "Target user ID"
+    <*> (Text.pack <$> strOption (long "operator" <> metavar "OPERATOR" <> help "Asserted local operator label (not authenticated human identity)"))
+    <*> (Text.pack <$> strOption (long "case-reference" <> metavar "CASE" <> help "Non-sensitive case reference, 1-128 ASCII letters/digits or ._:/-"))
+    <*> flag' True (long "identity-verified" <> help "Assert independent verification of the account owner")
+    <*> userOption "confirm-user" "Repeat the exact target user ID"
+  where
+    userOption name description = option (eitherReader (either (const (Left "invalid user ID")) Right . parseId . Text.pack)) (long name <> metavar "USER_ID" <> help description)
+
+validateResetMfaOptions :: ResetMfaOptions -> Either Text ()
+validateResetMfaOptions opts
+  | opts.targetUser /= opts.confirmUser = Left "--confirm-user must exactly match --user"
+  | otherwise =
+      either
+        (const (Left "identity assertion, operator label or case reference is invalid"))
+        Right
+        (validateRecovery (LocalOperator opts.operatorLabel) (RecoveryCommand opts.identityVerified opts.caseReference))
+
+-- | Run only the committed security workflow. The caller owns configured delivery/drain.
+runRecovery :: Pool -> (Notification -> IO ()) -> UserId -> Text -> RecoveryCommand -> IO (Either AuthError (Either AuthError RecoveryResult))
+runRecovery pool enqueue uid operator cmd =
+  runEff
+    . runErrorNoCallStack
+    . runDatabasePool pool
+    . runClockIO
+    . interpret_ (\case SendNotification notification -> liftIO (enqueue notification))
+    . runAuthUnitOfWorkPostgres
+    $ resetUserSecondFactors (LocalOperator operator) uid cmd
+
+resetMfaAction :: AdminEnv -> ResetMfaOptions -> IO ()
+resetMfaAction env opts = do
+  either (die . Text.unpack) pure (validateResetMfaOptions opts)
+  -- Validate transport secrets before the destructive operation.
+  secrets <- loadNotifierSecretsFromEnv env.config
+  manager <- newTlsManager
+  notices <- newIORef []
+  result <- runRecovery env.pool (\n -> modifyIORef' notices (n :)) opts.targetUser opts.operatorLabel (RecoveryCommand opts.identityVerified opts.caseReference)
+  committed <- case result of
+    Left _ -> die "recovery failed: database unavailable; inspect the audit trail before retrying"
+    Right (Left err) -> die ("recovery rejected: " <> show err)
+    Right (Right value) -> pure value
+  -- This one-command process waits for its queued notice before exit. The drain is bounded;
+  -- delivery uses exactly the configured server transport and its redacted failure contract.
+  queued <- readIORef notices
+  forM_ queued \notice -> do
+    delivered <-
+      timeout
+        30000000
+        ( runEff . runErrorNoCallStack @AuthError . runDatabasePool env.pool . runClockIO . runAuthEventPublisherPostgres $
+            deliverNotification manager secrets env.config notice
+        )
+    case delivered of
+      Just (Right ()) -> pure ()
+      _ -> hPutStrLn stderr "shomei-admin: recovery committed; notification drain failed or timed out; notify the owner through an established channel"
+  when (not committed.verifiedNotificationDestination) $
+    hPutStrLn stderr "shomei-admin: recovery committed without a verified email destination; notify the owner through an independently established channel"
+  LBS.putStrLn (encode (object ["userId" .= idText opts.targetUser, "resetAt" .= committed.resetAt, "counts" .= committed.counts]))
diff --git a/shomei-server.cabal b/shomei-server.cabal
--- a/shomei-server.cabal
+++ b/shomei-server.cabal
@@ -1,6 +1,6 @@
 cabal-version: 3.0
 name: shomei-server
-version: 0.3.0.1
+version: 0.4.0.0
 synopsis: Standalone Shōmei authentication service
 description:
   The standalone deployment of Shōmei: a warp executable that serves ShomeiAPI
@@ -21,6 +21,10 @@
 category: Web, Security
 tested-with: ghc ==9.12.4
 extra-doc-files: CHANGELOG.md
+extra-source-files:
+  test/fixtures/errors.hurl
+  test/fixtures/shomei-types.dhall
+  test/fixtures/throttling.hurl
 
 source-repository head
   type: git
@@ -70,6 +74,7 @@
     Shomei.Server.Boot
     Shomei.Server.BreachChecker
     Shomei.Server.Config
+    Shomei.Server.ConfigurationError
     Shomei.Server.DatabaseError
     Shomei.Server.ExceptionResponse
     Shomei.Server.Keys
@@ -102,12 +107,12 @@
     ram >=0.22 && <0.23,
     servant-health >=0.1 && <0.2,
     servant-server >=0.20.3 && <0.21,
-    shomei-core ^>=0.3.0.0,
-    shomei-jwt ^>=0.3.0.0,
-    shomei-migrations ^>=0.2.0.1,
-    shomei-postgres ^>=0.3.0.0,
-    shomei-servant ^>=0.3.0.0,
-    shomei-webauthn ^>=0.3.0.0,
+    shomei-core ^>=0.4.0.0,
+    shomei-jwt ^>=0.4.0.0,
+    shomei-migrations ^>=0.2.0.2,
+    shomei-postgres ^>=0.4.0.0,
+    shomei-servant ^>=0.4.0.0,
+    shomei-webauthn ^>=0.4.0.0,
     smtp-mail >=0.5.0.2 && <0.6,
     stm >=2.5 && <2.6,
     text >=2.0 && <2.2,
@@ -129,7 +134,7 @@
 
   build-depends:
     base >=4.18 && <5,
-    shomei-server ^>=0.3.0.0,
+    shomei-server ^>=0.4.0.0,
 
 -- EP-4: the operational CLI. A second executable in this package (MasterPlan 2 default;
 -- avoids registering a new mori.dhall package). It reuses the same pool/config/key/interpreter
@@ -166,11 +171,11 @@
     http-client-tls >=0.3 && <0.5,
     optparse-applicative >=0.19 && <0.20,
     pg-migrate >=1.2 && <1.3,
-    shomei-core ^>=0.3.0.0,
-    shomei-jwt ^>=0.3.0.0,
-    shomei-migrations ^>=0.2.0.1,
-    shomei-postgres ^>=0.3.0.0,
-    shomei-server ^>=0.3.0.0,
+    shomei-core ^>=0.4.0.0,
+    shomei-jwt ^>=0.4.0.0,
+    shomei-migrations ^>=0.2.0.2,
+    shomei-postgres ^>=0.4.0.0,
+    shomei-server ^>=0.4.0.0,
     text >=2.0 && <2.2,
     time >=1.12 && <1.15,
     uuid >=1.3 && <1.4,
@@ -192,9 +197,9 @@
     containers >=0.6 && <0.9,
     directory >=1.3 && <1.4,
     process >=1.6 && <1.7,
-    shomei-core ^>=0.3.0.0,
-    shomei-postgres ^>=0.3.0.0,
-    shomei-server ^>=0.3.0.0,
+    shomei-core ^>=0.4.0.0,
+    shomei-postgres ^>=0.4.0.0,
+    shomei-server ^>=0.4.0.0,
     tasty >=1.4 && <1.6,
     tasty-hunit >=0.10 && <0.11,
     text >=2.0 && <2.2,
@@ -222,12 +227,18 @@
     Shomei.Admin.Sweep
     Shomei.Admin.Users
 
+  build-tool-depends:
+    shomei-server:shomei-admin,
+    shomei-server:shomei-server,
+
   build-depends:
     aeson >=2.1 && <2.3,
     base >=4.18 && <5,
     bytestring >=0.11 && <0.13,
     containers >=0.6 && <0.9,
     contravariant-extras >=0.3 && <0.4,
+    crypton >=1.1 && <1.2,
+    directory >=1.3 && <1.4,
     effectful >=2.5 && <2.8,
     effectful-core >=2.5 && <2.8,
     hasql >=1.10 && <1.11,
@@ -235,13 +246,14 @@
     http-client-tls >=0.3 && <0.5,
     jose >=0.13 && <0.14,
     optparse-applicative >=0.19 && <0.20,
+    process >=1.6 && <1.7,
     ram >=0.22 && <0.23,
-    shomei-core ^>=0.3.0.0,
-    shomei-jwt ^>=0.3.0.0,
-    shomei-migrations ^>=0.2.0.1,
-    shomei-migrations:test-support ^>=0.2.0.1,
-    shomei-postgres ^>=0.3.0.0,
-    shomei-server ^>=0.3.0.0,
+    shomei-core ^>=0.4.0.0,
+    shomei-jwt ^>=0.4.0.0,
+    shomei-migrations ^>=0.2.0.2,
+    shomei-migrations:test-support ^>=0.2.0.2,
+    shomei-postgres ^>=0.4.0.0,
+    shomei-server ^>=0.4.0.0,
     tasty >=1.4 && <1.6,
     tasty-hunit >=0.10 && <0.11,
     text >=2.0 && <2.2,
@@ -257,9 +269,11 @@
     Shomei.Server.E2ESpec
     Shomei.Server.MiddlewareSpec
     Shomei.Server.NotifySpec
+    Shomei.Server.OAuthContractSpec
     Shomei.Server.RuntimeSpec
     Shomei.Server.SupervisorSpec
 
+  build-tool-depends: shomei-server:shomei-server
   ghc-options:
     -threaded
     -rtsopts
@@ -274,22 +288,25 @@
     directory >=1.3 && <1.4,
     effectful >=2.5 && <2.8,
     effectful-core >=2.5 && <2.8,
+    filepath >=1.4 && <1.6,
     hasql >=1.10 && <1.11,
     http-client >=0.7 && <0.8,
     http-types >=0.12 && <0.13,
     network >=3.1 && <3.3,
+    process >=1.6 && <1.7,
     servant-health >=0.1 && <0.2,
     servant-health:testkit,
-    shomei-core ^>=0.3.0.0,
-    shomei-jwt ^>=0.3.0.0,
-    shomei-migrations:test-support ^>=0.2.0.1,
-    shomei-postgres ^>=0.3.0.0,
-    shomei-servant ^>=0.3.0.0,
-    shomei-server ^>=0.3.0.0,
+    shomei-core ^>=0.4.0.0,
+    shomei-jwt ^>=0.4.0.0,
+    shomei-migrations:test-support ^>=0.2.0.2,
+    shomei-postgres ^>=0.4.0.0,
+    shomei-servant ^>=0.4.0.0,
+    shomei-server ^>=0.4.0.0,
     tasty >=1.4 && <1.6,
     tasty-hunit >=0.10 && <0.11,
     text >=2.0 && <2.2,
     time >=1.12 && <1.15,
+    unix >=2.8 && <2.9,
     wai >=3.2 && <3.3,
     warp >=3.3 && <3.5,
 
@@ -309,11 +326,11 @@
     http-client >=0.7 && <0.8,
     servant-health >=0.1 && <0.2,
     servant-health:testkit,
-    shomei-core ^>=0.3.0.0,
-    shomei-jwt ^>=0.3.0.0,
-    shomei-migrations:test-support ^>=0.2.0.1,
-    shomei-postgres ^>=0.3.0.0,
-    shomei-server ^>=0.3.0.0,
+    shomei-core ^>=0.4.0.0,
+    shomei-jwt ^>=0.4.0.0,
+    shomei-migrations:test-support ^>=0.2.0.2,
+    shomei-postgres ^>=0.4.0.0,
+    shomei-server ^>=0.4.0.0,
     tasty >=1.4 && <1.6,
     tasty-hunit >=0.10 && <0.11,
 
@@ -341,12 +358,12 @@
     http-types >=0.12 && <0.13,
     process >=1.6 && <1.7,
     servant-health >=0.1 && <0.2,
-    shomei-core ^>=0.3.0.0,
-    shomei-jwt ^>=0.3.0.0,
-    shomei-migrations:test-support ^>=0.2.0.1,
-    shomei-postgres ^>=0.3.0.0,
-    shomei-servant ^>=0.3.0.0,
-    shomei-server ^>=0.3.0.0,
+    shomei-core ^>=0.4.0.0,
+    shomei-jwt ^>=0.4.0.0,
+    shomei-migrations:test-support ^>=0.2.0.2,
+    shomei-postgres ^>=0.4.0.0,
+    shomei-servant ^>=0.4.0.0,
+    shomei-server ^>=0.4.0.0,
     text >=2.0 && <2.2,
     unix >=2.8 && <2.9,
     uuid >=1.3 && <1.4,
diff --git a/src/Shomei/Notify.hs b/src/Shomei/Notify.hs
--- a/src/Shomei/Notify.hs
+++ b/src/Shomei/Notify.hs
@@ -284,7 +284,7 @@
   Eff es ()
 deliverNotification mgr secrets cfg notification = do
   currentTime <- now
-  if notificationExpiresAt notification <= currentTime
+  if maybe False (<= currentTime) (notificationExpiresAt notification)
     then publishDeliveryFailed (transportChannel nc.notifierTransport) notification ExpiredInQueue
     else do
       when tee (logNotification nc notification)
@@ -305,10 +305,11 @@
   SmtpNotifier -> "smtp"
   WebhookNotifier -> "webhook"
 
-notificationExpiresAt :: Notification -> UTCTime
+notificationExpiresAt :: Notification -> Maybe UTCTime
 notificationExpiresAt = \case
-  EmailVerificationRequested _ _ expires -> expires
-  PasswordResetRequested _ _ expires -> expires
+  EmailVerificationRequested _ _ expires -> Just expires
+  PasswordResetRequested _ _ expires -> Just expires
+  SecondFactorsReset {} -> Nothing
 
 -- | Fallback used only if a transport is selected with no sub-config (boot validation prevents
 -- this): warn once and log the notification rather than silently dropping it.
@@ -344,6 +345,8 @@
     line "email_verification" "/v1/auth/verify-email/confirm" email token expires
   PasswordResetRequested email token expires ->
     line "password_reset" "/v1/auth/password-reset/confirm" email token expires
+  SecondFactorsReset email occurred instructions ->
+    "[shomei:second_factors_reset] to=" <> Text.unpack (emailText email) <> " occurred_at=" <> iso8601Show occurred <> " " <> Text.unpack instructions
   where
     line kind path email token expires =
       "[shomei:log] "
@@ -441,12 +444,14 @@
 notificationTypeText = \case
   EmailVerificationRequested {} -> "email_verification_requested"
   PasswordResetRequested {} -> "password_reset_requested"
+  SecondFactorsReset {} -> "second_factors_reset"
 
 -- | The recipient address of a notification.
 notificationRecipient :: Notification -> Text
 notificationRecipient = \case
   EmailVerificationRequested e _ _ -> emailText e
   PasswordResetRequested e _ _ -> emailText e
+  SecondFactorsReset e _ _ -> emailText e
 
 -- | The fixed English subject and plain-text body for a notification. These are the only two
 -- bodies Shōmei ever emails; there is no templating, i18n, or HTML part (operators who want
@@ -485,6 +490,8 @@
             ]
         )
     )
+  SecondFactorsReset _ occurred instructions ->
+    ("Your second factors were reset", TL.fromStrict (body ["Your second factors were reset at " <> isoUtc occurred <> " (UTC).", "", instructions]))
   where
     body = Text.intercalate "\n"
     link path token = nc.publicBaseUrl <> path <> "?token=" <> oneTimeTokenText token
@@ -539,12 +546,13 @@
 redactDeliveryText notification =
   truncateText
     . redactTokenParameters
-    . Text.replace (oneTimeTokenText (notificationToken notification)) "<redacted>"
+    . maybe id (\token -> Text.replace (oneTimeTokenText token) "<redacted>") (notificationToken notification)
 
-notificationToken :: Notification -> OneTimeToken
+notificationToken :: Notification -> Maybe OneTimeToken
 notificationToken = \case
-  EmailVerificationRequested _ token _ -> token
-  PasswordResetRequested _ token _ -> token
+  EmailVerificationRequested _ token _ -> Just token
+  PasswordResetRequested _ token _ -> Just token
+  SecondFactorsReset {} -> Nothing
 
 redactTokenParameters :: Text -> Text
 redactTokenParameters input =
diff --git a/src/Shomei/Server/Boot.hs b/src/Shomei/Server/Boot.hs
--- a/src/Shomei/Server/Boot.hs
+++ b/src/Shomei/Server/Boot.hs
@@ -14,7 +14,10 @@
     HostBackgroundTasks (..),
     installHostBackgroundTasks,
     hostMiddleware,
+    hostMiddlewareWithOAuthMounts,
+    authContextWithOAuthMounts,
     edgeMiddleware,
+    edgeMiddlewareWithOAuthMounts,
     buildEnv,
     seamEnv,
     authContext,
@@ -70,19 +73,22 @@
 
 -- '(.=)' is hidden from the prelude (it re-exports lens's state-setter of the same name);
 -- we mean aeson's JSON pair constructor here.
+
+import Shomei.OAuth.Boundary (OAuthMounts, defaultOAuthMounts)
 import Shomei.Prelude hiding (Context, (.=))
 import Shomei.Servant.Api (shomeiRoutesApi, shomeiThrottledRoutes)
 import Shomei.Servant.Auth (AuthUser, authHandler)
-import Shomei.Servant.Error (shomeiErrorFormatters)
+import Shomei.Servant.Error (shomeiErrorFormattersWithOAuthMounts)
 import Shomei.Servant.Middleware (problemMiddleware)
 import Shomei.Servant.Oidc (isAbsoluteHttpUrl)
 import Shomei.Servant.Seam qualified as Seam
 import Shomei.Servant.Server (shomeiRoutes)
 import Shomei.Server.App (Env (..), runAppIO)
 import Shomei.Server.Config (ProxyProtocolMode (..), ServerSettings (..), SweepSettings (..), loadConfig, loadNotifierSecretsFromEnv, toSweepConfig)
+import Shomei.Server.ConfigurationError (reportConfigurationError)
 import Shomei.Server.Keys (LoadedKeys (..), bootstrapKeys, loadKekFromEnv, reloadKeys)
-import Shomei.Server.Middleware.BodyLimit (bodyLimitMiddleware, defaultBodyLimitBytes)
-import Shomei.Server.Middleware.RateLimit (RateLimiter, newRateLimiterFor, rateLimitMiddleware)
+import Shomei.Server.Middleware.BodyLimit (bodyLimitMiddlewareWithOAuthMounts, defaultBodyLimitBytes)
+import Shomei.Server.Middleware.RateLimit (RateLimiter, newRateLimiterFor, rateLimitMiddlewareWithOAuthMounts)
 import Shomei.Server.Middleware.TrustedProxy (TrustedProxies, trustedProxyMiddleware, trustedProxyTexts)
 import Shomei.Server.Observability.Logging (requestLoggingMiddleware)
 import Shomei.Server.Observability.Metrics (Metrics, metricsEndpointMiddleware, metricsMiddleware, newMetrics)
@@ -103,7 +109,10 @@
   -- is a pipe/file it would otherwise be block-buffered and logs would not appear promptly).
   hSetBuffering stdout LineBuffering
   hSetBuffering stderr LineBuffering
-  (cfg, settings) <- loadConfig
+  (cfg, settings) <- reportConfigurationError "shomei-server" loadConfig
+  -- Validate env-only notifier credentials before startup diagnostics or database work.
+  -- buildEnv also loads these values for embedding callers.
+  _ <- reportConfigurationError "shomei-server" (loadNotifierSecretsFromEnv cfg)
   let trustedProxySummary =
         case trustedProxyTexts settings.serverTrustedProxies of
           [] -> "none"
@@ -193,18 +202,24 @@
 -- routes receive the same trusted-proxy attribution, request IDs, metrics, body cap, and
 -- per-client rate limiting as Shōmei's routes.
 hostMiddleware :: ShomeiConfig -> ServerSettings -> RateLimiter -> Metrics -> Middleware
-hostMiddleware cfg settings =
-  edgeMiddleware cfg.observabilityConfig settings.serverTrustedProxies
+hostMiddleware = hostMiddlewareWithOAuthMounts defaultOAuthMounts
 
+hostMiddlewareWithOAuthMounts :: OAuthMounts -> ShomeiConfig -> ServerSettings -> RateLimiter -> Metrics -> Middleware
+hostMiddlewareWithOAuthMounts mounts cfg settings =
+  edgeMiddlewareWithOAuthMounts mounts cfg.observabilityConfig settings.serverTrustedProxies
+
 -- | The WAI edge every host must install. The trusted-proxy rewrite is outermost so logging,
 -- metrics, the limiter, and Servant's 'RemoteHost' all observe the same client address.
 edgeMiddleware :: ObservabilityConfig -> TrustedProxies -> RateLimiter -> Metrics -> Middleware
-edgeMiddleware obs proxies limiter metrics =
+edgeMiddleware = edgeMiddlewareWithOAuthMounts defaultOAuthMounts
+
+edgeMiddlewareWithOAuthMounts :: OAuthMounts -> ObservabilityConfig -> TrustedProxies -> RateLimiter -> Metrics -> Middleware
+edgeMiddlewareWithOAuthMounts mounts obs proxies limiter metrics =
   trustedProxyMiddleware proxies
     . requestLoggingMiddleware obs
     . withMetrics
-    . bodyLimitMiddleware defaultBodyLimitBytes
-    . rateLimitMiddleware limiter
+    . bodyLimitMiddlewareWithOAuthMounts mounts defaultBodyLimitBytes
+    . rateLimitMiddlewareWithOAuthMounts mounts limiter
   where
     withMetrics
       | obs.metricsEnabled = metricsMiddleware metrics . metricsEndpointMiddleware metrics
@@ -512,9 +527,8 @@
 -- The served tree is 'shomeiRoutesApi' (EP-3): application routes under @\/v1@, JWKS and the
 -- probes at unversioned root paths.
 --
--- 'problemMiddleware' converts Servant's one un-formattable failure — the bare @405@ a method
--- mismatch raises below any 'ErrorFormatters' hook — into a problem document, so /every/ error
--- the process emits carries the same envelope.
+-- 'problemMiddleware' completes Servant's formatter hooks for method and negotiation failures.
+-- OAuth namespaces retain OAuth JSON; application routes use problem documents.
 application :: Env -> ProbeCheck -> ProbeCheck -> Application
 application env liveness readiness =
   problemMiddleware (serveWithContext shomeiRoutesApi (authContext senv) (shomeiRoutes senv liveness readiness))
@@ -523,12 +537,15 @@
 
 -- | The Servant 'Context' carrying the @AuthProtect "shomei-jwt"@ 'AuthHandler' (built from the
 -- seam env itself) and the 'ErrorFormatters' that render Servant's own body-parse,
--- url-parse, header-parse, and not-found failures as RFC 9457 problem documents. A host app
+-- url-parse, header-parse, and not-found failures according to their protocol namespace. A host app
 -- embedding 'ShomeiAPI' serves with this same context.
 authContext :: Seam.Env -> Context '[AuthHandler Request AuthUser, ErrorFormatters]
-authContext senv =
+authContext = authContextWithOAuthMounts defaultOAuthMounts
+
+authContextWithOAuthMounts :: OAuthMounts -> Seam.Env -> Context '[AuthHandler Request AuthUser, ErrorFormatters]
+authContextWithOAuthMounts mounts senv =
   authHandler senv
-    :. shomeiErrorFormatters
+    :. shomeiErrorFormattersWithOAuthMounts mounts
     :. EmptyContext
 
 -- | Build EP-5's seam 'Seam.Env' from this server's assembly 'Env'. The port runner
diff --git a/src/Shomei/Server/Config.hs b/src/Shomei/Server/Config.hs
--- a/src/Shomei/Server/Config.hs
+++ b/src/Shomei/Server/Config.hs
@@ -30,6 +30,7 @@
 
 -- Argon2Params is re-exported through 'ServerSettings'; import it from "Shomei.Account.Password.Hash.Postgres".
 
+import Control.Exception (IOException, try)
 import Data.Aeson (eitherDecodeStrict')
 import Data.Char (isDigit)
 import Data.Foldable (for_)
@@ -70,11 +71,12 @@
 import Shomei.Notify (NotifierSecrets (..), SmtpPassword (..), WebhookSecret (..))
 import Shomei.Persistence.Maintenance.Postgres (SweepConfig (..), defaultSweepConfig)
 import Shomei.Prelude
+import Shomei.Server.ConfigurationError (configurationError)
 import Shomei.Server.Middleware.TrustedProxy (TrustedProxies, emptyTrustedProxies, parseTrustedProxies)
 import Shomei.SigningKey.Verify.Jwt (checkStringOrUri)
 import System.Environment (lookupEnv)
-import System.IO (hPutStrLn, stderr)
-import System.Process (readProcess)
+import System.Exit (ExitCode (..))
+import System.Process (readProcessWithExitCode)
 import Text.Read (readMaybe)
 
 -- | Server-only settings not part of the transport-agnostic 'ShomeiConfig'.
@@ -354,12 +356,14 @@
   mPath <- lookupEnv "SHOMEI_CONFIG"
   case mPath of
     Just path | not (null path) -> do
-      out <- readProcess "dhall-to-json" ["--file", path] ""
-      case eitherDecodeStrict' (TE.encodeUtf8 (Text.pack out)) of
-        Right fc -> pure (Just fc)
-        Left err -> do
-          hPutStrLn stderr ("shomei: could not decode rendered Dhall config " <> path <> ": " <> err)
-          ioError (userError ("invalid SHOMEI_CONFIG: " <> path))
+      result <- try @IOException (readProcessWithExitCode "dhall-to-json" ["--file", path] "")
+      case result of
+        Left _ -> configurationError "SHOMEI_CONFIG: could not run dhall-to-json"
+        Right (ExitFailure _, _, _) -> configurationError "SHOMEI_CONFIG: Dhall conversion failed"
+        Right (ExitSuccess, out, _) ->
+          case eitherDecodeStrict' (TE.encodeUtf8 (Text.pack out)) of
+            Right fc -> pure (Just fc)
+            Left _ -> configurationError "SHOMEI_CONFIG: rendered configuration rejected (unknown field or invalid value)"
     _ -> pure Nothing
 
 baseDefaults :: IO (ShomeiConfig, ServerSettings)
@@ -566,24 +570,22 @@
   cfg <- overlayCoreFromEnv baseCfg {issuer = Issuer iss, audience = Audience aud}
   let WebAuthnConfig {origins = originList} = cfg.webauthnConfig
   when (null originList) $
-    ioError
-      ( userError
-          "SHOMEI_WEBAUTHN_ORIGINS (Dhall field webauthnOrigins) must list at least one origin; an empty list would fail every passkey ceremony"
-      )
-  when (Text.null connStr) (ioError (userError "PG_CONNECTION_STRING is not set (and no databaseUrl in the Dhall config)"))
+    configurationError "SHOMEI_WEBAUTHN_ORIGINS (Dhall field webauthnOrigins) must list at least one origin; an empty list would fail every passkey ceremony"
+
+  when (Text.null connStr) (configurationError "PG_CONNECTION_STRING is not set (and no databaseUrl in the Dhall config)")
   -- Validated after the overlay so a bad value fails the boot whichever layer supplied it.
   -- A zero-size pool deadlocks every request and a zero acquisition timeout fails every
   -- checkout, so neither is a survivable "disable" setting: refuse to start.
-  when (Text.null (Text.strip host)) (ioError (userError "SHOMEI_BIND_HOST (Dhall field bindHost) must be non-empty"))
+  when (Text.null (Text.strip host)) (configurationError "SHOMEI_BIND_HOST (Dhall field bindHost) must be non-empty")
   requirePositive "SHOMEI_MAX_CONNECTIONS" "maxConnections" connections
   requirePositive "SHOMEI_SLOW_CLIENT_TIMEOUT_SECONDS" "slowClientTimeoutSeconds" slowTimeout
-  when (slowTimeout > maxBound `div` 1000000) (ioError (userError "SHOMEI_SLOW_CLIENT_TIMEOUT_SECONDS is not representable in microseconds"))
+  when (slowTimeout > maxBound `div` 1000000) (configurationError "SHOMEI_SLOW_CLIENT_TIMEOUT_SECONDS is not representable in microseconds")
   requirePositive "SHOMEI_DB_POOL_SIZE" "dbPoolSize" poolSize
   requirePositive "SHOMEI_DB_POOL_ACQUISITION_TIMEOUT_MS" "dbPoolAcquisitionTimeoutMs" poolTimeout
   requireNonNegative "SHOMEI_DB_STATEMENT_TIMEOUT_MS" "dbStatementTimeoutMs" statementTimeout
   requirePositive "SHOMEI_DB_TRANSACTION_MAX_ATTEMPTS" "dbTransactionMaxAttempts" transactionAttempts
   requirePositive "SHOMEI_DB_TRANSACTION_DEADLINE_MS" "dbTransactionDeadlineMs" transactionDeadline
-  when (transactionDeadline > min 2147483647 (maxBound `div` 1000)) (ioError (userError "SHOMEI_DB_TRANSACTION_DEADLINE_MS is not representable"))
+  when (transactionDeadline > min 2147483647 (maxBound `div` 1000)) (configurationError "SHOMEI_DB_TRANSACTION_DEADLINE_MS is not representable")
   requirePositive "SHOMEI_NOTIFIER_QUEUE_SIZE" "notifierQueueSize" notifierQueueSize
   -- A zero interval would spin the sweeper; a zero batch size would make it delete nothing
   -- forever. Neither is a survivable "disable" setting — sweepEnabled=false is.
@@ -601,14 +603,13 @@
   requirePositive "SHOMEI_ARGON2_ITERATIONS" "argon2Iterations" argon2.iterations
   requirePositive "SHOMEI_ARGON2_PARALLELISM" "argon2Parallelism" argon2.parallelism
   for_ (argon2HardFloor argon2) \why ->
-    ioError
-      ( userError
-          ( "SHOMEI_ARGON2_MEMORY_KIB/SHOMEI_ARGON2_ITERATIONS/SHOMEI_ARGON2_PARALLELISM "
-              <> "(Dhall fields argon2MemoryKiB/argon2Iterations/argon2Parallelism) are rejected "
-              <> "by the Argon2 implementation: "
-              <> Text.unpack why
-          )
+    configurationError
+      ( "SHOMEI_ARGON2_MEMORY_KIB/SHOMEI_ARGON2_ITERATIONS/SHOMEI_ARGON2_PARALLELISM "
+          <> "(Dhall fields argon2MemoryKiB/argon2Iterations/argon2Parallelism) are rejected "
+          <> "by the Argon2 implementation: "
+          <> Text.unpack why
       )
+
   -- Zero permits would block every login forever.
   requirePositive "SHOMEI_HASHING_MAX_CONCURRENCY" "hashingMaxConcurrency" hashingConcurrency
   requireNonNegative
@@ -621,9 +622,9 @@
   requirePositive "SHOMEI_PER_IP_REQUESTS_PER_MINUTE" "perIpRequestsPerMinute" rate.perIpRequestsPerMinute
   requirePositive "SHOMEI_PER_IP_BURST" "perIpBurst" rate.perIpBurst
   when (rate.lockoutWindow <= 0) $
-    ioError (userError "SHOMEI_LOCKOUT_WINDOW_SECONDS (Dhall field lockoutWindowSeconds) must be a positive number of seconds")
+    configurationError "SHOMEI_LOCKOUT_WINDOW_SECONDS (Dhall field lockoutWindowSeconds) must be a positive number of seconds"
   when (rate.lockoutDuration <= 0) $
-    ioError (userError "SHOMEI_LOCKOUT_DURATION_SECONDS (Dhall field lockoutDurationSeconds) must be a positive number of seconds")
+    configurationError "SHOMEI_LOCKOUT_DURATION_SECONDS (Dhall field lockoutDurationSeconds) must be a positive number of seconds"
   -- Validated after the overlay so a selected notifier transport is proven fully configured
   -- whichever layer supplied its fields (secrets always come from the environment).
   notifierWarnings <- validateNotifierConfig cfg.notifierConfig
@@ -659,29 +660,22 @@
       case checkStringOrUri value of
         Right () -> pure ()
         Left reason ->
-          ioError
-            ( userError
-                ( Text.unpack envName
-                    <> " (Dhall field "
-                    <> Text.unpack dhallField
-                    <> ") "
-                    <> Text.unpack reason
-                    <> ", got "
-                    <> show value
-                )
+          configurationError
+            ( Text.unpack envName
+                <> " (Dhall field "
+                <> Text.unpack dhallField
+                <> ") "
+                <> Text.unpack reason
             )
+
     requireBound ok expected envName dhallField n =
       unless (ok n) do
-        ioError
-          ( userError
-              ( Text.unpack envName
-                  <> " (Dhall field "
-                  <> Text.unpack dhallField
-                  <> ") must be "
-                  <> expected
-                  <> ", got "
-                  <> show n
-              )
+        configurationError
+          ( Text.unpack envName
+              <> " (Dhall field "
+              <> Text.unpack dhallField
+              <> ") must be "
+              <> expected
           )
 
 -- | Overlay the @SHOMEI_ARGON2_*@ environment variables onto the Argon2 cost parameters.
@@ -732,10 +726,10 @@
   rememberedSes <- ttlEnv "SHOMEI_REMEMBERED_SESSION_TTL"
   activeSessionCap <- intEnvMaybe "SHOMEI_MAX_ACTIVE_NON_INTERACTIVE_SESSIONS"
   let activeCap = fromMaybe base.maxActiveNonInteractiveSessions activeSessionCap
-  when (activeCap < 1) (ioError (userError "SHOMEI_MAX_ACTIVE_NON_INTERACTIVE_SESSIONS (Dhall field maxActiveNonInteractiveSessions) must be positive"))
+  when (activeCap < 1) (configurationError "SHOMEI_MAX_ACTIVE_NON_INTERACTIVE_SESSIONS (Dhall field maxActiveNonInteractiveSessions) must be positive")
   passkeyCap <- intEnvMaybe "SHOMEI_MAX_PASSKEYS_PER_USER"
   let cap = fromMaybe base.maxPasskeysPerUser passkeyCap
-  when (cap < 1 || cap > 100) (ioError (userError "SHOMEI_MAX_PASSKEYS_PER_USER (Dhall field maxPasskeysPerUser) must be between 1 and 100"))
+  when (cap < 1 || cap > 100) (configurationError "SHOMEI_MAX_PASSKEYS_PER_USER (Dhall field maxPasskeysPerUser) must be between 1 and 100")
   tr <- transportEnv
   sc <- sessionCheckEnv
   wa <- overlayWebAuthnFromEnv base.webauthnConfig
@@ -757,8 +751,8 @@
   legacyEmission <- boolEnv "SHOMEI_EMIT_LEGACY_ACTOR"
   let deadline = actorUntil <|> base.signingKeyConfig.legacyActorUntilUnix
       emitLegacy = fromMaybe base.signingKeyConfig.emitLegacyActor legacyEmission
-  for_ deadline \value -> when (value <= 0) (ioError (userError "SHOMEI_LEGACY_ACTOR_UNTIL_UNIX (Dhall field legacyActorUntilUnix) must be a positive finite Unix timestamp"))
-  when (emitLegacy && isNothing deadline) (ioError (userError "SHOMEI_EMIT_LEGACY_ACTOR requires SHOMEI_LEGACY_ACTOR_UNTIL_UNIX or legacyActorUntilUnix"))
+  for_ deadline \value -> when (value <= 0) (configurationError "SHOMEI_LEGACY_ACTOR_UNTIL_UNIX (Dhall field legacyActorUntilUnix) must be a positive finite Unix timestamp")
+  when (emitLegacy && isNothing deadline) (configurationError "SHOMEI_EMIT_LEGACY_ACTOR requires SHOMEI_LEGACY_ACTOR_UNTIL_UNIX or legacyActorUntilUnix")
   -- Deliberately env-only, with no Dhall-file field: logging raw one-time tokens must be an
   -- explicit per-process decision, not something that lingers unnoticed in a committed file.
   logSecrets <- boolEnv "SHOMEI_NOTIFIER_LOG_SECRETS"
@@ -899,7 +893,7 @@
   "log" -> pure LogNotifier
   "smtp" -> pure SmtpNotifier
   "webhook" -> pure WebhookNotifier
-  other -> ioError (userError (Text.unpack label <> " must be log|smtp|webhook, got " <> Text.unpack other))
+  _ -> configurationError (Text.unpack label <> " must be log|smtp|webhook")
 
 -- | @plain@ (lab only) | @starttls@ | @implicit@. Accepts a couple of common spellings.
 parseSmtpTlsMode :: Text -> Text -> IO SmtpTlsMode
@@ -910,7 +904,7 @@
   "implicit" -> pure SmtpImplicitTls
   "implicit-tls" -> pure SmtpImplicitTls
   "tls" -> pure SmtpImplicitTls
-  other -> ioError (userError (Text.unpack label <> " must be plain|starttls|implicit, got " <> Text.unpack other))
+  _ -> configurationError (Text.unpack label <> " must be plain|starttls|implicit")
 
 notifierTransportEnv :: IO (Maybe NotifierTransport)
 notifierTransportEnv = do
@@ -1093,7 +1087,7 @@
         failWith "notifier transport webhook requires a non-empty SHOMEI_WEBHOOK_SECRET"
   pure NotifierSecrets {smtpPassword = smtpSecret, webhookSecret = webhookSigningSecret}
   where
-    failWith = ioError . userError
+    failWith = configurationError
 
 -- | Refuse incomplete or unsafe non-secret notifier settings. Lab escape hatches are env-only;
 -- plaintext unauthenticated SMTP is permitted but returned as a boot warning.
@@ -1128,7 +1122,7 @@
           failWith "webhookUrl must be https:// (set SHOMEI_WEBHOOK_ALLOW_INSECURE=true for a lab receiver)"
         pure ["webhookUrl uses HTTP under SHOMEI_WEBHOOK_ALLOW_INSECURE; one-time links travel in the clear; lab receivers only" | isHttp]
   where
-    failWith = ioError . userError
+    failWith = configurationError
 
 -- | Apply the optional @webauthn*@ fields of a decoded Dhall 'FileConfig' onto a base
 -- 'WebAuthnConfig'. The base record is read via record destructuring (not @value.field@ dot
@@ -1214,7 +1208,7 @@
     Just s -> case Text.toLower (Text.pack s) of
       "true" -> pure (Just True)
       "false" -> pure (Just False)
-      _ -> ioError (userError (Text.unpack name <> " must be true|false"))
+      _ -> configurationError (Text.unpack name <> " must be true|false")
 
 -- | Parse a WebAuthn user-verification policy from either configuration source. Unknown text is
 -- a boot error: silently falling back can weaken the ceremony an operator intended to require.
@@ -1223,14 +1217,14 @@
   "required" -> pure UVRequired
   "preferred" -> pure UVPreferred
   "discouraged" -> pure UVDiscouraged
-  other -> ioError (userError (Text.unpack label <> " must be required|preferred|discouraged, got " <> Text.unpack other))
+  _ -> configurationError (Text.unpack label <> " must be required|preferred|discouraged")
 
 -- | Parse a WebAuthn attestation policy from either configuration source.
 parseAttestationPolicy :: Text -> Text -> IO AttestationPolicy
 parseAttestationPolicy label t = case Text.toLower (Text.strip t) of
   "none" -> pure AttestationNone
   "direct" -> pure AttestationDirect
-  other -> ioError (userError (Text.unpack label <> " must be none|direct, got " <> Text.unpack other))
+  _ -> configurationError (Text.unpack label <> " must be none|direct")
 
 textEnv :: Text -> Text -> IO Text
 textEnv name def = do
@@ -1248,7 +1242,7 @@
     Just "" -> pure def
     Just s -> case readMaybe s of
       Just n -> pure n
-      Nothing -> ioError (userError (Text.unpack name <> " must be an integer"))
+      Nothing -> configurationError (Text.unpack name <> " must be an integer")
 
 -- | Like 'textEnv' but overlay-only: absent or empty → 'Nothing', so a caller can distinguish
 -- "the operator set nothing" from "the operator set the empty string" and fall back to the
@@ -1270,7 +1264,7 @@
     Just "" -> pure Nothing
     Just s -> case readMaybe s of
       Just n -> pure (Just n)
-      Nothing -> ioError (userError (Text.unpack name <> " must be an integer"))
+      Nothing -> configurationError (Text.unpack name <> " must be an integer")
 
 ttlEnv :: Text -> IO (Maybe NominalDiffTime)
 ttlEnv name = do
@@ -1280,7 +1274,7 @@
     Just "" -> pure Nothing
     Just s -> case readMaybe s :: Maybe Integer of
       Just n -> pure (Just (fromIntegral n))
-      Nothing -> ioError (userError (Text.unpack name <> " must be an integer (seconds)"))
+      Nothing -> configurationError (Text.unpack name <> " must be an integer (seconds)")
 
 transportEnv :: IO (Maybe TokenTransport)
 transportEnv = do
@@ -1296,7 +1290,7 @@
   "bearer" -> pure BearerToken
   "cookie" -> pure HttpOnlyCookie
   "both" -> pure BearerAndCookie
-  other -> ioError (userError (Text.unpack label <> " must be bearer|cookie|both, got " <> Text.unpack other))
+  _ -> configurationError (Text.unpack label <> " must be bearer|cookie|both")
 
 -- | @strict@ | @lax@ | @none@. Rejects anything else rather than silently defaulting: a typo
 -- that quietly became @Lax@ when the operator meant @None@ would break their deployment in a
@@ -1306,7 +1300,7 @@
   "strict" -> pure SameSiteStrict
   "lax" -> pure SameSiteLax
   "none" -> pure SameSiteNone
-  other -> ioError (userError (Text.unpack label <> " must be strict|lax|none, got " <> Text.unpack other))
+  _ -> configurationError (Text.unpack label <> " must be strict|lax|none")
 
 sameSiteEnv :: IO (Maybe SameSitePolicy)
 sameSiteEnv = do
@@ -1319,7 +1313,7 @@
 parseTrustedProxyList :: [Text] -> IO TrustedProxies
 parseTrustedProxyList values =
   case parseTrustedProxies values of
-    Left reason -> ioError (userError (Text.unpack reason))
+    Left _ -> configurationError "SHOMEI_TRUSTED_PROXIES (Dhall field trustedProxies) must contain valid CIDRs"
     Right proxies -> pure proxies
 
 -- | A comma-separated CIDR list. An explicitly empty value clears a file-supplied list.
@@ -1340,11 +1334,8 @@
   case Text.toLower (Text.strip value) of
     "none" -> pure ProxyProtocolOff
     "required" -> pure ProxyProtocolRequired
-    other ->
-      ioError
-        ( userError
-            (Text.unpack label <> " must be none|required, got " <> Text.unpack other)
-        )
+    _ ->
+      configurationError (Text.unpack label <> " must be none|required")
 
 proxyProtocolEnv :: ProxyProtocolMode -> IO ProxyProtocolMode
 proxyProtocolEnv fallback = do
@@ -1359,7 +1350,7 @@
   where
     normalizeOne origin =
       case normalizeOrigin origin of
-        Left reason -> ioError (userError (Text.unpack reason))
+        Left _ -> configurationError "SHOMEI_WEBAUTHN_ORIGINS (Dhall field webauthnOrigins) must be scheme://host[:port] with no path"
         Right normalized -> pure normalized
 
 -- | Warn when browser-cookie transport still has development-only or insecure origin policy.
@@ -1425,7 +1416,7 @@
 keyRefreshIntervalEnv = do
   m <- intEnvMaybe "SHOMEI_KEY_REFRESH_INTERVAL"
   case m of
-    Just n | n < 0 -> ioError (userError "SHOMEI_KEY_REFRESH_INTERVAL must be >= 0 (0 disables the periodic reload)")
+    Just n | n < 0 -> configurationError "SHOMEI_KEY_REFRESH_INTERVAL must be >= 0 (0 disables the periodic reload)"
     _ -> pure m
 
 -- | Read the JWT verifier's tolerance for exp/nbf/iat. A negative value has no
@@ -1436,10 +1427,7 @@
   case m of
     Just n
       | n < 0 ->
-          ioError
-            ( userError
-                "SHOMEI_ALLOWED_CLOCK_SKEW_SECONDS (Dhall field allowedClockSkewSeconds) must be >= 0"
-            )
+          configurationError "SHOMEI_ALLOWED_CLOCK_SKEW_SECONDS (Dhall field allowedClockSkewSeconds) must be >= 0"
     _ -> pure m
 
 -- | Read and validate @SHOMEI_SIGNING_ALG@ (@ES256@|@RS256@); absent/empty → Nothing.
@@ -1458,7 +1446,7 @@
 normalizeSigningAlg label t = case Text.strip t of
   "ES256" -> pure "ES256"
   "RS256" -> pure "RS256"
-  other -> ioError (userError (Text.unpack label <> " must be ES256|RS256, got " <> Text.unpack other))
+  _ -> configurationError (Text.unpack label <> " must be ES256|RS256")
 
 sessionCheckEnv :: IO (Maybe SessionCheckMode)
 sessionCheckEnv = do
@@ -1468,4 +1456,4 @@
     Just "" -> pure Nothing
     Just "token-only" -> pure (Just VerifyTokenOnly)
     Just "token-and-session" -> pure (Just VerifyTokenAndSession)
-    Just other -> ioError (userError ("SHOMEI_SESSION_CHECK must be token-only|token-and-session, got " <> other))
+    Just _ -> configurationError "SHOMEI_SESSION_CHECK must be token-only|token-and-session"
diff --git a/src/Shomei/Server/ConfigurationError.hs b/src/Shomei/Server/ConfigurationError.hs
new file mode 100644
--- /dev/null
+++ b/src/Shomei/Server/ConfigurationError.hs
@@ -0,0 +1,21 @@
+-- | Expected configuration rejection. Descriptions must contain no submitted values.
+module Shomei.Server.ConfigurationError (ConfigurationError (..), configurationError, reportConfigurationError) where
+
+import Control.Exception (Exception, catch, throwIO)
+import Data.Char (isControl)
+import System.Exit (exitFailure)
+import System.IO (hPutStrLn, stderr)
+
+newtype ConfigurationError = ConfigurationError String
+  deriving stock (Show)
+  deriving anyclass (Exception)
+
+configurationError :: String -> IO a
+configurationError = throwIO . ConfigurationError
+
+-- | Catch only expected configuration failures at an executable's loading boundary.
+reportConfigurationError :: String -> IO a -> IO a
+reportConfigurationError prefix action =
+  action `catch` \(ConfigurationError description) -> do
+    hPutStrLn stderr (prefix <> ": " <> map (\c -> if isControl c then ' ' else c) description)
+    exitFailure
diff --git a/src/Shomei/Server/Middleware/BodyLimit.hs b/src/Shomei/Server/Middleware/BodyLimit.hs
--- a/src/Shomei/Server/Middleware/BodyLimit.hs
+++ b/src/Shomei/Server/Middleware/BodyLimit.hs
@@ -7,6 +7,7 @@
 -- length are metered chunk by chunk as the downstream application consumes them.
 module Shomei.Server.Middleware.BodyLimit
   ( bodyLimitMiddleware,
+    bodyLimitMiddlewareWithOAuthMounts,
     defaultBodyLimitBytes,
   )
 where
@@ -20,9 +21,11 @@
   ( Middleware,
     RequestBodyLength (KnownLength),
     getRequestBodyChunk,
+    pathInfo,
     requestBodyLength,
     setRequestBodyChunks,
   )
+import Shomei.OAuth.Boundary (OAuthMounts, defaultOAuthMounts, isOAuthPath, oauthBoundaryResponse)
 import Shomei.Servant.Error (noProblemOccurrence, pcPayloadTooLarge)
 import Shomei.Servant.Middleware (problemResponse)
 
@@ -37,7 +40,10 @@
 
 -- | Reject a request once its declared or observed body length is strictly greater than @limit@.
 bodyLimitMiddleware :: Word64 -> Middleware
-bodyLimitMiddleware limit app req respond
+bodyLimitMiddleware = bodyLimitMiddlewareWithOAuthMounts defaultOAuthMounts
+
+bodyLimitMiddlewareWithOAuthMounts :: OAuthMounts -> Word64 -> Middleware
+bodyLimitMiddlewareWithOAuthMounts mounts limit app req respond
   | KnownLength n <- requestBodyLength req, n > limit = respond tooLarge
   | otherwise = do
       seen <- newIORef 0
@@ -55,4 +61,6 @@
         already <- readIORef responded
         if already then throwIO e else respond tooLarge
   where
-    tooLarge = problemResponse pcPayloadTooLarge noProblemOccurrence
+    tooLarge
+      | isOAuthPath mounts (pathInfo req) = oauthBoundaryResponse 413
+      | otherwise = problemResponse pcPayloadTooLarge noProblemOccurrence
diff --git a/src/Shomei/Server/Middleware/RateLimit.hs b/src/Shomei/Server/Middleware/RateLimit.hs
--- a/src/Shomei/Server/Middleware/RateLimit.hs
+++ b/src/Shomei/Server/Middleware/RateLimit.hs
@@ -42,6 +42,7 @@
     newRateLimiterFor,
     newRateLimiterWith,
     rateLimitMiddleware,
+    rateLimitMiddlewareWithOAuthMounts,
     throttledPath,
     takeToken,
     bucketCount,
@@ -56,6 +57,7 @@
 import GHC.Clock (getMonotonicTimeNSec)
 import Network.Wai (Middleware, Request, pathInfo, remoteHost, requestMethod)
 import Shomei.Config (RateLimitConfig (..))
+import Shomei.OAuth.Boundary (OAuthMounts, defaultOAuthMounts, isOAuthPath, oauthBoundaryResponse)
 import Shomei.Servant.Api (shomeiThrottledRoutes)
 import Shomei.Servant.ClientIp (clientIpText)
 import Shomei.Servant.Error (pcTooManyRequests, retryAfterOccurrence)
@@ -152,7 +154,10 @@
 
 -- | The WAI middleware. Passes non-throttled paths straight through.
 rateLimitMiddleware :: RateLimiter -> Middleware
-rateLimitMiddleware rl app req respond
+rateLimitMiddleware = rateLimitMiddlewareWithOAuthMounts defaultOAuthMounts
+
+rateLimitMiddlewareWithOAuthMounts :: OAuthMounts -> RateLimiter -> Middleware
+rateLimitMiddlewareWithOAuthMounts mounts rl app req respond
   | not rl.enabled || not (throttledPath rl req) = app req respond
   | otherwise = do
       nowSecs <- monotonicSeconds
@@ -163,7 +168,9 @@
     -- @Retry-After@. This
     -- answers before Servant ever routes the request, so it cannot go through the handler
     -- error mapping — it shares the catalog constant instead.
-    tooMany = problemResponse pcTooManyRequests (retryAfterOccurrence 60)
+    tooMany
+      | isOAuthPath mounts (pathInfo req) = oauthBoundaryResponse 429
+      | otherwise = problemResponse pcTooManyRequests (retryAfterOccurrence 60)
 
 -- | Match the request against the routes derived from the API type. Method, path length, and
 -- every literal segment must agree; captures match exactly one segment.
diff --git a/src/Shomei/Server/Observability/Metrics.hs b/src/Shomei/Server/Observability/Metrics.hs
--- a/src/Shomei/Server/Observability/Metrics.hs
+++ b/src/Shomei/Server/Observability/Metrics.hs
@@ -31,7 +31,6 @@
 import Data.ByteString.Builder (Builder, byteString, doubleDec, intDec, toLazyByteString)
 import Data.ByteString.Lazy qualified as BL
 import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef)
-import Data.List (sortOn)
 import Data.Map.Strict (Map)
 import Data.Map.Strict qualified as Map
 import Data.Text (Text)
@@ -60,8 +59,11 @@
   }
 
 histogramBuckets :: [Double]
-histogramBuckets = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
+histogramBuckets = map fst bucketLabels
 
+bucketLabels :: [(Double, Text)]
+bucketLabels = [(0.005, "0.005"), (0.01, "0.01"), (0.025, "0.025"), (0.05, "0.05"), (0.1, "0.1"), (0.25, "0.25"), (0.5, "0.5"), (1, "1"), (2.5, "2.5"), (5, "5"), (10, "10")]
+
 newMetrics :: IO Metrics
 newMetrics =
   Metrics
@@ -156,29 +158,29 @@
     )
   where
     reqLines reqs =
-      helpType "http_requests_total" "counter"
+      helpType "http_requests_total" "counter" "Requests with a completed response, by method and status."
         : [ line ("http_requests_total" <> labels [("method", method), ("status", tshow status)]) (intDec n)
           | ((method, status), n) <- Map.toList reqs
           ]
     flightLines flight =
-      [ helpType "http_requests_in_flight" "gauge",
+      [ helpType "http_requests_in_flight" "gauge" "Requests currently being handled.",
         line "http_requests_in_flight" (intDec flight)
       ]
     histLines dsum dcount buckets =
-      helpType "http_request_duration_seconds" "histogram"
-        : [ line ("http_request_duration_seconds_bucket" <> labels [("le", tshow le)]) (intDec c)
-          | (le, c) <- sortOn fst (Map.toList buckets)
+      helpType "http_request_duration_seconds" "histogram" "Time in seconds through response completion."
+        : [ line ("http_request_duration_seconds_bucket" <> labels [("le", label)]) (intDec (Map.findWithDefault 0 le buckets))
+          | (le, label) <- bucketLabels
           ]
           <> [ line ("http_request_duration_seconds_bucket" <> labels [("le", "+Inf")]) (intDec dcount),
                line "http_request_duration_seconds_sum" (doubleDec dsum),
                line "http_request_duration_seconds_count" (intDec dcount)
              ]
     domainLines ok failed issued =
-      [ helpType "shomei_logins_succeeded_total" "counter",
+      [ helpType "shomei_logins_succeeded_total" "counter" "Login POST responses with status 200.",
         line "shomei_logins_succeeded_total" (intDec ok),
-        helpType "shomei_logins_failed_total" "counter",
+        helpType "shomei_logins_failed_total" "counter" "Login POST responses with status 401.",
         line "shomei_logins_failed_total" (intDec failed),
-        helpType "shomei_tokens_issued_total" "counter",
+        helpType "shomei_tokens_issued_total" "counter" "Successful token-issuing login, signup, refresh and OAuth token responses.",
         line "shomei_tokens_issued_total" (intDec issued)
       ]
 
@@ -187,8 +189,22 @@
 line :: Builder -> Builder -> Builder
 line name val = name <> byteString " " <> val <> byteString "\n"
 
-helpType :: ByteString -> ByteString -> Builder
-helpType name ty = byteString "# TYPE " <> byteString name <> byteString " " <> byteString ty <> byteString "\n"
+helpType :: ByteString -> ByteString -> Text -> Builder
+helpType name ty description =
+  byteString "# HELP "
+    <> byteString name
+    <> byteString " "
+    <> byteString (encodeUtf8 (Text.concatMap escapeHelp description))
+    <> byteString "\n"
+    <> byteString "# TYPE "
+    <> byteString name
+    <> byteString " "
+    <> byteString ty
+    <> byteString "\n"
+  where
+    escapeHelp '\\' = "\\\\"
+    escapeHelp '\n' = "\\n"
+    escapeHelp c = Text.singleton c
 
 labels :: [(ByteString, Text)] -> Builder
 labels [] = mempty
diff --git a/test/Admin/Main.hs b/test/Admin/Main.hs
--- a/test/Admin/Main.hs
+++ b/test/Admin/Main.hs
@@ -4,16 +4,21 @@
 -- overlapping-key JWKS verification.
 module Main (main) where
 
-import Control.Exception (try)
+import Control.Exception (bracket, try)
 import Control.Monad (forM_, void)
+import Crypto.Cipher.AES (AES256)
+import Crypto.Cipher.Types (AEAD, AEADMode (AEAD_GCM), aeadInit, aeadSimpleEncrypt, cipherInit, unAuthTag)
+import Crypto.Error (CryptoFailable (..))
 import Crypto.JOSE.JWK (JWK, JWKSet (JWKSet))
 import Data.Aeson qualified as Aeson
 import Data.Aeson.KeyMap qualified as KeyMap
+import Data.ByteArray qualified as BA
 import Data.ByteArray.Encoding (Base (Base64), convertToBase)
+import Data.ByteString qualified as BS
 import Data.ByteString.Char8 qualified as BS8
-import Data.IORef (newIORef, readIORef)
+import Data.IORef (atomicModifyIORef', newIORef, readIORef)
 import Data.Int (Int64)
-import Data.List (find)
+import Data.List (find, isInfixOf, isPrefixOf)
 import Data.Maybe (isJust)
 import Data.Set (Set)
 import Data.Set qualified as Set
@@ -31,10 +36,11 @@
 import Hasql.Session qualified as Session
 import Hasql.Statement (preparable)
 import Options.Applicative (ParserResult (..), defaultPrefs, execParserPure, info)
+import Shomei.Account.Admin.Recovery (RecoveryCommand (..), RecoveryCounts (..), RecoveryResult (..))
 import Shomei.Account.Password.Domain (PasswordPolicy (..), PlainPassword (..))
 import Shomei.Account.Password.Hash.Postgres (Argon2Params (..), sha256Hex)
 import Shomei.Account.User.Postgres (runUserStorePostgres)
-import Shomei.Admin.Audit (AuditFilters (..), runAuditReader, toJsonObject, toQuery)
+import Shomei.Admin.Audit (AuditFilters (..), auditParser, runAuditReader, toJsonObject, toQuery)
 import Shomei.Admin.Env (AdminEnv (..))
 import Shomei.Admin.Keys
   ( keysActivate,
@@ -50,7 +56,7 @@
 import Shomei.Admin.Roles (GrantExpiry (..), RolesCommand (..), rolesParser, runRoles)
 import Shomei.Admin.ServiceAccounts (createAction, listAction, revokeAction, rotateSecretAction)
 import Shomei.Admin.Sweep (SweepOptions (..), defaultSweepOptions, runSweepReport)
-import Shomei.Admin.Users (createUserAction)
+import Shomei.Admin.Users (ResetMfaOptions (..), createUserAction, resetMfaAction, resetMfaParser, runRecovery, validateResetMfaOptions)
 import Shomei.Audit.Event.Domain qualified as Event
 import Shomei.Audit.Publisher.Postgres (runAuthEventPublisherPostgres)
 import Shomei.Audit.Publisher.Store (AuthEventPublisher, publishAuthEvent)
@@ -64,7 +70,7 @@
 import Shomei.Authorization.Claims.Domain (Audience (..), AuthClaims (..), Issuer (..), Role (..), Scope (..))
 import Shomei.Config (ShomeiConfig (..), defaultShomeiConfig)
 import Shomei.Error (AuthError (OAuthClientInvalid))
-import Shomei.Id (genSessionId, genUserId, idText, sessionIdToUUID, userIdToUUID)
+import Shomei.Id (genSessionId, genUserId, idText, sessionIdToUUID, userIdFromUUID, userIdToUUID)
 import Shomei.Migrations.TestSupport (withShomeiMigratedDatabase)
 import Shomei.OAuth.Client.Domain (ClientType (..), OAuthClient (..), OAuthClientStatus (..))
 import Shomei.OAuth.IdToken.Domain (IdToken (..))
@@ -97,7 +103,11 @@
 import Shomei.SigningKey.Signer (TokenSigner (..))
 import Shomei.SigningKey.Verify.Jwt (verifyToken)
 import Shomei.Time.Postgres (runClockIO)
+import System.Directory (findExecutable, getTemporaryDirectory, removeFile)
+import System.Environment (getEnvironment)
 import System.Exit (ExitCode (..))
+import System.IO (hClose, hPutStr, openTempFile)
+import System.Process (CreateProcess (..), proc, readCreateProcessWithExitCode)
 import Test.Tasty (TestTree, defaultMain, testGroup)
 import Test.Tasty.HUnit (assertBool, assertEqual, assertFailure, testCase, (@?=))
 
@@ -165,7 +175,11 @@
   defaultMain
     ( testGroup
         "shomei-admin"
-        [ testMigrateEmpty,
+        [ testOperatorArguments,
+          testStartupErrors,
+          testTotpMaintenance,
+          testRevocationNote,
+          testMigrateEmpty,
           testLifecycleOverlap,
           testReloadPicksUpRotation,
           testReloadKeepsLastGoodMaterial,
@@ -176,6 +190,8 @@
           testKeyWriteRollback,
           testMultipleActiveFailClosed,
           testUsageErrorSummary,
+          testResetMfaParsing,
+          testResetMfaPersisted,
           testUserCreate,
           testUserCreateEmailVerified,
           testUserCreateAppliesPasswordPolicy,
@@ -1075,3 +1091,164 @@
   case loaded of
     Left reason -> assertBool "diagnostic names the invariant" ("multiple active signing keys" `Text.isInfixOf` reason)
     Right _ -> assertFailure "ambiguous signer was accepted"
+
+-- Child environments never inherit deployment credentials or policy.
+runBinary :: String -> [String] -> [(String, String)] -> IO (ExitCode, String, String)
+runBinary binary args fixture = do
+  executable <- findExecutable binary >>= maybe (assertFailure ("missing build tool " <> binary)) pure
+  inherited <- getEnvironment
+  let clean = filter (\(key, _) -> not ("SHOMEI_" `isPrefixOf` key) && key `notElem` ["DATABASE_URL", "PG_CONNECTION_STRING"] && key `notElem` map fst fixture) inherited
+  readCreateProcessWithExitCode (proc executable args) {env = Just (fixture <> clean)} ""
+
+withConfigText :: String -> (FilePath -> IO a) -> IO a
+withConfigText contents action = do
+  directory <- getTemporaryDirectory
+  bracket (do (path, handle) <- openTempFile directory "shomei-config"; hPutStr handle contents; hClose handle; pure path) removeFile action
+
+assertSafeFailure :: String -> (ExitCode, String, String) -> IO ()
+assertSafeFailure setting (code, out, err) = do
+  assertBool "failure exit" (code /= ExitSuccess)
+  length (lines err) @?= 1
+  assertBool "names setting" (setting `isInfixOf` err)
+  forM_ ["Uncaught exception", "user error", "CallStack", "SENTINEL_SECRET"] \forbidden ->
+    assertBool ("diagnostic excludes " <> forbidden) (not (forbidden `isInfixOf` (out <> err)))
+
+testOperatorArguments :: TestTree
+testOperatorArguments = testCase "required redirects and known audit types are validated before loading configuration" do
+  let create = ["oauth-clients", "create", "--display-name", "example", "--type", "public"]
+  (helpCode, helpText, _) <- runBinary "shomei-admin" (create <> ["--help"]) []
+  helpCode @?= ExitSuccess
+  assertBool "help requires the first redirect" ("--redirect-uri URI" `isInfixOf` helpText && not ("[--redirect-uri URI" `isInfixOf` helpText))
+  (missing, _, missingErr) <- runBinary "shomei-admin" create []
+  assertBool "missing redirect fails at parse" (missing /= ExitSuccess && "--redirect-uri" `isInfixOf` missingErr && not ("DATABASE_URL" `isInfixOf` missingErr))
+  forM_ [["https://example.com/a"], ["https://example.com/a", "https://example.com/b"]] \uris -> do
+    result <- runBinary "shomei-admin" (create <> concatMap (\uri -> ["--redirect-uri", uri]) uris) []
+    assertSafeFailure "DATABASE_URL" result
+  forM_ [["events"], ["user", "00000000-0000-0000-0000-000000000001"], ["session", "00000000-0000-0000-0000-000000000001"], ["count"]] \command -> do
+    forM_ [["no_such_type"], ["login_failed", "no_such_type"]] \types -> do
+      (code, _, err) <- runBinary "shomei-admin" (["audit"] <> command <> concatMap (\ty -> ["--type", ty]) types) []
+      assertBool "unknown filter lists accepted names at parse time" (code /= ExitSuccess && "accepted:" `isInfixOf` err && "login_failed" `isInfixOf` err && not ("DATABASE_URL" `isInfixOf` err))
+    case execParserPure defaultPrefs (info auditParser mempty) (command <> ["--type", "login_failed", "--type", "login_succeeded"]) of
+      Success _ -> pure ()
+      _ -> assertFailure "repeated valid types should parse"
+  let filters = AuditFilters Nothing Nothing ["no_such_type"] Nothing Nothing 50 False
+  valid <- toQuery filters {fTypes = ["login_failed", "login_succeeded"]}
+  valid.queryEventTypes @?= ["login_failed", "login_succeeded"]
+  rejected <- try @ExitCode (toQuery filters)
+  case rejected of Left (ExitFailure _) -> pure (); _ -> assertFailure "direct unknown filter accepted"
+
+testStartupErrors :: TestTree
+testStartupErrors = testCase "both binaries report safe single-line configuration failures" do
+  forM_ [("shomei-admin", ["keys", "list"], "DATABASE_URL"), ("shomei-server", [], "PG_CONNECTION_STRING")] \(binary, args, connection) -> do
+    runBinary binary args [] >>= assertSafeFailure connection
+    let db = [(connection, "host=localhost password=SENTINEL_SECRET")]
+    runBinary binary args (db <> [("SHOMEI_ARGON2_MEMORY_KIB", "SENTINEL_SECRET\ninjected")]) >>= assertSafeFailure "SHOMEI_ARGON2_MEMORY_KIB"
+    runBinary binary args (db <> [("SHOMEI_CONFIG", "/missing/SENTINEL_SECRET")]) >>= assertSafeFailure "SHOMEI_CONFIG"
+    runBinary binary args (db <> [("SHOMEI_CONFIG", "/missing/SENTINEL_SECRET"), ("PATH", "/missing")]) >>= assertSafeFailure "SHOMEI_CONFIG"
+    forM_ ["{ unknown = \"SENTINEL_SECRET\" }", "{ argon2MemoryKiB = \"SENTINEL_SECRET\" }", "SENTINEL_SECRET invalid Dhall", "{ attestationPolicy = \"SENTINEL_SECRET\" }"] \contents ->
+      withConfigText contents \path -> runBinary binary args (db <> [("SHOMEI_CONFIG", path)]) >>= assertSafeFailure "SHOMEI_CONFIG"
+  runBinary "shomei-server" [] [("PG_CONNECTION_STRING", "host=localhost password=SENTINEL_SECRET"), ("SHOMEI_NOTIFIER_TRANSPORT", "webhook"), ("SHOMEI_WEBHOOK_URL", "https://example.com/SENTINEL_SECRET")] >>= assertSafeFailure "SHOMEI_WEBHOOK_SECRET"
+  (code, _, _) <- runBinary "shomei-admin" ["--help"] []
+  code @?= ExitSuccess
+
+testRevocationNote :: TestTree
+testRevocationNote = testCase "revocation guidance is independent of machine token TTL" $ withDb \pool connStr -> do
+  let admin = AdminEnv cfg pool connStr testArgon2Params
+  emptyRedirects <- try @ExitCode (OAuthClients.createAction admin "empty" PublicClient [] [])
+  case emptyRedirects of
+    Left (ExitFailure _) -> pure ()
+    _ -> assertFailure "direct empty redirect list accepted"
+  forM_ [[], [("SHOMEI_MACHINE_TOKEN_TTL", "900")]] \policy -> do
+    (account, _) <- createAction admin "note test" []
+    (code, out, err) <- runBinary "shomei-admin" ["service-accounts", "revoke", Text.unpack (saClientId' account)] ([("DATABASE_URL", Text.unpack connStr)] <> policy)
+    code @?= ExitSuccess
+    err @?= ""
+    lines out @?= ["revoked " <> Text.unpack (saClientId' account), "note: tokens already issued to this account remain valid until they expire"]
+
+testTotpMaintenance :: TestTree
+testTotpMaintenance = testCase "offline TOTP no-op is keyless but still checks versions and offline acknowledgement" $ withDb \pool connStr -> do
+  let fixture = [("DATABASE_URL", Text.unpack connStr)]
+      args = ["totp", "migrate-envelopes"]
+      success extra env expected = do
+        (code, out, err) <- runBinary "shomei-admin" (args <> extra) (env <> fixture)
+        code @?= ExitSuccess
+        err @?= ""
+        out @?= expected
+  success ["--check"] [] "legacy=0 invalid_versions=0\n"
+  forM_ [[], [("SHOMEI_TOTP_ENCRYPTION_KEY", "SENTINEL_SECRET")]] \key -> success ["--offline"] key "legacy=0 invalid_versions=0\nconverted=0\n"
+  (offlineCode, _, _) <- runBinary "shomei-admin" args fixture
+  assertBool "offline required even for no-op" (offlineCode /= ExitSuccess)
+  -- The no-op must neither decrypt nor rewrite bound rows, including pending factors.
+  execSql pool "INSERT INTO shomei.shomei_users (user_id,login_id,status,created_at,updated_at) VALUES ('00000000-0000-0000-0000-000000000001','totp-noop','active',now(),now()); INSERT INTO shomei.shomei_totp_credentials (totp_credential_id,user_id,secret_enc,envelope_version,created_at) VALUES ('00000000-0000-0000-0000-000000000002','00000000-0000-0000-0000-000000000001',decode('010203','hex'),1,now())"
+  success ["--offline"] [] "legacy=0 invalid_versions=0\nconverted=0\n"
+  success ["--offline"] [("SHOMEI_TOTP_ENCRYPTION_KEY", "SENTINEL_SECRET")] "legacy=0 invalid_versions=0\nconverted=0\n"
+  scalarInt pool "SELECT count(*) FROM shomei.shomei_totp_credentials WHERE secret_enc=decode('010203','hex')" >>= (@?= 1)
+  execSql pool "ALTER TABLE shomei.shomei_totp_credentials DROP CONSTRAINT IF EXISTS shomei_totp_credentials_envelope_version_check; UPDATE shomei.shomei_totp_credentials SET envelope_version=9"
+  success ["--check", "--offline"] [] "legacy=0 invalid_versions=1\n"
+  (unknown, _, _) <- runBinary "shomei-admin" (args <> ["--offline"]) fixture
+  assertBool "unknown version refused" (unknown /= ExitSuccess)
+  execSql pool "UPDATE shomei.shomei_totp_credentials SET envelope_version=0"
+  forM_ [[], [("SHOMEI_TOTP_ENCRYPTION_KEY", "SENTINEL_SECRET")]] \key -> do
+    result <- runBinary "shomei-admin" (args <> ["--offline"]) (key <> fixture)
+    assertSafeFailure "SHOMEI_TOTP_ENCRYPTION_KEY" result
+
+  -- Reuse the legacy AES-GCM fixture construction from the PostgreSQL converter tests.
+  let legacyBlob = case cipherInit (BS.replicate 32 7) >>= (\cipher -> aeadInit AEAD_GCM cipher (BS.replicate 12 3)) :: CryptoFailable (AEAD AES256) of
+        CryptoFailed _ -> error "test-only AES initialization failed"
+        CryptoPassed st ->
+          let (tag, ciphertext) = aeadSimpleEncrypt st (BS.empty :: BS.ByteString) ("12345678901234567890" :: BS.ByteString) 16
+           in BS.replicate 12 3 <> ciphertext <> BA.convert (unAuthTag tag)
+      seed = preparable "UPDATE shomei.shomei_totp_credentials SET secret_enc=$1, envelope_version=0" (E.param (E.nonNullable E.bytea)) D.noResult
+      encodedKey byte = Text.unpack (TE.decodeUtf8 (convertToBase Base64 (BS.replicate 32 byte) :: BS.ByteString))
+  okR =<< Pool.use pool (Session.statement legacyBlob seed)
+  (wrong, _, wrongErr) <- runBinary "shomei-admin" (args <> ["--offline"]) ([("SHOMEI_TOTP_ENCRYPTION_KEY", encodedKey 8)] <> fixture)
+  assertBool "wrong key fails without overwrite" (wrong /= ExitSuccess && "no unreadable row overwritten" `isInfixOf` wrongErr)
+  scalarInt pool "SELECT count(*) FROM shomei.shomei_totp_credentials WHERE envelope_version=0" >>= (@?= 1)
+  success ["--offline"] [("SHOMEI_TOTP_ENCRYPTION_KEY", encodedKey 7)] "legacy=1 invalid_versions=0\nconverted=1\n"
+  success ["--offline"] [] "legacy=0 invalid_versions=0\nconverted=0\n"
+  (emptyCode, emptyOut, emptyErr) <- runBinary "shomei-admin" ["audit", "events", "--type", "login_failed"] fixture
+  emptyCode @?= ExitSuccess
+  emptyOut @?= ""
+  emptyErr @?= ""
+  (countCode, countOut, _) <- runBinary "shomei-admin" ["audit", "count", "--type", "login_failed"] fixture
+  countCode @?= ExitSuccess
+  countOut @?= "0\n"
+
+testResetMfaParsing :: TestTree
+testResetMfaParsing = testCase "users reset-mfa requires every assertion and confirms the exact target before database work" $ do
+  uid <- genUserId
+  other <- genUserId
+  let args = ["--user", Text.unpack (idText uid), "--operator", "ops.test", "--case-reference", "INC-42", "--identity-verified", "--confirm-user", Text.unpack (idText uid)]
+      parse = execParserPure defaultPrefs (info resetMfaParser mempty)
+  case parse args of
+    Success options -> validateResetMfaOptions options @?= Right ()
+    _ -> assertFailure "complete recovery options did not parse"
+  forM_ [filter (/= "--identity-verified") args, take 7 args] $ \incomplete -> case parse incomplete of
+    Failure _ -> pure ()
+    _ -> assertFailure "missing recovery assertion was accepted"
+  validateResetMfaOptions (ResetMfaOptions uid "ops.test" "INC-42" True other) @?= Left "--confirm-user must exactly match --user"
+  case validateResetMfaOptions (ResetMfaOptions uid "unsafe operator" "INC-42" True uid) of
+    Left _ -> pure ()
+    _ -> assertFailure "invalid operator label accepted"
+
+testResetMfaPersisted :: TestTree
+testResetMfaPersisted = testCase "CLI recovery commits shared reset with local attribution and no manufactured administrator" $ withDb \pool connStr -> do
+  let env = AdminEnv {config = cfg, pool, connStr, argon2 = testArgon2Params}
+  createUserAction env "recovery@example.com" (PlainPassword "correct horse battery staple") Nothing False
+  raw <- scalarText pool "SELECT user_id::text FROM shomei.shomei_users WHERE email='recovery@example.com'"
+  uid <- maybe (assertFailure "invalid persisted UUID") (pure . userIdFromUUID) (UUID.fromText raw)
+  before <- scalarInt pool "SELECT count(*) FROM shomei.shomei_users"
+  expectExitFailure "mismatched target confirmation" (resetMfaAction env (ResetMfaOptions uid "ops.test" "INC-42" False uid))
+  scalarInt pool "SELECT count(*) FROM shomei.shomei_auth_events WHERE event_type='user_second_factors_reset'" >>= (@?= 0)
+  notices <- newIORef []
+  result <- runRecovery pool (\notice -> atomicModifyIORef' notices (\ns -> (notice : ns, ()))) uid "ops.test" (RecoveryCommand True "INC-42")
+  case result of
+    Right (Right recovered) -> do
+      recovered.counts.sessionsRevoked @?= 1
+      recovered.verifiedNotificationDestination @?= False
+    other -> assertFailure ("CLI shared recovery failed: " <> show other)
+  scalarInt pool "SELECT count(*) FROM shomei.shomei_users" >>= (@?= before)
+  scalarInt pool "SELECT count(*) FROM shomei.shomei_sessions WHERE status='active'" >>= (@?= 0)
+  scalarInt pool "SELECT count(*) FROM shomei.shomei_refresh_tokens WHERE status='active'" >>= (@?= 0)
+  scalarInt pool "SELECT count(*) FROM shomei.shomei_auth_events WHERE event_type='user_second_factors_reset' AND payload->'recoveryActor'->>'tag'='LocalOperator' AND payload->'recoveryActor'->>'contents'='ops.test' AND payload->>'caseReference'='INC-42'" >>= (@?= 1)
+  readIORef notices >>= (@?= [])
diff --git a/test/Main.hs b/test/Main.hs
--- a/test/Main.hs
+++ b/test/Main.hs
@@ -3,6 +3,7 @@
 import Shomei.Server.E2ESpec qualified as E2ESpec
 import Shomei.Server.MiddlewareSpec qualified as MiddlewareSpec
 import Shomei.Server.NotifySpec qualified as NotifySpec
+import Shomei.Server.OAuthContractSpec qualified as OAuthContract
 import Shomei.Server.RuntimeSpec qualified as RuntimeSpec
 import Shomei.Server.SupervisorSpec qualified as SupervisorSpec
 import Test.Tasty (defaultMain, testGroup)
@@ -12,5 +13,5 @@
   defaultMain
     ( testGroup
         "shomei-server"
-        [RuntimeSpec.tests, NotifySpec.tests, SupervisorSpec.tests, MiddlewareSpec.tests, E2ESpec.tests]
+        [OAuthContract.tests, RuntimeSpec.tests, NotifySpec.tests, SupervisorSpec.tests, MiddlewareSpec.tests, E2ESpec.tests]
     )
diff --git a/test/Shomei/Server/ConfigSpec.hs b/test/Shomei/Server/ConfigSpec.hs
--- a/test/Shomei/Server/ConfigSpec.hs
+++ b/test/Shomei/Server/ConfigSpec.hs
@@ -1,8 +1,7 @@
 -- | Tests for EP-5's Dhall + environment configuration loader. Writes a small Dhall file to a
 -- temp path, loads it through 'loadConfig' (which renders it via @dhall-to-json@ and decodes the
 -- result), asserts the parsed values win over the built-in defaults, and then proves an
--- environment variable overrides the file value (twelve-factor precedence). Using a temp file
--- avoids any dependency on the test's working directory.
+-- environment variable overrides the file value (twelve-factor precedence).
 module Main (main) where
 
 import Control.Exception (try)
@@ -19,10 +18,10 @@
 import Shomei.Config (CookieConfig (..), MachineTokenConfig (..), MfaConfig (..), NotifierConfig (..), NotifierTransport (..), RateLimitConfig (..), ShomeiConfig (..), SigningKeyConfig (..), SmtpConfig (..), SmtpTlsMode (..), WebAuthnConfig (..), WebhookConfig (..))
 import Shomei.Notify (NotifierSecrets (..), smtpPasswordText, webhookSecretBytes)
 import Shomei.Server.Config (FileConfig, ServerSettings (..), SweepSettings (..), loadConfig, loadConfigFromEnv, loadCoreConfig, loadNotifierSecretsFromEnv)
+import Shomei.Server.ConfigurationError (ConfigurationError)
 import Shomei.Server.Keys (loadKekFromEnv)
 import System.Directory (makeAbsolute)
 import System.Environment (setEnv, unsetEnv)
-import System.IO.Error (isUserError)
 import System.Process (readProcess)
 import Test.Tasty (TestTree, defaultMain)
 import Test.Tasty.HUnit (Assertion, assertBool, assertFailure, testCase, (@?=))
@@ -94,25 +93,25 @@
   setEnv "PG_CONNECTION_STRING" "host=localhost dbname=shomei"
   setEnv "SHOMEI_DB_POOL_SIZE" "0"
   sizeResult <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_DB_POOL_SIZE" sizeResult
+  expectConfigurationErrorNaming "SHOMEI_DB_POOL_SIZE" sizeResult
   unsetEnv "SHOMEI_DB_POOL_SIZE"
   setEnv "SHOMEI_DB_POOL_ACQUISITION_TIMEOUT_MS" "-1"
   timeoutResult <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_DB_POOL_ACQUISITION_TIMEOUT_MS" timeoutResult
+  expectConfigurationErrorNaming "SHOMEI_DB_POOL_ACQUISITION_TIMEOUT_MS" timeoutResult
   unsetEnv "SHOMEI_DB_POOL_ACQUISITION_TIMEOUT_MS"
   setEnv "SHOMEI_DB_STATEMENT_TIMEOUT_MS" "-1"
   statementTimeoutResult <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_DB_STATEMENT_TIMEOUT_MS" statementTimeoutResult
+  expectConfigurationErrorNaming "SHOMEI_DB_STATEMENT_TIMEOUT_MS" statementTimeoutResult
   unsetEnv "SHOMEI_DB_STATEMENT_TIMEOUT_MS"
   setEnv "SHOMEI_NOTIFIER_QUEUE_SIZE" "0"
   notifierQueueResult <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_NOTIFIER_QUEUE_SIZE" notifierQueueResult
+  expectConfigurationErrorNaming "SHOMEI_NOTIFIER_QUEUE_SIZE" notifierQueueResult
   unsetEnv "SHOMEI_NOTIFIER_QUEUE_SIZE"
   mapM_
     ( \key -> do
         setEnv key "0"
         invalid <- try loadConfigFromEnv
-        expectUserErrorNaming key invalid
+        expectConfigurationErrorNaming key invalid
         unsetEnv key
     )
     ["SHOMEI_DB_TRANSACTION_MAX_ATTEMPTS", "SHOMEI_DB_TRANSACTION_DEADLINE_MS", "SHOMEI_MAX_CONNECTIONS", "SHOMEI_SLOW_CLIENT_TIMEOUT_SECONDS"]
@@ -195,18 +194,18 @@
   setEnv "PG_CONNECTION_STRING" "host=localhost dbname=shomei"
   setEnv "SHOMEI_SWEEP_INTERVAL_SECONDS" "0"
   intervalResult <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_SWEEP_INTERVAL_SECONDS" intervalResult
+  expectConfigurationErrorNaming "SHOMEI_SWEEP_INTERVAL_SECONDS" intervalResult
   unsetEnv "SHOMEI_SWEEP_INTERVAL_SECONDS"
 
   setEnv "SHOMEI_SWEEP_BATCH_SIZE" "0"
   batchResult <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_SWEEP_BATCH_SIZE" batchResult
+  expectConfigurationErrorNaming "SHOMEI_SWEEP_BATCH_SIZE" batchResult
   unsetEnv "SHOMEI_SWEEP_BATCH_SIZE"
 
   -- A negative grace period would sweep rows that have not expired yet.
   setEnv "SHOMEI_SWEEP_CEREMONY_GRACE_MINUTES" "-1"
   graceResult <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_SWEEP_CEREMONY_GRACE_MINUTES" graceResult
+  expectConfigurationErrorNaming "SHOMEI_SWEEP_CEREMONY_GRACE_MINUTES" graceResult
   unsetEnv "SHOMEI_SWEEP_CEREMONY_GRACE_MINUTES"
   unsetEnv "PG_CONNECTION_STRING"
 
@@ -236,7 +235,7 @@
   setEnv "SHOMEI_ARGON2_MEMORY_KIB" "64"
   setEnv "SHOMEI_ARGON2_PARALLELISM" "16"
   hardFloorResult <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_ARGON2_MEMORY_KIB" hardFloorResult
+  expectConfigurationErrorNaming "SHOMEI_ARGON2_MEMORY_KIB" hardFloorResult
 
   setEnv "SHOMEI_ARGON2_MEMORY_KIB" "128"
   (_, boundary) <- loadConfigFromEnv
@@ -247,12 +246,12 @@
   -- A zero permit count would block every login forever.
   setEnv "SHOMEI_ARGON2_MEMORY_KIB" "0"
   memResult <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_ARGON2_MEMORY_KIB" memResult
+  expectConfigurationErrorNaming "SHOMEI_ARGON2_MEMORY_KIB" memResult
   unsetEnv "SHOMEI_ARGON2_MEMORY_KIB"
 
   setEnv "SHOMEI_HASHING_MAX_CONCURRENCY" "0"
   concResult <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_HASHING_MAX_CONCURRENCY" concResult
+  expectConfigurationErrorNaming "SHOMEI_HASHING_MAX_CONCURRENCY" concResult
   mapM_ unsetEnv argon2EnvVars
   unsetEnv "PG_CONNECTION_STRING"
 
@@ -273,20 +272,20 @@
 
   writeFile configPath "{ cookieSecue = False }"
   unknownKey <- try loadConfig
-  expectUserErrorNaming "invalid SHOMEI_CONFIG" unknownKey
+  expectConfigurationErrorNaming "SHOMEI_CONFIG" unknownKey
 
   writeFile configPath "{ webauthnAttestation = \"nope\" }"
   badAttestation <- try loadConfig
-  expectUserErrorNaming "webauthnAttestation" badAttestation
+  expectConfigurationErrorNaming "webauthnAttestation" badAttestation
 
   writeFile configPath "{ webauthnOrigins = ([] : List Text) }"
   emptyFileOrigins <- try loadConfig
-  expectUserErrorNaming "webauthnOrigins" emptyFileOrigins
+  expectConfigurationErrorNaming "webauthnOrigins" emptyFileOrigins
 
   unsetEnv "SHOMEI_CONFIG"
   setEnv "SHOMEI_WEBAUTHN_ORIGINS" ","
   emptyEnvOrigins <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_WEBAUTHN_ORIGINS" emptyEnvOrigins
+  expectConfigurationErrorNaming "SHOMEI_WEBAUTHN_ORIGINS" emptyEnvOrigins
   unsetEnv "SHOMEI_WEBAUTHN_ORIGINS"
 
   setEnv "SHOMEI_EMAIL_VERIFICATION_REQUIRED" "true"
@@ -302,7 +301,7 @@
 -- shipped default still has exactly the exported 'Type'.
 dhallSchemaMatchesFileConfig :: Assertion
 dhallSchemaMatchesFileConfig = do
-  schema <- makeAbsolute "../config/shomei-types.dhall"
+  schema <- makeAbsolute "test/fixtures/shomei-types.dhall"
   writeFile schemaProbePath ("(" <> schema <> ")::{=}")
   rendered <- readProcess "dhall-to-json" ["--preserve-null", "--file", schemaProbePath] ""
   dhallKeys <-
@@ -314,13 +313,13 @@
     _ -> assertFailure "FileConfig did not encode as an object"
   Set.fromList dhallKeys @?= Set.fromList loaderKeys
 
--- | Assert a config load failed with a 'userError' whose message names the offending variable.
-expectUserErrorNaming :: String -> Either IOError a -> Assertion
-expectUserErrorNaming name = \case
+-- | Assert a config load failed with a 'ConfigurationError' whose message names the offending variable.
+expectConfigurationErrorNaming :: String -> Either ConfigurationError a -> Assertion
+expectConfigurationErrorNaming name = \case
   Left e ->
     assertBool
-      ("expected a userError naming " <> name <> ", got: " <> show e)
-      (isUserError e && Text.isInfixOf (Text.pack name) (Text.pack (show e)))
+      ("expected a ConfigurationError naming " <> name <> ", got: " <> show e)
+      (Text.isInfixOf (Text.pack name) (Text.pack (show e)))
   Right _ -> assertFailure (name <> " out of range should have failed the config load")
 
 testLoadAndOverride :: TestTree
@@ -455,6 +454,7 @@
   notifierSecretsAreStrippedAndConfigIsSecretFree
   notifierInsecureTransportFlags
   kekIsRequired
+  safeLoaderFailures
 
 passkeyQuotaSettings :: Assertion
 passkeyQuotaSettings = do
@@ -468,7 +468,7 @@
   limited.maxPasskeysPerUser @?= 1
   setEnv "SHOMEI_MAX_PASSKEYS_PER_USER" "101"
   bad <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_MAX_PASSKEYS_PER_USER" bad
+  expectConfigurationErrorNaming "SHOMEI_MAX_PASSKEYS_PER_USER" bad
   unsetEnv "SHOMEI_MAX_PASSKEYS_PER_USER"
 
 -- | Administrative workflows consume the deployment's core policy without pretending to be a
@@ -502,7 +502,7 @@
 
   setEnv "SHOMEI_ALLOWED_CLOCK_SKEW_SECONDS" "-1"
   negativeSkew <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_ALLOWED_CLOCK_SKEW_SECONDS" negativeSkew
+  expectConfigurationErrorNaming "SHOMEI_ALLOWED_CLOCK_SKEW_SECONDS" negativeSkew
   unsetEnv "SHOMEI_ALLOWED_CLOCK_SKEW_SECONDS"
 
   -- RFC 3986 permits a scheme with a rootless path, so this is a valid URI.
@@ -513,12 +513,12 @@
 
   setEnv "SHOMEI_ISSUER" "https://bad host"
   invalidIssuer <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_ISSUER" invalidIssuer
+  expectConfigurationErrorNaming "SHOMEI_ISSUER" invalidIssuer
   unsetEnv "SHOMEI_ISSUER"
 
   setEnv "SHOMEI_AUDIENCE" "https://bad audience"
   invalidAudience <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_AUDIENCE" invalidAudience
+  expectConfigurationErrorNaming "SHOMEI_AUDIENCE" invalidAudience
 
   unsetEnv "SHOMEI_AUDIENCE"
   unsetEnv "PG_CONNECTION_STRING"
@@ -563,7 +563,7 @@
 
   setEnv "SHOMEI_PER_IP_BURST" "0"
   zeroBurst <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_PER_IP_BURST" zeroBurst
+  expectConfigurationErrorNaming "SHOMEI_PER_IP_BURST" zeroBurst
   mapM_ unsetEnv rateLimitEnvVars
 
   setEnv "SHOMEI_CSRF_ALLOWED_ORIGINS" "HTTPS://App.Example.com/"
@@ -571,7 +571,7 @@
   normalized.cookieConfig.allowedOrigins @?= ["https://app.example.com"]
   setEnv "SHOMEI_CSRF_ALLOWED_ORIGINS" "https://app.example.com/login"
   invalidOrigin <- try loadConfigFromEnv
-  expectUserErrorNaming "must be scheme://host[:port] with no path" invalidOrigin
+  expectConfigurationErrorNaming "must be scheme://host[:port] with no path" invalidOrigin
 
   unsetEnv "SHOMEI_CSRF_ALLOWED_ORIGINS"
   setEnv "SHOMEI_TOKEN_TRANSPORT" "cookie"
@@ -590,11 +590,11 @@
 kekIsRequired :: Assertion
 kekIsRequired = do
   unsetEnv "SHOMEI_KEY_ENCRYPTION_KEY"
-  missing <- try loadKekFromEnv
-  expectUserErrorNaming "SHOMEI_KEY_ENCRYPTION_KEY" missing
+  missing <- try @IOError loadKekFromEnv
+  assertBool "missing KEK rejected with setting name" (either (("SHOMEI_KEY_ENCRYPTION_KEY" `isInfixOf`) . show) (const False) missing)
   setEnv "SHOMEI_KEY_ENCRYPTION_KEY" "not-base64"
-  malformed <- try loadKekFromEnv
-  expectUserErrorNaming "SHOMEI_KEY_ENCRYPTION_KEY" malformed
+  malformed <- try @IOError loadKekFromEnv
+  assertBool "malformed KEK rejected with setting name" (either (("SHOMEI_KEY_ENCRYPTION_KEY" `isInfixOf`) . show) (const False) malformed)
   setEnv "SHOMEI_KEY_ENCRYPTION_KEY" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
   _ <- loadKekFromEnv
   unsetEnv "SHOMEI_KEY_ENCRYPTION_KEY"
@@ -716,7 +716,7 @@
   setEnv "SHOMEI_NOTIFIER_TRANSPORT" "smtp"
   setEnv "SHOMEI_SMTP_FROM" "auth@example.com"
   result <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_SMTP_HOST" result
+  expectConfigurationErrorNaming "SHOMEI_SMTP_HOST" result
   mapM_ unsetEnv notifierEnvVars
   unsetEnv "PG_CONNECTION_STRING"
 
@@ -733,7 +733,7 @@
   setEnv "SHOMEI_SMTP_USERNAME" "relay-user"
   (cfg, _) <- loadConfigFromEnv
   result <- try (loadNotifierSecretsFromEnv cfg)
-  expectUserErrorNaming "SHOMEI_SMTP_PASSWORD" result
+  expectConfigurationErrorNaming "SHOMEI_SMTP_PASSWORD" result
   mapM_ unsetEnv notifierEnvVars
   unsetEnv "PG_CONNECTION_STRING"
 
@@ -747,7 +747,7 @@
   setEnv "SHOMEI_WEBHOOK_URL" "https://hooks.example.com/shomei"
   (cfg, _) <- loadConfigFromEnv
   result <- try (loadNotifierSecretsFromEnv cfg)
-  expectUserErrorNaming "SHOMEI_WEBHOOK_SECRET" result
+  expectConfigurationErrorNaming "SHOMEI_WEBHOOK_SECRET" result
   mapM_ unsetEnv notifierEnvVars
   unsetEnv "PG_CONNECTION_STRING"
 
@@ -797,7 +797,7 @@
   setEnv "SHOMEI_WEBHOOK_URL" "http://127.0.0.1:9999/hook"
   setEnv "SHOMEI_WEBHOOK_SECRET" "secret"
   insecureWebhook <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_WEBHOOK_ALLOW_INSECURE" insecureWebhook
+  expectConfigurationErrorNaming "SHOMEI_WEBHOOK_ALLOW_INSECURE" insecureWebhook
   setEnv "SHOMEI_WEBHOOK_ALLOW_INSECURE" "true"
   (webhookCfg, _) <- loadConfigFromEnv
   _ <- loadNotifierSecretsFromEnv webhookCfg
@@ -814,7 +814,7 @@
   setEnv "SHOMEI_SMTP_USERNAME" "relay-user"
   setEnv "SHOMEI_SMTP_PASSWORD" "relay-password"
   plaintextAuth <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_SMTP_ALLOW_PLAINTEXT_AUTH" plaintextAuth
+  expectConfigurationErrorNaming "SHOMEI_SMTP_ALLOW_PLAINTEXT_AUTH" plaintextAuth
   setEnv "SHOMEI_SMTP_ALLOW_PLAINTEXT_AUTH" "true"
   (smtpCfg, smtpSettings) <- loadConfigFromEnv
   assertBool "plaintext credentials warn under the explicit lab override" ("smtpTlsMode=plain sends mail and SMTP credentials in the clear; explicit lab override" `elem` smtpSettings.serverWarnings)
@@ -841,14 +841,14 @@
   defaults.signingKeyConfig.emitLegacyActor @?= False
   setEnv "SHOMEI_EMIT_LEGACY_ACTOR" "true"
   missing <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_LEGACY_ACTOR_UNTIL_UNIX" missing
+  expectConfigurationErrorNaming "SHOMEI_LEGACY_ACTOR_UNTIL_UNIX" missing
   setEnv "SHOMEI_LEGACY_ACTOR_UNTIL_UNIX" "2000000000"
   (compatible, _) <- loadConfigFromEnv
   compatible.signingKeyConfig.legacyActorUntilUnix @?= Just 2000000000
   compatible.signingKeyConfig.emitLegacyActor @?= True
   setEnv "SHOMEI_LEGACY_ACTOR_UNTIL_UNIX" "0"
   invalid <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_LEGACY_ACTOR_UNTIL_UNIX" invalid
+  expectConfigurationErrorNaming "SHOMEI_LEGACY_ACTOR_UNTIL_UNIX" invalid
   unsetEnv "SHOMEI_LEGACY_ACTOR_UNTIL_UNIX"
   unsetEnv "SHOMEI_EMIT_LEGACY_ACTOR"
 
@@ -864,5 +864,24 @@
   limited.maxActiveNonInteractiveSessions @?= 1
   setEnv "SHOMEI_MAX_ACTIVE_NON_INTERACTIVE_SESSIONS" "0"
   bad <- try loadConfigFromEnv
-  expectUserErrorNaming "SHOMEI_MAX_ACTIVE_NON_INTERACTIVE_SESSIONS" bad
+  expectConfigurationErrorNaming "SHOMEI_MAX_ACTIVE_NON_INTERACTIVE_SESSIONS" bad
   unsetEnv "SHOMEI_MAX_ACTIVE_NON_INTERACTIVE_SESSIONS"
+
+safeLoaderFailures :: Assertion
+safeLoaderFailures = do
+  setEnv "SHOMEI_CONFIG" configPath
+  mapM_
+    ( \contents -> do
+        writeFile configPath contents
+        result <- try @ConfigurationError loadCoreConfig
+        expectConfigurationErrorNaming "SHOMEI_CONFIG" result
+        case result of
+          Left err -> assertBool "loader error redacts rendered content" (not ("SENTINEL_SECRET" `isInfixOf` show err))
+          Right _ -> assertFailure "invalid configuration accepted"
+    )
+    ["{ unknown = \"SENTINEL_SECRET\" }", "{ argon2MemoryKiB = \"SENTINEL_SECRET\" }", "SENTINEL_SECRET invalid Dhall"]
+  setEnv "SHOMEI_CONFIG" "/missing/SENTINEL_SECRET"
+  missing <- try @ConfigurationError loadCoreConfig
+  expectConfigurationErrorNaming "SHOMEI_CONFIG" missing
+  assertBool "missing file path redacted" (not ("SENTINEL_SECRET" `isInfixOf` show missing))
+  unsetEnv "SHOMEI_CONFIG"
diff --git a/test/Shomei/Server/E2ESpec.hs b/test/Shomei/Server/E2ESpec.hs
--- a/test/Shomei/Server/E2ESpec.hs
+++ b/test/Shomei/Server/E2ESpec.hs
@@ -5,11 +5,11 @@
 -- detection (HTTP 401 plus the persisted session revocation and reuse event), logout, the
 -- public JWKS document, and health — i.e. the vertical slice actually behaves against real
 -- PostgreSQL and real ES256 signing.
-module Shomei.Server.E2ESpec (tests) where
+module Shomei.Server.E2ESpec (tests, seedPublicOAuthClient) where
 
-import Control.Concurrent (threadDelay)
+import Control.Concurrent (newEmptyMVar, putMVar, takeMVar, threadDelay)
 import Control.Concurrent.MVar (MVar, modifyMVar_, newMVar, readMVar)
-import Control.Monad (forM_)
+import Control.Monad (forM_, void)
 import Data.Aeson (Value (Array, Bool, Object, String), decode, encode, object, (.=))
 import Data.Aeson qualified as Aeson
 import Data.Aeson.Key qualified as K
@@ -56,23 +56,31 @@
 import Network.Wai.Handler.Warp (testWithApplication)
 import Servant.Health (ProbeCheck, ProbeVerdict (Healthy))
 import Shomei.Account.LoginId.Domain (mkLoginId)
+import Shomei.Account.Notification.Domain (Notification (..))
+import Shomei.Account.OneTimeToken.Domain (oneTimeTokenText)
 import Shomei.Account.Password.Hash.Postgres (Argon2Params (..), newHashingLimiter)
 import Shomei.Account.User.Domain (NewUser (..), User (..))
 import Shomei.Account.User.Postgres (runUserStorePostgres)
-import Shomei.Account.User.Store (createUser)
-import Shomei.Authorization.Claims.Domain (Audience (..), AuthClaims (..), Issuer (..), Scope (..))
-import Shomei.Config (NotifierConfig (..), NotifierTransport (..), OAuthConfig (..), ShomeiConfig (..), SigningKeyConfig (..), TotpConfig (..), WebhookConfig (..), defaultShomeiConfig)
+import Shomei.Account.User.Store (createUser, findUserById)
+import Shomei.Authorization.Claims.Domain (Audience (..), AuthClaims (..), Issuer (..), Role (..), Scope (..))
+import Shomei.Authorization.Role.Postgres (runRoleStorePostgres)
+import Shomei.Authorization.Role.Store (grantRole)
+import Shomei.Config (NotifierConfig (..), NotifierTransport (..), OAuthConfig (..), SessionCheckMode (..), ShomeiConfig (..), SigningKeyConfig (..), TotpConfig (..), WebhookConfig (..), defaultShomeiConfig)
 import Shomei.Error (AuthError)
-import Shomei.Id (SessionId, UserId, genOAuthClientId, genServiceAccountDbId, idText)
+import Shomei.Id (SessionId, UserId, genOAuthClientId, genServiceAccountDbId, idText, parseId)
 import Shomei.Mfa.Totp.Algorithm (base32ToSecret, totpCode, totpCounter)
 import Shomei.Mfa.Totp.Postgres (TotpEncryptionKey, totpEncryptionKeyFromBytes)
 import Shomei.Migrations.TestSupport (withShomeiMigratedDatabase)
 import Shomei.Notify (NotifierSecrets (..), WebhookSecret (..), noNotifierSecrets, webhookSignature)
 import Shomei.Notify.Queue (newNotifierQueue)
+import Shomei.Notify.Queue qualified as Queue
 import Shomei.OAuth.Client.Domain (ClientType (..), NewOAuthClient (..))
 import Shomei.OAuth.Client.Postgres (runOAuthClientStorePostgres)
 import Shomei.OAuth.Client.Store (createOAuthClient)
 import Shomei.OAuth.TokenGrant.Workflow (pkceChallengeFor)
+import Shomei.Passkey.Domain (NewPasskeyCredential (..), PublicKeyBytes (..), SignatureCounter (..), UserHandle (..), WebAuthnCredentialId (..))
+import Shomei.Passkey.Postgres (runPasskeyStorePostgres)
+import Shomei.Passkey.Store (createPasskey)
 import Shomei.Persistence.Database.Postgres (defaultTransactionRetryPolicy, runDatabasePool)
 import Shomei.Persistence.Pool.Postgres (Pool, acquirePool)
 import Shomei.Persistence.Pool.Postgres qualified as Pool
@@ -80,13 +88,14 @@
 import Shomei.Server.Boot (NotifierWorker (..), application, installNotifierWorker)
 import Shomei.Server.Config (defaultDbStatementTimeoutMs)
 import Shomei.Server.Keys (LoadedKeys (..), bootstrapKeys)
-import Shomei.ServiceAccount.Domain (NewServiceAccount (..))
+import Shomei.ServiceAccount.Domain (NewServiceAccount (..), ServiceAccount (..))
 import Shomei.ServiceAccount.Postgres (runServiceAccountStorePostgres)
 import Shomei.ServiceAccount.Secret (sha256Hex)
-import Shomei.ServiceAccount.Store (createServiceAccount)
+import Shomei.ServiceAccount.Store (createServiceAccount, findServiceAccountByClientId, revokeServiceAccount)
+import Shomei.Session.Authentication.Guard (userGuard)
 import Shomei.Session.Domain (NewSession (..), Session (..), SessionKind (InteractiveSession))
 import Shomei.Session.Postgres (runSessionStorePostgres)
-import Shomei.Session.Store (createSession)
+import Shomei.Session.Store (createSession, revokeAllUserSessions)
 import Shomei.Session.Token.Domain (AccessToken (..))
 import Shomei.SigningKey.Domain (SigningAlgorithm (ES256))
 import Shomei.SigningKey.Protection.Jwt (KeyEncryptionKey, keyEncryptionKeyFromBase64)
@@ -94,6 +103,7 @@
 import Shomei.SigningKey.Verify.Jwt (verifyToken)
 import Shomei.Time.Postgres (runClockIO)
 import Shomei.Time.Store (now)
+import System.Timeout (timeout)
 import Test.Tasty (TestTree, testGroup)
 import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))
 
@@ -106,7 +116,14 @@
 tests =
   testGroup
     "auth lifecycle over HTTP against PostgreSQL"
-    [ testCase "signup → login → me(±token) → refresh → reuse-detect → logout → jwks → health" $
+    [ testGroup
+        "audited lost-factor recovery"
+        [ recoveryE2E "passkey-only" True False True,
+          recoveryE2E "TOTP-only" False True True,
+          recoveryE2E "both factors" True True True,
+          recoveryE2E "no email (session-aware verification)" False True False
+        ],
+      testCase "signup → login → me(±token) → refresh → reuse-detect → logout → jwks → health" $
         withShomeiMigratedDatabase \connStr -> do
           pool <- acquirePool 4 10 defaultDbStatementTimeoutMs connStr
           keysRef <- newIORef =<< bootstrapKeys e2eKek ES256 pool
@@ -322,7 +339,13 @@
 -- | Insert a confidential OAuth client through the PostgreSQL interpreter, as
 -- @shomei-admin oauth-clients create@ does. Returns its @client_id@.
 seedOAuthClient :: Pool -> IO Text
-seedOAuthClient pool = do
+seedOAuthClient = seedOAuthClientFor ConfidentialClient
+
+seedPublicOAuthClient :: Pool -> IO Text
+seedPublicOAuthClient = seedOAuthClientFor PublicClient
+
+seedOAuthClientFor :: ClientType -> Pool -> IO Text
+seedOAuthClientFor kind pool = do
   outcome <-
     runEff
       . runErrorNoCallStack @AuthError
@@ -338,8 +361,8 @@
             NewOAuthClient
               { oauthClientId = ocid,
                 clientId = cid,
-                secretHash = Just (sha256Hex oidcClientSecret),
-                clientType = ConfidentialClient,
+                secretHash = if kind == ConfidentialClient then Just (sha256Hex oidcClientSecret) else Nothing,
+                clientType = kind,
                 displayName = "e2e rp",
                 redirectUris = [oidcRedirectUri],
                 allowedScopes = Set.fromList [Scope "openid", Scope "profile"],
@@ -410,6 +433,7 @@
   iStatus @?= 200
   iresp <- must "introspect body" iBody
   dig ["active"] iresp @?= Just (jsonBool True)
+  dig ["session_kind"] iresp @?= Just (String "interactive")
 
   -- revoke the refresh token → 200.
   (rStatus, _, _) <- postForm mgr port "/oauth/revoke" basic [("token", Text.encodeUtf8 refresh), ("token_type_hint", "refresh_token")]
@@ -419,7 +443,7 @@
   (i2Status, _, i2Body) <- postForm mgr port "/oauth/introspect" basic [("token", Text.encodeUtf8 access)]
   i2Status @?= 200
   i2resp <- must "introspect body 2" i2Body
-  dig ["active"] i2resp @?= Just (jsonBool False)
+  i2resp @?= object ["active" .= False]
 
 -- | The @Location@ query parameter named @k@, percent-decoded enough for our fixed values.
 paramFrom :: Text -> Text -> Maybe Text
@@ -510,6 +534,13 @@
   meStatus @?= 200
   meresp <- must "me body" meBody
   (dig ["displayName"] meresp >>= asText) @?= Just "e2e connector"
+  (iStatus, _, iBody) <- postForm mgr port "/oauth/introspect" (Just (clientId, oauthSecret)) [("token", Text.encodeUtf8 access)]
+  iStatus @?= 200
+  intro <- must "machine introspection body" iBody
+  dig ["session_kind"] intro @?= Just (String "machine")
+  backingUser <- must "service backing user" (dig ["userId"] meresp)
+  dig ["sub"] intro @?= Just backingUser
+  dig ["act"] intro @?= Nothing
 
   -- (c) Its signing key is the one published at the JWKS endpoint, so any downstream verifier
   -- that fetches /.well-known/jwks.json can check this token offline.
@@ -655,9 +686,11 @@
   iStatus @?= 200
   intro <- must "on-behalf introspect body" iBody
   dig ["active"] intro @?= Just (Bool True)
+  dig ["session_kind"] intro @?= Just (String "delegated")
+  dig ["sid"] intro @?= Just (String (idText verified.sessionId))
   (dig ["sub"] intro >>= asText) @?= Just subjectId
   (dig ["scope"] intro >>= asText) @?= Just "kawa:ingest"
-  assertBool "on-behalf token carries an act member" (isJust (dig ["act", "sub"] intro >>= asText))
+  (dig ["act", "sub"] intro >>= asText) @?= fmap idText verified.actor
 
   actorId <- must "introspected actor" (dig ["act", "sub"] intro >>= asText)
   payload <- must "delegated JWT payload" (jwtPayload obAccess)
@@ -678,6 +711,7 @@
   (impIStatus, _, impIBody) <- postForm mgr port "/oauth/introspect" (Just (clientId, exchangeSecret)) [("token", enc impAccess)]
   impIStatus @?= 200
   impIntro <- must "impersonation introspect body" impIBody
+  dig ["session_kind"] impIntro @?= Just (String "delegated")
   (dig ["sub"] impIntro >>= asText) @?= Just targetId
   assertBool "impersonation token carries an act member" (isJust (dig ["act", "sub"] impIntro >>= asText))
 
@@ -689,6 +723,30 @@
     scalarInt pool "SELECT count(*) FROM shomei.shomei_auth_events WHERE event_type = 'impersonation_started' AND payload->>'subjectUserId' IS NOT NULL AND payload->>'actorUserId' IS NOT NULL"
   impStarted @?= 1
 
+  -- ===== Revoking a principal ends the non-interactive sessions it holds or acts in =====
+  let svcUser = "(SELECT user_id FROM shomei.shomei_service_accounts WHERE client_id = '" <> clientId <> "')"
+      activeWhere cond = scalarInt pool ("SELECT count(*) FROM shomei.shomei_sessions s WHERE s.status = 'active' AND " <> cond)
+      serviceSessions = activeWhere ("(s.user_id = " <> svcUser <> " OR s.actor_user_id = " <> svcUser <> ")")
+      operatorSessions = activeWhere ("s.actor_user_id IS NOT NULL AND s.actor_user_id <> " <> svcUser)
+      store action =
+        either (assertFailure . ("store action failed: " <>) . show) pure
+          =<< runEff (runErrorNoCallStack @AuthError (runDatabasePool pool (runClockIO action)))
+  assertBool "the service acts in a live delegated session" . (> 0) =<< serviceSessions
+  impersonations <- operatorSessions
+  assertBool "the operator acts in a live impersonation session" (impersonations > 0)
+  store . runServiceAccountStorePostgres $ do
+    ServiceAccount {serviceAccountId} <- maybe (error "exchange service account missing") pure =<< findServiceAccountByClientId clientId
+    ts <- now
+    revokeServiceAccount serviceAccountId ts
+  serviceSessions >>= (@?= 0)
+  -- Another principal's delegation is untouched.
+  operatorSessions >>= (@?= impersonations)
+  operatorId <- either (assertFailure . show) pure . parseId =<< must "impersonation actor" (dig ["act", "sub"] impIntro >>= asText)
+  store . runSessionStorePostgres $ do
+    ts <- now
+    void (revokeAllUserSessions (operatorId :: UserId) ts)
+  operatorSessions >>= (@?= 0)
+
 -- | The @kid@ from a JWT's header, without verifying anything.
 jwtHeaderKid :: Text -> Maybe Text
 jwtHeaderKid token = do
@@ -995,3 +1053,147 @@
 -- here; only that hashing round-trips.
 testArgon2Params :: Argon2Params
 testArgon2Params = Argon2Params {memoryKiB = 8192, iterations = 1, parallelism = 1}
+
+recoveryE2E :: String -> Bool -> Bool -> Bool -> TestTree
+recoveryE2E name hasPasskey hasTotp hasEmail = testCase name $
+  withShomeiMigratedDatabase \connStr -> do
+    pool <- acquirePool 4 10 defaultDbStatementTimeoutMs connStr
+    keysRef <- newIORef =<< bootstrapKeys e2eKek ES256 pool
+    envMgr <- newManager defaultManagerSettings
+    limiter <- newHashingLimiter 2
+    queue <- newNotifierQueue 64
+    let base = defaultShomeiConfig (Issuer "shomei") (Audience "shomei-clients")
+        cfg = base {totpConfig = base.totpConfig {totpEnabled = True}, sessionCheckMode = if hasEmail then VerifyTokenOnly else VerifyTokenAndSession}
+        env = Env {envPool = pool, envDbRetryPolicy = defaultTransactionRetryPolicy, envConfig = cfg, envKeys = keysRef, envKek = e2eKek, envHttpManager = envMgr, envNotifierSecrets = noNotifierSecrets, envNotifierQueue = queue, envArgon2Params = testArgon2Params, envHashingLimiter = limiter, envTotpKey = e2eTotpKey}
+    testWithApplication (pure (application env healthyProbe healthyProbe)) (recoveryScenario pool queue hasPasskey hasTotp hasEmail)
+
+queuedNotice :: Queue.NotifierQueue -> IO Notification
+queuedNotice queue = do
+  result <- newEmptyMVar
+  completed <- timeout 5000000 (Queue.withDequeued queue (putMVar result))
+  case completed of
+    Just () -> takeMVar result
+    Nothing -> assertFailure "committed lifecycle notification was not queued"
+
+recoveryScenario :: Pool -> Queue.NotifierQueue -> Bool -> Bool -> Bool -> Int -> IO ()
+recoveryScenario pool queue hasPasskey hasTotp hasEmail port = do
+  mgr <- newManager defaultManagerSettings
+  let password = "correct horse battery staple recovery" :: Text
+      replacementPassword = "correct horse battery staple recovered" :: Text
+      signupBody lid email = object (["loginId" .= (lid :: Text), "password" .= password, "displayName" .= ("" :: Text)] <> ["email" .= (lid <> "@example.com") | email])
+      loginBody pw = object ["loginId" .= ("lost-factor-user" :: Text), "password" .= pw]
+  (adminStatus, adminBody) <- postJSON mgr port "/v1/auth/signup" (signupBody "recovery-operator" False)
+  adminStatus @?= 201
+  adminIdText <- must "operator user" (adminBody >>= dig ["user", "userId"] >>= asText)
+  adminId <- either (assertFailure . show) pure (parseId adminIdText)
+  ts <- getCurrentTime
+  _ <- runEff . runErrorNoCallStack @AuthError . runDatabasePool pool . runRoleStorePostgres $ grantRole adminId (Role "admin") Nothing Nothing ts
+  (_, adminLogin) <- postJSON mgr port "/v1/auth/login" (object ["loginId" .= ("recovery-operator" :: Text), "password" .= password])
+  adminAccess <- must "admin access" (adminLogin >>= dig ["token", "accessToken"] >>= asText)
+  (created, body) <- postJSON mgr port "/v1/auth/signup" (signupBody "lost-factor-user" hasEmail)
+  created @?= 201
+  uidText <- must "target user" (body >>= dig ["user", "userId"] >>= asText)
+  uid <- either (assertFailure . show) pure (parseId uidText)
+  oldAccess <- must "initial access" (body >>= dig ["token", "accessToken"] >>= asText)
+  oldRefresh <- must "initial refresh" (body >>= dig ["token", "refreshToken"] >>= asText)
+  if hasEmail
+    then do
+      (requested, _) <- postJSON mgr port "/v1/auth/verify-email/request" (object ["email" .= ("lost-factor-user@example.com" :: Text)])
+      requested @?= 202
+      verification <- queuedNotice queue
+      raw <- case verification of
+        EmailVerificationRequested {token} -> pure (oneTimeTokenText token)
+        _ -> assertFailure "expected verification notice"
+      (verified, _) <- postJSON mgr port "/v1/auth/verify-email/confirm" (object ["token" .= raw])
+      verified @?= 200
+    else pure ()
+  if hasPasskey
+    then do
+      -- Lost authenticators cannot answer a fresh WebAuthn proof. Seed their previously enrolled
+      -- public credential through the real store; all recovery and replacement actions use HTTP.
+      seeded <- runEff . runErrorNoCallStack @AuthError . runDatabasePool pool . runClockIO . runPasskeyStorePostgres . runUserStorePostgres $ do
+        user <- maybe (error "missing recovery user") pure =<< findUserById uid
+        createPasskey (userGuard user) 20 (NewPasskeyCredential uid (WebAuthnCredentialId "lost-passkey") (UserHandle "lost-handle") (PublicKeyBytes "lost-public-key") (SignatureCounter 0) [] Nothing ts)
+      case seeded of
+        Right (Right _) -> pure ()
+        other -> assertFailure ("cannot seed enrolled lost passkey: " <> show other)
+    else pure ()
+  if hasTotp
+    then do
+      (enrolled, enrollment) <- postAuthNoBody mgr port "/v1/auth/totp/enroll" (bearer oldAccess)
+      enrolled @?= 200
+      base32 <- must "TOTP secret" (enrollment >>= dig ["secret"] >>= asText)
+      secret <- either (assertFailure . show) pure (base32ToSecret base32)
+      current <- getCurrentTime
+      (confirmed, _) <- postJSONAuth mgr port "/v1/auth/totp/verify" (bearer oldAccess) (object ["code" .= totpCode 6 secret (totpCounter current)])
+      confirmed @?= 200
+    else pure ()
+  (generated, codesBody) <- postAuthNoBody mgr port "/v1/auth/recovery-codes" (bearer oldAccess)
+  generated @?= 200
+  codes <- must "old codes" (codesBody >>= dig ["codes"] >>= asTextArray)
+  -- Password reset preserves all enrolled factors, including passkey-only accounts.
+  effectivePassword <-
+    if hasEmail
+      then do
+        (requested, _) <- postJSON mgr port "/v1/auth/password-reset/request" (object ["email" .= ("lost-factor-user@example.com" :: Text)])
+        requested @?= 202
+        notice <- queuedNotice queue
+        raw <- case notice of
+          PasswordResetRequested {token} -> pure (oneTimeTokenText token)
+          _ -> assertFailure "expected password-reset notice"
+        (changed, _) <- postJSON mgr port "/v1/auth/password-reset/confirm" (object ["token" .= raw, "newPassword" .= replacementPassword])
+        changed @?= 200
+        pure replacementPassword
+      else pure password
+  (challenged, challenge) <- postJSON mgr port "/v1/auth/login" (loginBody effectivePassword)
+  challenged @?= 200
+  (challenge >>= dig ["status"] >>= asText) @?= Just "mfa_required"
+  oldChallenge <- must "old MFA challenge" (challenge >>= dig ["ceremonyId"] >>= asText)
+  let path = "/v1/admin/users/" <> Text.unpack uidText <> "/mfa/reset"
+  (reset, result) <- postJSONAuth mgr port path (bearer adminAccess) (object ["identityVerified" .= True, "caseReference" .= ("INC-e2e" :: Text)])
+  reset @?= 200
+  (result >>= dig ["verifiedNotificationDestination"]) @?= Just (Bool hasEmail)
+  (result >>= dig ["counts", "passkeysRemoved"]) @?= Just (Aeson.toJSON (if hasPasskey then 1 :: Int else 0))
+  assertBool "no tokens issued by recovery" (not (isJust (result >>= dig ["token"])))
+  if hasEmail
+    then do
+      notice <- queuedNotice queue
+      case notice of
+        SecondFactorsReset {} -> pure ()
+        _ -> assertFailure "expected secret-free recovery notice"
+    else pure ()
+  (oldMfa, _) <- postJSON mgr port "/v1/auth/mfa/complete" (object ["ceremonyId" .= oldChallenge, "proof" .= object ["type" .= ("recovery_code" :: Text), "code" .= head codes]])
+  oldMfa @?= 404
+  (refreshRejected, _) <- postJSON mgr port "/v1/auth/refresh" (object ["refreshToken" .= oldRefresh])
+  refreshRejected @?= 401
+  (staleEnrollment, _) <- postAuthNoBody mgr port "/v1/auth/totp/enroll" (bearer oldAccess)
+  staleEnrollment @?= 401
+  (oldMe, _) <- getJSON mgr port "/v1/auth/me" (bearer oldAccess)
+  oldMe @?= (if hasEmail then 200 else 401)
+  if hasPasskey
+    then do
+      (begun, options) <- postAuthNoBody mgr port "/v1/auth/login/passkey/begin" []
+      begun @?= 200
+      cid <- must "new passwordless challenge" (options >>= dig ["ceremonyId"] >>= asText)
+      (oldPasskey, _) <- postJSON mgr port "/v1/auth/login/passkey/complete" (object ["ceremonyId" .= cid, "assertion" .= object ["credentialId" .= WebAuthnCredentialId "lost-passkey"]])
+      oldPasskey @?= 401
+    else pure ()
+  scalarInt pool "SELECT count(*) FROM shomei.shomei_totp_credentials" >>= (@?= 0)
+  scalarInt pool "SELECT count(*) FROM shomei.shomei_webauthn_credentials" >>= (@?= 0)
+  scalarInt pool "SELECT count(*) FROM shomei.shomei_recovery_codes" >>= (@?= 0)
+  (_, passwordLogin) <- postJSON mgr port "/v1/auth/login" (loginBody effectivePassword)
+  (passwordLogin >>= dig ["status"] >>= asText) @?= Just "complete"
+  access <- must "recovered password access" (passwordLogin >>= dig ["token", "accessToken"] >>= asText)
+  (_, enrollment) <- postAuthNoBody mgr port "/v1/auth/totp/enroll" (bearer access)
+  base32 <- must "replacement TOTP secret" (enrollment >>= dig ["secret"] >>= asText)
+  secret <- either (assertFailure . show) pure (base32ToSecret base32)
+  current <- getCurrentTime
+  (confirmed, _) <- postJSONAuth mgr port "/v1/auth/totp/verify" (bearer access) (object ["code" .= totpCode 6 secret (totpCounter current)])
+  confirmed @?= 200
+  (newCodes, _) <- postAuthNoBody mgr port "/v1/auth/recovery-codes" (bearer access)
+  newCodes @?= 200
+  (_, challengedAgain) <- postJSON mgr port "/v1/auth/login" (loginBody effectivePassword)
+  (challengedAgain >>= dig ["status"] >>= asText) @?= Just "mfa_required"
+  newChallenge <- must "new MFA challenge" (challengedAgain >>= dig ["ceremonyId"] >>= asText)
+  (oldCodeRejected, _) <- postJSON mgr port "/v1/auth/mfa/complete" (object ["ceremonyId" .= newChallenge, "proof" .= object ["type" .= ("recovery_code" :: Text), "code" .= head codes]])
+  oldCodeRejected @?= 401
diff --git a/test/Shomei/Server/MiddlewareSpec.hs b/test/Shomei/Server/MiddlewareSpec.hs
--- a/test/Shomei/Server/MiddlewareSpec.hs
+++ b/test/Shomei/Server/MiddlewareSpec.hs
@@ -22,7 +22,7 @@
 import Data.Set qualified as Set
 import Data.Text (Text)
 import Data.Word (Word16, Word64, Word8)
-import Network.HTTP.Types (hContentType, methodDelete, methodPost, statusCode)
+import Network.HTTP.Types (hContentType, methodDelete, methodPost, mkStatus, statusCode)
 import Network.HTTP.Types.Status (status200)
 import Network.Socket (SockAddr (..), tupleToHostAddress, tupleToHostAddress6)
 import Network.Wai (Request (..), RequestBodyLength (..), Response, defaultRequest, getRequestBodyChunk, responseHeaders, responseLBS, responseStatus, responseToStream, setRequestBodyChunks)
@@ -32,18 +32,21 @@
 import Shomei.Account.Password.Hash.Postgres (defaultArgon2Params)
 import Shomei.Authorization.Claims.Domain (Audience (..), Issuer (..))
 import Shomei.Config (LogFormat (..), RateLimitConfig (..), ShomeiConfig (..), defaultObservabilityConfig, defaultRateLimitConfig, defaultShomeiConfig)
+import Shomei.OAuth.Boundary (oauthMounts)
 import Shomei.Servant.Api (shomeiThrottledRoutes)
 import Shomei.Servant.ClientIp (clientIpText)
 import Shomei.Servant.Error (ProblemDetails (..))
+import Shomei.Servant.Middleware (problemMiddlewareWithOAuthMounts)
+import Shomei.Servant.OAuth (OAuthErrorResponse (..))
 import Shomei.Servant.Throttle (PathSegment (Literal), ThrottledRoute (..))
 import Shomei.Server.Boot (hostMiddleware)
 import Shomei.Server.Config (ProxyProtocolMode (..), ServerSettings (..), SweepSettings (..), defaultSweepSettings)
 import Shomei.Server.ExceptionResponse (problemExceptionResponse)
-import Shomei.Server.Middleware.BodyLimit (bodyLimitMiddleware)
-import Shomei.Server.Middleware.RateLimit (bucketCount, newRateLimiterFor, newRateLimiterWith, takeToken, throttledPath)
+import Shomei.Server.Middleware.BodyLimit (bodyLimitMiddleware, bodyLimitMiddlewareWithOAuthMounts)
+import Shomei.Server.Middleware.RateLimit (bucketCount, newRateLimiterFor, newRateLimiterWith, rateLimitMiddlewareWithOAuthMounts, takeToken, throttledPath)
 import Shomei.Server.Middleware.TrustedProxy (emptyTrustedProxies, parseTrustedProxies, trustedProxyMiddleware)
 import Shomei.Server.Observability.Logging (emitLine, renderLogLine, requestLoggingMiddleware, responseLogLevel, serverErrorLine)
-import Shomei.Server.Observability.Metrics (exportMetrics, metricsMiddleware, newMetrics)
+import Shomei.Server.Observability.Metrics (exportMetrics, metricsEndpointMiddleware, metricsMiddleware, newMetrics)
 import System.Directory (getTemporaryDirectory, removeFile)
 import System.IO (BufferMode (LineBuffering), hClose, hSetBuffering, openTempFile)
 import Test.Tasty (TestTree, testGroup)
@@ -75,7 +78,8 @@
         ],
       testGroup
         "metrics"
-        [ testThrowingHandlerLeavesGaugeAtZero,
+        [ testMetricsExposition,
+          testThrowingHandlerLeavesGaugeAtZero,
           testNormalRequestCountedAndGaugeReturnsToZero,
           testHostileMethodsShareTheBoundedSeries
         ],
@@ -91,7 +95,11 @@
         ],
       testGroup
         "body limit"
-        [ testHostMiddlewareOrder,
+        [ testOAuthResourceBoundary,
+          testNoDoubleBodyResponse,
+          testOAuthResponseHeaders,
+          testOAuthRawNotFound,
+          testHostMiddlewareOrder,
           testOversizedBodyRejected,
           testKnownSmallBodyPassesThrough,
           testChunkedBodyOverCapRejected,
@@ -544,3 +552,138 @@
 
 okResponse :: Response
 okResponse = responseLBS status200 [] "ok"
+
+-- The actual endpoint must keep metadata, labels, and cumulative samples coherent.
+testMetricsExposition :: TestTree
+testMetricsExposition = testCase "metrics endpoint exposes decimal buckets and family metadata" do
+  m <- newMetrics
+  let inner _ respond = respond (responseLBS status200 [] "ok")
+      families = ["http_requests_total", "http_requests_in_flight", "http_request_duration_seconds", "shomei_logins_succeeded_total", "shomei_logins_failed_total", "shomei_tokens_issued_total"]
+      bounds = ["0.005", "0.01", "0.025", "0.05", "0.1", "0.25", "0.5", "1", "2.5", "5", "10", "+Inf"]
+      check expected = do
+        ResponseReceived <- metricsEndpointMiddleware m inner defaultRequest {rawPathInfo = "/metrics"} \response -> do
+          responseStatus response @?= status200
+          lookup hContentType (responseHeaders response) @?= Just "text/plain; version=0.0.4"
+          let (_, _, stream) = responseToStream response
+          chunks <- newIORef mempty
+          stream (\body -> body (\chunk -> modifyIORef' chunks (<> toLazyByteString chunk)) (pure ()))
+          rows <- BLC.lines <$> readIORef chunks
+          forM_ families \family -> do
+            let help = filter (BLC.isPrefixOf ("# HELP " <> family <> " ")) rows
+                ty = filter (BLC.isPrefixOf ("# TYPE " <> family <> " ")) rows
+            length help @?= 1
+            length ty @?= 1
+            let beforeSamples = takeWhile (\row -> not (BLC.isPrefixOf family row)) rows
+            assertBool "metadata precedes samples" (head help `elem` beforeSamples && head ty `elem` beforeSamples)
+          let buckets = filter (BLC.isPrefixOf "http_request_duration_seconds_bucket{") rows
+              values = map (read . BLC.unpack . last . BLC.words) buckets :: [Int]
+          length buckets @?= length bounds
+          forM_ (zip bounds buckets) \(bound, row) -> assertBool "ordered decimal boundary" (BL.toStrict ("le=\"" <> bound <> "\"") `BS.isInfixOf` BL.toStrict row)
+          values @?= sort values
+          last values @?= expected
+          assertBool "count equals infinity" (("http_request_duration_seconds_count " <> BLC.pack (show expected)) `elem` rows)
+          pure ResponseReceived
+        pure ()
+  check 0
+  ResponseReceived <- metricsMiddleware m inner defaultRequest (\_ -> pure ResponseReceived)
+  check 1
+
+testOAuthResourceBoundary :: TestTree
+testOAuthResourceBoundary = testCase "OAuth body and rate rejections preserve resource accounting and namespace policy" do
+  mounts <- either (fail . show) pure (oauthMounts [["oauth"], ["identity", "oauth"]])
+  forM_ [["oauth", "token"], ["identity", "oauth", "token"], ["oauthish", "token"], ["reports", "oauth", "token"], ["v1", "auth", "login"]] \segments -> do
+    let oauth = segments `elem` [["oauth", "token"], ["identity", "oauth", "token"]]
+    forM_ [(KnownLength 9, ["ignored"], 0, 413), (KnownLength 8, ["12345678", ""], 2, 200), (ChunkedBody, ["1234", "5678", "9", "unread"], 3, 413), (ChunkedBody, ["1234", "5678", ""], 3, 200)] \(len, chunks, expectedReads, expectedStatus) -> do
+      chunksRef <- newIORef chunks
+      chunkReads <- newIORef (0 :: Int)
+      calls <- newIORef (0 :: Int)
+      let next = do
+            modifyIORef' chunkReads (+ 1)
+            atomicModifyIORef' chunksRef \case
+              [] -> ([], "")
+              chunk : rest -> (rest, chunk)
+          req = setRequestBodyChunks next defaultRequest {pathInfo = segments, requestBodyLength = len}
+          drain request = do
+            chunk <- getRequestBodyChunk request
+            unless (BS.null chunk) (drain request)
+          inner request respond = drain request >> modifyIORef' calls (+ 1) >> respond okResponse
+      ResponseReceived <- bodyLimitMiddlewareWithOAuthMounts mounts 8 inner req \res -> do
+        statusCode (responseStatus res) @?= expectedStatus
+        whenRejected oauth 413 res
+        pure ResponseReceived
+      readIORef chunkReads >>= (@?= expectedReads)
+      readIORef calls >>= (@?= if expectedStatus == 200 then 1 else 0)
+    calls <- newIORef (0 :: Int)
+    limiter <- newRateLimiterFor [ThrottledRoute methodPost (map Literal segments)] testLimiterConfig {perIpBurst = 0}
+    let req = defaultRequest {pathInfo = segments, requestMethod = methodPost}
+        inner _ respond = modifyIORef' calls (+ 1) >> respond okResponse
+    ResponseReceived <- rateLimitMiddlewareWithOAuthMounts mounts limiter inner req \res -> do
+      statusCode (responseStatus res) @?= 429
+      lookup "Retry-After" (responseHeaders res) @?= Just "60"
+      whenRejected oauth 429 res
+      pure ResponseReceived
+    readIORef calls >>= (@?= 0)
+  where
+    whenRejected :: Bool -> Int -> Response -> IO ()
+    whenRejected oauth code res
+      | statusCode (responseStatus res) == 200 = pure ()
+      | oauth = do
+          lookup "Content-Type" (responseHeaders res) @?= Just "application/json"
+          lookup "Cache-Control" (responseHeaders res) @?= Just "no-store"
+          lookup "Pragma" (responseHeaders res) @?= Just "no-cache"
+          lookup "WWW-Authenticate" (responseHeaders res) @?= Nothing
+          body <- collectResponseBody res
+          fmap oauthErrorCode (decode body :: Maybe OAuthErrorResponse) @?= Just (if code == 429 then "temporarily_unavailable" else "invalid_request")
+      | otherwise = lookup "Content-Type" (responseHeaders res) @?= Just "application/problem+json"
+
+testNoDoubleBodyResponse :: TestTree
+testNoDoubleBodyResponse = testCase "body overflow after a response never calls respond twice" do
+  calls <- newIORef (0 :: Int)
+  let req = setRequestBodyChunks (pure "oversized") defaultRequest {requestBodyLength = ChunkedBody, pathInfo = ["oauth", "token"]}
+      inner request respond = do
+        result <- respond okResponse
+        _ <- getRequestBodyChunk request
+        pure result
+  result <- try (bodyLimitMiddleware 1 inner req (\_ -> modifyIORef' calls (+ 1) >> pure ResponseReceived)) :: IO (Either SomeException ResponseReceived)
+  case result of
+    Left _ -> pure ()
+    Right _ -> fail "body cap exception must propagate after response"
+  readIORef calls >>= (@?= 1)
+
+testOAuthResponseHeaders :: TestTree
+testOAuthResponseHeaders = testCase "OAuth normalization preserves semantic headers and existing JSON without stale representation headers" do
+  mounts <- either (fail . show) pure (oauthMounts [["oauth"]])
+  forM_ [False, True] \alreadyProtocol -> do
+    let headers = [("Content-Type", if alreadyProtocol then "application/json" else "text/plain"), ("Allow", "POST"), ("Content-Length", "3"), ("ETag", "stale")]
+        response = responseLBS (mkStatus 405 "Method Not Allowed") headers "old"
+        app _ respond = respond response
+    ResponseReceived <- problemMiddlewareWithOAuthMounts mounts app defaultRequest {pathInfo = ["oauth", "token"]} \res -> do
+      lookup "Allow" (responseHeaders res) @?= Just "POST"
+      lookup "Content-Type" (responseHeaders res) @?= Just "application/json"
+      body <- collectResponseBody res
+      if alreadyProtocol
+        then body @?= "old"
+        else do
+          lookup "Content-Length" (responseHeaders res) @?= Nothing
+          lookup "ETag" (responseHeaders res) @?= Nothing
+          fmap oauthErrorCode (decode body :: Maybe OAuthErrorResponse) @?= Just "invalid_request"
+      pure ResponseReceived
+    pure ()
+  case oauthMounts [[]] of
+    Left _ -> pure ()
+    Right _ -> fail "root OAuth mount accepted"
+  case oauthMounts [["identity", ""]] of
+    Left _ -> pure ()
+    Right _ -> fail "empty OAuth segment accepted"
+
+testOAuthRawNotFound :: TestTree
+testOAuthRawNotFound = testCase "a host Raw fallback cannot replace an OAuth namespace 404 with plain text" do
+  mounts <- either (fail . show) pure (oauthMounts [["identity", "oauth"]])
+  let fallback _ respond = respond (responseLBS (mkStatus 404 "Not Found") [("Content-Type", "text/plain")] "host static file not found")
+  ResponseReceived <- problemMiddlewareWithOAuthMounts mounts fallback defaultRequest {pathInfo = ["identity", "oauth", "unknown"]} \res -> do
+    statusCode (responseStatus res) @?= 404
+    lookup "Content-Type" (responseHeaders res) @?= Just "application/json"
+    body <- collectResponseBody res
+    fmap oauthErrorCode (decode body :: Maybe OAuthErrorResponse) @?= Just "invalid_request"
+    pure ResponseReceived
+  pure ()
diff --git a/test/Shomei/Server/NotifySpec.hs b/test/Shomei/Server/NotifySpec.hs
--- a/test/Shomei/Server/NotifySpec.hs
+++ b/test/Shomei/Server/NotifySpec.hs
@@ -62,7 +62,15 @@
 tests =
   testGroup
     "Notify"
-    [ testCase "HIBP cancellation propagates instead of becoming an unavailable lookup" do
+    [ recoveryNoticeTransports,
+      testCase "second-factor reset rendering is secret-free and has no fictitious token or expiry" do
+        address <- testEmail
+        let notification = SecondFactorsReset address expires "Contact your established support channel if unexpected."
+            output = render False notification
+        assertBool "reset notice kind" ("second_factors_reset" `isInfixOf` output)
+        assertBool "no fabricated one-time credential" (not ("token" `isInfixOf` output))
+        assertBool "no fabricated expiry" (not ("expires" `isInfixOf` output)),
+      testCase "HIBP cancellation propagates instead of becoming an unavailable lookup" do
         reports <- newIORef []
         let query _ = throwIO ThreadKilled
             report line = modifyIORef' reports (line :)
@@ -485,3 +493,54 @@
         ("the request URL must not appear in the audit reason: " <> Text.unpack d.errorText)
         (not ("hunter2" `Text.isInfixOf` d.errorText))
     _ -> assertFailure ("expected exactly one delivery-failure event, got: " <> show events)
+
+recoveryNoticeTransports :: TestTree
+recoveryNoticeTransports =
+  testGroup
+    "secret-free recovery notice"
+    [ testCase "SMTP renders support instructions without token or expiry" do
+        email <- testEmail
+        let notice = SecondFactorsReset email fixtureExpiry "Contact established support if unexpected."
+        bracket openSink (close . sinkSocket) \sink -> bracket (forkIO (acceptLoop sink)) killThread \_ -> do
+          events <- deliverViaSmtp (plainSmtpConfig (sinkPort sink)) notice
+          events @?= []
+          transcript <- readMVar sink.sinkTranscript
+          assertBool "reset subject rendered" (any ("Your second factors were reset" `isInfixOf`) transcript)
+          assertBool "no one-time credential or expiry" (all (\line -> not ("?token=" `isInfixOf` line || "This link expires" `isInfixOf` line)) transcript),
+      testCase "configured delivery failure is redacted and does not throw" do
+        email <- testEmail
+        port <- closedPort
+        events <- deliverViaSmtp (plainSmtpConfig port) (SecondFactorsReset email fixtureExpiry "Contact support.")
+        case events of
+          [NotificationDeliveryFailed d] -> d.notificationType @?= "second_factors_reset"
+          _ -> assertFailure "expected one bounded delivery failure",
+      testCase "webhook carries a signed secret-free recovery payload" do
+        email <- testEmail
+        mgr <- newManager defaultManagerSettings
+        captured <- newMVar []
+        counter <- newIORef 0
+        let notice = SecondFactorsReset email fixtureExpiry "Contact support."
+        testWithApplication (pure (webhookStub counter (const 200) captured)) \port -> do
+          events <- deliverViaWebhook mgr (webhookConfigFor port 1) notice
+          events @?= []
+          requests <- readMVar captured
+          case requests of
+            [(headers, bytes)] -> do
+              decode (LBS.fromStrict bytes) @?= Just notice
+              lookup "X-Shomei-Notification-Type" headers @?= Just "second_factors_reset"
+              assertBool "no token in payload" (not ("token" `BS.isInfixOf` bytes))
+            _ -> assertFailure "expected one webhook notice",
+      testCase "queue overflow audits the recovery notice without blocking" do
+        email <- testEmail
+        queue <- Queue.newNotifierQueue 1
+        let notice = SecondFactorsReset email fixtureExpiry "Contact support."
+        Queue.enqueueNotification queue notice >>= (@?= Queue.Enqueued)
+        events <- newIORef []
+        runEff . runClockIO . runAuthEventCapture events . runNotifierEnqueue queue "smtp" $ sendNotification notice
+        captured <- readIORef events
+        case captured of
+          [NotificationDeliveryFailed d] -> do
+            d.notificationType @?= "second_factors_reset"
+            d.errorText @?= "queue_full"
+          _ -> assertFailure "expected queue overflow event"
+    ]
diff --git a/test/Shomei/Server/OAuthContractSpec.hs b/test/Shomei/Server/OAuthContractSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Shomei/Server/OAuthContractSpec.hs
@@ -0,0 +1,141 @@
+-- | Exercise the actual executable, configuration loader and outer WAI assembly.
+module Shomei.Server.OAuthContractSpec (tests) where
+
+import Control.Concurrent (threadDelay)
+import Control.Exception (bracket, try)
+import Control.Monad (forM_, unless, void)
+import Data.Aeson (encode)
+import Data.ByteString.Lazy qualified as LBS
+import Data.List (isPrefixOf)
+import Data.Text qualified as Text
+import Data.Text.Encoding qualified as Text
+import Network.HTTP.Client qualified as HTTP
+import Network.HTTP.Types (statusCode)
+import Network.Socket (close)
+import Network.Wai.Handler.Warp (openFreePort)
+import Shomei.Migrations.TestSupport (withShomeiMigratedDatabase)
+import Shomei.OAuth.TokenGrant.Workflow (pkceChallengeFor)
+import Shomei.Persistence.Pool.Postgres qualified as Pool
+import Shomei.Server.Config (defaultDbStatementTimeoutMs)
+import Shomei.Server.E2ESpec (seedPublicOAuthClient)
+import System.Directory (canonicalizePath, createDirectory, doesFileExist, findExecutable, getTemporaryDirectory, makeAbsolute, removeDirectoryRecursive, removeFile)
+import System.Environment (getEnvironment, lookupEnv)
+import System.Exit (ExitCode (ExitSuccess))
+import System.FilePath ((</>))
+import System.IO (IOMode (WriteMode), hClose, openTempFile, withFile)
+import System.Posix.Files (setFileMode)
+import System.Posix.Signals (sigKILL, signalProcess)
+import System.Process (CreateProcess (..), ProcessHandle, StdStream (UseHandle), createProcess, getPid, getProcessExitCode, proc, readProcessWithExitCode, terminateProcess, waitForProcess)
+import System.Timeout (timeout)
+import Test.Tasty (TestTree, testGroup)
+import Test.Tasty.HUnit (assertFailure, testCase)
+
+tests :: TestTree
+tests = testGroup "packaged OAuth contract" [testCase "Hurl validates executable errors and throttling" packagedContract]
+
+packagedContract :: IO ()
+packagedContract = do
+  fixtures <- makeAbsolute "test/fixtures"
+  hurl <- findExecutable "hurl" >>= maybe (fail "Hurl is required; run in nix develop") pure
+  supplied <- lookupEnv "SHOMEI_TEST_SERVER_BIN"
+  binary <- case supplied of
+    Just path -> canonicalizePath path
+    Nothing -> findExecutable "shomei-server" >>= maybe (fail "Cabal must provide the shomei-server executable") canonicalizePath
+  exists <- doesFileExist binary
+  unless exists (fail "Build exe:shomei-server before running the packaged OAuth test")
+  bracket makeTemporaryDirectory removeDirectoryRecursive \tmp ->
+    withShomeiMigratedDatabase \connStr -> do
+      clientId <- bracket (Pool.acquirePool 2 10 defaultDbStatementTimeoutMs connStr) Pool.release seedPublicOAuthClient
+      -- Generated locally, never checked into the repository.
+      LBS.writeFile (tmp </> "oversized.form") ("grant_type=client_credentials&padding=" <> LBS.replicate (1024 * 1024 + 1) 120)
+      forM_ [("errors.hurl", 100), ("throttling.hurl", 1)] \(suite, burst) -> do
+        (port, socket) <- openFreePort
+        close socket
+        let config = tmp </> "server.dhall"
+            base = "http://127.0.0.1:" <> show port
+            text value = Text.unpack (Text.decodeUtf8 (LBS.toStrict (encode value)))
+        -- Use the production typed Dhall loader. Environment overrides are isolated below.
+        writeFile config $
+          "let Config = "
+            <> (fixtures </> "shomei-types.dhall")
+            <> " in Config::{ "
+            <> "databaseUrl = Some "
+            <> text connStr
+            <> ", issuer = Some "
+            <> text base
+            <> ", audience = Some \"oauth-contract\", port = Some "
+            <> show port
+            <> ", bindHost = Some \"127.0.0.1\", oidcEnabled = Some True"
+            <> ", rateLimitEnabled = Some True, perIpBurst = Some "
+            <> show (burst :: Int)
+            <> ", perIpRequestsPerMinute = Some 1, sweepEnabled = Some False"
+            <> ", requestLoggingEnabled = Some False, metricsEnabled = Some False"
+            <> ", gracefulShutdownTimeoutSeconds = Some 1 }\n"
+        inherited <- getEnvironment
+        let childEnv =
+              [(k, v) | (k, v) <- inherited, not ("SHOMEI_" `isPrefixOf` k), k `notElem` ["GHCRTS", "PG_CONNECTION_STRING", "DATABASE_URL"]]
+                <> [("SHOMEI_CONFIG", config), ("SHOMEI_KEY_ENCRYPTION_KEY", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")]
+        withFile (tmp </> "server.log") WriteMode \logHandle ->
+          bracket
+            (createProcess (proc binary ["+RTS", "-N2", "-RTS"]) {env = Just childEnv, std_out = UseHandle logHandle, std_err = UseHandle logHandle})
+            (\(_, _, _, process) -> stopChild process)
+            \(_, _, _, process) -> do
+              manager <- HTTP.newManager HTTP.defaultManagerSettings
+              ready <- timeout 30_000_000 (awaitReady manager process base)
+              unless (ready == Just ()) (assertFailure "packaged server readiness timed out")
+              outcome <-
+                timeout 30_000_000 $
+                  readProcessWithExitCode
+                    hurl
+                    [ "--test",
+                      "--max-time",
+                      "5",
+                      "--file-root",
+                      tmp,
+                      "--variable",
+                      "base_url=" <> base,
+                      "--variable",
+                      "client_id=" <> Text.unpack clientId,
+                      "--variable",
+                      "challenge=" <> Text.unpack (pkceChallengeFor "contract-verifier-with-at-least-forty-three-characters"),
+                      fixtures </> suite
+                    ]
+                    ""
+              case outcome of
+                Just (ExitSuccess, _, _) -> pure ()
+                Just (_, output, errors) -> assertFailure (output <> errors)
+                Nothing -> assertFailure "Hurl timed out"
+
+awaitReady :: HTTP.Manager -> ProcessHandle -> String -> IO ()
+awaitReady manager process base = do
+  exited <- getProcessExitCode process
+  case exited of
+    Just code -> fail ("packaged server exited before readiness: " <> show code)
+    Nothing -> do
+      request <- HTTP.parseRequest (base <> "/health/ready")
+      result <- try @HTTP.HttpException (HTTP.httpLbs request {HTTP.responseTimeout = HTTP.responseTimeoutMicro 500_000} manager)
+      case result of
+        Right response | statusCode (HTTP.responseStatus response) == 200 -> pure ()
+        _ -> threadDelay 100_000 >> awaitReady manager process base
+
+-- Wait synchronously before the enclosing database and temporary files are released.
+stopChild :: ProcessHandle -> IO ()
+stopChild process = do
+  terminateProcess process
+  stopped <- timeout 5_000_000 (waitForProcess process)
+  case stopped of
+    Just _ -> pure ()
+    Nothing -> do
+      pid <- getPid process
+      forM_ pid (signalProcess sigKILL)
+      void (waitForProcess process)
+
+makeTemporaryDirectory :: IO FilePath
+makeTemporaryDirectory = do
+  base <- getTemporaryDirectory
+  (path, handle) <- openTempFile base "shomei-oauth-contract"
+  hClose handle
+  removeFile path
+  createDirectory path
+  setFileMode path 0o700
+  pure path
diff --git a/test/fixtures/errors.hurl b/test/fixtures/errors.hurl
new file mode 100644
--- /dev/null
+++ b/test/fixtures/errors.hurl
@@ -0,0 +1,107 @@
+# Run by the isolated packaged-server fixture; see README.md.
+
+GET {{base_url}}/oauth/authorize
+[Query]
+client_id: {{client_id}}
+response_type: code
+redirect_uri: http://localhost:9999/callback
+code_challenge: {{challenge}}
+code_challenge_method: S256
+HTTP 401
+Cache-Control: no-store
+Pragma: no-cache
+[Asserts]
+header "Content-Type" startsWith "application/json"
+header "WWW-Authenticate" not exists
+jsonpath "$.error" == "login_required"
+
+POST {{base_url}}/oauth/token
+[BasicAuth]
+unknown: wrong
+[Form]
+grant_type: client_credentials
+HTTP 401
+Cache-Control: no-store
+Pragma: no-cache
+[Asserts]
+header "Content-Type" startsWith "application/json"
+header "WWW-Authenticate" == "Basic realm=\"shomei\""
+jsonpath "$.error" == "invalid_client"
+
+GET {{base_url}}/oauth/userinfo
+HTTP 401
+Cache-Control: no-store
+Pragma: no-cache
+[Asserts]
+header "Content-Type" startsWith "application/json"
+header "WWW-Authenticate" == "Bearer realm=\"shomei\""
+jsonpath "$.error" == "invalid_token"
+
+GET {{base_url}}/oauth/userinfo
+Authorization: Bearer invalid-sentinel
+HTTP 401
+Cache-Control: no-store
+Pragma: no-cache
+[Asserts]
+header "Content-Type" startsWith "application/json"
+header "WWW-Authenticate" == "Bearer realm=\"shomei\", error=\"invalid_token\""
+jsonpath "$.error" == "invalid_token"
+
+POST {{base_url}}/oauth/token
+Content-Type: application/x-www-form-urlencoded
+file,oversized.form;
+HTTP 413
+Cache-Control: no-store
+Pragma: no-cache
+[Asserts]
+header "Content-Type" startsWith "application/json"
+header "WWW-Authenticate" not exists
+jsonpath "$.error" == "invalid_request"
+
+GET {{base_url}}/oauth/token
+HTTP 405
+Cache-Control: no-store
+Pragma: no-cache
+[Asserts]
+header "Content-Type" startsWith "application/json"
+header "WWW-Authenticate" not exists
+jsonpath "$.error" == "invalid_request"
+
+POST {{base_url}}/oauth/token
+Accept: application/xml
+Content-Type: application/x-www-form-urlencoded
+HTTP 406
+Cache-Control: no-store
+Pragma: no-cache
+[Asserts]
+header "Content-Type" startsWith "application/json"
+header "WWW-Authenticate" not exists
+jsonpath "$.error" == "invalid_request"
+
+POST {{base_url}}/oauth/token
+Content-Type: application/xml
+HTTP 415
+Cache-Control: no-store
+Pragma: no-cache
+[Asserts]
+header "Content-Type" startsWith "application/json"
+header "WWW-Authenticate" not exists
+jsonpath "$.error" == "invalid_request"
+
+GET {{base_url}}/oauth/unknown
+HTTP 404
+Cache-Control: no-store
+Pragma: no-cache
+[Asserts]
+header "Content-Type" startsWith "application/json"
+header "WWW-Authenticate" not exists
+jsonpath "$.error" == "invalid_request"
+
+POST {{base_url}}/v1/auth/login
+Content-Type: application/json
+file,oversized.form;
+HTTP 413
+Content-Type: application/problem+json
+[Asserts]
+jsonpath "$.code" == "payload_too_large"
+jsonpath "$.status" == 413
diff --git a/test/fixtures/shomei-types.dhall b/test/fixtures/shomei-types.dhall
new file mode 100644
--- /dev/null
+++ b/test/fixtures/shomei-types.dhall
@@ -0,0 +1,192 @@
+-- The typed schema for a Shōmei runtime configuration file.
+-- Every field is optional; an absent field falls back to the built-in default, and any
+-- SHOMEI_* variable overrides the file. Use record completion so omitted fields become None:
+--     let Shomei = ./shomei-types.dhall
+--     in Shomei::{ databaseUrl = Some "host=localhost dbname=shomei" }
+--
+-- The server renders the completed file with `dhall-to-json` and decodes it. Database
+-- credentials may live here, so the live `config/shomei.dhall` file is gitignored. Notifier,
+-- signing-key, and TOTP encryption secrets remain environment-only.
+let ConfigType =
+      { issuer : Optional Text
+      , audience : Optional Text
+      , databaseUrl : Optional Text
+      , bindHost : Optional Text
+      , maxConnections : Optional Natural
+      , slowClientTimeoutSeconds : Optional Natural
+      , port : Optional Natural
+      , trustedProxies : Optional (List Text)
+      , proxyProtocol : Optional Text
+      , dbPoolSize : Optional Natural
+      , dbPoolAcquisitionTimeoutMs : Optional Natural
+      , dbTransactionMaxAttempts : Optional Natural
+      , dbTransactionDeadlineMs : Optional Natural
+      , dbStatementTimeoutMs : Optional Natural
+      , sweepEnabled : Optional Bool
+      , sweepIntervalSeconds : Optional Natural
+      , sweepBatchSize : Optional Natural
+      , sweepDeadSessionGraceDays : Optional Natural
+      , sweepOneTimeTokenGraceDays : Optional Natural
+      , sweepCeremonyGraceMinutes : Optional Natural
+      , loginAttemptRetentionDays : Optional Natural
+      , authEventRetentionDays : Optional Natural
+      , argon2MemoryKiB : Optional Natural
+      , argon2Iterations : Optional Natural
+      , argon2Parallelism : Optional Natural
+      , hashingMaxConcurrency : Optional Natural
+      , accessTokenTtlSeconds : Optional Natural
+      , refreshTokenTtlSeconds : Optional Natural
+      , sessionTtlSeconds : Optional Natural
+      , maxActiveNonInteractiveSessions : Optional Natural
+      , maxPasskeysPerUser : Optional Natural
+      , rememberedSessionTtlSeconds : Optional Natural
+      , publicBaseUrl : Optional Text
+      , emailVerificationRequired : Optional Bool
+      , notifierTransport : Optional Text
+      , alsoLogNotifications : Optional Bool
+      , smtpHost : Optional Text
+      , smtpPort : Optional Natural
+      , smtpTlsMode : Optional Text
+      , smtpUsername : Optional Text
+      , smtpFromAddress : Optional Text
+      , smtpTimeoutSeconds : Optional Natural
+      , webhookUrl : Optional Text
+      , webhookTimeoutSeconds : Optional Natural
+      , webhookMaxAttempts : Optional Natural
+      , notifierQueueSize : Optional Natural
+      , rateLimitEnabled : Optional Bool
+      , maxFailedLoginsPerAccount : Optional Natural
+      , maxFailedLoginsPerIp : Optional Natural
+      , perIpRequestsPerMinute : Optional Natural
+      , perIpBurst : Optional Natural
+      , lockoutWindowSeconds : Optional Natural
+      , lockoutDurationSeconds : Optional Natural
+      , metricsEnabled : Optional Bool
+      , requestLoggingEnabled : Optional Bool
+      , gracefulShutdownTimeoutSeconds : Optional Natural
+      , passwordMinLength : Optional Natural
+      , passwordMaxLength : Optional Natural
+      , passwordRejectCommon : Optional Bool
+      , passwordRejectContextual : Optional Bool
+      , passwordBreachCheckEnabled : Optional Bool
+      , passwordBreachCheckFailClosed : Optional Bool
+      , passwordBreachCheckTimeoutMs : Optional Natural
+      , webauthnRpId : Optional Text
+      , webauthnRpName : Optional Text
+      , webauthnOrigins : Optional (List Text)
+      , webauthnUserVerification : Optional Text
+      , webauthnAttestation : Optional Text
+      , webauthnCeremonyTimeoutSeconds : Optional Natural
+      , webauthnPendingCeremonyTtlSeconds : Optional Natural
+      , mfaRequireSecondFactor : Optional Bool
+      , totpEnabled : Optional Bool
+      , totpEnrollmentTtlSeconds : Optional Natural
+      , machineTokenTtlSeconds : Optional Natural
+      , oidcEnabled : Optional Bool
+      , oauthLoginUrl : Optional Text
+      , oauthAuthorizationCodeTtlSeconds : Optional Natural
+      , oauthIdTokenTtlSeconds : Optional Natural
+      , legacyActorUntilUnix : Optional Natural
+      , emitLegacyActor : Optional Bool
+      , allowedClockSkewSeconds : Optional Natural
+      , signingAlgorithm : Optional Text
+      , keyRefreshIntervalSeconds : Optional Natural
+      , tokenTransport : Optional Text
+      , cookieSecure : Optional Bool
+      , cookieSameSite : Optional Text
+      , csrfAllowedOrigins : Optional (List Text)
+      , defaultRoles : Optional (List Text)
+      }
+
+let default =
+      { issuer = None Text
+      , audience = None Text
+      , databaseUrl = None Text
+      , bindHost = None Text
+      , maxConnections = None Natural
+      , slowClientTimeoutSeconds = None Natural
+      , port = None Natural
+      , trustedProxies = None (List Text)
+      , proxyProtocol = None Text
+      , dbPoolSize = None Natural
+      , dbPoolAcquisitionTimeoutMs = None Natural
+      , dbTransactionMaxAttempts = None Natural
+      , dbTransactionDeadlineMs = None Natural
+      , dbStatementTimeoutMs = None Natural
+      , sweepEnabled = None Bool
+      , sweepIntervalSeconds = None Natural
+      , sweepBatchSize = None Natural
+      , sweepDeadSessionGraceDays = None Natural
+      , sweepOneTimeTokenGraceDays = None Natural
+      , sweepCeremonyGraceMinutes = None Natural
+      , loginAttemptRetentionDays = None Natural
+      , authEventRetentionDays = None Natural
+      , argon2MemoryKiB = None Natural
+      , argon2Iterations = None Natural
+      , argon2Parallelism = None Natural
+      , hashingMaxConcurrency = None Natural
+      , accessTokenTtlSeconds = None Natural
+      , refreshTokenTtlSeconds = None Natural
+      , sessionTtlSeconds = None Natural
+      , maxActiveNonInteractiveSessions = None Natural
+      , maxPasskeysPerUser = None Natural
+      , rememberedSessionTtlSeconds = None Natural
+      , publicBaseUrl = None Text
+      , emailVerificationRequired = None Bool
+      , notifierTransport = None Text
+      , alsoLogNotifications = None Bool
+      , smtpHost = None Text
+      , smtpPort = None Natural
+      , smtpTlsMode = None Text
+      , smtpUsername = None Text
+      , smtpFromAddress = None Text
+      , smtpTimeoutSeconds = None Natural
+      , webhookUrl = None Text
+      , webhookTimeoutSeconds = None Natural
+      , webhookMaxAttempts = None Natural
+      , notifierQueueSize = None Natural
+      , rateLimitEnabled = None Bool
+      , maxFailedLoginsPerAccount = None Natural
+      , maxFailedLoginsPerIp = None Natural
+      , perIpRequestsPerMinute = None Natural
+      , perIpBurst = None Natural
+      , lockoutWindowSeconds = None Natural
+      , lockoutDurationSeconds = None Natural
+      , metricsEnabled = None Bool
+      , requestLoggingEnabled = None Bool
+      , gracefulShutdownTimeoutSeconds = None Natural
+      , passwordMinLength = None Natural
+      , passwordMaxLength = None Natural
+      , passwordRejectCommon = None Bool
+      , passwordRejectContextual = None Bool
+      , passwordBreachCheckEnabled = None Bool
+      , passwordBreachCheckFailClosed = None Bool
+      , passwordBreachCheckTimeoutMs = None Natural
+      , webauthnRpId = None Text
+      , webauthnRpName = None Text
+      , webauthnOrigins = None (List Text)
+      , webauthnUserVerification = None Text
+      , webauthnAttestation = None Text
+      , webauthnCeremonyTimeoutSeconds = None Natural
+      , webauthnPendingCeremonyTtlSeconds = None Natural
+      , mfaRequireSecondFactor = None Bool
+      , totpEnabled = None Bool
+      , totpEnrollmentTtlSeconds = None Natural
+      , machineTokenTtlSeconds = None Natural
+      , oidcEnabled = None Bool
+      , oauthLoginUrl = None Text
+      , oauthAuthorizationCodeTtlSeconds = None Natural
+      , oauthIdTokenTtlSeconds = None Natural
+      , legacyActorUntilUnix = None Natural
+      , emitLegacyActor = None Bool
+      , allowedClockSkewSeconds = None Natural
+      , signingAlgorithm = None Text
+      , keyRefreshIntervalSeconds = None Natural
+      , tokenTransport = None Text
+      , cookieSecure = None Bool
+      , cookieSameSite = None Text
+      , csrfAllowedOrigins = None (List Text)
+      , defaultRoles = None (List Text)
+      }
+
+in  { Type = ConfigType, default }
diff --git a/test/fixtures/throttling.hurl b/test/fixtures/throttling.hurl
new file mode 100644
--- /dev/null
+++ b/test/fixtures/throttling.hurl
@@ -0,0 +1,22 @@
+# Separate server lifetime with one token and a negligible refill rate.
+POST {{base_url}}/oauth/token
+[Form]
+grant_type: client_credentials
+HTTP 401
+Cache-Control: no-store
+Pragma: no-cache
+[Asserts]
+header "Content-Type" startsWith "application/json"
+jsonpath "$.error" == "invalid_client"
+
+POST {{base_url}}/oauth/token
+[Form]
+grant_type: client_credentials
+HTTP 429
+Cache-Control: no-store
+Pragma: no-cache
+[Asserts]
+header "Content-Type" startsWith "application/json"
+header "WWW-Authenticate" not exists
+header "Retry-After" == "60"
+jsonpath "$.error" == "temporarily_unavailable"
