Overview
Chatto authenticates users with typed opaque runtime credentials. API and multi-server clients present bearer credentials, while same-origin browser sessions present cookie-scoped first-party credentials through HttpOnly cookies. The bundled SPA uses only the cookie for its origin server and stores bearer sessions for remote servers. It explicitly requests cookie-only direct authentication, so the server does not create bearer credentials for that flow. During an upgrade, it revokes old origin bearer authority before it removes the stored credentials. Login flows include classic password login, configured external providers, and a bootstrap path for first-boot operator setup.
Behavior
-
Desktop password login — the installed app can submit a server password through its native host and store the returned programmatic bearer session. This session has no OAuth client grant. The web frontend keeps remote login on the server-owned OAuth page. Desktop shows configured provider buttons that start this OAuth flow with a provider hint. It also keeps the server page available for recovery. Create account starts registration in the system browser and returns the new session to Desktop after email-code verification and any required consent. See FDR-034.
-
Providers can opt into
manage_usernames. New accounts receive the verified provider username after trimming spaces and conversion to lowercase. OIDC usesusername_claim(defaultpreferred_username); GitHub, GitLab, and Discord use their account username. Google has no separate username, so it uses the local part of the verified email address and requires email access. This Google-specific source is not a fallback for other providers. Display names are never used. Missing, invalid, or reserved names stop creation. Collisions use numeric suffixes starting at-2, with at most 1,000 candidates and base truncation to fit the username limit. The server assigns the name; the confirmation preview is not a reservation. -
Existing names remain stable unless the provider enables
update_usernames. Synchronization occurs at sign-in and retains an existing name that matches the provider base or one of its numeric candidates. Failed synchronization preserves the current name, permits sign-in, and logs a warning without PII. No provider owns an account's username. Operators must configure multiple synchronizing providers consistently; the provider used at sign-in wins. -
Any linked managed provider blocks local username edits. Display names remain editable. Operator edits remain available. Removing the final managed link, removing its configuration, or disabling management restores local editing.
-
allow_unlinkingdefaults to true. A provider can disable user unlinking; settings show a disabled control and a notice. The operator API retains unlink access, subject to the existing last-enabled-method rule. -
Hash-only legacy OIDC links conservatively inherit configured OIDC username and unlink restrictions until a verified sign-in completes their metadata.
-
OIDC token authentication can use an explicit Basic, POST, or public-client method. Without an override, confidential clients prefer advertised Basic, then POST; omitted metadata defaults to Basic. Unsupported advertised methods fail before exchange. Each code is submitted once, with PKCE.
-
Each OIDC sign-in sends a new random nonce. Chatto rejects an ID token that does not contain the same nonce. If a sign-in started on a server version without this check, its callback fails once, and the user starts again.
-
Each request to an external provider has a 10-second limit. This includes OIDC discovery, token exchange, UserInfo, and key-set requests, and the requests of OAuth-only providers. Concurrent sign-ins share one discovery attempt. Thus an unavailable provider delays a sign-in by a limited time and does not hold later sign-ins.
-
UserInfo fills missing names or requested email only after its subject matches the verified ID token. Populated ID-token claims win, and email verification stays paired with its address. An unavailable or malformed UserInfo response does not discard valid ID-token hints. Suggestions keep their existing order and normalization; linked accounts retain their existing names.
-
OIDC key sets can contain key types or curves that Chatto does not support. Chatto ignores these keys and verifies signatures with supported keys. A set without a usable signing key still fails verification. The official suite checks this behavior and selected positive and negative client flows in CI.
-
Remote reconnection — the bundled client gives every remote API read, including the first viewer read, the active connection's bearer-renewal hook. A temporary network failure leaves renewal retryable and keeps the normal chat view visible. A confirmed authentication rejection asks the user to sign in to reconnect. Refresh rejection logs contain only a fixed reason code; they contain no credential or user identifier.
-
Consent identity display — the consent page shows the host for a URL-based client ID and the exact ID for an opaque native client identity. The server validates client registration; the page also checks that the callback and its reported origin agree before it offers approval or denial.
-
Official mobile client — the fixed OAuth identity is
eu.chattocorp.chatto.mobile, with the exact callbackeu.chattocorp.chatto.mobile:/oauth/callback. Servers recognize it without operator configuration or a client-metadata fetch. Existing client policy, consent, and PKCE checks still apply. The server records its authorization as a built-in client. Older servers without this registration cannot authorize the official mobile client. -
Loopback browser client — the bundled frontend can run on a loopback origin:
localhost, a.localhostname,127.0.0.1, or[::1]. When it signs in to a server that is not local, it uses the fixed OAuth identitychatto://loopback. That server cannot retrieve a CIMD document from the user's device. For a local server, the frontend keeps its origin CIMD identity. The server accepts the loopback client only whenauth.loopback_client_enabledis set; the default is off. Disabling the setting also rejects existing codes, refresh credentials, and access tokens of this client. The server accepts the callback path/servers/callback?mode=popupon each HTTP or HTTPS loopback origin, with any port. All other callback parts stay exact. Any local process can use this identity, so the consent page names it "Unverified app on this device", shows the callback origin as its identity, and requires consent for each authorization. The administrator inventory lists it as "Unverified local app" and does not record members' local callback origins. Its renewable session ends at most 24 hours after sign-in. Refresh does not extend it, and validation shortens a longer stored window. Client policy and PKCE checks still apply, and administrators can block the client. The server records its authorization as a built-in client. -
The standalone welcome page shows an introduction and a Connect to a server action. The action opens the Server Directory. The welcome page does not list or check saved servers; saved entries remain available in the directory.
-
Login — users sign in on the
/loginpage. Without configured external providers, the page shows the password form, the recovery link, and the email registration link when direct registration is enabled. With providers,/loginshows each configured name once. When email registration or a known provisioning provider is available, the heading offers sign-in and account creation. “Existing accounts only” identifies providers that explicitly disable provisioning. Providers on older servers that omit the flag have no caption. The email registration link opens the email flow directly. The registration page links back to sign-in. At email verification, users can edit the address and request a code for the corrected address. If password login is enabled, it also shows a Password button that opens/login/password. That page holds the password form, the recovery link, the email registration link when enabled, and a link back to the provider choices. Both pages keep the return path. A completed password reset opens/login/password./login/passwordredirects to/loginwhen password login is disabled. Operators can disable password login. When disabled, the server rejects password-login requests before credential validation, public discovery tells clients not to render the password form or recovery link, and direct registration is disabled too (§8d). Existing sessions and stored passwords remain. The page is also used for redirect-after-signup. -
External provider login — operators configure repeated
[[auth.providers]]entries or equivalent countedCHATTO_AUTH_PROVIDERS_<index>_<field>environment variables. Supported provider types areoidc,github,gitlab,google, anddiscord. The login page renders buttons fromchatto.discovery.v1.ServerDiscoveryService.GetServerlogin providers, and provider flows use/auth/providers/{providerID}plus/auth/providers/{providerID}/callback. OIDC also keeps/auth/oidcand/auth/oidc/callbackas compatibility aliases for older clients and provider registrations. A matched browser login establishes the HTTP-only cookie session and redirects without a bearer credential; when provider login is nested inside Chatto OAuth authorization, the existing PKCE authorization-code flow continues instead. -
CIMD public client — OIDC providers may use a confidential client secret or Chatto's public client ID at
{webserver.url}/oauth/client-metadata.json. The metadata document declares the exact callback URIs for OIDC providers configured with that client ID and requires Authorization Code with public token authentication, allowing CIMD-aware issuers to use Chatto without preregistration. -
Chatto OAuth client identity — browser client applications use their HTTPS CIMD URL as
client_id; Chatto retrieves the document, verifies its self-identified client ID, public-client grant shape, and registered redirect URI, then binds that client ID through consent, authorization code exchange, and the resulting opaque access token. The bundled frontend publishes one matching identity forwebserver.urland for each exactwebserver.allowed_originsalias. It does not publish an identity for a wildcard or an unknown request host. Metadata retrieval is bounded and blocks special-use network destinations unless the Chatto server itself uses a local development URL. Chatto Desktop uses the built-inchatto://desktopclient identity and exact registered callback. A bundled frontend on a loopback origin uses the built-inchatto://loopbackclient identity for servers that are not local, when the server enables it. Native CIMD clients may declare private-use callbacks or HTTP callbacks on a literal loopback IP,localhost, or one concrete.localhosthostname. Literal loopback IP callbacks can select a different port at run time; all other callback parts stay exact. A local callback shows a warning and requires consent for each authorization. CIMD identity means the app is identifiable, not endorsed; user consent is still required. -
Authorization response issuer — Chatto adds the origin of its required
webserver.urlto each authorization response as theissparameter (RFC 9207). The bundled client signs in to more than one server, so a malicious server can pass a sign-in to a different server and try to receive the code of that server. Before the token exchange, the client compares the issuer with the origin of the server that the user selected. If the response has no issuer, an empty issuer, more than one issuer, or an issuer with a different origin, the client stops the sign-in and sends the code to no server. A response without an issuer can come from a different server, so the client cannot accept it. Thus the client cannot sign in to an older server that has nowebserver.url, because that server sends an empty issuer. A server that the user added through an address other than itswebserver.urlorigin cannot complete sign-in; the user must add it with that address. Existing sessions are not affected, because the check applies only to a new sign-in. -
Authorization windows — the bundled client opens each sign-in, provider sign-in, and identity-link window on its own
/servers/authorizelaunch page, not onabout:blank. The window opens during the user's action, before the client knows the target URL. When the target is ready, the client writes it to a short-lived device-local launch record, and the launch page replaces itself with that HTTP or HTTPS URL. An installed Firefox for Android web app opens a new window in a separate Custom Tab with the URL that it has at open time, and the client cannot navigate that tab later. The launch record works because the tab shares the device storage of the client. Firefox can also load the launch page in the detached window thatwindow.openreturned. Thus only a visible launch page continues, and reading does not remove the record. The client removes the record when the flow ends, and removes expired records when it opens a window. When the callback page cannot close its window, it tells the user to close the window. -
OAuth client authorization inventory — after a successful user-approved authorization, Chatto durably records the client identity, source, validated display name, callback origins, first and latest authorization times, and distinct authorized-user count. Metadata retrieval and abandoned or denied authorization do not add a client to this inventory. Server managers can mark a recorded client default, trusted, or blocked from the Security page. Trusted is an informational label and never skips consent. Blocked clients cannot start or complete authorization or use existing OAuth access tokens; applying the policy terminates matching realtime connections on every replica and also revokes stored tokens best-effort across the shared runtime-state bucket. Unknown future source and policy values remain intact through the administration API. The frontend labels them explicitly and cannot overwrite an unsupported policy, while runtime enforcement denies access for unsupported policies during mixed-version operation.
-
Provider group restrictions — an OIDC provider can set
allowed_groupswith an optionalgroups_claim(defaultgroups). The user must be in at least one allowed group; names match exactly. The groups claim is a top-level claim that holds a string or a list of strings. Chatto reads it from the ID token and then from UserInfo. A missing claim denies the sign-in. An emptyALLOWED_GROUPSenvironment variable is a configuration error, because it would remove the restriction. Chatto checks the groups in the provider callback after it verifies the identity, so the check applies to each sign-in, to linked accounts, to account creation, and to identity links. A denied sign-in returnsprovider_access_denied, which does not give the reason. The login page and the identity-link window show a message for it. Logs contain only the provider ID and type. Existing sessions stay valid. Pending account-creation and link confirmations that Chatto created before a restriction changed do not get the new check before they expire. -
Provider group roles — an OIDC provider can map groups to Chatto roles with
group_roles. Chatto applies the mapping in the provider callback after the group restriction, at each sign-in, identity link, and account creation through the provider. A pending account-creation confirmation carries the groups claim to account creation. See FDR-050. -
External identity matching and confirmation — provider identities are linked through durable
EVTuser facts. OIDC providers use the verified issuer URL plus subject; OAuth-only providers use the configured provider ID plus GothUserID. Provider email is profile data unless the adapter has an explicit provider verification signal: OIDC requiresemail_verified, Discord requiresverified, Google-through-Goth requiresverified_email/email_verified, and GitHub requires a verified primary email from the GitHub emails API. Email is never used as the primary account match key. If a sign-in callback returns an identity that is not linked to an account, Chatto creates a short-lived pending account-creation flow only whenauto_provision = true. The user must explicitly confirm account creation through ConnectRPC. For explicit account linking, the authenticated user creates a one-time provider link-start URL. The verified provider callback links the identity to that bound account without another confirmation. An identity already linked to another account causes a conflict; email never causes an automatic merge. For providers without managed usernames, create confirmation pre-fills editable username and display-name fields from provider profile hints, and the submitted values become the new Chatto profile. The link-start handoff binds the target account before provider authorization, so remote-server callbacks do not depend on an origin-local bearer token. Previously issued pending link confirmations remain valid until they expire. Linking and disconnecting providers require a fresh runtime credential or current-password proof. Disconnecting accepts password proof for that operation without upgrading a delegated session to fresh-auth status. Disconnecting removes the sign-in method and refreshes account settings; established sessions remain active. Disconnecting refuses to remove the last enabled sign-in method. A stored password counts only when direct login is enabled; provider identities count only when their issuer namespace is configured. Provider avatar URLs are transient profile hints: Chatto imports them as managed avatar assets during account creation or first matched login when no avatar is already set, and does not persist the remote URL. -
Invitation-code admission — when the admin server setting
registration.admissionisinvite_only, direct registration and external-provider auto-provisioning carry a validated invitation through their short-lived flows and consume its code with account creation. A new SSO identity entering through Sign In passes the code gate before account creation. Existing-account sign-in and provider linking do not require or consume codes. See FDR-036. -
Password length — all new passwords must have 8 to 72 UTF-8 bytes, including registration, first-run setup, password changes, admin changes, and reset. Go bcrypt rejects inputs above 72 bytes. UI and API validation count bytes, not characters, and reject unsupported lengths before hashing. Passwords are never truncated. Sign-in verification and existing hashes are unchanged.
-
Password set/change — users can set or change their own password from account settings through authenticated ConnectRPC. Adding the first password to a passwordless account does not require current-password proof and preserves existing sessions because it adds a new sign-in method. Changing an existing password requires the current password, applies the same password length policy as registration/reset, writes the password hash as a durable user event, and revokes existing runtime credentials. Server admins can set another user's password through
AdminUserManagementService; admin-set passwords do not require the old password, reject self-targets, and revoke the target user's runtime credentials. -
Password-manager discovery — compatible password managers can open the standard
/.well-known/change-passwordURL on a Chatto server. The server redirects them to the origin server's account settings. A signed-out person signs in and then returns to those settings. Unknown/.well-knownresources return404instead of the bundled application shell. -
Chatto OAuth authorization — cross-origin Chatto clients use
/oauth/authorizewith a stableclient_idand PKCE to obtain a short-lived authorization code, then exchange it with that same client ID at/oauth/tokenfor an opaque delegated access token plus a rotating refresh credential. A request can also bind an enabled protected resource and its exact normalized scopes through consent, code exchange, the renewable session, and each access record. A request must omit both the resource and scope for an unrestricted grant. If it supplies either value, it must supply the complete supported pair. Chatto rejects partial or unsupported grants and does not ignore their scope. The bundled multi-server client opens the remote server's authorization UI in a separate browser window or, on installed Desktop, in the system browser, so passwords, passkeys, and external-provider sign-in remain visibly hosted by that server while the main client stays mounted. The callback returns only the authorization result to the main client, which performs the code exchange and stores the credential pair and expiries. Browser clients identify themselves through their published frontend CIMD document; Chatto validates the requested callback against it. Desktop uses its fixed built-in client and callback. A frontend on a loopback origin uses the opt-in built-in loopback client for servers that are not local. The first non-local authorization shows a user consent screen and remembers approval per user + client ID + exact grant. Local callbacks show their actual origin and require a decision for each authorization. OAuth access tokens can authenticate ordinary API and realtime requests, but cannot satisfy or acquire fresh-auth status for account-security operations. -
Cross-origin transport — Chatto permits browser HTTP and realtime transport from any syntactically valid origin without enabling credentialed CORS. Requests carrying an
Originthat matches neither the direct request target nor the configured public origin never authenticate through ambient session cookies and must present a bearer token. Checking the direct target keeps direct hostname aliases usable; the configured origin covers TLS-terminating proxies without trusting forwarded headers. Theoauth_redirect_originssetting and origin-only OAuth flow were removed for 0.5; compatibility with pre-0.5 clients is not required. Theallowed_originssetting now defines exact reverse-proxy aliases for cookie authentication and the bundled frontend CIMD document. -
Cookie session — on successful same-origin authentication, the server issues the opaque handle in an HttpOnly, SameSite=Lax
chatto_auth_<slot>cookie with a 90-day default expiry. SCS manages the session lifecycle through a Chatto JetStream store adapter. The authoritativeRUNTIME_STATEsession.{hmac}record contains the user ID, kindfirst_party_session, presentationcookie, source/request metadata, auth generation, fresh-auth metadata, and explicit expiry. Each changed revision has a per-message TTL equal to its remaining explicit lifetime. Validation checks the explicit expiry and resolves the current user from projections without rewriting the record or browser cookie. In the final quarter, the bundled frontend calls the protected browser renewal route. The core advances the same record's expiry with revision-checked optimistic concurrency, and the route writes the same opaque handle in a fresh cookie slot with the new lifetime. A late response can add an older slot, but it cannot overwrite a newer session. Chatto examines at most four distinct handles, deduplicates one handle across concurrent response slots, selects the newest valid session, ignores invalid or revoked handles, and removes obsolete slots during the next authentication change. A server-provided renewal time drives an HTTP timer, and the realtime close signal provides a second trigger. Public discovery, ordinary API responses, frontend responses, immutable assets, and WebSocket upgrades do not carry authenticationSet-Cookieheaders. The separate encryptedchatto_sessioncookie holds only short-lived provider, invitation, and OAuth browser-flow state. Version 0.6 removes the 0.5 migration bridge. No authentication path reads its retiredruntime_credential_idfield. Cookie-session records without explicitExpiresAtfail closed. A browser that still has only a 0.4 typed cookie must sign in again. Existing SCS cookie sessions keep their normal lifecycle. The bundled SPA also revokes old stored origin bearer authority before it removes those credentials. A separately hosted client uses the OAuth flow instead of direct authentication. -
CSRF protection — cookie-authenticated unsafe routes require an
X-CSRF-Tokenheader matching the readablechatto_csrfcookie, and that cookie value must be a server-signed token bound to the authenticated user session generation. Dedicated browser login, registration, renewal, bearer cleanup, and logout routes also require JSON and an exact same-origin request. A browser-auth mode header, if present, must select cookies. Browser routes treat an absent header as cookie mode. Plain HTML forms cannot make these requests. Login, registration, and bearer cleanup use the origin proof before a session exists. Renewal and logout require the signed CSRF proof while a valid cookie session exists. If every presented session is already invalid, logout uses the independent browser-route proof and clears the stale cookies. If the readable CSRF cookie expires during a longer active session, the frontend gets a new bound proof from an authenticated safe endpoint and retries the failed request once. Test endpoints, webhooks, OAuth token exchange, and ConnectRPC programmatic API traffic are exempt. Bearer-only requests are exempt because bearer credentials are not ambient browser cookies. -
Bearer session — direct password/registration flows and explicit external-identity account creation issue a renewable first-party bearer session by default for programmatic clients. These routes do not create or change browser authentication cookies. The bundled browser uses the dedicated cookie-only routes, which do not create or return bearer credentials. Cross-origin clients receive the delegated form through Chatto OAuth PKCE; matched external-provider browser login remains cookie-only and never places bearer credentials in its redirect URL. Each bearer session has a short-lived opaque
cht_AT…access token, a rotating refresh credential, and a renewable session window. Remote registered clients store the pair in device-local browser storage and send only the access token asAuthorization: Bearer …and in the realtime subscription message. Normal refresh-credential use is rotation at/oauth/token; the bundled client also presents it to/auth/logoutso logout can revoke the stable session.RUNTIME_STATEholds an immutable fixed-expirysession.{hmac}access record plus a mutablerenewable_session.{hmac}authority. Each authority revision has a per-message TTL equal to its remaining explicit lifetime. The server stores neither raw credential nor the raw refresh-recovery nonce. Delegated records use kindoauth_access_tokenand remain bound to their client ID. -
WebSocket auth — bearer-token clients pass the access token in the first
RealtimeSubscribemessage, where it is checked before event delivery. Cookie authentication is accepted only for same-origin browser connections or non-browser requests without anOriginheader. The server revalidates the exact human credential before subscription and once per minute. A bearer socket ends at access-token expiry with a reconnectingauthentication_requiredclose; the bundled client rotates once and reconnects the same event bus with its in-memory projection resume cursor. A cookie socket ends at the start of the final renewal quarter with a reconnectingsession_renewal_requiredclose. The bundled frontend calls the browser renewal route and then opens the replacement socket without user action. If the server accepts a credential but cannot load its account, the socket ends with a reconnectingtemporarily_unavailableclose, not withauthentication_required. -
Realtime account deactivation — each authenticated realtime connection watches account access in the durable User Auth projection. A deactivation closes the connections of that human and of the bots that the human owns, with
authentication_requiredand no reconnect instruction. The server registers the watch before it validates the credential again, so a deactivation and reactivation that complete before registration cannot keep an old session open. -
API auth failures — protected ConnectRPC methods return unauthenticated errors for missing or invalid credentials. The bundled multi-server client prefers structured error codes and keeps stable message fallbacks for compatibility with older servers. The bundled client handles these errors in its shared ConnectRPC transport, so all services use the same rules. A renewable bearer session rotates its token once and retries. If the server rejects the renewal, the client marks that server as requiring sign-in. A cookie session cannot renew itself, so one rejected request does not end it. The client first reads the account state again. It asks the user to sign in again on that server only when that read is also rejected. If the read fails for a different reason, the client tries again later. The account-state viewer read is the exception: the account state makes that decision itself. The server reports a request as unavailable, not unauthenticated, when the credential is valid but the server cannot load its account.
-
Logout — users select Sign out of server from an authenticated server's Server Menu. The Server Gutter icon and the Server Sidebar header open this menu. The settings navigation also shows Sign out of server in its Your account section. The app header has no sign-out action. Single-server sign-out keeps that server in the gutter and opens its sign-in view, including when the action starts from an inactive server's context menu. It does not select another authenticated server. For registered bearer sessions, the client sends the refresh credential to
/auth/logoutso the server can revoke this client's stable renewable session and every access generation, then removes the pair locally. A renewal response that arrives after sign-out cannot restore the pair. This programmatic route never reads or clears ambient cookies, including the remote server's browser cookie. Origin cookie logout uses the same-originPOST /auth/browser/logoutroute. It deletes the cookie-presentation runtime credential, clears the cookies, and the SPA does a hard reload. A successful logout means that the presented authority is gone. Audit recording is best-effort after revocation. Ordinary logout does not send a user-wide session-termination event. Other sessions keep working. Deleting the runtime authority rejects HTTP requests once the RUNTIME_STATE replica that serves the read has applied the deletion; a lagging replica can still accept it until then. The client closes its socket. Any remaining socket is receive-only and closes within the credential check interval (one minute), through strict periodic validation. If authoritative revocation fails, the route returns503and a current-server sign-out keeps its local authentication state. Network failures and all-server cleanup remain best-effort so users can remove unreachable server registrations locally. All-server sign-out removes remote registrations from the gutter. -
Known signed-out servers — the device-local frontend server catalogue is independent from device-local sessions. A known server can remain signed out. Joining a server from the Server Directory adds it in this state (FDR-042). Selecting its gutter icon opens the server, as for any other gutter icon. Web and Desktop share the remote sign-in layout and server branding. The web view offers one Continue on server button. It names the remote host and explains that a new window opens there for sign-in or account creation. It has no password form. Desktop can offer inline password login as described above. A signed-out origin server opens its sign-in page. The context menu of the icon also offers Log in to this server. Authentication starts only from an explicit sign-in or signup action; selecting the icon does not start it. A remote browser cookie can let this deliberate login complete without a password.
-
Room and message links — When a guest opens a link on the origin server, the sign-in and account creation pages keep the requested URL, including its query and fragment. After authentication, the client opens that URL and applies the usual room access checks.
-
Origin provider sign-in — on the origin login and registration pages, a provider button continues in the same window. A popup is not necessary there, because the page has no state to keep. After a successful sign-in, the server returns to the saved return path. When the provider identity has no linked account, the same window shows the account confirmation. Failed sign-ins, provider denials, and the unlinked-identity error show on the login page, which keeps the saved return path. Remote server sign-in, Chatto Desktop, and account linking from account settings continue to use a separate window. After the app loads with an origin session, it remembers a pending AT Protocol handle (FDR-058).
-
Sign-in window frame — the OAuth consent page, OAuth sign-in and registration, the Atmosphere account sign-in prompt, and account confirmation in a remote server's provider window do not show app navigation. A window bar above the frame shows the server icon and name next to the server address, so that the user can identify where they sign in. A long address loses its start, so that the domain at its end stays visible. Narrow windows show only the name, because the bar has no space for both. The page in the frame shows the server banner and description when the server has them, and the Chatto name below the frame content. In short windows, the banner is hidden so that the form has the space.
-
Sign-in window feedback — remote server sign-in and provider sign-in show Continue in the other window while the window is open. Closing the window cancels the attempt without an error. Chatto Desktop detects closure through the native window. A browser tab also detects closure while it prepares the sign-in URL. Some provider pages, such as Bluesky's, set
Cross-Origin-Opener-Policy: same-origin. The opening browser tab then cannot see whether the sign-in window is still open, so it keeps waiting for the result. The notice has a Cancel button, and the attempt ends after five minutes without a result. A blocked window explains how to allow popups and try again. Other failures keep an error message. Login, registration, and Desktop share provider buttons; origin login and Desktop also share password fields and submit feedback. Each screen keeps its own authentication and session completion. -
Server removal — the gutter menu and the unavailable-server view (FDR-031) offer Remove server for remote servers. Neither offers this action for the origin server, whether signed in or signed out.
-
Unreachable registered servers — the visible, online client retries failed discovery and retained bearer-session viewer loading with per-server delays of 1, 2, 4, 8, 16, then 30 seconds. Network return, foreground return, and native app resume trigger immediate attempts. Selecting an affected server or choosing Try Again retries without opening OAuth. Discovery and viewer requests have a 10-second limit. Successful recovery stops retries. An
invalid_grantrefresh response requires sign-in. An API rejection after successful refresh keeps the credentials; a rejected viewer read enters automatic recovery. Removing a server or unmounting the runtime coordinator stops its scheduled recovery work. -
Sign-out scope — Sign out of server opens one dialog from the Server Menu or the settings navigation. This device is selected by default and ends only the current session. On servers that advertise
allSessionsSignOut, the dialog also offers All devices and apps. This choice ends this device's session and all other sessions and OAuth app authorizations on this server. The user confirms with Sign out of server. Cancel makes no change. Without server support, the dialog confirms sign-out of this device only. Both logout routes acceptallSessions: true; omission or false keeps session-only logout. A valid general-purpose credential is sufficient. Resource-scoped OAuth credentials cannot authorize global sign-out. A scoped refresh token can still end its own session with plain sign-out. No fresh authentication or privileged mode is required. Invalid, expired, and already-revoked credentials cannot revoke other sessions. If no presented credential is valid, global sign-out returns HTTP 401. The dialog stays open and asks the user to sign in again. Plain sign-out remains idempotent. The server appends oneUserSessionsRevokedEventfor each authenticated user in the request, waits for local application, then publishes the user-wide termination reasonlogout_all. Cookie sessions, renewable bearer sessions, access credentials, and third-party OAuth authorization codes from the earlier auth generation stop validating. Connected clients clear private data and open the server's sign-in view. OAuth apps must authorize again; saved consent and the audit inventory remain. Bot API keys belong to separate bot accounts and are unchanged. HTTP validation has the same 60-second auth generation check window as a password change (ADR-127). The strict realtime credential timer keeps its one-minute bound if the best-effort termination signal is lost. A replica that does not know the new fact keeps accepting old sessions until it is upgraded. Update every replica before relying on global sign-out. Old servers ignore the field, so the client hides this choice without the catalog entry. Neither minimum server version changes. -
Other open tabs — origin sign-out notifies the other tabs of the same browser, and they sign out of the origin. A remote sign-out revokes the session on the server. Tabs that share that sign-in observe the local authentication removal. A remaining socket closes on its next credential check, within one minute. Other sessions do not receive a termination frame for ordinary logout. Each remote bearer sign-in gets a new local ID. A tab can adopt rotated credentials from the same sign-in. When it checks the stored credentials and finds a different sign-in, it clears its own viewer and server data and leaves the new credentials in storage. At the first rotation of an older session without an ID, the client derives the ID from a hash of the original access and refresh tokens. Other updated tabs that hold that pair can continue the session without a reload.
-
Global sign-out — the client API can sign out of all servers, but the bundled frontend has no entry point for this action. Global sign-out clears every device-local Chatto session, removes remote catalogue entries on this device, and retains only a configured origin entry in a signed-out state. Remote revocation is best-effort, so unavailable services cannot trap the user in stale local state.
-
Session refresh — cookie runtime credentials keep one stable opaque server-side handle. Ordinary validation is read-only. Before the final-quarter boundary, the bundled frontend calls
POST /auth/browser/session/renew. The server returns the next renewal time so an HTTP timer works when WebSockets are blocked; the realtime server also asks for renewal before it closes a cookie-authenticated socket. The core uses the record revision to advanceExpiresAtand the physical TTL on the same key. SCS writes the same opaque handle in a fresh browser cookie slot with the new browser lifetime. Logout deletes the key and fences a concurrent renewal. The frontend coalesces browser renewal in one tab and coordinates tabs with a Web Lock. Human bearer access records use a fixedauth.access_token_ttl(15 minutes by default) and never slide. Their refresh credentials rotate atomically against one stable renewable-session record. A refresh in the final quarter advances itsauth.token_ttlwindow (90 days by default) without user action. Standard OAuth clients can omitrefresh_request_id; Chatto then creates a fresh request value and cannot return the exact lost pair for that rotation. Clients that use Chatto's extension persist a cryptographically random UUID version 4 for each rotation. The server stores a purpose-separated HMAC verifier of the recovery value. An exact extension retry can recover the same credentials after a lost response. The server also records the highest generation that a client used. Use of an access token counts only 30 seconds or more after the token was issued, because a browser can lose a recently stored pair when the operating system ends it. The server treats a stale refresh credential at or above that generation as a lost response and returns a new pair. A stale credential below it is reuse and revokes the whole renewable session. The bundled frontend coalesces bearer rotation within a tab, coordinates same-browser tabs with a Web Lock, persists authentication in an independently keyed per-server record, renews before expiry while the page is visible or once after an API authentication failure, and continues renewal at the end of the current session window. Permanent refresh failure keeps the current route and exposes explicit reconnect UI. If no chat data for that remote server is loaded, for example after a page load, its route shows the signed-out view with Log in to this server instead of empty server chrome. Transient failures retain the pair for retry. -
Privileged mode — a cookie session stores its fixed activation deadline in its mutable credential record. A bearer login stores the deadline in the stable renewable session so access rotation keeps it. Logout, revocation, session expiry, and deletion remove the activation. See FDR-045.
-
Password and account lifecycle revocation — sign-out of all devices, password resets, password changes, and account deletion advance the user's auth generation through durable
EVTuser events. Cookie sessions, renewable bearer sessions, and OAuth authorization codes store the auth generation they were issued against; validation compares the stored generation with the current generation and rejects credentials from older generations. A strict auth generation check first waits until the User Auth projection has applied the newest auth-generation events of the user. After a strict check accepts a user, the read-only first pass of request validation on that replica can read the local projection for the auth generation check window (60 seconds) (ADR-127). When no such check is in the window, the replica takes one replica proof for all users: it reads the newest position of each auth-generation event type from the stream leader and waits until its projections have applied them. The proof starts the same window for every user of that replica. Thus a replica whose projection has not applied a revocation can accept the revoked credential for a maximum of 60 seconds. Issuance, renewal, logout, refresh rotation, and fresh-auth and privileged-mode changes always use the strict check. The realtime credential timer uses the same check as request validation, so a realtime connection on such a replica can stay open for approximately two minutes: one timer interval and one window. Adding the first password to a passwordless account marks the password event to preserve existing credentials and does not advance auth generation. New external identity disconnect events also setpreserve_existing_credentials; historical disconnect events without this flag retain their revocation behavior during replay. Older replicas that do not support this flag can still revoke sessions, so all replicas must be updated for the new unlink behavior. Generation0remains a valid current generation for accounts with no revoking auth event. A credential is valid only when its stored generation is the current generation. All credential records that validation accepts were written after auth generations were introduced, so there is no legacy exception. A record at generation0is revoked when the generation changes. This includes a record that a login writes while a password reset is in progress. Until all replicas run this release, older replicas still apply the removed legacy exception. Pre-renewal bearer records are rejected. Password resets and password changes rely only on the auth generation. They do not delete stored credential records. The server deletes a stale record when a client presents it, or the record expires through its TTL. A logout that presents a stale credential does not terminate the user's current sessions. Each retained account-deletion event schedules a durable job that scansrenewable_session.*andsession.*by owner. It removes the deleted account’s renewable sessions, cookie sessions, and bearer access records. A worker on any replica can retry after a partial deletion. The scan reads every runtime credential on the server, so it is not on the password paths. -
Password reset tokens — reset links are backed by
RUNTIME_STATEHMAC-derivedpassword_reset.{hmac}records with a 1-hour per-key TTL. A separate HMAC-derivedpassword_reset_request.{hmac}reservation permits one delivered reset link per account every five minutes across all server replicas. Unknown addresses, accepted requests, and throttled requests receive the same generic response. Failed delivery cancels the unusable token and releases its matching reservation. Raw reset tokens, links, and account identifiers are never stored in reservation keys or written toEVTor backup archives. -
Server version handshake — the WebSocket
connection_ackpayload includes the server's version. The frontend uses this to detect deployed-version drift and prompt the user to refresh. -
Auth audit facts — successful cookie/provider logins, failed password login attempts, logout completion, bearer-token issuance/revocation, OAuth consent decisions, OAuth authorization-code issuance/exchange, registration-code issuance, email-verification-code issuance, password-reset link preparation, and password-reset completion are appended to
EVTfor admin audit-log inspection. Password resets and changes do not append one bearer-token revocation fact per session. The password event and the reset-completion fact record the revocation. Password-reset preparation is recorded before transactional email delivery so an audit-storage failure cannot leave a delivered but untracked credential; if delivery then fails, the runtime token is canceled even though the preparation fact remains. Payloads carry safe request metadata only: capped user agent, HMAC-hashed IP, and hashed identifiers where needed.
Design Decisions
1. Cookie-based sessions for same-origin
Decision: The embedded SPA authenticates through HttpOnly SameSite=Lax chatto_auth_<slot> cookies. SCS stores one stable opaque first-party credential handle through a JetStream adapter, while the authoritative typed runtime credential lives in RUNTIME_STATE with user ID, explicit expiry, source/request metadata, fresh-auth metadata, and auth generation. Each authentication change uses a fresh random browser cookie slot so late responses cannot replace a newer session. Each changed credential revision keeps a per-message TTL equal to its remaining explicit lifetime. Ordinary validation does not update storage or set a cookie. Programmatic login and registration routes return bearer credentials and never change browser cookies. Dedicated bundled-browser login and registration routes require same-origin JSON plus the browser-auth mode header and create only the cookie session. An operator can configure exact additional browser origins with webserver.allowed_origins; * is never valid for cookie authentication. External-identity creation explicitly selects one mode. The bundled flow does not create, store, or present bearer credentials for the origin server.
For the 0.5 upgrade only, a dedicated same-origin route migrates the typed cookie credential written by 0.4. It updates the existing record and handle instead of creating a second authority. The bundled frontend calls it once after an unauthenticated origin-cookie probe and then repeats that probe. Remove the route and client retry in 0.6.
Why: Cookies are the simplest mechanism for browser SPAs — the browser handles attachment, expiry, and HttpOnly protects against XSS-extracted tokens. Storing the server-side runtime credential in RUNTIME_STATE adds revocation for logout, password changes/resets, and account deletion while staying within Chatto's NATS-backed runtime-state model. WebSocket auth comes from the browser sending the cookie with the upgrade request. See ADR-017, ADR-036, and ADR-046.
Tradeoff: Non-browser clients cannot use cookies. The bearer token path exists for them. A separately hosted browser client must use Chatto OAuth instead of a direct-login bearer fallback. Development and deployment proxies must preserve a consistent public origin for cookie-authenticated routes.
1a. CSRF protection for cookie-authenticated writes
Decision: Cookie-authenticated writes require a CSRF proof unless they target test endpoints, webhooks, OAuth token exchange, or ConnectRPC programmatic API traffic. The server mirrors a readable chatto_csrf cookie for the SPA and accepts X-CSRF-Token only when it matches that cookie and verifies as a server-signed token for the current authenticated user generation. Every browser authentication mutation also requires JSON, an exact same-origin request, and the browser-auth mode header. Browser login, registration, and bearer cleanup use that proof before a session exists. Browser renewal and logout require the signed CSRF proof while a valid session exists. If logout receives only invalid session handles, the independent browser-route proof is sufficient to clear them because they carry no remaining authority. Programmatic auth routes do not change ambient browser cookies. Bearer-only requests skip the CSRF check.
Why: Cookie sessions are ambient browser credentials, so another site can try to submit state-changing requests with the user's cookie attached. Storing CSRF state inside the signed browser session cookie made concurrent cookie refreshes brittle. Signed stateless tokens keep CSRF independent of session-cookie rewrites while preserving the double-submit browser proof. ConnectRPC requests are exempt because browsers cannot submit application/proto or application/connect+proto via plain HTML forms.
Tradeoff: The frontend must attach the CSRF header for protected origin POSTs outside the exempt API paths. The token is not HttpOnly by design; it is not an auth secret, only a same-origin request proof paired with server-side signature verification.
2. Renewable bearer sessions for cross-origin
Decision: Cross-origin clients (multi-server frontend, CLI tools) authenticate with short-lived opaque access tokens and rotate a longer-lived refresh credential through /oauth/token. RUNTIME_STATE stores HMAC-derived session.{hmac} access verifiers and one renewable_session.{hmac} authority per login. Validation checks the fixed access expiry, stable session, client binding, and current user auth generation; deleting the stable authority rejects every access generation on its next API request or realtime connection that reads a current RUNTIME_STATE replica; a lagging replica can accept it for its lag (ADR-079). An auth-generation change rejects them within one minute in the worst case, on a replica whose User Auth projection lags (ADR-127). A realtime socket that already authenticated remains bounded by that access token's fixed expiry unless a separate termination signal ends it sooner.
Why: Cookies are scoped to one origin and SameSite=Lax blocks them on cross-origin requests. Tokens are origin-agnostic. We chose opaque tokens over JWTs because Chatto still resolves the current user and permissions server-side per request — JWT's "stateless validation" advantage gives little here, while opaque tokens give fast revocation and natural TTL via KV's built-in expiry. A deleted key is rejected when the RUNTIME_STATE replica that serves the read has the deletion, usually at once. An auth-generation change is rejected within one minute in the worst case (ADR-127). See ADR-024.
Tradeoff: Credentials stored in device-local browser storage are vulnerable to XSS; cookie sessions are not. The refresh credential increases what an attacker can renew, while short access lifetimes reduce the value of an access token stolen alone. Cross-origin clients accept this tradeoff in exchange for being able to authenticate at all. Operators must keep [core].secret_key stable across restores to preserve active bearer sessions.
3. Absolute bearer lifetime and renewable cookie windows
Decision: Human bearer access tokens have a fixed 15-minute default lifetime. Renewable sessions and cookie runtime credentials have a 90-day default window. Refresh rotation advances an active bearer session in the final quarter. Cookie sessions advance the same stable record and physical TTL in the final quarter. Why: Short access credentials bound theft without forcing an interactive OAuth round trip every few minutes. Automatic window renewal keeps active users signed in. Cookie validation does not write storage on each request. Renewal keeps one stable handle, which prevents concurrent requests from creating multiple valid replacements and lets logout fence renewal with one key delete. Login rotates the handle to prevent session fixation. Tradeoff: Clients must implement serialized rotation plus lost-response recovery. A client that is inactive for a complete session window must sign in again. An attacker that keeps exclusive control of a refresh credential can keep that bearer session active. See ADR-079 and ADR-081.
4. WebSocket auth at HTTP upgrade
Decision: For cookie clients, authentication happens at the HTTP upgrade handshake. The handler does not update the session or include an authentication Set-Cookie header in the 101 response. It ends the socket at the cookie renewal threshold. The bundled frontend calls the explicit browser renewal route before it reconnects. For bearer-token clients, the server validates the access token from the first RealtimeSubscribe message before it starts event delivery. For both human credential types, the server revalidates the exact credential before subscription and once per minute.
Why: The browser sends its cookie with the HTTP upgrade request, so the server can authenticate a cookie client before it accepts the socket. Browser WebSocket APIs cannot set an Authorization header, so bearer clients send the access token in the required subscription message. The server does not start event delivery before it validates that message. See ADR-017.
Tradeoff: Bearer-token WebSocket clients have to deliver the token during the realtime websocket handshake and reconnect when that access generation expires. Cookie clients also reconnect at their renewal threshold. The bundled client preserves its route, projection, and opaque resume cursor across both reconnects.
5. Per-request user resolution, no in-session caching
Decision: Even though the session stores a user ID, the user record is resolved from the current projections on every request and every realtime websocket handler. Why: Caching the user in the session would mean serving stale data (display name, roles) across requests. Users expect profile, role, and deletion changes to be immediate; projection-backed resolution gives the current view while keeping sessions small. Dataloaders batch within a single request to prevent fan-out. Tradeoff: Each request still performs server-side user and permission resolution. At Chatto's volume, this is far below noise.
6. Parallel bearer and cookie presentation
Decision: Bearer tokens are a parallel presentation path rather than a replacement for cookies. The auth middleware checks the Authorization header first and falls back to the cookie; both paths validate typed runtime credentials from RUNTIME_STATE and inject the same normalized request credential shape: presentation kind, user ID, and opaque handle.
Why: The embedded SPA keeps the safer same-origin cookie path, while multi-instance frontends and CLI tools can authenticate across origins. Both presentation shapes coexist while sharing runtime credential semantics.
Tradeoff: The HTTP edge still has to understand both bearer and cookie presentation.
7. Server version in connection_ack for deploy detection
Decision: The WebSocket connection_ack payload includes the server's binary version. The frontend stores it and prompts the user to refresh when a newer version is detected mid-session.
Why: Without it, users get subtle errors when a deployed schema change lands but their old client is still connected. A "the server has been upgraded, please refresh" toast handles it explicitly.
Tradeoff: The frontend has to handle the toast and the user has to act on it. Considered acceptable for the rare deployment-during-session case.
8. OAuth code exchange and client metadata
Decision: Chatto's OAuth authorization endpoint returns a short-lived authorization code to the client's validated callback; the client exchanges that code plus its client_id, callback, PKCE verifier, and optional exact resource at /oauth/token for a renewable bearer credential pair. Later refresh grants retain the same client and grant binding without reopening authorization. Browser clients identify themselves with CIMD. The server retrieves and validates their metadata without following redirects or reaching special-use network addresses, except that a local development server can retrieve metadata from another confirmed local destination. Native clients can use an HTTP loopback callback with a remote server. Literal loopback IP callbacks can select a run-time port; named localhost callbacks stay exact. Chatto Desktop has an exact built-in registration. Consent is remembered per user + stable client identifier + exact resource and scope set for non-local callbacks. Local callbacks require consent for each authorization. The client ID and grant remain attached to the authorization code, renewable-session authority, and access records. The web frontend relays the result from its same-origin callback to the main window. Installed Desktop receives the callback through the operating system.
Why: Keeping the remote server's own authorization UI visible makes password, passkey, and external-provider sign-in work without teaching the multi-server client each server's authentication methods or asking users to submit credentials to a lookalike client form. PKCE protects the code, while CIMD exact callback binding prevents a client or attacker from substituting another destination. The open CIMD model lets compatible apps connect without operator coordination while retaining identity for consent, audit, revocation, and policy.
Tradeoff: Browsers can block the secondary window when the flow is not started by a direct user action, while desktop hosts must provide and secure an equivalent native-window lifecycle. Every client must publish stable metadata and coordinate a second browsing context. Chatto performs a bounded outbound metadata request at authorization time. CIMD publication proves control of a client URL but is not an endorsement of its software. See ADR-071.
8a. Durable OAuth-client authorization inventory and policy
Decision: Every successful authorization of a stable client ID appends an authorization-recorded EVT fact. The projection retains its validated metadata, callback-origin set, first and latest authorization times, and distinct authorized-user set. Administrators can append policy changes for default, trusted, or blocked. A cold-replayed projection serves the admin list and the authorization hot path. Trusted is descriptive only. Blocked is enforced when authorization starts, before and after authorization-code issuance, at code exchange, before and after OAuth token creation, during token validation, and for established realtime connections. Unknown future policies use the same denied-access path so an older replica cannot bypass a newer policy during a rolling upgrade. After initial credential validation, each socket atomically checks the current projected policy while registering a process-local watcher; every replica's projection closes the matching watchers when it observes a blocked or unsupported policy. Applying a block scans renewable_session.* and deletes matching stable authorities. Existing session.* access records remain for TTL cleanup but validation rejects them once their authority is absent. Per-client EVT aggregate subjects contain a SHA-256 digest of the client ID rather than its URL.
Why: Successful authorization is the point at which a client has actually gained access and is worth showing to administrators. Durable facts preserve that inventory and policy across restarts and replicas without allowing arbitrary CIMD probes to fill it. Checks around both sides of runtime-credential writes close the races where another replica blocks a client during issuance. Projection-backed socket watchers extend the same durable boundary to already authenticated transports without disconnecting the user's first-party or other-client sessions. Hashing the aggregate ID keeps URL punctuation and path data out of NATS subjects while the event payload retains the recognizable stable ID needed by the projection.
Tradeoff: Authorized user IDs are retained privately by the projection to compute a distinct count, although the admin API exposes only that count. Blocking requires a bounded global token scan in addition to the constant-time projection check; cleanup is best-effort because validation and realtime projection watchers independently enforce the durable policy. The watcher registry is process-local acceleration rebuilt naturally as sockets reconnect, while EVT remains authoritative. Trust does not currently unlock extra behavior.
8b. External provider registry and identity links
Provider account creation page: The page title is "Join {server}". A profile preview card shows the new account as other members will see it: the avatar, the display name, and the username. The card changes when the user edits the form. Below them, the card shows the provider of the sign-in and the verified email, when the provider supplies one. The avatar is the provider profile image, when the provider supplies one. Otherwise, the card shows initials. The browser does not contact the provider for the avatar. The pending flow gives the client a signed remote image URL (ADR-128). The server fetches the provider image, resizes and re-encodes it, and caches the result. Account creation fetches the avatar again and stores it as a managed avatar asset; the server does not keep the provider URL with the account. When the provider manages the username, the username field shows the assigned username and is disabled. The field shows the provider icon, and a short hint tells the user that the sign-in provider sets the username. The client then sends an empty username, and the server ignores any username that a client sends for a managed provider: it assigns the name from the verified provider claim. The display name field then shows the username as its placeholder, because an empty display name uses the username. A link for an existing account and a Cancel action follow the form.
Existing-account sign-in from provider confirmation: The confirmation page preserves its pending flow when the user chooses an existing account. After sign-in, the user confirms linking to the displayed account. The client starts the existing authenticated link operation, which binds the provider flow to that account, and continues provider authorization in the same window. A create token does not authorize linking. The client cancels the old create token after the server accepts the link start; if cancellation fails, the token expires.
The original return path survives this sequence. A saved app return path cannot replace the explicit continuation. Successful linking returns to the original return path. Cancellation returns there without an error. A failed link returns there with its error code. Provider sign-in denial and identity-exchange failures show the error on the login page, which keeps the saved return path. The external provider receives another authorization request, including the user's IP address, as it does for linking from account settings.
Identity-link window: The /sso/link page shows each step of a link in the popup as a full sign-in page, without the chat shell. A signed-out window first shows the compact sign-in pages and then returns to the link. The page does not contact the provider until the user selects Continue with {provider}. When the server requires fresh proof, the page then asks for the current password. Then it sends the window to the provider. The provider callback returns to the account settings URL with link parameters, which forwards to the same page. An older replica can serve the callback during a rolling upgrade, and it knows only that URL. After a successful link, the page tells the account settings page on its origin and closes the window. Each error has Close window. When a new attempt can succeed, the error also has Try Again, which starts the link again. Account settings on the origin ask for the password in their own dialog before they open the popup. For a remote server, the client opens the remote server's account settings URL with link parameters, because older servers have no /sso/link page. Newer servers forward that URL to /sso/link. The page can read before the origin's first realtime snapshot. That snapshot discards responses in flight, so the page repeats a discarded read once.
Legacy OIDC links: Older UserOIDCSubjectLinked events contain only a
subject hash. A verified OIDC sign-in that matches the account fills in the
issuer, subject, and provider metadata, even without group-role mappings or a
groups claim. Completion uses the existing identity-linked event, checks that
the hash-only link still exists inside user OCC, and waits for the projections.
Retries do not add duplicate events, and a concurrent unlink is not undone.
Until that sign-in occurs, a hash-only link does not count as an enabled
alternative when another provider is disconnected, because its issuer is unknown.
Decision: External login providers are configured as repeated [[auth.providers]] entries with stable local IDs, curated provider types, labels, client credentials, optional scopes, optional email-scope requests, and configurable auto-provisioning. OIDC clients may be confidential or public; a provider configured with {webserver.url}/oauth/client-metadata.json uses Chatto's built-in CIMD document and no client secret. OIDC verification remains on go-oidc; OAuth-only providers use Goth for authorization-code exchange and normalized user fetching. Linked and disconnected identities are durable EVT facts on the user aggregate. Pending account-creation confirmations live in RUNTIME_STATE as HMAC-derived external_identity_create.{hmac} records with short TTLs. The confirmation API also accepts previously issued external_identity_link.{hmac} records until they expire. Bearer-authenticated provider linking first creates a one-time external_identity_link_start.{hmac} handoff token, which the target server consumes before starting the browser redirect to the external provider. After verifying the provider response, the callback commits the identity link to the bound account and returns to the identity-link window page, which closes the popup. No second link confirmation is required. Users may disconnect linked provider identities from account settings, but Chatto refuses to remove the last enabled sign-in method, including for accounts with stored passwords when password login is disabled. The account and operator APIs share the same configuration-aware check inside the user OCC loop. ListExternalIdentities reports per-identity disconnect_eligibility: unspecified, allowed, or last enabled sign-in method; the mutation checks again, so a stale hint cannot permit a lockout. The browser-only provider redirects remain HTTP routes, while confirmation uses chatto.auth.v1.ExternalIdentityAuthService and authenticated management uses chatto.api.v1.MyAccountService.
Why: A provider list lets operators expose more than one login option without hard-coding a single OIDC provider. Keeping the provider ID stable gives OAuth-only providers a local issuer namespace. OIDC uses the verified issuer URL as the durable namespace because the issuer owns subject uniqueness; the configured provider ID is event-time metadata and can change without invalidating existing OIDC links. Matching by issuer/provider plus subject survives provider-side email changes and avoids account takeover through recycled or unverified email addresses.
Tradeoff: Existing [auth.oidc] TOML configuration is not accepted by this shape; deployments should use [[auth.providers]]. Legacy CHATTO_AUTH_OIDC_* environment variables are still accepted as a compatibility bridge for one OIDC provider. Account creation for new external identities requires explicit confirmation and uses capability-scoped tokens. Explicit linking uses the authenticated link-start request as consent and completes after provider verification. Email scopes are opt-in with request_email = true; OIDC providers can run with the default email-less openid profile request, in which case account creation, linking, and login still use issuer plus subject while password reset by email remains unavailable until the user verifies an email.
Provider sign-in from the login and registration pages opens a separate window, including on the origin server. Its callback reports completion to the opening client through a transaction-specific channel. The opening client verifies the cookie session with the server, refreshes authentication, and resumes its return path. The callback sends no session credential. Closing or blocking the window leaves the original form available to try again. Provider sign-in within an existing remote OAuth authorization window continues in that window.
When users link an identity on the origin server, Account settings starts the link and shows a password dialog there if the server requires fresh authentication. After the server accepts the request, the provider opens in a separate window. If the browser blocks the window, the user can open it with another click. For a remote account, Account settings first opens the account’s server in a separate window. The server checks that the signed-in account matches the selected account, then performs any required current-password check and continues to provider authorization. The verified callback completes the link without a second Chatto confirmation. If sign-in is required, the selected provider and account remain in the return path. Passwords are entered only on the server that owns the account. Delegated OAuth tokens do not gain fresh-auth status.
While the separate window is open, the original client checks the selected provider's link status on the account’s server. When the server confirms that the provider is linked to the selected account, the original client updates account settings. The separate window returns to account settings with a completion marker, checks the account and provider link, and closes itself. It also tells other Account settings pages on the same origin to refresh that account. This lets the original page show the result when the provider isolates its window. This preserves window isolation: the provider cannot access the original window. Users do not need to return to the original window or reload it. Periodic checks stop when the link is confirmed, the window closes, the settings page closes, or the account or session changes. Returning to the original window and closing the separate window also trigger a refresh. Closing the window alone does not mean that linking succeeded. This flow adds periodic account reads while linking, uses the existing account APIs, and needs no additional server-side operation state or cross-origin completion messages.
8c. Separate device-local catalogue and server sessions
Decision: Known server metadata and device-local Chatto sessions have separate state owners. Cross-boundary sign-out commands run through one client account coordinator. Authentication is persisted under an independently keyed per-server record, while the legacy combined browser-storage record remains a compatibility adapter and former catalogue provenance values are ignored during migration. Why: A server can be known while signed out, while catalogue metadata and credentials have different lifecycles. Authling stores identity-provider state only and does not synchronize the catalogue. See ADR-074. Tradeoff: The frontend retains a composed server view and combined persisted shape during migration. Every combined-record write must merge the authoritative per-server authentication fields so stale tabs cannot restore a rotated generation; the adapter and coordinator require explicit interleaving tests.
8d. Operator-controlled password login
Decision: Password sign-in is a deployment configuration capability, separate from whether an account retains a password. Direct registration depends on it. Public discovery reports the capability before authentication, while the password-login endpoint remains authoritative and rejects disabled requests before inspecting credentials. When auth.direct_login = false, the server also rejects user password creation, changes, reset requests, and reset completion. Account settings keeps the password controls visible but disabled, with a notice that the server uses SSO. Stored password hashes and explicit operator recovery remain available. Existing runtime credentials are not revoked when the setting changes.
Direct registration requires direct login. While auth.direct_login = false, the server treats direct registration as disabled: discovery reports direct_registration_enabled = false, the registration endpoints reject requests, and startup logs a warning if auth.direct_registration is still true. Without this rule, a user could create a password account that cannot sign in or reset its password. The reverse combination stays valid: direct login without direct registration lets existing accounts sign in while self-service sign-up is closed.
Sensitive account operations accept a fresh first-party SSO session within the existing 30-minute window. On SSO-only servers, a stored local password cannot replace fresh authentication. Delegated OAuth sessions do not gain fresh-auth status; users complete these operations in the account-owning server's account settings.
When freshness expires, a user without password proof re-verifies through an OIDC provider that is already linked to the account. The client opens /auth/providers/{id}/reverify with a redirect path. The provider start accepts only a navigation with Sec-Fetch-Site: same-origin from a browser with a valid cookie session of a user who has that provider linked, so only a page of this server can start it. It stores the user ID, the start time, and the OAuth state under re-verification keys in the signed provider-flow session; no other server-side record exists. The dedicated route and state key make the flow fail closed during a rolling upgrade: an older replica has no such route, and its callback finds no sign-in state, so it never runs the attempt as a sign-in that could replace the session. The authorization request sends prompt=login and max_age=0. The callback requires an auth_time claim at or after the start time, an identity linked to the same user, and a cookie session of that user in the browser. It then marks that cookie session fresh with method external_identity and source external_identity_reverification. It never creates or replaces a session. An identity of another account, a missing or earlier auth_time, or a browser without that user's session returns an error code and leaves freshness unchanged. A rejected start returns to the redirect path with error=reverification_failed. Bearer credentials cannot re-verify. ListExternalIdentities reports reverification_available for each provider that can do this for the caller.
Before the browser leaves for the re-verifying provider, Chatto explains the step: to link or disconnect provider X, the user first signs in again with a provider that is already linked, and then Chatto continues. Users would not otherwise expect a link of one provider to open another provider's sign-in. The user starts the re-verification with a button for each provider that can re-verify. The action resumes after the round trip. For a link, Account settings opens the identity-link window on the explanation (reverify=required), and the window shows it also when its own link start needs a recent sign-in. The provider returns to the window with reverified=1, and the window starts the link by itself. For a disconnect, Account settings shows the explanation in a dialog. The return path carries the identity, and Account settings shows the disconnect confirmation again, so that a crafted URL cannot disconnect an identity without a click. A repeated freshness failure after a successful re-verification shows the sign-out fallback instead of another round trip. Password servers keep the inline password prompt for accounts with a password.
Why: SSO-only deployments need to close the local password entry point without migrating accounts, deleting fallback credentials, or coupling sign-in policy to account-creation policy. Discovery lets compatible clients present only valid choices, and endpoint enforcement protects against older or custom clients. Re-verification is limited to OIDC because only OIDC can force a new provider sign-in and prove it with auth_time. AT Protocol and OAuth-only providers can let an existing provider session pass without a new sign-in, which does not prove that the user is present. The same-origin start and the cookie-session check stop a holder of a copied session from sending the user a start link and gaining freshness from the user's sign-in. A callback cannot prove that it runs on the device that holds a bearer token, so bearer clients cannot re-verify. Because only same-browser cookie sessions re-verify, the browser's own session carries the binding, and the flow needs no new RPC or stored handoff record.
Tradeoff: Older clients do not understand the discovery capability and can still display a form that the server rejects. Operators must configure every serving replica consistently and retain a tested provider or recovery path to avoid locking signed-out users out. Users whose only linked providers are AT Protocol or OAuth-only cannot re-verify in place; they must sign out and sign in again. Browsers without Sec-Fetch-Site (Safari before 16.4) cannot re-verify. Third-party bearer clients send users to the account's server for these operations.
8e. Origin-owned password-manager discovery
Decision: Each Chatto server publishes a temporary redirect from the standard well-known change-password URL to its own account settings. The redirect is always available and does not depend on password-login or registration configuration. A standalone client host does not publish this redirect.
Why: Password managers associate a saved password with the server origin. Account settings support both password changes and the addition of a first password. The signed-out return flow keeps the destination through local or external-provider sign-in. A standalone client does not own the server credential.
Tradeoff: A password for an external identity provider belongs to that provider's origin. The Chatto redirect cannot manage it. Reverse proxies must forward the well-known path to Chatto.
9. EVT audit facts without raw secrets
Decision: Authentication workflows append durable audit facts to EVT, but token bodies, verification codes, links, passwords, auth codes, raw IP addresses, full redirect URIs, and raw login/email identifiers stay out of the event log. Source IPs are HMAC-hashed before persistence; forwarded client-IP headers affect attribution only when the direct peer matches an explicit webserver.trusted_proxies IP/CIDR entry, otherwise the direct peer is hashed. OAuth consent grant/deny facts store the canonical callback origin or native callback scheme plus validated client ID, display metadata, optional protected resource, and scopes in plaintext so users and administrators can recognize approved client applications and grants. Successful user-scoped facts live on evt.user.{userId}; anonymous/server-wide facts such as registration-code issuance and failed login attempts live on evt.auth.server.
Why: EVT is Chatto's durable audit trail as well as the event-sourcing stream. Operators need to answer "what happened?" for sensitive workflows, but the audit log must not become a secondary secret store.
Tradeoff: Failed-login and unknown-code exchange attempts intentionally do not reveal whether the submitted identifier or code matched an account. Admins get timing, request metadata, and stable hashes for known-user workflows, not raw credential guesses.
OTP guardrails: Registration and authenticated email-verification OTPs share RUNTIME_STATE email_otp.* records. By default, throttling is enabled and each challenge allows at most ten successfully delivered codes and five wrong-code attempts in its 30-minute TTL window; operators can tune or disable these throttles through auth.email_otp / CHATTO_AUTH_EMAIL_OTP_*. Exhaustion blocks fresh codes for that challenge until TTL. If email delivery fails, the just-created OTP record is cancelled and does not count against the issued-code limit.
10. Short-lived auth codes in runtime state
Decision: Pending OAuth authorization browser flows, OAuth authorization codes, external-identity link-start handoffs, and pending external-identity confirmation flows live in RUNTIME_STATE as HMAC-derived records with short per-key TTLs and are deleted on successful consumption/exchange/confirmation. Pending OAuth authorization flows use oauth_authorize.{hmac} with a 15-minute TTL and include the optional exact resource and normalized scopes; the browser session carries only the opaque lookup token. OAuth authorization codes use grant.{hmac} with a 5-minute TTL and preserve the same grant. External identity confirmations use capability-scoped external_identity_create.{hmac} and external_identity_link.{hmac} records with a 15-minute TTL. Provider link-start handoffs use external_identity_link_start.{hmac} with a 15-minute TTL and are consumed before provider authorization begins.
Why: Authorization codes and external-identity tokens are short-lived runtime credentials. They need restart survival and TTL enforcement, but they are not domain history and must not be copied into EVT.
Tradeoff: Pending browser authorization now requires shared runtime storage even before a code is issued. The returned authorization code and browser behavior remain opaque and unchanged for clients, but stored keys are not human-recoverable from a backup without [core].secret_key.
Permissions
Authentication itself doesn't have a permission gate (you're either authenticated or not). After authentication, downstream actions are gated by the permissions described in FDR-001.
Related
-
Action availability: ADR-120 defines common conventions and action-specific states for username choice, username and password changes, account deletion, and identity disconnection. Commands still enforce all rules.
-
ADRs: ADR-017 (cookie-session auth for WebSocket), ADR-024 (opaque bearer tokens for cross-origin auth), ADR-025 (multi-instance client architecture), ADR-036 (runtime state in
RUNTIME_STATE), ADR-046 (typed runtime credentials), ADR-067 (Electron desktop packaging), ADR-071 (CIMD-identified open OAuth clients), ADR-074 (device-local frontend server catalogue), ADR-079 (renewable bearer sessions), ADR-081 (explicit expiry for mutable runtime credentials), ADR-085 (user-scoped MCP integration) -
FDRs: FDR-001 (Roles & Permissions), FDR-018 (Account Lifecycle), FDR-034 (Chatto Desktop), FDR-036 (Invitation Codes), FDR-043 (Model Context Protocol Integration), FDR-045 (Privileged Mode), FDR-058 (AT Protocol Sign-In)
Open Questions
- A "revoke all tokens for this user" admin affordance. Core supports revoke-all for account deletion, but there is no dedicated admin UI action yet.