Architecture Decision Record
ADR-097: Multi-Device Refresh Sessions (Hashed, Rotating, Per Device)
Status
Accepted (2026-08-26). Supersedes the storage model of ADR-050 (one plaintext refresh-token column on the user row); the rotation and reuse-detection policy that record decided is kept and generalized to a per-device set.
Revised 2026-08-27 (v1.164.0): the model gains the parts that make a per-device session
visible and finite. An access token now names the session that issued it (a sid claim), a user
can list and revoke their own devices through two endpoints and a shared page, and a retention sweep
ages the table out. Three of this record's original trade-offs are retired as a result, and the
sweep introduces one of its own. Every addition is additive: no consumer signature changes.
Revised 2026-09-01: rotation is a claim the store arbitrates rather than an in-memory revoke, so
two requests presenting the same live token cannot both walk away with a successor: the one that
loses the claim is answered exactly like a replay. The sessions page carries a sign-out-everywhere
action beside its per-device revokes.
Revised 2026-09-07 (a password change or reset revokes the whole session family, through a
refresh-session store the two handler bases require).
Revised 2026-10-01 (current-state sections re-anchored; the password handler bases require the
store).
Revised 2026-10-06: the session workflow now lives in the sealed AuthSessionIssuer behind a breaking
AuthenticationServiceBase constructor change (1.218.0), a signed-out or cap-evicted token no longer
revokes the family, an already-revoked revoke-by-id answers 404, and both page revokes confirm first.
Revised 2026-10-07: the reuse grace window this record originally rejected is adopted (1.233.0):
a token rotated less than RefreshSessions:ReuseGraceSeconds ago (default 10) answers 409
Auth.RefreshSuperseded and revokes nothing, on both the lookup path and the lost rotation claim,
so the 2026-09-01 note that a lost claim is answered exactly like a replay now holds only past the
grace and only when the row was not signed out or cap-evicted.
Revised 2026-10-21: account erasure revokes (as AccountDeleted) and anonymizes the account's
sessions when the host passes the session store, a password reset persists the session revocation
before it applies the password while a password change saves the revocation before its own password
save (atomic with the password only on a single data source), an administrator's read-only sessions
view sits over the same store, and anchors are refreshed after 1.250.0.
Revised 2026-10-25: a token already swept by reuse detection fails alone instead of re-revoking the
user's newer sessions (1.261.0), because the flagged row is dead by construction and re-revoking
bought no theft containment, only an extra sign-out per stale device.
Revised 2026-10-26: anchors refreshed after 1.261.0.
Revised 2026-11-02: opt-in lost-response recovery (1.273.0, RefreshSessions:LostResponseRecoveryMinutes,
default 0 = off) rotates a never-presented successor instead of revoking the family (see Revision below).
Amended 2026-11-07: sign-in history. A nullable SignInId groups a rotation chain into one sign-in,
users and administrators read the last RetentionDays of sign-ins (ended ones included, newest 50)
through two endpoints and a shared table, and a reuse revocation logs a Warning without IP or user
agent. One nullable column and one index per host that maps the table (see Amendment (2026-11-07)).
Revised 2026-11-23: a native client's device metadata is recorded per session (RecordDevice,
PUT auth/sessions/current/device, seven nullable Device* columns and a seventh summary field,
1.298.0), POST auth/revoke/current is the everyday single-device sign-out (1.295.0), the table
carries three indexes, the Cosmos mapping citation names CosmosDbContext, and anchors are
refreshed after 1.298.0.
Context
ADR-050 stores a user's refresh token as a single nullable RefreshToken string plus its
RefreshTokenExpiry on the app's User aggregate. That model settles rotation and reuse detection
correctly and costs three things it names but cannot fix from inside itself.
The token is a bearer credential kept in plaintext. Anything that can read the Identity database (a backup, a support query, a log of a row dump, a compromised read replica) can mint access tokens for any user who is signed in, because the stored value is exactly what the client presents.
There is one slot per user, so a session is an account-wide fact rather than a device fact.
Signing in on a phone overwrites the laptop's token, and the laptop's next refresh presents a value
that no longer matches, which the same record's reuse rule then treats as theft: the second device
is not merely signed out, it is signed out through the compromise path. ADR-050 records this as a
trade-off and names "a per-device or per-session token table" as the thing that would fix it
(050-jwt-refresh-token-rotation.md:211-213). The contract itself now says the same thing from the
other side: refresh tokens are "deliberately absent" from IAuthUser, with the reason written into
the interface (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IAuthUser.cs:9-14).
And a single column has no history. Rotation overwrites, so the row cannot say what replaced what, who signed out, when, or from where. A replayed token and an expired one are indistinguishable after the fact, which leaves an operator with nothing to look at after a reported account compromise.
Decision
Refresh tokens become rows in their own table: one row per signed-in device, hashed at rest, chained on rotation.
RefreshSessionis a flat framework record, not an aggregate.MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/RefreshSession.cs:46(asealed classimplementingIAnonymizable) carriesId,UserId,TokenHash,CreatedAt,ExpiresAt,RevokedAt,ReplacedByTokenHash,ReasonRevoked, the optionalIpAddress/UserAgent, and seven optionalDevice*members a native client reports for its session (:137-162, each capped atDeviceFieldMaxLength= 256,:64). LikeOutboxMessageandAuditTrailEntryit has no audit stamps, no soft-delete flag and no concurrency token, and a global query filter hiding a revoked row would break the reuse check that depends on finding it (:28-36). Rows change in exactly three ways (:30-32):RecordDevice, which stores the reported device metadata (:273);Revoke; andAnonymize, which nulls the[Pii]-markedIpAddressandUserAgent(:122,:129) and the seven[Pii]Device*members (:137-162) for an erasure request (:339-349; account erasure calls it on every row the account holds,.../Application/Auth/RefreshSessionRevocation.cs:89) while keeping the hashes, timestamps and revocation chain, so reuse detection still works on an anonymized row (:39-43). A rotation successor copies the device metadata, so a native client reports it once per sign-in (:252-258).- The store holds a hash, never a token.
RefreshSession.HashTokenis SHA-256 over the token's UTF-8 bytes, hex encoded in upper case (:301-305), andCreatehashes on the way in so the plaintext never reaches a property (:211, factory at:184). The digest is deliberately unsalted and deterministic, because every lookup is by hash: a salted digest could not be found (:14-16). The encoding is part of the contract rather than an implementation detail, and the method's remarks give the byte-for-byte SQL Server equivalent,CONVERT(char(64), HASHBYTES('SHA2_256', CONVERT(varchar(max), Token)), 2), so a consumer's data migration can reproduce it (:295); the digest width is a constant the mapping reads (:49). - Rotation leaves a walkable chain.
Revoke(revokedAt, reason, replacedByTokenHash)records the successor's hash (:315, the link at:327), and refuses to revoke an already-revoked session rather than overwriting the first reason and instant recorded (:317-323). The five reasons are constants on the entity:Rotated,SignedOut,ReuseDetected,SessionCapExceededandAccountDeleted(:67-79), the last written only by account erasure. - The rotation write is a claim the store arbitrates, not a mutation.
IRefreshSessionStore.TryRotateAsyncis the one write in the contract that is not a revoke on a tracked instance: two requests presenting the same live token both read an un-revoked row, so a check-then-act rotation would mint two successors from one token and the presented row could never fire reuse detection again (.../Application/Auth/IRefreshSessionStore.cs:13-14, the return value argued at:154-160). The shipped EF store claims the row with a conditionalUPDATE ... WHERE Id = @id AND RevokedAt IS NULL, so the database arbitrates: the winner affects one row, the loser affects none and writes nothing (.../Persistence/Auth/EFRefreshSessionStore.cs:321-322, argued at:289). The update and the successor insert share one transaction, so a loser cannot observe a half-finished rotation (TryRotateAsyncat:304). The interface's default implementation keeps the revoke-add-save shape, which is atomic only per instance and is all an in-memory or test store can offer (IRefreshSessionStore.cs:177). The caller that loses the claim re-reads the row as the database now holds it, throughIRefreshSessionStore.FindByIdUntrackedAsync(IRefreshSessionStore.cs:141; the EF store'sAsNoTrackingoverride atEFRefreshSessionStore.cs:277-279), and is answered by what that row says (RotateSessionAsync,.../Application/Auth/Sessions/AuthSessionIssuer.cs:510, the losing branch at:537-565): a sign-out, a cap eviction or an earlier reuse sweep of the same row fails that request alone (:546-552), a rotation less thanReuseGraceSecondsago answers409 Auth.RefreshSupersededwith nothing revoked (:554-557), and anything else gets the replay answer, every live session of that user going andAuth.InvalidRefreshTokencoming back (:559-564). The interface default of the re-read returns null (IRefreshSessionStore.cs:141), which lands on that last branch, so a store that does not override it keeps the conservative family revoke. - Reuse detection revokes the live family, and only on the right signal. The session workflow
lives in the sealed
AuthSessionIssuer(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:54), whichAuthenticationServiceBase<TUser>(.../Application/Auth/AuthenticationServiceBase.cs:74) takes as a requiredIAuthSessionIssuerconstructor parameter (:79): the base decides who is signed in, the issuer decides what they are handed (:50). The issuer resolves a presented token to its session (ResolveRotatableSessionAsync,AuthSessionIssuer.cs:398-462) and separates the rejections, which answer the caller with the sameAuth.InvalidRefreshTokenfailure except for the rotation race below. An unknown hash (or one belonging to another account) fails alone (:413-416), because revoking the family on it would let anyone holding one of a user's expired access tokens sign them out everywhere by posting a random string. A revoked row splits by why it was revoked (:418-457): one already rotated away (it carries a successor hash or theRotatedreason) has come back, which is the reuse signal that revokes every live session the user holds (IsReuseSignalat:579, the family sweepRevokeFamilyOnReuseAsyncat:666, called at:454), while one that was signed out, evicted by the session cap or already swept by an earlier reuse event only lost its session, so that request fails alone and the user's other devices keep working (:420-427). A row flaggedReuseDetectedis dead by construction: re-revoking on it would only sign the user out of the sessions they re-established, on demand of anyone holding a swept token, and a genuine replay lands on a rotated row instead (IsReuseSignal,:579). Any other or missing reason,AccountDeletedincluded, counts as the reuse signal, the conservative answer for a row the code does not recognize. An expired row is an ordinary end of life: that device re-authenticates and the user's other devices keep working (:459-461). The cases are argued together in the summary above the method. - A rotation race inside the reuse grace revokes nothing (since 1.233.0). A row revoked as
Rotatedless thanRefreshSessions:ReuseGraceSecondsago (default 10,[Range(0, 300)],.../Application/Auth/RefreshSessionSettings.cs:97-98, the trade-off argued at:82-96) is a sibling request (another tab, or the same browser served by another replica) that rotated the token a moment ago, so instead of the family revoke it answers409 ConflictwithAuth.RefreshSuperseded(RefreshSupersededError,AuthSessionIssuer.cs:376) and nothing is revoked, on the lookup path (:429-434) as on the lost rotation claim above. The predicate (IsWithinRotationGrace) admits only theRotatedreason, and a row already flagged as reuse never reaches it:IsReuseSignalfails that request alone first, however recent. A grace of0restores the original answer for every rotated row; it does not restore the family revoke for a lost claim whose row was signed out, cap-evicted or already swept by reuse detection, which fails alone at any grace (:546-552, pinned byAuthSessionIssuerReuseGraceTests.cs:98).AuthControllerBase's refresh action documents and declares the 409 (AuthControllerBase.cs:158-161,:169), and the clients treat it as transient:CookieSessionRefresherkeeps the cookie (.../MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:117, only 400, 401 and 403 classified as rejected byClassifyFailureat:122),DirectApiTokenRefreshernever reports it as signed out: it returns the newer stored pair when another refresh in the same process already stored one, and reports unavailable with the stored pair untouched otherwise (.../MMCA.Common.UI/Services/Auth/Tokens/DirectApiTokenRefresher.cs:25, the 409 branch at:85-87,ReadSupersededOutcomeAsyncat:111, documented at:108), andAuthUIService.TryRefreshTokenAsynckeeps the stored tokens on that outcome (.../MMCA.Common.UI/Services/Auth/AuthUIService.cs:167). - A lost rotation response can be recovered (opt-in, since 1.273.0). A mobile client can lose the
response to a refresh that succeeded on the server, for example when the app is suspended
mid-request or the network drops. It still holds the old pair and presents it again minutes later,
past the grace. With
RefreshSessions:LostResponseRecoveryMinutesset (.../Application/Auth/RefreshSessionSettings.cs:122-123,[Range(0, 1440)], default0= off, the trade-off argued at:101-121), that presentation is recovered instead of revoking the family. The conditions are checked inFindRecoverableSuccessorAsync(AuthSessionIssuer.cs:619): the presented row was revoked asRotatedno more than that many minutes ago, and its successor (found byReplacedByTokenHash) belongs to the same user and is still live. A live successor means nobody ever presented it. The issuer then returns the successor (:436-445), the caller's normal rotation claim rotates it, and a Warning records each recovery (:443). A successor that is used or expired, or a presentation past the window, keeps the family revoke (:454). A sibling that has just recovered the same stale token answers 409 (:447-452), so only one pair is issued. The cost is that detection is delayed by one refresh, never lost: a thief replaying inside the window while the owner is idle gets a session, and the owner's next refresh then presents a rotated-away successor, which revokes the whole family, the thief included. - Sign-out has both scopes.
RevokeTokenAsync(userId, refreshToken)(AuthenticationServiceBase.cs:476) delegates toIAuthSessionIssuer.SignOutAsync(:487;AuthSessionIssuer.cs:193), which signs out one device when the token resolves to a live session of that user; an unknown token, another account's token or an already-revoked row leaves the caller unidentifiable, so the request degrades to signing every device out rather than reporting success for a revocation that reached nothing.RevokeAllSessionsAsync(userId)is the explicit everywhere case, for a password change, an admin lockout or a "sign out everywhere" action (AuthenticationServiceBase.cs:493, delegating toIAuthSessionIssuer.SignOutEverywhereAsyncat:503;AuthSessionIssuer.cs:222; the contract states both scopes at.../Application/Auth/IAuthenticationService.cs:60-63,:69and:74-77,:81).AuthControllerBase'sPOST auth/revokecarries no body and signs out everywhere (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:189-207, call at:201); its own summary names it the explicit "sign out of all devices" action (:183-188). The everyday sign-out isPOST auth/revoke/current(since 1.295.0,MMCA.Common/CHANGELOG.md:404;AuthControllerBase.cs:219-237), which names the device through the access token's ownsidclaim rather than a body: it revokes that session throughRevokeSessionByIdAsync(:230-231), falls back to every session for a token minted beforesidshipped (:232), and answers 204 when the session is already revoked or gone (:234, reasoning at:214-217), because a sign-out is never a failure to show the user. It is[NonIdempotent]and[Authorize](:220-221), and the shared UI client's sign-out posts it (.../MMCA.Common.UI/Services/Auth/AuthUIService.cs:120-132). Since 2026-08-27 a further scope ships beside those, revoke-by-session-id, so a consumer no longer has to write its own action for per-device sign-out from a device list. - A configurable cap bounds the table without ever failing a login.
RefreshSessions:MaxActiveSessionsPerUser(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionSettings.cs:35, default 10,[Range(1, 1000)]at:34, reasoning at:27-33;AuthSessionIssuerrequiresIOptions<RefreshSessionSettings>(AuthSessionIssuer.cs:57) and reads the cap straight from the bound settings (:707), and because the issuer is sealed (:54) the bound value is the only source) is enforced before a new session is staged (:490): while the user is at or over the cap, the oldest live session is revoked with reasonSessionCapExceeded(EnforceSessionCapAsync,:705). Ordering isCreatedAtthenId(:710-711, matched by the store's own ordering,.../Infrastructure/Persistence/Auth/EFRefreshSessionStore.cs:70-71), so two sessions opened in the same clock tick still evict deterministically. Expired-but-unrevoked rows do not count against the cap: they authenticate nobody (EnforceSessionCapAsync,AuthSessionIssuer.cs:705). - IP and user-agent capture is optional and informational.
AuthControllerBasereads them from the connection and the request headers (AuthControllerBase.cs:64,:70) and passes them into login, registration and refresh (:87,:114,:175), and the entity truncates them to their column widths of 45 and 512 (RefreshSession.cs:214-215, widths at:52,:55). Neither value is ever part of a validation decision, so a mobile client changing networks is not signed out (:118-120). - Mapping is opt-in per data source.
RefreshSessionSettings.Enableddefaults tofalse(RefreshSessionSettings.cs:25, reasoning at:14-24), so a host that has not opted in keeps the model it had and its migrations never see the table.ApplicationDbContextmaps it only whenEnabledis true and the context instance's physical source name equalsRefreshSessions:DataSourceName(defaultDefault,RefreshSessionSettings.cs:52, reasoning at:41-49), the same two-part gate the scheduler table uses (.../Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:424-427, rationale at:104-113, applied at:575and:1048-1056). That keeps the table in exactly one database in a host that splits its modules across sources, instead of putting an emptyRefreshSessionstable in every module's migrations. A host with its own context class calls the publicApplyRefreshSessionConfigurationdirectly (.../Persistence/Auth/RefreshSessionModelBuilderExtensions.cs:39, the opt-in-unlike-the-outbox argument at:8-14); Cosmos never reaches either path, because its context overridesOnModelCreating(.../Persistence/DbContexts/CosmosDbContext.cs:119). - The shipped store routes to that same database.
EFRefreshSessionStore(.../Persistence/Auth/EFRefreshSessionStore.cs:34) resolves the physical source through the entity registry first (a consumer that ships a real entity configuration for the session entity is routed like any other entity), falling back to the source named byDataSourceName(ResolveDataSourceKey,:352-357, reasoning at:15-22), and is registered scoped beside its bound options (.../MMCA.Common.Infrastructure/DependencyInjection.cs:169-173), with theAuthSessionIssuerover it registered scoped for the same reason (:182); the same block registersRefreshSessionUserDataExportSection, a user-data export section over that store (:178). Every read the caller can revoke through is tracked on purpose:IRefreshSessionStorereturns instances the caller revokes by mutating, and a no-tracking read would drop those revocations at save time (.../Application/Auth/IRefreshSessionStore.cs:16-20, restated atEFRefreshSessionStore.cs:25-29). The one exception isFindByIdUntrackedAsync, a read-onlyAsNoTrackingre-read for the rotation loser that nothing revokes through (EFRefreshSessionStore.cs:277-279, declared atIRefreshSessionStore.cs:141). The two scalar projections behind an administrator's sessions view,GetUserIdsWithLiveSessionsAsyncandCountLiveSessionsByUserAsync(IRefreshSessionStore.cs:93,:106;EFRefreshSessionStore.cs:221,:236), return ids and counts rather than sessions, so there is nothing to track. The read-onlyIUserSessionsAdministrationService, which uses those two projections and lists sessions through the trackedGetUnrevokedByUserAsync(UserSessionsAdministrationService.cs:28), is registered scoped beside the issuer (DependencyInjection.cs:186) and never revokes. - The table carries three indexes, one per question it answers: a unique index on
TokenHash(IX_RefreshSessions_TokenHash,RefreshSessionModelBuilderExtensions.cs:80-82, name at:24), the validation path, unique so a hash collision across users cannot validate one account's token against another's session;(UserId, RevokedAt)(IX_RefreshSessions_UserId,:86-87, name at:27), the family path used by the cap, by reuse detection and by sign-out-everywhere; and(UserId, SignInId, CreatedAt)(IX_RefreshSessions_UserId_SignInId,:97-98, name at:30), the sign-in history path the 2026-11-07 amendment adds.TokenHashis fixed-length non-unicode, because the value is always a 64-character hex digest (:52). The sevenDevice*columns are nullable and capped atDeviceFieldMaxLength(:68-74). - Design time has its own flag, and it must agree with the host.
DesignTimeDbContextOptions.EnableRefreshSessions(defaultfalse,.../Persistence/DbContexts/Design/DesignTimeDbContextOptions.cs:73) belongs in the Identity migrations project only (:57-72).DesignTimeDbContextHelperregisters the settings with the source name this context actually resolved to (.../Design/DesignTimeDbContextHelper.cs:173-178, in the builder at:116thatCreateSqlServer,CreatePostgreSQLandCreateSqliteshare,:52,:74,:95), so the gate opens for exactly the context--datasourceselected, including a logical name that collapses ontoDefault(:136-140). A flag that disagrees with the host'sRefreshSessions:Enabledshows up ashas-pending-model-changes(DesignTimeDbContextOptions.cs:69-71). - The access token carries
suband nothing else that names the user.TokenServicemintsJwtRegisteredClaimNames.Subas the single carrier of the user id (.../MMCA.Common.Infrastructure/Auth/TokenService.cs:146); the duplicate custom claim that used to ride alongside it is gone, so there are no longer two values that can disagree and two claim names every reader has to know (:140-143).AuthClaimTypes.Subjectnames the claim (.../MMCA.Common.Shared/Auth/AuthClaimTypes.cs:34) andClaimsPrincipalExtensionsreads bothsuband theNameIdentifierform the JWT bearer handler maps it to (.../Shared/Auth/ClaimsPrincipalExtensions.cs:26-28), parsing throughIParsableso the solution-wide identifier alias (ADR-048) can change shape without editing the readers (:40-43). RS256 tokens now carry the JWKSKeyIdin theirkidheader (TokenService.cs:67, passed at:91, stamped at:292), so a validator reading the published JWKS document (ADR-004) selects the right key by name instead of trying each in turn (:288-290, the same id on the validation key at:314).
The session becomes visible and finite (2026-08-27)
An access token names the session that issued it, through a claim nothing validates.
AuthClaimTypes.SessionIdissid(MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/AuthClaimTypes.cs:47, the additive-and-never-validated contract at:36-46), read back throughClaimsPrincipalExtensions.FindSessionId, which returnsGuid?and answers null for an absent or unparsable claim rather than throwing (.../Shared/Auth/ClaimsPrincipalExtensions.cs:109-113). Its only job is to let a request say which of the caller's own devices it came from.TokenServiceis untouched, and that is the design. Neither it norITokenServicegains a parameter, an overload or an obsoletion (.../MMCA.Common.Infrastructure/Auth/TokenService.cs:108, the contract at.../MMCA.Common.Application/Interfaces/Infrastructure/Auth/ITokenService.cs:17-22). Instead a private pass-through decorator nested inAuthSessionIssuer,SessionStampingTokenService(.../Application/Auth/Sessions/AuthSessionIssuer.cs:737), appends the claim when an ambient session id is armed (and anmfaclaim when a verified second factor is) and forwards untouched when neither is. The issuer exposes it as itsTokenService(:77), and the base surfaces that to subclasses as its ownTokenServiceproperty (.../Application/Auth/AuthenticationServiceBase.cs:120, no field of its own).CreateAccessTokenForSession(:818-819) hands the mint toIAuthSessionIssuer.MintForSession, which arms, mints and disarms (AuthSessionIssuer.cs:164,:173). The abstractCreateAccessToken(TUser)hook every consumer already overrides (AuthenticationServiceBase.cs:798) keeps its signature, so every existing subclass emitssidwith no edit at all (:818-819).The session is created before the token is minted, because a token cannot name an id that does not exist yet. The ordering is explicit in the code and explained there (
IssueAsync,AuthSessionIssuer.cs:86):OpenSessionAsyncreturns the new row's id (:469-494, theIssuedSessionrecord at:725), the session is saved, and only then is the token minted. Login and registration reach it through the privateIssueTokensCoreAsynchelper (AuthenticationServiceBase.cs:281,:397; the helper at:725callsIssueAsyncat:737). On refresh the rotation mints against the successor's id, not the session it just revoked (RotateAsync,AuthSessionIssuer.cs:124, rotation at:510-567), so thesidin a freshly refreshed token names a live row.Three endpoints put the device list, the per-device revoke and the device report in the framework. All are on
AuthControllerBaseand all are[Authorize]:GET auth/my-sessions(AuthControllerBase.cs:250-268) returnsIReadOnlyList<RefreshSessionSummaryResponse>(:252) for the caller's own live sessions, passing the caller's ownsidstraight into the application layer (:262).POST auth/revoke/{sessionId:guid}(:423) answers 204, or 404 as ProblemDetails when the id names nothing the caller owns or a session already revoked (:418). It is explicitly[NonIdempotent](:424), so a replayed request cannot be served a cached 204 and report success for a revoke that never ran.PUT auth/sessions/current/device(:286-319, since 1.298.0,MMCA.Common/CHANGELOG.md:354) records theDeviceMetadataa native client reports for the session its ownsidnames, throughIAuthSessionIssuer.RecordDeviceAsync(AuthSessionIssuer.cs:330-357). It answers 404 for a token with nosidor for a session that is not the caller's live one (AuthControllerBase.cs:303-310;AuthSessionIssuer.cs:338-346), and is a PUT, so a retried call records the same values again (AuthControllerBase.cs:278-280).
RefreshSessionSummaryResponsecarries exactly seven fields:SessionId,CreatedAt,ExpiresAt,IpAddress,UserAgent,IsCurrentand the optionalDevice(DeviceMetadata?, null for every browser session, documented at:23-27) (.../MMCA.Common.Shared/Auth/Responses/RefreshSessionSummaryResponse.cs:28-35).TokenHashandReplacedByTokenHashare deliberately absent, because returning either would hand a caller a queryable index of credentials at rest for no gain (:6-11).IsCurrentis computed server-side from the caller's ownsid, never supplied by the client (ListActiveAsync,AuthSessionIssuer.cs:236, which filters to sessions live atnowand orders newest first,:248).Revoking a session you do not own is indistinguishable from revoking one that does not exist, and revoking one already revoked says so without writing.
RevokeSessionByIdAsync(AuthenticationServiceBase.cs:538-542) delegates toIAuthSessionIssuer.RevokeSessionAsync(AuthSessionIssuer.cs:293-321), which resolves through the user-scopedIRefreshSessionStore.FindByIdAsync(.../Application/Auth/IRefreshSessionStore.cs:121), whose EF implementation puts the user in the predicate rather than in a post-read check (.../Infrastructure/Persistence/Auth/EFRefreshSessionStore.cs:263), so another account's id returns the sameAuth.SessionNotFoundas a random one (AuthSessionIssuer.cs:298-306). An already-revoked row returnsNotFoundwith the codeAuth.SessionAlreadyRevokedand writes nothing (:308-315): the list the user clicked through rendered it as live, so after a double click, or a session the cap evicted between rendering the list and clicking the button, the client needs to say it was signed out earlier rather than claim this click signed it out; the lookup is user-scoped, so the answer reveals nothing about another account (:280-292). The page shows thatNotFoundas an informational "already signed out" toast (Sessions.razor.cs:181-186).The device list ships as a page, not as a sample.
/profile/sessions(.../MMCA.Common.UI/Pages/Auth/Sessions.razor:1,[Authorize]at:5, code-behind atSessions.razor.cs:28) renders a table of Device, IP, signed-in and expiry columns (:37-93) overIAuthUIService.GetSessionsAsync/RevokeSessionAsync, both of which returnResult(.../MMCA.Common.UI/Services/Auth/AuthUIService.cs:286,:314) rather than throwing (ADR-013). A sign-out-everywhere button sits below the table (Sessions.razor:95-106, its hint at:107-109) and runs throughIAuthUIService.RevokeAllSessionsAsync(Sessions.razor.cs:241;AuthUIService.cs:143), which is the account-wide revoke followed, only once the server confirmed it, by the local sign-out; the page then redirects to the login page, and a failed revoke shows the error and stays on the page (RevokeAllAsync,Sessions.razor.cs:215, reasoning at:208-214, redirect at:244); those two revoke paths are why the current row carries no button of its own (:18-26). Both paths ask first throughIAppDialogService.ConfirmAsync: a row's revoke names the device it is about to sign out (:154), and sign-out-everywhere confirms because it also ends the session in use (:222). Any host using the shared router gets the route with zero registration, because the router'sAppAssemblyisMMCA.Common.UI(.../MMCA.Common.UI/Routes.razor:12);AdditionalAssemblies(:13) is the separate mechanism that discovers a consumer module's own pages. Nav entry atLayout/NavMenu.razor:93(narrowed to one role when a host setsLayout:SessionsNavRequiredRole,:88,:91), route constant atCommon/RoutePaths.cs:16, 30 localizedAuth.Sessions.*keys in bothSharedResource.resxand its.essibling.Three of its choices are decisions rather than styling. The current device is marked with a text chip, not a colour (
Sessions.razor:54-60), for WCAG 1.4.1. The current row offers no revoke button at all, only a hint (:68-75), because ending your own session would leave the app signed in until the access token expired, which reads as a broken sign-out; the page-level button is where ending it belongs, because that path signs out locally too. And a load failure renders inline throughErrorSummarywith a retry button (:17,:23-29) rather than as a snackbar, because once a toast expires an empty table and a failed load look identical (:15-16); a failed reload clears the list rather than leaving stale rows a user could act on (Sessions.razor.cs:110).A retention sweep ages the table out.
RefreshSessionCleanupService(.../MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionCleanupService.cs:48-53) derives fromPeriodicBackgroundServiceand waits one full interval before its first sweep, so cleanup never competes with startup or migration work (StartupDelayat:68, reasoning at:64-67). It deletes rows that stopped being usable more thanRetentionDaysago, in one set-basedExecuteDeleteAsyncwith no batching (:124-128, cutoff at:107). The predicate ages each row from the instant it stopped being usable: its revocation if it was revoked, otherwise its expiry, which is the wording the setting itself uses (RefreshSessionSettings.cs:55-58). That is a conditional, not the later of the two: a row revoked minutes ago survives even if it expired long before (:99-104), and a row revoked 31 days ago is deleted even if itsExpiresAtis still in the future.RetentionDaysdefaults to 30 with[Range(0, 3650)](RefreshSessionSettings.cs:71-72), swept everyCleanupIntervalHours(default 6,[Range(1, 168)],:79-80). Zero disables the sweep and logs that it did (RefreshSessionCleanupService.cs:83-87), as doesEnabledbeing false (:77-81). Every sweep logs its count including zero, deliberately, because a log that speaks only when it deleted something gives an operator no evidence that retention is running at all (:132, message at:153-154, argued at:130-131):Purged {Count} refresh sessions that stopped being usable more than {RetentionDays} days agoRegistration is gated on
Enabledalone, not onDataSourceName(.../MMCA.Common.Infrastructure/DependencyInjection.cs:209-212): registering unconditionally would start a sweep in every service of a modular host, all but one of which has no table to sweep (:205-208).DataSourceNameis used only to resolve the source at sweep time, as the fallback when the entity registry has no entry (RefreshSessionCleanupService.cs:140-145), and a source that does not map the table warns once per sweep instead of failing with a translation error (:115-122).
Rationale
- A credential at rest is a credential. Hashing is what turns a database read from "mint tokens
for every signed-in user" into "hold a list of digests". The unsalted digest is the deliberate part:
the token is 64 bytes of
RandomNumberGeneratoroutput (TokenService.cs:185-187), not a guessable password, so the property a salt buys (resistance to offline guessing of the input) is worth nothing here, while the property it costs (lookup by hash) is the entire access path (IRefreshSessionStore.cs:29-38). - One row per device is what a session actually is. The single column made "signed in" an account
fact and forced every second device through the compromise path. Rows make it a device fact, which
is what both the user's mental model and any future "your devices" screen need
(
RefreshSession.cs:9-12). - A rotation chain is what makes replay detectable at all. Because using a session revokes it and
records its successor, a replayed token lands on a revoked row carrying a successor hash instead of
on nothing, and that is a signal an unknown hash can never produce (
RefreshSession.cs:18-25, and the store returning revoked rows on purpose,IRefreshSessionStore.cs:30-33). That distinction is what lets reuse revoke the family while a random string, or a token whose device was merely signed out, cannot. - Failing closed on reuse, open on the unknown. Both branches return the same error, so a caller
learns nothing about which one it hit (
AuthSessionIssuer.cs:261-271), but they behave differently where it matters: the branch an attacker can reach at will (post a random token) is the one that revokes nothing. The one distinct answer is the grace window's409 Auth.RefreshSuperseded(:273-282), which tells a caller only that its token was rotated within the lastReuseGraceSeconds: the signal a racing sibling tab needs to retry instead of signing out, and one a holder of a copied token learns too. - A cap that evicts beats a cap that refuses. Refusing the eleventh sign-in would fail a
legitimate login to protect a table; evicting the oldest live session bounds the growth and costs
the user the device they used least recently (
RefreshSessionSettings.cs:27-33). - Opt-in mapping is what keeps this one module's data. Sessions belong to Identity. The outbox is
configured on the base context because it is genuinely cross-cutting; copying that would have put an
empty table in every other database's migrations
(
RefreshSessionModelBuilderExtensions.cs:8-14). - The behavior is pinned by tests at all three layers: the entity's hashing, creation and
revocation rules
(
MMCA.Common/Tests/Core/MMCA.Common.Domain.Tests/Auth/RefreshSessionTests.cs:13), the login, rotation, reuse and cap workflow (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/AuthenticationServiceBaseTests.cs:29, hash-only storage at:257, other devices left alone at:271and:627, cap eviction at:287, rotation at:600, replay revoking the family at:647, a signed-out or evicted session failing alone at:673, a rotated one revoking the family at:697and a flagged-as-reuse one failing alone and keeping the family at:719, the lost and the won rotation claim at:740and:765, expiry and unknown tokens failing alone at:784and:807, per-device and all-device sign-out at:856,:872and:888), the reuse grace (.../MMCA.Common.Application.Tests/Auth/Sessions/AuthSessionIssuerReuseGraceTests.cs:25, the 10-second default at:34, a lost claim inside the grace answering 409 and keeping the family at:39, a lost claim to an earlier reuse sweep failing alone at:78, a rotated token inside the grace answering 409 and keeping the family at:116, a flagged-as-reuse row failing alone and keeping the family at any age at:154, and a zero grace treating every rotated token as reuse at:200), and the mapping (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Auth/RefreshSessionModelBuilderExtensionsTests.cs:14). - The 2026-08-27 additions are pinned at five layers, which is what lets the trade-offs above be
stated as facts: the claim and the projection
(
MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/RefreshSessionManagementTests.cs:31, successor-not-predecessorsidat:87, a token with nosidstill refreshing at:109, only-the-caller's-row-is-current at:162, no token material in the response at:188, another user's session answering not-found at:249, already-revoked answering not-found without a write at:267); the claim reader (.../MMCA.Common.Shared.Tests/Auth/ClaimsPrincipalExtensionsTests.cs:12); the endpoints, including reflection theories that pin the route templates (revoke/currentandsessions/current/deviceincluded) and the[Authorize]attribute (.../MMCA.Common.API.Tests/Controllers/Auth/AuthControllerBaseTests.cs:20, routes at:484-488, authorization at:506, the non-idempotent declaration at:518); the sweep, whose predicate semantics are settled by a test rather than by prose (.../MMCA.Common.Infrastructure.Tests/Persistence/Auth/RefreshSessionCleanupServiceTests.cs:35,PurgeSweep_MeasuresARevokedRowFromItsRevocationNotItsExpiryat:126, the zero-count log at:157, registration gating at:184and:196), with ownership scoping pinned against real SQLite (.../Persistence/Auth/EFRefreshSessionStoreFindByIdTests.cs:21, another user's session at:41, the tracked-instance requirement at:75); and the page (.../MMCA.Common.UI.Tests/Pages/Auth/SessionsTests.cs:27, the current row offering no revoke at:167, a failed reload not leaving stale rows at:231, a not-found revoke reading as already-signed-out at:265, both revoke paths confirming first and doing nothing when cancelled at:322,:339,:359and:376, sign-out-everywhere signing out through the auth service at:396, calling no per-device revoke at:410and staying on the page when it fails at:422). A WCAG 2.1 AA scan of the page runs in the out-of-solution gallery suite (.../MMCA.Common.UI.E2E.Tests/Auth/SessionsPageE2ETests.cs:13), which means it runs in theui-e2eCI job and not in a localdotnet test --solution MMCA.Common.slnx.
Trade-offs
- This is a breaking change with a data migration attached.
IAuthUserlosesRefreshToken,RefreshTokenExpiry,UpdateRefreshTokenandRevokeRefreshToken(IAuthUser.cs:9-14, the interface now being password material only at:16-25), so every consumer'sUseraggregate changes shape. The migration path is expand then contract (ADR-057): create theRefreshSessionstable, carry the live tokens over by hashing them in place with the SQL equivalent ofHashToken(which is why the encoding is documented as a contract,RefreshSession.cs:171-177), and only then drop the two user columns, with theEXPAND-CONTRACT-OVERRIDEmarker that drop requires. A consumer that skips the carry step is not broken, but every signed-in user is signed out at deploy. - Reuse detection still revokes a family on a benign race that outlasts the grace. Two client
tabs refreshing near simultaneously reach that outcome, once the reuse grace has passed, through
either of two branches: the second tab presents the just-rotated-away token and lands on its revoked
row, which carries its successor's hash (
AuthSessionIssuer.cs:418-457,IsReuseSignalat:579), or both present the same still-live token and the one that loses the store's rotation claim re-reads a row rotated longer ago than the grace (:554-564). Neither is distinguishable from theft, so both sign out every device rather than one. A loser whose row was signed out, cap-evicted or already swept by reuse detection instead fails alone (:546-552), and inside the grace both branches answer 409 with nothing revoked (next bullet). This is ADR-050's aggressive-by-design trade-off with a wider blast radius. As first recorded it was taken in full, rejecting a grace window because a genuinely stolen token works inside one; that window is now adopted (see the 2026-10-07 revision below), so the trade-off holds past the grace, and for every rotated row whenReuseGraceSecondsis0. - A replay inside the reuse grace revokes nothing (2026-10-07). A stolen refresh token presented
within
ReuseGraceSeconds(default 10) of a legitimate rotation is answered 409 like a racing sibling tab instead of revoking the user's whole session family, because the two cannot be told apart in that window (RefreshSessionSettings.cs:90-94). Past the window the family revoke applies unchanged to a rotated row (IsWithinRotationGrace); a row flagged as reuse fails alone at any age, because an earlier reuse event already revoked that device (IsReuseSignal,AuthSessionIssuer.cs:579). The price buys a concurrent refresh from two tabs or two replicas that no longer signs every device out. - "Nothing ages the table out" is retired (2026-08-27).
RefreshSessionCleanupServiceships the sweep, so a consumer no longer schedules its own. The cap still bounds only the live set; the sweep is what bounds the dead one. - The retention window is also the reuse-detection window, and the shorter one wins. Reuse
detection works because a replayed token lands on a revoked row; delete that row and the same
replay lands on nothing, which is the branch that deliberately fails alone. So retention silently
caps how long a stolen token remains detectable as theft rather than as an unknown value. Both the
setting and the service say so (
RefreshSessionSettings.cs:59-66,RefreshSessionCleanupService.cs:24-32, cross-referenced fromAuthSessionIssuer.cs:513-517). The 30-day default is comfortably longer than the 7-dayJwt:RefreshTokenExpirationDaysit has to outlive, but the two settings are independent and nothing fails a build when an operator sets retention below the refresh lifetime: it just quietly starts deleting rows whose tokens could still come back. - "Nothing in the framework reads
IpAddressandUserAgent" is retired (2026-08-27).GET auth/my-sessionsreturns both and/profile/sessionsrenders them. They remain informational, never part of a validation decision, which is the property that keeps a mobile client changing networks signed in. - The
sidclaim is stamped by a decorator, so a subclass can opt out of it by accident. A consumer whoseCreateAccessTokenoverride mints from its own injectedITokenServicerather than from the base'sTokenServiceproperty produces a perfectly valid token that simply carries nosid(AuthenticationServiceBase.cs:113-117; such a subclass can overrideCreateAccessTokenForSessioninstead,:818-819). Nothing fails; the device list just marks no row as current for that consumer, which is pinned byGetSessionsAsync_WithNoCurrentSessionId_MarksNothingCurrent(.../MMCA.Common.Application.Tests/Auth/RefreshSessionManagementTests.cs:176). That is the price of making the claim additive instead of changing an abstract signature every consumer implements, and the trade was taken deliberately. - Nothing validates
sid, by design, so it is a hint and not an authorization input. It is documented as additive and never validated (AuthClaimTypes.cs:36-46) and the reader answers null rather than throwing on a malformed value (ClaimsPrincipalExtensions.cs:109-113). A future temptation to authorize on it would need its own record: today a token whose session was revoked still validates until it expires, which is exactly ADR-047's revocation-gap posture. - Every revoke on the sessions page costs a confirmation. Both a row's revoke and
sign-out-everywhere open an
IAppDialogService.ConfirmAsyncdialog before anything is sent (Sessions.razor.cs:154,:222), with the in-flight disable still guarding a double click (Sessions.razor:80,:97). Tidying up several old devices therefore takes two clicks per row; the price buys a named, cancellable step in front of an action that has no undo. - Two gates have to agree, and only a scaffold says when they do not.
RefreshSessions:Enableddrives the runtime model (ApplicationDbContext.cs:424-427) andEnableRefreshSessionsdrives the design-time one (DesignTimeDbContextOptions.cs:73); a mismatch produces no startup error, just a migration that does not match the running model (:69-71). - The refresh path writes more than it did. A rotation inserts one row and revokes another
(
AuthSessionIssuer.cs:510-567), and every issue reads the user's live set to enforce the cap (:705), where the previous model wrote one column. The reads are index-covered (RefreshSessionModelBuilderExtensions.cs:86-87), but the refresh endpoint is no longer a single-row update. - The hash is confirmable, by design. Anyone holding both a database read and a candidate token
can verify the pairing, since the digest is deterministic and unsalted (
RefreshSession.cs:301-305). That is the accepted cost of lookup-by-hash and it holds only because the input is high-entropy random; the same scheme applied to anything guessable would be wrong.
Revision (2026-09-07)
Credential rotation now ends the session family (SEC-Common-02). A stolen refresh chain otherwise survived the exact remediation a user performs on discovering it: the rotation replaced the password and left every live refresh session minting tokens.
RefreshSessionRevocation.RevokeAllAsync
(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionRevocation.cs:27, in the
internal helper at :17) reads the account's un-revoked sessions through
GetUnrevokedByUserAsync (:39), revokes them and saves (:50). It is called after a successful
save by ChangePasswordHandlerBase
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePassword/ChangePasswordHandlerBase.cs:93)
and ResetPasswordHandlerBase
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:105).
Both bases take the store as an optional constructor parameter with a TimeProvider
(ChangePasswordHandlerBase.cs:40, ResetPasswordHandlerBase.cs:49), so this is not a breaking
signature change: a consumer that has not wired IRefreshSessionStore keeps compiling and keeps the
old behaviour, and injecting it is what turns the revocation on. The revocation runs after the
password save rather than before it, so a failure to revoke cannot leave an account whose password
changed but whose caller was told it did not.
Revision (2026-10-01)
No decision or rationale changed; the current-state sections now match the code. Content corrected
in place: the session cap is read through a protected virtual MaxActiveSessionsPerUser property, so
a subclass can override the bound value (AuthenticationServiceBase.cs:153); the sid decorator also
stamps an mfa claim and forwards untouched only when neither is armed (:966-970, :986-1005); the
sessions page's sign-out-everywhere runs through IAuthUIService.RevokeAllSessionsAsync, which signs
out locally only after the server confirmed the revoke, and a failure keeps the user on the page
(Sessions.razor.cs:156-185, AuthUIService.cs:118-139); the nav entry is role-gatable through
Layout:SessionsNavRequiredRole (NavMenu.razor:81-84, :249-250) and the page has 24 localized
keys; the retention sweep derives from PeriodicBackgroundService
(RefreshSessionCleanupService.cs:53); the design-time settings registration lives in a builder that
CreateSqlServer, CreatePostgreSQL and CreateSqlite share (DesignTimeDbContextHelper.cs:116,
:173-178); and both password handler bases now take IRefreshSessionStore as a required
constructor parameter, only the TimeProvider staying optional (ChangePasswordHandlerBase.cs:46-48,
ResetPasswordHandlerBase.cs:47-48), which corrects the Status line (the 2026-09-07 Revision above
records the original optional shape). Every other path:line citation in Status through Related was
re-anchored to current source, including moved files (Interfaces/Infrastructure/Auth/ITokenService.cs,
Shared/Auth/Responses/RefreshSessionSummaryResponse.cs, Controllers/Auth/AuthControllerBaseTests.cs,
UI.E2E.Tests/Auth/SessionsPageE2ETests.cs).
Revision (2026-10-06)
No decision changed; the current-state sections now match the code again. Content corrected in place:
- The session workflow (issue, rotation, reuse detection, the cap, sign-out, listing, revoke-by-id and
the
sid/mfastamping decorator) moved out ofAuthenticationServiceBaseinto the sealedAuthSessionIssuer(AuthSessionIssuer.cs:39). The base now takes a requiredIAuthSessionIssuer(AuthenticationServiceBase.cs:64-71), a breaking constructor change in 1.218.0 (MMCA.Common/CHANGELOG.md:283-284), so the 2026-08-27 Status note that no consumer signature changed holds only for that revision. - The 2026-10-01 Revision's
protected virtualMaxActiveSessionsPerUserproperty no longer exists: the issuer reads the cap from the bound settings (AuthSessionIssuer.cs:450) and cannot be subclassed. - A revoked row is a reuse signal only when it was rotated or already flagged as reuse; a signed-out or
cap-evicted token now fails alone (
AuthSessionIssuer.cs:301-309,:415-423;MMCA.Common/CHANGELOG.md:260, 1.219.0). - Revoking an already-revoked session by id answers
NotFound(Auth.SessionAlreadyRevoked) instead of success (AuthSessionIssuer.cs:244-251;MMCA.Common/CHANGELOG.md:216, 1.222.0). RefreshSessionimplementsIAnonymizable, soAnonymizeis a second mutation besideRevoke(RefreshSession.cs:39,:210-215).- Both sessions-page revokes confirm first, so the "no confirmation step" trade-off is replaced
(
Sessions.razor.cs:129-138,:188-197); the page has 28 localizedAuth.Sessions.*keys, not 24. - Every other
path:linecitation in Status through Related was re-verified against current source and re-anchored where it had moved.
Revision (2026-10-07)
Re-verified against current source. The storage model, the hashing, the cap, the sign-out scopes, the device list and the retention sweep are unchanged; what moved is the reuse answer to a rotation race, which reverses this record's original rejection of a grace window. This is an amendment, not a supersede: reuse detection still revokes the family past the grace.
- The reuse grace window is adopted (1.233.0).
RefreshSessions:ReuseGraceSecondsdefaults to 10 with[Range(0, 300)](MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionSettings.cs:82-98). A token whose row was revoked asRotatedless than the grace ago answers409 Conflict(Auth.RefreshSuperseded,AuthSessionIssuer.cs:276-280) and revokes nothing, on the lookup path (:326-331) and on the lost rotation claim (:436-439); the predicate is:477-485(MMCA.Common/CHANGELOG.md:12). Why: two tabs, or one browser served by two replicas, refreshing a moment apart no longer burns the whole session family, which the original trade-off accepted. The cost is that a replay inside the window revokes nothing; it is recorded as a new trade-off, and the original rejected-alternative bullet is narrowed to the race that outlasts the grace, re-anchored, and points here. A grace of0restores the family revoke for every rotated row but not for a lost claim on a signed-out or cap-evicted row, which fails alone (AuthSessionIssuer.cs:428-434,AuthSessionIssuerReuseGraceTests.cs:96). - The rotation loser re-reads its row.
IRefreshSessionStore.FindByIdUntrackedAsync(IRefreshSessionStore.cs:64-80, a default member returning null) is overridden by the EF store with anAsNoTrackingread (EFRefreshSessionStore.cs:87-97), so the loser of the claim fails alone on a sign-out or cap eviction (AuthSessionIssuer.cs:428-434), answers 409 inside the grace, and otherwise gets the replay answer (:441-448). The "every read is tracked" statement now names that exception (EFRefreshSessionStore.cs:25-29). - The 409 is part of the HTTP contract and the clients honour it. The refresh action documents
and declares it (
AuthControllerBase.cs:116-121,:128);CookieSessionRefresher.cs:117,DirectApiTokenRefresher.cs:64-67andAuthUIService.TryRefreshTokenAsync(:151,:165) treat it as transient (MMCA.Common/CHANGELOG.md:21).DirectApiTokenRefresheranswers a 409 with the newer stored pair when another in-process refresh already stored one, and as unavailable otherwise (DirectApiTokenRefresher.cs:26-32,:88-97). The grace is pinned byAuthSessionIssuerReuseGraceTests.cs:24. - The everywhere sign-out delegates to
IAuthSessionIssuer.SignOutEverywhereAsync(AuthSessionIssuer.cs:179-184), not toSignOutAsync; theAuthSessionIssuerregistration beside the store is cited (DependencyInjection.cs:176). - Anchors re-verified against current source:
AuthSessionIssuer.cs(class:41, options:44, cap:510-523, rotation:392-452,IsReuseSignal:460-468, family sweep:488-499, decorator:542),RefreshSession.cs(:41,:55-65,:127-160,:175-179,:189-204,:212-217),EFRefreshSessionStore.cs(:31-35,:134-163,:169-174),IRefreshSessionStore.cs(:92-94,:113-131),AuthControllerBase.cs(:142-169,:182-187,:215-221),DependencyInjection.cs:168-185,ApplicationDbContext.cs:336-339,:882-883,IAuthenticationService.cs:58-62,72-75,Sessions.razor.cs:155-161,:187-230,:194-203,AuthUIService.cs:127,:261,:275,AuthenticationServiceBaseTests.cs:615through:836, and050-jwt-refresh-token-rotation.md:207-209. Dated revisions above keep their anchors as written.
Revision (2026-10-21)
Re-verified against current source. The storage model, the hashing, the rotation claim, the reuse rules and grace, the cap, the sign-out scopes, the device list and the retention sweep are unchanged; what moved is account erasure, the order of the password-rotation revoke, an administrator's read-only view over the same store, and most anchors.
- Account erasure ends and anonymizes the account's sessions (1.245.0, breaking).
DeleteUserHandlerBasetakes an optionalIRefreshSessionStoreandTimeProvider(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:78-79) and callsRefreshSessionRevocation.RevokeAndAnonymizeAllAsyncbefore its unit-of-work save (:155-159). The helper reads every row through the newIRefreshSessionStore.GetAllByUserAsync(IRefreshSessionStore.cs:60, tracked inEFRefreshSessionStore.cs:74-82), revokes the un-revoked ones with the new fifth reasonAccountDeleted(RefreshSession.cs:70) and anonymizes every row, revoked ones too, saving nothing itself (RefreshSessionRevocation.cs:69-91;MMCA.Common/CHANGELOG.md:143).Anonymizetherefore has a framework caller, and the ADR-047 entry in Related no longer says the delete handler leaves the sessions alone. - A password reset persists the revocation before the password; a password change saves it first
(1.247.0, M240). This reverses the order the 2026-09-07 Revision records.
ChangePasswordHandlerBasehas the aggregate take the new password first (ChangePasswordHandlerBase.cs:119), then revokes and saves the sessions (:127-129) before its explicit password save (:131). That revoke save goes through the shared context factory and already carries the mutated user (:124-126), so on a single data source the password and the revocation commit in the same save, and across data sources the saves run in sequence with no two-phase commit (:27-37).ResetPasswordHandlerBaserevokes (ResetPasswordHandlerBase.cs:106-108) before it even applies the new password (:110-111), so the revoke stands when the aggregate then rejects that password, and a revoke failure throws with the password unchanged (MMCA.Common/CHANGELOG.md:75). Both still require the store (ChangePasswordHandlerBase.cs:60,ResetPasswordHandlerBase.cs:48). RefreshSessionRevocationis public. The class ispublic static(RefreshSessionRevocation.cs:22) andRevokeAllAsyncis public (:31), so an app-sideIUserAdministrationServicecan run the same step after a lockout (:17-18); a role change does not need it, since the refresh path mints from the stored role (:18-19); only the erasure helper is internal (:69).RevokeAllAsyncreads throughGetUnrevokedByUserAsync(:43), revokes asSignedOut(:51) and saves (:54).- An administrator's read-only sessions view sits over the same store.
IUserSessionsAdministrationService(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/IUserSessionsAdministrationService.cs:10) is registered scoped beside the issuer (DependencyInjection.cs:180). It lists another account's live sessions withIsCurrentfalse, and backs a roster's signed-in filter and per-user counts through the store's two scalar projections,GetUserIdsWithLiveSessionsAsyncandCountLiveSessionsByUserAsync(IRefreshSessionStore.cs:72,:85;UserSessionsAdministrationService.cs:53,:72; the two store members are a 1.236.0 breaking addition,MMCA.Common/CHANGELOG.md:265). It never revokes. The projections return ids and counts, not sessions, so the "every read is tracked" rule and its one exception still cover every read that returns a session; the Decision bullet on the shipped store now says so. - The sessions page carries 29 localized
Auth.Sessions.*keys in each ofSharedResource.resxandSharedResource.es.resx, not 28. - Anchors re-verified against current source:
RefreshSession.cs(class:43, constants:46-70, properties:73-112,Create:132-165,HashToken:180-184,Revoke:194-209,Anonymize:217-222),IRefreshSessionStore.cs(FindByIdAsync:90-103,FindByIdUntrackedAsync:105-121,TryRotateAsync:156-174),EFRefreshSessionStore.cs(:62-70,:125-136,:144-147,:171-214,:219-224),AuthSessionIssuer.cs(shifted by two from:260on::267-271,:278-282,:298-345,:352-378,:394-454,:462-470,:479-487,:489-501,:512-525, decorator:544),AuthControllerBase.cs(:107,:129,:135,:143-170,:185,:195,:217),DependencyInjection.cs:180-190,ApplicationDbContext.cs:888-889,:899-907,Sessions.razor.cs(:28,:104,:188-231),AuthenticationServiceBaseTests.cs:257through:868, and050-jwt-refresh-token-rotation.md:211-213. Dated revisions above keep their anchors as written.
Revision (2026-10-26)
Re-verified against current source. No decision, default or behavior changed: the cap (default 10,
[Range(1, 1000)], RefreshSessionSettings.cs:34-35), the eviction reason, the rotation claim, the
reuse rules and grace, the 409 handling in both clients and the sign-out scopes read as before. What
moved is line numbers in AuthSessionIssuer.cs, AuthenticationServiceBase.cs and
EFRefreshSessionStore.cs, plus two client anchors that had landed beside the code they cite.
- Anchors re-verified against current source:
AuthSessionIssuer.cs(OpenSessionAsync:355-380, cap call before staging:376-377, rotation:396-455,EnforceSessionCapAsync:519-532with the cap read at:521, filter:523, ordering:524-525, eviction loop:528-531, the expired-rows and retention remarks:513-517,IssuedSession:539, the additive-claim remarks:546-550,SessionStampingTokenService:551, forward untouched:576-579,sid:583-588,mfa:590-593),AuthenticationServiceBase.cs(base and issuer split:43-48, constructor:67-74,TokenService:105with its no-sidremarks:97-103,IssueTokensAsynccallers:230and:325, helper:463-477,RevokeTokenAsync:398,RevokeAllSessionsAsync:415,RevokeSessionByIdAsync:448-452,CreateAccessToken:496,CreateAccessTokenForSessionremarks:502-511and method:515-516, the ADR-029 lockout check:152-157and registration rate limit:263-268),EFRefreshSessionStore.cs(class:33-37, ordering:64-72, projections:91and:106,FindByIdAsync:127-138,FindByIdUntrackedAsync:147-150, claim argument:159-164, transaction reasoning:167-171,TryRotateAsync:174-217, conditional UPDATE:190-198, data-source fallback:222-227),CookieSessionRefresher.cs(the 409 remark:118-121,ClassifyFailure:123-126) andDirectApiTokenRefresher.cs(the 409 branch:86-89,ReadSupersededOutcomeAsync:108-122). Dated revisions above keep their anchors as written, including theirCHANGELOG.mdline citations.
Revision (2026-11-02)
Behavior added in MMCA.Common 1.273.0 (MMCA.Common/CHANGELOG.md:17); every other decision and default
is unchanged.
- Lost-response recovery. A rotated token presented past the reuse grace no longer always
revokes the family. When
LostResponseRecoveryMinutesis above zero, the presented row was revoked asRotatedinside that window, and its successor is live and was never rotated, the issuer rotates the successor in its place (AuthSessionIssuer.cs:345-354,:531-555). The setting defaults to0(RefreshSessionSettings.cs:122-123), so a host that sets nothing sees the original BR-206 answer. MMCA.ADC sets it to 120 minutes. The Decision has a new bullet for it. - Anchors outside that bullet were not re-verified in this revision.
Amendment (2026-11-07): sign-in history
Context. Sessions were visible only while live: GET auth/my-sessions and the administrator's
sessions view list un-revoked rows, so a user or an operator reviewing a suspected compromise had no
record of a sign-in once it ended. A rotation chain was linked only by ReplacedByTokenHash, so
grouping one sign-in meant walking the chain row by row. And a refresh-token reuse that revoked a
whole family was silent.
Decision.
SignInIdgroups a rotation chain.RefreshSession.SignInIdis a nullableGuid(MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/RefreshSession.cs:106).Createsets it to the row's ownId(:176), so a fresh sign-in opens a group, andCreateSuccessor(:192) copies the predecessor's value to the successor (:200-204), which the issuer's rotation now calls (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:450). A row written before the column existed holds null; its successor keeps the group it opened inCreate, so from the first rotation after the upgrade the chain is grouped like any other.- The store aggregates; one row per sign-in, never one per rotation.
IRefreshSessionStore.GetRecentSignInsAsync(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IRefreshSessionStore.cs:81) returnsRefreshSessionSignInaggregates. The EF store runs at most three statements, each bounded by the cap and none by the user's row count (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFRefreshSessionStore.cs:88-95): a grouped query that returns eachSignInIdwith the MIN and MAX of its rows'CreatedAt, ordered and limited in the database (SignInChainsQuery,:158-173); a load of only the row at each group's MAX, the head (SignInHeadsQuery,:186-193, matched exactly in memory with the key as the tie-break,:120-131); and the capped legacy rows, where each null-SignInIdrow that was not revoked asRotatedcounts as its own sign-in (LegacySignInsQuery,:204-214). All three are untracked (:103). That fallback ages out with the retention sweep. - One index.
IX_RefreshSessions_UserId_SignInIdon(UserId, SignInId, CreatedAt)(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionModelBuilderExtensions.cs:28,:83-85).CreatedAtis the trailing key, so the per-group MIN and MAX and the head lookup are answered from the index rather than by visiting every row of a long chain (:75-81). It declares no filter or INCLUDE list, so one configuration serves every relational engine. - The shaping is shared.
SignInHistory(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/SignInHistory.cs:20) turns each aggregate into aSignInSummaryResponse, capped atMaxEntries= 50 (:23), newest first (:57-59). A sign-in starts at its earliest retained row and was last active at its head's issue instant (:94-97); the head decides how it ended: live (no end), revoked (the revocation instant and the stored reason, reported as it is) or expired (its expiry,SignInEndReasons.Expired) (:105-115).IsCurrentmarks the sign-in the caller's ownsidbelongs to, found among the heads or by one user-scoped primary-key lookup (:67-87). Self-service (AuthSessionIssuer.ListSignInsAsync,AuthSessionIssuer.cs:238) and administration (UserSessionsAdministrationService.GetSignInsAsync,.../Auth/Administration/UserSessionsAdministrationService.cs:59) both go through it. - The response.
SignInSummaryResponse(SignInId, StartedAt, LastActiveAt, IpAddress, UserAgent, EndedAt, EndReason, IsCurrent, Kind)(MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/SignInSummaryResponse.cs:35-44).EndReasontakes the values ofSignInEndReasons:SignedOut,ReuseDetected,SessionCapExceeded,AccountDeletedandExpired(.../Shared/Auth/Responses/SignInEndReasons.cs:11-23), the first four shared with the session's own revocation reasons.Kindis an extension point serialized by name (.../Shared/Auth/Responses/SignInHistoryEntryKind.cs:9-10), so a later entry kind reads as an unknown string to an older client rather than as a bare number; besidesSignIn(:13), view-as grants now appear in the viewed user's history asSignInHistoryEntryKind.ViewAsrows (:19, "Viewed by support", endedViewAsEndedorExpired,SignInEndReasons.cs:26), merged bySignInHistory(SignInHistory.cs:55-56) as ADR-137 decides. - Two endpoints.
GET auth/my-sign-insonAuthControllerBase,[Authorize]and scoped to the caller (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:215-227), andGET {userId}/sign-insonUsersAdminControllerBase(.../Controllers/Administration/UsersAdminControllerBase.cs:104-118), which the class-level[HasPermission(AdministrationPermissions.ManageUsers)]gates tousers:manage(:46). The admin route prefix is the consumer's ([Route("Admin/Users")]in the class example,:22). - One shared component.
SignInHistoryTable(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/SignInHistoryTable.razor) renders the list read-only, with the current sign-in marked by a text chip rather than a colour, and the shared/profile/sessionspage shows it below the live devices (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Sessions.razor:1,:125). The administrator's client isIUserAdminUIService<TUserDto>.GetSignInsAsync; a consumer places the component on its own user-detail page. - Reuse is logged. When a replayed token revokes the family,
RevokeFamilyOnReuseAsynclogs one Warning, "Refresh token reuse detected for user {UserId}; {RevokedCount} live sessions revoked" (AuthSessionIssuer.cs:584-587, called at:601). Both reuse paths end in that method, so each event logs once (:590-593). It carries the user id and the count only, never the client IP or user agent, which are personal data on the session row (:582-583). The lockout Warning that pairs with it is ADR-029's.
Consequences.
- Every host that maps
RefreshSessionsadds one migration: a nullable column and one index, with no data rewrite (MMCA.Common/CHANGELOG.md:11). - History depth equals
RefreshSessions:RetentionDays(default 30,MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionSettings.cs:72): the sweep that bounds reuse detection also bounds what a user can review, and nothing here extends it. - "Last active" is the last refresh, not the last request: an access token used for its full lifetime without a refresh does not move it.
- A sign-in that began before the upgrade loses its start: once its live pre-upgrade row rotates, that
row is
Rotatedand leaves the legacy query, and the history shows the sign-in as starting at the first post-upgrade rotation. A pre-upgrade row that never rotates again shows as its own sign-in until it ages out.
Rejected.
- Walking
ReplacedByTokenHashchains per request (2026-11-07): unbounded rows per active device, since a device that refreshes at the default 15-minute access-token lifetime (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSettings.cs:66) writes about 96 rows a day. Revisit only if a host cannot take the migration. - A failed-attempts table (2026-11-07): failed sign-ins stay counters in the cache, as ADR-029 decided; a sign-in history lists sessions that were issued, not attempts that failed.
Revision (2026-11-23)
Re-verified against current source. The storage model, the hashing, the rotation claim, the reuse rules and grace, lost-response recovery, the cap, the retention sweep and the sign-in history read as before; what moved is device metadata on the session row, a single-device sign-out endpoint, the index count, one wrong-file citation and most anchors. Content corrected in place:
- A session row records the device a native client reports (1.298.0).
RefreshSessiongains seven[Pii]Device*members (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/RefreshSession.cs:137-162) and a third mutation,RecordDevice(:273), besideRevokeandAnonymize(:30-32);Anonymizeclears the seven as well (:343-349) and a rotation successor copies them (:252-258).PUT auth/sessions/current/device(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:286-319) reaches it throughIAuthSessionIssuer.RecordDeviceAsync(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:330-357),RefreshSessionSummaryResponsecarries a seventh field,DeviceMetadata? Device = null(MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/RefreshSessionSummaryResponse.cs:28-35), and the mapping adds seven nullable columns (RefreshSessionModelBuilderExtensions.cs:68-74). The "exactly two ways" and "exactly six fields" statements in the Decision are corrected. POST auth/revoke/currentis the everyday sign-out (1.295.0,MMCA.Common/CHANGELOG.md:404). It revokes the session the caller's ownsidnames, falls back to every session for a token with nosid, and answers 204 on an already-revoked or missing session (AuthControllerBase.cs:219-237).POST auth/revokestill signs out everywhere, and its own summary now calls it the explicit all-devices action (:183-188), so the Decision no longer says a sign-out cannot name the device it is called from.- The table carries three indexes, not two. The body bullet now lists the
(UserId, SignInId, CreatedAt)index the 2026-11-07 amendment added (RefreshSessionModelBuilderExtensions.cs:97-98, name at:30) besideTokenHash(:80-82) and(UserId, RevokedAt)(:86-87). - The Cosmos citation named the wrong file. The override that keeps Cosmos off both mapping
paths is
CosmosDbContext.OnModelCreating(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/CosmosDbContext.cs:119), not a line ofApplicationDbContext.cs. - The same DI block also registers
RefreshSessionUserDataExportSectionover the session store (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:178), and the sessions page carries 30 localizedAuth.Sessions.*keys in each ofSharedResource.resxandSharedResource.es.resx, not 29. - Anchors re-verified against current source:
RefreshSession.cs(class:46, constants:67-79,Create:184, hash on the way in:211, truncation:214-215,HashToken:301-305,Revoke:315with refusal:317-323and link:327,Anonymize:339),AuthSessionIssuer.cs(class:54, options:57,TokenService:77,IssueAsync:86,RotateAsync:124,MintForSession:164/:173,SignOutAsync:193,SignOutEverywhereAsync:222,ListActiveAsync:236,RevokeSessionAsync:293,RefreshSupersededError:376,ResolveRotatableSessionAsync:398-462,OpenSessionAsync:469-494,RotateSessionAsync:510, losing branch:537-565,IsReuseSignal:579,FindRecoverableSuccessorAsync:619,RevokeFamilyOnReuseAsync:666,EnforceSessionCapAsync:705with the cap read at:707,IssuedSession:725,SessionStampingTokenService:737),AuthenticationServiceBase.cs(class:74, issuer parameter:79,TokenService:120,RevokeTokenAsync:476,RevokeAllSessionsAsync:493,RevokeSessionByIdAsync:538-542,IssueTokensCoreAsync:725(callers:281,:397),CreateAccessToken:798,CreateAccessTokenForSession:818-819),IAuthenticationService.cs(:60-63,:69,:74-77,:81),AuthControllerBase.cs(:64,:70,:87,:114,:158-161,:169,:175,:189-207,:250-268,:423),EFRefreshSessionStore.cs(class:34,GetUnrevokedByUserAsync:65, projections:221/:236,FindByIdAsync:263,FindByIdUntrackedAsync:277-279,TryRotateAsync:304, conditional UPDATE:321-322),IRefreshSessionStore.cs(projections:93/:106,FindByIdAsync:121,FindByIdUntrackedAsync:141,TryRotateAsync:177),DependencyInjection.cs(:169-173,:182,:186,:205-212),ApplicationDbContext.cs(gate:424-427, remarks:104-113, call:575,ConfigureRefreshSessions:1048-1056),RefreshSessionModelBuilderExtensions.cs:39,TokenService.cs(:67,:91,:108,:146,:185-187,:292,:314),Sessions.razor.cs(:110,:154,:181-186,:222,:241),AuthUIService.cs(:143,:167,:286,:314),CookieSessionRefresher.cs(:117,:122),DirectApiTokenRefresher.cs(:25,:85-87,:108,:111),NavMenu.razor(:88,:91,:93),DeleteUserHandlerBase.cs:178andAuthControllerBaseTests.cs(:484-488,:506,:518). Dated revisions and the 2026-11-07 amendment above keep their anchors as written.
Related
ADR-050 (the single-column model this record replaces, and the
source of the rotation and reuse-detection policy it keeps),
ADR-004 (the stateless RS256 access token this flow reissues, and
the JWKS document the new kid header points into),
ADR-006 (one sealed context class per engine, which is why the mapping
gate lives on the base context rather than in a consumer subclass),
ADR-029 (the lockout and rate-limit checks that run
before a session is ever opened, in the same shared workflow,
AuthenticationServiceBase.cs:152-157 for login and :263-268 for registration),
ADR-047 (the middleware that bounds the access token's
revocation gap; a soft-deleted user's sessions stop refreshing because the refresh flow re-fetches
through the same query filter; when a store is passed, the delete handler also revokes them as
AccountDeleted and anonymizes every row in the erasure's own save,
.../Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:178),
ADR-051 (the client half: the rotated pair each head persists
and replays),
ADR-057 (the gate the column drop has to be marked
for),
ADR-048 (the identifier alias the sessions and the sub
reader are typed against),
ADR-013 (the Result-returning UI client the sessions page branches on, and
the ErrorSummary component it renders a failed load through),
ADR-074 (the scheduler a consumer would have used for its own
retention job before the framework shipped one, and the same two-part Enabled plus DataSourceName
gate the scheduler table uses),
ADR-020 (why these two endpoints are [Authorize] and
self-scoped rather than permission-gated: a user listing and revoking their own devices needs no
permission, and the ownership scope is enforced in the query),
ADR-063 (the WCAG gate the sessions page is scanned under,
and the reason the current-device marker is text rather than colour).