Auth

Multi-realm authentication with email/password, Google SSO, GitHub SSO, and JWT tokens.

Realms

An auth realm represents a user population with its own providers, password policy, and user model. An app can have multiple realms — one for admin users, another for customers.

class AdminUserRealm(
    override val deps: AuthSystem.Deps,
    private val usersRepo: AdminUsersRepo,
) : AuthRealm<AdminUser> {

    override val id = RealmId("admin-user")

    override val providers = listOf(
        EmailAndPasswordAuth(deps),
        GoogleSsoAuth(deps, clientId = "your-google-client-id"),
        GithubSsoAuth(deps, clientId = "your-github-id", clientSecret = "your-github-secret"),
    )

    override val passwordPolicy = PasswordPolicy.default

    // Operations on users live on AuthUserAdapter, reached via `realm.users`.
    override val users = object : AuthUserAdapter<AdminUser> {
        override suspend fun loadById(id: UserId) = usersRepo.findById(id.value)

        // EmailAddress is always canonical (trimmed + lowercased), so this lookup is
        // case-insensitive by TYPE — callers no longer have to remember to normalize.
        override suspend fun loadByEmail(email: EmailAddress) = usersRepo.findByEmail(email)

        override suspend fun createForSignup(
            params: AuthUserAdapter.CreateUserForSignupParams,
        ): Stored<AdminUser> = usersRepo.insert(
            AdminUser(email = params.email, name = params.displayName),
        )

        override suspend fun serialize(user: Stored<AdminUser>) = /* ... */
    }
}

JWT generation

Each realm generates JWT tokens for authenticated users. The token includes user data and permissions, signed with HMAC-512.

override suspend fun generateJwt(
    user: Stored<AdminUser>,
    selectedOrg: SelectedOrg?,
): String {
    val gen = deps.jwtGenerator
    val userValue = user.resolve()

    val token = gen.createJwt(
        user = JwtUserData(
            id = UserId(user._id),
            desc = userValue.name,
            type = AdminUser.USER_TYPE,
            email = userValue.email,
        ),
        permissions = UserPermissions(isSuperUser = userValue.isSuperUser),
    ) {
        withExpiresAt(Kronos.systemUtc.instantNow().plus(1.hours).jvm)
    }

    return token
}

selectedOrg is null for an org-less realm. JwtUserData.id is a UserId, not a string — see typed identifiers.

Providers

Each provider handles a specific authentication mechanism:

EmailAndPasswordAuth

Sign up, sign in, password recovery, password change. Passwords are hashed with Argon2/Bcrypt and stored separately from user records.

GoogleSsoAuth

Google OAuth flow. Verifies ID tokens and creates or matches users by email.

GithubSsoAuth

GitHub OAuth flow. Exchanges authorization codes for access tokens.

Account activation

A realm can require a new account to prove its email address before it can sign in. Sign-up mails a link and issues no session; sign-in with the correct password answers with a response case rather than an error, so the frontend can offer to resend rather than showing a generic failure.

when (val response = api.auth.signIn(realm, credentials)) {
    is AuthSignInResponse.Success            -> gotoDashboard(response)
    is AuthSignInResponse.ActivationRequired -> offerResend(response.resendToken)
    is AuthSignInResponse.OrgSelectionRequired -> showOrgPicker(response)
}

“Not activated” is modelled as the presence of a marker record, not a flag on the user and not “an unexpired token exists”. A flag would need a default, and the only safe default locks out every existing account; the token test erases itself once the token expires.

Resending is authorized by a single-use token minted only on the sign-in path that proved the password — not by naming an email address. That is what keeps the endpoint from being an open mail relay aimed at any mailbox. A resend rotates the token, so the superseded link dies immediately, and a cooldown bounds how fast a caller can trigger mail.

The first cut took a bare email address on an anonymous route, which would have turned sign-up into a sustained mail faucet pointed at anyone. The review caught it; the token is the fix.

Clearing the marker requires proving the mailbox and invalidating every earlier password. Completing a password reset does both, so it also activates. SSO sign-in proves the mailbox but leaves an attacker-set password intact, so it deliberately does not.

Organisations

A realm declares how it relates to organisations through its orgPolicy. The default is OrgPolicy.None — an org-less realm, such as an internal operator console.

Under OrgPolicy.Required, sign-in resolves the user's accessible organisations and answers with the 0/1/n flow: none is a refusal, exactly one auto-selects, and several return an OrgSelectionRequired response backed by a single-use selection token. Refresh keeps the same organisation — it never silently changes which one is active.

class B2bRealm(...) : AuthRealm<B2bUser> {
    override val orgPolicy = OrgPolicy.Required()

    override suspend fun getMemberships(user: Stored<B2bUser>): Set<OrgMembership> =
        orgMembers.sessionMembershipsOf(UserId(user._id))

    // How "accessible" is defined is the APP's call — the framework only asks.
    // The demo filters to active orgs and dedupes; see saas_org_hooks.kt.
    override suspend fun getAccessibleOrgs(memberships: Set<OrgMembership>): List<AuthOrgRef> =
        orgs.accessibleActiveOrgs(memberships)
}

Typed identifiers

Identity values are value classes rather than raw strings — RealmId, UserId, OrgId and EmailAddress. They are threaded end to end: through JWT claims, URI parameters, storage and the API surface.

EmailAddress canonicalizes on construction (trim + lower-case), which is what makes lookups case-insensitive by type rather than by remembering to call .lowercase() at every call site.

Localized emails

Auth emails render per locale. The language is chosen from the user's own setting, then the realm's defaultLanguage, then the framework's guaranteed fallback — a chain, not an either/or, so a German-only deployment does not mail English to a user whose stored language it has no rendering for.

class MyRealm(...) : AuthRealm<MyUser> {
    override val defaultLanguage = Locale("de")

    override val messaging = AuthRealm.DefaultMessaging(
        senderEmail = "noreply@example.com",
        senderName = "Example",
        applicationName = "Example",
        realm = this,
        templates = AuthEmailTemplates.default(myBrandedLayout),
    )
}

See Messaging for the template and layout surface.

Wiring in Kontainer

Register your realm and its dependencies as a Kontainer module:

val AdminUserModule = module {
    dynamic(AdminUsersRepo::class)
    dynamic(AdminUserRealm::class)
    dynamic(AdminUserServices::class)
}

// In your main blueprint:
val blueprint = kontainer {
    funktor(
        config = config,
        auth = { useKarango() },
        // ...
    )

    module(AdminUserModule)
}

Auth API

The auth module provides pre-built API endpoints for all auth operations: sign up, sign in, activate account, set password, password recovery, token refresh, and user-specific API access queries. A matching client library (AuthApiClient) is available for Kotlin/JS frontends.

Token refresh

The GET /auth/{realm}/refresh-token endpoint issues a fresh JWT for authenticated users. The server re-loads the user and regenerates the token, so permission changes are picked up automatically.

// Frontend: the token is refreshed automatically by AuthState.
// You can also call it manually:
val response = api.auth.refreshToken().firstOrNull()
// response.data?.token  — the new JWT

API access matrix (ApiAcl)

The GET /auth/my-api-access endpoint returns a flat list of API endpoints the current user can access, with their estimated access level (Granted or Partial). Denied endpoints are filtered out — the response only reveals what the user CAN access.

Advisory only. ApiAcl decides what to RENDER. The server remains the authority and nothing here enforces anything — never use it in place of an auth rule.

// Fetch the access matrix once after login
val matrix = api.auth.getMyApiAccess().first().data!!
val acl = ApiAcl(matrix)

// Type-safe lookup using the same endpoint objects from your ApiClient
if (acl.canAccess(MyApiClient.GetEvent)) {
    navLink("/events") { +"Events" }
}

// Destructive actions too — Partial IS access; the backend checks ownership
if (acl.canAccess(MyApiClient.DeleteEvent)) {
    button { +"Delete" }
}

Four predicates, sharing their names with the generated TypeScript SDK so both clients read the same way. canAccess is true for anything but Denied — it includes Partial, and that is access: Partial means the route is callable and the server will additionally check the arguments — typically "do you own this resource". So canAccess is the predicate for visibility, destructive actions included; gating a delete on canFullyAccess would hide it from the user on their own resource. canPartiallyAccess is Partial only and isDenied is the negation of canAccess. Only a rule that estimates Partial produces it — forCall given an estimateFn, or an AccessLevelCheck; the built-in rules never do, so do not gate on canPartiallyAccess expecting the branch to run.

canFullyAccess means only that no auth rule reported an argument check — not that the route works for every resource. A forCall rule estimates Granted unless it is given an estimateFn, so an ownership check written with it reads as full access; checks inside a handler, and RouteParamsGuards such as the saas OrgIsolationGuard, are not auth rules and are invisible too.

ApiAcl.empty denies everything, and unknown endpoints default to Denied. Note that this includes public() routes — a logged-out visitor has no matrix at all, so do not gate a sign-in control on the ACL.

Frontend support

Pre-built Kraft components for login pages, password reset, and password change widgets. Auth state management with router middleware that redirects unauthenticated users to the login page.

Session lifecycle

AuthState automatically manages the JWT session lifecycle. Enabled by default with zero configuration:

  • Periodic refresh — checks token expiry every 60 seconds, refreshes 2 minutes before it expires
  • Focus check — verifies token when the browser tab regains focus
  • Graceful expiry — on expiry: saves the current page, logs out, redirects to login. After re-login, navigates back to the previous page
  • Page reload — clears expired tokens from localStorage immediately on app init
// Zero-config: auto-refresh is enabled by default
val auth = authState<MyUser>(
    frontend = AuthFrontend.default(config = AuthFrontendConfig(redirectAfterLogin = Nav.dashboard())),
    api = Apis.auth,
    router = { kraft.router },
)

// With custom config:
val auth = authState<MyUser>(
    frontend = AuthFrontend.default(config = AuthFrontendConfig(redirectAfterLogin = Nav.dashboard())),
    api = Apis.auth,
    router = { kraft.router },
    sessionConfig = AuthSessionConfig(
        checkIntervalMs = 30_000,          // check every 30 seconds
        refreshBeforeExpiryMs = 120_000L,  // refresh 2 minutes before expiry
        onTokenRefreshed = { refreshApiAcl() },
        onSessionExpired = { showLoginDialog() },
    ),
)

// Disable auto-refresh entirely:
sessionConfig = AuthSessionConfig.disabled
The auth module handles the plumbing — token storage, JWT generation, password hashing, recovery tokens, session lifecycle. You implement the user model and the realm. That's it.

Storage backends

Auth records (passwords, recovery tokens) are stored via pluggable backends:

  • useKarango() — ArangoDB via Karango
  • useMonko() — MongoDB via Monko